From a5bbc6b77327c2241edb0108ed7b75f45efbe57c Mon Sep 17 00:00:00 2001 From: Ayush Srivastava Date: Wed, 15 Jun 2022 19:06:54 +0530 Subject: [PATCH] ok --- node_modules/.bin/color-support | 12 + node_modules/.bin/color-support.cmd | 17 + node_modules/.bin/color-support.ps1 | 28 + node_modules/.bin/detect-libc | 12 + node_modules/.bin/detect-libc.cmd | 17 + node_modules/.bin/detect-libc.ps1 | 28 + node_modules/.bin/mime | 12 + node_modules/.bin/mime.cmd | 17 + node_modules/.bin/mime.ps1 | 28 + node_modules/.bin/mkdirp | 12 + node_modules/.bin/mkdirp.cmd | 17 + node_modules/.bin/mkdirp.ps1 | 28 + node_modules/.bin/node-pre-gyp | 12 + node_modules/.bin/node-pre-gyp.cmd | 17 + node_modules/.bin/node-pre-gyp.ps1 | 28 + node_modules/.bin/nopt | 12 + node_modules/.bin/nopt.cmd | 17 + node_modules/.bin/nopt.ps1 | 28 + node_modules/.bin/rimraf | 12 + node_modules/.bin/rimraf.cmd | 17 + node_modules/.bin/rimraf.ps1 | 28 + node_modules/.bin/semver | 12 + node_modules/.bin/semver.cmd | 17 + node_modules/.bin/semver.ps1 | 28 + node_modules/.package-lock.json | 1495 +++ .../@mapbox/node-pre-gyp/CHANGELOG.md | 500 + node_modules/@mapbox/node-pre-gyp/LICENSE | 27 + node_modules/@mapbox/node-pre-gyp/README.md | 742 ++ .../@mapbox/node-pre-gyp/bin/node-pre-gyp | 4 + .../@mapbox/node-pre-gyp/bin/node-pre-gyp.cmd | 2 + .../@mapbox/node-pre-gyp/contributing.md | 10 + .../@mapbox/node-pre-gyp/lib/build.js | 51 + .../@mapbox/node-pre-gyp/lib/clean.js | 31 + .../@mapbox/node-pre-gyp/lib/configure.js | 52 + node_modules/@mapbox/node-pre-gyp/lib/info.js | 38 + .../@mapbox/node-pre-gyp/lib/install.js | 235 + node_modules/@mapbox/node-pre-gyp/lib/main.js | 125 + .../@mapbox/node-pre-gyp/lib/node-pre-gyp.js | 309 + .../@mapbox/node-pre-gyp/lib/package.js | 73 + .../@mapbox/node-pre-gyp/lib/pre-binding.js | 34 + .../@mapbox/node-pre-gyp/lib/publish.js | 81 + .../@mapbox/node-pre-gyp/lib/rebuild.js | 20 + .../@mapbox/node-pre-gyp/lib/reinstall.js | 19 + .../@mapbox/node-pre-gyp/lib/reveal.js | 32 + .../@mapbox/node-pre-gyp/lib/testbinary.js | 79 + .../@mapbox/node-pre-gyp/lib/testpackage.js | 53 + .../@mapbox/node-pre-gyp/lib/unpublish.js | 41 + .../node-pre-gyp/lib/util/abi_crosswalk.json | 2602 +++++ .../@mapbox/node-pre-gyp/lib/util/compile.js | 93 + .../node-pre-gyp/lib/util/handle_gyp_opts.js | 102 + .../@mapbox/node-pre-gyp/lib/util/napi.js | 205 + .../lib/util/nw-pre-gyp/index.html | 26 + .../lib/util/nw-pre-gyp/package.json | 9 + .../@mapbox/node-pre-gyp/lib/util/s3_setup.js | 163 + .../node-pre-gyp/lib/util/versioning.js | 335 + .../@mapbox/node-pre-gyp/package.json | 62 + node_modules/@types/node/LICENSE | 21 + node_modules/@types/node/README.md | 16 + node_modules/@types/node/assert.d.ts | 912 ++ node_modules/@types/node/assert/strict.d.ts | 8 + node_modules/@types/node/async_hooks.d.ts | 497 + node_modules/@types/node/buffer.d.ts | 2142 +++++ node_modules/@types/node/child_process.d.ts | 1365 +++ node_modules/@types/node/cluster.d.ts | 414 + node_modules/@types/node/console.d.ts | 412 + node_modules/@types/node/constants.d.ts | 18 + node_modules/@types/node/crypto.d.ts | 3307 +++++++ node_modules/@types/node/dgram.d.ts | 545 ++ .../@types/node/diagnostics_channel.d.ts | 134 + node_modules/@types/node/dns.d.ts | 643 ++ node_modules/@types/node/dns/promises.d.ts | 357 + node_modules/@types/node/domain.d.ts | 169 + node_modules/@types/node/events.d.ts | 623 ++ node_modules/@types/node/fs.d.ts | 3748 ++++++++ node_modules/@types/node/fs/promises.d.ts | 1091 +++ node_modules/@types/node/globals.d.ts | 284 + node_modules/@types/node/globals.global.d.ts | 1 + node_modules/@types/node/http.d.ts | 1368 +++ node_modules/@types/node/http2.d.ts | 2100 ++++ node_modules/@types/node/https.d.ts | 391 + node_modules/@types/node/index.d.ts | 131 + node_modules/@types/node/inspector.d.ts | 2745 ++++++ node_modules/@types/node/module.d.ts | 114 + node_modules/@types/node/net.d.ts | 783 ++ node_modules/@types/node/os.d.ts | 455 + node_modules/@types/node/package.json | 230 + node_modules/@types/node/path.d.ts | 172 + node_modules/@types/node/perf_hooks.d.ts | 555 ++ node_modules/@types/node/process.d.ts | 1477 +++ node_modules/@types/node/punycode.d.ts | 117 + node_modules/@types/node/querystring.d.ts | 131 + node_modules/@types/node/readline.d.ts | 542 ++ node_modules/@types/node/repl.d.ts | 424 + node_modules/@types/node/stream.d.ts | 1249 +++ .../@types/node/stream/consumers.d.ts | 24 + node_modules/@types/node/stream/promises.d.ts | 42 + node_modules/@types/node/stream/web.d.ts | 6 + node_modules/@types/node/string_decoder.d.ts | 67 + node_modules/@types/node/timers.d.ts | 94 + node_modules/@types/node/timers/promises.d.ts | 68 + node_modules/@types/node/tls.d.ts | 1019 ++ node_modules/@types/node/trace_events.d.ts | 161 + node_modules/@types/node/tty.d.ts | 204 + node_modules/@types/node/url.d.ts | 821 ++ node_modules/@types/node/util.d.ts | 1594 ++++ node_modules/@types/node/v8.d.ts | 378 + node_modules/@types/node/vm.d.ts | 507 + node_modules/@types/node/wasi.d.ts | 158 + node_modules/@types/node/worker_threads.d.ts | 649 ++ node_modules/@types/node/zlib.d.ts | 517 + .../@types/webidl-conversions/LICENSE | 21 + .../@types/webidl-conversions/README.md | 16 + .../@types/webidl-conversions/index.d.ts | 103 + .../@types/webidl-conversions/package.json | 25 + node_modules/@types/whatwg-url/LICENSE | 21 + node_modules/@types/whatwg-url/README.md | 16 + .../@types/whatwg-url/dist/URL-impl.d.ts | 23 + node_modules/@types/whatwg-url/dist/URL.d.ts | 76 + .../whatwg-url/dist/URLSearchParams-impl.d.ts | 23 + .../whatwg-url/dist/URLSearchParams.d.ts | 91 + node_modules/@types/whatwg-url/index.d.ts | 162 + node_modules/@types/whatwg-url/package.json | 40 + .../whatwg-url/ts3.9/dist/URL-impl.d.ts | 23 + .../@types/whatwg-url/ts3.9/dist/URL.d.ts | 76 + .../ts3.9/dist/URLSearchParams-impl.d.ts | 24 + .../ts3.9/dist/URLSearchParams.d.ts | 94 + .../@types/whatwg-url/ts3.9/index.d.ts | 155 + .../whatwg-url/ts3.9/webidl2js-wrapper.d.ts | 4 + .../@types/whatwg-url/webidl2js-wrapper.d.ts | 4 + node_modules/abbrev/LICENSE | 46 + node_modules/abbrev/README.md | 23 + node_modules/abbrev/abbrev.js | 61 + node_modules/abbrev/package.json | 21 + node_modules/accepts/HISTORY.md | 236 + node_modules/accepts/LICENSE | 23 + node_modules/accepts/README.md | 142 + node_modules/accepts/index.js | 238 + node_modules/accepts/package.json | 47 + node_modules/agent-base/README.md | 145 + node_modules/agent-base/dist/src/index.d.ts | 78 + node_modules/agent-base/dist/src/index.js | 203 + node_modules/agent-base/dist/src/index.js.map | 1 + .../agent-base/dist/src/promisify.d.ts | 4 + node_modules/agent-base/dist/src/promisify.js | 18 + .../agent-base/dist/src/promisify.js.map | 1 + .../agent-base/node_modules/debug/LICENSE | 20 + .../agent-base/node_modules/debug/README.md | 478 + .../node_modules/debug/package.json | 59 + .../node_modules/debug/src/browser.js | 269 + .../node_modules/debug/src/common.js | 274 + .../node_modules/debug/src/index.js | 10 + .../agent-base/node_modules/debug/src/node.js | 263 + .../agent-base/node_modules/ms/index.js | 162 + .../agent-base/node_modules/ms/license.md | 21 + .../agent-base/node_modules/ms/package.json | 37 + .../agent-base/node_modules/ms/readme.md | 60 + node_modules/agent-base/package.json | 64 + node_modules/agent-base/src/index.ts | 345 + node_modules/agent-base/src/promisify.ts | 33 + node_modules/ansi-regex/index.d.ts | 37 + node_modules/ansi-regex/index.js | 10 + node_modules/ansi-regex/license | 9 + node_modules/ansi-regex/package.json | 55 + node_modules/ansi-regex/readme.md | 78 + node_modules/aproba/CHANGELOG.md | 4 + node_modules/aproba/LICENSE | 14 + node_modules/aproba/README.md | 94 + node_modules/aproba/index.js | 105 + node_modules/aproba/package.json | 35 + node_modules/are-we-there-yet/LICENSE.md | 18 + node_modules/are-we-there-yet/README.md | 208 + node_modules/are-we-there-yet/lib/index.js | 4 + .../are-we-there-yet/lib/tracker-base.js | 11 + .../are-we-there-yet/lib/tracker-group.js | 116 + .../are-we-there-yet/lib/tracker-stream.js | 36 + node_modules/are-we-there-yet/lib/tracker.js | 32 + node_modules/are-we-there-yet/package.json | 53 + node_modules/array-flatten/LICENSE | 21 + node_modules/array-flatten/README.md | 43 + node_modules/array-flatten/array-flatten.js | 64 + node_modules/array-flatten/package.json | 39 + .../balanced-match/.github/FUNDING.yml | 2 + node_modules/balanced-match/LICENSE.md | 21 + node_modules/balanced-match/README.md | 97 + node_modules/balanced-match/index.js | 62 + node_modules/balanced-match/package.json | 48 + node_modules/base64-js/LICENSE | 21 + node_modules/base64-js/README.md | 34 + node_modules/base64-js/base64js.min.js | 1 + node_modules/base64-js/index.d.ts | 3 + node_modules/base64-js/index.js | 150 + node_modules/base64-js/package.json | 47 + node_modules/bcrypt/.editorconfig | 19 + node_modules/bcrypt/.travis.yml | 63 + node_modules/bcrypt/CHANGELOG.md | 171 + node_modules/bcrypt/ISSUE_TEMPLATE.md | 18 + node_modules/bcrypt/LICENSE | 19 + node_modules/bcrypt/Makefile | 19 + node_modules/bcrypt/README.md | 374 + node_modules/bcrypt/SECURITY.md | 15 + node_modules/bcrypt/appveyor.yml | 50 + node_modules/bcrypt/bcrypt.js | 236 + node_modules/bcrypt/binding.gyp | 57 + node_modules/bcrypt/examples/async_compare.js | 21 + .../bcrypt/examples/forever_gen_salt.js | 8 + .../lib/binding/napi-v3/bcrypt_lib.node | Bin 0 -> 167424 bytes node_modules/bcrypt/package.json | 67 + node_modules/bcrypt/promises.js | 42 + node_modules/bcrypt/src/bcrypt.cc | 315 + node_modules/bcrypt/src/bcrypt_node.cc | 286 + node_modules/bcrypt/src/blowfish.cc | 679 ++ node_modules/bcrypt/src/node_blf.h | 132 + node_modules/bcrypt/test/async.js | 181 + node_modules/bcrypt/test/implementation.js | 53 + node_modules/bcrypt/test/promise.js | 252 + node_modules/bcrypt/test/repetitions.js | 118 + node_modules/bcrypt/test/sync.js | 137 + node_modules/bcrypt/test_alpine.sh | 12 + node_modules/bcryptjs/.npmignore | 6 + node_modules/bcryptjs/.travis.yml | 18 + node_modules/bcryptjs/.vscode/settings.json | 3 + node_modules/bcryptjs/LICENSE | 50 + node_modules/bcryptjs/README.md | 251 + node_modules/bcryptjs/bin/bcrypt | 25 + node_modules/bcryptjs/bower.json | 22 + node_modules/bcryptjs/dist/README.md | 15 + node_modules/bcryptjs/dist/bcrypt.js | 1379 +++ node_modules/bcryptjs/dist/bcrypt.min.js | 48 + node_modules/bcryptjs/dist/bcrypt.min.js.gz | Bin 0 -> 9443 bytes node_modules/bcryptjs/dist/bcrypt.min.map | 8 + node_modules/bcryptjs/externs/bcrypt.js | 91 + node_modules/bcryptjs/externs/minimal-env.js | 98 + node_modules/bcryptjs/index.js | 29 + node_modules/bcryptjs/package.json | 47 + node_modules/bcryptjs/scripts/build.js | 37 + node_modules/bcryptjs/src/bcrypt.js | 327 + node_modules/bcryptjs/src/bcrypt/impl.js | 669 ++ .../bcryptjs/src/bcrypt/prng/README.md | 5 + .../bcryptjs/src/bcrypt/prng/accum.js | 133 + .../bcryptjs/src/bcrypt/prng/isaac.js | 140 + node_modules/bcryptjs/src/bcrypt/util.js | 33 + .../bcryptjs/src/bcrypt/util/base64.js | 115 + node_modules/bcryptjs/src/bower.json | 22 + node_modules/bcryptjs/src/wrap.js | 50 + node_modules/bcryptjs/tests/quickbrown.txt | 150 + node_modules/bcryptjs/tests/suite.js | 197 + node_modules/body-parser/HISTORY.md | 609 ++ node_modules/body-parser/LICENSE | 23 + node_modules/body-parser/README.md | 443 + node_modules/body-parser/index.js | 157 + node_modules/body-parser/lib/read.js | 181 + node_modules/body-parser/lib/types/json.js | 230 + node_modules/body-parser/lib/types/raw.js | 101 + node_modules/body-parser/lib/types/text.js | 121 + .../body-parser/lib/types/urlencoded.js | 284 + node_modules/body-parser/package.json | 52 + node_modules/brace-expansion/LICENSE | 21 + node_modules/brace-expansion/README.md | 129 + node_modules/brace-expansion/index.js | 201 + node_modules/brace-expansion/package.json | 47 + node_modules/bson/LICENSE.md | 201 + node_modules/bson/README.md | 376 + node_modules/bson/bower.json | 26 + node_modules/bson/bson.d.ts | 1098 +++ node_modules/bson/dist/bson.browser.esm.js | 7428 +++++++++++++++ .../bson/dist/bson.browser.esm.js.map | 1 + node_modules/bson/dist/bson.browser.umd.js | 7495 +++++++++++++++ .../bson/dist/bson.browser.umd.js.map | 1 + node_modules/bson/dist/bson.bundle.js | 7494 +++++++++++++++ node_modules/bson/dist/bson.bundle.js.map | 1 + node_modules/bson/dist/bson.esm.js | 5397 +++++++++++ node_modules/bson/dist/bson.esm.js.map | 1 + node_modules/bson/etc/prepare.js | 19 + node_modules/bson/lib/binary.js | 239 + node_modules/bson/lib/binary.js.map | 1 + node_modules/bson/lib/bson.js | 252 + node_modules/bson/lib/bson.js.map | 1 + node_modules/bson/lib/code.js | 45 + node_modules/bson/lib/code.js.map | 1 + node_modules/bson/lib/constants.js | 82 + node_modules/bson/lib/constants.js.map | 1 + node_modules/bson/lib/db_ref.js | 96 + node_modules/bson/lib/db_ref.js.map | 1 + node_modules/bson/lib/decimal128.js | 661 ++ node_modules/bson/lib/decimal128.js.map | 1 + node_modules/bson/lib/double.js | 75 + node_modules/bson/lib/double.js.map | 1 + node_modules/bson/lib/ensure_buffer.js | 25 + node_modules/bson/lib/ensure_buffer.js.map | 1 + node_modules/bson/lib/error.js | 51 + node_modules/bson/lib/error.js.map | 1 + node_modules/bson/lib/extended_json.js | 378 + node_modules/bson/lib/extended_json.js.map | 1 + node_modules/bson/lib/float_parser.js | 137 + node_modules/bson/lib/float_parser.js.map | 1 + node_modules/bson/lib/int_32.js | 57 + node_modules/bson/lib/int_32.js.map | 1 + node_modules/bson/lib/long.js | 899 ++ node_modules/bson/lib/long.js.map | 1 + node_modules/bson/lib/map.js | 123 + node_modules/bson/lib/map.js.map | 1 + node_modules/bson/lib/max_key.js | 32 + node_modules/bson/lib/max_key.js.map | 1 + node_modules/bson/lib/min_key.js | 32 + node_modules/bson/lib/min_key.js.map | 1 + node_modules/bson/lib/objectid.js | 301 + node_modules/bson/lib/objectid.js.map | 1 + .../bson/lib/parser/calculate_size.js | 193 + .../bson/lib/parser/calculate_size.js.map | 1 + node_modules/bson/lib/parser/deserializer.js | 587 ++ .../bson/lib/parser/deserializer.js.map | 1 + node_modules/bson/lib/parser/serializer.js | 869 ++ .../bson/lib/parser/serializer.js.map | 1 + node_modules/bson/lib/parser/utils.js | 111 + node_modules/bson/lib/parser/utils.js.map | 1 + node_modules/bson/lib/regexp.js | 73 + node_modules/bson/lib/regexp.js.map | 1 + node_modules/bson/lib/symbol.js | 47 + node_modules/bson/lib/symbol.js.map | 1 + node_modules/bson/lib/timestamp.js | 99 + node_modules/bson/lib/timestamp.js.map | 1 + node_modules/bson/lib/utils/global.js | 18 + node_modules/bson/lib/utils/global.js.map | 1 + node_modules/bson/lib/uuid.js | 179 + node_modules/bson/lib/uuid.js.map | 1 + node_modules/bson/lib/uuid_utils.js | 35 + node_modules/bson/lib/uuid_utils.js.map | 1 + node_modules/bson/lib/validate_utf8.js | 47 + node_modules/bson/lib/validate_utf8.js.map | 1 + node_modules/bson/package.json | 115 + node_modules/bson/src/binary.ts | 286 + node_modules/bson/src/bson.ts | 335 + node_modules/bson/src/code.ts | 60 + node_modules/bson/src/constants.ts | 110 + node_modules/bson/src/db_ref.ts | 123 + node_modules/bson/src/decimal128.ts | 766 ++ node_modules/bson/src/double.ts | 90 + node_modules/bson/src/ensure_buffer.ts | 27 + node_modules/bson/src/error.ts | 13 + node_modules/bson/src/extended_json.ts | 451 + node_modules/bson/src/float_parser.ts | 152 + node_modules/bson/src/int_32.ts | 69 + node_modules/bson/src/long.ts | 1014 ++ node_modules/bson/src/map.ts | 119 + node_modules/bson/src/max_key.ts | 37 + node_modules/bson/src/min_key.ts | 37 + node_modules/bson/src/objectid.ts | 369 + .../bson/src/parser/calculate_size.ts | 227 + node_modules/bson/src/parser/deserializer.ts | 684 ++ node_modules/bson/src/parser/serializer.ts | 1071 +++ node_modules/bson/src/parser/utils.ts | 123 + node_modules/bson/src/regexp.ts | 104 + node_modules/bson/src/symbol.ts | 57 + node_modules/bson/src/timestamp.ts | 116 + node_modules/bson/src/utils/global.ts | 22 + node_modules/bson/src/uuid.ts | 209 + node_modules/bson/src/uuid_utils.ts | 33 + node_modules/bson/src/validate_utf8.ts | 47 + .../buffer-equal-constant-time/.npmignore | 2 + .../buffer-equal-constant-time/.travis.yml | 4 + .../buffer-equal-constant-time/LICENSE.txt | 12 + .../buffer-equal-constant-time/README.md | 50 + .../buffer-equal-constant-time/index.js | 41 + .../buffer-equal-constant-time/package.json | 21 + .../buffer-equal-constant-time/test.js | 42 + node_modules/buffer/AUTHORS.md | 70 + node_modules/buffer/LICENSE | 21 + node_modules/buffer/README.md | 410 + node_modules/buffer/index.d.ts | 186 + node_modules/buffer/index.js | 1817 ++++ node_modules/buffer/package.json | 96 + node_modules/bytes/History.md | 87 + node_modules/bytes/LICENSE | 23 + node_modules/bytes/Readme.md | 126 + node_modules/bytes/index.js | 162 + node_modules/bytes/package.json | 41 + node_modules/child_process/README.md | 9 + node_modules/child_process/package.json | 20 + node_modules/chownr/LICENSE | 15 + node_modules/chownr/README.md | 3 + node_modules/chownr/chownr.js | 167 + node_modules/chownr/package.json | 32 + node_modules/color-support/LICENSE | 15 + node_modules/color-support/README.md | 129 + node_modules/color-support/bin.js | 3 + node_modules/color-support/browser.js | 14 + node_modules/color-support/index.js | 134 + node_modules/color-support/package.json | 36 + node_modules/concat-map/.travis.yml | 4 + node_modules/concat-map/LICENSE | 18 + node_modules/concat-map/README.markdown | 62 + node_modules/concat-map/example/map.js | 6 + node_modules/concat-map/index.js | 13 + node_modules/concat-map/package.json | 43 + node_modules/concat-map/test/map.js | 39 + node_modules/console-control-strings/LICENSE | 13 + .../console-control-strings/README.md | 145 + .../console-control-strings/README.md~ | 140 + node_modules/console-control-strings/index.js | 125 + .../console-control-strings/package.json | 27 + node_modules/content-disposition/HISTORY.md | 55 + node_modules/content-disposition/LICENSE | 22 + node_modules/content-disposition/README.md | 148 + node_modules/content-disposition/index.js | 458 + node_modules/content-disposition/package.json | 44 + node_modules/content-type/HISTORY.md | 24 + node_modules/content-type/LICENSE | 22 + node_modules/content-type/README.md | 92 + node_modules/content-type/index.js | 222 + node_modules/content-type/package.json | 40 + node_modules/cookie-signature/.npmignore | 4 + node_modules/cookie-signature/History.md | 38 + node_modules/cookie-signature/Readme.md | 42 + node_modules/cookie-signature/index.js | 51 + node_modules/cookie-signature/package.json | 18 + node_modules/cookie/HISTORY.md | 123 + node_modules/cookie/LICENSE | 24 + node_modules/cookie/README.md | 253 + node_modules/cookie/index.js | 198 + node_modules/cookie/package.json | 40 + node_modules/debug/.coveralls.yml | 1 + node_modules/debug/.eslintrc | 11 + node_modules/debug/.npmignore | 9 + node_modules/debug/.travis.yml | 14 + node_modules/debug/CHANGELOG.md | 362 + node_modules/debug/LICENSE | 19 + node_modules/debug/Makefile | 50 + node_modules/debug/README.md | 312 + node_modules/debug/component.json | 19 + node_modules/debug/karma.conf.js | 70 + node_modules/debug/node.js | 1 + node_modules/debug/package.json | 49 + node_modules/debug/src/browser.js | 185 + node_modules/debug/src/debug.js | 202 + node_modules/debug/src/index.js | 10 + node_modules/debug/src/inspector-log.js | 15 + node_modules/debug/src/node.js | 248 + node_modules/delegates/.npmignore | 1 + node_modules/delegates/History.md | 22 + node_modules/delegates/License | 20 + node_modules/delegates/Makefile | 8 + node_modules/delegates/Readme.md | 94 + node_modules/delegates/index.js | 121 + node_modules/delegates/package.json | 13 + node_modules/delegates/test/index.js | 94 + node_modules/denque/CHANGELOG.md | 22 + node_modules/denque/LICENSE | 201 + node_modules/denque/README.md | 77 + node_modules/denque/index.d.ts | 47 + node_modules/denque/index.js | 443 + node_modules/denque/package.json | 55 + node_modules/depd/History.md | 96 + node_modules/depd/LICENSE | 22 + node_modules/depd/Readme.md | 280 + node_modules/depd/index.js | 522 + node_modules/depd/lib/browser/index.js | 77 + .../depd/lib/compat/callsite-tostring.js | 103 + .../depd/lib/compat/event-listener-count.js | 22 + node_modules/depd/lib/compat/index.js | 79 + node_modules/depd/package.json | 41 + node_modules/destroy/LICENSE | 22 + node_modules/destroy/README.md | 60 + node_modules/destroy/index.js | 75 + node_modules/destroy/package.json | 37 + node_modules/detect-libc/.npmignore | 7 + node_modules/detect-libc/LICENSE | 201 + node_modules/detect-libc/README.md | 78 + node_modules/detect-libc/bin/detect-libc.js | 18 + node_modules/detect-libc/lib/detect-libc.js | 92 + node_modules/detect-libc/package.json | 35 + node_modules/ecdsa-sig-formatter/CODEOWNERS | 1 + node_modules/ecdsa-sig-formatter/LICENSE | 201 + node_modules/ecdsa-sig-formatter/README.md | 65 + node_modules/ecdsa-sig-formatter/package.json | 46 + .../src/ecdsa-sig-formatter.d.ts | 17 + .../src/ecdsa-sig-formatter.js | 187 + .../src/param-bytes-for-alg.js | 23 + node_modules/ee-first/LICENSE | 22 + node_modules/ee-first/README.md | 80 + node_modules/ee-first/index.js | 95 + node_modules/ee-first/package.json | 29 + node_modules/emoji-regex/LICENSE-MIT.txt | 20 + node_modules/emoji-regex/README.md | 73 + node_modules/emoji-regex/es2015/index.js | 6 + node_modules/emoji-regex/es2015/text.js | 6 + node_modules/emoji-regex/index.d.ts | 23 + node_modules/emoji-regex/index.js | 6 + node_modules/emoji-regex/package.json | 50 + node_modules/emoji-regex/text.js | 6 + node_modules/encodeurl/HISTORY.md | 14 + node_modules/encodeurl/LICENSE | 22 + node_modules/encodeurl/README.md | 128 + node_modules/encodeurl/index.js | 60 + node_modules/encodeurl/package.json | 40 + node_modules/escape-html/LICENSE | 24 + node_modules/escape-html/Readme.md | 43 + node_modules/escape-html/index.js | 78 + node_modules/escape-html/package.json | 24 + node_modules/etag/HISTORY.md | 83 + node_modules/etag/LICENSE | 22 + node_modules/etag/README.md | 159 + node_modules/etag/index.js | 131 + node_modules/etag/package.json | 47 + node_modules/express/History.md | 3477 +++++++ node_modules/express/LICENSE | 24 + node_modules/express/Readme.md | 155 + node_modules/express/index.js | 11 + node_modules/express/lib/application.js | 644 ++ node_modules/express/lib/express.js | 116 + node_modules/express/lib/middleware/init.js | 43 + node_modules/express/lib/middleware/query.js | 47 + node_modules/express/lib/request.js | 525 + node_modules/express/lib/response.js | 1142 +++ node_modules/express/lib/router/index.js | 662 ++ node_modules/express/lib/router/layer.js | 181 + node_modules/express/lib/router/route.js | 216 + node_modules/express/lib/utils.js | 306 + node_modules/express/lib/view.js | 182 + node_modules/express/package.json | 98 + node_modules/finalhandler/HISTORY.md | 187 + node_modules/finalhandler/LICENSE | 22 + node_modules/finalhandler/README.md | 148 + node_modules/finalhandler/index.js | 331 + node_modules/finalhandler/package.json | 45 + node_modules/forwarded/HISTORY.md | 21 + node_modules/forwarded/LICENSE | 22 + node_modules/forwarded/README.md | 57 + node_modules/forwarded/index.js | 90 + node_modules/forwarded/package.json | 45 + node_modules/fresh/HISTORY.md | 70 + node_modules/fresh/LICENSE | 23 + node_modules/fresh/README.md | 119 + node_modules/fresh/index.js | 137 + node_modules/fresh/package.json | 46 + node_modules/fs-minipass/LICENSE | 15 + node_modules/fs-minipass/README.md | 70 + node_modules/fs-minipass/index.js | 422 + node_modules/fs-minipass/package.json | 39 + node_modules/fs.realpath/LICENSE | 43 + node_modules/fs.realpath/README.md | 33 + node_modules/fs.realpath/index.js | 66 + node_modules/fs.realpath/old.js | 303 + node_modules/fs.realpath/package.json | 26 + node_modules/gauge/CHANGELOG.md | 163 + node_modules/gauge/LICENSE | 13 + node_modules/gauge/README.md | 402 + node_modules/gauge/base-theme.js | 14 + node_modules/gauge/error.js | 24 + node_modules/gauge/has-color.js | 4 + node_modules/gauge/index.js | 233 + node_modules/gauge/package.json | 66 + node_modules/gauge/plumbing.js | 48 + node_modules/gauge/process.js | 3 + node_modules/gauge/progress-bar.js | 35 + node_modules/gauge/render-template.js | 178 + node_modules/gauge/set-immediate.js | 7 + node_modules/gauge/set-interval.js | 3 + node_modules/gauge/spin.js | 5 + node_modules/gauge/template-item.js | 72 + node_modules/gauge/theme-set.js | 114 + node_modules/gauge/themes.js | 56 + node_modules/gauge/wide-truncate.js | 25 + node_modules/glob/LICENSE | 21 + node_modules/glob/README.md | 378 + node_modules/glob/common.js | 236 + node_modules/glob/glob.js | 787 ++ node_modules/glob/package.json | 52 + node_modules/glob/sync.js | 483 + node_modules/has-unicode/LICENSE | 14 + node_modules/has-unicode/README.md | 43 + node_modules/has-unicode/index.js | 16 + node_modules/has-unicode/package.json | 30 + node_modules/http-errors/HISTORY.md | 149 + node_modules/http-errors/LICENSE | 23 + node_modules/http-errors/README.md | 163 + node_modules/http-errors/index.js | 266 + node_modules/http-errors/package.json | 49 + node_modules/http-status/CHANGELOG.md | 80 + node_modules/http-status/LICENSE | 15 + node_modules/http-status/README.md | 189 + node_modules/http-status/lib/cloudflare.js | 23 + node_modules/http-status/lib/iis.js | 23 + node_modules/http-status/lib/index.d.ts | 587 ++ node_modules/http-status/lib/index.js | 623 ++ node_modules/http-status/lib/nginx.js | 23 + node_modules/http-status/lib/unofficial.js | 23 + node_modules/http-status/package.json | 82 + node_modules/http-status/tsconfig.json | 8 + node_modules/https-proxy-agent/README.md | 137 + .../https-proxy-agent/dist/agent.d.ts | 30 + node_modules/https-proxy-agent/dist/agent.js | 180 + .../https-proxy-agent/dist/agent.js.map | 1 + .../https-proxy-agent/dist/index.d.ts | 23 + node_modules/https-proxy-agent/dist/index.js | 14 + .../https-proxy-agent/dist/index.js.map | 1 + .../dist/parse-proxy-response.d.ts | 7 + .../dist/parse-proxy-response.js | 66 + .../dist/parse-proxy-response.js.map | 1 + .../node_modules/debug/LICENSE | 20 + .../node_modules/debug/README.md | 478 + .../node_modules/debug/package.json | 59 + .../node_modules/debug/src/browser.js | 269 + .../node_modules/debug/src/common.js | 274 + .../node_modules/debug/src/index.js | 10 + .../node_modules/debug/src/node.js | 263 + .../node_modules/ms/index.js | 162 + .../node_modules/ms/license.md | 21 + .../node_modules/ms/package.json | 37 + .../node_modules/ms/readme.md | 60 + node_modules/https-proxy-agent/package.json | 56 + node_modules/iconv-lite/Changelog.md | 162 + node_modules/iconv-lite/LICENSE | 21 + node_modules/iconv-lite/README.md | 156 + .../iconv-lite/encodings/dbcs-codec.js | 555 ++ .../iconv-lite/encodings/dbcs-data.js | 176 + node_modules/iconv-lite/encodings/index.js | 22 + node_modules/iconv-lite/encodings/internal.js | 188 + .../iconv-lite/encodings/sbcs-codec.js | 72 + .../encodings/sbcs-data-generated.js | 451 + .../iconv-lite/encodings/sbcs-data.js | 174 + .../encodings/tables/big5-added.json | 122 + .../iconv-lite/encodings/tables/cp936.json | 264 + .../iconv-lite/encodings/tables/cp949.json | 273 + .../iconv-lite/encodings/tables/cp950.json | 177 + .../iconv-lite/encodings/tables/eucjp.json | 182 + .../encodings/tables/gb18030-ranges.json | 1 + .../encodings/tables/gbk-added.json | 55 + .../iconv-lite/encodings/tables/shiftjis.json | 125 + node_modules/iconv-lite/encodings/utf16.js | 177 + node_modules/iconv-lite/encodings/utf7.js | 290 + node_modules/iconv-lite/lib/bom-handling.js | 52 + node_modules/iconv-lite/lib/extend-node.js | 217 + node_modules/iconv-lite/lib/index.d.ts | 24 + node_modules/iconv-lite/lib/index.js | 153 + node_modules/iconv-lite/lib/streams.js | 121 + node_modules/iconv-lite/package.json | 46 + node_modules/ieee754/LICENSE | 11 + node_modules/ieee754/README.md | 51 + node_modules/ieee754/index.d.ts | 10 + node_modules/ieee754/index.js | 85 + node_modules/ieee754/package.json | 52 + node_modules/inflight/LICENSE | 15 + node_modules/inflight/README.md | 37 + node_modules/inflight/inflight.js | 54 + node_modules/inflight/package.json | 29 + node_modules/inherits/LICENSE | 16 + node_modules/inherits/README.md | 42 + node_modules/inherits/inherits.js | 7 + node_modules/inherits/inherits_browser.js | 23 + node_modules/inherits/package.json | 29 + node_modules/ipaddr.js/LICENSE | 19 + node_modules/ipaddr.js/README.md | 233 + node_modules/ipaddr.js/ipaddr.min.js | 1 + node_modules/ipaddr.js/lib/ipaddr.js | 673 ++ node_modules/ipaddr.js/lib/ipaddr.js.d.ts | 68 + node_modules/ipaddr.js/package.json | 35 + .../is-fullwidth-code-point/index.d.ts | 17 + node_modules/is-fullwidth-code-point/index.js | 50 + node_modules/is-fullwidth-code-point/license | 9 + .../is-fullwidth-code-point/package.json | 42 + .../is-fullwidth-code-point/readme.md | 39 + node_modules/jsonwebtoken/CHANGELOG.md | 476 + node_modules/jsonwebtoken/LICENSE | 21 + node_modules/jsonwebtoken/README.md | 375 + node_modules/jsonwebtoken/decode.js | 30 + node_modules/jsonwebtoken/index.js | 8 + .../jsonwebtoken/lib/JsonWebTokenError.js | 14 + .../jsonwebtoken/lib/NotBeforeError.js | 13 + .../jsonwebtoken/lib/TokenExpiredError.js | 13 + node_modules/jsonwebtoken/lib/psSupported.js | 3 + node_modules/jsonwebtoken/lib/timespan.js | 18 + .../jsonwebtoken/node_modules/.bin/semver | 12 + .../jsonwebtoken/node_modules/.bin/semver.cmd | 17 + .../jsonwebtoken/node_modules/.bin/semver.ps1 | 28 + .../jsonwebtoken/node_modules/ms/index.js | 162 + .../jsonwebtoken/node_modules/ms/license.md | 21 + .../jsonwebtoken/node_modules/ms/package.json | 38 + .../jsonwebtoken/node_modules/ms/readme.md | 59 + .../node_modules/semver/CHANGELOG.md | 39 + .../jsonwebtoken/node_modules/semver/LICENSE | 15 + .../node_modules/semver/README.md | 412 + .../node_modules/semver/bin/semver | 160 + .../node_modules/semver/package.json | 28 + .../node_modules/semver/range.bnf | 16 + .../node_modules/semver/semver.js | 1483 +++ node_modules/jsonwebtoken/package.json | 71 + node_modules/jsonwebtoken/sign.js | 206 + node_modules/jsonwebtoken/verify.js | 225 + node_modules/jwa/LICENSE | 17 + node_modules/jwa/README.md | 150 + node_modules/jwa/index.js | 252 + node_modules/jwa/package.json | 37 + node_modules/jws/CHANGELOG.md | 34 + node_modules/jws/LICENSE | 17 + node_modules/jws/index.js | 22 + node_modules/jws/lib/data-stream.js | 55 + node_modules/jws/lib/sign-stream.js | 78 + node_modules/jws/lib/tostring.js | 10 + node_modules/jws/lib/verify-stream.js | 120 + node_modules/jws/package.json | 34 + node_modules/jws/readme.md | 255 + node_modules/kareem/.travis.yml | 12 + node_modules/kareem/CHANGELOG.md | 793 ++ node_modules/kareem/LICENSE | 202 + node_modules/kareem/Makefile | 5 + node_modules/kareem/README.md | 420 + node_modules/kareem/docs.js | 39 + node_modules/kareem/gulpfile.js | 18 + node_modules/kareem/index.js | 512 + node_modules/kareem/package.json | 22 + node_modules/kareem/test/examples.test.js | 426 + node_modules/kareem/test/misc.test.js | 71 + node_modules/kareem/test/post.test.js | 198 + node_modules/kareem/test/pre.test.js | 340 + node_modules/kareem/test/wrap.test.js | 342 + node_modules/lodash.includes/LICENSE | 47 + node_modules/lodash.includes/README.md | 18 + node_modules/lodash.includes/index.js | 745 ++ node_modules/lodash.includes/package.json | 17 + node_modules/lodash.isboolean/LICENSE | 22 + node_modules/lodash.isboolean/README.md | 18 + node_modules/lodash.isboolean/index.js | 70 + node_modules/lodash.isboolean/package.json | 17 + node_modules/lodash.isinteger/LICENSE | 47 + node_modules/lodash.isinteger/README.md | 18 + node_modules/lodash.isinteger/index.js | 265 + node_modules/lodash.isinteger/package.json | 17 + node_modules/lodash.isnumber/LICENSE | 22 + node_modules/lodash.isnumber/README.md | 18 + node_modules/lodash.isnumber/index.js | 79 + node_modules/lodash.isnumber/package.json | 17 + node_modules/lodash.isplainobject/LICENSE | 47 + node_modules/lodash.isplainobject/README.md | 18 + node_modules/lodash.isplainobject/index.js | 139 + .../lodash.isplainobject/package.json | 17 + node_modules/lodash.isstring/LICENSE | 22 + node_modules/lodash.isstring/README.md | 18 + node_modules/lodash.isstring/index.js | 95 + node_modules/lodash.isstring/package.json | 17 + node_modules/lodash.once/LICENSE | 47 + node_modules/lodash.once/README.md | 18 + node_modules/lodash.once/index.js | 294 + node_modules/lodash.once/package.json | 17 + node_modules/lru-cache/LICENSE | 15 + node_modules/lru-cache/README.md | 166 + node_modules/lru-cache/index.js | 334 + node_modules/lru-cache/package.json | 34 + node_modules/make-dir/index.d.ts | 66 + node_modules/make-dir/index.js | 156 + node_modules/make-dir/license | 9 + .../make-dir/node_modules/.bin/semver | 12 + .../make-dir/node_modules/.bin/semver.cmd | 17 + .../make-dir/node_modules/.bin/semver.ps1 | 28 + .../make-dir/node_modules/semver/CHANGELOG.md | 70 + .../make-dir/node_modules/semver/LICENSE | 15 + .../make-dir/node_modules/semver/README.md | 443 + .../node_modules/semver/bin/semver.js | 174 + .../make-dir/node_modules/semver/package.json | 28 + .../make-dir/node_modules/semver/range.bnf | 16 + .../make-dir/node_modules/semver/semver.js | 1596 ++++ node_modules/make-dir/package.json | 59 + node_modules/make-dir/readme.md | 125 + node_modules/media-typer/HISTORY.md | 22 + node_modules/media-typer/LICENSE | 22 + node_modules/media-typer/README.md | 81 + node_modules/media-typer/index.js | 270 + node_modules/media-typer/package.json | 26 + node_modules/memory-pager/.travis.yml | 4 + node_modules/memory-pager/LICENSE | 21 + node_modules/memory-pager/README.md | 65 + node_modules/memory-pager/index.js | 160 + node_modules/memory-pager/package.json | 24 + node_modules/memory-pager/test.js | 80 + node_modules/merge-descriptors/HISTORY.md | 21 + node_modules/merge-descriptors/LICENSE | 23 + node_modules/merge-descriptors/README.md | 48 + node_modules/merge-descriptors/index.js | 60 + node_modules/merge-descriptors/package.json | 32 + node_modules/methods/HISTORY.md | 29 + node_modules/methods/LICENSE | 24 + node_modules/methods/README.md | 51 + node_modules/methods/index.js | 69 + node_modules/methods/package.json | 36 + node_modules/mime-db/HISTORY.md | 492 + node_modules/mime-db/LICENSE | 22 + node_modules/mime-db/README.md | 100 + node_modules/mime-db/db.json | 8453 +++++++++++++++++ node_modules/mime-db/index.js | 11 + node_modules/mime-db/package.json | 59 + node_modules/mime-types/HISTORY.md | 385 + node_modules/mime-types/LICENSE | 23 + node_modules/mime-types/README.md | 113 + node_modules/mime-types/index.js | 188 + node_modules/mime-types/package.json | 44 + node_modules/mime/.npmignore | 0 node_modules/mime/CHANGELOG.md | 164 + node_modules/mime/LICENSE | 21 + node_modules/mime/README.md | 90 + node_modules/mime/cli.js | 8 + node_modules/mime/mime.js | 108 + node_modules/mime/package.json | 44 + node_modules/mime/src/build.js | 53 + node_modules/mime/src/test.js | 60 + node_modules/mime/types.json | 1 + node_modules/minimatch/LICENSE | 15 + node_modules/minimatch/README.md | 209 + node_modules/minimatch/minimatch.js | 923 ++ node_modules/minimatch/package.json | 30 + node_modules/minipass/LICENSE | 15 + node_modules/minipass/README.md | 613 ++ node_modules/minipass/index.js | 560 ++ node_modules/minipass/package.json | 39 + node_modules/minizlib/LICENSE | 26 + node_modules/minizlib/README.md | 60 + node_modules/minizlib/constants.js | 115 + node_modules/minizlib/index.js | 348 + node_modules/minizlib/package.json | 42 + node_modules/mkdirp/CHANGELOG.md | 15 + node_modules/mkdirp/LICENSE | 21 + node_modules/mkdirp/bin/cmd.js | 68 + node_modules/mkdirp/index.js | 31 + node_modules/mkdirp/lib/find-made.js | 29 + node_modules/mkdirp/lib/mkdirp-manual.js | 64 + node_modules/mkdirp/lib/mkdirp-native.js | 39 + node_modules/mkdirp/lib/opts-arg.js | 23 + node_modules/mkdirp/lib/path-arg.js | 29 + node_modules/mkdirp/lib/use-native.js | 10 + node_modules/mkdirp/package.json | 44 + node_modules/mkdirp/readme.markdown | 266 + .../.esm-wrapper.mjs | 4 + .../mongodb-connection-string-url/LICENSE | 192 + .../mongodb-connection-string-url/README.md | 25 + .../lib/index.d.ts | 40 + .../lib/index.js | 161 + .../lib/index.js.map | 1 + .../package.json | 62 + node_modules/mongodb/LICENSE.md | 201 + node_modules/mongodb/README.md | 278 + node_modules/mongodb/etc/prepare.js | 12 + node_modules/mongodb/lib/admin.js | 124 + node_modules/mongodb/lib/admin.js.map | 1 + node_modules/mongodb/lib/bson.js | 67 + node_modules/mongodb/lib/bson.js.map | 1 + node_modules/mongodb/lib/bulk/common.js | 941 ++ node_modules/mongodb/lib/bulk/common.js.map | 1 + node_modules/mongodb/lib/bulk/ordered.js | 66 + node_modules/mongodb/lib/bulk/ordered.js.map | 1 + node_modules/mongodb/lib/bulk/unordered.js | 91 + .../mongodb/lib/bulk/unordered.js.map | 1 + node_modules/mongodb/lib/change_stream.js | 495 + node_modules/mongodb/lib/change_stream.js.map | 1 + .../mongodb/lib/cmap/auth/auth_provider.js | 36 + .../lib/cmap/auth/auth_provider.js.map | 1 + .../lib/cmap/auth/defaultAuthProviders.js | 30 + .../lib/cmap/auth/defaultAuthProviders.js.map | 1 + node_modules/mongodb/lib/cmap/auth/gssapi.js | 148 + .../mongodb/lib/cmap/auth/gssapi.js.map | 1 + .../lib/cmap/auth/mongo_credentials.js | 125 + .../lib/cmap/auth/mongo_credentials.js.map | 1 + node_modules/mongodb/lib/cmap/auth/mongocr.js | 44 + .../mongodb/lib/cmap/auth/mongocr.js.map | 1 + .../mongodb/lib/cmap/auth/mongodb_aws.js | 201 + .../mongodb/lib/cmap/auth/mongodb_aws.js.map | 1 + node_modules/mongodb/lib/cmap/auth/plain.js | 27 + .../mongodb/lib/cmap/auth/plain.js.map | 1 + node_modules/mongodb/lib/cmap/auth/scram.js | 276 + .../mongodb/lib/cmap/auth/scram.js.map | 1 + node_modules/mongodb/lib/cmap/auth/x509.js | 39 + .../mongodb/lib/cmap/auth/x509.js.map | 1 + .../lib/cmap/command_monitoring_events.js | 272 + .../lib/cmap/command_monitoring_events.js.map | 1 + node_modules/mongodb/lib/cmap/commands.js | 623 ++ node_modules/mongodb/lib/cmap/commands.js.map | 1 + node_modules/mongodb/lib/cmap/connect.js | 304 + node_modules/mongodb/lib/cmap/connect.js.map | 1 + node_modules/mongodb/lib/cmap/connection.js | 557 ++ .../mongodb/lib/cmap/connection.js.map | 1 + .../mongodb/lib/cmap/connection_pool.js | 495 + .../mongodb/lib/cmap/connection_pool.js.map | 1 + .../lib/cmap/connection_pool_events.js | 147 + .../lib/cmap/connection_pool_events.js.map | 1 + node_modules/mongodb/lib/cmap/errors.js | 33 + node_modules/mongodb/lib/cmap/errors.js.map | 1 + .../mongodb/lib/cmap/message_stream.js | 142 + .../mongodb/lib/cmap/message_stream.js.map | 1 + node_modules/mongodb/lib/cmap/metrics.js | 62 + node_modules/mongodb/lib/cmap/metrics.js.map | 1 + .../mongodb/lib/cmap/stream_description.js | 48 + .../lib/cmap/stream_description.js.map | 1 + .../lib/cmap/wire_protocol/compression.js | 83 + .../lib/cmap/wire_protocol/compression.js.map | 1 + .../lib/cmap/wire_protocol/constants.js | 17 + .../lib/cmap/wire_protocol/constants.js.map | 1 + .../mongodb/lib/cmap/wire_protocol/shared.js | 51 + .../lib/cmap/wire_protocol/shared.js.map | 1 + node_modules/mongodb/lib/collection.js | 491 + node_modules/mongodb/lib/collection.js.map | 1 + node_modules/mongodb/lib/connection_string.js | 996 ++ .../mongodb/lib/connection_string.js.map | 1 + node_modules/mongodb/lib/constants.js | 10 + node_modules/mongodb/lib/constants.js.map | 1 + .../mongodb/lib/cursor/abstract_cursor.js | 629 ++ .../mongodb/lib/cursor/abstract_cursor.js.map | 1 + .../mongodb/lib/cursor/aggregation_cursor.js | 172 + .../lib/cursor/aggregation_cursor.js.map | 1 + .../mongodb/lib/cursor/find_cursor.js | 376 + .../mongodb/lib/cursor/find_cursor.js.map | 1 + node_modules/mongodb/lib/db.js | 317 + node_modules/mongodb/lib/db.js.map | 1 + node_modules/mongodb/lib/deps.js | 59 + node_modules/mongodb/lib/deps.js.map | 1 + node_modules/mongodb/lib/encrypter.js | 93 + node_modules/mongodb/lib/encrypter.js.map | 1 + node_modules/mongodb/lib/error.js | 712 ++ node_modules/mongodb/lib/error.js.map | 1 + node_modules/mongodb/lib/explain.js | 35 + node_modules/mongodb/lib/explain.js.map | 1 + node_modules/mongodb/lib/gridfs/download.js | 315 + .../mongodb/lib/gridfs/download.js.map | 1 + node_modules/mongodb/lib/gridfs/index.js | 161 + node_modules/mongodb/lib/gridfs/index.js.map | 1 + node_modules/mongodb/lib/gridfs/upload.js | 375 + node_modules/mongodb/lib/gridfs/upload.js.map | 1 + node_modules/mongodb/lib/index.js | 149 + node_modules/mongodb/lib/index.js.map | 1 + node_modules/mongodb/lib/logger.js | 217 + node_modules/mongodb/lib/logger.js.map | 1 + node_modules/mongodb/lib/mongo_client.js | 262 + node_modules/mongodb/lib/mongo_client.js.map | 1 + node_modules/mongodb/lib/mongo_types.js | 41 + node_modules/mongodb/lib/mongo_types.js.map | 1 + .../mongodb/lib/operations/add_user.js | 65 + .../mongodb/lib/operations/add_user.js.map | 1 + .../mongodb/lib/operations/aggregate.js | 86 + .../mongodb/lib/operations/aggregate.js.map | 1 + .../mongodb/lib/operations/bulk_write.js | 43 + .../mongodb/lib/operations/bulk_write.js.map | 1 + .../mongodb/lib/operations/collections.js | 29 + .../mongodb/lib/operations/collections.js.map | 1 + .../mongodb/lib/operations/command.js | 95 + .../mongodb/lib/operations/command.js.map | 1 + .../lib/operations/common_functions.js | 64 + .../lib/operations/common_functions.js.map | 1 + .../mongodb/lib/operations/connect.js | 93 + .../mongodb/lib/operations/connect.js.map | 1 + node_modules/mongodb/lib/operations/count.js | 39 + .../mongodb/lib/operations/count.js.map | 1 + .../mongodb/lib/operations/count_documents.js | 37 + .../lib/operations/count_documents.js.map | 1 + .../lib/operations/create_collection.js | 60 + .../lib/operations/create_collection.js.map | 1 + node_modules/mongodb/lib/operations/delete.js | 133 + .../mongodb/lib/operations/delete.js.map | 1 + .../mongodb/lib/operations/distinct.js | 67 + .../mongodb/lib/operations/distinct.js.map | 1 + node_modules/mongodb/lib/operations/drop.js | 43 + .../mongodb/lib/operations/drop.js.map | 1 + .../operations/estimated_document_count.js | 52 + .../estimated_document_count.js.map | 1 + node_modules/mongodb/lib/operations/eval.js | 55 + .../mongodb/lib/operations/eval.js.map | 1 + .../lib/operations/execute_operation.js | 162 + .../lib/operations/execute_operation.js.map | 1 + node_modules/mongodb/lib/operations/find.js | 211 + .../mongodb/lib/operations/find.js.map | 1 + .../mongodb/lib/operations/find_and_modify.js | 151 + .../lib/operations/find_and_modify.js.map | 1 + .../mongodb/lib/operations/indexes.js | 297 + .../mongodb/lib/operations/indexes.js.map | 1 + node_modules/mongodb/lib/operations/insert.js | 93 + .../mongodb/lib/operations/insert.js.map | 1 + .../mongodb/lib/operations/is_capped.js | 30 + .../mongodb/lib/operations/is_capped.js.map | 1 + .../lib/operations/list_collections.js | 105 + .../lib/operations/list_collections.js.map | 1 + .../mongodb/lib/operations/list_databases.js | 30 + .../lib/operations/list_databases.js.map | 1 + .../mongodb/lib/operations/map_reduce.js | 166 + .../mongodb/lib/operations/map_reduce.js.map | 1 + .../mongodb/lib/operations/operation.js | 67 + .../mongodb/lib/operations/operation.js.map | 1 + .../lib/operations/options_operation.js | 29 + .../lib/operations/options_operation.js.map | 1 + .../mongodb/lib/operations/profiling_level.js | 33 + .../lib/operations/profiling_level.js.map | 1 + .../mongodb/lib/operations/remove_user.js | 21 + .../mongodb/lib/operations/remove_user.js.map | 1 + node_modules/mongodb/lib/operations/rename.js | 46 + .../mongodb/lib/operations/rename.js.map | 1 + .../mongodb/lib/operations/run_command.js | 26 + .../mongodb/lib/operations/run_command.js.map | 1 + .../lib/operations/set_profiling_level.js | 51 + .../lib/operations/set_profiling_level.js.map | 1 + node_modules/mongodb/lib/operations/stats.js | 48 + .../mongodb/lib/operations/stats.js.map | 1 + node_modules/mongodb/lib/operations/update.js | 195 + .../mongodb/lib/operations/update.js.map | 1 + .../lib/operations/validate_collection.js | 41 + .../lib/operations/validate_collection.js.map | 1 + node_modules/mongodb/lib/promise_provider.js | 36 + .../mongodb/lib/promise_provider.js.map | 1 + node_modules/mongodb/lib/read_concern.js | 73 + node_modules/mongodb/lib/read_concern.js.map | 1 + node_modules/mongodb/lib/read_preference.js | 194 + .../mongodb/lib/read_preference.js.map | 1 + node_modules/mongodb/lib/sdam/common.js | 61 + node_modules/mongodb/lib/sdam/common.js.map | 1 + node_modules/mongodb/lib/sdam/events.js | 125 + node_modules/mongodb/lib/sdam/events.js.map | 1 + node_modules/mongodb/lib/sdam/monitor.js | 319 + node_modules/mongodb/lib/sdam/monitor.js.map | 1 + node_modules/mongodb/lib/sdam/server.js | 366 + node_modules/mongodb/lib/sdam/server.js.map | 1 + .../mongodb/lib/sdam/server_description.js | 197 + .../lib/sdam/server_description.js.map | 1 + .../mongodb/lib/sdam/server_selection.js | 193 + .../mongodb/lib/sdam/server_selection.js.map | 1 + node_modules/mongodb/lib/sdam/srv_polling.js | 121 + .../mongodb/lib/sdam/srv_polling.js.map | 1 + node_modules/mongodb/lib/sdam/topology.js | 722 ++ node_modules/mongodb/lib/sdam/topology.js.map | 1 + .../mongodb/lib/sdam/topology_description.js | 337 + .../lib/sdam/topology_description.js.map | 1 + node_modules/mongodb/lib/sessions.js | 726 ++ node_modules/mongodb/lib/sessions.js.map | 1 + node_modules/mongodb/lib/sort.js | 97 + node_modules/mongodb/lib/sort.js.map | 1 + node_modules/mongodb/lib/transactions.js | 138 + node_modules/mongodb/lib/transactions.js.map | 1 + node_modules/mongodb/lib/utils.js | 1150 +++ node_modules/mongodb/lib/utils.js.map | 1 + node_modules/mongodb/lib/write_concern.js | 71 + node_modules/mongodb/lib/write_concern.js.map | 1 + node_modules/mongodb/mongodb.d.ts | 5944 ++++++++++++ node_modules/mongodb/mongodb.ts34.d.ts | 5504 +++++++++++ node_modules/mongodb/package.json | 130 + node_modules/mongodb/src/admin.ts | 314 + node_modules/mongodb/src/bson.ts | 103 + node_modules/mongodb/src/bulk/common.ts | 1340 +++ node_modules/mongodb/src/bulk/ordered.ts | 82 + node_modules/mongodb/src/bulk/unordered.ts | 109 + node_modules/mongodb/src/change_stream.ts | 827 ++ .../mongodb/src/cmap/auth/auth_provider.ts | 60 + .../src/cmap/auth/defaultAuthProviders.ts | 32 + node_modules/mongodb/src/cmap/auth/gssapi.ts | 190 + .../src/cmap/auth/mongo_credentials.ts | 179 + node_modules/mongodb/src/cmap/auth/mongocr.ts | 46 + .../mongodb/src/cmap/auth/mongodb_aws.ts | 289 + node_modules/mongodb/src/cmap/auth/plain.ts | 25 + node_modules/mongodb/src/cmap/auth/scram.ts | 373 + node_modules/mongodb/src/cmap/auth/x509.ts | 49 + .../src/cmap/command_monitoring_events.ts | 334 + node_modules/mongodb/src/cmap/commands.ts | 876 ++ node_modules/mongodb/src/cmap/connect.ts | 400 + node_modules/mongodb/src/cmap/connection.ts | 854 ++ .../mongodb/src/cmap/connection_pool.ts | 692 ++ .../src/cmap/connection_pool_events.ts | 179 + node_modules/mongodb/src/cmap/errors.ts | 38 + .../mongodb/src/cmap/message_stream.ts | 208 + node_modules/mongodb/src/cmap/metrics.ts | 58 + .../mongodb/src/cmap/stream_description.ts | 73 + .../src/cmap/wire_protocol/compression.ts | 103 + .../src/cmap/wire_protocol/constants.ts | 13 + .../mongodb/src/cmap/wire_protocol/shared.ts | 71 + node_modules/mongodb/src/collection.ts | 1617 ++++ node_modules/mongodb/src/connection_string.ts | 1119 +++ node_modules/mongodb/src/constants.ts | 6 + .../mongodb/src/cursor/abstract_cursor.ts | 889 ++ .../mongodb/src/cursor/aggregation_cursor.ts | 219 + .../mongodb/src/cursor/find_cursor.ts | 464 + node_modules/mongodb/src/db.ts | 756 ++ node_modules/mongodb/src/deps.ts | 275 + node_modules/mongodb/src/encrypter.ts | 119 + node_modules/mongodb/src/error.ts | 813 ++ node_modules/mongodb/src/explain.ts | 52 + node_modules/mongodb/src/gridfs/download.ts | 454 + node_modules/mongodb/src/gridfs/index.ts | 274 + node_modules/mongodb/src/gridfs/upload.ts | 563 ++ node_modules/mongodb/src/index.ts | 435 + node_modules/mongodb/src/logger.ts | 264 + node_modules/mongodb/src/mongo_client.ts | 699 ++ node_modules/mongodb/src/mongo_types.ts | 427 + .../mongodb/src/operations/add_user.ts | 106 + .../mongodb/src/operations/aggregate.ts | 135 + .../mongodb/src/operations/bulk_write.ts | 63 + .../mongodb/src/operations/collections.ts | 44 + .../mongodb/src/operations/command.ts | 171 + .../src/operations/common_functions.ts | 95 + .../mongodb/src/operations/connect.ts | 116 + node_modules/mongodb/src/operations/count.ts | 64 + .../mongodb/src/operations/count_documents.ts | 53 + .../src/operations/create_collection.ts | 122 + node_modules/mongodb/src/operations/delete.ts | 188 + .../mongodb/src/operations/distinct.ts | 88 + node_modules/mongodb/src/operations/drop.ts | 52 + .../operations/estimated_document_count.ts | 75 + node_modules/mongodb/src/operations/eval.ts | 78 + .../src/operations/execute_operation.ts | 269 + node_modules/mongodb/src/operations/find.ts | 355 + .../mongodb/src/operations/find_and_modify.ts | 276 + .../mongodb/src/operations/indexes.ts | 525 + node_modules/mongodb/src/operations/insert.ts | 137 + .../mongodb/src/operations/is_capped.ts | 38 + .../src/operations/list_collections.ts | 161 + .../mongodb/src/operations/list_databases.ts | 50 + .../mongodb/src/operations/map_reduce.ts | 248 + .../mongodb/src/operations/operation.ts | 116 + .../src/operations/options_operation.ts | 38 + .../mongodb/src/operations/profiling_level.ts | 35 + .../mongodb/src/operations/remove_user.ts | 29 + node_modules/mongodb/src/operations/rename.ts | 63 + .../mongodb/src/operations/run_command.ts | 32 + .../src/operations/set_profiling_level.ts | 69 + node_modules/mongodb/src/operations/stats.ts | 263 + node_modules/mongodb/src/operations/update.ts | 322 + .../src/operations/validate_collection.ts | 55 + node_modules/mongodb/src/promise_provider.ts | 41 + node_modules/mongodb/src/read_concern.ts | 87 + node_modules/mongodb/src/read_preference.ts | 264 + node_modules/mongodb/src/sdam/common.ts | 83 + node_modules/mongodb/src/sdam/events.ts | 182 + node_modules/mongodb/src/sdam/monitor.ts | 465 + node_modules/mongodb/src/sdam/server.ts | 602 ++ .../mongodb/src/sdam/server_description.ts | 279 + .../mongodb/src/sdam/server_selection.ts | 281 + node_modules/mongodb/src/sdam/srv_polling.ts | 162 + node_modules/mongodb/src/sdam/topology.ts | 1109 +++ .../mongodb/src/sdam/topology_description.ts | 487 + node_modules/mongodb/src/sessions.ts | 1058 +++ node_modules/mongodb/src/sort.ts | 132 + node_modules/mongodb/src/transactions.ts | 187 + node_modules/mongodb/src/utils.ts | 1440 +++ node_modules/mongodb/src/write_concern.ts | 114 + node_modules/mongoose/LICENSE.md | 22 + node_modules/mongoose/README.md | 366 + node_modules/mongoose/SECURITY.md | 1 + node_modules/mongoose/browser.js | 8 + node_modules/mongoose/build-browser.js | 18 + node_modules/mongoose/dist/browser.umd.js | 1665 ++++ node_modules/mongoose/index.d.ts | 3098 ++++++ node_modules/mongoose/index.js | 9 + node_modules/mongoose/lib/aggregate.js | 1141 +++ node_modules/mongoose/lib/browser.js | 158 + node_modules/mongoose/lib/browserDocument.js | 100 + node_modules/mongoose/lib/cast.js | 369 + node_modules/mongoose/lib/cast/boolean.js | 32 + node_modules/mongoose/lib/cast/date.js | 41 + node_modules/mongoose/lib/cast/decimal128.js | 36 + node_modules/mongoose/lib/cast/number.js | 43 + node_modules/mongoose/lib/cast/objectid.js | 29 + node_modules/mongoose/lib/cast/string.js | 37 + node_modules/mongoose/lib/collection.js | 318 + node_modules/mongoose/lib/connection.js | 1395 +++ node_modules/mongoose/lib/connectionstate.js | 26 + .../mongoose/lib/cursor/AggregationCursor.js | 375 + .../mongoose/lib/cursor/ChangeStream.js | 61 + .../mongoose/lib/cursor/QueryCursor.js | 528 + node_modules/mongoose/lib/document.js | 4362 +++++++++ .../mongoose/lib/document_provider.js | 30 + node_modules/mongoose/lib/driver.js | 15 + node_modules/mongoose/lib/drivers/SPEC.md | 4 + .../lib/drivers/browser/ReadPreference.js | 7 + .../mongoose/lib/drivers/browser/binary.js | 14 + .../lib/drivers/browser/decimal128.js | 7 + .../mongoose/lib/drivers/browser/index.js | 16 + .../mongoose/lib/drivers/browser/objectid.js | 28 + .../node-mongodb-native/ReadPreference.js | 47 + .../lib/drivers/node-mongodb-native/binary.js | 10 + .../drivers/node-mongodb-native/collection.js | 411 + .../drivers/node-mongodb-native/connection.js | 153 + .../drivers/node-mongodb-native/decimal128.js | 7 + .../lib/drivers/node-mongodb-native/index.js | 12 + .../drivers/node-mongodb-native/objectid.js | 16 + .../lib/error/browserMissingSchema.js | 28 + node_modules/mongoose/lib/error/cast.js | 150 + .../mongoose/lib/error/disconnected.js | 34 + .../mongoose/lib/error/divergentArray.js | 37 + node_modules/mongoose/lib/error/index.js | 205 + node_modules/mongoose/lib/error/messages.js | 47 + .../mongoose/lib/error/missingSchema.js | 30 + .../mongoose/lib/error/mongooseError.js | 13 + node_modules/mongoose/lib/error/notFound.js | 44 + .../mongoose/lib/error/objectExpected.js | 30 + .../mongoose/lib/error/objectParameter.js | 30 + .../mongoose/lib/error/overwriteModel.js | 29 + .../mongoose/lib/error/parallelSave.js | 30 + .../mongoose/lib/error/parallelValidate.js | 31 + .../mongoose/lib/error/serverSelection.js | 61 + node_modules/mongoose/lib/error/strict.js | 33 + node_modules/mongoose/lib/error/validation.js | 112 + node_modules/mongoose/lib/error/validator.js | 94 + node_modules/mongoose/lib/error/version.js | 36 + .../aggregate/stringifyFunctionOperators.js | 50 + .../mongoose/lib/helpers/arrayDepth.js | 33 + node_modules/mongoose/lib/helpers/clone.js | 148 + node_modules/mongoose/lib/helpers/common.js | 115 + .../mongoose/lib/helpers/cursor/eachAsync.js | 157 + .../areDiscriminatorValuesEqual.js | 16 + ...checkEmbeddedDiscriminatorKeyProjection.js | 12 + .../helpers/discriminator/getConstructor.js | 25 + .../discriminator/getDiscriminatorByValue.js | 27 + .../getSchemaDiscriminatorByValue.js | 26 + .../helpers/document/cleanModifiedSubpaths.js | 28 + .../mongoose/lib/helpers/document/compile.js | 207 + .../document/getEmbeddedDiscriminatorPath.js | 46 + .../lib/helpers/document/handleSpreadDoc.js | 17 + node_modules/mongoose/lib/helpers/each.js | 25 + node_modules/mongoose/lib/helpers/get.js | 64 + .../lib/helpers/getConstructorName.js | 15 + .../lib/helpers/getDefaultBulkwriteResult.js | 27 + .../mongoose/lib/helpers/getFunctionName.js | 8 + .../mongoose/lib/helpers/immediate.js | 14 + .../lib/helpers/indexes/isDefaultIdIndex.js | 18 + .../lib/helpers/indexes/isIndexEqual.js | 96 + .../mongoose/lib/helpers/isAsyncFunction.js | 11 + .../mongoose/lib/helpers/isBsonType.js | 13 + .../mongoose/lib/helpers/isMongooseObject.js | 21 + node_modules/mongoose/lib/helpers/isObject.js | 16 + .../mongoose/lib/helpers/isPromise.js | 6 + .../mongoose/lib/helpers/model/applyHooks.js | 138 + .../lib/helpers/model/applyMethods.js | 57 + .../lib/helpers/model/applyStaticHooks.js | 71 + .../lib/helpers/model/applyStatics.js | 12 + .../lib/helpers/model/castBulkWrite.js | 223 + .../lib/helpers/model/discriminator.js | 209 + node_modules/mongoose/lib/helpers/once.js | 12 + .../mongoose/lib/helpers/parallelLimit.js | 55 + .../path/flattenObjectWithDottedPaths.js | 25 + .../mongoose/lib/helpers/path/parentPaths.js | 13 + .../lib/helpers/path/setDottedPath.js | 16 + .../mongoose/lib/helpers/pluralize.js | 94 + .../lib/helpers/populate/SkipPopulateValue.js | 10 + .../populate/assignRawDocsToIdStructure.js | 107 + .../lib/helpers/populate/assignVals.js | 307 + .../populate/createPopulateQueryFilter.js | 80 + .../populate/getModelsMapForPopulate.js | 680 ++ .../lib/helpers/populate/getSchemaTypes.js | 229 + .../lib/helpers/populate/getVirtual.js | 72 + .../lib/helpers/populate/leanPopulateMap.js | 7 + .../lib/helpers/populate/lookupLocalFields.js | 40 + .../populate/markArraySubdocsPopulated.js | 40 + .../helpers/populate/modelNamesFromRefPath.js | 65 + .../populate/removeDeselectedForeignField.js | 31 + .../lib/helpers/populate/validateRef.js | 19 + .../mongoose/lib/helpers/printJestWarning.js | 17 + .../lib/helpers/processConnectionOptions.js | 64 + .../projection/isDefiningProjection.js | 18 + .../lib/helpers/projection/isExclusive.js | 32 + .../lib/helpers/projection/isInclusive.js | 34 + .../lib/helpers/projection/isPathExcluded.js | 35 + .../projection/isPathSelectedInclusive.js | 28 + .../lib/helpers/projection/parseProjection.js | 33 + .../mongoose/lib/helpers/promiseOrCallback.js | 46 + .../lib/helpers/query/applyGlobalMaxTimeMS.js | 15 + .../lib/helpers/query/applyQueryMiddleware.js | 78 + .../lib/helpers/query/castFilterPath.js | 55 + .../mongoose/lib/helpers/query/castUpdate.js | 532 ++ .../lib/helpers/query/completeMany.js | 51 + .../query/getEmbeddedDiscriminatorPath.js | 84 + .../lib/helpers/query/handleImmutable.js | 28 + .../lib/helpers/query/hasDollarKeys.js | 19 + .../mongoose/lib/helpers/query/isOperator.js | 11 + .../lib/helpers/query/sanitizeFilter.js | 38 + .../lib/helpers/query/sanitizeProjection.js | 14 + .../helpers/query/selectPopulatedFields.js | 49 + .../mongoose/lib/helpers/query/trusted.js | 13 + .../mongoose/lib/helpers/query/validOps.js | 24 + .../mongoose/lib/helpers/query/wrapThunk.js | 29 + .../mongoose/lib/helpers/schema/addAutoId.js | 7 + .../lib/helpers/schema/applyPlugins.js | 44 + .../lib/helpers/schema/applyWriteConcern.js | 30 + .../schema/cleanPositionalOperators.js | 12 + .../mongoose/lib/helpers/schema/getIndexes.js | 155 + .../helpers/schema/getKeysInSchemaOrder.js | 28 + .../mongoose/lib/helpers/schema/getPath.js | 35 + .../lib/helpers/schema/handleIdOption.js | 20 + .../helpers/schema/handleTimestampOption.js | 24 + .../mongoose/lib/helpers/schema/idGetter.js | 31 + .../mongoose/lib/helpers/schema/merge.js | 27 + .../lib/helpers/schematype/handleImmutable.js | 47 + .../lib/helpers/setDefaultsOnInsert.js | 108 + .../mongoose/lib/helpers/specialProperties.js | 3 + node_modules/mongoose/lib/helpers/symbols.js | 20 + node_modules/mongoose/lib/helpers/timers.js | 3 + .../lib/helpers/timestamps/setupTimestamps.js | 107 + .../lib/helpers/topology/allServersUnknown.js | 12 + .../mongoose/lib/helpers/topology/isAtlas.js | 13 + .../lib/helpers/topology/isSSLError.js | 16 + .../update/applyTimestampsToChildren.js | 185 + .../helpers/update/applyTimestampsToUpdate.js | 118 + .../lib/helpers/update/castArrayFilters.js | 70 + .../lib/helpers/update/modifiedPaths.js | 33 + .../helpers/update/moveImmutableProperties.js | 53 + .../update/removeUnusedArrayFilters.js | 32 + .../update/updatedPathsByArrayFilter.js | 27 + .../mongoose/lib/helpers/updateValidators.js | 256 + node_modules/mongoose/lib/index.js | 1162 +++ node_modules/mongoose/lib/internal.js | 38 + node_modules/mongoose/lib/model.js | 4980 ++++++++++ node_modules/mongoose/lib/options.js | 15 + .../mongoose/lib/options/PopulateOptions.js | 36 + .../lib/options/SchemaArrayOptions.js | 59 + .../lib/options/SchemaBufferOptions.js | 38 + .../mongoose/lib/options/SchemaDateOptions.js | 64 + .../lib/options/SchemaDocumentArrayOptions.js | 68 + .../mongoose/lib/options/SchemaMapOptions.js | 43 + .../lib/options/SchemaNumberOptions.js | 99 + .../lib/options/SchemaObjectIdOptions.js | 63 + .../lib/options/SchemaStringOptions.js | 138 + .../lib/options/SchemaSubdocumentOptions.js | 42 + .../mongoose/lib/options/SchemaTypeOptions.js | 231 + .../mongoose/lib/options/VirtualOptions.js | 164 + .../mongoose/lib/options/propertyOptions.js | 8 + .../mongoose/lib/options/removeOptions.js | 14 + .../mongoose/lib/options/saveOptions.js | 14 + .../mongoose/lib/plugins/removeSubdocs.js | 31 + .../mongoose/lib/plugins/saveSubdocs.js | 66 + node_modules/mongoose/lib/plugins/sharding.js | 83 + .../mongoose/lib/plugins/trackTransaction.js | 91 + .../lib/plugins/validateBeforeSave.js | 45 + node_modules/mongoose/lib/promise_provider.js | 49 + node_modules/mongoose/lib/query.js | 5598 +++++++++++ node_modules/mongoose/lib/queryhelpers.js | 330 + node_modules/mongoose/lib/schema.js | 2241 +++++ .../mongoose/lib/schema/SubdocumentPath.js | 349 + node_modules/mongoose/lib/schema/array.js | 651 ++ node_modules/mongoose/lib/schema/boolean.js | 270 + node_modules/mongoose/lib/schema/buffer.js | 267 + node_modules/mongoose/lib/schema/date.js | 403 + .../mongoose/lib/schema/decimal128.js | 210 + .../mongoose/lib/schema/documentarray.js | 583 ++ node_modules/mongoose/lib/schema/index.js | 37 + node_modules/mongoose/lib/schema/map.js | 76 + node_modules/mongoose/lib/schema/mixed.js | 132 + node_modules/mongoose/lib/schema/number.js | 440 + node_modules/mongoose/lib/schema/objectid.js | 297 + .../mongoose/lib/schema/operators/bitwise.js | 38 + .../mongoose/lib/schema/operators/exists.js | 12 + .../lib/schema/operators/geospatial.js | 107 + .../mongoose/lib/schema/operators/helpers.js | 32 + .../mongoose/lib/schema/operators/text.js | 39 + .../mongoose/lib/schema/operators/type.js | 20 + node_modules/mongoose/lib/schema/string.js | 672 ++ node_modules/mongoose/lib/schema/symbols.js | 5 + node_modules/mongoose/lib/schematype.js | 1638 ++++ node_modules/mongoose/lib/statemachine.js | 180 + .../mongoose/lib/types/ArraySubdocument.js | 170 + .../mongoose/lib/types/DocumentArray/index.js | 130 + .../lib/types/DocumentArray/methods/index.js | 359 + .../mongoose/lib/types/array/ArrayWrapper.js | 981 ++ .../mongoose/lib/types/array/index.js | 115 + .../mongoose/lib/types/array/methods/index.js | 960 ++ node_modules/mongoose/lib/types/buffer.js | 273 + node_modules/mongoose/lib/types/decimal128.js | 13 + node_modules/mongoose/lib/types/index.js | 20 + node_modules/mongoose/lib/types/map.js | 244 + node_modules/mongoose/lib/types/objectid.js | 41 + .../mongoose/lib/types/subdocument.js | 372 + node_modules/mongoose/lib/utils.js | 961 ++ node_modules/mongoose/lib/validoptions.js | 32 + node_modules/mongoose/lib/virtualtype.js | 176 + .../mongoose/node_modules/ms/index.js | 162 + .../mongoose/node_modules/ms/license.md | 21 + .../mongoose/node_modules/ms/package.json | 37 + .../mongoose/node_modules/ms/readme.md | 60 + node_modules/mongoose/package.json | 250 + node_modules/mongoose/tools/auth.js | 31 + node_modules/mongoose/tools/repl.js | 36 + node_modules/mongoose/tools/sharded.js | 46 + node_modules/mpath/.travis.yml | 9 + node_modules/mpath/History.md | 84 + node_modules/mpath/LICENSE | 22 + node_modules/mpath/Makefile | 4 + node_modules/mpath/README.md | 278 + node_modules/mpath/SECURITY.md | 5 + node_modules/mpath/bench.js | 110 + node_modules/mpath/bench.log | 0 node_modules/mpath/bench.out | 52 + node_modules/mpath/index.js | 3 + node_modules/mpath/lib/index.js | 326 + node_modules/mpath/lib/stringToParts.js | 48 + node_modules/mpath/package.json | 144 + node_modules/mpath/test/.eslintrc.yml | 4 + node_modules/mpath/test/index.js | 1879 ++++ node_modules/mpath/test/stringToParts.js | 30 + node_modules/mquery/.eslintignore | 1 + node_modules/mquery/.eslintrc.json | 123 + node_modules/mquery/.travis.yml | 17 + node_modules/mquery/History.md | 363 + node_modules/mquery/LICENSE | 22 + node_modules/mquery/Makefile | 26 + node_modules/mquery/README.md | 1373 +++ node_modules/mquery/SECURITY.md | 1 + .../mquery/lib/collection/collection.js | 47 + node_modules/mquery/lib/collection/index.js | 13 + node_modules/mquery/lib/collection/node.js | 148 + node_modules/mquery/lib/env.js | 22 + node_modules/mquery/lib/mquery.js | 3201 +++++++ node_modules/mquery/lib/permissions.js | 88 + node_modules/mquery/lib/utils.js | 359 + .../mquery/node_modules/debug/LICENSE | 19 + .../mquery/node_modules/debug/README.md | 455 + .../mquery/node_modules/debug/package.json | 59 + .../mquery/node_modules/debug/src/browser.js | 269 + .../mquery/node_modules/debug/src/common.js | 274 + .../mquery/node_modules/debug/src/index.js | 10 + .../mquery/node_modules/debug/src/node.js | 263 + node_modules/mquery/node_modules/ms/index.js | 162 + .../mquery/node_modules/ms/license.md | 21 + .../mquery/node_modules/ms/package.json | 37 + node_modules/mquery/node_modules/ms/readme.md | 60 + node_modules/mquery/package.json | 40 + node_modules/mquery/test/.eslintrc.yml | 2 + .../mquery/test/collection/browser.js | 0 node_modules/mquery/test/collection/mongo.js | 0 node_modules/mquery/test/collection/node.js | 29 + node_modules/mquery/test/env.js | 22 + node_modules/mquery/test/index.js | 2956 ++++++ node_modules/mquery/test/utils.test.js | 161 + node_modules/ms/index.js | 152 + node_modules/ms/license.md | 21 + node_modules/ms/package.json | 37 + node_modules/ms/readme.md | 51 + node_modules/negotiator/HISTORY.md | 103 + node_modules/negotiator/LICENSE | 24 + node_modules/negotiator/README.md | 203 + node_modules/negotiator/index.js | 124 + node_modules/negotiator/lib/charset.js | 169 + node_modules/negotiator/lib/encoding.js | 184 + node_modules/negotiator/lib/language.js | 179 + node_modules/negotiator/lib/mediaType.js | 294 + node_modules/negotiator/package.json | 42 + node_modules/node-addon-api/CHANGELOG.md | 722 ++ node_modules/node-addon-api/LICENSE.md | 13 + node_modules/node-addon-api/README.md | 293 + node_modules/node-addon-api/common.gypi | 21 + node_modules/node-addon-api/except.gypi | 16 + node_modules/node-addon-api/index.js | 11 + .../node-addon-api/napi-inl.deprecated.h | 192 + node_modules/node-addon-api/napi-inl.h | 5671 +++++++++++ node_modules/node-addon-api/napi.h | 2727 ++++++ node_modules/node-addon-api/node_api.gyp | 9 + node_modules/node-addon-api/noexcept.gypi | 16 + node_modules/node-addon-api/nothing.c | 0 .../node-addon-api/package-support.json | 21 + node_modules/node-addon-api/package.json | 368 + node_modules/node-addon-api/tools/README.md | 73 + .../node-addon-api/tools/check-napi.js | 100 + .../node-addon-api/tools/clang-format.js | 67 + .../node-addon-api/tools/conversion.js | 309 + node_modules/node-fetch/LICENSE.md | 22 + node_modules/node-fetch/README.md | 590 ++ node_modules/node-fetch/browser.js | 25 + node_modules/node-fetch/lib/index.es.js | 1662 ++++ node_modules/node-fetch/lib/index.js | 1671 ++++ node_modules/node-fetch/lib/index.mjs | 1660 ++++ .../node-fetch/node_modules/tr46/.npmignore | 4 + .../node-fetch/node_modules/tr46/index.js | 193 + .../node-fetch/node_modules/tr46/lib/.gitkeep | 0 .../node_modules/tr46/lib/mappingTable.json | 1 + .../node-fetch/node_modules/tr46/package.json | 31 + .../webidl-conversions/LICENSE.md | 12 + .../node_modules/webidl-conversions/README.md | 53 + .../webidl-conversions/lib/index.js | 189 + .../webidl-conversions/package.json | 23 + .../node_modules/whatwg-url/LICENSE.txt | 21 + .../node_modules/whatwg-url/README.md | 67 + .../node_modules/whatwg-url/lib/URL-impl.js | 200 + .../node_modules/whatwg-url/lib/URL.js | 196 + .../node_modules/whatwg-url/lib/public-api.js | 11 + .../whatwg-url/lib/url-state-machine.js | 1297 +++ .../node_modules/whatwg-url/lib/utils.js | 20 + .../node_modules/whatwg-url/package.json | 32 + node_modules/node-fetch/package.json | 68 + node_modules/nopt/CHANGELOG.md | 58 + node_modules/nopt/LICENSE | 15 + node_modules/nopt/README.md | 213 + node_modules/nopt/bin/nopt.js | 54 + node_modules/nopt/lib/nopt.js | 441 + node_modules/nopt/package.json | 34 + node_modules/npmlog/LICENSE | 15 + node_modules/npmlog/README.md | 216 + node_modules/npmlog/log.js | 403 + node_modules/npmlog/package.json | 33 + node_modules/object-assign/index.js | 90 + node_modules/object-assign/license | 21 + node_modules/object-assign/package.json | 42 + node_modules/object-assign/readme.md | 61 + node_modules/on-finished/HISTORY.md | 88 + node_modules/on-finished/LICENSE | 23 + node_modules/on-finished/README.md | 154 + node_modules/on-finished/index.js | 196 + node_modules/on-finished/package.json | 31 + node_modules/once/LICENSE | 15 + node_modules/once/README.md | 79 + node_modules/once/once.js | 42 + node_modules/once/package.json | 33 + node_modules/parseurl/HISTORY.md | 58 + node_modules/parseurl/LICENSE | 24 + node_modules/parseurl/README.md | 133 + node_modules/parseurl/index.js | 158 + node_modules/parseurl/package.json | 40 + node_modules/passport-jwt/.travis.yml | 12 + node_modules/passport-jwt/LICENSE | 22 + node_modules/passport-jwt/README.md | 176 + node_modules/passport-jwt/docs/migrating.md | 70 + node_modules/passport-jwt/lib/auth_header.js | 19 + node_modules/passport-jwt/lib/extract_jwt.js | 134 + .../passport-jwt/lib/helpers/assign.js | 24 + node_modules/passport-jwt/lib/index.js | 10 + node_modules/passport-jwt/lib/strategy.js | 139 + node_modules/passport-jwt/lib/verify_jwt.js | 5 + node_modules/passport-jwt/package.json | 39 + .../passport-jwt/test/auth_header-test.js | 28 + node_modules/passport-jwt/test/bootstrap.js | 3 + .../passport-jwt/test/extrators-test.js | 287 + .../passport-jwt/test/mock_request.js | 10 + .../passport-jwt/test/strategy-init-test.js | 41 + .../test/strategy-requests-test.js | 124 + .../test/strategy-validation-test.js | 182 + .../passport-jwt/test/strategy-verify-test.js | 245 + node_modules/passport-jwt/test/testdata.js | 14 + node_modules/passport-strategy/.jshintrc | 20 + node_modules/passport-strategy/.travis.yml | 15 + node_modules/passport-strategy/LICENSE | 20 + node_modules/passport-strategy/README.md | 61 + node_modules/passport-strategy/lib/index.js | 15 + .../passport-strategy/lib/strategy.js | 28 + node_modules/passport-strategy/package.json | 50 + node_modules/passport/CHANGELOG.md | 48 + node_modules/passport/LICENSE | 20 + node_modules/passport/README.md | 174 + node_modules/passport/lib/authenticator.js | 468 + .../lib/errors/authenticationerror.js | 20 + .../passport/lib/framework/connect.js | 22 + node_modules/passport/lib/http/request.js | 82 + node_modules/passport/lib/index.js | 26 + .../passport/lib/middleware/authenticate.js | 372 + .../passport/lib/middleware/initialize.js | 91 + node_modules/passport/lib/sessionmanager.js | 39 + .../passport/lib/strategies/session.js | 83 + node_modules/passport/package.json | 55 + .../passport/sponsors/loginradius.png | Bin 0 -> 10888 bytes node_modules/passport/sponsors/workos.png | Bin 0 -> 6854 bytes node_modules/path-is-absolute/index.js | 20 + node_modules/path-is-absolute/license | 21 + node_modules/path-is-absolute/package.json | 43 + node_modules/path-is-absolute/readme.md | 59 + node_modules/path-to-regexp/History.md | 36 + node_modules/path-to-regexp/LICENSE | 21 + node_modules/path-to-regexp/Readme.md | 35 + node_modules/path-to-regexp/index.js | 129 + node_modules/path-to-regexp/package.json | 30 + node_modules/pause/.npmignore | 4 + node_modules/pause/History.md | 5 + node_modules/pause/Makefile | 7 + node_modules/pause/Readme.md | 29 + node_modules/pause/index.js | 29 + node_modules/pause/package.json | 13 + node_modules/proxy-addr/HISTORY.md | 161 + node_modules/proxy-addr/LICENSE | 22 + node_modules/proxy-addr/README.md | 139 + node_modules/proxy-addr/index.js | 327 + node_modules/proxy-addr/package.json | 47 + node_modules/punycode/LICENSE-MIT.txt | 20 + node_modules/punycode/README.md | 122 + node_modules/punycode/package.json | 58 + node_modules/punycode/punycode.es6.js | 441 + node_modules/punycode/punycode.js | 440 + node_modules/qs/.editorconfig | 30 + node_modules/qs/.eslintignore | 1 + node_modules/qs/.eslintrc | 21 + node_modules/qs/CHANGELOG.md | 256 + node_modules/qs/LICENSE | 28 + node_modules/qs/README.md | 570 ++ node_modules/qs/dist/qs.js | 782 ++ node_modules/qs/lib/formats.js | 18 + node_modules/qs/lib/index.js | 11 + node_modules/qs/lib/parse.js | 242 + node_modules/qs/lib/stringify.js | 269 + node_modules/qs/lib/utils.js | 230 + node_modules/qs/package.json | 58 + node_modules/qs/test/.eslintrc | 17 + node_modules/qs/test/index.js | 7 + node_modules/qs/test/parse.js | 676 ++ node_modules/qs/test/stringify.js | 679 ++ node_modules/qs/test/utils.js | 136 + node_modules/range-parser/HISTORY.md | 56 + node_modules/range-parser/LICENSE | 23 + node_modules/range-parser/README.md | 84 + node_modules/range-parser/index.js | 162 + node_modules/range-parser/package.json | 44 + node_modules/raw-body/HISTORY.md | 270 + node_modules/raw-body/LICENSE | 22 + node_modules/raw-body/README.md | 219 + node_modules/raw-body/index.d.ts | 87 + node_modules/raw-body/index.js | 286 + node_modules/raw-body/package.json | 48 + node_modules/readable-stream/CONTRIBUTING.md | 38 + node_modules/readable-stream/GOVERNANCE.md | 136 + node_modules/readable-stream/LICENSE | 47 + node_modules/readable-stream/README.md | 106 + .../readable-stream/errors-browser.js | 127 + node_modules/readable-stream/errors.js | 116 + .../readable-stream/experimentalWarning.js | 17 + .../readable-stream/lib/_stream_duplex.js | 139 + .../lib/_stream_passthrough.js | 39 + .../readable-stream/lib/_stream_readable.js | 1124 +++ .../readable-stream/lib/_stream_transform.js | 201 + .../readable-stream/lib/_stream_writable.js | 697 ++ .../lib/internal/streams/async_iterator.js | 207 + .../lib/internal/streams/buffer_list.js | 210 + .../lib/internal/streams/destroy.js | 105 + .../lib/internal/streams/end-of-stream.js | 104 + .../lib/internal/streams/from-browser.js | 3 + .../lib/internal/streams/from.js | 64 + .../lib/internal/streams/pipeline.js | 97 + .../lib/internal/streams/state.js | 27 + .../lib/internal/streams/stream-browser.js | 1 + .../lib/internal/streams/stream.js | 1 + node_modules/readable-stream/package.json | 68 + .../readable-stream/readable-browser.js | 9 + node_modules/readable-stream/readable.js | 16 + node_modules/regexp-clone/.travis.yml | 14 + node_modules/regexp-clone/History.md | 5 + node_modules/regexp-clone/LICENSE | 22 + node_modules/regexp-clone/Makefile | 5 + node_modules/regexp-clone/README.md | 42 + node_modules/regexp-clone/index.js | 27 + node_modules/regexp-clone/package.json | 22 + node_modules/regexp-clone/test/index.js | 171 + node_modules/rimraf/CHANGELOG.md | 65 + node_modules/rimraf/LICENSE | 15 + node_modules/rimraf/README.md | 101 + node_modules/rimraf/bin.js | 68 + node_modules/rimraf/package.json | 32 + node_modules/rimraf/rimraf.js | 360 + node_modules/safe-buffer/LICENSE | 21 + node_modules/safe-buffer/README.md | 584 ++ node_modules/safe-buffer/index.d.ts | 187 + node_modules/safe-buffer/index.js | 62 + node_modules/safe-buffer/package.json | 37 + node_modules/safer-buffer/LICENSE | 21 + node_modules/safer-buffer/Porting-Buffer.md | 268 + node_modules/safer-buffer/Readme.md | 156 + node_modules/safer-buffer/dangerous.js | 58 + node_modules/safer-buffer/package.json | 34 + node_modules/safer-buffer/safer.js | 77 + node_modules/safer-buffer/tests.js | 406 + node_modules/saslprep/.editorconfig | 10 + node_modules/saslprep/.gitattributes | 1 + node_modules/saslprep/.travis.yml | 10 + node_modules/saslprep/CHANGELOG.md | 19 + node_modules/saslprep/LICENSE | 22 + node_modules/saslprep/code-points.mem | Bin 0 -> 419864 bytes node_modules/saslprep/generate-code-points.js | 51 + node_modules/saslprep/index.js | 157 + node_modules/saslprep/lib/code-points.js | 996 ++ .../saslprep/lib/memory-code-points.js | 39 + node_modules/saslprep/lib/util.js | 21 + node_modules/saslprep/package.json | 72 + node_modules/saslprep/readme.md | 31 + node_modules/saslprep/test/index.js | 76 + node_modules/saslprep/test/util.js | 16 + node_modules/semver/CHANGELOG.md | 111 + node_modules/semver/LICENSE | 15 + node_modules/semver/README.md | 566 ++ node_modules/semver/bin/semver.js | 173 + node_modules/semver/classes/comparator.js | 135 + node_modules/semver/classes/index.js | 5 + node_modules/semver/classes/range.js | 510 + node_modules/semver/classes/semver.js | 287 + node_modules/semver/functions/clean.js | 6 + node_modules/semver/functions/cmp.js | 48 + node_modules/semver/functions/coerce.js | 51 + .../semver/functions/compare-build.js | 7 + .../semver/functions/compare-loose.js | 3 + node_modules/semver/functions/compare.js | 5 + node_modules/semver/functions/diff.js | 23 + node_modules/semver/functions/eq.js | 3 + node_modules/semver/functions/gt.js | 3 + node_modules/semver/functions/gte.js | 3 + node_modules/semver/functions/inc.js | 15 + node_modules/semver/functions/lt.js | 3 + node_modules/semver/functions/lte.js | 3 + node_modules/semver/functions/major.js | 3 + node_modules/semver/functions/minor.js | 3 + node_modules/semver/functions/neq.js | 3 + node_modules/semver/functions/parse.js | 33 + node_modules/semver/functions/patch.js | 3 + node_modules/semver/functions/prerelease.js | 6 + node_modules/semver/functions/rcompare.js | 3 + node_modules/semver/functions/rsort.js | 3 + node_modules/semver/functions/satisfies.js | 10 + node_modules/semver/functions/sort.js | 3 + node_modules/semver/functions/valid.js | 6 + node_modules/semver/index.js | 48 + node_modules/semver/internal/constants.js | 17 + node_modules/semver/internal/debug.js | 9 + node_modules/semver/internal/identifiers.js | 23 + node_modules/semver/internal/parse-options.js | 11 + node_modules/semver/internal/re.js | 182 + node_modules/semver/package.json | 41 + node_modules/semver/preload.js | 2 + node_modules/semver/range.bnf | 16 + node_modules/semver/ranges/gtr.js | 4 + node_modules/semver/ranges/intersects.js | 7 + node_modules/semver/ranges/ltr.js | 4 + node_modules/semver/ranges/max-satisfying.js | 25 + node_modules/semver/ranges/min-satisfying.js | 24 + node_modules/semver/ranges/min-version.js | 60 + node_modules/semver/ranges/outside.js | 80 + node_modules/semver/ranges/simplify.js | 44 + node_modules/semver/ranges/subset.js | 222 + node_modules/semver/ranges/to-comparators.js | 8 + node_modules/semver/ranges/valid.js | 11 + node_modules/send/HISTORY.md | 496 + node_modules/send/LICENSE | 23 + node_modules/send/README.md | 329 + node_modules/send/index.js | 1129 +++ node_modules/send/node_modules/ms/index.js | 162 + node_modules/send/node_modules/ms/license.md | 21 + .../send/node_modules/ms/package.json | 37 + node_modules/send/node_modules/ms/readme.md | 60 + node_modules/send/package.json | 61 + node_modules/serve-static/HISTORY.md | 451 + node_modules/serve-static/LICENSE | 25 + node_modules/serve-static/README.md | 259 + node_modules/serve-static/index.js | 210 + node_modules/serve-static/package.json | 42 + node_modules/set-blocking/CHANGELOG.md | 26 + node_modules/set-blocking/LICENSE.txt | 14 + node_modules/set-blocking/README.md | 31 + node_modules/set-blocking/index.js | 7 + node_modules/set-blocking/package.json | 42 + node_modules/setprototypeof/LICENSE | 13 + node_modules/setprototypeof/README.md | 31 + node_modules/setprototypeof/index.d.ts | 2 + node_modules/setprototypeof/index.js | 17 + node_modules/setprototypeof/package.json | 36 + node_modules/setprototypeof/test/index.js | 24 + node_modules/sift/MIT-LICENSE.txt | 20 + node_modules/sift/README.md | 465 + node_modules/sift/changelog.md | 77 + node_modules/sift/es/index.js | 528 + node_modules/sift/es/index.js.map | 1 + node_modules/sift/es5m/index.js | 652 ++ node_modules/sift/es5m/index.js.map | 1 + node_modules/sift/index.d.ts | 4 + node_modules/sift/index.js | 4 + node_modules/sift/lib/core.d.ts | 115 + node_modules/sift/lib/index.d.ts | 6 + node_modules/sift/lib/index.js | 689 ++ node_modules/sift/lib/index.js.map | 1 + node_modules/sift/lib/operations.d.ts | 70 + node_modules/sift/lib/utils.d.ts | 9 + node_modules/sift/package.json | 61 + node_modules/sift/sift.csp.min.js | 686 ++ node_modules/sift/sift.csp.min.js.map | 1 + node_modules/sift/sift.min.js | 16 + node_modules/sift/sift.min.js.map | 1 + node_modules/signal-exit/LICENSE.txt | 16 + node_modules/signal-exit/README.md | 39 + node_modules/signal-exit/index.js | 200 + node_modules/signal-exit/package.json | 38 + node_modules/signal-exit/signals.js | 53 + node_modules/sliced/History.md | 41 + node_modules/sliced/LICENSE | 22 + node_modules/sliced/README.md | 62 + node_modules/sliced/index.js | 33 + node_modules/sliced/package.json | 30 + node_modules/sparse-bitfield/.npmignore | 1 + node_modules/sparse-bitfield/.travis.yml | 6 + node_modules/sparse-bitfield/LICENSE | 21 + node_modules/sparse-bitfield/README.md | 62 + node_modules/sparse-bitfield/index.js | 95 + node_modules/sparse-bitfield/package.json | 27 + node_modules/sparse-bitfield/test.js | 79 + node_modules/statuses/HISTORY.md | 65 + node_modules/statuses/LICENSE | 23 + node_modules/statuses/README.md | 127 + node_modules/statuses/codes.json | 66 + node_modules/statuses/index.js | 113 + node_modules/statuses/package.json | 48 + node_modules/string-width/index.d.ts | 29 + node_modules/string-width/index.js | 47 + node_modules/string-width/license | 9 + node_modules/string-width/package.json | 56 + node_modules/string-width/readme.md | 50 + node_modules/string_decoder/LICENSE | 48 + node_modules/string_decoder/README.md | 47 + .../string_decoder/lib/string_decoder.js | 296 + .../node_modules/safe-buffer/LICENSE | 21 + .../node_modules/safe-buffer/README.md | 584 ++ .../node_modules/safe-buffer/index.d.ts | 187 + .../node_modules/safe-buffer/index.js | 65 + .../node_modules/safe-buffer/package.json | 51 + node_modules/string_decoder/package.json | 34 + node_modules/strip-ansi/index.d.ts | 17 + node_modules/strip-ansi/index.js | 4 + node_modules/strip-ansi/license | 9 + node_modules/strip-ansi/package.json | 54 + node_modules/strip-ansi/readme.md | 46 + node_modules/tar/LICENSE | 15 + node_modules/tar/README.md | 1042 ++ node_modules/tar/index.js | 18 + node_modules/tar/lib/create.js | 104 + node_modules/tar/lib/extract.js | 107 + node_modules/tar/lib/get-write-flag.js | 20 + node_modules/tar/lib/header.js | 288 + node_modules/tar/lib/high-level-opt.js | 29 + node_modules/tar/lib/large-numbers.js | 99 + node_modules/tar/lib/list.js | 132 + node_modules/tar/lib/mkdir.js | 213 + node_modules/tar/lib/mode-fix.js | 23 + node_modules/tar/lib/normalize-unicode.js | 11 + .../tar/lib/normalize-windows-path.js | 8 + node_modules/tar/lib/pack.js | 397 + node_modules/tar/lib/parse.js | 481 + node_modules/tar/lib/path-reservations.js | 148 + node_modules/tar/lib/pax.js | 143 + node_modules/tar/lib/read-entry.js | 100 + node_modules/tar/lib/replace.js | 223 + node_modules/tar/lib/strip-absolute-path.js | 24 + .../tar/lib/strip-trailing-slashes.js | 13 + node_modules/tar/lib/types.js | 44 + node_modules/tar/lib/unpack.js | 877 ++ node_modules/tar/lib/update.js | 36 + node_modules/tar/lib/warn-mixin.js | 21 + node_modules/tar/lib/winchars.js | 23 + node_modules/tar/lib/write-entry.js | 525 + node_modules/tar/package.json | 59 + node_modules/toidentifier/LICENSE | 21 + node_modules/toidentifier/README.md | 61 + node_modules/toidentifier/index.js | 30 + node_modules/toidentifier/package.json | 34 + node_modules/tr46/LICENSE.md | 21 + node_modules/tr46/README.md | 72 + node_modules/tr46/index.js | 297 + node_modules/tr46/lib/mappingTable.json | 1 + node_modules/tr46/lib/regexes.js | 29 + node_modules/tr46/lib/statusMapping.js | 11 + node_modules/tr46/package.json | 46 + node_modules/type-is/HISTORY.md | 259 + node_modules/type-is/LICENSE | 23 + node_modules/type-is/README.md | 170 + node_modules/type-is/index.js | 266 + node_modules/type-is/package.json | 45 + node_modules/unpipe/HISTORY.md | 4 + node_modules/unpipe/LICENSE | 22 + node_modules/unpipe/README.md | 43 + node_modules/unpipe/index.js | 69 + node_modules/unpipe/package.json | 27 + node_modules/util-deprecate/History.md | 16 + node_modules/util-deprecate/LICENSE | 24 + node_modules/util-deprecate/README.md | 53 + node_modules/util-deprecate/browser.js | 67 + node_modules/util-deprecate/node.js | 6 + node_modules/util-deprecate/package.json | 27 + node_modules/utils-merge/.npmignore | 9 + node_modules/utils-merge/LICENSE | 20 + node_modules/utils-merge/README.md | 34 + node_modules/utils-merge/index.js | 23 + node_modules/utils-merge/package.json | 40 + node_modules/validator/LICENSE | 20 + node_modules/validator/README.md | 274 + node_modules/validator/es/index.js | 198 + node_modules/validator/es/lib/alpha.js | 123 + node_modules/validator/es/lib/blacklist.js | 5 + node_modules/validator/es/lib/contains.js | 17 + node_modules/validator/es/lib/equals.js | 5 + node_modules/validator/es/lib/escape.js | 5 + node_modules/validator/es/lib/isAfter.js | 9 + node_modules/validator/es/lib/isAlpha.js | 26 + .../validator/es/lib/isAlphanumeric.js | 26 + node_modules/validator/es/lib/isAscii.js | 10 + node_modules/validator/es/lib/isBIC.js | 14 + node_modules/validator/es/lib/isBase32.js | 12 + node_modules/validator/es/lib/isBase58.js | 12 + node_modules/validator/es/lib/isBase64.js | 23 + node_modules/validator/es/lib/isBefore.js | 9 + node_modules/validator/es/lib/isBoolean.js | 16 + node_modules/validator/es/lib/isBtcAddress.js | 13 + node_modules/validator/es/lib/isByteLength.js | 22 + node_modules/validator/es/lib/isCreditCard.js | 40 + node_modules/validator/es/lib/isCurrency.js | 77 + node_modules/validator/es/lib/isDataURI.js | 39 + node_modules/validator/es/lib/isDate.js | 86 + node_modules/validator/es/lib/isDecimal.js | 26 + .../validator/es/lib/isDivisibleBy.js | 6 + node_modules/validator/es/lib/isEAN.js | 72 + node_modules/validator/es/lib/isEmail.js | 180 + node_modules/validator/es/lib/isEmpty.js | 10 + .../validator/es/lib/isEthereumAddress.js | 6 + node_modules/validator/es/lib/isFQDN.js | 74 + node_modules/validator/es/lib/isFloat.js | 16 + node_modules/validator/es/lib/isFullWidth.js | 6 + node_modules/validator/es/lib/isHSL.js | 14 + node_modules/validator/es/lib/isHalfWidth.js | 6 + node_modules/validator/es/lib/isHash.js | 21 + node_modules/validator/es/lib/isHexColor.js | 6 + .../validator/es/lib/isHexadecimal.js | 6 + node_modules/validator/es/lib/isIBAN.js | 138 + node_modules/validator/es/lib/isIMEI.js | 47 + node_modules/validator/es/lib/isIP.js | 62 + node_modules/validator/es/lib/isIPRange.js | 47 + node_modules/validator/es/lib/isISBN.js | 51 + node_modules/validator/es/lib/isISIN.js | 60 + .../validator/es/lib/isISO31661Alpha2.js | 8 + .../validator/es/lib/isISO31661Alpha3.js | 7 + node_modules/validator/es/lib/isISO4217.js | 8 + node_modules/validator/es/lib/isISO8601.js | 47 + node_modules/validator/es/lib/isISRC.js | 7 + node_modules/validator/es/lib/isISSN.js | 23 + .../validator/es/lib/isIdentityCard.js | 369 + node_modules/validator/es/lib/isIn.js | 28 + node_modules/validator/es/lib/isInt.js | 16 + node_modules/validator/es/lib/isJSON.js | 26 + node_modules/validator/es/lib/isJWT.js | 17 + node_modules/validator/es/lib/isLatLong.js | 22 + node_modules/validator/es/lib/isLength.js | 23 + .../validator/es/lib/isLicensePlate.js | 44 + node_modules/validator/es/lib/isLocale.js | 11 + node_modules/validator/es/lib/isLowercase.js | 5 + node_modules/validator/es/lib/isMACAddress.js | 16 + node_modules/validator/es/lib/isMD5.js | 6 + node_modules/validator/es/lib/isMagnetURI.js | 6 + node_modules/validator/es/lib/isMimeType.js | 39 + .../validator/es/lib/isMobilePhone.js | 187 + node_modules/validator/es/lib/isMongoId.js | 6 + node_modules/validator/es/lib/isMultibyte.js | 10 + node_modules/validator/es/lib/isNumeric.js | 12 + node_modules/validator/es/lib/isOctal.js | 6 + .../validator/es/lib/isPassportNumber.js | 126 + node_modules/validator/es/lib/isPort.js | 7 + node_modules/validator/es/lib/isPostalCode.js | 96 + node_modules/validator/es/lib/isRFC3339.js | 20 + node_modules/validator/es/lib/isRgbColor.js | 15 + node_modules/validator/es/lib/isSemVer.js | 14 + node_modules/validator/es/lib/isSlug.js | 6 + .../validator/es/lib/isStrongPassword.js | 101 + .../validator/es/lib/isSurrogatePair.js | 6 + node_modules/validator/es/lib/isTaxID.js | 1508 +++ node_modules/validator/es/lib/isURL.js | 193 + node_modules/validator/es/lib/isUUID.js | 14 + node_modules/validator/es/lib/isUppercase.js | 5 + node_modules/validator/es/lib/isVAT.js | 16 + .../validator/es/lib/isVariableWidth.js | 7 + .../validator/es/lib/isWhitelisted.js | 12 + node_modules/validator/es/lib/ltrim.js | 7 + node_modules/validator/es/lib/matches.js | 10 + .../validator/es/lib/normalizeEmail.js | 138 + node_modules/validator/es/lib/rtrim.js | 19 + node_modules/validator/es/lib/stripLow.js | 7 + node_modules/validator/es/lib/toBoolean.js | 10 + node_modules/validator/es/lib/toDate.js | 6 + node_modules/validator/es/lib/toFloat.js | 5 + node_modules/validator/es/lib/toInt.js | 5 + node_modules/validator/es/lib/trim.js | 5 + node_modules/validator/es/lib/unescape.js | 7 + .../validator/es/lib/util/algorithms.js | 88 + .../validator/es/lib/util/assertString.js | 12 + .../validator/es/lib/util/includes.js | 7 + node_modules/validator/es/lib/util/merge.js | 12 + .../validator/es/lib/util/multilineRegex.js | 12 + .../validator/es/lib/util/toString.js | 15 + node_modules/validator/es/lib/util/typeOf.js | 10 + node_modules/validator/es/lib/whitelist.js | 5 + node_modules/validator/index.js | 309 + node_modules/validator/lib/alpha.js | 137 + node_modules/validator/lib/blacklist.js | 18 + node_modules/validator/lib/contains.js | 33 + node_modules/validator/lib/equals.js | 18 + node_modules/validator/lib/escape.js | 18 + node_modules/validator/lib/isAfter.js | 23 + node_modules/validator/lib/isAlpha.js | 40 + node_modules/validator/lib/isAlphanumeric.js | 40 + node_modules/validator/lib/isAscii.js | 22 + node_modules/validator/lib/isBIC.js | 29 + node_modules/validator/lib/isBase32.js | 26 + node_modules/validator/lib/isBase58.js | 26 + node_modules/validator/lib/isBase64.js | 38 + node_modules/validator/lib/isBefore.js | 23 + node_modules/validator/lib/isBoolean.js | 30 + node_modules/validator/lib/isBtcAddress.js | 27 + node_modules/validator/lib/isByteLength.js | 34 + node_modules/validator/lib/isCreditCard.js | 52 + node_modules/validator/lib/isCurrency.js | 91 + node_modules/validator/lib/isDataURI.js | 53 + node_modules/validator/lib/isDate.js | 99 + node_modules/validator/lib/isDecimal.js | 42 + node_modules/validator/lib/isDivisibleBy.js | 20 + node_modules/validator/lib/isEAN.js | 85 + node_modules/validator/lib/isEmail.js | 197 + node_modules/validator/lib/isEmpty.js | 25 + .../validator/lib/isEthereumAddress.js | 20 + node_modules/validator/lib/isFQDN.js | 89 + node_modules/validator/lib/isFloat.js | 29 + node_modules/validator/lib/isFullWidth.js | 19 + node_modules/validator/lib/isHSL.js | 28 + node_modules/validator/lib/isHalfWidth.js | 19 + node_modules/validator/lib/isHash.js | 35 + node_modules/validator/lib/isHexColor.js | 20 + node_modules/validator/lib/isHexadecimal.js | 20 + node_modules/validator/lib/isIBAN.js | 150 + node_modules/validator/lib/isIMEI.js | 61 + node_modules/validator/lib/isIP.js | 75 + node_modules/validator/lib/isIPRange.js | 62 + node_modules/validator/lib/isISBN.js | 65 + node_modules/validator/lib/isISIN.js | 73 + .../validator/lib/isISO31661Alpha2.js | 22 + .../validator/lib/isISO31661Alpha3.js | 21 + node_modules/validator/lib/isISO4217.js | 22 + node_modules/validator/lib/isISO8601.js | 59 + node_modules/validator/lib/isISRC.js | 21 + node_modules/validator/lib/isISSN.js | 37 + node_modules/validator/lib/isIdentityCard.js | 384 + node_modules/validator/lib/isIn.js | 42 + node_modules/validator/lib/isInt.js | 30 + node_modules/validator/lib/isJSON.js | 41 + node_modules/validator/lib/isJWT.js | 31 + node_modules/validator/lib/isLatLong.js | 37 + node_modules/validator/lib/isLength.js | 35 + node_modules/validator/lib/isLicensePlate.js | 58 + node_modules/validator/lib/isLocale.js | 25 + node_modules/validator/lib/isLowercase.js | 18 + node_modules/validator/lib/isMACAddress.js | 30 + node_modules/validator/lib/isMD5.js | 20 + node_modules/validator/lib/isMagnetURI.js | 20 + node_modules/validator/lib/isMimeType.js | 51 + node_modules/validator/lib/isMobilePhone.js | 200 + node_modules/validator/lib/isMongoId.js | 20 + node_modules/validator/lib/isMultibyte.js | 22 + node_modules/validator/lib/isNumeric.js | 27 + node_modules/validator/lib/isOctal.js | 20 + .../validator/lib/isPassportNumber.js | 138 + node_modules/validator/lib/isPort.js | 20 + node_modules/validator/lib/isPostalCode.js | 109 + node_modules/validator/lib/isRFC3339.js | 33 + node_modules/validator/lib/isRgbColor.js | 29 + node_modules/validator/lib/isSemVer.js | 28 + node_modules/validator/lib/isSlug.js | 20 + .../validator/lib/isStrongPassword.js | 115 + node_modules/validator/lib/isSurrogatePair.js | 20 + node_modules/validator/lib/isTaxID.js | 1528 +++ node_modules/validator/lib/isURL.js | 208 + node_modules/validator/lib/isUUID.js | 28 + node_modules/validator/lib/isUppercase.js | 18 + node_modules/validator/lib/isVAT.js | 29 + node_modules/validator/lib/isVariableWidth.js | 22 + node_modules/validator/lib/isWhitelisted.js | 25 + node_modules/validator/lib/ltrim.js | 20 + node_modules/validator/lib/matches.js | 23 + node_modules/validator/lib/normalizeEmail.js | 151 + node_modules/validator/lib/rtrim.js | 32 + node_modules/validator/lib/stripLow.js | 21 + node_modules/validator/lib/toBoolean.js | 23 + node_modules/validator/lib/toDate.js | 19 + node_modules/validator/lib/toFloat.js | 18 + node_modules/validator/lib/toInt.js | 18 + node_modules/validator/lib/trim.js | 19 + node_modules/validator/lib/unescape.js | 20 + node_modules/validator/lib/util/algorithms.js | 101 + .../validator/lib/util/assertString.js | 22 + node_modules/validator/lib/util/includes.js | 17 + node_modules/validator/lib/util/merge.js | 22 + .../validator/lib/util/multilineRegex.js | 22 + node_modules/validator/lib/util/toString.js | 25 + node_modules/validator/lib/util/typeOf.js | 20 + node_modules/validator/lib/whitelist.js | 18 + node_modules/validator/package.json | 75 + node_modules/validator/validator.js | 5094 ++++++++++ node_modules/validator/validator.min.js | 23 + node_modules/vary/HISTORY.md | 39 + node_modules/vary/LICENSE | 22 + node_modules/vary/README.md | 101 + node_modules/vary/index.js | 149 + node_modules/vary/package.json | 43 + node_modules/webidl-conversions/LICENSE.md | 12 + node_modules/webidl-conversions/README.md | 101 + node_modules/webidl-conversions/lib/index.js | 489 + node_modules/webidl-conversions/package.json | 30 + node_modules/whatwg-url/LICENSE.txt | 21 + node_modules/whatwg-url/README.md | 105 + node_modules/whatwg-url/dist/Function.js | 46 + node_modules/whatwg-url/dist/URL-impl.js | 217 + node_modules/whatwg-url/dist/URL.js | 417 + .../whatwg-url/dist/URLSearchParams-impl.js | 130 + .../whatwg-url/dist/URLSearchParams.js | 457 + node_modules/whatwg-url/dist/VoidFunction.js | 30 + node_modules/whatwg-url/dist/encoding.js | 16 + node_modules/whatwg-url/dist/infra.js | 26 + .../whatwg-url/dist/percent-encoding.js | 138 + .../whatwg-url/dist/url-state-machine.js | 1230 +++ node_modules/whatwg-url/dist/urlencoded.js | 102 + node_modules/whatwg-url/dist/utils.js | 141 + node_modules/whatwg-url/index.js | 25 + node_modules/whatwg-url/package.json | 59 + node_modules/whatwg-url/webidl2js-wrapper.js | 7 + node_modules/wide-align/LICENSE | 14 + node_modules/wide-align/README.md | 47 + node_modules/wide-align/align.js | 65 + node_modules/wide-align/package.json | 33 + node_modules/wrappy/LICENSE | 15 + node_modules/wrappy/README.md | 36 + node_modules/wrappy/package.json | 29 + node_modules/wrappy/wrappy.js | 33 + node_modules/yallist/LICENSE | 15 + node_modules/yallist/README.md | 204 + node_modules/yallist/iterator.js | 8 + node_modules/yallist/package.json | 29 + node_modules/yallist/yallist.js | 426 + package-lock.json | 1528 ++- routes/v1/index.js | 4 +- routes/v1/model.route.js | 61 +- 2115 files changed, 378405 insertions(+), 49 deletions(-) create mode 100644 node_modules/.bin/color-support create mode 100644 node_modules/.bin/color-support.cmd create mode 100644 node_modules/.bin/color-support.ps1 create mode 100644 node_modules/.bin/detect-libc create mode 100644 node_modules/.bin/detect-libc.cmd create mode 100644 node_modules/.bin/detect-libc.ps1 create mode 100644 node_modules/.bin/mime create mode 100644 node_modules/.bin/mime.cmd create mode 100644 node_modules/.bin/mime.ps1 create mode 100644 node_modules/.bin/mkdirp create mode 100644 node_modules/.bin/mkdirp.cmd create mode 100644 node_modules/.bin/mkdirp.ps1 create mode 100644 node_modules/.bin/node-pre-gyp create mode 100644 node_modules/.bin/node-pre-gyp.cmd create mode 100644 node_modules/.bin/node-pre-gyp.ps1 create mode 100644 node_modules/.bin/nopt create mode 100644 node_modules/.bin/nopt.cmd create mode 100644 node_modules/.bin/nopt.ps1 create mode 100644 node_modules/.bin/rimraf create mode 100644 node_modules/.bin/rimraf.cmd create mode 100644 node_modules/.bin/rimraf.ps1 create mode 100644 node_modules/.bin/semver create mode 100644 node_modules/.bin/semver.cmd create mode 100644 node_modules/.bin/semver.ps1 create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/@mapbox/node-pre-gyp/CHANGELOG.md create mode 100644 node_modules/@mapbox/node-pre-gyp/LICENSE create mode 100644 node_modules/@mapbox/node-pre-gyp/README.md create mode 100644 node_modules/@mapbox/node-pre-gyp/bin/node-pre-gyp create mode 100644 node_modules/@mapbox/node-pre-gyp/bin/node-pre-gyp.cmd create mode 100644 node_modules/@mapbox/node-pre-gyp/contributing.md create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/build.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/clean.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/configure.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/info.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/install.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/main.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/package.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/pre-binding.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/publish.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/rebuild.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/reinstall.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/reveal.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/testbinary.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/testpackage.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/unpublish.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/util/abi_crosswalk.json create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/util/compile.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/util/handle_gyp_opts.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/util/napi.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/package.json create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js create mode 100644 node_modules/@mapbox/node-pre-gyp/lib/util/versioning.js create mode 100644 node_modules/@mapbox/node-pre-gyp/package.json create mode 100644 node_modules/@types/node/LICENSE create mode 100644 node_modules/@types/node/README.md create mode 100644 node_modules/@types/node/assert.d.ts create mode 100644 node_modules/@types/node/assert/strict.d.ts create mode 100644 node_modules/@types/node/async_hooks.d.ts create mode 100644 node_modules/@types/node/buffer.d.ts create mode 100644 node_modules/@types/node/child_process.d.ts create mode 100644 node_modules/@types/node/cluster.d.ts create mode 100644 node_modules/@types/node/console.d.ts create mode 100644 node_modules/@types/node/constants.d.ts create mode 100644 node_modules/@types/node/crypto.d.ts create mode 100644 node_modules/@types/node/dgram.d.ts create mode 100644 node_modules/@types/node/diagnostics_channel.d.ts create mode 100644 node_modules/@types/node/dns.d.ts create mode 100644 node_modules/@types/node/dns/promises.d.ts create mode 100644 node_modules/@types/node/domain.d.ts create mode 100644 node_modules/@types/node/events.d.ts create mode 100644 node_modules/@types/node/fs.d.ts create mode 100644 node_modules/@types/node/fs/promises.d.ts create mode 100644 node_modules/@types/node/globals.d.ts create mode 100644 node_modules/@types/node/globals.global.d.ts create mode 100644 node_modules/@types/node/http.d.ts create mode 100644 node_modules/@types/node/http2.d.ts create mode 100644 node_modules/@types/node/https.d.ts create mode 100644 node_modules/@types/node/index.d.ts create mode 100644 node_modules/@types/node/inspector.d.ts create mode 100644 node_modules/@types/node/module.d.ts create mode 100644 node_modules/@types/node/net.d.ts create mode 100644 node_modules/@types/node/os.d.ts create mode 100644 node_modules/@types/node/package.json create mode 100644 node_modules/@types/node/path.d.ts create mode 100644 node_modules/@types/node/perf_hooks.d.ts create mode 100644 node_modules/@types/node/process.d.ts create mode 100644 node_modules/@types/node/punycode.d.ts create mode 100644 node_modules/@types/node/querystring.d.ts create mode 100644 node_modules/@types/node/readline.d.ts create mode 100644 node_modules/@types/node/repl.d.ts create mode 100644 node_modules/@types/node/stream.d.ts create mode 100644 node_modules/@types/node/stream/consumers.d.ts create mode 100644 node_modules/@types/node/stream/promises.d.ts create mode 100644 node_modules/@types/node/stream/web.d.ts create mode 100644 node_modules/@types/node/string_decoder.d.ts create mode 100644 node_modules/@types/node/timers.d.ts create mode 100644 node_modules/@types/node/timers/promises.d.ts create mode 100644 node_modules/@types/node/tls.d.ts create mode 100644 node_modules/@types/node/trace_events.d.ts create mode 100644 node_modules/@types/node/tty.d.ts create mode 100644 node_modules/@types/node/url.d.ts create mode 100644 node_modules/@types/node/util.d.ts create mode 100644 node_modules/@types/node/v8.d.ts create mode 100644 node_modules/@types/node/vm.d.ts create mode 100644 node_modules/@types/node/wasi.d.ts create mode 100644 node_modules/@types/node/worker_threads.d.ts create mode 100644 node_modules/@types/node/zlib.d.ts create mode 100644 node_modules/@types/webidl-conversions/LICENSE create mode 100644 node_modules/@types/webidl-conversions/README.md create mode 100644 node_modules/@types/webidl-conversions/index.d.ts create mode 100644 node_modules/@types/webidl-conversions/package.json create mode 100644 node_modules/@types/whatwg-url/LICENSE create mode 100644 node_modules/@types/whatwg-url/README.md create mode 100644 node_modules/@types/whatwg-url/dist/URL-impl.d.ts create mode 100644 node_modules/@types/whatwg-url/dist/URL.d.ts create mode 100644 node_modules/@types/whatwg-url/dist/URLSearchParams-impl.d.ts create mode 100644 node_modules/@types/whatwg-url/dist/URLSearchParams.d.ts create mode 100644 node_modules/@types/whatwg-url/index.d.ts create mode 100644 node_modules/@types/whatwg-url/package.json create mode 100644 node_modules/@types/whatwg-url/ts3.9/dist/URL-impl.d.ts create mode 100644 node_modules/@types/whatwg-url/ts3.9/dist/URL.d.ts create mode 100644 node_modules/@types/whatwg-url/ts3.9/dist/URLSearchParams-impl.d.ts create mode 100644 node_modules/@types/whatwg-url/ts3.9/dist/URLSearchParams.d.ts create mode 100644 node_modules/@types/whatwg-url/ts3.9/index.d.ts create mode 100644 node_modules/@types/whatwg-url/ts3.9/webidl2js-wrapper.d.ts create mode 100644 node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts create mode 100644 node_modules/abbrev/LICENSE create mode 100644 node_modules/abbrev/README.md create mode 100644 node_modules/abbrev/abbrev.js create mode 100644 node_modules/abbrev/package.json create mode 100644 node_modules/accepts/HISTORY.md create mode 100644 node_modules/accepts/LICENSE create mode 100644 node_modules/accepts/README.md create mode 100644 node_modules/accepts/index.js create mode 100644 node_modules/accepts/package.json create mode 100644 node_modules/agent-base/README.md create mode 100644 node_modules/agent-base/dist/src/index.d.ts create mode 100644 node_modules/agent-base/dist/src/index.js create mode 100644 node_modules/agent-base/dist/src/index.js.map create mode 100644 node_modules/agent-base/dist/src/promisify.d.ts create mode 100644 node_modules/agent-base/dist/src/promisify.js create mode 100644 node_modules/agent-base/dist/src/promisify.js.map create mode 100644 node_modules/agent-base/node_modules/debug/LICENSE create mode 100644 node_modules/agent-base/node_modules/debug/README.md create mode 100644 node_modules/agent-base/node_modules/debug/package.json create mode 100644 node_modules/agent-base/node_modules/debug/src/browser.js create mode 100644 node_modules/agent-base/node_modules/debug/src/common.js create mode 100644 node_modules/agent-base/node_modules/debug/src/index.js create mode 100644 node_modules/agent-base/node_modules/debug/src/node.js create mode 100644 node_modules/agent-base/node_modules/ms/index.js create mode 100644 node_modules/agent-base/node_modules/ms/license.md create mode 100644 node_modules/agent-base/node_modules/ms/package.json create mode 100644 node_modules/agent-base/node_modules/ms/readme.md create mode 100644 node_modules/agent-base/package.json create mode 100644 node_modules/agent-base/src/index.ts create mode 100644 node_modules/agent-base/src/promisify.ts create mode 100644 node_modules/ansi-regex/index.d.ts create mode 100644 node_modules/ansi-regex/index.js create mode 100644 node_modules/ansi-regex/license create mode 100644 node_modules/ansi-regex/package.json create mode 100644 node_modules/ansi-regex/readme.md create mode 100644 node_modules/aproba/CHANGELOG.md create mode 100644 node_modules/aproba/LICENSE create mode 100644 node_modules/aproba/README.md create mode 100644 node_modules/aproba/index.js create mode 100644 node_modules/aproba/package.json create mode 100644 node_modules/are-we-there-yet/LICENSE.md create mode 100644 node_modules/are-we-there-yet/README.md create mode 100644 node_modules/are-we-there-yet/lib/index.js create mode 100644 node_modules/are-we-there-yet/lib/tracker-base.js create mode 100644 node_modules/are-we-there-yet/lib/tracker-group.js create mode 100644 node_modules/are-we-there-yet/lib/tracker-stream.js create mode 100644 node_modules/are-we-there-yet/lib/tracker.js create mode 100644 node_modules/are-we-there-yet/package.json create mode 100644 node_modules/array-flatten/LICENSE create mode 100644 node_modules/array-flatten/README.md create mode 100644 node_modules/array-flatten/array-flatten.js create mode 100644 node_modules/array-flatten/package.json create mode 100644 node_modules/balanced-match/.github/FUNDING.yml create mode 100644 node_modules/balanced-match/LICENSE.md create mode 100644 node_modules/balanced-match/README.md create mode 100644 node_modules/balanced-match/index.js create mode 100644 node_modules/balanced-match/package.json create mode 100644 node_modules/base64-js/LICENSE create mode 100644 node_modules/base64-js/README.md create mode 100644 node_modules/base64-js/base64js.min.js create mode 100644 node_modules/base64-js/index.d.ts create mode 100644 node_modules/base64-js/index.js create mode 100644 node_modules/base64-js/package.json create mode 100644 node_modules/bcrypt/.editorconfig create mode 100644 node_modules/bcrypt/.travis.yml create mode 100644 node_modules/bcrypt/CHANGELOG.md create mode 100644 node_modules/bcrypt/ISSUE_TEMPLATE.md create mode 100644 node_modules/bcrypt/LICENSE create mode 100644 node_modules/bcrypt/Makefile create mode 100644 node_modules/bcrypt/README.md create mode 100644 node_modules/bcrypt/SECURITY.md create mode 100644 node_modules/bcrypt/appveyor.yml create mode 100644 node_modules/bcrypt/bcrypt.js create mode 100644 node_modules/bcrypt/binding.gyp create mode 100644 node_modules/bcrypt/examples/async_compare.js create mode 100644 node_modules/bcrypt/examples/forever_gen_salt.js create mode 100644 node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node create mode 100644 node_modules/bcrypt/package.json create mode 100644 node_modules/bcrypt/promises.js create mode 100644 node_modules/bcrypt/src/bcrypt.cc create mode 100644 node_modules/bcrypt/src/bcrypt_node.cc create mode 100644 node_modules/bcrypt/src/blowfish.cc create mode 100644 node_modules/bcrypt/src/node_blf.h create mode 100644 node_modules/bcrypt/test/async.js create mode 100644 node_modules/bcrypt/test/implementation.js create mode 100644 node_modules/bcrypt/test/promise.js create mode 100644 node_modules/bcrypt/test/repetitions.js create mode 100644 node_modules/bcrypt/test/sync.js create mode 100644 node_modules/bcrypt/test_alpine.sh create mode 100644 node_modules/bcryptjs/.npmignore create mode 100644 node_modules/bcryptjs/.travis.yml create mode 100644 node_modules/bcryptjs/.vscode/settings.json create mode 100644 node_modules/bcryptjs/LICENSE create mode 100644 node_modules/bcryptjs/README.md create mode 100644 node_modules/bcryptjs/bin/bcrypt create mode 100644 node_modules/bcryptjs/bower.json create mode 100644 node_modules/bcryptjs/dist/README.md create mode 100644 node_modules/bcryptjs/dist/bcrypt.js create mode 100644 node_modules/bcryptjs/dist/bcrypt.min.js create mode 100644 node_modules/bcryptjs/dist/bcrypt.min.js.gz create mode 100644 node_modules/bcryptjs/dist/bcrypt.min.map create mode 100644 node_modules/bcryptjs/externs/bcrypt.js create mode 100644 node_modules/bcryptjs/externs/minimal-env.js create mode 100644 node_modules/bcryptjs/index.js create mode 100644 node_modules/bcryptjs/package.json create mode 100644 node_modules/bcryptjs/scripts/build.js create mode 100644 node_modules/bcryptjs/src/bcrypt.js create mode 100644 node_modules/bcryptjs/src/bcrypt/impl.js create mode 100644 node_modules/bcryptjs/src/bcrypt/prng/README.md create mode 100644 node_modules/bcryptjs/src/bcrypt/prng/accum.js create mode 100644 node_modules/bcryptjs/src/bcrypt/prng/isaac.js create mode 100644 node_modules/bcryptjs/src/bcrypt/util.js create mode 100644 node_modules/bcryptjs/src/bcrypt/util/base64.js create mode 100644 node_modules/bcryptjs/src/bower.json create mode 100644 node_modules/bcryptjs/src/wrap.js create mode 100644 node_modules/bcryptjs/tests/quickbrown.txt create mode 100644 node_modules/bcryptjs/tests/suite.js create mode 100644 node_modules/body-parser/HISTORY.md create mode 100644 node_modules/body-parser/LICENSE create mode 100644 node_modules/body-parser/README.md create mode 100644 node_modules/body-parser/index.js create mode 100644 node_modules/body-parser/lib/read.js create mode 100644 node_modules/body-parser/lib/types/json.js create mode 100644 node_modules/body-parser/lib/types/raw.js create mode 100644 node_modules/body-parser/lib/types/text.js create mode 100644 node_modules/body-parser/lib/types/urlencoded.js create mode 100644 node_modules/body-parser/package.json create mode 100644 node_modules/brace-expansion/LICENSE create mode 100644 node_modules/brace-expansion/README.md create mode 100644 node_modules/brace-expansion/index.js create mode 100644 node_modules/brace-expansion/package.json create mode 100644 node_modules/bson/LICENSE.md create mode 100644 node_modules/bson/README.md create mode 100644 node_modules/bson/bower.json create mode 100644 node_modules/bson/bson.d.ts create mode 100644 node_modules/bson/dist/bson.browser.esm.js create mode 100644 node_modules/bson/dist/bson.browser.esm.js.map create mode 100644 node_modules/bson/dist/bson.browser.umd.js create mode 100644 node_modules/bson/dist/bson.browser.umd.js.map create mode 100644 node_modules/bson/dist/bson.bundle.js create mode 100644 node_modules/bson/dist/bson.bundle.js.map create mode 100644 node_modules/bson/dist/bson.esm.js create mode 100644 node_modules/bson/dist/bson.esm.js.map create mode 100644 node_modules/bson/etc/prepare.js create mode 100644 node_modules/bson/lib/binary.js create mode 100644 node_modules/bson/lib/binary.js.map create mode 100644 node_modules/bson/lib/bson.js create mode 100644 node_modules/bson/lib/bson.js.map create mode 100644 node_modules/bson/lib/code.js create mode 100644 node_modules/bson/lib/code.js.map create mode 100644 node_modules/bson/lib/constants.js create mode 100644 node_modules/bson/lib/constants.js.map create mode 100644 node_modules/bson/lib/db_ref.js create mode 100644 node_modules/bson/lib/db_ref.js.map create mode 100644 node_modules/bson/lib/decimal128.js create mode 100644 node_modules/bson/lib/decimal128.js.map create mode 100644 node_modules/bson/lib/double.js create mode 100644 node_modules/bson/lib/double.js.map create mode 100644 node_modules/bson/lib/ensure_buffer.js create mode 100644 node_modules/bson/lib/ensure_buffer.js.map create mode 100644 node_modules/bson/lib/error.js create mode 100644 node_modules/bson/lib/error.js.map create mode 100644 node_modules/bson/lib/extended_json.js create mode 100644 node_modules/bson/lib/extended_json.js.map create mode 100644 node_modules/bson/lib/float_parser.js create mode 100644 node_modules/bson/lib/float_parser.js.map create mode 100644 node_modules/bson/lib/int_32.js create mode 100644 node_modules/bson/lib/int_32.js.map create mode 100644 node_modules/bson/lib/long.js create mode 100644 node_modules/bson/lib/long.js.map create mode 100644 node_modules/bson/lib/map.js create mode 100644 node_modules/bson/lib/map.js.map create mode 100644 node_modules/bson/lib/max_key.js create mode 100644 node_modules/bson/lib/max_key.js.map create mode 100644 node_modules/bson/lib/min_key.js create mode 100644 node_modules/bson/lib/min_key.js.map create mode 100644 node_modules/bson/lib/objectid.js create mode 100644 node_modules/bson/lib/objectid.js.map create mode 100644 node_modules/bson/lib/parser/calculate_size.js create mode 100644 node_modules/bson/lib/parser/calculate_size.js.map create mode 100644 node_modules/bson/lib/parser/deserializer.js create mode 100644 node_modules/bson/lib/parser/deserializer.js.map create mode 100644 node_modules/bson/lib/parser/serializer.js create mode 100644 node_modules/bson/lib/parser/serializer.js.map create mode 100644 node_modules/bson/lib/parser/utils.js create mode 100644 node_modules/bson/lib/parser/utils.js.map create mode 100644 node_modules/bson/lib/regexp.js create mode 100644 node_modules/bson/lib/regexp.js.map create mode 100644 node_modules/bson/lib/symbol.js create mode 100644 node_modules/bson/lib/symbol.js.map create mode 100644 node_modules/bson/lib/timestamp.js create mode 100644 node_modules/bson/lib/timestamp.js.map create mode 100644 node_modules/bson/lib/utils/global.js create mode 100644 node_modules/bson/lib/utils/global.js.map create mode 100644 node_modules/bson/lib/uuid.js create mode 100644 node_modules/bson/lib/uuid.js.map create mode 100644 node_modules/bson/lib/uuid_utils.js create mode 100644 node_modules/bson/lib/uuid_utils.js.map create mode 100644 node_modules/bson/lib/validate_utf8.js create mode 100644 node_modules/bson/lib/validate_utf8.js.map create mode 100644 node_modules/bson/package.json create mode 100644 node_modules/bson/src/binary.ts create mode 100644 node_modules/bson/src/bson.ts create mode 100644 node_modules/bson/src/code.ts create mode 100644 node_modules/bson/src/constants.ts create mode 100644 node_modules/bson/src/db_ref.ts create mode 100644 node_modules/bson/src/decimal128.ts create mode 100644 node_modules/bson/src/double.ts create mode 100644 node_modules/bson/src/ensure_buffer.ts create mode 100644 node_modules/bson/src/error.ts create mode 100644 node_modules/bson/src/extended_json.ts create mode 100644 node_modules/bson/src/float_parser.ts create mode 100644 node_modules/bson/src/int_32.ts create mode 100644 node_modules/bson/src/long.ts create mode 100644 node_modules/bson/src/map.ts create mode 100644 node_modules/bson/src/max_key.ts create mode 100644 node_modules/bson/src/min_key.ts create mode 100644 node_modules/bson/src/objectid.ts create mode 100644 node_modules/bson/src/parser/calculate_size.ts create mode 100644 node_modules/bson/src/parser/deserializer.ts create mode 100644 node_modules/bson/src/parser/serializer.ts create mode 100644 node_modules/bson/src/parser/utils.ts create mode 100644 node_modules/bson/src/regexp.ts create mode 100644 node_modules/bson/src/symbol.ts create mode 100644 node_modules/bson/src/timestamp.ts create mode 100644 node_modules/bson/src/utils/global.ts create mode 100644 node_modules/bson/src/uuid.ts create mode 100644 node_modules/bson/src/uuid_utils.ts create mode 100644 node_modules/bson/src/validate_utf8.ts create mode 100644 node_modules/buffer-equal-constant-time/.npmignore create mode 100644 node_modules/buffer-equal-constant-time/.travis.yml create mode 100644 node_modules/buffer-equal-constant-time/LICENSE.txt create mode 100644 node_modules/buffer-equal-constant-time/README.md create mode 100644 node_modules/buffer-equal-constant-time/index.js create mode 100644 node_modules/buffer-equal-constant-time/package.json create mode 100644 node_modules/buffer-equal-constant-time/test.js create mode 100644 node_modules/buffer/AUTHORS.md create mode 100644 node_modules/buffer/LICENSE create mode 100644 node_modules/buffer/README.md create mode 100644 node_modules/buffer/index.d.ts create mode 100644 node_modules/buffer/index.js create mode 100644 node_modules/buffer/package.json create mode 100644 node_modules/bytes/History.md create mode 100644 node_modules/bytes/LICENSE create mode 100644 node_modules/bytes/Readme.md create mode 100644 node_modules/bytes/index.js create mode 100644 node_modules/bytes/package.json create mode 100644 node_modules/child_process/README.md create mode 100644 node_modules/child_process/package.json create mode 100644 node_modules/chownr/LICENSE create mode 100644 node_modules/chownr/README.md create mode 100644 node_modules/chownr/chownr.js create mode 100644 node_modules/chownr/package.json create mode 100644 node_modules/color-support/LICENSE create mode 100644 node_modules/color-support/README.md create mode 100644 node_modules/color-support/bin.js create mode 100644 node_modules/color-support/browser.js create mode 100644 node_modules/color-support/index.js create mode 100644 node_modules/color-support/package.json create mode 100644 node_modules/concat-map/.travis.yml create mode 100644 node_modules/concat-map/LICENSE create mode 100644 node_modules/concat-map/README.markdown create mode 100644 node_modules/concat-map/example/map.js create mode 100644 node_modules/concat-map/index.js create mode 100644 node_modules/concat-map/package.json create mode 100644 node_modules/concat-map/test/map.js create mode 100644 node_modules/console-control-strings/LICENSE create mode 100644 node_modules/console-control-strings/README.md create mode 100644 node_modules/console-control-strings/README.md~ create mode 100644 node_modules/console-control-strings/index.js create mode 100644 node_modules/console-control-strings/package.json create mode 100644 node_modules/content-disposition/HISTORY.md create mode 100644 node_modules/content-disposition/LICENSE create mode 100644 node_modules/content-disposition/README.md create mode 100644 node_modules/content-disposition/index.js create mode 100644 node_modules/content-disposition/package.json create mode 100644 node_modules/content-type/HISTORY.md create mode 100644 node_modules/content-type/LICENSE create mode 100644 node_modules/content-type/README.md create mode 100644 node_modules/content-type/index.js create mode 100644 node_modules/content-type/package.json create mode 100644 node_modules/cookie-signature/.npmignore create mode 100644 node_modules/cookie-signature/History.md create mode 100644 node_modules/cookie-signature/Readme.md create mode 100644 node_modules/cookie-signature/index.js create mode 100644 node_modules/cookie-signature/package.json create mode 100644 node_modules/cookie/HISTORY.md create mode 100644 node_modules/cookie/LICENSE create mode 100644 node_modules/cookie/README.md create mode 100644 node_modules/cookie/index.js create mode 100644 node_modules/cookie/package.json create mode 100644 node_modules/debug/.coveralls.yml create mode 100644 node_modules/debug/.eslintrc create mode 100644 node_modules/debug/.npmignore create mode 100644 node_modules/debug/.travis.yml create mode 100644 node_modules/debug/CHANGELOG.md create mode 100644 node_modules/debug/LICENSE create mode 100644 node_modules/debug/Makefile create mode 100644 node_modules/debug/README.md create mode 100644 node_modules/debug/component.json create mode 100644 node_modules/debug/karma.conf.js create mode 100644 node_modules/debug/node.js create mode 100644 node_modules/debug/package.json create mode 100644 node_modules/debug/src/browser.js create mode 100644 node_modules/debug/src/debug.js create mode 100644 node_modules/debug/src/index.js create mode 100644 node_modules/debug/src/inspector-log.js create mode 100644 node_modules/debug/src/node.js create mode 100644 node_modules/delegates/.npmignore create mode 100644 node_modules/delegates/History.md create mode 100644 node_modules/delegates/License create mode 100644 node_modules/delegates/Makefile create mode 100644 node_modules/delegates/Readme.md create mode 100644 node_modules/delegates/index.js create mode 100644 node_modules/delegates/package.json create mode 100644 node_modules/delegates/test/index.js create mode 100644 node_modules/denque/CHANGELOG.md create mode 100644 node_modules/denque/LICENSE create mode 100644 node_modules/denque/README.md create mode 100644 node_modules/denque/index.d.ts create mode 100644 node_modules/denque/index.js create mode 100644 node_modules/denque/package.json create mode 100644 node_modules/depd/History.md create mode 100644 node_modules/depd/LICENSE create mode 100644 node_modules/depd/Readme.md create mode 100644 node_modules/depd/index.js create mode 100644 node_modules/depd/lib/browser/index.js create mode 100644 node_modules/depd/lib/compat/callsite-tostring.js create mode 100644 node_modules/depd/lib/compat/event-listener-count.js create mode 100644 node_modules/depd/lib/compat/index.js create mode 100644 node_modules/depd/package.json create mode 100644 node_modules/destroy/LICENSE create mode 100644 node_modules/destroy/README.md create mode 100644 node_modules/destroy/index.js create mode 100644 node_modules/destroy/package.json create mode 100644 node_modules/detect-libc/.npmignore create mode 100644 node_modules/detect-libc/LICENSE create mode 100644 node_modules/detect-libc/README.md create mode 100644 node_modules/detect-libc/bin/detect-libc.js create mode 100644 node_modules/detect-libc/lib/detect-libc.js create mode 100644 node_modules/detect-libc/package.json create mode 100644 node_modules/ecdsa-sig-formatter/CODEOWNERS create mode 100644 node_modules/ecdsa-sig-formatter/LICENSE create mode 100644 node_modules/ecdsa-sig-formatter/README.md create mode 100644 node_modules/ecdsa-sig-formatter/package.json create mode 100644 node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts create mode 100644 node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js create mode 100644 node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js create mode 100644 node_modules/ee-first/LICENSE create mode 100644 node_modules/ee-first/README.md create mode 100644 node_modules/ee-first/index.js create mode 100644 node_modules/ee-first/package.json create mode 100644 node_modules/emoji-regex/LICENSE-MIT.txt create mode 100644 node_modules/emoji-regex/README.md create mode 100644 node_modules/emoji-regex/es2015/index.js create mode 100644 node_modules/emoji-regex/es2015/text.js create mode 100644 node_modules/emoji-regex/index.d.ts create mode 100644 node_modules/emoji-regex/index.js create mode 100644 node_modules/emoji-regex/package.json create mode 100644 node_modules/emoji-regex/text.js create mode 100644 node_modules/encodeurl/HISTORY.md create mode 100644 node_modules/encodeurl/LICENSE create mode 100644 node_modules/encodeurl/README.md create mode 100644 node_modules/encodeurl/index.js create mode 100644 node_modules/encodeurl/package.json create mode 100644 node_modules/escape-html/LICENSE create mode 100644 node_modules/escape-html/Readme.md create mode 100644 node_modules/escape-html/index.js create mode 100644 node_modules/escape-html/package.json create mode 100644 node_modules/etag/HISTORY.md create mode 100644 node_modules/etag/LICENSE create mode 100644 node_modules/etag/README.md create mode 100644 node_modules/etag/index.js create mode 100644 node_modules/etag/package.json create mode 100644 node_modules/express/History.md create mode 100644 node_modules/express/LICENSE create mode 100644 node_modules/express/Readme.md create mode 100644 node_modules/express/index.js create mode 100644 node_modules/express/lib/application.js create mode 100644 node_modules/express/lib/express.js create mode 100644 node_modules/express/lib/middleware/init.js create mode 100644 node_modules/express/lib/middleware/query.js create mode 100644 node_modules/express/lib/request.js create mode 100644 node_modules/express/lib/response.js create mode 100644 node_modules/express/lib/router/index.js create mode 100644 node_modules/express/lib/router/layer.js create mode 100644 node_modules/express/lib/router/route.js create mode 100644 node_modules/express/lib/utils.js create mode 100644 node_modules/express/lib/view.js create mode 100644 node_modules/express/package.json create mode 100644 node_modules/finalhandler/HISTORY.md create mode 100644 node_modules/finalhandler/LICENSE create mode 100644 node_modules/finalhandler/README.md create mode 100644 node_modules/finalhandler/index.js create mode 100644 node_modules/finalhandler/package.json create mode 100644 node_modules/forwarded/HISTORY.md create mode 100644 node_modules/forwarded/LICENSE create mode 100644 node_modules/forwarded/README.md create mode 100644 node_modules/forwarded/index.js create mode 100644 node_modules/forwarded/package.json create mode 100644 node_modules/fresh/HISTORY.md create mode 100644 node_modules/fresh/LICENSE create mode 100644 node_modules/fresh/README.md create mode 100644 node_modules/fresh/index.js create mode 100644 node_modules/fresh/package.json create mode 100644 node_modules/fs-minipass/LICENSE create mode 100644 node_modules/fs-minipass/README.md create mode 100644 node_modules/fs-minipass/index.js create mode 100644 node_modules/fs-minipass/package.json create mode 100644 node_modules/fs.realpath/LICENSE create mode 100644 node_modules/fs.realpath/README.md create mode 100644 node_modules/fs.realpath/index.js create mode 100644 node_modules/fs.realpath/old.js create mode 100644 node_modules/fs.realpath/package.json create mode 100644 node_modules/gauge/CHANGELOG.md create mode 100644 node_modules/gauge/LICENSE create mode 100644 node_modules/gauge/README.md create mode 100644 node_modules/gauge/base-theme.js create mode 100644 node_modules/gauge/error.js create mode 100644 node_modules/gauge/has-color.js create mode 100644 node_modules/gauge/index.js create mode 100644 node_modules/gauge/package.json create mode 100644 node_modules/gauge/plumbing.js create mode 100644 node_modules/gauge/process.js create mode 100644 node_modules/gauge/progress-bar.js create mode 100644 node_modules/gauge/render-template.js create mode 100644 node_modules/gauge/set-immediate.js create mode 100644 node_modules/gauge/set-interval.js create mode 100644 node_modules/gauge/spin.js create mode 100644 node_modules/gauge/template-item.js create mode 100644 node_modules/gauge/theme-set.js create mode 100644 node_modules/gauge/themes.js create mode 100644 node_modules/gauge/wide-truncate.js create mode 100644 node_modules/glob/LICENSE create mode 100644 node_modules/glob/README.md create mode 100644 node_modules/glob/common.js create mode 100644 node_modules/glob/glob.js create mode 100644 node_modules/glob/package.json create mode 100644 node_modules/glob/sync.js create mode 100644 node_modules/has-unicode/LICENSE create mode 100644 node_modules/has-unicode/README.md create mode 100644 node_modules/has-unicode/index.js create mode 100644 node_modules/has-unicode/package.json create mode 100644 node_modules/http-errors/HISTORY.md create mode 100644 node_modules/http-errors/LICENSE create mode 100644 node_modules/http-errors/README.md create mode 100644 node_modules/http-errors/index.js create mode 100644 node_modules/http-errors/package.json create mode 100644 node_modules/http-status/CHANGELOG.md create mode 100644 node_modules/http-status/LICENSE create mode 100644 node_modules/http-status/README.md create mode 100644 node_modules/http-status/lib/cloudflare.js create mode 100644 node_modules/http-status/lib/iis.js create mode 100644 node_modules/http-status/lib/index.d.ts create mode 100644 node_modules/http-status/lib/index.js create mode 100644 node_modules/http-status/lib/nginx.js create mode 100644 node_modules/http-status/lib/unofficial.js create mode 100644 node_modules/http-status/package.json create mode 100644 node_modules/http-status/tsconfig.json create mode 100644 node_modules/https-proxy-agent/README.md create mode 100644 node_modules/https-proxy-agent/dist/agent.d.ts create mode 100644 node_modules/https-proxy-agent/dist/agent.js create mode 100644 node_modules/https-proxy-agent/dist/agent.js.map create mode 100644 node_modules/https-proxy-agent/dist/index.d.ts create mode 100644 node_modules/https-proxy-agent/dist/index.js create mode 100644 node_modules/https-proxy-agent/dist/index.js.map create mode 100644 node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts create mode 100644 node_modules/https-proxy-agent/dist/parse-proxy-response.js create mode 100644 node_modules/https-proxy-agent/dist/parse-proxy-response.js.map create mode 100644 node_modules/https-proxy-agent/node_modules/debug/LICENSE create mode 100644 node_modules/https-proxy-agent/node_modules/debug/README.md create mode 100644 node_modules/https-proxy-agent/node_modules/debug/package.json create mode 100644 node_modules/https-proxy-agent/node_modules/debug/src/browser.js create mode 100644 node_modules/https-proxy-agent/node_modules/debug/src/common.js create mode 100644 node_modules/https-proxy-agent/node_modules/debug/src/index.js create mode 100644 node_modules/https-proxy-agent/node_modules/debug/src/node.js create mode 100644 node_modules/https-proxy-agent/node_modules/ms/index.js create mode 100644 node_modules/https-proxy-agent/node_modules/ms/license.md create mode 100644 node_modules/https-proxy-agent/node_modules/ms/package.json create mode 100644 node_modules/https-proxy-agent/node_modules/ms/readme.md create mode 100644 node_modules/https-proxy-agent/package.json create mode 100644 node_modules/iconv-lite/Changelog.md create mode 100644 node_modules/iconv-lite/LICENSE create mode 100644 node_modules/iconv-lite/README.md create mode 100644 node_modules/iconv-lite/encodings/dbcs-codec.js create mode 100644 node_modules/iconv-lite/encodings/dbcs-data.js create mode 100644 node_modules/iconv-lite/encodings/index.js create mode 100644 node_modules/iconv-lite/encodings/internal.js create mode 100644 node_modules/iconv-lite/encodings/sbcs-codec.js create mode 100644 node_modules/iconv-lite/encodings/sbcs-data-generated.js create mode 100644 node_modules/iconv-lite/encodings/sbcs-data.js create mode 100644 node_modules/iconv-lite/encodings/tables/big5-added.json create mode 100644 node_modules/iconv-lite/encodings/tables/cp936.json create mode 100644 node_modules/iconv-lite/encodings/tables/cp949.json create mode 100644 node_modules/iconv-lite/encodings/tables/cp950.json create mode 100644 node_modules/iconv-lite/encodings/tables/eucjp.json create mode 100644 node_modules/iconv-lite/encodings/tables/gb18030-ranges.json create mode 100644 node_modules/iconv-lite/encodings/tables/gbk-added.json create mode 100644 node_modules/iconv-lite/encodings/tables/shiftjis.json create mode 100644 node_modules/iconv-lite/encodings/utf16.js create mode 100644 node_modules/iconv-lite/encodings/utf7.js create mode 100644 node_modules/iconv-lite/lib/bom-handling.js create mode 100644 node_modules/iconv-lite/lib/extend-node.js create mode 100644 node_modules/iconv-lite/lib/index.d.ts create mode 100644 node_modules/iconv-lite/lib/index.js create mode 100644 node_modules/iconv-lite/lib/streams.js create mode 100644 node_modules/iconv-lite/package.json create mode 100644 node_modules/ieee754/LICENSE create mode 100644 node_modules/ieee754/README.md create mode 100644 node_modules/ieee754/index.d.ts create mode 100644 node_modules/ieee754/index.js create mode 100644 node_modules/ieee754/package.json create mode 100644 node_modules/inflight/LICENSE create mode 100644 node_modules/inflight/README.md create mode 100644 node_modules/inflight/inflight.js create mode 100644 node_modules/inflight/package.json create mode 100644 node_modules/inherits/LICENSE create mode 100644 node_modules/inherits/README.md create mode 100644 node_modules/inherits/inherits.js create mode 100644 node_modules/inherits/inherits_browser.js create mode 100644 node_modules/inherits/package.json create mode 100644 node_modules/ipaddr.js/LICENSE create mode 100644 node_modules/ipaddr.js/README.md create mode 100644 node_modules/ipaddr.js/ipaddr.min.js create mode 100644 node_modules/ipaddr.js/lib/ipaddr.js create mode 100644 node_modules/ipaddr.js/lib/ipaddr.js.d.ts create mode 100644 node_modules/ipaddr.js/package.json create mode 100644 node_modules/is-fullwidth-code-point/index.d.ts create mode 100644 node_modules/is-fullwidth-code-point/index.js create mode 100644 node_modules/is-fullwidth-code-point/license create mode 100644 node_modules/is-fullwidth-code-point/package.json create mode 100644 node_modules/is-fullwidth-code-point/readme.md create mode 100644 node_modules/jsonwebtoken/CHANGELOG.md create mode 100644 node_modules/jsonwebtoken/LICENSE create mode 100644 node_modules/jsonwebtoken/README.md create mode 100644 node_modules/jsonwebtoken/decode.js create mode 100644 node_modules/jsonwebtoken/index.js create mode 100644 node_modules/jsonwebtoken/lib/JsonWebTokenError.js create mode 100644 node_modules/jsonwebtoken/lib/NotBeforeError.js create mode 100644 node_modules/jsonwebtoken/lib/TokenExpiredError.js create mode 100644 node_modules/jsonwebtoken/lib/psSupported.js create mode 100644 node_modules/jsonwebtoken/lib/timespan.js create mode 100644 node_modules/jsonwebtoken/node_modules/.bin/semver create mode 100644 node_modules/jsonwebtoken/node_modules/.bin/semver.cmd create mode 100644 node_modules/jsonwebtoken/node_modules/.bin/semver.ps1 create mode 100644 node_modules/jsonwebtoken/node_modules/ms/index.js create mode 100644 node_modules/jsonwebtoken/node_modules/ms/license.md create mode 100644 node_modules/jsonwebtoken/node_modules/ms/package.json create mode 100644 node_modules/jsonwebtoken/node_modules/ms/readme.md create mode 100644 node_modules/jsonwebtoken/node_modules/semver/CHANGELOG.md create mode 100644 node_modules/jsonwebtoken/node_modules/semver/LICENSE create mode 100644 node_modules/jsonwebtoken/node_modules/semver/README.md create mode 100644 node_modules/jsonwebtoken/node_modules/semver/bin/semver create mode 100644 node_modules/jsonwebtoken/node_modules/semver/package.json create mode 100644 node_modules/jsonwebtoken/node_modules/semver/range.bnf create mode 100644 node_modules/jsonwebtoken/node_modules/semver/semver.js create mode 100644 node_modules/jsonwebtoken/package.json create mode 100644 node_modules/jsonwebtoken/sign.js create mode 100644 node_modules/jsonwebtoken/verify.js create mode 100644 node_modules/jwa/LICENSE create mode 100644 node_modules/jwa/README.md create mode 100644 node_modules/jwa/index.js create mode 100644 node_modules/jwa/package.json create mode 100644 node_modules/jws/CHANGELOG.md create mode 100644 node_modules/jws/LICENSE create mode 100644 node_modules/jws/index.js create mode 100644 node_modules/jws/lib/data-stream.js create mode 100644 node_modules/jws/lib/sign-stream.js create mode 100644 node_modules/jws/lib/tostring.js create mode 100644 node_modules/jws/lib/verify-stream.js create mode 100644 node_modules/jws/package.json create mode 100644 node_modules/jws/readme.md create mode 100644 node_modules/kareem/.travis.yml create mode 100644 node_modules/kareem/CHANGELOG.md create mode 100644 node_modules/kareem/LICENSE create mode 100644 node_modules/kareem/Makefile create mode 100644 node_modules/kareem/README.md create mode 100644 node_modules/kareem/docs.js create mode 100644 node_modules/kareem/gulpfile.js create mode 100644 node_modules/kareem/index.js create mode 100644 node_modules/kareem/package.json create mode 100644 node_modules/kareem/test/examples.test.js create mode 100644 node_modules/kareem/test/misc.test.js create mode 100644 node_modules/kareem/test/post.test.js create mode 100644 node_modules/kareem/test/pre.test.js create mode 100644 node_modules/kareem/test/wrap.test.js create mode 100644 node_modules/lodash.includes/LICENSE create mode 100644 node_modules/lodash.includes/README.md create mode 100644 node_modules/lodash.includes/index.js create mode 100644 node_modules/lodash.includes/package.json create mode 100644 node_modules/lodash.isboolean/LICENSE create mode 100644 node_modules/lodash.isboolean/README.md create mode 100644 node_modules/lodash.isboolean/index.js create mode 100644 node_modules/lodash.isboolean/package.json create mode 100644 node_modules/lodash.isinteger/LICENSE create mode 100644 node_modules/lodash.isinteger/README.md create mode 100644 node_modules/lodash.isinteger/index.js create mode 100644 node_modules/lodash.isinteger/package.json create mode 100644 node_modules/lodash.isnumber/LICENSE create mode 100644 node_modules/lodash.isnumber/README.md create mode 100644 node_modules/lodash.isnumber/index.js create mode 100644 node_modules/lodash.isnumber/package.json create mode 100644 node_modules/lodash.isplainobject/LICENSE create mode 100644 node_modules/lodash.isplainobject/README.md create mode 100644 node_modules/lodash.isplainobject/index.js create mode 100644 node_modules/lodash.isplainobject/package.json create mode 100644 node_modules/lodash.isstring/LICENSE create mode 100644 node_modules/lodash.isstring/README.md create mode 100644 node_modules/lodash.isstring/index.js create mode 100644 node_modules/lodash.isstring/package.json create mode 100644 node_modules/lodash.once/LICENSE create mode 100644 node_modules/lodash.once/README.md create mode 100644 node_modules/lodash.once/index.js create mode 100644 node_modules/lodash.once/package.json create mode 100644 node_modules/lru-cache/LICENSE create mode 100644 node_modules/lru-cache/README.md create mode 100644 node_modules/lru-cache/index.js create mode 100644 node_modules/lru-cache/package.json create mode 100644 node_modules/make-dir/index.d.ts create mode 100644 node_modules/make-dir/index.js create mode 100644 node_modules/make-dir/license create mode 100644 node_modules/make-dir/node_modules/.bin/semver create mode 100644 node_modules/make-dir/node_modules/.bin/semver.cmd create mode 100644 node_modules/make-dir/node_modules/.bin/semver.ps1 create mode 100644 node_modules/make-dir/node_modules/semver/CHANGELOG.md create mode 100644 node_modules/make-dir/node_modules/semver/LICENSE create mode 100644 node_modules/make-dir/node_modules/semver/README.md create mode 100644 node_modules/make-dir/node_modules/semver/bin/semver.js create mode 100644 node_modules/make-dir/node_modules/semver/package.json create mode 100644 node_modules/make-dir/node_modules/semver/range.bnf create mode 100644 node_modules/make-dir/node_modules/semver/semver.js create mode 100644 node_modules/make-dir/package.json create mode 100644 node_modules/make-dir/readme.md create mode 100644 node_modules/media-typer/HISTORY.md create mode 100644 node_modules/media-typer/LICENSE create mode 100644 node_modules/media-typer/README.md create mode 100644 node_modules/media-typer/index.js create mode 100644 node_modules/media-typer/package.json create mode 100644 node_modules/memory-pager/.travis.yml create mode 100644 node_modules/memory-pager/LICENSE create mode 100644 node_modules/memory-pager/README.md create mode 100644 node_modules/memory-pager/index.js create mode 100644 node_modules/memory-pager/package.json create mode 100644 node_modules/memory-pager/test.js create mode 100644 node_modules/merge-descriptors/HISTORY.md create mode 100644 node_modules/merge-descriptors/LICENSE create mode 100644 node_modules/merge-descriptors/README.md create mode 100644 node_modules/merge-descriptors/index.js create mode 100644 node_modules/merge-descriptors/package.json create mode 100644 node_modules/methods/HISTORY.md create mode 100644 node_modules/methods/LICENSE create mode 100644 node_modules/methods/README.md create mode 100644 node_modules/methods/index.js create mode 100644 node_modules/methods/package.json create mode 100644 node_modules/mime-db/HISTORY.md create mode 100644 node_modules/mime-db/LICENSE create mode 100644 node_modules/mime-db/README.md create mode 100644 node_modules/mime-db/db.json create mode 100644 node_modules/mime-db/index.js create mode 100644 node_modules/mime-db/package.json create mode 100644 node_modules/mime-types/HISTORY.md create mode 100644 node_modules/mime-types/LICENSE create mode 100644 node_modules/mime-types/README.md create mode 100644 node_modules/mime-types/index.js create mode 100644 node_modules/mime-types/package.json create mode 100644 node_modules/mime/.npmignore create mode 100644 node_modules/mime/CHANGELOG.md create mode 100644 node_modules/mime/LICENSE create mode 100644 node_modules/mime/README.md create mode 100644 node_modules/mime/cli.js create mode 100644 node_modules/mime/mime.js create mode 100644 node_modules/mime/package.json create mode 100644 node_modules/mime/src/build.js create mode 100644 node_modules/mime/src/test.js create mode 100644 node_modules/mime/types.json create mode 100644 node_modules/minimatch/LICENSE create mode 100644 node_modules/minimatch/README.md create mode 100644 node_modules/minimatch/minimatch.js create mode 100644 node_modules/minimatch/package.json create mode 100644 node_modules/minipass/LICENSE create mode 100644 node_modules/minipass/README.md create mode 100644 node_modules/minipass/index.js create mode 100644 node_modules/minipass/package.json create mode 100644 node_modules/minizlib/LICENSE create mode 100644 node_modules/minizlib/README.md create mode 100644 node_modules/minizlib/constants.js create mode 100644 node_modules/minizlib/index.js create mode 100644 node_modules/minizlib/package.json create mode 100644 node_modules/mkdirp/CHANGELOG.md create mode 100644 node_modules/mkdirp/LICENSE create mode 100644 node_modules/mkdirp/bin/cmd.js create mode 100644 node_modules/mkdirp/index.js create mode 100644 node_modules/mkdirp/lib/find-made.js create mode 100644 node_modules/mkdirp/lib/mkdirp-manual.js create mode 100644 node_modules/mkdirp/lib/mkdirp-native.js create mode 100644 node_modules/mkdirp/lib/opts-arg.js create mode 100644 node_modules/mkdirp/lib/path-arg.js create mode 100644 node_modules/mkdirp/lib/use-native.js create mode 100644 node_modules/mkdirp/package.json create mode 100644 node_modules/mkdirp/readme.markdown create mode 100644 node_modules/mongodb-connection-string-url/.esm-wrapper.mjs create mode 100644 node_modules/mongodb-connection-string-url/LICENSE create mode 100644 node_modules/mongodb-connection-string-url/README.md create mode 100644 node_modules/mongodb-connection-string-url/lib/index.d.ts create mode 100644 node_modules/mongodb-connection-string-url/lib/index.js create mode 100644 node_modules/mongodb-connection-string-url/lib/index.js.map create mode 100644 node_modules/mongodb-connection-string-url/package.json create mode 100644 node_modules/mongodb/LICENSE.md create mode 100644 node_modules/mongodb/README.md create mode 100644 node_modules/mongodb/etc/prepare.js create mode 100644 node_modules/mongodb/lib/admin.js create mode 100644 node_modules/mongodb/lib/admin.js.map create mode 100644 node_modules/mongodb/lib/bson.js create mode 100644 node_modules/mongodb/lib/bson.js.map create mode 100644 node_modules/mongodb/lib/bulk/common.js create mode 100644 node_modules/mongodb/lib/bulk/common.js.map create mode 100644 node_modules/mongodb/lib/bulk/ordered.js create mode 100644 node_modules/mongodb/lib/bulk/ordered.js.map create mode 100644 node_modules/mongodb/lib/bulk/unordered.js create mode 100644 node_modules/mongodb/lib/bulk/unordered.js.map create mode 100644 node_modules/mongodb/lib/change_stream.js create mode 100644 node_modules/mongodb/lib/change_stream.js.map create mode 100644 node_modules/mongodb/lib/cmap/auth/auth_provider.js create mode 100644 node_modules/mongodb/lib/cmap/auth/auth_provider.js.map create mode 100644 node_modules/mongodb/lib/cmap/auth/defaultAuthProviders.js create mode 100644 node_modules/mongodb/lib/cmap/auth/defaultAuthProviders.js.map create mode 100644 node_modules/mongodb/lib/cmap/auth/gssapi.js create mode 100644 node_modules/mongodb/lib/cmap/auth/gssapi.js.map create mode 100644 node_modules/mongodb/lib/cmap/auth/mongo_credentials.js create mode 100644 node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map create mode 100644 node_modules/mongodb/lib/cmap/auth/mongocr.js create mode 100644 node_modules/mongodb/lib/cmap/auth/mongocr.js.map create mode 100644 node_modules/mongodb/lib/cmap/auth/mongodb_aws.js create mode 100644 node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map create mode 100644 node_modules/mongodb/lib/cmap/auth/plain.js create mode 100644 node_modules/mongodb/lib/cmap/auth/plain.js.map create mode 100644 node_modules/mongodb/lib/cmap/auth/scram.js create mode 100644 node_modules/mongodb/lib/cmap/auth/scram.js.map create mode 100644 node_modules/mongodb/lib/cmap/auth/x509.js create mode 100644 node_modules/mongodb/lib/cmap/auth/x509.js.map create mode 100644 node_modules/mongodb/lib/cmap/command_monitoring_events.js create mode 100644 node_modules/mongodb/lib/cmap/command_monitoring_events.js.map create mode 100644 node_modules/mongodb/lib/cmap/commands.js create mode 100644 node_modules/mongodb/lib/cmap/commands.js.map create mode 100644 node_modules/mongodb/lib/cmap/connect.js create mode 100644 node_modules/mongodb/lib/cmap/connect.js.map create mode 100644 node_modules/mongodb/lib/cmap/connection.js create mode 100644 node_modules/mongodb/lib/cmap/connection.js.map create mode 100644 node_modules/mongodb/lib/cmap/connection_pool.js create mode 100644 node_modules/mongodb/lib/cmap/connection_pool.js.map create mode 100644 node_modules/mongodb/lib/cmap/connection_pool_events.js create mode 100644 node_modules/mongodb/lib/cmap/connection_pool_events.js.map create mode 100644 node_modules/mongodb/lib/cmap/errors.js create mode 100644 node_modules/mongodb/lib/cmap/errors.js.map create mode 100644 node_modules/mongodb/lib/cmap/message_stream.js create mode 100644 node_modules/mongodb/lib/cmap/message_stream.js.map create mode 100644 node_modules/mongodb/lib/cmap/metrics.js create mode 100644 node_modules/mongodb/lib/cmap/metrics.js.map create mode 100644 node_modules/mongodb/lib/cmap/stream_description.js create mode 100644 node_modules/mongodb/lib/cmap/stream_description.js.map create mode 100644 node_modules/mongodb/lib/cmap/wire_protocol/compression.js create mode 100644 node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map create mode 100644 node_modules/mongodb/lib/cmap/wire_protocol/constants.js create mode 100644 node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map create mode 100644 node_modules/mongodb/lib/cmap/wire_protocol/shared.js create mode 100644 node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map create mode 100644 node_modules/mongodb/lib/collection.js create mode 100644 node_modules/mongodb/lib/collection.js.map create mode 100644 node_modules/mongodb/lib/connection_string.js create mode 100644 node_modules/mongodb/lib/connection_string.js.map create mode 100644 node_modules/mongodb/lib/constants.js create mode 100644 node_modules/mongodb/lib/constants.js.map create mode 100644 node_modules/mongodb/lib/cursor/abstract_cursor.js create mode 100644 node_modules/mongodb/lib/cursor/abstract_cursor.js.map create mode 100644 node_modules/mongodb/lib/cursor/aggregation_cursor.js create mode 100644 node_modules/mongodb/lib/cursor/aggregation_cursor.js.map create mode 100644 node_modules/mongodb/lib/cursor/find_cursor.js create mode 100644 node_modules/mongodb/lib/cursor/find_cursor.js.map create mode 100644 node_modules/mongodb/lib/db.js create mode 100644 node_modules/mongodb/lib/db.js.map create mode 100644 node_modules/mongodb/lib/deps.js create mode 100644 node_modules/mongodb/lib/deps.js.map create mode 100644 node_modules/mongodb/lib/encrypter.js create mode 100644 node_modules/mongodb/lib/encrypter.js.map create mode 100644 node_modules/mongodb/lib/error.js create mode 100644 node_modules/mongodb/lib/error.js.map create mode 100644 node_modules/mongodb/lib/explain.js create mode 100644 node_modules/mongodb/lib/explain.js.map create mode 100644 node_modules/mongodb/lib/gridfs/download.js create mode 100644 node_modules/mongodb/lib/gridfs/download.js.map create mode 100644 node_modules/mongodb/lib/gridfs/index.js create mode 100644 node_modules/mongodb/lib/gridfs/index.js.map create mode 100644 node_modules/mongodb/lib/gridfs/upload.js create mode 100644 node_modules/mongodb/lib/gridfs/upload.js.map create mode 100644 node_modules/mongodb/lib/index.js create mode 100644 node_modules/mongodb/lib/index.js.map create mode 100644 node_modules/mongodb/lib/logger.js create mode 100644 node_modules/mongodb/lib/logger.js.map create mode 100644 node_modules/mongodb/lib/mongo_client.js create mode 100644 node_modules/mongodb/lib/mongo_client.js.map create mode 100644 node_modules/mongodb/lib/mongo_types.js create mode 100644 node_modules/mongodb/lib/mongo_types.js.map create mode 100644 node_modules/mongodb/lib/operations/add_user.js create mode 100644 node_modules/mongodb/lib/operations/add_user.js.map create mode 100644 node_modules/mongodb/lib/operations/aggregate.js create mode 100644 node_modules/mongodb/lib/operations/aggregate.js.map create mode 100644 node_modules/mongodb/lib/operations/bulk_write.js create mode 100644 node_modules/mongodb/lib/operations/bulk_write.js.map create mode 100644 node_modules/mongodb/lib/operations/collections.js create mode 100644 node_modules/mongodb/lib/operations/collections.js.map create mode 100644 node_modules/mongodb/lib/operations/command.js create mode 100644 node_modules/mongodb/lib/operations/command.js.map create mode 100644 node_modules/mongodb/lib/operations/common_functions.js create mode 100644 node_modules/mongodb/lib/operations/common_functions.js.map create mode 100644 node_modules/mongodb/lib/operations/connect.js create mode 100644 node_modules/mongodb/lib/operations/connect.js.map create mode 100644 node_modules/mongodb/lib/operations/count.js create mode 100644 node_modules/mongodb/lib/operations/count.js.map create mode 100644 node_modules/mongodb/lib/operations/count_documents.js create mode 100644 node_modules/mongodb/lib/operations/count_documents.js.map create mode 100644 node_modules/mongodb/lib/operations/create_collection.js create mode 100644 node_modules/mongodb/lib/operations/create_collection.js.map create mode 100644 node_modules/mongodb/lib/operations/delete.js create mode 100644 node_modules/mongodb/lib/operations/delete.js.map create mode 100644 node_modules/mongodb/lib/operations/distinct.js create mode 100644 node_modules/mongodb/lib/operations/distinct.js.map create mode 100644 node_modules/mongodb/lib/operations/drop.js create mode 100644 node_modules/mongodb/lib/operations/drop.js.map create mode 100644 node_modules/mongodb/lib/operations/estimated_document_count.js create mode 100644 node_modules/mongodb/lib/operations/estimated_document_count.js.map create mode 100644 node_modules/mongodb/lib/operations/eval.js create mode 100644 node_modules/mongodb/lib/operations/eval.js.map create mode 100644 node_modules/mongodb/lib/operations/execute_operation.js create mode 100644 node_modules/mongodb/lib/operations/execute_operation.js.map create mode 100644 node_modules/mongodb/lib/operations/find.js create mode 100644 node_modules/mongodb/lib/operations/find.js.map create mode 100644 node_modules/mongodb/lib/operations/find_and_modify.js create mode 100644 node_modules/mongodb/lib/operations/find_and_modify.js.map create mode 100644 node_modules/mongodb/lib/operations/indexes.js create mode 100644 node_modules/mongodb/lib/operations/indexes.js.map create mode 100644 node_modules/mongodb/lib/operations/insert.js create mode 100644 node_modules/mongodb/lib/operations/insert.js.map create mode 100644 node_modules/mongodb/lib/operations/is_capped.js create mode 100644 node_modules/mongodb/lib/operations/is_capped.js.map create mode 100644 node_modules/mongodb/lib/operations/list_collections.js create mode 100644 node_modules/mongodb/lib/operations/list_collections.js.map create mode 100644 node_modules/mongodb/lib/operations/list_databases.js create mode 100644 node_modules/mongodb/lib/operations/list_databases.js.map create mode 100644 node_modules/mongodb/lib/operations/map_reduce.js create mode 100644 node_modules/mongodb/lib/operations/map_reduce.js.map create mode 100644 node_modules/mongodb/lib/operations/operation.js create mode 100644 node_modules/mongodb/lib/operations/operation.js.map create mode 100644 node_modules/mongodb/lib/operations/options_operation.js create mode 100644 node_modules/mongodb/lib/operations/options_operation.js.map create mode 100644 node_modules/mongodb/lib/operations/profiling_level.js create mode 100644 node_modules/mongodb/lib/operations/profiling_level.js.map create mode 100644 node_modules/mongodb/lib/operations/remove_user.js create mode 100644 node_modules/mongodb/lib/operations/remove_user.js.map create mode 100644 node_modules/mongodb/lib/operations/rename.js create mode 100644 node_modules/mongodb/lib/operations/rename.js.map create mode 100644 node_modules/mongodb/lib/operations/run_command.js create mode 100644 node_modules/mongodb/lib/operations/run_command.js.map create mode 100644 node_modules/mongodb/lib/operations/set_profiling_level.js create mode 100644 node_modules/mongodb/lib/operations/set_profiling_level.js.map create mode 100644 node_modules/mongodb/lib/operations/stats.js create mode 100644 node_modules/mongodb/lib/operations/stats.js.map create mode 100644 node_modules/mongodb/lib/operations/update.js create mode 100644 node_modules/mongodb/lib/operations/update.js.map create mode 100644 node_modules/mongodb/lib/operations/validate_collection.js create mode 100644 node_modules/mongodb/lib/operations/validate_collection.js.map create mode 100644 node_modules/mongodb/lib/promise_provider.js create mode 100644 node_modules/mongodb/lib/promise_provider.js.map create mode 100644 node_modules/mongodb/lib/read_concern.js create mode 100644 node_modules/mongodb/lib/read_concern.js.map create mode 100644 node_modules/mongodb/lib/read_preference.js create mode 100644 node_modules/mongodb/lib/read_preference.js.map create mode 100644 node_modules/mongodb/lib/sdam/common.js create mode 100644 node_modules/mongodb/lib/sdam/common.js.map create mode 100644 node_modules/mongodb/lib/sdam/events.js create mode 100644 node_modules/mongodb/lib/sdam/events.js.map create mode 100644 node_modules/mongodb/lib/sdam/monitor.js create mode 100644 node_modules/mongodb/lib/sdam/monitor.js.map create mode 100644 node_modules/mongodb/lib/sdam/server.js create mode 100644 node_modules/mongodb/lib/sdam/server.js.map create mode 100644 node_modules/mongodb/lib/sdam/server_description.js create mode 100644 node_modules/mongodb/lib/sdam/server_description.js.map create mode 100644 node_modules/mongodb/lib/sdam/server_selection.js create mode 100644 node_modules/mongodb/lib/sdam/server_selection.js.map create mode 100644 node_modules/mongodb/lib/sdam/srv_polling.js create mode 100644 node_modules/mongodb/lib/sdam/srv_polling.js.map create mode 100644 node_modules/mongodb/lib/sdam/topology.js create mode 100644 node_modules/mongodb/lib/sdam/topology.js.map create mode 100644 node_modules/mongodb/lib/sdam/topology_description.js create mode 100644 node_modules/mongodb/lib/sdam/topology_description.js.map create mode 100644 node_modules/mongodb/lib/sessions.js create mode 100644 node_modules/mongodb/lib/sessions.js.map create mode 100644 node_modules/mongodb/lib/sort.js create mode 100644 node_modules/mongodb/lib/sort.js.map create mode 100644 node_modules/mongodb/lib/transactions.js create mode 100644 node_modules/mongodb/lib/transactions.js.map create mode 100644 node_modules/mongodb/lib/utils.js create mode 100644 node_modules/mongodb/lib/utils.js.map create mode 100644 node_modules/mongodb/lib/write_concern.js create mode 100644 node_modules/mongodb/lib/write_concern.js.map create mode 100644 node_modules/mongodb/mongodb.d.ts create mode 100644 node_modules/mongodb/mongodb.ts34.d.ts create mode 100644 node_modules/mongodb/package.json create mode 100644 node_modules/mongodb/src/admin.ts create mode 100644 node_modules/mongodb/src/bson.ts create mode 100644 node_modules/mongodb/src/bulk/common.ts create mode 100644 node_modules/mongodb/src/bulk/ordered.ts create mode 100644 node_modules/mongodb/src/bulk/unordered.ts create mode 100644 node_modules/mongodb/src/change_stream.ts create mode 100644 node_modules/mongodb/src/cmap/auth/auth_provider.ts create mode 100644 node_modules/mongodb/src/cmap/auth/defaultAuthProviders.ts create mode 100644 node_modules/mongodb/src/cmap/auth/gssapi.ts create mode 100644 node_modules/mongodb/src/cmap/auth/mongo_credentials.ts create mode 100644 node_modules/mongodb/src/cmap/auth/mongocr.ts create mode 100644 node_modules/mongodb/src/cmap/auth/mongodb_aws.ts create mode 100644 node_modules/mongodb/src/cmap/auth/plain.ts create mode 100644 node_modules/mongodb/src/cmap/auth/scram.ts create mode 100644 node_modules/mongodb/src/cmap/auth/x509.ts create mode 100644 node_modules/mongodb/src/cmap/command_monitoring_events.ts create mode 100644 node_modules/mongodb/src/cmap/commands.ts create mode 100644 node_modules/mongodb/src/cmap/connect.ts create mode 100644 node_modules/mongodb/src/cmap/connection.ts create mode 100644 node_modules/mongodb/src/cmap/connection_pool.ts create mode 100644 node_modules/mongodb/src/cmap/connection_pool_events.ts create mode 100644 node_modules/mongodb/src/cmap/errors.ts create mode 100644 node_modules/mongodb/src/cmap/message_stream.ts create mode 100644 node_modules/mongodb/src/cmap/metrics.ts create mode 100644 node_modules/mongodb/src/cmap/stream_description.ts create mode 100644 node_modules/mongodb/src/cmap/wire_protocol/compression.ts create mode 100644 node_modules/mongodb/src/cmap/wire_protocol/constants.ts create mode 100644 node_modules/mongodb/src/cmap/wire_protocol/shared.ts create mode 100644 node_modules/mongodb/src/collection.ts create mode 100644 node_modules/mongodb/src/connection_string.ts create mode 100644 node_modules/mongodb/src/constants.ts create mode 100644 node_modules/mongodb/src/cursor/abstract_cursor.ts create mode 100644 node_modules/mongodb/src/cursor/aggregation_cursor.ts create mode 100644 node_modules/mongodb/src/cursor/find_cursor.ts create mode 100644 node_modules/mongodb/src/db.ts create mode 100644 node_modules/mongodb/src/deps.ts create mode 100644 node_modules/mongodb/src/encrypter.ts create mode 100644 node_modules/mongodb/src/error.ts create mode 100644 node_modules/mongodb/src/explain.ts create mode 100644 node_modules/mongodb/src/gridfs/download.ts create mode 100644 node_modules/mongodb/src/gridfs/index.ts create mode 100644 node_modules/mongodb/src/gridfs/upload.ts create mode 100644 node_modules/mongodb/src/index.ts create mode 100644 node_modules/mongodb/src/logger.ts create mode 100644 node_modules/mongodb/src/mongo_client.ts create mode 100644 node_modules/mongodb/src/mongo_types.ts create mode 100644 node_modules/mongodb/src/operations/add_user.ts create mode 100644 node_modules/mongodb/src/operations/aggregate.ts create mode 100644 node_modules/mongodb/src/operations/bulk_write.ts create mode 100644 node_modules/mongodb/src/operations/collections.ts create mode 100644 node_modules/mongodb/src/operations/command.ts create mode 100644 node_modules/mongodb/src/operations/common_functions.ts create mode 100644 node_modules/mongodb/src/operations/connect.ts create mode 100644 node_modules/mongodb/src/operations/count.ts create mode 100644 node_modules/mongodb/src/operations/count_documents.ts create mode 100644 node_modules/mongodb/src/operations/create_collection.ts create mode 100644 node_modules/mongodb/src/operations/delete.ts create mode 100644 node_modules/mongodb/src/operations/distinct.ts create mode 100644 node_modules/mongodb/src/operations/drop.ts create mode 100644 node_modules/mongodb/src/operations/estimated_document_count.ts create mode 100644 node_modules/mongodb/src/operations/eval.ts create mode 100644 node_modules/mongodb/src/operations/execute_operation.ts create mode 100644 node_modules/mongodb/src/operations/find.ts create mode 100644 node_modules/mongodb/src/operations/find_and_modify.ts create mode 100644 node_modules/mongodb/src/operations/indexes.ts create mode 100644 node_modules/mongodb/src/operations/insert.ts create mode 100644 node_modules/mongodb/src/operations/is_capped.ts create mode 100644 node_modules/mongodb/src/operations/list_collections.ts create mode 100644 node_modules/mongodb/src/operations/list_databases.ts create mode 100644 node_modules/mongodb/src/operations/map_reduce.ts create mode 100644 node_modules/mongodb/src/operations/operation.ts create mode 100644 node_modules/mongodb/src/operations/options_operation.ts create mode 100644 node_modules/mongodb/src/operations/profiling_level.ts create mode 100644 node_modules/mongodb/src/operations/remove_user.ts create mode 100644 node_modules/mongodb/src/operations/rename.ts create mode 100644 node_modules/mongodb/src/operations/run_command.ts create mode 100644 node_modules/mongodb/src/operations/set_profiling_level.ts create mode 100644 node_modules/mongodb/src/operations/stats.ts create mode 100644 node_modules/mongodb/src/operations/update.ts create mode 100644 node_modules/mongodb/src/operations/validate_collection.ts create mode 100644 node_modules/mongodb/src/promise_provider.ts create mode 100644 node_modules/mongodb/src/read_concern.ts create mode 100644 node_modules/mongodb/src/read_preference.ts create mode 100644 node_modules/mongodb/src/sdam/common.ts create mode 100644 node_modules/mongodb/src/sdam/events.ts create mode 100644 node_modules/mongodb/src/sdam/monitor.ts create mode 100644 node_modules/mongodb/src/sdam/server.ts create mode 100644 node_modules/mongodb/src/sdam/server_description.ts create mode 100644 node_modules/mongodb/src/sdam/server_selection.ts create mode 100644 node_modules/mongodb/src/sdam/srv_polling.ts create mode 100644 node_modules/mongodb/src/sdam/topology.ts create mode 100644 node_modules/mongodb/src/sdam/topology_description.ts create mode 100644 node_modules/mongodb/src/sessions.ts create mode 100644 node_modules/mongodb/src/sort.ts create mode 100644 node_modules/mongodb/src/transactions.ts create mode 100644 node_modules/mongodb/src/utils.ts create mode 100644 node_modules/mongodb/src/write_concern.ts create mode 100644 node_modules/mongoose/LICENSE.md create mode 100644 node_modules/mongoose/README.md create mode 100644 node_modules/mongoose/SECURITY.md create mode 100644 node_modules/mongoose/browser.js create mode 100644 node_modules/mongoose/build-browser.js create mode 100644 node_modules/mongoose/dist/browser.umd.js create mode 100644 node_modules/mongoose/index.d.ts create mode 100644 node_modules/mongoose/index.js create mode 100644 node_modules/mongoose/lib/aggregate.js create mode 100644 node_modules/mongoose/lib/browser.js create mode 100644 node_modules/mongoose/lib/browserDocument.js create mode 100644 node_modules/mongoose/lib/cast.js create mode 100644 node_modules/mongoose/lib/cast/boolean.js create mode 100644 node_modules/mongoose/lib/cast/date.js create mode 100644 node_modules/mongoose/lib/cast/decimal128.js create mode 100644 node_modules/mongoose/lib/cast/number.js create mode 100644 node_modules/mongoose/lib/cast/objectid.js create mode 100644 node_modules/mongoose/lib/cast/string.js create mode 100644 node_modules/mongoose/lib/collection.js create mode 100644 node_modules/mongoose/lib/connection.js create mode 100644 node_modules/mongoose/lib/connectionstate.js create mode 100644 node_modules/mongoose/lib/cursor/AggregationCursor.js create mode 100644 node_modules/mongoose/lib/cursor/ChangeStream.js create mode 100644 node_modules/mongoose/lib/cursor/QueryCursor.js create mode 100644 node_modules/mongoose/lib/document.js create mode 100644 node_modules/mongoose/lib/document_provider.js create mode 100644 node_modules/mongoose/lib/driver.js create mode 100644 node_modules/mongoose/lib/drivers/SPEC.md create mode 100644 node_modules/mongoose/lib/drivers/browser/ReadPreference.js create mode 100644 node_modules/mongoose/lib/drivers/browser/binary.js create mode 100644 node_modules/mongoose/lib/drivers/browser/decimal128.js create mode 100644 node_modules/mongoose/lib/drivers/browser/index.js create mode 100644 node_modules/mongoose/lib/drivers/browser/objectid.js create mode 100644 node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js create mode 100644 node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js create mode 100644 node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js create mode 100644 node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js create mode 100644 node_modules/mongoose/lib/drivers/node-mongodb-native/decimal128.js create mode 100644 node_modules/mongoose/lib/drivers/node-mongodb-native/index.js create mode 100644 node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js create mode 100644 node_modules/mongoose/lib/error/browserMissingSchema.js create mode 100644 node_modules/mongoose/lib/error/cast.js create mode 100644 node_modules/mongoose/lib/error/disconnected.js create mode 100644 node_modules/mongoose/lib/error/divergentArray.js create mode 100644 node_modules/mongoose/lib/error/index.js create mode 100644 node_modules/mongoose/lib/error/messages.js create mode 100644 node_modules/mongoose/lib/error/missingSchema.js create mode 100644 node_modules/mongoose/lib/error/mongooseError.js create mode 100644 node_modules/mongoose/lib/error/notFound.js create mode 100644 node_modules/mongoose/lib/error/objectExpected.js create mode 100644 node_modules/mongoose/lib/error/objectParameter.js create mode 100644 node_modules/mongoose/lib/error/overwriteModel.js create mode 100644 node_modules/mongoose/lib/error/parallelSave.js create mode 100644 node_modules/mongoose/lib/error/parallelValidate.js create mode 100644 node_modules/mongoose/lib/error/serverSelection.js create mode 100644 node_modules/mongoose/lib/error/strict.js create mode 100644 node_modules/mongoose/lib/error/validation.js create mode 100644 node_modules/mongoose/lib/error/validator.js create mode 100644 node_modules/mongoose/lib/error/version.js create mode 100644 node_modules/mongoose/lib/helpers/aggregate/stringifyFunctionOperators.js create mode 100644 node_modules/mongoose/lib/helpers/arrayDepth.js create mode 100644 node_modules/mongoose/lib/helpers/clone.js create mode 100644 node_modules/mongoose/lib/helpers/common.js create mode 100644 node_modules/mongoose/lib/helpers/cursor/eachAsync.js create mode 100644 node_modules/mongoose/lib/helpers/discriminator/areDiscriminatorValuesEqual.js create mode 100644 node_modules/mongoose/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js create mode 100644 node_modules/mongoose/lib/helpers/discriminator/getConstructor.js create mode 100644 node_modules/mongoose/lib/helpers/discriminator/getDiscriminatorByValue.js create mode 100644 node_modules/mongoose/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js create mode 100644 node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js create mode 100644 node_modules/mongoose/lib/helpers/document/compile.js create mode 100644 node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js create mode 100644 node_modules/mongoose/lib/helpers/document/handleSpreadDoc.js create mode 100644 node_modules/mongoose/lib/helpers/each.js create mode 100644 node_modules/mongoose/lib/helpers/get.js create mode 100644 node_modules/mongoose/lib/helpers/getConstructorName.js create mode 100644 node_modules/mongoose/lib/helpers/getDefaultBulkwriteResult.js create mode 100644 node_modules/mongoose/lib/helpers/getFunctionName.js create mode 100644 node_modules/mongoose/lib/helpers/immediate.js create mode 100644 node_modules/mongoose/lib/helpers/indexes/isDefaultIdIndex.js create mode 100644 node_modules/mongoose/lib/helpers/indexes/isIndexEqual.js create mode 100644 node_modules/mongoose/lib/helpers/isAsyncFunction.js create mode 100644 node_modules/mongoose/lib/helpers/isBsonType.js create mode 100644 node_modules/mongoose/lib/helpers/isMongooseObject.js create mode 100644 node_modules/mongoose/lib/helpers/isObject.js create mode 100644 node_modules/mongoose/lib/helpers/isPromise.js create mode 100644 node_modules/mongoose/lib/helpers/model/applyHooks.js create mode 100644 node_modules/mongoose/lib/helpers/model/applyMethods.js create mode 100644 node_modules/mongoose/lib/helpers/model/applyStaticHooks.js create mode 100644 node_modules/mongoose/lib/helpers/model/applyStatics.js create mode 100644 node_modules/mongoose/lib/helpers/model/castBulkWrite.js create mode 100644 node_modules/mongoose/lib/helpers/model/discriminator.js create mode 100644 node_modules/mongoose/lib/helpers/once.js create mode 100644 node_modules/mongoose/lib/helpers/parallelLimit.js create mode 100644 node_modules/mongoose/lib/helpers/path/flattenObjectWithDottedPaths.js create mode 100644 node_modules/mongoose/lib/helpers/path/parentPaths.js create mode 100644 node_modules/mongoose/lib/helpers/path/setDottedPath.js create mode 100644 node_modules/mongoose/lib/helpers/pluralize.js create mode 100644 node_modules/mongoose/lib/helpers/populate/SkipPopulateValue.js create mode 100644 node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js create mode 100644 node_modules/mongoose/lib/helpers/populate/assignVals.js create mode 100644 node_modules/mongoose/lib/helpers/populate/createPopulateQueryFilter.js create mode 100644 node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js create mode 100644 node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js create mode 100644 node_modules/mongoose/lib/helpers/populate/getVirtual.js create mode 100644 node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js create mode 100644 node_modules/mongoose/lib/helpers/populate/lookupLocalFields.js create mode 100644 node_modules/mongoose/lib/helpers/populate/markArraySubdocsPopulated.js create mode 100644 node_modules/mongoose/lib/helpers/populate/modelNamesFromRefPath.js create mode 100644 node_modules/mongoose/lib/helpers/populate/removeDeselectedForeignField.js create mode 100644 node_modules/mongoose/lib/helpers/populate/validateRef.js create mode 100644 node_modules/mongoose/lib/helpers/printJestWarning.js create mode 100644 node_modules/mongoose/lib/helpers/processConnectionOptions.js create mode 100644 node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js create mode 100644 node_modules/mongoose/lib/helpers/projection/isExclusive.js create mode 100644 node_modules/mongoose/lib/helpers/projection/isInclusive.js create mode 100644 node_modules/mongoose/lib/helpers/projection/isPathExcluded.js create mode 100644 node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js create mode 100644 node_modules/mongoose/lib/helpers/projection/parseProjection.js create mode 100644 node_modules/mongoose/lib/helpers/promiseOrCallback.js create mode 100644 node_modules/mongoose/lib/helpers/query/applyGlobalMaxTimeMS.js create mode 100644 node_modules/mongoose/lib/helpers/query/applyQueryMiddleware.js create mode 100644 node_modules/mongoose/lib/helpers/query/castFilterPath.js create mode 100644 node_modules/mongoose/lib/helpers/query/castUpdate.js create mode 100644 node_modules/mongoose/lib/helpers/query/completeMany.js create mode 100644 node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js create mode 100644 node_modules/mongoose/lib/helpers/query/handleImmutable.js create mode 100644 node_modules/mongoose/lib/helpers/query/hasDollarKeys.js create mode 100644 node_modules/mongoose/lib/helpers/query/isOperator.js create mode 100644 node_modules/mongoose/lib/helpers/query/sanitizeFilter.js create mode 100644 node_modules/mongoose/lib/helpers/query/sanitizeProjection.js create mode 100644 node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js create mode 100644 node_modules/mongoose/lib/helpers/query/trusted.js create mode 100644 node_modules/mongoose/lib/helpers/query/validOps.js create mode 100644 node_modules/mongoose/lib/helpers/query/wrapThunk.js create mode 100644 node_modules/mongoose/lib/helpers/schema/addAutoId.js create mode 100644 node_modules/mongoose/lib/helpers/schema/applyPlugins.js create mode 100644 node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js create mode 100644 node_modules/mongoose/lib/helpers/schema/cleanPositionalOperators.js create mode 100644 node_modules/mongoose/lib/helpers/schema/getIndexes.js create mode 100644 node_modules/mongoose/lib/helpers/schema/getKeysInSchemaOrder.js create mode 100644 node_modules/mongoose/lib/helpers/schema/getPath.js create mode 100644 node_modules/mongoose/lib/helpers/schema/handleIdOption.js create mode 100644 node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js create mode 100644 node_modules/mongoose/lib/helpers/schema/idGetter.js create mode 100644 node_modules/mongoose/lib/helpers/schema/merge.js create mode 100644 node_modules/mongoose/lib/helpers/schematype/handleImmutable.js create mode 100644 node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js create mode 100644 node_modules/mongoose/lib/helpers/specialProperties.js create mode 100644 node_modules/mongoose/lib/helpers/symbols.js create mode 100644 node_modules/mongoose/lib/helpers/timers.js create mode 100644 node_modules/mongoose/lib/helpers/timestamps/setupTimestamps.js create mode 100644 node_modules/mongoose/lib/helpers/topology/allServersUnknown.js create mode 100644 node_modules/mongoose/lib/helpers/topology/isAtlas.js create mode 100644 node_modules/mongoose/lib/helpers/topology/isSSLError.js create mode 100644 node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js create mode 100644 node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js create mode 100644 node_modules/mongoose/lib/helpers/update/castArrayFilters.js create mode 100644 node_modules/mongoose/lib/helpers/update/modifiedPaths.js create mode 100644 node_modules/mongoose/lib/helpers/update/moveImmutableProperties.js create mode 100644 node_modules/mongoose/lib/helpers/update/removeUnusedArrayFilters.js create mode 100644 node_modules/mongoose/lib/helpers/update/updatedPathsByArrayFilter.js create mode 100644 node_modules/mongoose/lib/helpers/updateValidators.js create mode 100644 node_modules/mongoose/lib/index.js create mode 100644 node_modules/mongoose/lib/internal.js create mode 100644 node_modules/mongoose/lib/model.js create mode 100644 node_modules/mongoose/lib/options.js create mode 100644 node_modules/mongoose/lib/options/PopulateOptions.js create mode 100644 node_modules/mongoose/lib/options/SchemaArrayOptions.js create mode 100644 node_modules/mongoose/lib/options/SchemaBufferOptions.js create mode 100644 node_modules/mongoose/lib/options/SchemaDateOptions.js create mode 100644 node_modules/mongoose/lib/options/SchemaDocumentArrayOptions.js create mode 100644 node_modules/mongoose/lib/options/SchemaMapOptions.js create mode 100644 node_modules/mongoose/lib/options/SchemaNumberOptions.js create mode 100644 node_modules/mongoose/lib/options/SchemaObjectIdOptions.js create mode 100644 node_modules/mongoose/lib/options/SchemaStringOptions.js create mode 100644 node_modules/mongoose/lib/options/SchemaSubdocumentOptions.js create mode 100644 node_modules/mongoose/lib/options/SchemaTypeOptions.js create mode 100644 node_modules/mongoose/lib/options/VirtualOptions.js create mode 100644 node_modules/mongoose/lib/options/propertyOptions.js create mode 100644 node_modules/mongoose/lib/options/removeOptions.js create mode 100644 node_modules/mongoose/lib/options/saveOptions.js create mode 100644 node_modules/mongoose/lib/plugins/removeSubdocs.js create mode 100644 node_modules/mongoose/lib/plugins/saveSubdocs.js create mode 100644 node_modules/mongoose/lib/plugins/sharding.js create mode 100644 node_modules/mongoose/lib/plugins/trackTransaction.js create mode 100644 node_modules/mongoose/lib/plugins/validateBeforeSave.js create mode 100644 node_modules/mongoose/lib/promise_provider.js create mode 100644 node_modules/mongoose/lib/query.js create mode 100644 node_modules/mongoose/lib/queryhelpers.js create mode 100644 node_modules/mongoose/lib/schema.js create mode 100644 node_modules/mongoose/lib/schema/SubdocumentPath.js create mode 100644 node_modules/mongoose/lib/schema/array.js create mode 100644 node_modules/mongoose/lib/schema/boolean.js create mode 100644 node_modules/mongoose/lib/schema/buffer.js create mode 100644 node_modules/mongoose/lib/schema/date.js create mode 100644 node_modules/mongoose/lib/schema/decimal128.js create mode 100644 node_modules/mongoose/lib/schema/documentarray.js create mode 100644 node_modules/mongoose/lib/schema/index.js create mode 100644 node_modules/mongoose/lib/schema/map.js create mode 100644 node_modules/mongoose/lib/schema/mixed.js create mode 100644 node_modules/mongoose/lib/schema/number.js create mode 100644 node_modules/mongoose/lib/schema/objectid.js create mode 100644 node_modules/mongoose/lib/schema/operators/bitwise.js create mode 100644 node_modules/mongoose/lib/schema/operators/exists.js create mode 100644 node_modules/mongoose/lib/schema/operators/geospatial.js create mode 100644 node_modules/mongoose/lib/schema/operators/helpers.js create mode 100644 node_modules/mongoose/lib/schema/operators/text.js create mode 100644 node_modules/mongoose/lib/schema/operators/type.js create mode 100644 node_modules/mongoose/lib/schema/string.js create mode 100644 node_modules/mongoose/lib/schema/symbols.js create mode 100644 node_modules/mongoose/lib/schematype.js create mode 100644 node_modules/mongoose/lib/statemachine.js create mode 100644 node_modules/mongoose/lib/types/ArraySubdocument.js create mode 100644 node_modules/mongoose/lib/types/DocumentArray/index.js create mode 100644 node_modules/mongoose/lib/types/DocumentArray/methods/index.js create mode 100644 node_modules/mongoose/lib/types/array/ArrayWrapper.js create mode 100644 node_modules/mongoose/lib/types/array/index.js create mode 100644 node_modules/mongoose/lib/types/array/methods/index.js create mode 100644 node_modules/mongoose/lib/types/buffer.js create mode 100644 node_modules/mongoose/lib/types/decimal128.js create mode 100644 node_modules/mongoose/lib/types/index.js create mode 100644 node_modules/mongoose/lib/types/map.js create mode 100644 node_modules/mongoose/lib/types/objectid.js create mode 100644 node_modules/mongoose/lib/types/subdocument.js create mode 100644 node_modules/mongoose/lib/utils.js create mode 100644 node_modules/mongoose/lib/validoptions.js create mode 100644 node_modules/mongoose/lib/virtualtype.js create mode 100644 node_modules/mongoose/node_modules/ms/index.js create mode 100644 node_modules/mongoose/node_modules/ms/license.md create mode 100644 node_modules/mongoose/node_modules/ms/package.json create mode 100644 node_modules/mongoose/node_modules/ms/readme.md create mode 100644 node_modules/mongoose/package.json create mode 100644 node_modules/mongoose/tools/auth.js create mode 100644 node_modules/mongoose/tools/repl.js create mode 100644 node_modules/mongoose/tools/sharded.js create mode 100644 node_modules/mpath/.travis.yml create mode 100644 node_modules/mpath/History.md create mode 100644 node_modules/mpath/LICENSE create mode 100644 node_modules/mpath/Makefile create mode 100644 node_modules/mpath/README.md create mode 100644 node_modules/mpath/SECURITY.md create mode 100644 node_modules/mpath/bench.js create mode 100644 node_modules/mpath/bench.log create mode 100644 node_modules/mpath/bench.out create mode 100644 node_modules/mpath/index.js create mode 100644 node_modules/mpath/lib/index.js create mode 100644 node_modules/mpath/lib/stringToParts.js create mode 100644 node_modules/mpath/package.json create mode 100644 node_modules/mpath/test/.eslintrc.yml create mode 100644 node_modules/mpath/test/index.js create mode 100644 node_modules/mpath/test/stringToParts.js create mode 100644 node_modules/mquery/.eslintignore create mode 100644 node_modules/mquery/.eslintrc.json create mode 100644 node_modules/mquery/.travis.yml create mode 100644 node_modules/mquery/History.md create mode 100644 node_modules/mquery/LICENSE create mode 100644 node_modules/mquery/Makefile create mode 100644 node_modules/mquery/README.md create mode 100644 node_modules/mquery/SECURITY.md create mode 100644 node_modules/mquery/lib/collection/collection.js create mode 100644 node_modules/mquery/lib/collection/index.js create mode 100644 node_modules/mquery/lib/collection/node.js create mode 100644 node_modules/mquery/lib/env.js create mode 100644 node_modules/mquery/lib/mquery.js create mode 100644 node_modules/mquery/lib/permissions.js create mode 100644 node_modules/mquery/lib/utils.js create mode 100644 node_modules/mquery/node_modules/debug/LICENSE create mode 100644 node_modules/mquery/node_modules/debug/README.md create mode 100644 node_modules/mquery/node_modules/debug/package.json create mode 100644 node_modules/mquery/node_modules/debug/src/browser.js create mode 100644 node_modules/mquery/node_modules/debug/src/common.js create mode 100644 node_modules/mquery/node_modules/debug/src/index.js create mode 100644 node_modules/mquery/node_modules/debug/src/node.js create mode 100644 node_modules/mquery/node_modules/ms/index.js create mode 100644 node_modules/mquery/node_modules/ms/license.md create mode 100644 node_modules/mquery/node_modules/ms/package.json create mode 100644 node_modules/mquery/node_modules/ms/readme.md create mode 100644 node_modules/mquery/package.json create mode 100644 node_modules/mquery/test/.eslintrc.yml create mode 100644 node_modules/mquery/test/collection/browser.js create mode 100644 node_modules/mquery/test/collection/mongo.js create mode 100644 node_modules/mquery/test/collection/node.js create mode 100644 node_modules/mquery/test/env.js create mode 100644 node_modules/mquery/test/index.js create mode 100644 node_modules/mquery/test/utils.test.js create mode 100644 node_modules/ms/index.js create mode 100644 node_modules/ms/license.md create mode 100644 node_modules/ms/package.json create mode 100644 node_modules/ms/readme.md create mode 100644 node_modules/negotiator/HISTORY.md create mode 100644 node_modules/negotiator/LICENSE create mode 100644 node_modules/negotiator/README.md create mode 100644 node_modules/negotiator/index.js create mode 100644 node_modules/negotiator/lib/charset.js create mode 100644 node_modules/negotiator/lib/encoding.js create mode 100644 node_modules/negotiator/lib/language.js create mode 100644 node_modules/negotiator/lib/mediaType.js create mode 100644 node_modules/negotiator/package.json create mode 100644 node_modules/node-addon-api/CHANGELOG.md create mode 100644 node_modules/node-addon-api/LICENSE.md create mode 100644 node_modules/node-addon-api/README.md create mode 100644 node_modules/node-addon-api/common.gypi create mode 100644 node_modules/node-addon-api/except.gypi create mode 100644 node_modules/node-addon-api/index.js create mode 100644 node_modules/node-addon-api/napi-inl.deprecated.h create mode 100644 node_modules/node-addon-api/napi-inl.h create mode 100644 node_modules/node-addon-api/napi.h create mode 100644 node_modules/node-addon-api/node_api.gyp create mode 100644 node_modules/node-addon-api/noexcept.gypi create mode 100644 node_modules/node-addon-api/nothing.c create mode 100644 node_modules/node-addon-api/package-support.json create mode 100644 node_modules/node-addon-api/package.json create mode 100644 node_modules/node-addon-api/tools/README.md create mode 100644 node_modules/node-addon-api/tools/check-napi.js create mode 100644 node_modules/node-addon-api/tools/clang-format.js create mode 100644 node_modules/node-addon-api/tools/conversion.js create mode 100644 node_modules/node-fetch/LICENSE.md create mode 100644 node_modules/node-fetch/README.md create mode 100644 node_modules/node-fetch/browser.js create mode 100644 node_modules/node-fetch/lib/index.es.js create mode 100644 node_modules/node-fetch/lib/index.js create mode 100644 node_modules/node-fetch/lib/index.mjs create mode 100644 node_modules/node-fetch/node_modules/tr46/.npmignore create mode 100644 node_modules/node-fetch/node_modules/tr46/index.js create mode 100644 node_modules/node-fetch/node_modules/tr46/lib/.gitkeep create mode 100644 node_modules/node-fetch/node_modules/tr46/lib/mappingTable.json create mode 100644 node_modules/node-fetch/node_modules/tr46/package.json create mode 100644 node_modules/node-fetch/node_modules/webidl-conversions/LICENSE.md create mode 100644 node_modules/node-fetch/node_modules/webidl-conversions/README.md create mode 100644 node_modules/node-fetch/node_modules/webidl-conversions/lib/index.js create mode 100644 node_modules/node-fetch/node_modules/webidl-conversions/package.json create mode 100644 node_modules/node-fetch/node_modules/whatwg-url/LICENSE.txt create mode 100644 node_modules/node-fetch/node_modules/whatwg-url/README.md create mode 100644 node_modules/node-fetch/node_modules/whatwg-url/lib/URL-impl.js create mode 100644 node_modules/node-fetch/node_modules/whatwg-url/lib/URL.js create mode 100644 node_modules/node-fetch/node_modules/whatwg-url/lib/public-api.js create mode 100644 node_modules/node-fetch/node_modules/whatwg-url/lib/url-state-machine.js create mode 100644 node_modules/node-fetch/node_modules/whatwg-url/lib/utils.js create mode 100644 node_modules/node-fetch/node_modules/whatwg-url/package.json create mode 100644 node_modules/node-fetch/package.json create mode 100644 node_modules/nopt/CHANGELOG.md create mode 100644 node_modules/nopt/LICENSE create mode 100644 node_modules/nopt/README.md create mode 100644 node_modules/nopt/bin/nopt.js create mode 100644 node_modules/nopt/lib/nopt.js create mode 100644 node_modules/nopt/package.json create mode 100644 node_modules/npmlog/LICENSE create mode 100644 node_modules/npmlog/README.md create mode 100644 node_modules/npmlog/log.js create mode 100644 node_modules/npmlog/package.json create mode 100644 node_modules/object-assign/index.js create mode 100644 node_modules/object-assign/license create mode 100644 node_modules/object-assign/package.json create mode 100644 node_modules/object-assign/readme.md create mode 100644 node_modules/on-finished/HISTORY.md create mode 100644 node_modules/on-finished/LICENSE create mode 100644 node_modules/on-finished/README.md create mode 100644 node_modules/on-finished/index.js create mode 100644 node_modules/on-finished/package.json create mode 100644 node_modules/once/LICENSE create mode 100644 node_modules/once/README.md create mode 100644 node_modules/once/once.js create mode 100644 node_modules/once/package.json create mode 100644 node_modules/parseurl/HISTORY.md create mode 100644 node_modules/parseurl/LICENSE create mode 100644 node_modules/parseurl/README.md create mode 100644 node_modules/parseurl/index.js create mode 100644 node_modules/parseurl/package.json create mode 100644 node_modules/passport-jwt/.travis.yml create mode 100644 node_modules/passport-jwt/LICENSE create mode 100644 node_modules/passport-jwt/README.md create mode 100644 node_modules/passport-jwt/docs/migrating.md create mode 100644 node_modules/passport-jwt/lib/auth_header.js create mode 100644 node_modules/passport-jwt/lib/extract_jwt.js create mode 100644 node_modules/passport-jwt/lib/helpers/assign.js create mode 100644 node_modules/passport-jwt/lib/index.js create mode 100644 node_modules/passport-jwt/lib/strategy.js create mode 100644 node_modules/passport-jwt/lib/verify_jwt.js create mode 100644 node_modules/passport-jwt/package.json create mode 100644 node_modules/passport-jwt/test/auth_header-test.js create mode 100644 node_modules/passport-jwt/test/bootstrap.js create mode 100644 node_modules/passport-jwt/test/extrators-test.js create mode 100644 node_modules/passport-jwt/test/mock_request.js create mode 100644 node_modules/passport-jwt/test/strategy-init-test.js create mode 100644 node_modules/passport-jwt/test/strategy-requests-test.js create mode 100644 node_modules/passport-jwt/test/strategy-validation-test.js create mode 100644 node_modules/passport-jwt/test/strategy-verify-test.js create mode 100644 node_modules/passport-jwt/test/testdata.js create mode 100644 node_modules/passport-strategy/.jshintrc create mode 100644 node_modules/passport-strategy/.travis.yml create mode 100644 node_modules/passport-strategy/LICENSE create mode 100644 node_modules/passport-strategy/README.md create mode 100644 node_modules/passport-strategy/lib/index.js create mode 100644 node_modules/passport-strategy/lib/strategy.js create mode 100644 node_modules/passport-strategy/package.json create mode 100644 node_modules/passport/CHANGELOG.md create mode 100644 node_modules/passport/LICENSE create mode 100644 node_modules/passport/README.md create mode 100644 node_modules/passport/lib/authenticator.js create mode 100644 node_modules/passport/lib/errors/authenticationerror.js create mode 100644 node_modules/passport/lib/framework/connect.js create mode 100644 node_modules/passport/lib/http/request.js create mode 100644 node_modules/passport/lib/index.js create mode 100644 node_modules/passport/lib/middleware/authenticate.js create mode 100644 node_modules/passport/lib/middleware/initialize.js create mode 100644 node_modules/passport/lib/sessionmanager.js create mode 100644 node_modules/passport/lib/strategies/session.js create mode 100644 node_modules/passport/package.json create mode 100644 node_modules/passport/sponsors/loginradius.png create mode 100644 node_modules/passport/sponsors/workos.png create mode 100644 node_modules/path-is-absolute/index.js create mode 100644 node_modules/path-is-absolute/license create mode 100644 node_modules/path-is-absolute/package.json create mode 100644 node_modules/path-is-absolute/readme.md create mode 100644 node_modules/path-to-regexp/History.md create mode 100644 node_modules/path-to-regexp/LICENSE create mode 100644 node_modules/path-to-regexp/Readme.md create mode 100644 node_modules/path-to-regexp/index.js create mode 100644 node_modules/path-to-regexp/package.json create mode 100644 node_modules/pause/.npmignore create mode 100644 node_modules/pause/History.md create mode 100644 node_modules/pause/Makefile create mode 100644 node_modules/pause/Readme.md create mode 100644 node_modules/pause/index.js create mode 100644 node_modules/pause/package.json create mode 100644 node_modules/proxy-addr/HISTORY.md create mode 100644 node_modules/proxy-addr/LICENSE create mode 100644 node_modules/proxy-addr/README.md create mode 100644 node_modules/proxy-addr/index.js create mode 100644 node_modules/proxy-addr/package.json create mode 100644 node_modules/punycode/LICENSE-MIT.txt create mode 100644 node_modules/punycode/README.md create mode 100644 node_modules/punycode/package.json create mode 100644 node_modules/punycode/punycode.es6.js create mode 100644 node_modules/punycode/punycode.js create mode 100644 node_modules/qs/.editorconfig create mode 100644 node_modules/qs/.eslintignore create mode 100644 node_modules/qs/.eslintrc create mode 100644 node_modules/qs/CHANGELOG.md create mode 100644 node_modules/qs/LICENSE create mode 100644 node_modules/qs/README.md create mode 100644 node_modules/qs/dist/qs.js create mode 100644 node_modules/qs/lib/formats.js create mode 100644 node_modules/qs/lib/index.js create mode 100644 node_modules/qs/lib/parse.js create mode 100644 node_modules/qs/lib/stringify.js create mode 100644 node_modules/qs/lib/utils.js create mode 100644 node_modules/qs/package.json create mode 100644 node_modules/qs/test/.eslintrc create mode 100644 node_modules/qs/test/index.js create mode 100644 node_modules/qs/test/parse.js create mode 100644 node_modules/qs/test/stringify.js create mode 100644 node_modules/qs/test/utils.js create mode 100644 node_modules/range-parser/HISTORY.md create mode 100644 node_modules/range-parser/LICENSE create mode 100644 node_modules/range-parser/README.md create mode 100644 node_modules/range-parser/index.js create mode 100644 node_modules/range-parser/package.json create mode 100644 node_modules/raw-body/HISTORY.md create mode 100644 node_modules/raw-body/LICENSE create mode 100644 node_modules/raw-body/README.md create mode 100644 node_modules/raw-body/index.d.ts create mode 100644 node_modules/raw-body/index.js create mode 100644 node_modules/raw-body/package.json create mode 100644 node_modules/readable-stream/CONTRIBUTING.md create mode 100644 node_modules/readable-stream/GOVERNANCE.md create mode 100644 node_modules/readable-stream/LICENSE create mode 100644 node_modules/readable-stream/README.md create mode 100644 node_modules/readable-stream/errors-browser.js create mode 100644 node_modules/readable-stream/errors.js create mode 100644 node_modules/readable-stream/experimentalWarning.js create mode 100644 node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 node_modules/readable-stream/lib/_stream_readable.js create mode 100644 node_modules/readable-stream/lib/_stream_transform.js create mode 100644 node_modules/readable-stream/lib/_stream_writable.js create mode 100644 node_modules/readable-stream/lib/internal/streams/async_iterator.js create mode 100644 node_modules/readable-stream/lib/internal/streams/buffer_list.js create mode 100644 node_modules/readable-stream/lib/internal/streams/destroy.js create mode 100644 node_modules/readable-stream/lib/internal/streams/end-of-stream.js create mode 100644 node_modules/readable-stream/lib/internal/streams/from-browser.js create mode 100644 node_modules/readable-stream/lib/internal/streams/from.js create mode 100644 node_modules/readable-stream/lib/internal/streams/pipeline.js create mode 100644 node_modules/readable-stream/lib/internal/streams/state.js create mode 100644 node_modules/readable-stream/lib/internal/streams/stream-browser.js create mode 100644 node_modules/readable-stream/lib/internal/streams/stream.js create mode 100644 node_modules/readable-stream/package.json create mode 100644 node_modules/readable-stream/readable-browser.js create mode 100644 node_modules/readable-stream/readable.js create mode 100644 node_modules/regexp-clone/.travis.yml create mode 100644 node_modules/regexp-clone/History.md create mode 100644 node_modules/regexp-clone/LICENSE create mode 100644 node_modules/regexp-clone/Makefile create mode 100644 node_modules/regexp-clone/README.md create mode 100644 node_modules/regexp-clone/index.js create mode 100644 node_modules/regexp-clone/package.json create mode 100644 node_modules/regexp-clone/test/index.js create mode 100644 node_modules/rimraf/CHANGELOG.md create mode 100644 node_modules/rimraf/LICENSE create mode 100644 node_modules/rimraf/README.md create mode 100644 node_modules/rimraf/bin.js create mode 100644 node_modules/rimraf/package.json create mode 100644 node_modules/rimraf/rimraf.js create mode 100644 node_modules/safe-buffer/LICENSE create mode 100644 node_modules/safe-buffer/README.md create mode 100644 node_modules/safe-buffer/index.d.ts create mode 100644 node_modules/safe-buffer/index.js create mode 100644 node_modules/safe-buffer/package.json create mode 100644 node_modules/safer-buffer/LICENSE create mode 100644 node_modules/safer-buffer/Porting-Buffer.md create mode 100644 node_modules/safer-buffer/Readme.md create mode 100644 node_modules/safer-buffer/dangerous.js create mode 100644 node_modules/safer-buffer/package.json create mode 100644 node_modules/safer-buffer/safer.js create mode 100644 node_modules/safer-buffer/tests.js create mode 100644 node_modules/saslprep/.editorconfig create mode 100644 node_modules/saslprep/.gitattributes create mode 100644 node_modules/saslprep/.travis.yml create mode 100644 node_modules/saslprep/CHANGELOG.md create mode 100644 node_modules/saslprep/LICENSE create mode 100644 node_modules/saslprep/code-points.mem create mode 100644 node_modules/saslprep/generate-code-points.js create mode 100644 node_modules/saslprep/index.js create mode 100644 node_modules/saslprep/lib/code-points.js create mode 100644 node_modules/saslprep/lib/memory-code-points.js create mode 100644 node_modules/saslprep/lib/util.js create mode 100644 node_modules/saslprep/package.json create mode 100644 node_modules/saslprep/readme.md create mode 100644 node_modules/saslprep/test/index.js create mode 100644 node_modules/saslprep/test/util.js create mode 100644 node_modules/semver/CHANGELOG.md create mode 100644 node_modules/semver/LICENSE create mode 100644 node_modules/semver/README.md create mode 100644 node_modules/semver/bin/semver.js create mode 100644 node_modules/semver/classes/comparator.js create mode 100644 node_modules/semver/classes/index.js create mode 100644 node_modules/semver/classes/range.js create mode 100644 node_modules/semver/classes/semver.js create mode 100644 node_modules/semver/functions/clean.js create mode 100644 node_modules/semver/functions/cmp.js create mode 100644 node_modules/semver/functions/coerce.js create mode 100644 node_modules/semver/functions/compare-build.js create mode 100644 node_modules/semver/functions/compare-loose.js create mode 100644 node_modules/semver/functions/compare.js create mode 100644 node_modules/semver/functions/diff.js create mode 100644 node_modules/semver/functions/eq.js create mode 100644 node_modules/semver/functions/gt.js create mode 100644 node_modules/semver/functions/gte.js create mode 100644 node_modules/semver/functions/inc.js create mode 100644 node_modules/semver/functions/lt.js create mode 100644 node_modules/semver/functions/lte.js create mode 100644 node_modules/semver/functions/major.js create mode 100644 node_modules/semver/functions/minor.js create mode 100644 node_modules/semver/functions/neq.js create mode 100644 node_modules/semver/functions/parse.js create mode 100644 node_modules/semver/functions/patch.js create mode 100644 node_modules/semver/functions/prerelease.js create mode 100644 node_modules/semver/functions/rcompare.js create mode 100644 node_modules/semver/functions/rsort.js create mode 100644 node_modules/semver/functions/satisfies.js create mode 100644 node_modules/semver/functions/sort.js create mode 100644 node_modules/semver/functions/valid.js create mode 100644 node_modules/semver/index.js create mode 100644 node_modules/semver/internal/constants.js create mode 100644 node_modules/semver/internal/debug.js create mode 100644 node_modules/semver/internal/identifiers.js create mode 100644 node_modules/semver/internal/parse-options.js create mode 100644 node_modules/semver/internal/re.js create mode 100644 node_modules/semver/package.json create mode 100644 node_modules/semver/preload.js create mode 100644 node_modules/semver/range.bnf create mode 100644 node_modules/semver/ranges/gtr.js create mode 100644 node_modules/semver/ranges/intersects.js create mode 100644 node_modules/semver/ranges/ltr.js create mode 100644 node_modules/semver/ranges/max-satisfying.js create mode 100644 node_modules/semver/ranges/min-satisfying.js create mode 100644 node_modules/semver/ranges/min-version.js create mode 100644 node_modules/semver/ranges/outside.js create mode 100644 node_modules/semver/ranges/simplify.js create mode 100644 node_modules/semver/ranges/subset.js create mode 100644 node_modules/semver/ranges/to-comparators.js create mode 100644 node_modules/semver/ranges/valid.js create mode 100644 node_modules/send/HISTORY.md create mode 100644 node_modules/send/LICENSE create mode 100644 node_modules/send/README.md create mode 100644 node_modules/send/index.js create mode 100644 node_modules/send/node_modules/ms/index.js create mode 100644 node_modules/send/node_modules/ms/license.md create mode 100644 node_modules/send/node_modules/ms/package.json create mode 100644 node_modules/send/node_modules/ms/readme.md create mode 100644 node_modules/send/package.json create mode 100644 node_modules/serve-static/HISTORY.md create mode 100644 node_modules/serve-static/LICENSE create mode 100644 node_modules/serve-static/README.md create mode 100644 node_modules/serve-static/index.js create mode 100644 node_modules/serve-static/package.json create mode 100644 node_modules/set-blocking/CHANGELOG.md create mode 100644 node_modules/set-blocking/LICENSE.txt create mode 100644 node_modules/set-blocking/README.md create mode 100644 node_modules/set-blocking/index.js create mode 100644 node_modules/set-blocking/package.json create mode 100644 node_modules/setprototypeof/LICENSE create mode 100644 node_modules/setprototypeof/README.md create mode 100644 node_modules/setprototypeof/index.d.ts create mode 100644 node_modules/setprototypeof/index.js create mode 100644 node_modules/setprototypeof/package.json create mode 100644 node_modules/setprototypeof/test/index.js create mode 100644 node_modules/sift/MIT-LICENSE.txt create mode 100644 node_modules/sift/README.md create mode 100644 node_modules/sift/changelog.md create mode 100644 node_modules/sift/es/index.js create mode 100644 node_modules/sift/es/index.js.map create mode 100644 node_modules/sift/es5m/index.js create mode 100644 node_modules/sift/es5m/index.js.map create mode 100644 node_modules/sift/index.d.ts create mode 100644 node_modules/sift/index.js create mode 100644 node_modules/sift/lib/core.d.ts create mode 100644 node_modules/sift/lib/index.d.ts create mode 100644 node_modules/sift/lib/index.js create mode 100644 node_modules/sift/lib/index.js.map create mode 100644 node_modules/sift/lib/operations.d.ts create mode 100644 node_modules/sift/lib/utils.d.ts create mode 100644 node_modules/sift/package.json create mode 100644 node_modules/sift/sift.csp.min.js create mode 100644 node_modules/sift/sift.csp.min.js.map create mode 100644 node_modules/sift/sift.min.js create mode 100644 node_modules/sift/sift.min.js.map create mode 100644 node_modules/signal-exit/LICENSE.txt create mode 100644 node_modules/signal-exit/README.md create mode 100644 node_modules/signal-exit/index.js create mode 100644 node_modules/signal-exit/package.json create mode 100644 node_modules/signal-exit/signals.js create mode 100644 node_modules/sliced/History.md create mode 100644 node_modules/sliced/LICENSE create mode 100644 node_modules/sliced/README.md create mode 100644 node_modules/sliced/index.js create mode 100644 node_modules/sliced/package.json create mode 100644 node_modules/sparse-bitfield/.npmignore create mode 100644 node_modules/sparse-bitfield/.travis.yml create mode 100644 node_modules/sparse-bitfield/LICENSE create mode 100644 node_modules/sparse-bitfield/README.md create mode 100644 node_modules/sparse-bitfield/index.js create mode 100644 node_modules/sparse-bitfield/package.json create mode 100644 node_modules/sparse-bitfield/test.js create mode 100644 node_modules/statuses/HISTORY.md create mode 100644 node_modules/statuses/LICENSE create mode 100644 node_modules/statuses/README.md create mode 100644 node_modules/statuses/codes.json create mode 100644 node_modules/statuses/index.js create mode 100644 node_modules/statuses/package.json create mode 100644 node_modules/string-width/index.d.ts create mode 100644 node_modules/string-width/index.js create mode 100644 node_modules/string-width/license create mode 100644 node_modules/string-width/package.json create mode 100644 node_modules/string-width/readme.md create mode 100644 node_modules/string_decoder/LICENSE create mode 100644 node_modules/string_decoder/README.md create mode 100644 node_modules/string_decoder/lib/string_decoder.js create mode 100644 node_modules/string_decoder/node_modules/safe-buffer/LICENSE create mode 100644 node_modules/string_decoder/node_modules/safe-buffer/README.md create mode 100644 node_modules/string_decoder/node_modules/safe-buffer/index.d.ts create mode 100644 node_modules/string_decoder/node_modules/safe-buffer/index.js create mode 100644 node_modules/string_decoder/node_modules/safe-buffer/package.json create mode 100644 node_modules/string_decoder/package.json create mode 100644 node_modules/strip-ansi/index.d.ts create mode 100644 node_modules/strip-ansi/index.js create mode 100644 node_modules/strip-ansi/license create mode 100644 node_modules/strip-ansi/package.json create mode 100644 node_modules/strip-ansi/readme.md create mode 100644 node_modules/tar/LICENSE create mode 100644 node_modules/tar/README.md create mode 100644 node_modules/tar/index.js create mode 100644 node_modules/tar/lib/create.js create mode 100644 node_modules/tar/lib/extract.js create mode 100644 node_modules/tar/lib/get-write-flag.js create mode 100644 node_modules/tar/lib/header.js create mode 100644 node_modules/tar/lib/high-level-opt.js create mode 100644 node_modules/tar/lib/large-numbers.js create mode 100644 node_modules/tar/lib/list.js create mode 100644 node_modules/tar/lib/mkdir.js create mode 100644 node_modules/tar/lib/mode-fix.js create mode 100644 node_modules/tar/lib/normalize-unicode.js create mode 100644 node_modules/tar/lib/normalize-windows-path.js create mode 100644 node_modules/tar/lib/pack.js create mode 100644 node_modules/tar/lib/parse.js create mode 100644 node_modules/tar/lib/path-reservations.js create mode 100644 node_modules/tar/lib/pax.js create mode 100644 node_modules/tar/lib/read-entry.js create mode 100644 node_modules/tar/lib/replace.js create mode 100644 node_modules/tar/lib/strip-absolute-path.js create mode 100644 node_modules/tar/lib/strip-trailing-slashes.js create mode 100644 node_modules/tar/lib/types.js create mode 100644 node_modules/tar/lib/unpack.js create mode 100644 node_modules/tar/lib/update.js create mode 100644 node_modules/tar/lib/warn-mixin.js create mode 100644 node_modules/tar/lib/winchars.js create mode 100644 node_modules/tar/lib/write-entry.js create mode 100644 node_modules/tar/package.json create mode 100644 node_modules/toidentifier/LICENSE create mode 100644 node_modules/toidentifier/README.md create mode 100644 node_modules/toidentifier/index.js create mode 100644 node_modules/toidentifier/package.json create mode 100644 node_modules/tr46/LICENSE.md create mode 100644 node_modules/tr46/README.md create mode 100644 node_modules/tr46/index.js create mode 100644 node_modules/tr46/lib/mappingTable.json create mode 100644 node_modules/tr46/lib/regexes.js create mode 100644 node_modules/tr46/lib/statusMapping.js create mode 100644 node_modules/tr46/package.json create mode 100644 node_modules/type-is/HISTORY.md create mode 100644 node_modules/type-is/LICENSE create mode 100644 node_modules/type-is/README.md create mode 100644 node_modules/type-is/index.js create mode 100644 node_modules/type-is/package.json create mode 100644 node_modules/unpipe/HISTORY.md create mode 100644 node_modules/unpipe/LICENSE create mode 100644 node_modules/unpipe/README.md create mode 100644 node_modules/unpipe/index.js create mode 100644 node_modules/unpipe/package.json create mode 100644 node_modules/util-deprecate/History.md create mode 100644 node_modules/util-deprecate/LICENSE create mode 100644 node_modules/util-deprecate/README.md create mode 100644 node_modules/util-deprecate/browser.js create mode 100644 node_modules/util-deprecate/node.js create mode 100644 node_modules/util-deprecate/package.json create mode 100644 node_modules/utils-merge/.npmignore create mode 100644 node_modules/utils-merge/LICENSE create mode 100644 node_modules/utils-merge/README.md create mode 100644 node_modules/utils-merge/index.js create mode 100644 node_modules/utils-merge/package.json create mode 100644 node_modules/validator/LICENSE create mode 100644 node_modules/validator/README.md create mode 100644 node_modules/validator/es/index.js create mode 100644 node_modules/validator/es/lib/alpha.js create mode 100644 node_modules/validator/es/lib/blacklist.js create mode 100644 node_modules/validator/es/lib/contains.js create mode 100644 node_modules/validator/es/lib/equals.js create mode 100644 node_modules/validator/es/lib/escape.js create mode 100644 node_modules/validator/es/lib/isAfter.js create mode 100644 node_modules/validator/es/lib/isAlpha.js create mode 100644 node_modules/validator/es/lib/isAlphanumeric.js create mode 100644 node_modules/validator/es/lib/isAscii.js create mode 100644 node_modules/validator/es/lib/isBIC.js create mode 100644 node_modules/validator/es/lib/isBase32.js create mode 100644 node_modules/validator/es/lib/isBase58.js create mode 100644 node_modules/validator/es/lib/isBase64.js create mode 100644 node_modules/validator/es/lib/isBefore.js create mode 100644 node_modules/validator/es/lib/isBoolean.js create mode 100644 node_modules/validator/es/lib/isBtcAddress.js create mode 100644 node_modules/validator/es/lib/isByteLength.js create mode 100644 node_modules/validator/es/lib/isCreditCard.js create mode 100644 node_modules/validator/es/lib/isCurrency.js create mode 100644 node_modules/validator/es/lib/isDataURI.js create mode 100644 node_modules/validator/es/lib/isDate.js create mode 100644 node_modules/validator/es/lib/isDecimal.js create mode 100644 node_modules/validator/es/lib/isDivisibleBy.js create mode 100644 node_modules/validator/es/lib/isEAN.js create mode 100644 node_modules/validator/es/lib/isEmail.js create mode 100644 node_modules/validator/es/lib/isEmpty.js create mode 100644 node_modules/validator/es/lib/isEthereumAddress.js create mode 100644 node_modules/validator/es/lib/isFQDN.js create mode 100644 node_modules/validator/es/lib/isFloat.js create mode 100644 node_modules/validator/es/lib/isFullWidth.js create mode 100644 node_modules/validator/es/lib/isHSL.js create mode 100644 node_modules/validator/es/lib/isHalfWidth.js create mode 100644 node_modules/validator/es/lib/isHash.js create mode 100644 node_modules/validator/es/lib/isHexColor.js create mode 100644 node_modules/validator/es/lib/isHexadecimal.js create mode 100644 node_modules/validator/es/lib/isIBAN.js create mode 100644 node_modules/validator/es/lib/isIMEI.js create mode 100644 node_modules/validator/es/lib/isIP.js create mode 100644 node_modules/validator/es/lib/isIPRange.js create mode 100644 node_modules/validator/es/lib/isISBN.js create mode 100644 node_modules/validator/es/lib/isISIN.js create mode 100644 node_modules/validator/es/lib/isISO31661Alpha2.js create mode 100644 node_modules/validator/es/lib/isISO31661Alpha3.js create mode 100644 node_modules/validator/es/lib/isISO4217.js create mode 100644 node_modules/validator/es/lib/isISO8601.js create mode 100644 node_modules/validator/es/lib/isISRC.js create mode 100644 node_modules/validator/es/lib/isISSN.js create mode 100644 node_modules/validator/es/lib/isIdentityCard.js create mode 100644 node_modules/validator/es/lib/isIn.js create mode 100644 node_modules/validator/es/lib/isInt.js create mode 100644 node_modules/validator/es/lib/isJSON.js create mode 100644 node_modules/validator/es/lib/isJWT.js create mode 100644 node_modules/validator/es/lib/isLatLong.js create mode 100644 node_modules/validator/es/lib/isLength.js create mode 100644 node_modules/validator/es/lib/isLicensePlate.js create mode 100644 node_modules/validator/es/lib/isLocale.js create mode 100644 node_modules/validator/es/lib/isLowercase.js create mode 100644 node_modules/validator/es/lib/isMACAddress.js create mode 100644 node_modules/validator/es/lib/isMD5.js create mode 100644 node_modules/validator/es/lib/isMagnetURI.js create mode 100644 node_modules/validator/es/lib/isMimeType.js create mode 100644 node_modules/validator/es/lib/isMobilePhone.js create mode 100644 node_modules/validator/es/lib/isMongoId.js create mode 100644 node_modules/validator/es/lib/isMultibyte.js create mode 100644 node_modules/validator/es/lib/isNumeric.js create mode 100644 node_modules/validator/es/lib/isOctal.js create mode 100644 node_modules/validator/es/lib/isPassportNumber.js create mode 100644 node_modules/validator/es/lib/isPort.js create mode 100644 node_modules/validator/es/lib/isPostalCode.js create mode 100644 node_modules/validator/es/lib/isRFC3339.js create mode 100644 node_modules/validator/es/lib/isRgbColor.js create mode 100644 node_modules/validator/es/lib/isSemVer.js create mode 100644 node_modules/validator/es/lib/isSlug.js create mode 100644 node_modules/validator/es/lib/isStrongPassword.js create mode 100644 node_modules/validator/es/lib/isSurrogatePair.js create mode 100644 node_modules/validator/es/lib/isTaxID.js create mode 100644 node_modules/validator/es/lib/isURL.js create mode 100644 node_modules/validator/es/lib/isUUID.js create mode 100644 node_modules/validator/es/lib/isUppercase.js create mode 100644 node_modules/validator/es/lib/isVAT.js create mode 100644 node_modules/validator/es/lib/isVariableWidth.js create mode 100644 node_modules/validator/es/lib/isWhitelisted.js create mode 100644 node_modules/validator/es/lib/ltrim.js create mode 100644 node_modules/validator/es/lib/matches.js create mode 100644 node_modules/validator/es/lib/normalizeEmail.js create mode 100644 node_modules/validator/es/lib/rtrim.js create mode 100644 node_modules/validator/es/lib/stripLow.js create mode 100644 node_modules/validator/es/lib/toBoolean.js create mode 100644 node_modules/validator/es/lib/toDate.js create mode 100644 node_modules/validator/es/lib/toFloat.js create mode 100644 node_modules/validator/es/lib/toInt.js create mode 100644 node_modules/validator/es/lib/trim.js create mode 100644 node_modules/validator/es/lib/unescape.js create mode 100644 node_modules/validator/es/lib/util/algorithms.js create mode 100644 node_modules/validator/es/lib/util/assertString.js create mode 100644 node_modules/validator/es/lib/util/includes.js create mode 100644 node_modules/validator/es/lib/util/merge.js create mode 100644 node_modules/validator/es/lib/util/multilineRegex.js create mode 100644 node_modules/validator/es/lib/util/toString.js create mode 100644 node_modules/validator/es/lib/util/typeOf.js create mode 100644 node_modules/validator/es/lib/whitelist.js create mode 100644 node_modules/validator/index.js create mode 100644 node_modules/validator/lib/alpha.js create mode 100644 node_modules/validator/lib/blacklist.js create mode 100644 node_modules/validator/lib/contains.js create mode 100644 node_modules/validator/lib/equals.js create mode 100644 node_modules/validator/lib/escape.js create mode 100644 node_modules/validator/lib/isAfter.js create mode 100644 node_modules/validator/lib/isAlpha.js create mode 100644 node_modules/validator/lib/isAlphanumeric.js create mode 100644 node_modules/validator/lib/isAscii.js create mode 100644 node_modules/validator/lib/isBIC.js create mode 100644 node_modules/validator/lib/isBase32.js create mode 100644 node_modules/validator/lib/isBase58.js create mode 100644 node_modules/validator/lib/isBase64.js create mode 100644 node_modules/validator/lib/isBefore.js create mode 100644 node_modules/validator/lib/isBoolean.js create mode 100644 node_modules/validator/lib/isBtcAddress.js create mode 100644 node_modules/validator/lib/isByteLength.js create mode 100644 node_modules/validator/lib/isCreditCard.js create mode 100644 node_modules/validator/lib/isCurrency.js create mode 100644 node_modules/validator/lib/isDataURI.js create mode 100644 node_modules/validator/lib/isDate.js create mode 100644 node_modules/validator/lib/isDecimal.js create mode 100644 node_modules/validator/lib/isDivisibleBy.js create mode 100644 node_modules/validator/lib/isEAN.js create mode 100644 node_modules/validator/lib/isEmail.js create mode 100644 node_modules/validator/lib/isEmpty.js create mode 100644 node_modules/validator/lib/isEthereumAddress.js create mode 100644 node_modules/validator/lib/isFQDN.js create mode 100644 node_modules/validator/lib/isFloat.js create mode 100644 node_modules/validator/lib/isFullWidth.js create mode 100644 node_modules/validator/lib/isHSL.js create mode 100644 node_modules/validator/lib/isHalfWidth.js create mode 100644 node_modules/validator/lib/isHash.js create mode 100644 node_modules/validator/lib/isHexColor.js create mode 100644 node_modules/validator/lib/isHexadecimal.js create mode 100644 node_modules/validator/lib/isIBAN.js create mode 100644 node_modules/validator/lib/isIMEI.js create mode 100644 node_modules/validator/lib/isIP.js create mode 100644 node_modules/validator/lib/isIPRange.js create mode 100644 node_modules/validator/lib/isISBN.js create mode 100644 node_modules/validator/lib/isISIN.js create mode 100644 node_modules/validator/lib/isISO31661Alpha2.js create mode 100644 node_modules/validator/lib/isISO31661Alpha3.js create mode 100644 node_modules/validator/lib/isISO4217.js create mode 100644 node_modules/validator/lib/isISO8601.js create mode 100644 node_modules/validator/lib/isISRC.js create mode 100644 node_modules/validator/lib/isISSN.js create mode 100644 node_modules/validator/lib/isIdentityCard.js create mode 100644 node_modules/validator/lib/isIn.js create mode 100644 node_modules/validator/lib/isInt.js create mode 100644 node_modules/validator/lib/isJSON.js create mode 100644 node_modules/validator/lib/isJWT.js create mode 100644 node_modules/validator/lib/isLatLong.js create mode 100644 node_modules/validator/lib/isLength.js create mode 100644 node_modules/validator/lib/isLicensePlate.js create mode 100644 node_modules/validator/lib/isLocale.js create mode 100644 node_modules/validator/lib/isLowercase.js create mode 100644 node_modules/validator/lib/isMACAddress.js create mode 100644 node_modules/validator/lib/isMD5.js create mode 100644 node_modules/validator/lib/isMagnetURI.js create mode 100644 node_modules/validator/lib/isMimeType.js create mode 100644 node_modules/validator/lib/isMobilePhone.js create mode 100644 node_modules/validator/lib/isMongoId.js create mode 100644 node_modules/validator/lib/isMultibyte.js create mode 100644 node_modules/validator/lib/isNumeric.js create mode 100644 node_modules/validator/lib/isOctal.js create mode 100644 node_modules/validator/lib/isPassportNumber.js create mode 100644 node_modules/validator/lib/isPort.js create mode 100644 node_modules/validator/lib/isPostalCode.js create mode 100644 node_modules/validator/lib/isRFC3339.js create mode 100644 node_modules/validator/lib/isRgbColor.js create mode 100644 node_modules/validator/lib/isSemVer.js create mode 100644 node_modules/validator/lib/isSlug.js create mode 100644 node_modules/validator/lib/isStrongPassword.js create mode 100644 node_modules/validator/lib/isSurrogatePair.js create mode 100644 node_modules/validator/lib/isTaxID.js create mode 100644 node_modules/validator/lib/isURL.js create mode 100644 node_modules/validator/lib/isUUID.js create mode 100644 node_modules/validator/lib/isUppercase.js create mode 100644 node_modules/validator/lib/isVAT.js create mode 100644 node_modules/validator/lib/isVariableWidth.js create mode 100644 node_modules/validator/lib/isWhitelisted.js create mode 100644 node_modules/validator/lib/ltrim.js create mode 100644 node_modules/validator/lib/matches.js create mode 100644 node_modules/validator/lib/normalizeEmail.js create mode 100644 node_modules/validator/lib/rtrim.js create mode 100644 node_modules/validator/lib/stripLow.js create mode 100644 node_modules/validator/lib/toBoolean.js create mode 100644 node_modules/validator/lib/toDate.js create mode 100644 node_modules/validator/lib/toFloat.js create mode 100644 node_modules/validator/lib/toInt.js create mode 100644 node_modules/validator/lib/trim.js create mode 100644 node_modules/validator/lib/unescape.js create mode 100644 node_modules/validator/lib/util/algorithms.js create mode 100644 node_modules/validator/lib/util/assertString.js create mode 100644 node_modules/validator/lib/util/includes.js create mode 100644 node_modules/validator/lib/util/merge.js create mode 100644 node_modules/validator/lib/util/multilineRegex.js create mode 100644 node_modules/validator/lib/util/toString.js create mode 100644 node_modules/validator/lib/util/typeOf.js create mode 100644 node_modules/validator/lib/whitelist.js create mode 100644 node_modules/validator/package.json create mode 100644 node_modules/validator/validator.js create mode 100644 node_modules/validator/validator.min.js create mode 100644 node_modules/vary/HISTORY.md create mode 100644 node_modules/vary/LICENSE create mode 100644 node_modules/vary/README.md create mode 100644 node_modules/vary/index.js create mode 100644 node_modules/vary/package.json create mode 100644 node_modules/webidl-conversions/LICENSE.md create mode 100644 node_modules/webidl-conversions/README.md create mode 100644 node_modules/webidl-conversions/lib/index.js create mode 100644 node_modules/webidl-conversions/package.json create mode 100644 node_modules/whatwg-url/LICENSE.txt create mode 100644 node_modules/whatwg-url/README.md create mode 100644 node_modules/whatwg-url/dist/Function.js create mode 100644 node_modules/whatwg-url/dist/URL-impl.js create mode 100644 node_modules/whatwg-url/dist/URL.js create mode 100644 node_modules/whatwg-url/dist/URLSearchParams-impl.js create mode 100644 node_modules/whatwg-url/dist/URLSearchParams.js create mode 100644 node_modules/whatwg-url/dist/VoidFunction.js create mode 100644 node_modules/whatwg-url/dist/encoding.js create mode 100644 node_modules/whatwg-url/dist/infra.js create mode 100644 node_modules/whatwg-url/dist/percent-encoding.js create mode 100644 node_modules/whatwg-url/dist/url-state-machine.js create mode 100644 node_modules/whatwg-url/dist/urlencoded.js create mode 100644 node_modules/whatwg-url/dist/utils.js create mode 100644 node_modules/whatwg-url/index.js create mode 100644 node_modules/whatwg-url/package.json create mode 100644 node_modules/whatwg-url/webidl2js-wrapper.js create mode 100644 node_modules/wide-align/LICENSE create mode 100644 node_modules/wide-align/README.md create mode 100644 node_modules/wide-align/align.js create mode 100644 node_modules/wide-align/package.json create mode 100644 node_modules/wrappy/LICENSE create mode 100644 node_modules/wrappy/README.md create mode 100644 node_modules/wrappy/package.json create mode 100644 node_modules/wrappy/wrappy.js create mode 100644 node_modules/yallist/LICENSE create mode 100644 node_modules/yallist/README.md create mode 100644 node_modules/yallist/iterator.js create mode 100644 node_modules/yallist/package.json create mode 100644 node_modules/yallist/yallist.js diff --git a/node_modules/.bin/color-support b/node_modules/.bin/color-support new file mode 100644 index 0000000..59e6506 --- /dev/null +++ b/node_modules/.bin/color-support @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../color-support/bin.js" "$@" +else + exec node "$basedir/../color-support/bin.js" "$@" +fi diff --git a/node_modules/.bin/color-support.cmd b/node_modules/.bin/color-support.cmd new file mode 100644 index 0000000..005f9a5 --- /dev/null +++ b/node_modules/.bin/color-support.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\color-support\bin.js" %* diff --git a/node_modules/.bin/color-support.ps1 b/node_modules/.bin/color-support.ps1 new file mode 100644 index 0000000..f5c9fe4 --- /dev/null +++ b/node_modules/.bin/color-support.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../color-support/bin.js" $args + } else { + & "$basedir/node$exe" "$basedir/../color-support/bin.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../color-support/bin.js" $args + } else { + & "node$exe" "$basedir/../color-support/bin.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/detect-libc b/node_modules/.bin/detect-libc new file mode 100644 index 0000000..9a7ff33 --- /dev/null +++ b/node_modules/.bin/detect-libc @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../detect-libc/bin/detect-libc.js" "$@" +else + exec node "$basedir/../detect-libc/bin/detect-libc.js" "$@" +fi diff --git a/node_modules/.bin/detect-libc.cmd b/node_modules/.bin/detect-libc.cmd new file mode 100644 index 0000000..1c5d86d --- /dev/null +++ b/node_modules/.bin/detect-libc.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\detect-libc\bin\detect-libc.js" %* diff --git a/node_modules/.bin/detect-libc.ps1 b/node_modules/.bin/detect-libc.ps1 new file mode 100644 index 0000000..5ebeae1 --- /dev/null +++ b/node_modules/.bin/detect-libc.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../detect-libc/bin/detect-libc.js" $args + } else { + & "$basedir/node$exe" "$basedir/../detect-libc/bin/detect-libc.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../detect-libc/bin/detect-libc.js" $args + } else { + & "node$exe" "$basedir/../detect-libc/bin/detect-libc.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 100644 index 0000000..0a62a1b --- /dev/null +++ b/node_modules/.bin/mime @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../mime/cli.js" "$@" +else + exec node "$basedir/../mime/cli.js" "$@" +fi diff --git a/node_modules/.bin/mime.cmd b/node_modules/.bin/mime.cmd new file mode 100644 index 0000000..54491f1 --- /dev/null +++ b/node_modules/.bin/mime.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mime\cli.js" %* diff --git a/node_modules/.bin/mime.ps1 b/node_modules/.bin/mime.ps1 new file mode 100644 index 0000000..2222f40 --- /dev/null +++ b/node_modules/.bin/mime.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../mime/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../mime/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../mime/cli.js" $args + } else { + & "node$exe" "$basedir/../mime/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/mkdirp b/node_modules/.bin/mkdirp new file mode 100644 index 0000000..6ba5765 --- /dev/null +++ b/node_modules/.bin/mkdirp @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../mkdirp/bin/cmd.js" "$@" +else + exec node "$basedir/../mkdirp/bin/cmd.js" "$@" +fi diff --git a/node_modules/.bin/mkdirp.cmd b/node_modules/.bin/mkdirp.cmd new file mode 100644 index 0000000..a865dd9 --- /dev/null +++ b/node_modules/.bin/mkdirp.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mkdirp\bin\cmd.js" %* diff --git a/node_modules/.bin/mkdirp.ps1 b/node_modules/.bin/mkdirp.ps1 new file mode 100644 index 0000000..911e854 --- /dev/null +++ b/node_modules/.bin/mkdirp.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args + } else { + & "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args + } else { + & "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/node-pre-gyp b/node_modules/.bin/node-pre-gyp new file mode 100644 index 0000000..004c3be --- /dev/null +++ b/node_modules/.bin/node-pre-gyp @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../@mapbox/node-pre-gyp/bin/node-pre-gyp" "$@" +else + exec node "$basedir/../@mapbox/node-pre-gyp/bin/node-pre-gyp" "$@" +fi diff --git a/node_modules/.bin/node-pre-gyp.cmd b/node_modules/.bin/node-pre-gyp.cmd new file mode 100644 index 0000000..a2fc508 --- /dev/null +++ b/node_modules/.bin/node-pre-gyp.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\@mapbox\node-pre-gyp\bin\node-pre-gyp" %* diff --git a/node_modules/.bin/node-pre-gyp.ps1 b/node_modules/.bin/node-pre-gyp.ps1 new file mode 100644 index 0000000..ed297ff --- /dev/null +++ b/node_modules/.bin/node-pre-gyp.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../@mapbox/node-pre-gyp/bin/node-pre-gyp" $args + } else { + & "$basedir/node$exe" "$basedir/../@mapbox/node-pre-gyp/bin/node-pre-gyp" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../@mapbox/node-pre-gyp/bin/node-pre-gyp" $args + } else { + & "node$exe" "$basedir/../@mapbox/node-pre-gyp/bin/node-pre-gyp" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/nopt b/node_modules/.bin/nopt new file mode 100644 index 0000000..f1ec43b --- /dev/null +++ b/node_modules/.bin/nopt @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../nopt/bin/nopt.js" "$@" +else + exec node "$basedir/../nopt/bin/nopt.js" "$@" +fi diff --git a/node_modules/.bin/nopt.cmd b/node_modules/.bin/nopt.cmd new file mode 100644 index 0000000..a7f38b3 --- /dev/null +++ b/node_modules/.bin/nopt.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nopt\bin\nopt.js" %* diff --git a/node_modules/.bin/nopt.ps1 b/node_modules/.bin/nopt.ps1 new file mode 100644 index 0000000..9d6ba56 --- /dev/null +++ b/node_modules/.bin/nopt.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../nopt/bin/nopt.js" $args + } else { + & "$basedir/node$exe" "$basedir/../nopt/bin/nopt.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../nopt/bin/nopt.js" $args + } else { + & "node$exe" "$basedir/../nopt/bin/nopt.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/rimraf b/node_modules/.bin/rimraf new file mode 100644 index 0000000..b816825 --- /dev/null +++ b/node_modules/.bin/rimraf @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../rimraf/bin.js" "$@" +else + exec node "$basedir/../rimraf/bin.js" "$@" +fi diff --git a/node_modules/.bin/rimraf.cmd b/node_modules/.bin/rimraf.cmd new file mode 100644 index 0000000..13f45ec --- /dev/null +++ b/node_modules/.bin/rimraf.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\rimraf\bin.js" %* diff --git a/node_modules/.bin/rimraf.ps1 b/node_modules/.bin/rimraf.ps1 new file mode 100644 index 0000000..1716791 --- /dev/null +++ b/node_modules/.bin/rimraf.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../rimraf/bin.js" $args + } else { + & "$basedir/node$exe" "$basedir/../rimraf/bin.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../rimraf/bin.js" $args + } else { + & "node$exe" "$basedir/../rimraf/bin.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 100644 index 0000000..77443e7 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../semver/bin/semver.js" "$@" +else + exec node "$basedir/../semver/bin/semver.js" "$@" +fi diff --git a/node_modules/.bin/semver.cmd b/node_modules/.bin/semver.cmd new file mode 100644 index 0000000..9913fa9 --- /dev/null +++ b/node_modules/.bin/semver.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %* diff --git a/node_modules/.bin/semver.ps1 b/node_modules/.bin/semver.ps1 new file mode 100644 index 0000000..314717a --- /dev/null +++ b/node_modules/.bin/semver.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args + } else { + & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../semver/bin/semver.js" $args + } else { + & "node$exe" "$basedir/../semver/bin/semver.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..d05c4d1 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,1495 @@ +{ + "name": "rocked_backend", + "version": "1.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@mapbox/node-pre-gyp": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.8.tgz", + "integrity": "sha512-CMGKi28CF+qlbXh26hDe6NxCd7amqeAzEqnS6IHeO6LoaKyM/n+Xw3HT1COdq8cuioOdlKdqn/hCmqPUOMOywg==", + "dependencies": { + "detect-libc": "^1.0.3", + "https-proxy-agent": "^5.0.0", + "make-dir": "^3.1.0", + "node-fetch": "^2.6.5", + "nopt": "^5.0.0", + "npmlog": "^5.0.1", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.11" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp" + } + }, + "node_modules/@types/node": { + "version": "16.11.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.11.1.tgz", + "integrity": "sha512-PYGcJHL9mwl1Ek3PLiYgyEKtwTMmkMw4vbiyz/ps3pfdRYLVv+SN7qHVAImrjdAXxgluDEw6Ph4lyv+m9UpRmA==" + }, + "node_modules/@types/webidl-conversions": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-6.1.1.tgz", + "integrity": "sha512-XAahCdThVuCFDQLT7R7Pk/vqeObFNL3YqRyFZg+AqAP/W1/w3xHaIxuW7WszQqTbIBOPRcItYJIou3i/mppu3Q==" + }, + "node_modules/@types/whatwg-url": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-8.2.1.tgz", + "integrity": "sha512-2YubE1sjj5ifxievI5Ge1sckb9k/Er66HyR2c+3+I6VDUUg1TLPdYYTEbQ+DjRkS4nTxMJhgWfSfMRD2sl2EYQ==", + "dependencies": { + "@types/node": "*", + "@types/webidl-conversions": "*" + } + }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" + }, + "node_modules/accepts": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", + "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", + "dependencies": { + "mime-types": "~2.1.24", + "negotiator": "0.6.2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/agent-base/node_modules/debug": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", + "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/agent-base/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "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/aproba": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==" + }, + "node_modules/are-we-there-yet": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", + "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==", + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/bcrypt": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.0.1.tgz", + "integrity": "sha512-9BTgmrhZM2t1bNuDtrtIMVSmmxZBrJ71n8Wg+YgdjHuIWYF7SjjmCPZFB+/5i/o/PIeRpwVJR3P+NrpIItUjqw==", + "hasInstallScript": true, + "dependencies": { + "@mapbox/node-pre-gyp": "^1.0.0", + "node-addon-api": "^3.1.0" + }, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/bcryptjs": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", + "integrity": "sha1-mrVie5PmBiH/fNrF2pczAn3x0Ms=" + }, + "node_modules/body-parser": { + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", + "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", + "dependencies": { + "bytes": "3.1.0", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.2", + "http-errors": "1.7.2", + "iconv-lite": "0.4.24", + "on-finished": "~2.3.0", + "qs": "6.7.0", + "raw-body": "2.4.0", + "type-is": "~1.6.17" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/bson": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/bson/-/bson-4.5.3.tgz", + "integrity": "sha512-qVX7LX79Mtj7B3NPLzCfBiCP6RAsjiV8N63DjlaVVpZW+PFoDTxQ4SeDbSpcqgE6mXksM5CAwZnXxxxn/XwC0g==", + "dependencies": { + "buffer": "^5.6.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" + }, + "node_modules/bytes": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", + "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/child_process": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/child_process/-/child_process-1.0.2.tgz", + "integrity": "sha1-sffn/HPSXn/R1FWtyU4UODAYK1o=" + }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "engines": { + "node": ">=10" + } + }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "bin": { + "color-support": "bin.js" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=" + }, + "node_modules/content-disposition": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", + "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", + "dependencies": { + "safe-buffer": "5.1.2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", + "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=" + }, + "node_modules/denque": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.0.1.tgz", + "integrity": "sha512-tfiWc6BQLXNLpNiR5iGd0Ocu3P3VpxfzFiqubLgMfhfOw9WyvgJBd46CClNn9k3qfbjvT//0cf7AlYRX/OslMQ==", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/destroy": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" + }, + "node_modules/detect-libc": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz", + "integrity": "sha1-+hN8S9aY7fVc1c0CrFWfkaTEups=", + "bin": { + "detect-libc": "bin/detect-libc.js" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" + }, + "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/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.17.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", + "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", + "dependencies": { + "accepts": "~1.3.7", + "array-flatten": "1.1.1", + "body-parser": "1.19.0", + "content-disposition": "0.5.3", + "content-type": "~1.0.4", + "cookie": "0.4.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.2", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.1.2", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.5", + "qs": "6.7.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.1.2", + "send": "0.17.1", + "serve-static": "1.14.1", + "setprototypeof": "1.1.1", + "statuses": "~1.5.0", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/finalhandler": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", + "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "statuses": "~1.5.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "node_modules/gauge": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz", + "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==", + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.2", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.1", + "object-assign": "^4.1.1", + "signal-exit": "^3.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=" + }, + "node_modules/http-errors": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", + "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.1", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-status": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/http-status/-/http-status-1.5.0.tgz", + "integrity": "sha512-wcGvY31MpFNHIkUcXHHnvrE4IKYlpvitJw5P/1u892gMBAM46muQ+RH7UN1d+Ntnfx5apnOnVY6vcLmrWHOLwg==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz", + "integrity": "sha512-EkYm5BcKUGiduxzSt3Eppko+PiNWNEpa4ySk9vTC6wDsQJW9rHSa+UhGNJoRYp7bz6Ht1eaRIa6QaJqO5rCFbA==", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/https-proxy-agent/node_modules/debug": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", + "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/https-proxy-agent/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.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/jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=4", + "npm": ">=1.4.28" + } + }, + "node_modules/jsonwebtoken/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/jsonwebtoken/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/kareem": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.3.2.tgz", + "integrity": "sha512-STHz9P7X2L4Kwn72fA4rGyqyXdmrMSdxqHx9IXon/FXluXieaFA6KJ2upcHAHxQPQ0LeM/OjLrhFxifHewOALQ==" + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "optional": true + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.50.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.50.0.tgz", + "integrity": "sha512-9tMZCDlYHqeERXEHO9f/hKfNXhre5dK2eE/krIvUjZbS2KPcqGDfNShIWS1uW9XOTKQKqK6qbeOci18rbfW77A==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.33", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.33.tgz", + "integrity": "sha512-plLElXp7pRDd0bNZHw+nMd52vRYjLwQjygaNg7ddJ2uJtTlmnTCjWuPKxVu6//AdaRuME84SvLW91sIkBqGT0g==", + "dependencies": { + "mime-db": "1.50.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minipass": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.1.6.tgz", + "integrity": "sha512-rty5kpw9/z8SX9dmxblFA6edItUmwJgMeYDZRrwlIVN27i8gysGbznJwUggw2V/FVqFSDdWy040ZPS811DYAqQ==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mongodb": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-4.1.2.tgz", + "integrity": "sha512-pHCKDoOy1h6mVurziJmXmTMPatYWOx8pbnyFgSgshja9Y36Q+caHUzTDY6rrIy9HCSrjnbXmx3pCtvNZHmR8xg==", + "dependencies": { + "bson": "^4.5.2", + "denque": "^2.0.1", + "mongodb-connection-string-url": "^2.0.0" + }, + "engines": { + "node": ">=12.9.0" + }, + "optionalDependencies": { + "saslprep": "^1.0.3" + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.1.0.tgz", + "integrity": "sha512-Qf9Zw7KGiRljWvMrrUFDdVqo46KIEiDuCzvEN97rh/PcKzk2bd6n9KuzEwBwW9xo5glwx69y1mI6s+jFUD/aIQ==", + "dependencies": { + "@types/whatwg-url": "^8.2.1", + "whatwg-url": "^9.1.0" + } + }, + "node_modules/mongoose": { + "version": "6.0.11", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-6.0.11.tgz", + "integrity": "sha512-ESLnGIZB15xpqAbtjL/wcx+NEmzewlNuST/Dp/md4eqirVGTuEeN+IhS4qr3D5GFhnQAGdadpGlTfrWj5Ggykw==", + "dependencies": { + "bson": "^4.2.2", + "kareem": "2.3.2", + "mongodb": "4.1.2", + "mpath": "0.8.4", + "mquery": "4.0.0", + "ms": "2.1.2", + "regexp-clone": "1.0.0", + "sift": "13.5.2", + "sliced": "1.0.1" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/mongoose/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/mpath": { + "version": "0.8.4", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.8.4.tgz", + "integrity": "sha512-DTxNZomBcTWlrMW76jy1wvV37X/cNNxPW1y2Jzd4DZkAaC5ZGsm8bfGfNOthcDuRJujXLqiuS6o3Tpy0JEoh7g==", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mquery": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-4.0.0.tgz", + "integrity": "sha512-nGjm89lHja+T/b8cybAby6H0YgA4qYC/lx6UlwvHGqvTq8bDaNeCwl1sY8uRELrNbVWJzIihxVd+vphGGn1vBw==", + "dependencies": { + "debug": "4.x", + "regexp-clone": "^1.0.0", + "sliced": "1.0.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/mquery/node_modules/debug": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", + "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/mquery/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "node_modules/negotiator": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", + "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-addon-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.2.1.tgz", + "integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==" + }, + "node_modules/node-fetch": { + "version": "2.6.6", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.6.tgz", + "integrity": "sha512-Z8/6vRlTUChSdIgMa51jxQ4lrw/Jy5SOW10ObaA47/RElsAN2c5Pn8bTgFGWn/ibwzXTE8qwr1Yzx28vsecXEA==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + } + }, + "node_modules/node-fetch/node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o=" + }, + "node_modules/node-fetch/node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=" + }, + "node_modules/node-fetch/node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/npmlog": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", + "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==", + "dependencies": { + "are-we-there-yet": "^2.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^3.0.0", + "set-blocking": "^2.0.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/passport": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/passport/-/passport-0.5.2.tgz", + "integrity": "sha512-w9n/Ot5I7orGD4y+7V3EFJCQEznE5RxHamUxcqLT2QoJY0f2JdN8GyHonYFvN0Vz+L6lUJfVhrk2aZz2LbuREw==", + "dependencies": { + "passport-strategy": "1.x.x", + "pause": "0.0.1" + }, + "engines": { + "node": ">= 0.4.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jaredhanson" + } + }, + "node_modules/passport-jwt": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/passport-jwt/-/passport-jwt-4.0.0.tgz", + "integrity": "sha512-BwC0n2GP/1hMVjR4QpnvqA61TxenUMlmfNjYNgK0ZAs0HK4SOQkHcSv4L328blNTLtHq7DbmvyNJiH+bn6C5Mg==", + "dependencies": { + "jsonwebtoken": "^8.2.0", + "passport-strategy": "^1.0.0" + } + }, + "node_modules/passport-strategy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/passport-strategy/-/passport-strategy-1.0.0.tgz", + "integrity": "sha1-tVOaqPwiWj0a0XlHbd8ja0QPUuQ=", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" + }, + "node_modules/pause": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz", + "integrity": "sha1-HUCLP9t2kjuVQ9lvtMnf1TXZy10=" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.7.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", + "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz", + "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==", + "dependencies": { + "bytes": "3.1.0", + "http-errors": "1.7.2", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readable-stream": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/regexp-clone": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-1.0.0.tgz", + "integrity": "sha512-TuAasHQNamyyJ2hb97IuBEif4qBHGjPHBS64sZwytpLEqtBQ1gPJTnOaQ6qmpET16cK14kkjbazl6+p0RRv0yw==" + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/saslprep": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", + "integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", + "optional": true, + "dependencies": { + "sparse-bitfield": "^3.0.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/semver": { + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.17.1", + "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", + "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==", + "dependencies": { + "debug": "2.6.9", + "depd": "~1.1.2", + "destroy": "~1.0.4", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "~1.7.2", + "mime": "1.6.0", + "ms": "2.1.1", + "on-finished": "~2.3.0", + "range-parser": "~1.2.1", + "statuses": "~1.5.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" + }, + "node_modules/serve-static": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz", + "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.17.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" + }, + "node_modules/setprototypeof": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", + "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==" + }, + "node_modules/sift": { + "version": "13.5.2", + "resolved": "https://registry.npmjs.org/sift/-/sift-13.5.2.tgz", + "integrity": "sha512-+gxdEOMA2J+AI+fVsCqeNn7Tgx3M9ZN9jdi95939l1IJ8cZsqS8sqpJyOkic2SJk+1+98Uwryt/gL6XDaV+UZA==" + }, + "node_modules/signal-exit": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.6.tgz", + "integrity": "sha512-sDl4qMFpijcGw22U5w63KmD3cZJfBuFlVNbVMKje2keoKML7X2UzWbc4XrmEbDwg0NXJc3yv4/ox7b+JWb57kQ==" + }, + "node_modules/sliced": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", + "integrity": "sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E=" + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", + "optional": true, + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "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/tar": { + "version": "6.1.11", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.1.11.tgz", + "integrity": "sha512-an/KZQzQUkZCkuoAA64hM92X0Urb6VpRhAFllDzz44U2mcD5scmT3zBc4VgVpkugF580+DQn8eAFSyoQt0tznA==", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^3.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/toidentifier": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", + "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tr46": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-2.1.0.tgz", + "integrity": "sha512-15Ih7phfcdP5YxqiB+iDtLoaTz4Nd35+IiAv0kQ5FNKHzXgdWqPoTIqEDDJmXceQt4JZk6lVPT8lnDlPpGDppw==", + "dependencies": { + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/validator": { + "version": "13.7.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.7.0.tgz", + "integrity": "sha512-nYXQLCBkpJ8X6ltALua9dRrZDHVYxjJ1wgskNt1lH9fzGjs3tgojGSCBjmEPwkWS1y29+DrizMTW19Pr9uB2nw==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/webidl-conversions": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-6.1.0.tgz", + "integrity": "sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w==", + "engines": { + "node": ">=10.4" + } + }, + "node_modules/whatwg-url": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-9.1.0.tgz", + "integrity": "sha512-CQ0UcrPHyomtlOCot1TL77WyMIm/bCwrJ2D6AOKGwEczU9EpyoqAokfqrf/MioU9kHcMsmJZcg1egXix2KYEsA==", + "dependencies": { + "tr46": "^2.1.0", + "webidl-conversions": "^6.1.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + } + } +} diff --git a/node_modules/@mapbox/node-pre-gyp/CHANGELOG.md b/node_modules/@mapbox/node-pre-gyp/CHANGELOG.md new file mode 100644 index 0000000..741e22c --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/CHANGELOG.md @@ -0,0 +1,500 @@ +# node-pre-gyp changelog + +## 1.0.8 +- Downgraded npmlog to maintain node v10 and v8 support (https://github.com/mapbox/node-pre-gyp/pull/624) + +## 1.0.7 +- Upgraded nyc and npmlog to address https://github.com/advisories/GHSA-93q8-gq69-wqmw + +## 1.0.6 +- Added node v17 to the internal node releases listing +- Upgraded various dependencies declared in package.json to latest major versions (node-fetch from 2.6.1 to 2.6.5, npmlog from 4.1.2 to 5.01, semver from 7.3.4 to 7.3.5, and tar from 6.1.0 to 6.1.11) +- Fixed bug in `staging_host` parameter (https://github.com/mapbox/node-pre-gyp/pull/590) + + +## 1.0.5 +- Fix circular reference warning with node >= v14 + +## 1.0.4 +- Added node v16 to the internal node releases listing + +## 1.0.3 +- Improved support configuring s3 uploads (solves https://github.com/mapbox/node-pre-gyp/issues/571) + - New options added in https://github.com/mapbox/node-pre-gyp/pull/576: 'bucket', 'region', and `s3ForcePathStyle` + +## 1.0.2 +- Fixed regression in proxy support (https://github.com/mapbox/node-pre-gyp/issues/572) + +## 1.0.1 +- Switched from mkdirp@1.0.4 to make-dir@3.1.0 to avoid this bug: https://github.com/isaacs/node-mkdirp/issues/31 + +## 1.0.0 +- Module is now name-spaced at `@mapbox/node-pre-gyp` and the original `node-pre-gyp` is deprecated. +- New: support for staging and production s3 targets (see README.md) +- BREAKING: no longer supporting `node_pre_gyp_accessKeyId` & `node_pre_gyp_secretAccessKey`, use `AWS_ACCESS_KEY_ID` & `AWS_SECRET_ACCESS_KEY` instead to authenticate against s3 for `info`, `publish`, and `unpublish` commands. +- Dropped node v6 support, added node v14 support +- Switched tests to use mapbox-owned bucket for testing +- Added coverage tracking and linting with eslint +- Added back support for symlinks inside the tarball +- Upgraded all test apps to N-API/node-addon-api +- New: support for staging and production s3 targets (see README.md) +- Added `node_pre_gyp_s3_host` env var which has priority over the `--s3_host` option or default. +- Replaced needle with node-fetch +- Added proxy support for node-fetch +- Upgraded to mkdirp@1.x + +## 0.17.0 +- Got travis + appveyor green again +- Added support for more node versions + +## 0.16.0 + +- Added Node 15 support in the local database (https://github.com/mapbox/node-pre-gyp/pull/520) + +## 0.15.0 + +- Bump dependency on `mkdirp` from `^0.5.1` to `^0.5.3` (https://github.com/mapbox/node-pre-gyp/pull/492) +- Bump dependency on `needle` from `^2.2.1` to `^2.5.0` (https://github.com/mapbox/node-pre-gyp/pull/502) +- Added Node 14 support in the local database (https://github.com/mapbox/node-pre-gyp/pull/501) + +## 0.14.0 + +- Defer modules requires in napi.js (https://github.com/mapbox/node-pre-gyp/pull/434) +- Bump dependency on `tar` from `^4` to `^4.4.2` (https://github.com/mapbox/node-pre-gyp/pull/454) +- Support extracting compiled binary from local offline mirror (https://github.com/mapbox/node-pre-gyp/pull/459) +- Added Node 13 support in the local database (https://github.com/mapbox/node-pre-gyp/pull/483) + +## 0.13.0 + +- Added Node 12 support in the local database (https://github.com/mapbox/node-pre-gyp/pull/449) + +## 0.12.0 + +- Fixed double-build problem with node v10 (https://github.com/mapbox/node-pre-gyp/pull/428) +- Added node 11 support in the local database (https://github.com/mapbox/node-pre-gyp/pull/422) + +## 0.11.0 + +- Fixed double-install problem with node v10 +- Significant N-API improvements (https://github.com/mapbox/node-pre-gyp/pull/405) + +## 0.10.3 + +- Now will use `request` over `needle` if request is installed. By default `needle` is used for `https`. This should unbreak proxy support that regressed in v0.9.0 + +## 0.10.2 + +- Fixed rc/deep-extent security vulnerability +- Fixed broken reinstall script do to incorrectly named get_best_napi_version + +## 0.10.1 + +- Fix needle error event (@medns) + +## 0.10.0 + +- Allow for a single-level module path when packing @allenluce (https://github.com/mapbox/node-pre-gyp/pull/371) +- Log warnings instead of errors when falling back @xzyfer (https://github.com/mapbox/node-pre-gyp/pull/366) +- Add Node.js v10 support to tests (https://github.com/mapbox/node-pre-gyp/pull/372) +- Remove retire.js from CI (https://github.com/mapbox/node-pre-gyp/pull/372) +- Remove support for Node.js v4 due to [EOL on April 30th, 2018](https://github.com/nodejs/Release/blob/7dd52354049cae99eed0e9fe01345b0722a86fde/schedule.json#L14) +- Update appveyor tests to install default NPM version instead of NPM v2.x for all Windows builds (https://github.com/mapbox/node-pre-gyp/pull/375) + +## 0.9.1 + +- Fixed regression (in v0.9.0) with support for http redirects @allenluce (https://github.com/mapbox/node-pre-gyp/pull/361) + +## 0.9.0 + +- Switched from using `request` to `needle` to reduce size of module deps (https://github.com/mapbox/node-pre-gyp/pull/350) + +## 0.8.0 + +- N-API support (@inspiredware) + +## 0.7.1 + +- Upgraded to tar v4.x + +## 0.7.0 + + - Updated request and hawk (#347) + - Dropped node v0.10.x support + +## 0.6.40 + + - Improved error reporting if an install fails + +## 0.6.39 + + - Support for node v9 + - Support for versioning on `{libc}` to allow binaries to work on non-glic linux systems like alpine linux + + +## 0.6.38 + + - Maintaining compatibility (for v0.6.x series) with node v0.10.x + +## 0.6.37 + + - Solved one part of #276: now now deduce the node ABI from the major version for node >= 2 even when not stored in the abi_crosswalk.json + - Fixed docs to avoid mentioning the deprecated and dangerous `prepublish` in package.json (#291) + - Add new node versions to crosswalk + - Ported tests to use tape instead of mocha + - Got appveyor tests passing by downgrading npm and node-gyp + +## 0.6.36 + + - Removed the running of `testbinary` during install. Because this was regressed for so long, it is too dangerous to re-enable by default. Developers needing validation can call `node-pre-gyp testbinary` directory. + - Fixed regression in v0.6.35 for electron installs (now skipping binary validation which is not yet supported for electron) + +## 0.6.35 + + - No longer recommending `npm ls` in `prepublish` (#291) + - Fixed testbinary command (#283) @szdavid92 + +## 0.6.34 + + - Added new node versions to crosswalk, including v8 + - Upgraded deps to latest versions, started using `^` instead of `~` for all deps. + +## 0.6.33 + + - Improved support for yarn + +## 0.6.32 + + - Honor npm configuration for CA bundles (@heikkipora) + - Add node-pre-gyp and npm versions to user agent (@addaleax) + - Updated various deps + - Add known node version for v7.x + +## 0.6.31 + + - Updated various deps + +## 0.6.30 + + - Update to npmlog@4.x and semver@5.3.x + - Add known node version for v6.5.0 + +## 0.6.29 + + - Add known node versions for v0.10.45, v0.12.14, v4.4.4, v5.11.1, and v6.1.0 + +## 0.6.28 + + - Now more verbose when remote binaries are not available. This is needed since npm is increasingly more quiet by default + and users need to know why builds are falling back to source compiles that might then error out. + +## 0.6.27 + + - Add known node version for node v6 + - Stopped bundling dependencies + - Documented method for module authors to avoid bundling node-pre-gyp + - See https://github.com/mapbox/node-pre-gyp/tree/master#configuring for details + +## 0.6.26 + + - Skip validation for nw runtime (https://github.com/mapbox/node-pre-gyp/pull/181) via @fleg + +## 0.6.25 + + - Improved support for auto-detection of electron runtime in `node-pre-gyp.find()` + - Pull request from @enlight - https://github.com/mapbox/node-pre-gyp/pull/187 + - Add known node version for 4.4.1 and 5.9.1 + +## 0.6.24 + + - Add known node version for 5.8.0, 5.9.0, and 4.4.0. + +## 0.6.23 + + - Add known node version for 0.10.43, 0.12.11, 4.3.2, and 5.7.1. + +## 0.6.22 + + - Add known node version for 4.3.1, and 5.7.0. + +## 0.6.21 + + - Add known node version for 0.10.42, 0.12.10, 4.3.0, and 5.6.0. + +## 0.6.20 + + - Add known node version for 4.2.5, 4.2.6, 5.4.0, 5.4.1,and 5.5.0. + +## 0.6.19 + + - Add known node version for 4.2.4 + +## 0.6.18 + + - Add new known node versions for 0.10.x, 0.12.x, 4.x, and 5.x + +## 0.6.17 + + - Re-tagged to fix packaging problem of `Error: Cannot find module 'isarray'` + +## 0.6.16 + + - Added known version in crosswalk for 5.1.0. + +## 0.6.15 + + - Upgraded tar-pack (https://github.com/mapbox/node-pre-gyp/issues/182) + - Support custom binary hosting mirror (https://github.com/mapbox/node-pre-gyp/pull/170) + - Added known version in crosswalk for 4.2.2. + +## 0.6.14 + + - Added node 5.x version + +## 0.6.13 + + - Added more known node 4.x versions + +## 0.6.12 + + - Added support for [Electron](http://electron.atom.io/). Just pass the `--runtime=electron` flag when building/installing. Thanks @zcbenz + +## 0.6.11 + + - Added known node and io.js versions including more 3.x and 4.x versions + +## 0.6.10 + + - Added known node and io.js versions including 3.x and 4.x versions + - Upgraded `tar` dep + +## 0.6.9 + + - Upgraded `rc` dep + - Updated known io.js version: v2.4.0 + +## 0.6.8 + + - Upgraded `semver` and `rimraf` deps + - Updated known node and io.js versions + +## 0.6.7 + + - Fixed `node_abi` versions for io.js 1.1.x -> 1.8.x (should be 43, but was stored as 42) (refs https://github.com/iojs/build/issues/94) + +## 0.6.6 + + - Updated with known io.js 2.0.0 version + +## 0.6.5 + + - Now respecting `npm_config_node_gyp` (https://github.com/npm/npm/pull/4887) + - Updated to semver@4.3.2 + - Updated known node v0.12.x versions and io.js 1.x versions. + +## 0.6.4 + + - Improved support for `io.js` (@fengmk2) + - Test coverage improvements (@mikemorris) + - Fixed support for `--dist-url` that regressed in 0.6.3 + +## 0.6.3 + + - Added support for passing raw options to node-gyp using `--` separator. Flags passed after + the `--` to `node-pre-gyp configure` will be passed directly to gyp while flags passed + after the `--` will be passed directly to make/visual studio. + - Added `node-pre-gyp configure` command to be able to call `node-gyp configure` directly + - Fix issue with require validation not working on windows 7 (@edgarsilva) + +## 0.6.2 + + - Support for io.js >= v1.0.2 + - Deferred require of `request` and `tar` to help speed up command line usage of `node-pre-gyp`. + +## 0.6.1 + + - Fixed bundled `tar` version + +## 0.6.0 + + - BREAKING: node odd releases like v0.11.x now use `major.minor.patch` for `{node_abi}` instead of `NODE_MODULE_VERSION` (#124) + - Added support for `toolset` option in versioning. By default is an empty string but `--toolset` can be passed to publish or install to select alternative binaries that target a custom toolset like C++11. For example to target Visual Studio 2014 modules like node-sqlite3 use `--toolset=v140`. + - Added support for `--no-rollback` option to request that a failed binary test does not remove the binary module leaves it in place. + - Added support for `--update-binary` option to request an existing binary be re-installed and the check for a valid local module be skipped. + - Added support for passing build options from `npm` through `node-pre-gyp` to `node-gyp`: `--nodedir`, `--disturl`, `--python`, and `--msvs_version` + +## 0.5.31 + + - Added support for deducing node_abi for node.js runtime from previous release if the series is even + - Added support for --target=0.10.33 + +## 0.5.30 + + - Repackaged with latest bundled deps + +## 0.5.29 + + - Added support for semver `build`. + - Fixed support for downloading from urls that include `+`. + +## 0.5.28 + + - Now reporting unix style paths only in reveal command + +## 0.5.27 + + - Fixed support for auto-detecting s3 bucket name when it contains `.` - @taavo + - Fixed support for installing when path contains a `'` - @halfdan + - Ported tests to mocha + +## 0.5.26 + + - Fix node-webkit support when `--target` option is not provided + +## 0.5.25 + + - Fix bundling of deps + +## 0.5.24 + + - Updated ABI crosswalk to incldue node v0.10.30 and v0.10.31 + +## 0.5.23 + + - Added `reveal` command. Pass no options to get all versioning data as json. Pass a second arg to grab a single versioned property value + - Added support for `--silent` (shortcut for `--loglevel=silent`) + +## 0.5.22 + + - Fixed node-webkit versioning name (NOTE: node-webkit support still experimental) + +## 0.5.21 + + - New package to fix `shasum check failed` error with v0.5.20 + +## 0.5.20 + + - Now versioning node-webkit binaries based on major.minor.patch - assuming no compatible ABI across versions (#90) + +## 0.5.19 + + - Updated to know about more node-webkit releases + +## 0.5.18 + + - Updated to know about more node-webkit releases + +## 0.5.17 + + - Updated to know about node v0.10.29 release + +## 0.5.16 + + - Now supporting all aws-sdk configuration parameters (http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html) (#86) + +## 0.5.15 + + - Fixed installation of windows packages sub directories on unix systems (#84) + +## 0.5.14 + + - Finished support for cross building using `--target_platform` option (#82) + - Now skipping binary validation on install if target arch/platform do not match the host. + - Removed multi-arch validing for OS X since it required a FAT node.js binary + +## 0.5.13 + + - Fix problem in 0.5.12 whereby the wrong versions of mkdirp and semver where bundled. + +## 0.5.12 + + - Improved support for node-webkit (@Mithgol) + +## 0.5.11 + + - Updated target versions listing + +## 0.5.10 + + - Fixed handling of `-debug` flag passed directory to node-pre-gyp (#72) + - Added optional second arg to `node_pre_gyp.find` to customize the default versioning options used to locate the runtime binary + - Failed install due to `testbinary` check failure no longer leaves behind binary (#70) + +## 0.5.9 + + - Fixed regression in `testbinary` command causing installs to fail on windows with 0.5.7 (#60) + +## 0.5.8 + + - Started bundling deps + +## 0.5.7 + + - Fixed the `testbinary` check, which is used to determine whether to re-download or source compile, to work even in complex dependency situations (#63) + - Exposed the internal `testbinary` command in node-pre-gyp command line tool + - Fixed minor bug so that `fallback_to_build` option is always respected + +## 0.5.6 + + - Added support for versioning on the `name` value in `package.json` (#57). + - Moved to using streams for reading tarball when publishing (#52) + +## 0.5.5 + + - Improved binary validation that also now works with node-webkit (@Mithgol) + - Upgraded test apps to work with node v0.11.x + - Improved test coverage + +## 0.5.4 + + - No longer depends on external install of node-gyp for compiling builds. + +## 0.5.3 + + - Reverted fix for debian/nodejs since it broke windows (#45) + +## 0.5.2 + + - Support for debian systems where the node binary is named `nodejs` (#45) + - Added `bin/node-pre-gyp.cmd` to be able to run command on windows locally (npm creates an .npm automatically when globally installed) + - Updated abi-crosswalk with node v0.10.26 entry. + +## 0.5.1 + + - Various minor bug fixes, several improving windows support for publishing. + +## 0.5.0 + + - Changed property names in `binary` object: now required are `module_name`, `module_path`, and `host`. + - Now `module_path` supports versioning, which allows developers to opt-in to using a versioned install path (#18). + - Added `remote_path` which also supports versioning. + - Changed `remote_uri` to `host`. + +## 0.4.2 + + - Added support for `--target` flag to request cross-compile against a specific node/node-webkit version. + - Added preliminary support for node-webkit + - Fixed support for `--target_arch` option being respected in all cases. + +## 0.4.1 + + - Fixed exception when only stderr is available in binary test (@bendi / #31) + +## 0.4.0 + + - Enforce only `https:` based remote publishing access. + - Added `node-pre-gyp info` command to display listing of published binaries + - Added support for changing the directory node-pre-gyp should build in with the `-C/--directory` option. + - Added support for S3 prefixes. + +## 0.3.1 + + - Added `unpublish` command. + - Fixed module path construction in tests. + - Added ability to disable falling back to build behavior via `npm install --fallback-to-build=false` which overrides setting in a depedencies package.json `install` target. + +## 0.3.0 + + - Support for packaging all files in `module_path` directory - see `app4` for example + - Added `testpackage` command. + - Changed `clean` command to only delete `.node` not entire `build` directory since node-gyp will handle that. + - `.node` modules must be in a folder of there own since tar-pack will remove everything when it unpacks. diff --git a/node_modules/@mapbox/node-pre-gyp/LICENSE b/node_modules/@mapbox/node-pre-gyp/LICENSE new file mode 100644 index 0000000..8f5fce9 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/LICENSE @@ -0,0 +1,27 @@ +Copyright (c), Mapbox + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of node-pre-gyp nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@mapbox/node-pre-gyp/README.md b/node_modules/@mapbox/node-pre-gyp/README.md new file mode 100644 index 0000000..fcb7812 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/README.md @@ -0,0 +1,742 @@ +# @mapbox/node-pre-gyp + +#### @mapbox/node-pre-gyp makes it easy to publish and install Node.js C++ addons from binaries + +[![Build Status](https://travis-ci.com/mapbox/node-pre-gyp.svg?branch=master)](https://travis-ci.com/mapbox/node-pre-gyp) +[![Build status](https://ci.appveyor.com/api/projects/status/3nxewb425y83c0gv)](https://ci.appveyor.com/project/Mapbox/node-pre-gyp) + +`@mapbox/node-pre-gyp` stands between [npm](https://github.com/npm/npm) and [node-gyp](https://github.com/Tootallnate/node-gyp) and offers a cross-platform method of binary deployment. + +### Special note on previous package + +On Feb 9th, 2021 `@mapbox/node-pre-gyp@1.0.0` was [released](./CHANGELOG.md). Older, unscoped versions that are not part of the `@mapbox` org are deprecated and only `@mapbox/node-pre-gyp` will see updates going forward. To upgrade to the new package do: + +``` +npm uninstall node-pre-gyp --save +npm install @mapbox/node-pre-gyp --save +``` + +### Features + + - A command line tool called `node-pre-gyp` that can install your package's C++ module from a binary. + - A variety of developer targeted commands for packaging, testing, and publishing binaries. + - A JavaScript module that can dynamically require your installed binary: `require('@mapbox/node-pre-gyp').find` + +For a hello world example of a module packaged with `node-pre-gyp` see and [the wiki ](https://github.com/mapbox/node-pre-gyp/wiki/Modules-using-node-pre-gyp) for real world examples. + +## Credits + + - The module is modeled after [node-gyp](https://github.com/Tootallnate/node-gyp) by [@Tootallnate](https://github.com/Tootallnate) + - Motivation for initial development came from [@ErisDS](https://github.com/ErisDS) and the [Ghost Project](https://github.com/TryGhost/Ghost). + - Development is sponsored by [Mapbox](https://www.mapbox.com/) + +## FAQ + +See the [Frequently Ask Questions](https://github.com/mapbox/node-pre-gyp/wiki/FAQ). + +## Depends + + - Node.js >= node v8.x + +## Install + +`node-pre-gyp` is designed to be installed as a local dependency of your Node.js C++ addon and accessed like: + + ./node_modules/.bin/node-pre-gyp --help + +But you can also install it globally: + + npm install @mapbox/node-pre-gyp -g + +## Usage + +### Commands + +View all possible commands: + + node-pre-gyp --help + +- clean - Remove the entire folder containing the compiled .node module +- install - Install pre-built binary for module +- reinstall - Run "clean" and "install" at once +- build - Compile the module by dispatching to node-gyp or nw-gyp +- rebuild - Run "clean" and "build" at once +- package - Pack binary into tarball +- testpackage - Test that the staged package is valid +- publish - Publish pre-built binary +- unpublish - Unpublish pre-built binary +- info - Fetch info on published binaries + +You can also chain commands: + + node-pre-gyp clean build unpublish publish info + +### Options + +Options include: + + - `-C/--directory`: run the command in this directory + - `--build-from-source`: build from source instead of using pre-built binary + - `--update-binary`: reinstall by replacing previously installed local binary with remote binary + - `--runtime=node-webkit`: customize the runtime: `node`, `electron` and `node-webkit` are the valid options + - `--fallback-to-build`: fallback to building from source if pre-built binary is not available + - `--target=0.4.0`: Pass the target node or node-webkit version to compile against + - `--target_arch=ia32`: Pass the target arch and override the host `arch`. Valid values are 'ia32','x64', or `arm`. + - `--target_platform=win32`: Pass the target platform and override the host `platform`. Valid values are `linux`, `darwin`, `win32`, `sunos`, `freebsd`, `openbsd`, and `aix`. + +Both `--build-from-source` and `--fallback-to-build` can be passed alone or they can provide values. You can pass `--fallback-to-build=false` to override the option as declared in package.json. In addition to being able to pass `--build-from-source` you can also pass `--build-from-source=myapp` where `myapp` is the name of your module. + +For example: `npm install --build-from-source=myapp`. This is useful if: + + - `myapp` is referenced in the package.json of a larger app and therefore `myapp` is being installed as a dependency with `npm install`. + - The larger app also depends on other modules installed with `node-pre-gyp` + - You only want to trigger a source compile for `myapp` and the other modules. + +### Configuring + +This is a guide to configuring your module to use node-pre-gyp. + +#### 1) Add new entries to your `package.json` + + - Add `@mapbox/node-pre-gyp` to `dependencies` + - Add `aws-sdk` as a `devDependency` + - Add a custom `install` script + - Declare a `binary` object + +This looks like: + +```js + "dependencies" : { + "@mapbox/node-pre-gyp": "1.x" + }, + "devDependencies": { + "aws-sdk": "2.x" + } + "scripts": { + "install": "node-pre-gyp install --fallback-to-build" + }, + "binary": { + "module_name": "your_module", + "module_path": "./lib/binding/", + "host": "https://your_module.s3-us-west-1.amazonaws.com" + } +``` + +For a full example see [node-addon-examples's package.json](https://github.com/springmeyer/node-addon-example/blob/master/package.json). + +Let's break this down: + + - Dependencies need to list `node-pre-gyp` + - Your devDependencies should list `aws-sdk` so that you can run `node-pre-gyp publish` locally or a CI system. We recommend using `devDependencies` only since `aws-sdk` is large and not needed for `node-pre-gyp install` since it only uses http to fetch binaries + - Your `scripts` section should override the `install` target with `"install": "node-pre-gyp install --fallback-to-build"`. This allows node-pre-gyp to be used instead of the default npm behavior of always source compiling with `node-gyp` directly. + - Your package.json should contain a `binary` section describing key properties you provide to allow node-pre-gyp to package optimally. They are detailed below. + +Note: in the past we recommended putting `@mapbox/node-pre-gyp` in the `bundledDependencies`, but we no longer recommend this. In the past there were npm bugs (with node versions 0.10.x) that could lead to node-pre-gyp not being available at the right time during install (unless we bundled). This should no longer be the case. Also, for a time we recommended using `"preinstall": "npm install @mapbox/node-pre-gyp"` as an alternative method to avoid needing to bundle. But this did not behave predictably across all npm versions - see https://github.com/mapbox/node-pre-gyp/issues/260 for the details. So we do not recommend using `preinstall` to install `@mapbox/node-pre-gyp`. More history on this at https://github.com/strongloop/fsevents/issues/157#issuecomment-265545908. + +##### The `binary` object has three required properties + +###### module_name + +The name of your native node module. This value must: + + - Match the name passed to [the NODE_MODULE macro](http://nodejs.org/api/addons.html#addons_hello_world) + - Must be a valid C variable name (e.g. it cannot contain `-`) + - Should not include the `.node` extension. + +###### module_path + +The location your native module is placed after a build. This should be an empty directory without other Javascript files. This entire directory will be packaged in the binary tarball. When installing from a remote package this directory will be overwritten with the contents of the tarball. + +Note: This property supports variables based on [Versioning](#versioning). + +###### host + +A url to the remote location where you've published tarball binaries (must be `https` not `http`). + +It is highly recommended that you use Amazon S3. The reasons are: + + - Various node-pre-gyp commands like `publish` and `info` only work with an S3 host. + - S3 is a very solid hosting platform for distributing large files. + - We provide detail documentation for using [S3 hosting](#s3-hosting) with node-pre-gyp. + +Why then not require S3? Because while some applications using node-pre-gyp need to distribute binaries as large as 20-30 MB, others might have very small binaries and might wish to store them in a GitHub repo. This is not recommended, but if an author really wants to host in a non-S3 location then it should be possible. + +It should also be mentioned that there is an optional and entirely separate npm module called [node-pre-gyp-github](https://github.com/bchr02/node-pre-gyp-github) which is intended to complement node-pre-gyp and be installed along with it. It provides the ability to store and publish your binaries within your repositories GitHub Releases if you would rather not use S3 directly. Installation and usage instructions can be found [here](https://github.com/bchr02/node-pre-gyp-github), but the basic premise is that instead of using the ```node-pre-gyp publish``` command you would use ```node-pre-gyp-github publish```. + +##### The `binary` object other optional S3 properties + +If you are not using a standard s3 path like `bucket_name.s3(.-)region.amazonaws.com`, you might get an error on `publish` because node-pre-gyp extracts the region and bucket from the `host` url. For example, you may have an on-premises s3-compatible storage server, or may have configured a specific dns redirecting to an s3 endpoint. In these cases, you can explicitly set the `region` and `bucket` properties to tell node-pre-gyp to use these values instead of guessing from the `host` property. The following values can be used in the `binary` section: + +###### host + +The url to the remote server root location (must be `https` not `http`). + +###### bucket + +The bucket name where your tarball binaries should be located. + +###### region + +Your S3 server region. + +###### s3ForcePathStyle + +Set `s3ForcePathStyle` to true if the endpoint url should not be prefixed with the bucket name. If false (default), the server endpoint would be constructed as `bucket_name.your_server.com`. + +##### The `binary` object has optional properties + +###### remote_path + +It **is recommended** that you customize this property. This is an extra path to use for publishing and finding remote tarballs. The default value for `remote_path` is `""` meaning that if you do not provide it then all packages will be published at the base of the `host`. It is recommended to provide a value like `./{name}/v{version}` to help organize remote packages in the case that you choose to publish multiple node addons to the same `host`. + +Note: This property supports variables based on [Versioning](#versioning). + +###### package_name + +It is **not recommended** to override this property unless you are also overriding the `remote_path`. This is the versioned name of the remote tarball containing the binary `.node` module and any supporting files you've placed inside the `module_path` directory. Unless you specify `package_name` in your `package.json` then it defaults to `{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz` which allows your binary to work across node versions, platforms, and architectures. If you are using `remote_path` that is also versioned by `./{module_name}/v{version}` then you could remove these variables from the `package_name` and just use: `{node_abi}-{platform}-{arch}.tar.gz`. Then your remote tarball will be looked up at, for example, `https://example.com/your-module/v0.1.0/node-v11-linux-x64.tar.gz`. + +Avoiding the version of your module in the `package_name` and instead only embedding in a directory name can be useful when you want to make a quick tag of your module that does not change any C++ code. In this case you can just copy binaries to the new version behind the scenes like: + +```sh +aws s3 sync --acl public-read s3://mapbox-node-binary/sqlite3/v3.0.3/ s3://mapbox-node-binary/sqlite3/v3.0.4/ +``` + +Note: This property supports variables based on [Versioning](#versioning). + +#### 2) Add a new target to binding.gyp + +`node-pre-gyp` calls out to `node-gyp` to compile the module and passes variables along like [module_name](#module_name) and [module_path](#module_path). + +A new target must be added to `binding.gyp` that moves the compiled `.node` module from `./build/Release/module_name.node` into the directory specified by `module_path`. + +Add a target like this at the end of your `targets` list: + +```js + { + "target_name": "action_after_build", + "type": "none", + "dependencies": [ "<(module_name)" ], + "copies": [ + { + "files": [ "<(PRODUCT_DIR)/<(module_name).node" ], + "destination": "<(module_path)" + } + ] + } +``` + +For a full example see [node-addon-example's binding.gyp](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/binding.gyp). + +#### 3) Dynamically require your `.node` + +Inside the main js file that requires your addon module you are likely currently doing: + +```js +var binding = require('../build/Release/binding.node'); +``` + +or: + +```js +var bindings = require('./bindings') +``` + +Change those lines to: + +```js +var binary = require('@mapbox/node-pre-gyp'); +var path = require('path'); +var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json'))); +var binding = require(binding_path); +``` + +For a full example see [node-addon-example's index.js](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/index.js#L1-L4) + +#### 4) Build and package your app + +Now build your module from source: + + npm install --build-from-source + +The `--build-from-source` tells `node-pre-gyp` to not look for a remote package and instead dispatch to node-gyp to build. + +Now `node-pre-gyp` should now also be installed as a local dependency so the command line tool it offers can be found at `./node_modules/.bin/node-pre-gyp`. + +#### 5) Test + +Now `npm test` should work just as it did before. + +#### 6) Publish the tarball + +Then package your app: + + ./node_modules/.bin/node-pre-gyp package + +Once packaged, now you can publish: + + ./node_modules/.bin/node-pre-gyp publish + +Currently the `publish` command pushes your binary to S3. This requires: + + - You have installed `aws-sdk` with `npm install aws-sdk` + - You have created a bucket already. + - The `host` points to an S3 http or https endpoint. + - You have configured node-pre-gyp to read your S3 credentials (see [S3 hosting](#s3-hosting) for details). + +You can also host your binaries elsewhere. To do this requires: + + - You manually publish the binary created by the `package` command to an `https` endpoint + - Ensure that the `host` value points to your custom `https` endpoint. + +#### 7) Automate builds + +Now you need to publish builds for all the platforms and node versions you wish to support. This is best automated. + + - See [Appveyor Automation](#appveyor-automation) for how to auto-publish builds on Windows. + - See [Travis Automation](#travis-automation) for how to auto-publish builds on OS X and Linux. + +#### 8) You're done! + +Now publish your module to the npm registry. Users will now be able to install your module from a binary. + +What will happen is this: + +1. `npm install ` will pull from the npm registry +2. npm will run the `install` script which will call out to `node-pre-gyp` +3. `node-pre-gyp` will fetch the binary `.node` module and unpack in the right place +4. Assuming that all worked, you are done + +If a a binary was not available for a given platform and `--fallback-to-build` was used then `node-gyp rebuild` will be called to try to source compile the module. + +#### 9) One more option + +It may be that you want to work with two s3 buckets, one for staging and one for production; this +arrangement makes it less likely to accidentally overwrite a production binary. It also allows the production +environment to have more restrictive permissions than staging while still enabling publishing when +developing and testing. + +The binary.host property can be set at execution time. In order to do so all of the following conditions +must be true. + +- binary.host is falsey or not present +- binary.staging_host is not empty +- binary.production_host is not empty + +If any of these checks fail then the operation will not perform execution time determination of the s3 target. + +If the command being executed is either "publish" or "unpublish" then the default is set to `binary.staging_host`. In all other cases +the default is `binary.production_host`. + +The command-line options `--s3_host=staging` or `--s3_host=production` override the default. If `s3_host` +is present and not `staging` or `production` an exception is thrown. + +This allows installing from staging by specifying `--s3_host=staging`. And it requires specifying +`--s3_option=production` in order to publish to, or unpublish from, production, making accidental errors less likely. + +## Node-API Considerations + +[Node-API](https://nodejs.org/api/n-api.html#n_api_node_api), which was previously known as N-API, is an ABI-stable alternative to previous technologies such as [nan](https://github.com/nodejs/nan) which are tied to a specific Node runtime engine. Node-API is Node runtime engine agnostic and guarantees modules created today will continue to run, without changes, into the future. + +Using `node-pre-gyp` with Node-API projects requires a handful of additional configuration values and imposes some additional requirements. + +The most significant difference is that an Node-API module can be coded to target multiple Node-API versions. Therefore, an Node-API module must declare in its `package.json` file which Node-API versions the module is designed to run against. In addition, since multiple builds may be required for a single module, path and file names must be specified in way that avoids naming conflicts. + +### The `napi_versions` array property + +A Node-API module must declare in its `package.json` file, the Node-API versions the module is intended to support. This is accomplished by including an `napi-versions` array property in the `binary` object. For example: + +```js +"binary": { + "module_name": "your_module", + "module_path": "your_module_path", + "host": "https://your_bucket.s3-us-west-1.amazonaws.com", + "napi_versions": [1,3] + } +``` + +If the `napi_versions` array property is *not* present, `node-pre-gyp` operates as it always has. Including the `napi_versions` array property instructs `node-pre-gyp` that this is a Node-API module build. + +When the `napi_versions` array property is present, `node-pre-gyp` fires off multiple operations, one for each of the Node-API versions in the array. In the example above, two operations are initiated, one for Node-API version 1 and second for Node-API version 3. How this version number is communicated is described next. + +### The `napi_build_version` value + +For each of the Node-API module operations `node-pre-gyp` initiates, it ensures that the `napi_build_version` is set appropriately. + +This value is of importance in two areas: + +1. The C/C++ code which needs to know against which Node-API version it should compile. +2. `node-pre-gyp` itself which must assign appropriate path and file names to avoid collisions. + +### Defining `NAPI_VERSION` for the C/C++ code + +The `napi_build_version` value is communicated to the C/C++ code by adding this code to the `binding.gyp` file: + +``` +"defines": [ + "NAPI_VERSION=<(napi_build_version)", +] +``` + +This ensures that `NAPI_VERSION`, an integer value, is declared appropriately to the C/C++ code for each build. + +> Note that earlier versions of this document recommended defining the symbol `NAPI_BUILD_VERSION`. `NAPI_VERSION` is preferred because it used by the Node-API C/C++ headers to configure the specific Node-API versions being requested. + +### Path and file naming requirements in `package.json` + +Since `node-pre-gyp` fires off multiple operations for each request, it is essential that path and file names be created in such a way as to avoid collisions. This is accomplished by imposing additional path and file naming requirements. + +Specifically, when performing Node-API builds, the `{napi_build_version}` text configuration value *must* be present in the `module_path` property. In addition, the `{napi_build_version}` text configuration value *must* be present in either the `remote_path` or `package_name` property. (No problem if it's in both.) + +Here's an example: + +```js +"binary": { + "module_name": "your_module", + "module_path": "./lib/binding/napi-v{napi_build_version}", + "remote_path": "./{module_name}/v{version}/{configuration}/", + "package_name": "{platform}-{arch}-napi-v{napi_build_version}.tar.gz", + "host": "https://your_bucket.s3-us-west-1.amazonaws.com", + "napi_versions": [1,3] + } +``` + +## Supporting both Node-API and NAN builds + +You may have a legacy native add-on that you wish to continue supporting for those versions of Node that do not support Node-API, as you add Node-API support for later Node versions. This can be accomplished by specifying the `node_napi_label` configuration value in the package.json `binary.package_name` property. + +Placing the configuration value `node_napi_label` in the package.json `binary.package_name` property instructs `node-pre-gyp` to build all viable Node-API binaries supported by the current Node instance. If the current Node instance does not support Node-API, `node-pre-gyp` will request a traditional, non-Node-API build. + +The configuration value `node_napi_label` is set by `node-pre-gyp` to the type of build created, `napi` or `node`, and the version number. For Node-API builds, the string contains the Node-API version nad has values like `napi-v3`. For traditional, non-Node-API builds, the string contains the ABI version with values like `node-v46`. + +Here's how the `binary` configuration above might be changed to support both Node-API and NAN builds: + +```js +"binary": { + "module_name": "your_module", + "module_path": "./lib/binding/{node_napi_label}", + "remote_path": "./{module_name}/v{version}/{configuration}/", + "package_name": "{platform}-{arch}-{node_napi_label}.tar.gz", + "host": "https://your_bucket.s3-us-west-1.amazonaws.com", + "napi_versions": [1,3] + } +``` + +The C/C++ symbol `NAPI_VERSION` can be used to distinguish Node-API and non-Node-API builds. The value of `NAPI_VERSION` is set to the integer Node-API version for Node-API builds and is set to `0` for non-Node-API builds. + +For example: + +```C +#if NAPI_VERSION +// Node-API code goes here +#else +// NAN code goes here +#endif +``` + +### Two additional configuration values + +The following two configuration values, which were implemented in previous versions of `node-pre-gyp`, continue to exist, but have been replaced by the `node_napi_label` configuration value described above. + +1. `napi_version` If Node-API is supported by the currently executing Node instance, this value is the Node-API version number supported by Node. If Node-API is not supported, this value is an empty string. + +2. `node_abi_napi` If the value returned for `napi_version` is non empty, this value is `'napi'`. If the value returned for `napi_version` is empty, this value is the value returned for `node_abi`. + +These values are present for use in the `binding.gyp` file and may be used as `{napi_version}` and `{node_abi_napi}` for text substituion in the `binary` properties of the `package.json` file. + +## S3 Hosting + +You can host wherever you choose but S3 is cheap, `node-pre-gyp publish` expects it, and S3 can be integrated well with [Travis.ci](http://travis-ci.org) to automate builds for OS X and Ubuntu, and with [Appveyor](http://appveyor.com) to automate builds for Windows. Here is an approach to do this: + +First, get setup locally and test the workflow: + +#### 1) Create an S3 bucket + +And have your **key** and **secret key** ready for writing to the bucket. + +It is recommended to create a IAM user with a policy that only gives permissions to the specific bucket you plan to publish to. This can be done in the [IAM console](https://console.aws.amazon.com/iam/) by: 1) adding a new user, 2) choosing `Attach User Policy`, 3) Using the `Policy Generator`, 4) selecting `Amazon S3` for the service, 5) adding the actions: `DeleteObject`, `GetObject`, `GetObjectAcl`, `ListBucket`, `HeadBucket`, `PutObject`, `PutObjectAcl`, 6) adding an ARN of `arn:aws:s3:::bucket/*` (replacing `bucket` with your bucket name), and finally 7) clicking `Add Statement` and saving the policy. It should generate a policy like: + +```js +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "objects", + "Effect": "Allow", + "Action": [ + "s3:PutObject", + "s3:GetObjectAcl", + "s3:GetObject", + "s3:DeleteObject", + "s3:PutObjectAcl" + ], + "Resource": "arn:aws:s3:::your-bucket-name/*" + }, + { + "Sid": "bucket", + "Effect": "Allow", + "Action": "s3:ListBucket", + "Resource": "arn:aws:s3:::your-bucket-name" + }, + { + "Sid": "buckets", + "Effect": "Allow", + "Action": "s3:HeadBucket", + "Resource": "*" + } + ] +} +``` + +#### 2) Install node-pre-gyp + +Either install it globally: + + npm install node-pre-gyp -g + +Or put the local version on your PATH + + export PATH=`pwd`/node_modules/.bin/:$PATH + +#### 3) Configure AWS credentials + +It is recommended to configure the AWS JS SDK v2 used internally by `node-pre-gyp` by setting these environment variables: + +- AWS_ACCESS_KEY_ID +- AWS_SECRET_ACCESS_KEY + +But also you can also use the `Shared Config File` mentioned [in the AWS JS SDK v2 docs](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/configuring-the-jssdk.html) + +#### 4) Package and publish your build + +Install the `aws-sdk`: + + npm install aws-sdk + +Then publish: + + node-pre-gyp package publish + +Note: if you hit an error like `Hostname/IP doesn't match certificate's altnames` it may mean that you need to provide the `region` option in your config. + +## Appveyor Automation + +[Appveyor](http://www.appveyor.com/) can build binaries and publish the results per commit and supports: + + - Windows Visual Studio 2013 and related compilers + - Both 64 bit (x64) and 32 bit (x86) build configurations + - Multiple Node.js versions + +For an example of doing this see [node-sqlite3's appveyor.yml](https://github.com/mapbox/node-sqlite3/blob/master/appveyor.yml). + +Below is a guide to getting set up: + +#### 1) Create a free Appveyor account + +Go to https://ci.appveyor.com/signup/free and sign in with your GitHub account. + +#### 2) Create a new project + +Go to https://ci.appveyor.com/projects/new and select the GitHub repo for your module + +#### 3) Add appveyor.yml and push it + +Once you have committed an `appveyor.yml` ([appveyor.yml reference](http://www.appveyor.com/docs/appveyor-yml)) to your GitHub repo and pushed it AppVeyor should automatically start building your project. + +#### 4) Create secure variables + +Encrypt your S3 AWS keys by going to and hitting the `encrypt` button. + +Then paste the result into your `appveyor.yml` + +```yml +environment: + AWS_ACCESS_KEY_ID: + secure: Dn9HKdLNYvDgPdQOzRq/DqZ/MPhjknRHB1o+/lVU8MA= + AWS_SECRET_ACCESS_KEY: + secure: W1rwNoSnOku1r+28gnoufO8UA8iWADmL1LiiwH9IOkIVhDTNGdGPJqAlLjNqwLnL +``` + +NOTE: keys are per account but not per repo (this is difference than Travis where keys are per repo but not related to the account used to encrypt them). + +#### 5) Hook up publishing + +Just put `node-pre-gyp package publish` in your `appveyor.yml` after `npm install`. + +#### 6) Publish when you want + +You might wish to publish binaries only on a specific commit. To do this you could borrow from the [Travis CI idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`: + + SET CM=%APPVEYOR_REPO_COMMIT_MESSAGE% + if not "%CM%" == "%CM:[publish binary]=%" node-pre-gyp --msvs_version=2013 publish + +If your commit message contains special characters (e.g. `&`) this method might fail. An alternative is to use PowerShell, which gives you additional possibilities, like ignoring case by using `ToLower()`: + + ps: if($env:APPVEYOR_REPO_COMMIT_MESSAGE.ToLower().Contains('[publish binary]')) { node-pre-gyp --msvs_version=2013 publish } + +Remember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package. + +## Travis Automation + +[Travis](https://travis-ci.org/) can push to S3 after a successful build and supports both: + + - Ubuntu Precise and OS X (64 bit) + - Multiple Node.js versions + +For an example of doing this see [node-add-example's .travis.yml](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/.travis.yml). + +Note: if you need 32 bit binaries, this can be done from a 64 bit Travis machine. See [the node-sqlite3 scripts for an example of doing this](https://github.com/mapbox/node-sqlite3/blob/bae122aa6a2b8a45f6b717fab24e207740e32b5d/scripts/build_against_node.sh#L54-L74). + +Below is a guide to getting set up: + +#### 1) Install the Travis gem + + gem install travis + +#### 2) Create secure variables + +Make sure you run this command from within the directory of your module. + +Use `travis-encrypt` like: + + travis encrypt AWS_ACCESS_KEY_ID=${node_pre_gyp_accessKeyId} + travis encrypt AWS_SECRET_ACCESS_KEY=${node_pre_gyp_secretAccessKey} + +Then put those values in your `.travis.yml` like: + +```yaml +env: + global: + - secure: F+sEL/v56CzHqmCSSES4pEyC9NeQlkoR0Gs/ZuZxX1ytrj8SKtp3MKqBj7zhIclSdXBz4Ev966Da5ctmcTd410p0b240MV6BVOkLUtkjZJyErMBOkeb8n8yVfSoeMx8RiIhBmIvEn+rlQq+bSFis61/JkE9rxsjkGRZi14hHr4M= + - secure: o2nkUQIiABD139XS6L8pxq3XO5gch27hvm/gOdV+dzNKc/s2KomVPWcOyXNxtJGhtecAkABzaW8KHDDi5QL1kNEFx6BxFVMLO8rjFPsMVaBG9Ks6JiDQkkmrGNcnVdxI/6EKTLHTH5WLsz8+J7caDBzvKbEfTux5EamEhxIWgrI= +``` + +More details on Travis encryption at http://about.travis-ci.org/docs/user/encryption-keys/. + +#### 3) Hook up publishing + +Just put `node-pre-gyp package publish` in your `.travis.yml` after `npm install`. + +##### OS X publishing + +If you want binaries for OS X in addition to linux you can enable [multi-os for Travis](http://docs.travis-ci.com/user/multi-os/#Setting-.travis.yml) + +Use a configuration like: + +```yml + +language: cpp + +os: +- linux +- osx + +env: + matrix: + - NODE_VERSION="4" + - NODE_VERSION="6" + +before_install: +- rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm +- source ~/.nvm/nvm.sh +- nvm install $NODE_VERSION +- nvm use $NODE_VERSION +``` + +See [Travis OS X Gotchas](#travis-os-x-gotchas) for why we replace `language: node_js` and `node_js:` sections with `language: cpp` and a custom matrix. + +Also create platform specific sections for any deps that need install. For example if you need libpng: + +```yml +- if [ $(uname -s) == 'Linux' ]; then apt-get install libpng-dev; fi; +- if [ $(uname -s) == 'Darwin' ]; then brew install libpng; fi; +``` + +For detailed multi-OS examples see [node-mapnik](https://github.com/mapnik/node-mapnik/blob/master/.travis.yml) and [node-sqlite3](https://github.com/mapbox/node-sqlite3/blob/master/.travis.yml). + +##### Travis OS X Gotchas + +First, unlike the Travis Linux machines, the OS X machines do not put `node-pre-gyp` on PATH by default. To do so you will need to: + +```sh +export PATH=$(pwd)/node_modules/.bin:${PATH} +``` + +Second, the OS X machines do not support using a matrix for installing different Node.js versions. So you need to bootstrap the installation of Node.js in a cross platform way. + +By doing: + +```yml +env: + matrix: + - NODE_VERSION="4" + - NODE_VERSION="6" + +before_install: + - rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm + - source ~/.nvm/nvm.sh + - nvm install $NODE_VERSION + - nvm use $NODE_VERSION +``` + +You can easily recreate the previous behavior of this matrix: + +```yml +node_js: + - "4" + - "6" +``` + +#### 4) Publish when you want + +You might wish to publish binaries only on a specific commit. To do this you could borrow from the [Travis CI idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`: + + COMMIT_MESSAGE=$(git log --format=%B --no-merges -n 1 | tr -d '\n') + if [[ ${COMMIT_MESSAGE} =~ "[publish binary]" ]]; then node-pre-gyp publish; fi; + +Then you can trigger new binaries to be built like: + + git commit -a -m "[publish binary]" + +Or, if you don't have any changes to make simply run: + + git commit --allow-empty -m "[publish binary]" + +WARNING: if you are working in a pull request and publishing binaries from there then you will want to avoid double publishing when Travis CI builds both the `push` and `pr`. You only want to run the publish on the `push` commit. See https://github.com/Project-OSRM/node-osrm/blob/8eb837abe2e2e30e595093d16e5354bc5c573575/scripts/is_pr_merge.sh which is called from https://github.com/Project-OSRM/node-osrm/blob/8eb837abe2e2e30e595093d16e5354bc5c573575/scripts/publish.sh for an example of how to do this. + +Remember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package. To automate the publishing of your entire package to npm on Travis see http://about.travis-ci.org/docs/user/deployment/npm/ + +# Versioning + +The `binary` properties of `module_path`, `remote_path`, and `package_name` support variable substitution. The strings are evaluated by `node-pre-gyp` depending on your system and any custom build flags you passed. + + - `node_abi`: The node C++ `ABI` number. This value is available in Javascript as `process.versions.modules` as of [`>= v0.10.4 >= v0.11.7`](https://github.com/joyent/node/commit/ccabd4a6fa8a6eb79d29bc3bbe9fe2b6531c2d8e) and in C++ as the `NODE_MODULE_VERSION` define much earlier. For versions of Node before this was available we fallback to the V8 major and minor version. + - `platform` matches node's `process.platform` like `linux`, `darwin`, and `win32` unless the user passed the `--target_platform` option to override. + - `arch` matches node's `process.arch` like `x64` or `ia32` unless the user passes the `--target_arch` option to override. + - `libc` matches `require('detect-libc').family` like `glibc` or `musl` unless the user passes the `--target_libc` option to override. + - `configuration` - Either 'Release' or 'Debug' depending on if `--debug` is passed during the build. + - `module_name` - the `binary.module_name` attribute from `package.json`. + - `version` - the semver `version` value for your module from `package.json` (NOTE: ignores the `semver.build` property). + - `major`, `minor`, `patch`, and `prelease` match the individual semver values for your module's `version` + - `build` - the sevmer `build` value. For example it would be `this.that` if your package.json `version` was `v1.0.0+this.that` + - `prerelease` - the semver `prerelease` value. For example it would be `alpha.beta` if your package.json `version` was `v1.0.0-alpha.beta` + + +The options are visible in the code at + +# Download binary files from a mirror + +S3 is broken in China for the well known reason. + +Using the `npm` config argument: `--{module_name}_binary_host_mirror` can download binary files through a mirror, `-` in `module_name` will be replaced with `_`. + +e.g.: Install [v8-profiler](https://www.npmjs.com/package/v8-profiler) from `npm`. + +```bash +$ npm install v8-profiler --profiler_binary_host_mirror=https://npm.taobao.org/mirrors/node-inspector/ +``` + +e.g.: Install [canvas-prebuilt](https://www.npmjs.com/package/canvas-prebuilt) from `npm`. + +```bash +$ npm install canvas-prebuilt --canvas_prebuilt_binary_host_mirror=https://npm.taobao.org/mirrors/canvas-prebuilt/ +``` diff --git a/node_modules/@mapbox/node-pre-gyp/bin/node-pre-gyp b/node_modules/@mapbox/node-pre-gyp/bin/node-pre-gyp new file mode 100644 index 0000000..c38d34d --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/bin/node-pre-gyp @@ -0,0 +1,4 @@ +#!/usr/bin/env node +'use strict'; + +require('../lib/main'); diff --git a/node_modules/@mapbox/node-pre-gyp/bin/node-pre-gyp.cmd b/node_modules/@mapbox/node-pre-gyp/bin/node-pre-gyp.cmd new file mode 100644 index 0000000..46e14b5 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/bin/node-pre-gyp.cmd @@ -0,0 +1,2 @@ +@echo off +node "%~dp0\node-pre-gyp" %* diff --git a/node_modules/@mapbox/node-pre-gyp/contributing.md b/node_modules/@mapbox/node-pre-gyp/contributing.md new file mode 100644 index 0000000..4038fa6 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/contributing.md @@ -0,0 +1,10 @@ +# Contributing + + +### Releasing a new version: + +- Ensure tests are passing on travis and appveyor +- Run `node scripts/abi_crosswalk.js` and commit any changes +- Update the changelog +- Tag a new release like: `git tag -a v0.6.34 -m "tagging v0.6.34" && git push --tags` +- Run `npm publish` diff --git a/node_modules/@mapbox/node-pre-gyp/lib/build.js b/node_modules/@mapbox/node-pre-gyp/lib/build.js new file mode 100644 index 0000000..e8a1459 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/build.js @@ -0,0 +1,51 @@ +'use strict'; + +module.exports = exports = build; + +exports.usage = 'Attempts to compile the module by dispatching to node-gyp or nw-gyp'; + +const napi = require('./util/napi.js'); +const compile = require('./util/compile.js'); +const handle_gyp_opts = require('./util/handle_gyp_opts.js'); +const configure = require('./configure.js'); + +function do_build(gyp, argv, callback) { + handle_gyp_opts(gyp, argv, (err, result) => { + let final_args = ['build'].concat(result.gyp).concat(result.pre); + if (result.unparsed.length > 0) { + final_args = final_args. + concat(['--']). + concat(result.unparsed); + } + if (!err && result.opts.napi_build_version) { + napi.swap_build_dir_in(result.opts.napi_build_version); + } + compile.run_gyp(final_args, result.opts, (err2) => { + if (result.opts.napi_build_version) { + napi.swap_build_dir_out(result.opts.napi_build_version); + } + return callback(err2); + }); + }); +} + +function build(gyp, argv, callback) { + + // Form up commands to pass to node-gyp: + // We map `node-pre-gyp build` to `node-gyp configure build` so that we do not + // trigger a clean and therefore do not pay the penalty of a full recompile + if (argv.length && (argv.indexOf('rebuild') > -1)) { + argv.shift(); // remove `rebuild` + // here we map `node-pre-gyp rebuild` to `node-gyp rebuild` which internally means + // "clean + configure + build" and triggers a full recompile + compile.run_gyp(['clean'], {}, (err3) => { + if (err3) return callback(err3); + configure(gyp, argv, (err4) => { + if (err4) return callback(err4); + return do_build(gyp, argv, callback); + }); + }); + } else { + return do_build(gyp, argv, callback); + } +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/clean.js b/node_modules/@mapbox/node-pre-gyp/lib/clean.js new file mode 100644 index 0000000..e693392 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/clean.js @@ -0,0 +1,31 @@ +'use strict'; + +module.exports = exports = clean; + +exports.usage = 'Removes the entire folder containing the compiled .node module'; + +const rm = require('rimraf'); +const exists = require('fs').exists || require('path').exists; +const versioning = require('./util/versioning.js'); +const napi = require('./util/napi.js'); +const path = require('path'); + +function clean(gyp, argv, callback) { + const package_json = gyp.package_json; + const napi_build_version = napi.get_napi_build_version_from_command_args(argv); + const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version); + const to_delete = opts.module_path; + if (!to_delete) { + return callback(new Error('module_path is empty, refusing to delete')); + } else if (path.normalize(to_delete) === path.normalize(process.cwd())) { + return callback(new Error('module_path is not set, refusing to delete')); + } else { + exists(to_delete, (found) => { + if (found) { + if (!gyp.opts.silent_clean) console.log('[' + package_json.name + '] Removing "%s"', to_delete); + return rm(to_delete, callback); + } + return callback(); + }); + } +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/configure.js b/node_modules/@mapbox/node-pre-gyp/lib/configure.js new file mode 100644 index 0000000..1337c0c --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/configure.js @@ -0,0 +1,52 @@ +'use strict'; + +module.exports = exports = configure; + +exports.usage = 'Attempts to configure node-gyp or nw-gyp build'; + +const napi = require('./util/napi.js'); +const compile = require('./util/compile.js'); +const handle_gyp_opts = require('./util/handle_gyp_opts.js'); + +function configure(gyp, argv, callback) { + handle_gyp_opts(gyp, argv, (err, result) => { + let final_args = result.gyp.concat(result.pre); + // pull select node-gyp configure options out of the npm environ + const known_gyp_args = ['dist-url', 'python', 'nodedir', 'msvs_version']; + known_gyp_args.forEach((key) => { + const val = gyp.opts[key] || gyp.opts[key.replace('-', '_')]; + if (val) { + final_args.push('--' + key + '=' + val); + } + }); + // --ensure=false tell node-gyp to re-install node development headers + // but it is only respected by node-gyp install, so we have to call install + // as a separate step if the user passes it + if (gyp.opts.ensure === false) { + const install_args = final_args.concat(['install', '--ensure=false']); + compile.run_gyp(install_args, result.opts, (err2) => { + if (err2) return callback(err2); + if (result.unparsed.length > 0) { + final_args = final_args. + concat(['--']). + concat(result.unparsed); + } + compile.run_gyp(['configure'].concat(final_args), result.opts, (err3) => { + return callback(err3); + }); + }); + } else { + if (result.unparsed.length > 0) { + final_args = final_args. + concat(['--']). + concat(result.unparsed); + } + compile.run_gyp(['configure'].concat(final_args), result.opts, (err4) => { + if (!err4 && result.opts.napi_build_version) { + napi.swap_build_dir_out(result.opts.napi_build_version); + } + return callback(err4); + }); + } + }); +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/info.js b/node_modules/@mapbox/node-pre-gyp/lib/info.js new file mode 100644 index 0000000..ba22f32 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/info.js @@ -0,0 +1,38 @@ +'use strict'; + +module.exports = exports = info; + +exports.usage = 'Lists all published binaries (requires aws-sdk)'; + +const log = require('npmlog'); +const versioning = require('./util/versioning.js'); +const s3_setup = require('./util/s3_setup.js'); + +function info(gyp, argv, callback) { + const package_json = gyp.package_json; + const opts = versioning.evaluate(package_json, gyp.opts); + const config = {}; + s3_setup.detect(opts, config); + const s3 = s3_setup.get_s3(config); + const s3_opts = { + Bucket: config.bucket, + Prefix: config.prefix + }; + s3.listObjects(s3_opts, (err, meta) => { + if (err && err.code === 'NotFound') { + return callback(new Error('[' + package_json.name + '] Not found: https://' + s3_opts.Bucket + '.s3.amazonaws.com/' + config.prefix)); + } else if (err) { + return callback(err); + } else { + log.verbose(JSON.stringify(meta, null, 1)); + if (meta && meta.Contents) { + meta.Contents.forEach((obj) => { + console.log(obj.Key); + }); + } else { + console.error('[' + package_json.name + '] No objects found at https://' + s3_opts.Bucket + '.s3.amazonaws.com/' + config.prefix); + } + return callback(); + } + }); +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/install.js b/node_modules/@mapbox/node-pre-gyp/lib/install.js new file mode 100644 index 0000000..617dd86 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/install.js @@ -0,0 +1,235 @@ +'use strict'; + +module.exports = exports = install; + +exports.usage = 'Attempts to install pre-built binary for module'; + +const fs = require('fs'); +const path = require('path'); +const log = require('npmlog'); +const existsAsync = fs.exists || path.exists; +const versioning = require('./util/versioning.js'); +const napi = require('./util/napi.js'); +const makeDir = require('make-dir'); +// for fetching binaries +const fetch = require('node-fetch'); +const tar = require('tar'); + +let npgVersion = 'unknown'; +try { + // Read own package.json to get the current node-pre-pyp version. + const ownPackageJSON = fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'); + npgVersion = JSON.parse(ownPackageJSON).version; +} catch (e) { + // do nothing +} + +function place_binary(uri, targetDir, opts, callback) { + log.http('GET', uri); + + // Try getting version info from the currently running npm. + const envVersionInfo = process.env.npm_config_user_agent || + 'node ' + process.version; + + const sanitized = uri.replace('+', '%2B'); + const requestOpts = { + uri: sanitized, + headers: { + 'User-Agent': 'node-pre-gyp (v' + npgVersion + ', ' + envVersionInfo + ')' + }, + follow_max: 10 + }; + + if (opts.cafile) { + try { + requestOpts.ca = fs.readFileSync(opts.cafile); + } catch (e) { + return callback(e); + } + } else if (opts.ca) { + requestOpts.ca = opts.ca; + } + + const proxyUrl = opts.proxy || + process.env.http_proxy || + process.env.HTTP_PROXY || + process.env.npm_config_proxy; + let agent; + if (proxyUrl) { + const ProxyAgent = require('https-proxy-agent'); + agent = new ProxyAgent(proxyUrl); + log.http('download', 'proxy agent configured using: "%s"', proxyUrl); + } + + fetch(sanitized, { agent }) + .then((res) => { + if (!res.ok) { + throw new Error(`response status ${res.status} ${res.statusText} on ${sanitized}`); + } + const dataStream = res.body; + + return new Promise((resolve, reject) => { + let extractions = 0; + const countExtractions = (entry) => { + extractions += 1; + log.info('install', 'unpacking %s', entry.path); + }; + + dataStream.pipe(extract(targetDir, countExtractions)) + .on('error', (e) => { + reject(e); + }); + dataStream.on('end', () => { + resolve(`extracted file count: ${extractions}`); + }); + dataStream.on('error', (e) => { + reject(e); + }); + }); + }) + .then((text) => { + log.info(text); + callback(); + }) + .catch((e) => { + log.error(`install ${e.message}`); + callback(e); + }); +} + +function extract(to, onentry) { + return tar.extract({ + cwd: to, + strip: 1, + onentry + }); +} + +function extract_from_local(from, targetDir, callback) { + if (!fs.existsSync(from)) { + return callback(new Error('Cannot find file ' + from)); + } + log.info('Found local file to extract from ' + from); + + // extract helpers + let extractCount = 0; + function countExtractions(entry) { + extractCount += 1; + log.info('install', 'unpacking ' + entry.path); + } + function afterExtract(err) { + if (err) return callback(err); + if (extractCount === 0) { + return callback(new Error('There was a fatal problem while extracting the tarball')); + } + log.info('tarball', 'done parsing tarball'); + callback(); + } + + fs.createReadStream(from).pipe(extract(targetDir, countExtractions)) + .on('close', afterExtract) + .on('error', afterExtract); +} + +function do_build(gyp, argv, callback) { + const args = ['rebuild'].concat(argv); + gyp.todo.push({ name: 'build', args: args }); + process.nextTick(callback); +} + +function print_fallback_error(err, opts, package_json) { + const fallback_message = ' (falling back to source compile with node-gyp)'; + let full_message = ''; + if (err.statusCode !== undefined) { + // If we got a network response it but failed to download + // it means remote binaries are not available, so let's try to help + // the user/developer with the info to debug why + full_message = 'Pre-built binaries not found for ' + package_json.name + '@' + package_json.version; + full_message += ' and ' + opts.runtime + '@' + (opts.target || process.versions.node) + ' (' + opts.node_abi + ' ABI, ' + opts.libc + ')'; + full_message += fallback_message; + log.warn('Tried to download(' + err.statusCode + '): ' + opts.hosted_tarball); + log.warn(full_message); + log.http(err.message); + } else { + // If we do not have a statusCode that means an unexpected error + // happened and prevented an http response, so we output the exact error + full_message = 'Pre-built binaries not installable for ' + package_json.name + '@' + package_json.version; + full_message += ' and ' + opts.runtime + '@' + (opts.target || process.versions.node) + ' (' + opts.node_abi + ' ABI, ' + opts.libc + ')'; + full_message += fallback_message; + log.warn(full_message); + log.warn('Hit error ' + err.message); + } +} + +// +// install +// +function install(gyp, argv, callback) { + const package_json = gyp.package_json; + const napi_build_version = napi.get_napi_build_version_from_command_args(argv); + const source_build = gyp.opts['build-from-source'] || gyp.opts.build_from_source; + const update_binary = gyp.opts['update-binary'] || gyp.opts.update_binary; + const should_do_source_build = source_build === package_json.name || (source_build === true || source_build === 'true'); + if (should_do_source_build) { + log.info('build', 'requesting source compile'); + return do_build(gyp, argv, callback); + } else { + const fallback_to_build = gyp.opts['fallback-to-build'] || gyp.opts.fallback_to_build; + let should_do_fallback_build = fallback_to_build === package_json.name || (fallback_to_build === true || fallback_to_build === 'true'); + // but allow override from npm + if (process.env.npm_config_argv) { + const cooked = JSON.parse(process.env.npm_config_argv).cooked; + const match = cooked.indexOf('--fallback-to-build'); + if (match > -1 && cooked.length > match && cooked[match + 1] === 'false') { + should_do_fallback_build = false; + log.info('install', 'Build fallback disabled via npm flag: --fallback-to-build=false'); + } + } + let opts; + try { + opts = versioning.evaluate(package_json, gyp.opts, napi_build_version); + } catch (err) { + return callback(err); + } + + opts.ca = gyp.opts.ca; + opts.cafile = gyp.opts.cafile; + + const from = opts.hosted_tarball; + const to = opts.module_path; + const binary_module = path.join(to, opts.module_name + '.node'); + existsAsync(binary_module, (found) => { + if (!update_binary) { + if (found) { + console.log('[' + package_json.name + '] Success: "' + binary_module + '" already installed'); + console.log('Pass --update-binary to reinstall or --build-from-source to recompile'); + return callback(); + } + log.info('check', 'checked for "' + binary_module + '" (not found)'); + } + + makeDir(to).then(() => { + const fileName = from.startsWith('file://') && from.slice('file://'.length); + if (fileName) { + extract_from_local(fileName, to, after_place); + } else { + place_binary(from, to, opts, after_place); + } + }).catch((err) => { + after_place(err); + }); + + function after_place(err) { + if (err && should_do_fallback_build) { + print_fallback_error(err, opts, package_json); + return do_build(gyp, argv, callback); + } else if (err) { + return callback(err); + } else { + console.log('[' + package_json.name + '] Success: "' + binary_module + '" is installed via remote'); + return callback(); + } + } + }); + } +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/main.js b/node_modules/@mapbox/node-pre-gyp/lib/main.js new file mode 100644 index 0000000..bae32ac --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/main.js @@ -0,0 +1,125 @@ +'use strict'; + +/** + * Set the title. + */ + +process.title = 'node-pre-gyp'; + +const node_pre_gyp = require('../'); +const log = require('npmlog'); + +/** + * Process and execute the selected commands. + */ + +const prog = new node_pre_gyp.Run({ argv: process.argv }); +let completed = false; + +if (prog.todo.length === 0) { + if (~process.argv.indexOf('-v') || ~process.argv.indexOf('--version')) { + console.log('v%s', prog.version); + process.exit(0); + } else if (~process.argv.indexOf('-h') || ~process.argv.indexOf('--help')) { + console.log('%s', prog.usage()); + process.exit(0); + } + console.log('%s', prog.usage()); + process.exit(1); +} + +// if --no-color is passed +if (prog.opts && Object.hasOwnProperty.call(prog, 'color') && !prog.opts.color) { + log.disableColor(); +} + +log.info('it worked if it ends with', 'ok'); +log.verbose('cli', process.argv); +log.info('using', process.title + '@%s', prog.version); +log.info('using', 'node@%s | %s | %s', process.versions.node, process.platform, process.arch); + + +/** + * Change dir if -C/--directory was passed. + */ + +const dir = prog.opts.directory; +if (dir) { + const fs = require('fs'); + try { + const stat = fs.statSync(dir); + if (stat.isDirectory()) { + log.info('chdir', dir); + process.chdir(dir); + } else { + log.warn('chdir', dir + ' is not a directory'); + } + } catch (e) { + if (e.code === 'ENOENT') { + log.warn('chdir', dir + ' is not a directory'); + } else { + log.warn('chdir', 'error during chdir() "%s"', e.message); + } + } +} + +function run() { + const command = prog.todo.shift(); + if (!command) { + // done! + completed = true; + log.info('ok'); + return; + } + + // set binary.host when appropriate. host determines the s3 target bucket. + const target = prog.setBinaryHostProperty(command.name); + if (target && ['install', 'publish', 'unpublish', 'info'].indexOf(command.name) >= 0) { + log.info('using binary.host: ' + prog.package_json.binary.host); + } + + prog.commands[command.name](command.args, function(err) { + if (err) { + log.error(command.name + ' error'); + log.error('stack', err.stack); + errorMessage(); + log.error('not ok'); + console.log(err.message); + return process.exit(1); + } + const args_array = [].slice.call(arguments, 1); + if (args_array.length) { + console.log.apply(console, args_array); + } + // now run the next command in the queue + process.nextTick(run); + }); +} + +process.on('exit', (code) => { + if (!completed && !code) { + log.error('Completion callback never invoked!'); + errorMessage(); + process.exit(6); + } +}); + +process.on('uncaughtException', (err) => { + log.error('UNCAUGHT EXCEPTION'); + log.error('stack', err.stack); + errorMessage(); + process.exit(7); +}); + +function errorMessage() { + // copied from npm's lib/util/error-handler.js + const os = require('os'); + log.error('System', os.type() + ' ' + os.release()); + log.error('command', process.argv.map(JSON.stringify).join(' ')); + log.error('cwd', process.cwd()); + log.error('node -v', process.version); + log.error(process.title + ' -v', 'v' + prog.package.version); +} + +// start running the given commands! +run(); diff --git a/node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js b/node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js new file mode 100644 index 0000000..dc18e74 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js @@ -0,0 +1,309 @@ +'use strict'; + +/** + * Module exports. + */ + +module.exports = exports; + +/** + * Module dependencies. + */ + +// load mocking control function for accessing s3 via https. the function is a noop always returning +// false if not mocking. +exports.mockS3Http = require('./util/s3_setup').get_mockS3Http(); +exports.mockS3Http('on'); +const mocking = exports.mockS3Http('get'); + + +const fs = require('fs'); +const path = require('path'); +const nopt = require('nopt'); +const log = require('npmlog'); +log.disableProgress(); +const napi = require('./util/napi.js'); + +const EE = require('events').EventEmitter; +const inherits = require('util').inherits; +const cli_commands = [ + 'clean', + 'install', + 'reinstall', + 'build', + 'rebuild', + 'package', + 'testpackage', + 'publish', + 'unpublish', + 'info', + 'testbinary', + 'reveal', + 'configure' +]; +const aliases = {}; + +// differentiate node-pre-gyp's logs from npm's +log.heading = 'node-pre-gyp'; + +if (mocking) { + log.warn(`mocking s3 to ${process.env.node_pre_gyp_mock_s3}`); +} + +// this is a getter to avoid circular reference warnings with node v14. +Object.defineProperty(exports, 'find', { + get: function() { + return require('./pre-binding').find; + }, + enumerable: true +}); + +// in the following, "my_module" is using node-pre-gyp to +// prebuild and install pre-built binaries. "main_module" +// is using "my_module". +// +// "bin/node-pre-gyp" invokes Run() without a path. the +// expectation is that the working directory is the package +// root "my_module". this is true because in all cases npm is +// executing a script in the context of "my_module". +// +// "pre-binding.find()" is executed by "my_module" but in the +// context of "main_module". this is because "main_module" is +// executing and requires "my_module" which is then executing +// "pre-binding.find()" via "node-pre-gyp.find()", so the working +// directory is that of "main_module". +// +// that's why "find()" must pass the path to package.json. +// +function Run({ package_json_path = './package.json', argv }) { + this.package_json_path = package_json_path; + this.commands = {}; + + const self = this; + cli_commands.forEach((command) => { + self.commands[command] = function(argvx, callback) { + log.verbose('command', command, argvx); + return require('./' + command)(self, argvx, callback); + }; + }); + + this.parseArgv(argv); + + // this is set to true after the binary.host property was set to + // either staging_host or production_host. + this.binaryHostSet = false; +} +inherits(Run, EE); +exports.Run = Run; +const proto = Run.prototype; + +/** + * Export the contents of the package.json. + */ + +proto.package = require('../package.json'); + +/** + * nopt configuration definitions + */ + +proto.configDefs = { + help: Boolean, // everywhere + arch: String, // 'configure' + debug: Boolean, // 'build' + directory: String, // bin + proxy: String, // 'install' + loglevel: String // everywhere +}; + +/** + * nopt shorthands + */ + +proto.shorthands = { + release: '--no-debug', + C: '--directory', + debug: '--debug', + j: '--jobs', + silent: '--loglevel=silent', + silly: '--loglevel=silly', + verbose: '--loglevel=verbose' +}; + +/** + * expose the command aliases for the bin file to use. + */ + +proto.aliases = aliases; + +/** + * Parses the given argv array and sets the 'opts', 'argv', + * 'command', and 'package_json' properties. + */ + +proto.parseArgv = function parseOpts(argv) { + this.opts = nopt(this.configDefs, this.shorthands, argv); + this.argv = this.opts.argv.remain.slice(); + const commands = this.todo = []; + + // create a copy of the argv array with aliases mapped + argv = this.argv.map((arg) => { + // is this an alias? + if (arg in this.aliases) { + arg = this.aliases[arg]; + } + return arg; + }); + + // process the mapped args into "command" objects ("name" and "args" props) + argv.slice().forEach((arg) => { + if (arg in this.commands) { + const args = argv.splice(0, argv.indexOf(arg)); + argv.shift(); + if (commands.length > 0) { + commands[commands.length - 1].args = args; + } + commands.push({ name: arg, args: [] }); + } + }); + if (commands.length > 0) { + commands[commands.length - 1].args = argv.splice(0); + } + + + // if a directory was specified package.json is assumed to be relative + // to it. + let package_json_path = this.package_json_path; + if (this.opts.directory) { + package_json_path = path.join(this.opts.directory, package_json_path); + } + + this.package_json = JSON.parse(fs.readFileSync(package_json_path)); + + // expand commands entries for multiple napi builds + this.todo = napi.expand_commands(this.package_json, this.opts, commands); + + // support for inheriting config env variables from npm + const npm_config_prefix = 'npm_config_'; + Object.keys(process.env).forEach((name) => { + if (name.indexOf(npm_config_prefix) !== 0) return; + const val = process.env[name]; + if (name === npm_config_prefix + 'loglevel') { + log.level = val; + } else { + // add the user-defined options to the config + name = name.substring(npm_config_prefix.length); + // avoid npm argv clobber already present args + // which avoids problem of 'npm test' calling + // script that runs unique npm install commands + if (name === 'argv') { + if (this.opts.argv && + this.opts.argv.remain && + this.opts.argv.remain.length) { + // do nothing + } else { + this.opts[name] = val; + } + } else { + this.opts[name] = val; + } + } + }); + + if (this.opts.loglevel) { + log.level = this.opts.loglevel; + } + log.resume(); +}; + +/** + * allow the binary.host property to be set at execution time. + * + * for this to take effect requires all the following to be true. + * - binary is a property in package.json + * - binary.host is falsey + * - binary.staging_host is not empty + * - binary.production_host is not empty + * + * if any of the previous checks fail then the function returns an empty string + * and makes no changes to package.json's binary property. + * + * + * if command is "publish" then the default is set to "binary.staging_host" + * if command is not "publish" the the default is set to "binary.production_host" + * + * if the command-line option '--s3_host' is set to "staging" or "production" then + * "binary.host" is set to the specified "staging_host" or "production_host". if + * '--s3_host' is any other value an exception is thrown. + * + * if '--s3_host' is not present then "binary.host" is set to the default as above. + * + * this strategy was chosen so that any command other than "publish" or "unpublish" uses "production" + * as the default without requiring any command-line options but that "publish" and "unpublish" require + * '--s3_host production_host' to be specified in order to *really* publish (or unpublish). publishing + * to staging can be done freely without worrying about disturbing any production releases. + */ +proto.setBinaryHostProperty = function(command) { + if (this.binaryHostSet) { + return this.package_json.binary.host; + } + const p = this.package_json; + // don't set anything if host is present. it must be left blank to trigger this. + if (!p || !p.binary || p.binary.host) { + return ''; + } + // and both staging and production must be present. errors will be reported later. + if (!p.binary.staging_host || !p.binary.production_host) { + return ''; + } + let target = 'production_host'; + if (command === 'publish' || command === 'unpublish') { + target = 'staging_host'; + } + // the environment variable has priority over the default or the command line. if + // either the env var or the command line option are invalid throw an error. + const npg_s3_host = process.env.node_pre_gyp_s3_host; + if (npg_s3_host === 'staging' || npg_s3_host === 'production') { + target = `${npg_s3_host}_host`; + } else if (this.opts['s3_host'] === 'staging' || this.opts['s3_host'] === 'production') { + target = `${this.opts['s3_host']}_host`; + } else if (this.opts['s3_host'] || npg_s3_host) { + throw new Error(`invalid s3_host ${this.opts['s3_host'] || npg_s3_host}`); + } + + p.binary.host = p.binary[target]; + this.binaryHostSet = true; + + return p.binary.host; +}; + +/** + * Returns the usage instructions for node-pre-gyp. + */ + +proto.usage = function usage() { + const str = [ + '', + ' Usage: node-pre-gyp [options]', + '', + ' where is one of:', + cli_commands.map((c) => { + return ' - ' + c + ' - ' + require('./' + c).usage; + }).join('\n'), + '', + 'node-pre-gyp@' + this.version + ' ' + path.resolve(__dirname, '..'), + 'node@' + process.versions.node + ].join('\n'); + return str; +}; + +/** + * Version number getter. + */ + +Object.defineProperty(proto, 'version', { + get: function() { + return this.package.version; + }, + enumerable: true +}); diff --git a/node_modules/@mapbox/node-pre-gyp/lib/package.js b/node_modules/@mapbox/node-pre-gyp/lib/package.js new file mode 100644 index 0000000..0734984 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/package.js @@ -0,0 +1,73 @@ +'use strict'; + +module.exports = exports = _package; + +exports.usage = 'Packs binary (and enclosing directory) into locally staged tarball'; + +const fs = require('fs'); +const path = require('path'); +const log = require('npmlog'); +const versioning = require('./util/versioning.js'); +const napi = require('./util/napi.js'); +const existsAsync = fs.exists || path.exists; +const makeDir = require('make-dir'); +const tar = require('tar'); + +function readdirSync(dir) { + let list = []; + const files = fs.readdirSync(dir); + + files.forEach((file) => { + const stats = fs.lstatSync(path.join(dir, file)); + if (stats.isDirectory()) { + list = list.concat(readdirSync(path.join(dir, file))); + } else { + list.push(path.join(dir, file)); + } + }); + return list; +} + +function _package(gyp, argv, callback) { + const package_json = gyp.package_json; + const napi_build_version = napi.get_napi_build_version_from_command_args(argv); + const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version); + const from = opts.module_path; + const binary_module = path.join(from, opts.module_name + '.node'); + existsAsync(binary_module, (found) => { + if (!found) { + return callback(new Error('Cannot package because ' + binary_module + ' missing: run `node-pre-gyp rebuild` first')); + } + const tarball = opts.staged_tarball; + const filter_func = function(entry) { + const basename = path.basename(entry); + if (basename.length && basename[0] !== '.') { + console.log('packing ' + entry); + return true; + } else { + console.log('skipping ' + entry); + } + return false; + }; + makeDir(path.dirname(tarball)).then(() => { + let files = readdirSync(from); + const base = path.basename(from); + files = files.map((file) => { + return path.join(base, path.relative(from, file)); + }); + tar.create({ + portable: false, + gzip: true, + filter: filter_func, + file: tarball, + cwd: path.dirname(from) + }, files, (err2) => { + if (err2) console.error('[' + package_json.name + '] ' + err2.message); + else log.info('package', 'Binary staged at "' + tarball + '"'); + return callback(err2); + }); + }).catch((err) => { + return callback(err); + }); + }); +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/pre-binding.js b/node_modules/@mapbox/node-pre-gyp/lib/pre-binding.js new file mode 100644 index 0000000..e110fe3 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/pre-binding.js @@ -0,0 +1,34 @@ +'use strict'; + +const npg = require('..'); +const versioning = require('../lib/util/versioning.js'); +const napi = require('../lib/util/napi.js'); +const existsSync = require('fs').existsSync || require('path').existsSync; +const path = require('path'); + +module.exports = exports; + +exports.usage = 'Finds the require path for the node-pre-gyp installed module'; + +exports.validate = function(package_json, opts) { + versioning.validate_config(package_json, opts); +}; + +exports.find = function(package_json_path, opts) { + if (!existsSync(package_json_path)) { + throw new Error(package_json_path + 'does not exist'); + } + const prog = new npg.Run({ package_json_path, argv: process.argv }); + prog.setBinaryHostProperty(); + const package_json = prog.package_json; + + versioning.validate_config(package_json, opts); + let napi_build_version; + if (napi.get_napi_build_versions(package_json, opts)) { + napi_build_version = napi.get_best_napi_build_version(package_json, opts); + } + opts = opts || {}; + if (!opts.module_root) opts.module_root = path.dirname(package_json_path); + const meta = versioning.evaluate(package_json, opts, napi_build_version); + return meta.module; +}; diff --git a/node_modules/@mapbox/node-pre-gyp/lib/publish.js b/node_modules/@mapbox/node-pre-gyp/lib/publish.js new file mode 100644 index 0000000..8367b15 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/publish.js @@ -0,0 +1,81 @@ +'use strict'; + +module.exports = exports = publish; + +exports.usage = 'Publishes pre-built binary (requires aws-sdk)'; + +const fs = require('fs'); +const path = require('path'); +const log = require('npmlog'); +const versioning = require('./util/versioning.js'); +const napi = require('./util/napi.js'); +const s3_setup = require('./util/s3_setup.js'); +const existsAsync = fs.exists || path.exists; +const url = require('url'); + +function publish(gyp, argv, callback) { + const package_json = gyp.package_json; + const napi_build_version = napi.get_napi_build_version_from_command_args(argv); + const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version); + const tarball = opts.staged_tarball; + existsAsync(tarball, (found) => { + if (!found) { + return callback(new Error('Cannot publish because ' + tarball + ' missing: run `node-pre-gyp package` first')); + } + + log.info('publish', 'Detecting s3 credentials'); + const config = {}; + s3_setup.detect(opts, config); + const s3 = s3_setup.get_s3(config); + + const key_name = url.resolve(config.prefix, opts.package_name); + const s3_opts = { + Bucket: config.bucket, + Key: key_name + }; + log.info('publish', 'Authenticating with s3'); + log.info('publish', config); + + log.info('publish', 'Checking for existing binary at ' + opts.hosted_path); + s3.headObject(s3_opts, (err, meta) => { + if (meta) log.info('publish', JSON.stringify(meta)); + if (err && err.code === 'NotFound') { + // we are safe to publish because + // the object does not already exist + log.info('publish', 'Preparing to put object'); + const s3_put_opts = { + ACL: 'public-read', + Body: fs.createReadStream(tarball), + Key: key_name, + Bucket: config.bucket + }; + log.info('publish', 'Putting object', s3_put_opts.ACL, s3_put_opts.Bucket, s3_put_opts.Key); + try { + s3.putObject(s3_put_opts, (err2, resp) => { + log.info('publish', 'returned from putting object'); + if (err2) { + log.info('publish', 's3 putObject error: "' + err2 + '"'); + return callback(err2); + } + if (resp) log.info('publish', 's3 putObject response: "' + JSON.stringify(resp) + '"'); + log.info('publish', 'successfully put object'); + console.log('[' + package_json.name + '] published to ' + opts.hosted_path); + return callback(); + }); + } catch (err3) { + log.info('publish', 's3 putObject error: "' + err3 + '"'); + return callback(err3); + } + } else if (err) { + log.info('publish', 's3 headObject error: "' + err + '"'); + return callback(err); + } else { + log.error('publish', 'Cannot publish over existing version'); + log.error('publish', "Update the 'version' field in package.json and try again"); + log.error('publish', 'If the previous version was published in error see:'); + log.error('publish', '\t node-pre-gyp unpublish'); + return callback(new Error('Failed publishing to ' + opts.hosted_path)); + } + }); + }); +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/rebuild.js b/node_modules/@mapbox/node-pre-gyp/lib/rebuild.js new file mode 100644 index 0000000..31510fb --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/rebuild.js @@ -0,0 +1,20 @@ +'use strict'; + +module.exports = exports = rebuild; + +exports.usage = 'Runs "clean" and "build" at once'; + +const napi = require('./util/napi.js'); + +function rebuild(gyp, argv, callback) { + const package_json = gyp.package_json; + let commands = [ + { name: 'clean', args: [] }, + { name: 'build', args: ['rebuild'] } + ]; + commands = napi.expand_commands(package_json, gyp.opts, commands); + for (let i = commands.length; i !== 0; i--) { + gyp.todo.unshift(commands[i - 1]); + } + process.nextTick(callback); +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/reinstall.js b/node_modules/@mapbox/node-pre-gyp/lib/reinstall.js new file mode 100644 index 0000000..a29b5c9 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/reinstall.js @@ -0,0 +1,19 @@ +'use strict'; + +module.exports = exports = rebuild; + +exports.usage = 'Runs "clean" and "install" at once'; + +const napi = require('./util/napi.js'); + +function rebuild(gyp, argv, callback) { + const package_json = gyp.package_json; + let installArgs = []; + const napi_build_version = napi.get_best_napi_build_version(package_json, gyp.opts); + if (napi_build_version != null) installArgs = [napi.get_command_arg(napi_build_version)]; + gyp.todo.unshift( + { name: 'clean', args: [] }, + { name: 'install', args: installArgs } + ); + process.nextTick(callback); +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/reveal.js b/node_modules/@mapbox/node-pre-gyp/lib/reveal.js new file mode 100644 index 0000000..7255e5f --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/reveal.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = exports = reveal; + +exports.usage = 'Reveals data on the versioned binary'; + +const versioning = require('./util/versioning.js'); +const napi = require('./util/napi.js'); + +function unix_paths(key, val) { + return val && val.replace ? val.replace(/\\/g, '/') : val; +} + +function reveal(gyp, argv, callback) { + const package_json = gyp.package_json; + const napi_build_version = napi.get_napi_build_version_from_command_args(argv); + const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version); + let hit = false; + // if a second arg is passed look to see + // if it is a known option + // console.log(JSON.stringify(gyp.opts,null,1)) + const remain = gyp.opts.argv.remain[gyp.opts.argv.remain.length - 1]; + if (remain && Object.hasOwnProperty.call(opts, remain)) { + console.log(opts[remain].replace(/\\/g, '/')); + hit = true; + } + // otherwise return all options as json + if (!hit) { + console.log(JSON.stringify(opts, unix_paths, 2)); + } + return callback(); +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/testbinary.js b/node_modules/@mapbox/node-pre-gyp/lib/testbinary.js new file mode 100644 index 0000000..429cb13 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/testbinary.js @@ -0,0 +1,79 @@ +'use strict'; + +module.exports = exports = testbinary; + +exports.usage = 'Tests that the binary.node can be required'; + +const path = require('path'); +const log = require('npmlog'); +const cp = require('child_process'); +const versioning = require('./util/versioning.js'); +const napi = require('./util/napi.js'); + +function testbinary(gyp, argv, callback) { + const args = []; + const options = {}; + let shell_cmd = process.execPath; + const package_json = gyp.package_json; + const napi_build_version = napi.get_napi_build_version_from_command_args(argv); + const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version); + // skip validation for runtimes we don't explicitly support (like electron) + if (opts.runtime && + opts.runtime !== 'node-webkit' && + opts.runtime !== 'node') { + return callback(); + } + const nw = (opts.runtime && opts.runtime === 'node-webkit'); + // ensure on windows that / are used for require path + const binary_module = opts.module.replace(/\\/g, '/'); + if ((process.arch !== opts.target_arch) || + (process.platform !== opts.target_platform)) { + let msg = 'skipping validation since host platform/arch ('; + msg += process.platform + '/' + process.arch + ')'; + msg += ' does not match target ('; + msg += opts.target_platform + '/' + opts.target_arch + ')'; + log.info('validate', msg); + return callback(); + } + if (nw) { + options.timeout = 5000; + if (process.platform === 'darwin') { + shell_cmd = 'node-webkit'; + } else if (process.platform === 'win32') { + shell_cmd = 'nw.exe'; + } else { + shell_cmd = 'nw'; + } + const modulePath = path.resolve(binary_module); + const appDir = path.join(__dirname, 'util', 'nw-pre-gyp'); + args.push(appDir); + args.push(modulePath); + log.info('validate', "Running test command: '" + shell_cmd + ' ' + args.join(' ') + "'"); + cp.execFile(shell_cmd, args, options, (err, stdout, stderr) => { + // check for normal timeout for node-webkit + if (err) { + if (err.killed === true && err.signal && err.signal.indexOf('SIG') > -1) { + return callback(); + } + const stderrLog = stderr.toString(); + log.info('stderr', stderrLog); + if (/^\s*Xlib:\s*extension\s*"RANDR"\s*missing\s*on\s*display\s*":\d+\.\d+"\.\s*$/.test(stderrLog)) { + log.info('RANDR', 'stderr contains only RANDR error, ignored'); + return callback(); + } + return callback(err); + } + return callback(); + }); + return; + } + args.push('--eval'); + args.push("require('" + binary_module.replace(/'/g, '\'') + "')"); + log.info('validate', "Running test command: '" + shell_cmd + ' ' + args.join(' ') + "'"); + cp.execFile(shell_cmd, args, options, (err, stdout, stderr) => { + if (err) { + return callback(err, { stdout: stdout, stderr: stderr }); + } + return callback(); + }); +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/testpackage.js b/node_modules/@mapbox/node-pre-gyp/lib/testpackage.js new file mode 100644 index 0000000..fab1911 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/testpackage.js @@ -0,0 +1,53 @@ +'use strict'; + +module.exports = exports = testpackage; + +exports.usage = 'Tests that the staged package is valid'; + +const fs = require('fs'); +const path = require('path'); +const log = require('npmlog'); +const existsAsync = fs.exists || path.exists; +const versioning = require('./util/versioning.js'); +const napi = require('./util/napi.js'); +const testbinary = require('./testbinary.js'); +const tar = require('tar'); +const makeDir = require('make-dir'); + +function testpackage(gyp, argv, callback) { + const package_json = gyp.package_json; + const napi_build_version = napi.get_napi_build_version_from_command_args(argv); + const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version); + const tarball = opts.staged_tarball; + existsAsync(tarball, (found) => { + if (!found) { + return callback(new Error('Cannot test package because ' + tarball + ' missing: run `node-pre-gyp package` first')); + } + const to = opts.module_path; + function filter_func(entry) { + log.info('install', 'unpacking [' + entry.path + ']'); + } + + makeDir(to).then(() => { + tar.extract({ + file: tarball, + cwd: to, + strip: 1, + onentry: filter_func + }).then(after_extract, callback); + }).catch((err) => { + return callback(err); + }); + + function after_extract() { + testbinary(gyp, argv, (err) => { + if (err) { + return callback(err); + } else { + console.log('[' + package_json.name + '] Package appears valid'); + return callback(); + } + }); + } + }); +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/unpublish.js b/node_modules/@mapbox/node-pre-gyp/lib/unpublish.js new file mode 100644 index 0000000..12c9f56 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/unpublish.js @@ -0,0 +1,41 @@ +'use strict'; + +module.exports = exports = unpublish; + +exports.usage = 'Unpublishes pre-built binary (requires aws-sdk)'; + +const log = require('npmlog'); +const versioning = require('./util/versioning.js'); +const napi = require('./util/napi.js'); +const s3_setup = require('./util/s3_setup.js'); +const url = require('url'); + +function unpublish(gyp, argv, callback) { + const package_json = gyp.package_json; + const napi_build_version = napi.get_napi_build_version_from_command_args(argv); + const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version); + const config = {}; + s3_setup.detect(opts, config); + const s3 = s3_setup.get_s3(config); + const key_name = url.resolve(config.prefix, opts.package_name); + const s3_opts = { + Bucket: config.bucket, + Key: key_name + }; + s3.headObject(s3_opts, (err, meta) => { + if (err && err.code === 'NotFound') { + console.log('[' + package_json.name + '] Not found: https://' + s3_opts.Bucket + '.s3.amazonaws.com/' + s3_opts.Key); + return callback(); + } else if (err) { + return callback(err); + } else { + log.info('unpublish', JSON.stringify(meta)); + s3.deleteObject(s3_opts, (err2, resp) => { + if (err2) return callback(err2); + log.info(JSON.stringify(resp)); + console.log('[' + package_json.name + '] Success: removed https://' + s3_opts.Bucket + '.s3.amazonaws.com/' + s3_opts.Key); + return callback(); + }); + } + }); +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/util/abi_crosswalk.json b/node_modules/@mapbox/node-pre-gyp/lib/util/abi_crosswalk.json new file mode 100644 index 0000000..7f52972 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/util/abi_crosswalk.json @@ -0,0 +1,2602 @@ +{ + "0.1.14": { + "node_abi": null, + "v8": "1.3" + }, + "0.1.15": { + "node_abi": null, + "v8": "1.3" + }, + "0.1.16": { + "node_abi": null, + "v8": "1.3" + }, + "0.1.17": { + "node_abi": null, + "v8": "1.3" + }, + "0.1.18": { + "node_abi": null, + "v8": "1.3" + }, + "0.1.19": { + "node_abi": null, + "v8": "2.0" + }, + "0.1.20": { + "node_abi": null, + "v8": "2.0" + }, + "0.1.21": { + "node_abi": null, + "v8": "2.0" + }, + "0.1.22": { + "node_abi": null, + "v8": "2.0" + }, + "0.1.23": { + "node_abi": null, + "v8": "2.0" + }, + "0.1.24": { + "node_abi": null, + "v8": "2.0" + }, + "0.1.25": { + "node_abi": null, + "v8": "2.0" + }, + "0.1.26": { + "node_abi": null, + "v8": "2.0" + }, + "0.1.27": { + "node_abi": null, + "v8": "2.1" + }, + "0.1.28": { + "node_abi": null, + "v8": "2.1" + }, + "0.1.29": { + "node_abi": null, + "v8": "2.1" + }, + "0.1.30": { + "node_abi": null, + "v8": "2.1" + }, + "0.1.31": { + "node_abi": null, + "v8": "2.1" + }, + "0.1.32": { + "node_abi": null, + "v8": "2.1" + }, + "0.1.33": { + "node_abi": null, + "v8": "2.1" + }, + "0.1.90": { + "node_abi": null, + "v8": "2.2" + }, + "0.1.91": { + "node_abi": null, + "v8": "2.2" + }, + "0.1.92": { + "node_abi": null, + "v8": "2.2" + }, + "0.1.93": { + "node_abi": null, + "v8": "2.2" + }, + "0.1.94": { + "node_abi": null, + "v8": "2.2" + }, + "0.1.95": { + "node_abi": null, + "v8": "2.2" + }, + "0.1.96": { + "node_abi": null, + "v8": "2.2" + }, + "0.1.97": { + "node_abi": null, + "v8": "2.2" + }, + "0.1.98": { + "node_abi": null, + "v8": "2.2" + }, + "0.1.99": { + "node_abi": null, + "v8": "2.2" + }, + "0.1.100": { + "node_abi": null, + "v8": "2.2" + }, + "0.1.101": { + "node_abi": null, + "v8": "2.3" + }, + "0.1.102": { + "node_abi": null, + "v8": "2.3" + }, + "0.1.103": { + "node_abi": null, + "v8": "2.3" + }, + "0.1.104": { + "node_abi": null, + "v8": "2.3" + }, + "0.2.0": { + "node_abi": 1, + "v8": "2.3" + }, + "0.2.1": { + "node_abi": 1, + "v8": "2.3" + }, + "0.2.2": { + "node_abi": 1, + "v8": "2.3" + }, + "0.2.3": { + "node_abi": 1, + "v8": "2.3" + }, + "0.2.4": { + "node_abi": 1, + "v8": "2.3" + }, + "0.2.5": { + "node_abi": 1, + "v8": "2.3" + }, + "0.2.6": { + "node_abi": 1, + "v8": "2.3" + }, + "0.3.0": { + "node_abi": 1, + "v8": "2.5" + }, + "0.3.1": { + "node_abi": 1, + "v8": "2.5" + }, + "0.3.2": { + "node_abi": 1, + "v8": "3.0" + }, + "0.3.3": { + "node_abi": 1, + "v8": "3.0" + }, + "0.3.4": { + "node_abi": 1, + "v8": "3.0" + }, + "0.3.5": { + "node_abi": 1, + "v8": "3.0" + }, + "0.3.6": { + "node_abi": 1, + "v8": "3.0" + }, + "0.3.7": { + "node_abi": 1, + "v8": "3.0" + }, + "0.3.8": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.0": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.1": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.2": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.3": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.4": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.5": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.6": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.7": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.8": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.9": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.10": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.11": { + "node_abi": 1, + "v8": "3.1" + }, + "0.4.12": { + "node_abi": 1, + "v8": "3.1" + }, + "0.5.0": { + "node_abi": 1, + "v8": "3.1" + }, + "0.5.1": { + "node_abi": 1, + "v8": "3.4" + }, + "0.5.2": { + "node_abi": 1, + "v8": "3.4" + }, + "0.5.3": { + "node_abi": 1, + "v8": "3.4" + }, + "0.5.4": { + "node_abi": 1, + "v8": "3.5" + }, + "0.5.5": { + "node_abi": 1, + "v8": "3.5" + }, + "0.5.6": { + "node_abi": 1, + "v8": "3.6" + }, + "0.5.7": { + "node_abi": 1, + "v8": "3.6" + }, + "0.5.8": { + "node_abi": 1, + "v8": "3.6" + }, + "0.5.9": { + "node_abi": 1, + "v8": "3.6" + }, + "0.5.10": { + "node_abi": 1, + "v8": "3.7" + }, + "0.6.0": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.1": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.2": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.3": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.4": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.5": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.6": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.7": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.8": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.9": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.10": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.11": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.12": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.13": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.14": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.15": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.16": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.17": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.18": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.19": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.20": { + "node_abi": 1, + "v8": "3.6" + }, + "0.6.21": { + "node_abi": 1, + "v8": "3.6" + }, + "0.7.0": { + "node_abi": 1, + "v8": "3.8" + }, + "0.7.1": { + "node_abi": 1, + "v8": "3.8" + }, + "0.7.2": { + "node_abi": 1, + "v8": "3.8" + }, + "0.7.3": { + "node_abi": 1, + "v8": "3.9" + }, + "0.7.4": { + "node_abi": 1, + "v8": "3.9" + }, + "0.7.5": { + "node_abi": 1, + "v8": "3.9" + }, + "0.7.6": { + "node_abi": 1, + "v8": "3.9" + }, + "0.7.7": { + "node_abi": 1, + "v8": "3.9" + }, + "0.7.8": { + "node_abi": 1, + "v8": "3.9" + }, + "0.7.9": { + "node_abi": 1, + "v8": "3.11" + }, + "0.7.10": { + "node_abi": 1, + "v8": "3.9" + }, + "0.7.11": { + "node_abi": 1, + "v8": "3.11" + }, + "0.7.12": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.0": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.1": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.2": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.3": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.4": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.5": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.6": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.7": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.8": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.9": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.10": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.11": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.12": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.13": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.14": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.15": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.16": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.17": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.18": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.19": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.20": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.21": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.22": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.23": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.24": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.25": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.26": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.27": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.28": { + "node_abi": 1, + "v8": "3.11" + }, + "0.9.0": { + "node_abi": 1, + "v8": "3.11" + }, + "0.9.1": { + "node_abi": 10, + "v8": "3.11" + }, + "0.9.2": { + "node_abi": 10, + "v8": "3.11" + }, + "0.9.3": { + "node_abi": 10, + "v8": "3.13" + }, + "0.9.4": { + "node_abi": 10, + "v8": "3.13" + }, + "0.9.5": { + "node_abi": 10, + "v8": "3.13" + }, + "0.9.6": { + "node_abi": 10, + "v8": "3.15" + }, + "0.9.7": { + "node_abi": 10, + "v8": "3.15" + }, + "0.9.8": { + "node_abi": 10, + "v8": "3.15" + }, + "0.9.9": { + "node_abi": 11, + "v8": "3.15" + }, + "0.9.10": { + "node_abi": 11, + "v8": "3.15" + }, + "0.9.11": { + "node_abi": 11, + "v8": "3.14" + }, + "0.9.12": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.0": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.1": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.2": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.3": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.4": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.5": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.6": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.7": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.8": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.9": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.10": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.11": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.12": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.13": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.14": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.15": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.16": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.17": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.18": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.19": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.20": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.21": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.22": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.23": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.24": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.25": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.26": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.27": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.28": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.29": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.30": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.31": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.32": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.33": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.34": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.35": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.36": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.37": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.38": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.39": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.40": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.41": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.42": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.43": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.44": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.45": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.46": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.47": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.48": { + "node_abi": 11, + "v8": "3.14" + }, + "0.11.0": { + "node_abi": 12, + "v8": "3.17" + }, + "0.11.1": { + "node_abi": 12, + "v8": "3.18" + }, + "0.11.2": { + "node_abi": 12, + "v8": "3.19" + }, + "0.11.3": { + "node_abi": 12, + "v8": "3.19" + }, + "0.11.4": { + "node_abi": 12, + "v8": "3.20" + }, + "0.11.5": { + "node_abi": 12, + "v8": "3.20" + }, + "0.11.6": { + "node_abi": 12, + "v8": "3.20" + }, + "0.11.7": { + "node_abi": 12, + "v8": "3.20" + }, + "0.11.8": { + "node_abi": 13, + "v8": "3.21" + }, + "0.11.9": { + "node_abi": 13, + "v8": "3.22" + }, + "0.11.10": { + "node_abi": 13, + "v8": "3.22" + }, + "0.11.11": { + "node_abi": 14, + "v8": "3.22" + }, + "0.11.12": { + "node_abi": 14, + "v8": "3.22" + }, + "0.11.13": { + "node_abi": 14, + "v8": "3.25" + }, + "0.11.14": { + "node_abi": 14, + "v8": "3.26" + }, + "0.11.15": { + "node_abi": 14, + "v8": "3.28" + }, + "0.11.16": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.0": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.1": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.2": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.3": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.4": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.5": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.6": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.7": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.8": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.9": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.10": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.11": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.12": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.13": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.14": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.15": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.16": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.17": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.18": { + "node_abi": 14, + "v8": "3.28" + }, + "1.0.0": { + "node_abi": 42, + "v8": "3.31" + }, + "1.0.1": { + "node_abi": 42, + "v8": "3.31" + }, + "1.0.2": { + "node_abi": 42, + "v8": "3.31" + }, + "1.0.3": { + "node_abi": 42, + "v8": "4.1" + }, + "1.0.4": { + "node_abi": 42, + "v8": "4.1" + }, + "1.1.0": { + "node_abi": 43, + "v8": "4.1" + }, + "1.2.0": { + "node_abi": 43, + "v8": "4.1" + }, + "1.3.0": { + "node_abi": 43, + "v8": "4.1" + }, + "1.4.1": { + "node_abi": 43, + "v8": "4.1" + }, + "1.4.2": { + "node_abi": 43, + "v8": "4.1" + }, + "1.4.3": { + "node_abi": 43, + "v8": "4.1" + }, + "1.5.0": { + "node_abi": 43, + "v8": "4.1" + }, + "1.5.1": { + "node_abi": 43, + "v8": "4.1" + }, + "1.6.0": { + "node_abi": 43, + "v8": "4.1" + }, + "1.6.1": { + "node_abi": 43, + "v8": "4.1" + }, + "1.6.2": { + "node_abi": 43, + "v8": "4.1" + }, + "1.6.3": { + "node_abi": 43, + "v8": "4.1" + }, + "1.6.4": { + "node_abi": 43, + "v8": "4.1" + }, + "1.7.1": { + "node_abi": 43, + "v8": "4.1" + }, + "1.8.1": { + "node_abi": 43, + "v8": "4.1" + }, + "1.8.2": { + "node_abi": 43, + "v8": "4.1" + }, + "1.8.3": { + "node_abi": 43, + "v8": "4.1" + }, + "1.8.4": { + "node_abi": 43, + "v8": "4.1" + }, + "2.0.0": { + "node_abi": 44, + "v8": "4.2" + }, + "2.0.1": { + "node_abi": 44, + "v8": "4.2" + }, + "2.0.2": { + "node_abi": 44, + "v8": "4.2" + }, + "2.1.0": { + "node_abi": 44, + "v8": "4.2" + }, + "2.2.0": { + "node_abi": 44, + "v8": "4.2" + }, + "2.2.1": { + "node_abi": 44, + "v8": "4.2" + }, + "2.3.0": { + "node_abi": 44, + "v8": "4.2" + }, + "2.3.1": { + "node_abi": 44, + "v8": "4.2" + }, + "2.3.2": { + "node_abi": 44, + "v8": "4.2" + }, + "2.3.3": { + "node_abi": 44, + "v8": "4.2" + }, + "2.3.4": { + "node_abi": 44, + "v8": "4.2" + }, + "2.4.0": { + "node_abi": 44, + "v8": "4.2" + }, + "2.5.0": { + "node_abi": 44, + "v8": "4.2" + }, + "3.0.0": { + "node_abi": 45, + "v8": "4.4" + }, + "3.1.0": { + "node_abi": 45, + "v8": "4.4" + }, + "3.2.0": { + "node_abi": 45, + "v8": "4.4" + }, + "3.3.0": { + "node_abi": 45, + "v8": "4.4" + }, + "3.3.1": { + "node_abi": 45, + "v8": "4.4" + }, + "4.0.0": { + "node_abi": 46, + "v8": "4.5" + }, + "4.1.0": { + "node_abi": 46, + "v8": "4.5" + }, + "4.1.1": { + "node_abi": 46, + "v8": "4.5" + }, + "4.1.2": { + "node_abi": 46, + "v8": "4.5" + }, + "4.2.0": { + "node_abi": 46, + "v8": "4.5" + }, + "4.2.1": { + "node_abi": 46, + "v8": "4.5" + }, + "4.2.2": { + "node_abi": 46, + "v8": "4.5" + }, + "4.2.3": { + "node_abi": 46, + "v8": "4.5" + }, + "4.2.4": { + "node_abi": 46, + "v8": "4.5" + }, + "4.2.5": { + "node_abi": 46, + "v8": "4.5" + }, + "4.2.6": { + "node_abi": 46, + "v8": "4.5" + }, + "4.3.0": { + "node_abi": 46, + "v8": "4.5" + }, + "4.3.1": { + "node_abi": 46, + "v8": "4.5" + }, + "4.3.2": { + "node_abi": 46, + "v8": "4.5" + }, + "4.4.0": { + "node_abi": 46, + "v8": "4.5" + }, + "4.4.1": { + "node_abi": 46, + "v8": "4.5" + }, + "4.4.2": { + "node_abi": 46, + "v8": "4.5" + }, + "4.4.3": { + "node_abi": 46, + "v8": "4.5" + }, + "4.4.4": { + "node_abi": 46, + "v8": "4.5" + }, + "4.4.5": { + "node_abi": 46, + "v8": "4.5" + }, + "4.4.6": { + "node_abi": 46, + "v8": "4.5" + }, + "4.4.7": { + "node_abi": 46, + "v8": "4.5" + }, + "4.5.0": { + "node_abi": 46, + "v8": "4.5" + }, + "4.6.0": { + "node_abi": 46, + "v8": "4.5" + }, + "4.6.1": { + "node_abi": 46, + "v8": "4.5" + }, + "4.6.2": { + "node_abi": 46, + "v8": "4.5" + }, + "4.7.0": { + "node_abi": 46, + "v8": "4.5" + }, + "4.7.1": { + "node_abi": 46, + "v8": "4.5" + }, + "4.7.2": { + "node_abi": 46, + "v8": "4.5" + }, + "4.7.3": { + "node_abi": 46, + "v8": "4.5" + }, + "4.8.0": { + "node_abi": 46, + "v8": "4.5" + }, + "4.8.1": { + "node_abi": 46, + "v8": "4.5" + }, + "4.8.2": { + "node_abi": 46, + "v8": "4.5" + }, + "4.8.3": { + "node_abi": 46, + "v8": "4.5" + }, + "4.8.4": { + "node_abi": 46, + "v8": "4.5" + }, + "4.8.5": { + "node_abi": 46, + "v8": "4.5" + }, + "4.8.6": { + "node_abi": 46, + "v8": "4.5" + }, + "4.8.7": { + "node_abi": 46, + "v8": "4.5" + }, + "4.9.0": { + "node_abi": 46, + "v8": "4.5" + }, + "4.9.1": { + "node_abi": 46, + "v8": "4.5" + }, + "5.0.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.1.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.1.1": { + "node_abi": 47, + "v8": "4.6" + }, + "5.2.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.3.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.4.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.4.1": { + "node_abi": 47, + "v8": "4.6" + }, + "5.5.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.6.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.7.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.7.1": { + "node_abi": 47, + "v8": "4.6" + }, + "5.8.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.9.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.9.1": { + "node_abi": 47, + "v8": "4.6" + }, + "5.10.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.10.1": { + "node_abi": 47, + "v8": "4.6" + }, + "5.11.0": { + "node_abi": 47, + "v8": "4.6" + }, + "5.11.1": { + "node_abi": 47, + "v8": "4.6" + }, + "5.12.0": { + "node_abi": 47, + "v8": "4.6" + }, + "6.0.0": { + "node_abi": 48, + "v8": "5.0" + }, + "6.1.0": { + "node_abi": 48, + "v8": "5.0" + }, + "6.2.0": { + "node_abi": 48, + "v8": "5.0" + }, + "6.2.1": { + "node_abi": 48, + "v8": "5.0" + }, + "6.2.2": { + "node_abi": 48, + "v8": "5.0" + }, + "6.3.0": { + "node_abi": 48, + "v8": "5.0" + }, + "6.3.1": { + "node_abi": 48, + "v8": "5.0" + }, + "6.4.0": { + "node_abi": 48, + "v8": "5.0" + }, + "6.5.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.6.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.7.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.8.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.8.1": { + "node_abi": 48, + "v8": "5.1" + }, + "6.9.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.9.1": { + "node_abi": 48, + "v8": "5.1" + }, + "6.9.2": { + "node_abi": 48, + "v8": "5.1" + }, + "6.9.3": { + "node_abi": 48, + "v8": "5.1" + }, + "6.9.4": { + "node_abi": 48, + "v8": "5.1" + }, + "6.9.5": { + "node_abi": 48, + "v8": "5.1" + }, + "6.10.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.10.1": { + "node_abi": 48, + "v8": "5.1" + }, + "6.10.2": { + "node_abi": 48, + "v8": "5.1" + }, + "6.10.3": { + "node_abi": 48, + "v8": "5.1" + }, + "6.11.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.11.1": { + "node_abi": 48, + "v8": "5.1" + }, + "6.11.2": { + "node_abi": 48, + "v8": "5.1" + }, + "6.11.3": { + "node_abi": 48, + "v8": "5.1" + }, + "6.11.4": { + "node_abi": 48, + "v8": "5.1" + }, + "6.11.5": { + "node_abi": 48, + "v8": "5.1" + }, + "6.12.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.12.1": { + "node_abi": 48, + "v8": "5.1" + }, + "6.12.2": { + "node_abi": 48, + "v8": "5.1" + }, + "6.12.3": { + "node_abi": 48, + "v8": "5.1" + }, + "6.13.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.13.1": { + "node_abi": 48, + "v8": "5.1" + }, + "6.14.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.14.1": { + "node_abi": 48, + "v8": "5.1" + }, + "6.14.2": { + "node_abi": 48, + "v8": "5.1" + }, + "6.14.3": { + "node_abi": 48, + "v8": "5.1" + }, + "6.14.4": { + "node_abi": 48, + "v8": "5.1" + }, + "6.15.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.15.1": { + "node_abi": 48, + "v8": "5.1" + }, + "6.16.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.17.0": { + "node_abi": 48, + "v8": "5.1" + }, + "6.17.1": { + "node_abi": 48, + "v8": "5.1" + }, + "7.0.0": { + "node_abi": 51, + "v8": "5.4" + }, + "7.1.0": { + "node_abi": 51, + "v8": "5.4" + }, + "7.2.0": { + "node_abi": 51, + "v8": "5.4" + }, + "7.2.1": { + "node_abi": 51, + "v8": "5.4" + }, + "7.3.0": { + "node_abi": 51, + "v8": "5.4" + }, + "7.4.0": { + "node_abi": 51, + "v8": "5.4" + }, + "7.5.0": { + "node_abi": 51, + "v8": "5.4" + }, + "7.6.0": { + "node_abi": 51, + "v8": "5.5" + }, + "7.7.0": { + "node_abi": 51, + "v8": "5.5" + }, + "7.7.1": { + "node_abi": 51, + "v8": "5.5" + }, + "7.7.2": { + "node_abi": 51, + "v8": "5.5" + }, + "7.7.3": { + "node_abi": 51, + "v8": "5.5" + }, + "7.7.4": { + "node_abi": 51, + "v8": "5.5" + }, + "7.8.0": { + "node_abi": 51, + "v8": "5.5" + }, + "7.9.0": { + "node_abi": 51, + "v8": "5.5" + }, + "7.10.0": { + "node_abi": 51, + "v8": "5.5" + }, + "7.10.1": { + "node_abi": 51, + "v8": "5.5" + }, + "8.0.0": { + "node_abi": 57, + "v8": "5.8" + }, + "8.1.0": { + "node_abi": 57, + "v8": "5.8" + }, + "8.1.1": { + "node_abi": 57, + "v8": "5.8" + }, + "8.1.2": { + "node_abi": 57, + "v8": "5.8" + }, + "8.1.3": { + "node_abi": 57, + "v8": "5.8" + }, + "8.1.4": { + "node_abi": 57, + "v8": "5.8" + }, + "8.2.0": { + "node_abi": 57, + "v8": "5.8" + }, + "8.2.1": { + "node_abi": 57, + "v8": "5.8" + }, + "8.3.0": { + "node_abi": 57, + "v8": "6.0" + }, + "8.4.0": { + "node_abi": 57, + "v8": "6.0" + }, + "8.5.0": { + "node_abi": 57, + "v8": "6.0" + }, + "8.6.0": { + "node_abi": 57, + "v8": "6.0" + }, + "8.7.0": { + "node_abi": 57, + "v8": "6.1" + }, + "8.8.0": { + "node_abi": 57, + "v8": "6.1" + }, + "8.8.1": { + "node_abi": 57, + "v8": "6.1" + }, + "8.9.0": { + "node_abi": 57, + "v8": "6.1" + }, + "8.9.1": { + "node_abi": 57, + "v8": "6.1" + }, + "8.9.2": { + "node_abi": 57, + "v8": "6.1" + }, + "8.9.3": { + "node_abi": 57, + "v8": "6.1" + }, + "8.9.4": { + "node_abi": 57, + "v8": "6.1" + }, + "8.10.0": { + "node_abi": 57, + "v8": "6.2" + }, + "8.11.0": { + "node_abi": 57, + "v8": "6.2" + }, + "8.11.1": { + "node_abi": 57, + "v8": "6.2" + }, + "8.11.2": { + "node_abi": 57, + "v8": "6.2" + }, + "8.11.3": { + "node_abi": 57, + "v8": "6.2" + }, + "8.11.4": { + "node_abi": 57, + "v8": "6.2" + }, + "8.12.0": { + "node_abi": 57, + "v8": "6.2" + }, + "8.13.0": { + "node_abi": 57, + "v8": "6.2" + }, + "8.14.0": { + "node_abi": 57, + "v8": "6.2" + }, + "8.14.1": { + "node_abi": 57, + "v8": "6.2" + }, + "8.15.0": { + "node_abi": 57, + "v8": "6.2" + }, + "8.15.1": { + "node_abi": 57, + "v8": "6.2" + }, + "8.16.0": { + "node_abi": 57, + "v8": "6.2" + }, + "8.16.1": { + "node_abi": 57, + "v8": "6.2" + }, + "8.16.2": { + "node_abi": 57, + "v8": "6.2" + }, + "8.17.0": { + "node_abi": 57, + "v8": "6.2" + }, + "9.0.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.1.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.2.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.2.1": { + "node_abi": 59, + "v8": "6.2" + }, + "9.3.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.4.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.5.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.6.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.6.1": { + "node_abi": 59, + "v8": "6.2" + }, + "9.7.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.7.1": { + "node_abi": 59, + "v8": "6.2" + }, + "9.8.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.9.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.10.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.10.1": { + "node_abi": 59, + "v8": "6.2" + }, + "9.11.0": { + "node_abi": 59, + "v8": "6.2" + }, + "9.11.1": { + "node_abi": 59, + "v8": "6.2" + }, + "9.11.2": { + "node_abi": 59, + "v8": "6.2" + }, + "10.0.0": { + "node_abi": 64, + "v8": "6.6" + }, + "10.1.0": { + "node_abi": 64, + "v8": "6.6" + }, + "10.2.0": { + "node_abi": 64, + "v8": "6.6" + }, + "10.2.1": { + "node_abi": 64, + "v8": "6.6" + }, + "10.3.0": { + "node_abi": 64, + "v8": "6.6" + }, + "10.4.0": { + "node_abi": 64, + "v8": "6.7" + }, + "10.4.1": { + "node_abi": 64, + "v8": "6.7" + }, + "10.5.0": { + "node_abi": 64, + "v8": "6.7" + }, + "10.6.0": { + "node_abi": 64, + "v8": "6.7" + }, + "10.7.0": { + "node_abi": 64, + "v8": "6.7" + }, + "10.8.0": { + "node_abi": 64, + "v8": "6.7" + }, + "10.9.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.10.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.11.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.12.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.13.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.14.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.14.1": { + "node_abi": 64, + "v8": "6.8" + }, + "10.14.2": { + "node_abi": 64, + "v8": "6.8" + }, + "10.15.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.15.1": { + "node_abi": 64, + "v8": "6.8" + }, + "10.15.2": { + "node_abi": 64, + "v8": "6.8" + }, + "10.15.3": { + "node_abi": 64, + "v8": "6.8" + }, + "10.16.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.16.1": { + "node_abi": 64, + "v8": "6.8" + }, + "10.16.2": { + "node_abi": 64, + "v8": "6.8" + }, + "10.16.3": { + "node_abi": 64, + "v8": "6.8" + }, + "10.17.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.18.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.18.1": { + "node_abi": 64, + "v8": "6.8" + }, + "10.19.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.20.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.20.1": { + "node_abi": 64, + "v8": "6.8" + }, + "10.21.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.22.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.22.1": { + "node_abi": 64, + "v8": "6.8" + }, + "10.23.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.23.1": { + "node_abi": 64, + "v8": "6.8" + }, + "10.23.2": { + "node_abi": 64, + "v8": "6.8" + }, + "10.23.3": { + "node_abi": 64, + "v8": "6.8" + }, + "10.24.0": { + "node_abi": 64, + "v8": "6.8" + }, + "10.24.1": { + "node_abi": 64, + "v8": "6.8" + }, + "11.0.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.1.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.2.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.3.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.4.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.5.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.6.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.7.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.8.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.9.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.10.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.10.1": { + "node_abi": 67, + "v8": "7.0" + }, + "11.11.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.12.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.13.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.14.0": { + "node_abi": 67, + "v8": "7.0" + }, + "11.15.0": { + "node_abi": 67, + "v8": "7.0" + }, + "12.0.0": { + "node_abi": 72, + "v8": "7.4" + }, + "12.1.0": { + "node_abi": 72, + "v8": "7.4" + }, + "12.2.0": { + "node_abi": 72, + "v8": "7.4" + }, + "12.3.0": { + "node_abi": 72, + "v8": "7.4" + }, + "12.3.1": { + "node_abi": 72, + "v8": "7.4" + }, + "12.4.0": { + "node_abi": 72, + "v8": "7.4" + }, + "12.5.0": { + "node_abi": 72, + "v8": "7.5" + }, + "12.6.0": { + "node_abi": 72, + "v8": "7.5" + }, + "12.7.0": { + "node_abi": 72, + "v8": "7.5" + }, + "12.8.0": { + "node_abi": 72, + "v8": "7.5" + }, + "12.8.1": { + "node_abi": 72, + "v8": "7.5" + }, + "12.9.0": { + "node_abi": 72, + "v8": "7.6" + }, + "12.9.1": { + "node_abi": 72, + "v8": "7.6" + }, + "12.10.0": { + "node_abi": 72, + "v8": "7.6" + }, + "12.11.0": { + "node_abi": 72, + "v8": "7.7" + }, + "12.11.1": { + "node_abi": 72, + "v8": "7.7" + }, + "12.12.0": { + "node_abi": 72, + "v8": "7.7" + }, + "12.13.0": { + "node_abi": 72, + "v8": "7.7" + }, + "12.13.1": { + "node_abi": 72, + "v8": "7.7" + }, + "12.14.0": { + "node_abi": 72, + "v8": "7.7" + }, + "12.14.1": { + "node_abi": 72, + "v8": "7.7" + }, + "12.15.0": { + "node_abi": 72, + "v8": "7.7" + }, + "12.16.0": { + "node_abi": 72, + "v8": "7.8" + }, + "12.16.1": { + "node_abi": 72, + "v8": "7.8" + }, + "12.16.2": { + "node_abi": 72, + "v8": "7.8" + }, + "12.16.3": { + "node_abi": 72, + "v8": "7.8" + }, + "12.17.0": { + "node_abi": 72, + "v8": "7.8" + }, + "12.18.0": { + "node_abi": 72, + "v8": "7.8" + }, + "12.18.1": { + "node_abi": 72, + "v8": "7.8" + }, + "12.18.2": { + "node_abi": 72, + "v8": "7.8" + }, + "12.18.3": { + "node_abi": 72, + "v8": "7.8" + }, + "12.18.4": { + "node_abi": 72, + "v8": "7.8" + }, + "12.19.0": { + "node_abi": 72, + "v8": "7.8" + }, + "12.19.1": { + "node_abi": 72, + "v8": "7.8" + }, + "12.20.0": { + "node_abi": 72, + "v8": "7.8" + }, + "12.20.1": { + "node_abi": 72, + "v8": "7.8" + }, + "12.20.2": { + "node_abi": 72, + "v8": "7.8" + }, + "12.21.0": { + "node_abi": 72, + "v8": "7.8" + }, + "12.22.0": { + "node_abi": 72, + "v8": "7.8" + }, + "12.22.1": { + "node_abi": 72, + "v8": "7.8" + }, + "12.22.2": { + "node_abi": 72, + "v8": "7.8" + }, + "12.22.3": { + "node_abi": 72, + "v8": "7.8" + }, + "12.22.4": { + "node_abi": 72, + "v8": "7.8" + }, + "12.22.5": { + "node_abi": 72, + "v8": "7.8" + }, + "12.22.6": { + "node_abi": 72, + "v8": "7.8" + }, + "12.22.7": { + "node_abi": 72, + "v8": "7.8" + }, + "13.0.0": { + "node_abi": 79, + "v8": "7.8" + }, + "13.0.1": { + "node_abi": 79, + "v8": "7.8" + }, + "13.1.0": { + "node_abi": 79, + "v8": "7.8" + }, + "13.2.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.3.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.4.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.5.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.6.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.7.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.8.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.9.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.10.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.10.1": { + "node_abi": 79, + "v8": "7.9" + }, + "13.11.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.12.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.13.0": { + "node_abi": 79, + "v8": "7.9" + }, + "13.14.0": { + "node_abi": 79, + "v8": "7.9" + }, + "14.0.0": { + "node_abi": 83, + "v8": "8.1" + }, + "14.1.0": { + "node_abi": 83, + "v8": "8.1" + }, + "14.2.0": { + "node_abi": 83, + "v8": "8.1" + }, + "14.3.0": { + "node_abi": 83, + "v8": "8.1" + }, + "14.4.0": { + "node_abi": 83, + "v8": "8.1" + }, + "14.5.0": { + "node_abi": 83, + "v8": "8.3" + }, + "14.6.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.7.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.8.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.9.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.10.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.10.1": { + "node_abi": 83, + "v8": "8.4" + }, + "14.11.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.12.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.13.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.13.1": { + "node_abi": 83, + "v8": "8.4" + }, + "14.14.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.15.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.15.1": { + "node_abi": 83, + "v8": "8.4" + }, + "14.15.2": { + "node_abi": 83, + "v8": "8.4" + }, + "14.15.3": { + "node_abi": 83, + "v8": "8.4" + }, + "14.15.4": { + "node_abi": 83, + "v8": "8.4" + }, + "14.15.5": { + "node_abi": 83, + "v8": "8.4" + }, + "14.16.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.16.1": { + "node_abi": 83, + "v8": "8.4" + }, + "14.17.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.17.1": { + "node_abi": 83, + "v8": "8.4" + }, + "14.17.2": { + "node_abi": 83, + "v8": "8.4" + }, + "14.17.3": { + "node_abi": 83, + "v8": "8.4" + }, + "14.17.4": { + "node_abi": 83, + "v8": "8.4" + }, + "14.17.5": { + "node_abi": 83, + "v8": "8.4" + }, + "14.17.6": { + "node_abi": 83, + "v8": "8.4" + }, + "14.18.0": { + "node_abi": 83, + "v8": "8.4" + }, + "14.18.1": { + "node_abi": 83, + "v8": "8.4" + }, + "15.0.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.0.1": { + "node_abi": 88, + "v8": "8.6" + }, + "15.1.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.2.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.2.1": { + "node_abi": 88, + "v8": "8.6" + }, + "15.3.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.4.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.5.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.5.1": { + "node_abi": 88, + "v8": "8.6" + }, + "15.6.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.7.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.8.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.9.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.10.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.11.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.12.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.13.0": { + "node_abi": 88, + "v8": "8.6" + }, + "15.14.0": { + "node_abi": 88, + "v8": "8.6" + }, + "16.0.0": { + "node_abi": 93, + "v8": "9.0" + }, + "16.1.0": { + "node_abi": 93, + "v8": "9.0" + }, + "16.2.0": { + "node_abi": 93, + "v8": "9.0" + }, + "16.3.0": { + "node_abi": 93, + "v8": "9.0" + }, + "16.4.0": { + "node_abi": 93, + "v8": "9.1" + }, + "16.4.1": { + "node_abi": 93, + "v8": "9.1" + }, + "16.4.2": { + "node_abi": 93, + "v8": "9.1" + }, + "16.5.0": { + "node_abi": 93, + "v8": "9.1" + }, + "16.6.0": { + "node_abi": 93, + "v8": "9.2" + }, + "16.6.1": { + "node_abi": 93, + "v8": "9.2" + }, + "16.6.2": { + "node_abi": 93, + "v8": "9.2" + }, + "16.7.0": { + "node_abi": 93, + "v8": "9.2" + }, + "16.8.0": { + "node_abi": 93, + "v8": "9.2" + }, + "16.9.0": { + "node_abi": 93, + "v8": "9.3" + }, + "16.9.1": { + "node_abi": 93, + "v8": "9.3" + }, + "16.10.0": { + "node_abi": 93, + "v8": "9.3" + }, + "16.11.0": { + "node_abi": 93, + "v8": "9.4" + }, + "16.11.1": { + "node_abi": 93, + "v8": "9.4" + }, + "16.12.0": { + "node_abi": 93, + "v8": "9.4" + }, + "16.13.0": { + "node_abi": 93, + "v8": "9.4" + }, + "17.0.0": { + "node_abi": 102, + "v8": "9.5" + }, + "17.0.1": { + "node_abi": 102, + "v8": "9.5" + }, + "17.1.0": { + "node_abi": 102, + "v8": "9.5" + } +} \ No newline at end of file diff --git a/node_modules/@mapbox/node-pre-gyp/lib/util/compile.js b/node_modules/@mapbox/node-pre-gyp/lib/util/compile.js new file mode 100644 index 0000000..956e5aa --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/util/compile.js @@ -0,0 +1,93 @@ +'use strict'; + +module.exports = exports; + +const fs = require('fs'); +const path = require('path'); +const win = process.platform === 'win32'; +const existsSync = fs.existsSync || path.existsSync; +const cp = require('child_process'); + +// try to build up the complete path to node-gyp +/* priority: + - node-gyp on ENV:npm_config_node_gyp (https://github.com/npm/npm/pull/4887) + - node-gyp on NODE_PATH + - node-gyp inside npm on NODE_PATH (ignore on iojs) + - node-gyp inside npm beside node exe +*/ +function which_node_gyp() { + let node_gyp_bin; + if (process.env.npm_config_node_gyp) { + try { + node_gyp_bin = process.env.npm_config_node_gyp; + if (existsSync(node_gyp_bin)) { + return node_gyp_bin; + } + } catch (err) { + // do nothing + } + } + try { + const node_gyp_main = require.resolve('node-gyp'); // eslint-disable-line node/no-missing-require + node_gyp_bin = path.join(path.dirname( + path.dirname(node_gyp_main)), + 'bin/node-gyp.js'); + if (existsSync(node_gyp_bin)) { + return node_gyp_bin; + } + } catch (err) { + // do nothing + } + if (process.execPath.indexOf('iojs') === -1) { + try { + const npm_main = require.resolve('npm'); // eslint-disable-line node/no-missing-require + node_gyp_bin = path.join(path.dirname( + path.dirname(npm_main)), + 'node_modules/node-gyp/bin/node-gyp.js'); + if (existsSync(node_gyp_bin)) { + return node_gyp_bin; + } + } catch (err) { + // do nothing + } + } + const npm_base = path.join(path.dirname( + path.dirname(process.execPath)), + 'lib/node_modules/npm/'); + node_gyp_bin = path.join(npm_base, 'node_modules/node-gyp/bin/node-gyp.js'); + if (existsSync(node_gyp_bin)) { + return node_gyp_bin; + } +} + +module.exports.run_gyp = function(args, opts, callback) { + let shell_cmd = ''; + const cmd_args = []; + if (opts.runtime && opts.runtime === 'node-webkit') { + shell_cmd = 'nw-gyp'; + if (win) shell_cmd += '.cmd'; + } else { + const node_gyp_path = which_node_gyp(); + if (node_gyp_path) { + shell_cmd = process.execPath; + cmd_args.push(node_gyp_path); + } else { + shell_cmd = 'node-gyp'; + if (win) shell_cmd += '.cmd'; + } + } + const final_args = cmd_args.concat(args); + const cmd = cp.spawn(shell_cmd, final_args, { cwd: undefined, env: process.env, stdio: [0, 1, 2] }); + cmd.on('error', (err) => { + if (err) { + return callback(new Error("Failed to execute '" + shell_cmd + ' ' + final_args.join(' ') + "' (" + err + ')')); + } + callback(null, opts); + }); + cmd.on('close', (code) => { + if (code && code !== 0) { + return callback(new Error("Failed to execute '" + shell_cmd + ' ' + final_args.join(' ') + "' (" + code + ')')); + } + callback(null, opts); + }); +}; diff --git a/node_modules/@mapbox/node-pre-gyp/lib/util/handle_gyp_opts.js b/node_modules/@mapbox/node-pre-gyp/lib/util/handle_gyp_opts.js new file mode 100644 index 0000000..d702f78 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/util/handle_gyp_opts.js @@ -0,0 +1,102 @@ +'use strict'; + +module.exports = exports = handle_gyp_opts; + +const versioning = require('./versioning.js'); +const napi = require('./napi.js'); + +/* + +Here we gather node-pre-gyp generated options (from versioning) and pass them along to node-gyp. + +We massage the args and options slightly to account for differences in what commands mean between +node-pre-gyp and node-gyp (e.g. see the difference between "build" and "rebuild" below) + +Keep in mind: the values inside `argv` and `gyp.opts` below are different depending on whether +node-pre-gyp is called directory, or if it is called in a `run-script` phase of npm. + +We also try to preserve any command line options that might have been passed to npm or node-pre-gyp. +But this is fairly difficult without passing way to much through. For example `gyp.opts` contains all +the process.env and npm pushes a lot of variables into process.env which node-pre-gyp inherits. So we have +to be very selective about what we pass through. + +For example: + +`npm install --build-from-source` will give: + +argv == [ 'rebuild' ] +gyp.opts.argv == { remain: [ 'install' ], + cooked: [ 'install', '--fallback-to-build' ], + original: [ 'install', '--fallback-to-build' ] } + +`./bin/node-pre-gyp build` will give: + +argv == [] +gyp.opts.argv == { remain: [ 'build' ], + cooked: [ 'build' ], + original: [ '-C', 'test/app1', 'build' ] } + +*/ + +// select set of node-pre-gyp versioning info +// to share with node-gyp +const share_with_node_gyp = [ + 'module', + 'module_name', + 'module_path', + 'napi_version', + 'node_abi_napi', + 'napi_build_version', + 'node_napi_label' +]; + +function handle_gyp_opts(gyp, argv, callback) { + + // Collect node-pre-gyp specific variables to pass to node-gyp + const node_pre_gyp_options = []; + // generate custom node-pre-gyp versioning info + const napi_build_version = napi.get_napi_build_version_from_command_args(argv); + const opts = versioning.evaluate(gyp.package_json, gyp.opts, napi_build_version); + share_with_node_gyp.forEach((key) => { + const val = opts[key]; + if (val) { + node_pre_gyp_options.push('--' + key + '=' + val); + } else if (key === 'napi_build_version') { + node_pre_gyp_options.push('--' + key + '=0'); + } else { + if (key !== 'napi_version' && key !== 'node_abi_napi') + return callback(new Error('Option ' + key + ' required but not found by node-pre-gyp')); + } + }); + + // Collect options that follow the special -- which disables nopt parsing + const unparsed_options = []; + let double_hyphen_found = false; + gyp.opts.argv.original.forEach((opt) => { + if (double_hyphen_found) { + unparsed_options.push(opt); + } + if (opt === '--') { + double_hyphen_found = true; + } + }); + + // We try respect and pass through remaining command + // line options (like --foo=bar) to node-gyp + const cooked = gyp.opts.argv.cooked; + const node_gyp_options = []; + cooked.forEach((value) => { + if (value.length > 2 && value.slice(0, 2) === '--') { + const key = value.slice(2); + const val = cooked[cooked.indexOf(value) + 1]; + if (val && val.indexOf('--') === -1) { // handle '--foo=bar' or ['--foo','bar'] + node_gyp_options.push('--' + key + '=' + val); + } else { // pass through --foo + node_gyp_options.push(value); + } + } + }); + + const result = { 'opts': opts, 'gyp': node_gyp_options, 'pre': node_pre_gyp_options, 'unparsed': unparsed_options }; + return callback(null, result); +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/util/napi.js b/node_modules/@mapbox/node-pre-gyp/lib/util/napi.js new file mode 100644 index 0000000..5d14ad6 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/util/napi.js @@ -0,0 +1,205 @@ +'use strict'; + +const fs = require('fs'); + +module.exports = exports; + +const versionArray = process.version + .substr(1) + .replace(/-.*$/, '') + .split('.') + .map((item) => { + return +item; + }); + +const napi_multiple_commands = [ + 'build', + 'clean', + 'configure', + 'package', + 'publish', + 'reveal', + 'testbinary', + 'testpackage', + 'unpublish' +]; + +const napi_build_version_tag = 'napi_build_version='; + +module.exports.get_napi_version = function() { + // returns the non-zero numeric napi version or undefined if napi is not supported. + // correctly supporting target requires an updated cross-walk + let version = process.versions.napi; // can be undefined + if (!version) { // this code should never need to be updated + if (versionArray[0] === 9 && versionArray[1] >= 3) version = 2; // 9.3.0+ + else if (versionArray[0] === 8) version = 1; // 8.0.0+ + } + return version; +}; + +module.exports.get_napi_version_as_string = function(target) { + // returns the napi version as a string or an empty string if napi is not supported. + const version = module.exports.get_napi_version(target); + return version ? '' + version : ''; +}; + +module.exports.validate_package_json = function(package_json, opts) { // throws Error + + const binary = package_json.binary; + const module_path_ok = pathOK(binary.module_path); + const remote_path_ok = pathOK(binary.remote_path); + const package_name_ok = pathOK(binary.package_name); + const napi_build_versions = module.exports.get_napi_build_versions(package_json, opts, true); + const napi_build_versions_raw = module.exports.get_napi_build_versions_raw(package_json); + + if (napi_build_versions) { + napi_build_versions.forEach((napi_build_version)=> { + if (!(parseInt(napi_build_version, 10) === napi_build_version && napi_build_version > 0)) { + throw new Error('All values specified in napi_versions must be positive integers.'); + } + }); + } + + if (napi_build_versions && (!module_path_ok || (!remote_path_ok && !package_name_ok))) { + throw new Error('When napi_versions is specified; module_path and either remote_path or ' + + "package_name must contain the substitution string '{napi_build_version}`."); + } + + if ((module_path_ok || remote_path_ok || package_name_ok) && !napi_build_versions_raw) { + throw new Error("When the substitution string '{napi_build_version}` is specified in " + + 'module_path, remote_path, or package_name; napi_versions must also be specified.'); + } + + if (napi_build_versions && !module.exports.get_best_napi_build_version(package_json, opts) && + module.exports.build_napi_only(package_json)) { + throw new Error( + 'The Node-API version of this Node instance is ' + module.exports.get_napi_version(opts ? opts.target : undefined) + '. ' + + 'This module supports Node-API version(s) ' + module.exports.get_napi_build_versions_raw(package_json) + '. ' + + 'This Node instance cannot run this module.'); + } + + if (napi_build_versions_raw && !napi_build_versions && module.exports.build_napi_only(package_json)) { + throw new Error( + 'The Node-API version of this Node instance is ' + module.exports.get_napi_version(opts ? opts.target : undefined) + '. ' + + 'This module supports Node-API version(s) ' + module.exports.get_napi_build_versions_raw(package_json) + '. ' + + 'This Node instance cannot run this module.'); + } + +}; + +function pathOK(path) { + return path && (path.indexOf('{napi_build_version}') !== -1 || path.indexOf('{node_napi_label}') !== -1); +} + +module.exports.expand_commands = function(package_json, opts, commands) { + const expanded_commands = []; + const napi_build_versions = module.exports.get_napi_build_versions(package_json, opts); + commands.forEach((command)=> { + if (napi_build_versions && command.name === 'install') { + const napi_build_version = module.exports.get_best_napi_build_version(package_json, opts); + const args = napi_build_version ? [napi_build_version_tag + napi_build_version] : []; + expanded_commands.push({ name: command.name, args: args }); + } else if (napi_build_versions && napi_multiple_commands.indexOf(command.name) !== -1) { + napi_build_versions.forEach((napi_build_version)=> { + const args = command.args.slice(); + args.push(napi_build_version_tag + napi_build_version); + expanded_commands.push({ name: command.name, args: args }); + }); + } else { + expanded_commands.push(command); + } + }); + return expanded_commands; +}; + +module.exports.get_napi_build_versions = function(package_json, opts, warnings) { // opts may be undefined + const log = require('npmlog'); + let napi_build_versions = []; + const supported_napi_version = module.exports.get_napi_version(opts ? opts.target : undefined); + // remove duplicates, verify each napi version can actaully be built + if (package_json.binary && package_json.binary.napi_versions) { + package_json.binary.napi_versions.forEach((napi_version) => { + const duplicated = napi_build_versions.indexOf(napi_version) !== -1; + if (!duplicated && supported_napi_version && napi_version <= supported_napi_version) { + napi_build_versions.push(napi_version); + } else if (warnings && !duplicated && supported_napi_version) { + log.info('This Node instance does not support builds for Node-API version', napi_version); + } + }); + } + if (opts && opts['build-latest-napi-version-only']) { + let latest_version = 0; + napi_build_versions.forEach((napi_version) => { + if (napi_version > latest_version) latest_version = napi_version; + }); + napi_build_versions = latest_version ? [latest_version] : []; + } + return napi_build_versions.length ? napi_build_versions : undefined; +}; + +module.exports.get_napi_build_versions_raw = function(package_json) { + const napi_build_versions = []; + // remove duplicates + if (package_json.binary && package_json.binary.napi_versions) { + package_json.binary.napi_versions.forEach((napi_version) => { + if (napi_build_versions.indexOf(napi_version) === -1) { + napi_build_versions.push(napi_version); + } + }); + } + return napi_build_versions.length ? napi_build_versions : undefined; +}; + +module.exports.get_command_arg = function(napi_build_version) { + return napi_build_version_tag + napi_build_version; +}; + +module.exports.get_napi_build_version_from_command_args = function(command_args) { + for (let i = 0; i < command_args.length; i++) { + const arg = command_args[i]; + if (arg.indexOf(napi_build_version_tag) === 0) { + return parseInt(arg.substr(napi_build_version_tag.length), 10); + } + } + return undefined; +}; + +module.exports.swap_build_dir_out = function(napi_build_version) { + if (napi_build_version) { + const rm = require('rimraf'); + rm.sync(module.exports.get_build_dir(napi_build_version)); + fs.renameSync('build', module.exports.get_build_dir(napi_build_version)); + } +}; + +module.exports.swap_build_dir_in = function(napi_build_version) { + if (napi_build_version) { + const rm = require('rimraf'); + rm.sync('build'); + fs.renameSync(module.exports.get_build_dir(napi_build_version), 'build'); + } +}; + +module.exports.get_build_dir = function(napi_build_version) { + return 'build-tmp-napi-v' + napi_build_version; +}; + +module.exports.get_best_napi_build_version = function(package_json, opts) { + let best_napi_build_version = 0; + const napi_build_versions = module.exports.get_napi_build_versions(package_json, opts); + if (napi_build_versions) { + const our_napi_version = module.exports.get_napi_version(opts ? opts.target : undefined); + napi_build_versions.forEach((napi_build_version)=> { + if (napi_build_version > best_napi_build_version && + napi_build_version <= our_napi_version) { + best_napi_build_version = napi_build_version; + } + }); + } + return best_napi_build_version === 0 ? undefined : best_napi_build_version; +}; + +module.exports.build_napi_only = function(package_json) { + return package_json.binary && package_json.binary.package_name && + package_json.binary.package_name.indexOf('{node_napi_label}') === -1; +}; diff --git a/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html b/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html new file mode 100644 index 0000000..244466c --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html @@ -0,0 +1,26 @@ + + + + +Node-webkit-based module test + + + +

Node-webkit-based module test

+ + diff --git a/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/package.json b/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/package.json new file mode 100644 index 0000000..71d03f8 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/package.json @@ -0,0 +1,9 @@ +{ +"main": "index.html", +"name": "nw-pre-gyp-module-test", +"description": "Node-webkit-based module test.", +"version": "0.0.1", +"window": { + "show": false +} +} diff --git a/node_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js b/node_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js new file mode 100644 index 0000000..6b1b1a6 --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js @@ -0,0 +1,163 @@ +'use strict'; + +module.exports = exports; + +const url = require('url'); +const fs = require('fs'); +const path = require('path'); + +module.exports.detect = function(opts, config) { + const to = opts.hosted_path; + const uri = url.parse(to); + config.prefix = (!uri.pathname || uri.pathname === '/') ? '' : uri.pathname.replace('/', ''); + if (opts.bucket && opts.region) { + config.bucket = opts.bucket; + config.region = opts.region; + config.endpoint = opts.host; + config.s3ForcePathStyle = opts.s3ForcePathStyle; + } else { + const parts = uri.hostname.split('.s3'); + const bucket = parts[0]; + if (!bucket) { + return; + } + if (!config.bucket) { + config.bucket = bucket; + } + if (!config.region) { + const region = parts[1].slice(1).split('.')[0]; + if (region === 'amazonaws') { + config.region = 'us-east-1'; + } else { + config.region = region; + } + } + } +}; + +module.exports.get_s3 = function(config) { + + if (process.env.node_pre_gyp_mock_s3) { + // here we're mocking. node_pre_gyp_mock_s3 is the scratch directory + // for the mock code. + const AWSMock = require('mock-aws-s3'); + const os = require('os'); + + AWSMock.config.basePath = `${os.tmpdir()}/mock`; + + const s3 = AWSMock.S3(); + + // wrapped callback maker. fs calls return code of ENOENT but AWS.S3 returns + // NotFound. + const wcb = (fn) => (err, ...args) => { + if (err && err.code === 'ENOENT') { + err.code = 'NotFound'; + } + return fn(err, ...args); + }; + + return { + listObjects(params, callback) { + return s3.listObjects(params, wcb(callback)); + }, + headObject(params, callback) { + return s3.headObject(params, wcb(callback)); + }, + deleteObject(params, callback) { + return s3.deleteObject(params, wcb(callback)); + }, + putObject(params, callback) { + return s3.putObject(params, wcb(callback)); + } + }; + } + + // if not mocking then setup real s3. + const AWS = require('aws-sdk'); + + AWS.config.update(config); + const s3 = new AWS.S3(); + + // need to change if additional options need to be specified. + return { + listObjects(params, callback) { + return s3.listObjects(params, callback); + }, + headObject(params, callback) { + return s3.headObject(params, callback); + }, + deleteObject(params, callback) { + return s3.deleteObject(params, callback); + }, + putObject(params, callback) { + return s3.putObject(params, callback); + } + }; + + + +}; + +// +// function to get the mocking control function. if not mocking it returns a no-op. +// +// if mocking it sets up the mock http interceptors that use the mocked s3 file system +// to fulfill reponses. +module.exports.get_mockS3Http = function() { + let mock_s3 = false; + if (!process.env.node_pre_gyp_mock_s3) { + return () => mock_s3; + } + + const nock = require('nock'); + // the bucket used for testing, as addressed by https. + const host = 'https://mapbox-node-pre-gyp-public-testing-bucket.s3.us-east-1.amazonaws.com'; + const mockDir = process.env.node_pre_gyp_mock_s3 + '/mapbox-node-pre-gyp-public-testing-bucket'; + + // function to setup interceptors. they are "turned off" by setting mock_s3 to false. + const mock_http = () => { + // eslint-disable-next-line no-unused-vars + function get(uri, requestBody) { + const filepath = path.join(mockDir, uri.replace('%2B', '+')); + + try { + fs.accessSync(filepath, fs.constants.R_OK); + } catch (e) { + return [404, 'not found\n']; + } + + // the mock s3 functions just write to disk, so just read from it. + return [200, fs.createReadStream(filepath)]; + } + + // eslint-disable-next-line no-unused-vars + return nock(host) + .persist() + .get(() => mock_s3) // mock any uri for s3 when true + .reply(get); + }; + + // setup interceptors. they check the mock_s3 flag to determine whether to intercept. + mock_http(nock, host, mockDir); + // function to turn matching all requests to s3 on/off. + const mockS3Http = (action) => { + const previous = mock_s3; + if (action === 'off') { + mock_s3 = false; + } else if (action === 'on') { + mock_s3 = true; + } else if (action !== 'get') { + throw new Error(`illegal action for setMockHttp ${action}`); + } + return previous; + }; + + // call mockS3Http with the argument + // - 'on' - turn it on + // - 'off' - turn it off (used by fetch.test.js so it doesn't interfere with redirects) + // - 'get' - return true or false for 'on' or 'off' + return mockS3Http; +}; + + + diff --git a/node_modules/@mapbox/node-pre-gyp/lib/util/versioning.js b/node_modules/@mapbox/node-pre-gyp/lib/util/versioning.js new file mode 100644 index 0000000..4409d7c --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/lib/util/versioning.js @@ -0,0 +1,335 @@ +'use strict'; + +module.exports = exports; + +const path = require('path'); +const semver = require('semver'); +const url = require('url'); +const detect_libc = require('detect-libc'); +const napi = require('./napi.js'); + +let abi_crosswalk; + +// This is used for unit testing to provide a fake +// ABI crosswalk that emulates one that is not updated +// for the current version +if (process.env.NODE_PRE_GYP_ABI_CROSSWALK) { + abi_crosswalk = require(process.env.NODE_PRE_GYP_ABI_CROSSWALK); +} else { + abi_crosswalk = require('./abi_crosswalk.json'); +} + +const major_versions = {}; +Object.keys(abi_crosswalk).forEach((v) => { + const major = v.split('.')[0]; + if (!major_versions[major]) { + major_versions[major] = v; + } +}); + +function get_electron_abi(runtime, target_version) { + if (!runtime) { + throw new Error('get_electron_abi requires valid runtime arg'); + } + if (typeof target_version === 'undefined') { + // erroneous CLI call + throw new Error('Empty target version is not supported if electron is the target.'); + } + // Electron guarantees that patch version update won't break native modules. + const sem_ver = semver.parse(target_version); + return runtime + '-v' + sem_ver.major + '.' + sem_ver.minor; +} +module.exports.get_electron_abi = get_electron_abi; + +function get_node_webkit_abi(runtime, target_version) { + if (!runtime) { + throw new Error('get_node_webkit_abi requires valid runtime arg'); + } + if (typeof target_version === 'undefined') { + // erroneous CLI call + throw new Error('Empty target version is not supported if node-webkit is the target.'); + } + return runtime + '-v' + target_version; +} +module.exports.get_node_webkit_abi = get_node_webkit_abi; + +function get_node_abi(runtime, versions) { + if (!runtime) { + throw new Error('get_node_abi requires valid runtime arg'); + } + if (!versions) { + throw new Error('get_node_abi requires valid process.versions object'); + } + const sem_ver = semver.parse(versions.node); + if (sem_ver.major === 0 && sem_ver.minor % 2) { // odd series + // https://github.com/mapbox/node-pre-gyp/issues/124 + return runtime + '-v' + versions.node; + } else { + // process.versions.modules added in >= v0.10.4 and v0.11.7 + // https://github.com/joyent/node/commit/ccabd4a6fa8a6eb79d29bc3bbe9fe2b6531c2d8e + return versions.modules ? runtime + '-v' + (+versions.modules) : + 'v8-' + versions.v8.split('.').slice(0, 2).join('.'); + } +} +module.exports.get_node_abi = get_node_abi; + +function get_runtime_abi(runtime, target_version) { + if (!runtime) { + throw new Error('get_runtime_abi requires valid runtime arg'); + } + if (runtime === 'node-webkit') { + return get_node_webkit_abi(runtime, target_version || process.versions['node-webkit']); + } else if (runtime === 'electron') { + return get_electron_abi(runtime, target_version || process.versions.electron); + } else { + if (runtime !== 'node') { + throw new Error("Unknown Runtime: '" + runtime + "'"); + } + if (!target_version) { + return get_node_abi(runtime, process.versions); + } else { + let cross_obj; + // abi_crosswalk generated with ./scripts/abi_crosswalk.js + if (abi_crosswalk[target_version]) { + cross_obj = abi_crosswalk[target_version]; + } else { + const target_parts = target_version.split('.').map((i) => { return +i; }); + if (target_parts.length !== 3) { // parse failed + throw new Error('Unknown target version: ' + target_version); + } + /* + The below code tries to infer the last known ABI compatible version + that we have recorded in the abi_crosswalk.json when an exact match + is not possible. The reasons for this to exist are complicated: + + - We support passing --target to be able to allow developers to package binaries for versions of node + that are not the same one as they are running. This might also be used in combination with the + --target_arch or --target_platform flags to also package binaries for alternative platforms + - When --target is passed we can't therefore determine the ABI (process.versions.modules) from the node + version that is running in memory + - So, therefore node-pre-gyp keeps an "ABI crosswalk" (lib/util/abi_crosswalk.json) to be able to look + this info up for all versions + - But we cannot easily predict what the future ABI will be for released versions + - And node-pre-gyp needs to be a `bundledDependency` in apps that depend on it in order to work correctly + by being fully available at install time. + - So, the speed of node releases and the bundled nature of node-pre-gyp mean that a new node-pre-gyp release + need to happen for every node.js/io.js/node-webkit/nw.js/atom-shell/etc release that might come online if + you want the `--target` flag to keep working for the latest version + - Which is impractical ^^ + - Hence the below code guesses about future ABI to make the need to update node-pre-gyp less demanding. + + In practice then you can have a dependency of your app like `node-sqlite3` that bundles a `node-pre-gyp` that + only knows about node v0.10.33 in the `abi_crosswalk.json` but target node v0.10.34 (which is assumed to be + ABI compatible with v0.10.33). + + TODO: use semver module instead of custom version parsing + */ + const major = target_parts[0]; + let minor = target_parts[1]; + let patch = target_parts[2]; + // io.js: yeah if node.js ever releases 1.x this will break + // but that is unlikely to happen: https://github.com/iojs/io.js/pull/253#issuecomment-69432616 + if (major === 1) { + // look for last release that is the same major version + // e.g. we assume io.js 1.x is ABI compatible with >= 1.0.0 + while (true) { + if (minor > 0) --minor; + if (patch > 0) --patch; + const new_iojs_target = '' + major + '.' + minor + '.' + patch; + if (abi_crosswalk[new_iojs_target]) { + cross_obj = abi_crosswalk[new_iojs_target]; + console.log('Warning: node-pre-gyp could not find exact match for ' + target_version); + console.log('Warning: but node-pre-gyp successfully choose ' + new_iojs_target + ' as ABI compatible target'); + break; + } + if (minor === 0 && patch === 0) { + break; + } + } + } else if (major >= 2) { + // look for last release that is the same major version + if (major_versions[major]) { + cross_obj = abi_crosswalk[major_versions[major]]; + console.log('Warning: node-pre-gyp could not find exact match for ' + target_version); + console.log('Warning: but node-pre-gyp successfully choose ' + major_versions[major] + ' as ABI compatible target'); + } + } else if (major === 0) { // node.js + if (target_parts[1] % 2 === 0) { // for stable/even node.js series + // look for the last release that is the same minor release + // e.g. we assume node 0.10.x is ABI compatible with >= 0.10.0 + while (--patch > 0) { + const new_node_target = '' + major + '.' + minor + '.' + patch; + if (abi_crosswalk[new_node_target]) { + cross_obj = abi_crosswalk[new_node_target]; + console.log('Warning: node-pre-gyp could not find exact match for ' + target_version); + console.log('Warning: but node-pre-gyp successfully choose ' + new_node_target + ' as ABI compatible target'); + break; + } + } + } + } + } + if (!cross_obj) { + throw new Error('Unsupported target version: ' + target_version); + } + // emulate process.versions + const versions_obj = { + node: target_version, + v8: cross_obj.v8 + '.0', + // abi_crosswalk uses 1 for node versions lacking process.versions.modules + // process.versions.modules added in >= v0.10.4 and v0.11.7 + modules: cross_obj.node_abi > 1 ? cross_obj.node_abi : undefined + }; + return get_node_abi(runtime, versions_obj); + } + } +} +module.exports.get_runtime_abi = get_runtime_abi; + +const required_parameters = [ + 'module_name', + 'module_path', + 'host' +]; + +function validate_config(package_json, opts) { + const msg = package_json.name + ' package.json is not node-pre-gyp ready:\n'; + const missing = []; + if (!package_json.main) { + missing.push('main'); + } + if (!package_json.version) { + missing.push('version'); + } + if (!package_json.name) { + missing.push('name'); + } + if (!package_json.binary) { + missing.push('binary'); + } + const o = package_json.binary; + if (o) { + required_parameters.forEach((p) => { + if (!o[p] || typeof o[p] !== 'string') { + missing.push('binary.' + p); + } + }); + } + + if (missing.length >= 1) { + throw new Error(msg + 'package.json must declare these properties: \n' + missing.join('\n')); + } + if (o) { + // enforce https over http + const protocol = url.parse(o.host).protocol; + if (protocol === 'http:') { + throw new Error("'host' protocol (" + protocol + ") is invalid - only 'https:' is accepted"); + } + } + napi.validate_package_json(package_json, opts); +} + +module.exports.validate_config = validate_config; + +function eval_template(template, opts) { + Object.keys(opts).forEach((key) => { + const pattern = '{' + key + '}'; + while (template.indexOf(pattern) > -1) { + template = template.replace(pattern, opts[key]); + } + }); + return template; +} + +// url.resolve needs single trailing slash +// to behave correctly, otherwise a double slash +// may end up in the url which breaks requests +// and a lacking slash may not lead to proper joining +function fix_slashes(pathname) { + if (pathname.slice(-1) !== '/') { + return pathname + '/'; + } + return pathname; +} + +// remove double slashes +// note: path.normalize will not work because +// it will convert forward to back slashes +function drop_double_slashes(pathname) { + return pathname.replace(/\/\//g, '/'); +} + +function get_process_runtime(versions) { + let runtime = 'node'; + if (versions['node-webkit']) { + runtime = 'node-webkit'; + } else if (versions.electron) { + runtime = 'electron'; + } + return runtime; +} + +module.exports.get_process_runtime = get_process_runtime; + +const default_package_name = '{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz'; +const default_remote_path = ''; + +module.exports.evaluate = function(package_json, options, napi_build_version) { + options = options || {}; + validate_config(package_json, options); // options is a suitable substitute for opts in this case + const v = package_json.version; + const module_version = semver.parse(v); + const runtime = options.runtime || get_process_runtime(process.versions); + const opts = { + name: package_json.name, + configuration: options.debug ? 'Debug' : 'Release', + debug: options.debug, + module_name: package_json.binary.module_name, + version: module_version.version, + prerelease: module_version.prerelease.length ? module_version.prerelease.join('.') : '', + build: module_version.build.length ? module_version.build.join('.') : '', + major: module_version.major, + minor: module_version.minor, + patch: module_version.patch, + runtime: runtime, + node_abi: get_runtime_abi(runtime, options.target), + node_abi_napi: napi.get_napi_version(options.target) ? 'napi' : get_runtime_abi(runtime, options.target), + napi_version: napi.get_napi_version(options.target), // non-zero numeric, undefined if unsupported + napi_build_version: napi_build_version || '', + node_napi_label: napi_build_version ? 'napi-v' + napi_build_version : get_runtime_abi(runtime, options.target), + target: options.target || '', + platform: options.target_platform || process.platform, + target_platform: options.target_platform || process.platform, + arch: options.target_arch || process.arch, + target_arch: options.target_arch || process.arch, + libc: options.target_libc || detect_libc.family || 'unknown', + module_main: package_json.main, + toolset: options.toolset || '', // address https://github.com/mapbox/node-pre-gyp/issues/119 + bucket: package_json.binary.bucket, + region: package_json.binary.region, + s3ForcePathStyle: package_json.binary.s3ForcePathStyle || false + }; + // support host mirror with npm config `--{module_name}_binary_host_mirror` + // e.g.: https://github.com/node-inspector/v8-profiler/blob/master/package.json#L25 + // > npm install v8-profiler --profiler_binary_host_mirror=https://npm.taobao.org/mirrors/node-inspector/ + const validModuleName = opts.module_name.replace('-', '_'); + const host = process.env['npm_config_' + validModuleName + '_binary_host_mirror'] || package_json.binary.host; + opts.host = fix_slashes(eval_template(host, opts)); + opts.module_path = eval_template(package_json.binary.module_path, opts); + // now we resolve the module_path to ensure it is absolute so that binding.gyp variables work predictably + if (options.module_root) { + // resolve relative to known module root: works for pre-binding require + opts.module_path = path.join(options.module_root, opts.module_path); + } else { + // resolve relative to current working directory: works for node-pre-gyp commands + opts.module_path = path.resolve(opts.module_path); + } + opts.module = path.join(opts.module_path, opts.module_name + '.node'); + opts.remote_path = package_json.binary.remote_path ? drop_double_slashes(fix_slashes(eval_template(package_json.binary.remote_path, opts))) : default_remote_path; + const package_name = package_json.binary.package_name ? package_json.binary.package_name : default_package_name; + opts.package_name = eval_template(package_name, opts); + opts.staged_tarball = path.join('build/stage', opts.remote_path, opts.package_name); + opts.hosted_path = url.resolve(opts.host, opts.remote_path); + opts.hosted_tarball = url.resolve(opts.hosted_path, opts.package_name); + return opts; +}; diff --git a/node_modules/@mapbox/node-pre-gyp/package.json b/node_modules/@mapbox/node-pre-gyp/package.json new file mode 100644 index 0000000..baf8e1c --- /dev/null +++ b/node_modules/@mapbox/node-pre-gyp/package.json @@ -0,0 +1,62 @@ +{ + "name": "@mapbox/node-pre-gyp", + "description": "Node.js native addon binary install tool", + "version": "1.0.8", + "keywords": [ + "native", + "addon", + "module", + "c", + "c++", + "bindings", + "binary" + ], + "license": "BSD-3-Clause", + "author": "Dane Springmeyer ", + "repository": { + "type": "git", + "url": "git://github.com/mapbox/node-pre-gyp.git" + }, + "bin": "./bin/node-pre-gyp", + "main": "./lib/node-pre-gyp.js", + "dependencies": { + "detect-libc": "^1.0.3", + "https-proxy-agent": "^5.0.0", + "make-dir": "^3.1.0", + "node-fetch": "^2.6.5", + "nopt": "^5.0.0", + "npmlog": "^5.0.1", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.11" + }, + "devDependencies": { + "@mapbox/cloudfriend": "^5.1.0", + "@mapbox/eslint-config-mapbox": "^3.0.0", + "aws-sdk": "^2.1012.0", + "codecov": "^3.8.3", + "eslint": "^7.32.0", + "eslint-plugin-node": "^11.1.0", + "mock-aws-s3": "^4.0.2", + "nock": "^12.0.3", + "node-addon-api": "^4.2.0", + "nyc": "^15.1.0", + "tape": "^5.3.1", + "tar-fs": "^2.1.1" + }, + "nyc": { + "all": true, + "skip-full": false, + "exclude": [ + "test/**" + ] + }, + "scripts": { + "coverage": "nyc --all --include index.js --include lib/ npm test", + "upload-coverage": "nyc report --reporter json && codecov --clear --flags=unit --file=./coverage/coverage-final.json", + "lint": "eslint bin/node-pre-gyp lib/*js lib/util/*js test/*js scripts/*js", + "fix": "npm run lint -- --fix", + "update-crosswalk": "node scripts/abi_crosswalk.js", + "test": "tape test/*test.js" + } +} 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..6d695d3 --- /dev/null +++ b/node_modules/@types/node/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for Node.js (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Sun, 17 Oct 2021 04:01:18 GMT + * Dependencies: none + * Global values: `AbortController`, `AbortSignal`, `__dirname`, `__filename`, `console`, `exports`, `gc`, `global`, `module`, `process`, `require` + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [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), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [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), [Minh Son Nguyen](https://github.com/nguymin4), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Surasak Chaisurin](https://github.com/Ryan-Willpower), [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), and [wafuwafu13](https://github.com/wafuwafu13). diff --git a/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..9f916c1 --- /dev/null +++ b/node_modules/@types/node/assert.d.ts @@ -0,0 +1,912 @@ +/** + * The `assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/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 `assert` module + * will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + 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. */ + // tslint:disable-next-line:ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is currently experimental and behavior might still change. + * @since v14.2.0, v12.19.0 + * @experimental + */ + 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 '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 that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * 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 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * function foo() {} + * + * // 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() + * 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 of objects containing information about the wrapper functions returned by `calls`. + */ + report(): CallTrackerReportInformation[]; + /** + * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from '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 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 '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, + // tslint:disable-next-line: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 '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 '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 [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison) ( `==` ). `NaN` is special handled + * and treated as being identical in case both sides are `NaN`. + * + * ```js + * import assert from '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 [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison)(`!=` ). `NaN` is special handled and treated as + * being identical in case both + * sides are `NaN`. + * + * ```js + * import assert from '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 'assert'; + * + * const obj1 = { + * a: { + * b: 1 + * } + * }; + * const obj2 = { + * a: { + * b: 2 + * } + * }; + * const obj3 = { + * a: { + * b: 1 + * } + * }; + * const obj4 = Object.create(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 the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * + * ```js + * import assert from '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 the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * + * ```js + * import assert from '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 '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 '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: + * 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: + * 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 '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 '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 '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 '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 '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 '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 '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 '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` 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 `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value' + * } + * ); + * ``` + * + * ```js + * import assert from '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 '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` 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 'assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * ```js + * import assert from '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 '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 `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 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 '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 `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 v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + const strict: Omit & { + (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..b4319b9 --- /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..35b9be2 --- /dev/null +++ b/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,497 @@ +/** + * The `async_hooks` module provides an API to track asynchronous resources. It + * can be accessed using: + * + * ```js + * import async_hooks from 'async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/async_hooks.js) + */ +declare module 'async_hooks' { + /** + * ```js + * import { executionAsyncId } from 'async_hooks'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * 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`. + * @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 'fs'; + * import { executionAsyncId, executionAsyncResource } from '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 '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`. + * @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. + * @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 '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 '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 9.3) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @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 & { + asyncResource: AsyncResource; + }; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>( + fn: Func + ): Func & { + asyncResource: AsyncResource; + }; + /** + * 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 `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 'http'; + * import { AsyncLocalStorage } from '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 data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * 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 or + * the 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 + * 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: (...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..cfcd33e --- /dev/null +++ b/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,2142 @@ +/** + * `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 '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/v16.9.0/lib/buffer.js) + */ +declare module 'buffer' { + import { BinaryLike } from 'node:crypto'; + 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' | 'utf16le' | 'ucs2' | '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 '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 { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * 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 + * @experimental + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.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 + */ + 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 + * @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 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): unknown; // pending web streams types + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + global { + // Buffer class + type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | '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: ReadonlyArray): 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 'buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * 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 | ReadonlyArray): Buffer; + from(data: WithImplicitCoercion | string>): 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 '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 '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 '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 | 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 '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: ReadonlyArray, totalLength?: 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 '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): number; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from '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 '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 | Buffer | 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_INVALID_ARG_VALUE` 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 '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)`, `Buffer.concat()`, and the + * deprecated`new Buffer(size)` constructor only when `size` is less than or equal + * to `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_INVALID_ARG_VALUE` 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 KB 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 '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 '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 '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 '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 '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 '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 '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): number; + /** + * 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 '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 '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 is the same behavior as `buf.subarray()`. + * + * 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 '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 + * ``` + * @since v0.3.0 + * @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 '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 '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 '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 '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 '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; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from '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; + /** + * 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 '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; + /** + * 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 '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; + /** + * 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 '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 '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 '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; + /** + * 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 '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; + /** + * 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 '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; + /** + * 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 '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; + /** + * 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 '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 '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 '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; + /** + * 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 '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; + /** + * 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 '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; + /** + * 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 '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; + /** + * 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 '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; + /** + * 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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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; + /** + * 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 '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; + /** + * 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 '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; + /** + * 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 '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; + /** + * 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 '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; + /** + * 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 '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 '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 '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 '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 '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 '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 '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 '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 '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 'buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * ``` + * + * `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 '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 '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`. + * @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.slice()`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from '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 '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 '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 '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 '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 '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 '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 '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 + * @deprecated 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 + * @deprecated Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + } +} +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..0851f51 --- /dev/null +++ b/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1365 @@ +/** + * The `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('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 it is in the `options` object. Otherwise, `process.env.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 `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/v16.9.0/lib/child_process.js) + */ +declare module 'child_process' { + import { ObjectEncodingOptions } from 'node:fs'; + import { EventEmitter, Abortable } from 'node:events'; + import * as net from 'node:net'; + import { Writable, Readable, Stream, Pipe } from 'node:stream'; + import { URL } from 'node:url'; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server; + /** + * 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 `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('child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` 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` 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 currently 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('assert'); + * const fs = require('fs'); + * const child_process = require('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('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('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('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; + /** + * 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('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. + * + * 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('child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('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 `net` module, `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, currently 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('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('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 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('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('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 true + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + 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 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('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('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('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 currently 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('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?: ReadonlyArray, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | 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; + } + /** + * 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('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('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('util'); + * const exec = util.promisify(require('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('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.log(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 = ExecException & NodeJS.ErrnoException; + /** + * 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('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('util'); + * const execFile = util.promisify(require('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('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.log(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?: ReadonlyArray | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray | 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: ReadonlyArray | 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: ReadonlyArray | 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: ReadonlyArray | 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: ReadonlyArray | 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: ReadonlyArray | 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: ReadonlyArray | 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: ReadonlyArray | undefined | null + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | 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: ReadonlyArray | 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: ReadonlyArray | 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: ReadonlyArray | 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: ReadonlyArray | 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; + 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('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?: ReadonlyArray, 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: ReadonlyArray): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + 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: ReadonlyArray): Buffer; + function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, args?: ReadonlyArray, 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..7f16141 --- /dev/null +++ b/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,414 @@ +/** + * A single instance of Node.js runs in a single thread. To take advantage of + * multi-core systems, the user will sometimes want to launch a cluster of Node.js + * processes to handle the load. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * 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/v16.9.0/lib/cluster.js) + */ +declare module 'cluster' { + import * as child from 'node:child_process'; + import EventEmitter = require('node:events'); + import * as net from 'node:net'; + export interface ClusterSettings { + execArgv?: string[] | undefined; // default: process.execArgv + exec?: string | undefined; + args?: string[] | undefined; + silent?: boolean | undefined; + stdio?: any[] | undefined; + uid?: number | undefined; + gid?: number | undefined; + inspectPort?: number | (() => number) | undefined; + } + export interface Address { + address: string; + port: number; + addressType: number | 'udp4' | 'udp6'; // 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()`, the returned object + * from this function is stored as `.process`. In a worker, the global `process`is stored. + * + * See: `Child Process module`. + * + * 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()`. + * + * 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. `options` supports the following properties: + */ + 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, it does this + * by disconnecting the `worker.process`, and once disconnected, killing + * with `signal`. In the worker, it does it by disconnecting the channel, + * and then exiting with code `0`. + * + * Because `kill()` attempts to gracefully disconnect the worker process, it is + * susceptible to waiting indefinitely for the disconnect to complete. For example, + * if the worker enters an infinite loop, a graceful disconnect will never occur. + * If the graceful disconnect behavior is not needed, use `worker.process.kill()`. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * This method is aliased as `worker.destroy()` for backward compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is `kill()`. + * @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('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 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * 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 `.kill()` or`.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; + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + readonly isPrimary: boolean; + readonly isWorker: boolean; + schedulingPolicy: number; + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use setupPrimary. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. + */ + setupPrimary(settings?: ClusterSettings): void; + readonly worker?: Worker | undefined; + 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..ede7a53 --- /dev/null +++ b/node_modules/@types/node/console.d.ts @@ -0,0 +1,412 @@ +/** + * 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` and `process.stderr`. 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` 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/v16.9.0/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()`. + * + * 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 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 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()` 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()`). + * + * ```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()` is called on each argument and the resulting string + * values are concatenated. See `util.format()` 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()`). + * + * ```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()` 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?: ReadonlyArray): 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 + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('100-elements'); + * for (let i = 0; i < 100; i++) {} + * console.timeEnd('100-elements'); + * // prints 100-elements: 225.438ms + * ``` + * @since v0.1.104 + */ + 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 + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` 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. + * Starts a JavaScript CPU profile with an optional label. + */ + 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. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + 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` and `process.stderr`. 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` 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/v16.4.2/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + ignoreErrors?: boolean | undefined; + colorMode?: boolean | 'auto' | undefined; + 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..208020d --- /dev/null +++ b/node_modules/@types/node/constants.d.ts @@ -0,0 +1,18 @@ +/** @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..a896ae7 --- /dev/null +++ b/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,3307 @@ +/** + * The `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('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/v16.9.0/lib/crypto.js) + */ +declare module 'crypto' { + import * as stream from 'node:stream'; + import { PeerCertificate } from 'node:tls'; + interface Certificate { + /** + * @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; + } + const Certificate: Certificate & { + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + new (): Certificate; + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + (): Certificate; + /** + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @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; + /** + * @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-v10.x/docs/api/crypto.html#crypto_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; + /** 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 "speshul" version 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; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: 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 ALPN_ENABLED: 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`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHash + * } = await import('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`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) 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`. + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHmac + * } = await import('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'; + type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | '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('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 'fs'; + * import { stdout } from 'process'; + * const { createHash } = await import('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('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('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?: stream.TransformOptions): 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('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 'fs'; + * import { stdout } from 'process'; + * const { + * createHmac + * } = await import('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('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + 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; + } + interface JwkKeyExportOptions { + format: 'jwk'; + } + /** + * 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 { webcrypto, KeyObject } = await import('crypto'); + * const { subtle } = webcrypto; + * + * 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; + /** + * 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 BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + /** + * 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 is used (e.g. `'aes-128-ccm'`). 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. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) 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`. + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/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/man1.1.0/crypto/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 is used (e.g. `'aes-128-ccm'`). 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. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) 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 | null, options: CipherCCMOptions): CipherCCM; + function createCipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, 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('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 'fs'; + * + * import { + * pipeline + * } from 'stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('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('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; + } + /** + * 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 is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/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/man1.1.0/crypto/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 is used (e.g. `'aes-128-ccm'`). 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. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) 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 | null, options: CipherCCMOptions): DecipherCCM; + function createDecipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, 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 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('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', () => { + * 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 'fs'; + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('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 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('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 PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'pkcs8' | 'sec1' | undefined; + passphrase?: string | Buffer | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'spki' | 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('crypto'); + * + * generateKey('hmac', { length: 64 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * @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('crypto'); + * + * const key = generateKeySync('hmac', { length: 64 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * @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; + } + 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('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('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, signature: NodeJS.ArrayBufferView): boolean; + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, 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 | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: number | 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 'assert'; + * + * const { + * createDiffieHellman + * } = await import('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, 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. + * @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): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, 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`. + * @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 `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; + } + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, + * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). 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('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): DiffieHellman; + /** + * 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. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * 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('crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been + * deprecated and use should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey); // '3745e48...aa39b34' + * }); + * ``` + * + * 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`. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * 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('crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use + * should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); + * console.log(key); // '3745e48...aa39b34' + * ``` + * + * 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('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('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 248. `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('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('crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt + * } = await import('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 'buffer'; + * const { randomFillSync } = await import('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 'buffer'; + * const { randomFillSync } = await import('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 'buffer'; + * const { randomFill } = await import('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 'buffer'; + * const { randomFill } = await import('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('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('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('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('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; + /** + * ```js + * const { + * getHashes + * } = await import('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 'assert'; + * + * const { + * createECDH + * } = await import('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('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(): 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 is based on a constant-time algorithm. + * Returns true if `a` is equal to `b`, without leaking 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. + * + * 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. + * + * 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; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: BufferEncoding; + type KeyType = 'rsa' | 'rsa-pss' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; + type KeyFormat = 'pem' | 'der'; + 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; + } + 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 { + /** + * Name of the curve to use. + */ + namedCurve: string; + 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('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('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, signature: NodeJS.ArrayBufferView): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + 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; + 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 'buffer'; + * const { + * hkdf + * } = await import('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. It must be at least one byte in 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 'buffer'; + * const { + * hkdfSync + * } = await import('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. It must be at least one byte in 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; + } + /** + * 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 + */ + function randomUUID(options?: RandomUUIDOptions): string; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject: 'always' | '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('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. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * @since v15.6.0 + */ + readonly subjectAltName: string; + /** + * The information access content of this certificate. + * @since v15.6.0 + */ + readonly infoAccess: string; + /** + * 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. + * @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. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * @since v15.6.0 + * @return Returns `name` if the certificate matches, `undefined` if it does not. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string, options?: X509CheckOptions): 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; + namespace webcrypto { + class CryptoKey {} // placeholder + } +} +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..d7b9ee2 --- /dev/null +++ b/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,545 @@ +/** + * The `dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`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/v16.9.0/lib/dgram.js) + */ +declare module 'dgram' { + import { AddressInfo } from 'node:net'; + import * as dns from 'node:dns'; + import { EventEmitter, Abortable } 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 'cluster'; + * import dgram from '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 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`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; + /** + * 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 falsy, `'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 'dgram'; + * import { Buffer } from '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 'dgram'; + * import { Buffer } from '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 'dgram'; + * import { Buffer } from '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 | ReadonlyArray, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, 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 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 addition 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; + } +} +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..d6747da --- /dev/null +++ b/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,134 @@ +/** + * The `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 '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. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/diagnostics_channel.js) + */ +declare module 'diagnostics_channel' { + /** + * 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 '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): boolean; + /** + * This is the primary entry-point for anyone wanting to interact with 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 '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): Channel; + type ChannelListener = (name: string, message: unknown) => void; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is use 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; + /** + * 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 '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); + /** + * 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 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @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 '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 + * @param onMessage The previous subscribed handler to remove + */ + unsubscribe(onMessage: ChannelListener): 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..11af817 --- /dev/null +++ b/node_modules/@types/node/dns.d.ts @@ -0,0 +1,643 @@ +/** + * The `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('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 `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('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` for more information. + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/dns.js) + */ +declare module 'dns' { + import * as dnsPromises from 'node:dns/promises'; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + 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 { + family?: number | undefined; + hints?: number | undefined; + all?: boolean | undefined; + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + address: string; + 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 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` before using`dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('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()` 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` object, where `err.code` is the error code. + * + * ```js + * const dns = require('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()` 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 { + critial: 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` 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 a 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 + */ + 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` object, where `err.code` is + * one of the `DNS error codes`. + * @since v0.1.16 + */ + export function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; + /** + * 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` formatted addresses + */ + export function setServers(servers: ReadonlyArray): 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[]; + // Error codes + export const NODATA: string; + export const FORMERR: string; + export const SERVFAIL: string; + export const NOTFOUND: string; + export const NOTIMP: string; + export const REFUSED: string; + export const BADQUERY: string; + export const BADNAME: string; + export const BADFAMILY: string; + export const BADRESP: string; + export const CONNREFUSED: string; + export const TIMEOUT: string; + export const EOF: string; + export const FILE: string; + export const NOMEM: string; + export const DESTRUCTION: string; + export const BADSTR: string; + export const BADFLAGS: string; + export const NONAME: string; + export const BADHINTS: string; + export const NOTINITIALIZED: string; + export const LOADIPHLPAPI: string; + export const ADDRGETNETWORKPARAMS: string; + export const CANCELLED: string; + export interface ResolverOptions { + timeout?: number | undefined; + /** + * @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()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('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 `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; + 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 + * @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..fbfe1db --- /dev/null +++ b/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,357 @@ +/** + * 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('dns').promises` or `require('dns/promises')`. + * @since v10.6.0 + */ +declare module 'dns/promises' { + import { + LookupAddress, + LookupOneOptions, + LookupAllOptions, + LookupOptions, + AnyRecord, + CaaRecord, + MxRecord, + NaptrRecord, + SoaRecord, + SrvRecord, + ResolveWithTtlOptions, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + } 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` 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()` 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` before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('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` object, where `err.code`is the error code. + * + * ```js + * const dnsPromises = require('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` object, where `err.code`is one of the `DNS 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 + */ + 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` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * 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: ReadonlyArray): void; + class Resolver { + constructor(options?: ResolverOptions); + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + 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; + 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/domain.d.ts b/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..383e385 --- /dev/null +++ b/node_modules/@types/node/domain.d.ts @@ -0,0 +1,169 @@ +/** + * **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/v16.9.0/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 lowlevel 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('domain'); + * const fs = require('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..a1ed5ab --- /dev/null +++ b/node_modules/@types/node/events.d.ts @@ -0,0 +1,623 @@ +/** + * 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 + * const EventEmitter = require('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/v16.9.0/lib/events.js) + */ +declare module 'events' { + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + interface DOMEventTarget { + addEventListener( + eventName: string, + listener: (...args: any[]) => void, + opts?: { + once: boolean; + } + ): any; + } + interface StaticEventEmitterOptions { + signal?: AbortSignal | undefined; + } + interface EventEmitter extends NodeJS.EventEmitter {} + /** + * The `EventEmitter` class is defined and exposed by the `events` module: + * + * ```js + * const EventEmitter = require('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 { + constructor(options?: EventEmitterOptions); + /** + * 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 + * const { once, EventEmitter } = require('events'); + * + * async function run() { + * 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.log('error happened', err); + * } + * } + * + * run(); + * ``` + * + * 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 + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.log('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * const { EventEmitter, once } = require('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: NodeEventTarget, eventName: string | symbol, options?: StaticEventEmitterOptions): Promise; + static once(emitter: DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * const { on, EventEmitter } = require('events'); + * + * (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')) { + * // 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 + * const { on, EventEmitter } = require('events'); + * 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 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 + * const { EventEmitter, listenerCount } = require('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 + * const { getEventListeners, EventEmitter } = require('events'); + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * getEventListeners(ee, 'foo'); // [listener] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * getEventListeners(et, 'foo'); // [listener] + * } + * ``` + * @since v15.2.0 + */ + static getEventListeners(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * 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. + */ + static readonly errorMonitor: unique symbol; + static readonly captureRejectionSymbol: unique symbol; + /** + * Sets or gets the default captureRejection value for all emitters. + */ + // TODO: These should be described using static getter/setter pairs: + static captureRejections: boolean; + 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; + } + } + global { + namespace NodeJS { + interface EventEmitter { + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: string | symbol, listener: (...args: any[]) => void): 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 + * 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: string | symbol, listener: (...args: any[]) => void): 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 + * 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: string | symbol, listener: (...args: any[]) => void): 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 + * 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 + * 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: string | symbol, listener: (...args: any[]) => void): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: string | symbol, listener: (...args: any[]) => void): 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(event?: string | symbol): 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: string | symbol): Function[]; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * 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: string | symbol): Function[]; + /** + * 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 + * const EventEmitter = require('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: string | symbol, ...args: any[]): boolean; + /** + * Returns the number of listeners listening to the event named `eventName`. + * @since v3.2.0 + * @param eventName The name of the event being listened for + */ + listenerCount(eventName: string | symbol): 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: string | symbol, listener: (...args: any[]) => void): 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: string | symbol, listener: (...args: any[]) => void): 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 + * const EventEmitter = require('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; + } + } + } + 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..0a1cd5a --- /dev/null +++ b/node_modules/@types/node/fs.d.ts @@ -0,0 +1,3748 @@ +/** + * The `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 'fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from '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/v16.9.0/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} and {@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`. + * + * ```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 {} + /** + * 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; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from '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 resolved 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 resolved 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; + } + 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; + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'close', listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'close', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'close', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'close', listener: () => 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(): 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(): 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 '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 '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 '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 '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`. + * + * 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 '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; + } + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + 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; + } + /** + * 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 set, 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. + * + * Relative targets are relative to the link’s parent directory. + * + * ```js + * import { symlink } from 'fs'; + * + * symlink('./mew', './example/mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` in the `example` which points + * to `mew` in the same directory: + * + * ```bash + * $ tree example/ + * example/ + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + */ + 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 + */ + 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 '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 soperations 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. + * + * 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. + * + * ```js + * import { mkdir } from 'fs'; + * + * // Creates /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 '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 'fs'; + * + * mkdtemp(path.join(os.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('path').sep`). + * + * ```js + * import { tmpdir } from 'os'; + * import { mkdtemp } from '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 '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; + } + | 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; + } + | '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; + }) + | 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; + }, + 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; + } + | 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; + } + ): 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; + }) + | 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; + } + ): 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; + } + | 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; + } + | '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; + }) + | 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; + } + ): 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, 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. + */ + export function open(path: PathLike, flags: OpenMode, 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`. If `buffer` is a normal object, it + * must have an own `toString` function property. + * + * `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 + */ + 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; + }>; + } + /** + * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @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; + /** + * 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; + 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; + }>; + } + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + */ + 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 '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 '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 '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 '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 '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; + }) + | 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. + * + * If `data` is a plain object, it must have an own (not inherited) `toString`function property. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from '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 '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 'fs'; + * import { Buffer } from '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`. + * + * If `data` is a plain object, it must have an own (not inherited) `toString`function property. + * + * 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 '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 '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 '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 '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 '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 '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 function watchFile( + filename: PathLike, + options: + | { + persistent?: boolean | undefined; + interval?: number | undefined; + } + | undefined, + listener: (curr: Stats, prev: Stats) => void + ): void; + /** + * 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: (curr: Stats, prev: Stats) => void): void; + /** + * 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?: (curr: Stats, prev: Stats) => void): 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) => 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 '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 '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 '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 '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 '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 '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. Check `File access constants` for possible values + * of `mode`. It is possible to create a mask consisting of the bitwise OR of + * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * 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 '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 exists in the current directory, and if it is writable. + * access(file, constants.F_OK | constants.W_OK, (err) => { + * if (err) { + * console.error( + * `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`); + * } else { + * console.log(`${file} exists, and it is 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 '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 '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 '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 '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. Check `File access constants` for + * possible values of `mode`. It is possible to create a mask consisting of + * the bitwise OR of two or more values + * (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from '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; + /** + * @default false + */ + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + } + interface ReadStreamOptions extends StreamOptions { + end?: number | undefined; + } + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `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 '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 '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 | StreamOptions): 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 '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 '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 + */ + export function writev(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function writev( + fd: number, + buffers: ReadonlyArray, + 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: ReadonlyArray, position?: number): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: ReadonlyArray, 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 + */ + export function readv(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function readv( + fd: number, + buffers: ReadonlyArray, + 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: ReadonlyArray, 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 + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: ReadonlyArray, position?: number): number; + export interface OpenDirOptions { + 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; + } + /** + * 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; + } + export interface CopyOptions { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): 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; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: 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, destination: string, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function cp(source: string, destination: string, 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, destination: string, opts?: CopyOptions): 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..f2e981d --- /dev/null +++ b/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1091 @@ +/** + * 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 { + Stats, + BigIntStats, + StatOptions, + WriteVResult, + ReadVResult, + PathLike, + RmDirOptions, + RmOptions, + MakeDirectoryOptions, + Dirent, + OpenDirOptions, + Dir, + ObjectEncodingOptions, + BufferEncodingOption, + OpenMode, + Mode, + WatchOptions, + WatchEventType, + CopyOptions, + ReadStream, + WriteStream, + } from 'node:fs'; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T; + } + 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; + } + // 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) | 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 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `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 '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 '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 Fufills 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>; + /** + * 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; + /** + * @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 '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 resolves the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: string | number | Date, mtime: string | number | Date): 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 + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object, or an + * object with an own `toString` function + * property. The promise is resolved 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 resolved (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) | BufferEncoding | null): Promise; + /** + * Write `buffer` to the file. + * + * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. + * + * The promise is resolved 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 resolved (or rejected). For this + * scenario, use `fs.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=0] The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength] The number of bytes from `buffer` to write. + * @param position 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 resolved 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 resolved (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 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: ReadonlyArray, 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 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: ReadonlyArray, position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from '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; + } + /** + * 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. Check `File access constants` for possible values + * of `mode`. It is possible to create a mask consisting of the bitwise OR of + * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * If the accessibility check is successful, the promise is resolved 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 } from 'fs/promises'; + * import { constants } from 'fs'; + * + * 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 { constants } from 'fs'; + * import { copyFile } from 'fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('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.log('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. + * @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 resolved array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from '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; + }) + | 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; + } + | '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; + }) + | 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; + } + ): 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 + * resolved 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'`. Windows junction points require the destination path + * to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. + * @since v10.0.0 + * @param [type='file'] + * @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; + /** + * 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: string | number | Date, mtime: string | number | Date): 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: string | number | Date, mtime: string | number | Date): 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 'fs/promises'; + * + * try { + * await mkdtemp(path.join(os.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('path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the filesystem 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`, or, an object with an own (not inherited)`toString` function property. + * + * 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()`. + * + * 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 'fs/promises'; + * import { Buffer } from '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; + } & 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) | 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. + * + * 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 '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 '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('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 + * @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, destination: string, 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..ae974db --- /dev/null +++ b/node_modules/@types/node/globals.d.ts @@ -0,0 +1,284 @@ +// 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 { } + +declare var process: NodeJS.Process; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare var require: NodeRequire; +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +/** + * Only available if `--expose-gc` is passed to the process. + */ +declare 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(): 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 { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; + // TODO: Add abort() static +}; +//#endregion borrowed + +//#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 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 + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare 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 | null; + + /** + * 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; + } + + 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): void; + end(data: string | Uint8Array, cb?: () => void): void; + end(str: string, encoding?: BufferEncoding, cb?: () => void): void; + } + + 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 14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since 11.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; + } +} 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..9081954 --- /dev/null +++ b/node_modules/@types/node/http.d.ts @@ -0,0 +1,1368 @@ +/** + * To use the HTTP server and client one must `require('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: + * + * ```js + * { 'content-length': '123', + * 'content-type': 'text/plain', + * 'connection': 'keep-alive', + * 'host': 'mysite.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', 'mysite.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/http.js) + */ +declare module 'http' { + import * as stream from 'node:stream'; + import { URL } from 'node:url'; + import { Socket, Server as NetServer } 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 {} + interface ClientRequestArgs { + abort?: AbortSignal | undefined; + protocol?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + family?: number | undefined; + port?: number | string | null | undefined; + defaultPort?: number | string | undefined; + localAddress?: string | undefined; + socketPath?: string | undefined; + /** + * @default 8192 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + headers?: OutgoingHttpHeaders | undefined; + auth?: string | null | undefined; + agent?: Agent | boolean | undefined; + _defaultAgent?: Agent | undefined; + timeout?: number | undefined; + setHost?: boolean | undefined; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) | undefined; + } + interface ServerOptions { + IncomingMessage?: typeof IncomingMessage | undefined; + ServerResponse?: typeof ServerResponse | 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 8192 + */ + maxHeaderSize?: 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; + } + type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; + /** + * @since v0.1.17 + */ + class Server 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. + * + * In case of inactivity, the rules defined in `server.timeout` apply. However, + * that inactivity based timeout would still allow the connection to be kept open + * if the headers are being sent very slowly (by default, up to a byte per 2 + * minutes). In order to prevent this, whenever header data arrives an additional + * check is made that more than `server.headersTimeout` milliseconds has not + * passed since the connection was established. If the check fails, a `'timeout'`event is emitted on the server object, and (by default) the socket is destroyed. + * See `server.timeout` for more information on how timeout behavior can be + * customized. + * @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; + 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: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: RequestListener): this; + addListener(event: 'upgrade', listener: (req: IncomingMessage, 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: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'checkExpectation', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean; + emit(event: 'connect', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + emit(event: 'request', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'upgrade', req: IncomingMessage, 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: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'request', listener: RequestListener): this; + on(event: 'upgrade', listener: (req: IncomingMessage, 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: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once(event: 'request', listener: RequestListener): this; + once(event: 'upgrade', listener: (req: IncomingMessage, 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: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: RequestListener): this; + prependListener(event: 'upgrade', listener: (req: IncomingMessage, 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: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from + * the perspective of the participants of HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: IncomingMessage; + 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; + /** + * Aliases of `outgoingMessage.socket` + * @since v0.3.0 + * @deprecated Since v15.12.0 - 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 for the header object. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | ReadonlyArray): this; + /** + * Gets the value of HTTP header with the given name. If such a name doesn't + * exist in message, it 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 v8.0.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array of names of headers of the outgoing outgoingMessage. All + * names are lowercase. + * @since v8.0.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 v8.0.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers are **only** be emitted if the message is chunked encoded. If not, + * the trailer will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header fields 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; + /** + * Compulsorily 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 request. + * @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; + constructor(req: IncomingMessage); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends a 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 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 given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * does not 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 `TypeError` 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. + * + * Node.js does not check whether Content-Length and the length of the + * body which has been transmitted are equal or not. + * @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 + */ + 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; + 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 + */ + getRawHeaderNames(): string[]; + 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; + 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; + 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; + 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; + 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 + */ + 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`. + * @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. + * * `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; + /** + * 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; + /** + * 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(request.url, `http://${request.headers.host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and`request.headers.host` is `'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.headers.host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @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): void; + } + interface AgentOptions { + /** + * 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 + * }); + * ``` + * @since v0.3.4 + */ + class Agent { + /** + * 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. + * @since v0.1.13 + */ + function createServer(requestListener?: RequestListener): Server; + function createServer(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 {} + /** + * 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 + * const http = require('http'); + * + * 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 + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'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'` + * * `'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'` + * * `'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 + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'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 itself. + * @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 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` always set to `GET`. Properties that are inherited from the prototype are ignored. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + 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..3aa9497 --- /dev/null +++ b/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2100 @@ +/** + * The `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('http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/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, OutgoingHttpHeaders, IncomingMessage, 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 { + 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 the `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; + /** + * 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('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('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('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('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * 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('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('http2'); + * const fs = require('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('http2'); + * const fs = require('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('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.log(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('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('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; + } + 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('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 + */ + 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): 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. + * + * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('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: ReadonlyArray): 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('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('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('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; + /** + * 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; + createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; + } + 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: ReadonlyArray); + /** + * 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 + */ + readonly 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; + /** + * 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('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): void; + end(data: string | Uint8Array, callback?: () => void): void; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): void; + /** + * 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 | ReadonlyArray): 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 `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 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_ORIGIN: 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('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('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(80); + * ``` + * @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('http2'); + * const fs = require('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(80); + * ``` + * @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('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; +} +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..194a3ad --- /dev/null +++ b/node_modules/@types/node/https.d.ts @@ -0,0 +1,391 @@ +/** + * 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/v16.9.0/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 = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = http.RequestOptions & + tls.SecureContextOptions & { + 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 extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor(options: ServerOptions, requestListener?: http.RequestListener); + 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: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: http.RequestListener): this; + addListener(event: 'upgrade', listener: (req: http.IncomingMessage, 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: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'checkExpectation', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: Duplex): boolean; + emit(event: 'connect', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + emit(event: 'request', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'upgrade', req: http.IncomingMessage, 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: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + on(event: 'request', listener: http.RequestListener): this; + on(event: 'upgrade', listener: (req: http.IncomingMessage, 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: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: 'request', listener: http.RequestListener): this; + once(event: 'upgrade', listener: (req: http.IncomingMessage, 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: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: http.RequestListener): this; + prependListener(event: 'upgrade', listener: (req: http.IncomingMessage, 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: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: http.RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('https'); + * const fs = require('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('https'); + * const fs = require('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(requestListener?: http.RequestListener): Server; + function createServer(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('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('tls'); + * const https = require('https'); + * const crypto = require('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-sha25 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('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..4ff0a92 --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,131 @@ +// Type definitions for non-npm package Node.js 16.11 +// Project: https://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Chigozirim C. +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Hannes Magnusson +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Samuel Ainsworth +// Kyle Uehlein +// Thanik Bhongbhibhat +// Marcin Kopacz +// Trivikram Kamat +// Minh Son Nguyen +// Junxiao Shi +// Ilia Baryshnikov +// ExE Boss +// Surasak Chaisurin +// Piotr Błażejewicz +// Anna Henningsen +// Victor Perin +// Yongsheng Zhang +// NodeJS Contributors +// Linus Unnebäck +// wafuwafu13 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * 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 3.7+. + +// 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..5e84a1a --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2745 @@ +// tslint:disable-next-line:dt-header +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +// tslint:disable:max-line-length + +/** + * The `inspector` module provides an API for interacting with the V8 inspector. + * + * It can be accessed using: + * + * ```js + * const inspector = require('inspector'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/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; + /** + * 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; + /** + * Connects a session to the main thread inspector back-end. + * An exception will be thrown if this API was not called on a Worker + * thread. + * @since 12.11.0 + */ + connectToMainThread(): 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. + */ + function open(port?: number, host?: string, wait?: boolean): void; + /** + * 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; +} +declare module 'node:inspector' { + import EventEmitter = require('inspector'); + export = EventEmitter; +} diff --git a/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..d83aec9 --- /dev/null +++ b/node_modules/@types/node/module.d.ts @@ -0,0 +1,114 @@ +/** + * @since v0.3.7 + */ +declare module 'module' { + import { URL } from 'node:url'; + 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('fs'); + * const assert = require('assert'); + * const { syncBuiltinESMExports } = require('module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('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 + */ + 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; + } + /** + * @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 number and column number in the generated source file, returns + * an object representing the position in the original file. The object returned + * consists of the following keys: + */ + findEntry(line: number, column: number): SourceMapping; + } + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static Module: typeof Module; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + url: string; + /** + * @experimental + * This feature is only available with the `--experimental-import-meta-resolve` + * command flag enabled. + * + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * @param specified The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. If none + * is specified, the value of `import.meta.url` is used as the default. + */ + resolve?(specified: string, parent?: string | URL): Promise; + } + } + 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..331cd55 --- /dev/null +++ b/node_modules/@types/node/net.d.ts @@ -0,0 +1,783 @@ +/** + * > Stability: 2 - Stable + * + * The `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('net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/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.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, 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; + } + 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; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + /** + * 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); + /** + * 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; + /** + * 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 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; + /** + * 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 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'`. + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. + * @since v0.5.10 + */ + readonly remotePort?: 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): void; + end(buffer: Uint8Array | string, callback?: () => void): void; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. 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: '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: '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: '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: '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: '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: '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; + } + /** + * 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.log('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 + */ + listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + 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; + 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; + 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; + 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; + 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; + 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; + } + 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 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.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 + * @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 + * @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 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + } + 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 an TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('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`: + * + * ```console + * $ 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: + * + * ```console + * $ 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; + /** + * Tests if input is an IP address. Returns `0` for invalid strings, + * returns `4` for IP version 4 addresses, and returns `6` for IP version 6 + * addresses. + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if input is a version 4 IP address, otherwise returns `false`. + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if input is a version 6 IP address, otherwise 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 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0 + */ + readonly port: number; + /** + * @since v15.14.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..f9cd242 --- /dev/null +++ b/node_modules/@types/node/os.d.ts @@ -0,0 +1,455 @@ +/** + * The `os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/os.js) + */ +declare module 'os' { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: 'IPv4'; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: 'IPv6'; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T; + 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 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. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * 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` 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 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; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. + * + * The return value is equivalent to `process.arch`. + * @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. 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 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..58c4d28 --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,230 @@ +{ + "name": "@types/node", + "version": "16.11.1", + "description": "TypeScript definitions for Node.js", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "url": "https://github.com/Microsoft", + "githubUsername": "Microsoft" + }, + { + "name": "DefinitelyTyped", + "url": "https://github.com/DefinitelyTyped", + "githubUsername": "DefinitelyTyped" + }, + { + "name": "Alberto Schiabel", + "url": "https://github.com/jkomyno", + "githubUsername": "jkomyno" + }, + { + "name": "Alvis HT Tang", + "url": "https://github.com/alvis", + "githubUsername": "alvis" + }, + { + "name": "Andrew Makarov", + "url": "https://github.com/r3nya", + "githubUsername": "r3nya" + }, + { + "name": "Benjamin Toueg", + "url": "https://github.com/btoueg", + "githubUsername": "btoueg" + }, + { + "name": "Chigozirim C.", + "url": "https://github.com/smac89", + "githubUsername": "smac89" + }, + { + "name": "David Junger", + "url": "https://github.com/touffy", + "githubUsername": "touffy" + }, + { + "name": "Deividas Bakanas", + "url": "https://github.com/DeividasBakanas", + "githubUsername": "DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "url": "https://github.com/eyqs", + "githubUsername": "eyqs" + }, + { + "name": "Hannes Magnusson", + "url": "https://github.com/Hannes-Magnusson-CK", + "githubUsername": "Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "url": "https://github.com/hoo29", + "githubUsername": "hoo29" + }, + { + "name": "Kelvin Jin", + "url": "https://github.com/kjin", + "githubUsername": "kjin" + }, + { + "name": "Klaus Meinhardt", + "url": "https://github.com/ajafff", + "githubUsername": "ajafff" + }, + { + "name": "Lishude", + "url": "https://github.com/islishude", + "githubUsername": "islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "url": "https://github.com/mwiktorczyk", + "githubUsername": "mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "url": "https://github.com/mohsen1", + "githubUsername": "mohsen1" + }, + { + "name": "Nicolas Even", + "url": "https://github.com/n-e", + "githubUsername": "n-e" + }, + { + "name": "Nikita Galkin", + "url": "https://github.com/galkin", + "githubUsername": "galkin" + }, + { + "name": "Parambir Singh", + "url": "https://github.com/parambirs", + "githubUsername": "parambirs" + }, + { + "name": "Sebastian Silbermann", + "url": "https://github.com/eps1lon", + "githubUsername": "eps1lon" + }, + { + "name": "Simon Schick", + "url": "https://github.com/SimonSchick", + "githubUsername": "SimonSchick" + }, + { + "name": "Thomas den Hollander", + "url": "https://github.com/ThomasdenH", + "githubUsername": "ThomasdenH" + }, + { + "name": "Wilco Bakker", + "url": "https://github.com/WilcoBakker", + "githubUsername": "WilcoBakker" + }, + { + "name": "wwwy3y3", + "url": "https://github.com/wwwy3y3", + "githubUsername": "wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "url": "https://github.com/samuela", + "githubUsername": "samuela" + }, + { + "name": "Kyle Uehlein", + "url": "https://github.com/kuehlein", + "githubUsername": "kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "url": "https://github.com/bhongy", + "githubUsername": "bhongy" + }, + { + "name": "Marcin Kopacz", + "url": "https://github.com/chyzwar", + "githubUsername": "chyzwar" + }, + { + "name": "Trivikram Kamat", + "url": "https://github.com/trivikr", + "githubUsername": "trivikr" + }, + { + "name": "Minh Son Nguyen", + "url": "https://github.com/nguymin4", + "githubUsername": "nguymin4" + }, + { + "name": "Junxiao Shi", + "url": "https://github.com/yoursunny", + "githubUsername": "yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "url": "https://github.com/qwelias", + "githubUsername": "qwelias" + }, + { + "name": "ExE Boss", + "url": "https://github.com/ExE-Boss", + "githubUsername": "ExE-Boss" + }, + { + "name": "Surasak Chaisurin", + "url": "https://github.com/Ryan-Willpower", + "githubUsername": "Ryan-Willpower" + }, + { + "name": "Piotr Błażejewicz", + "url": "https://github.com/peterblazejewicz", + "githubUsername": "peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "url": "https://github.com/addaleax", + "githubUsername": "addaleax" + }, + { + "name": "Victor Perin", + "url": "https://github.com/victorperin", + "githubUsername": "victorperin" + }, + { + "name": "Yongsheng Zhang", + "url": "https://github.com/ZYSzys", + "githubUsername": "ZYSzys" + }, + { + "name": "NodeJS Contributors", + "url": "https://github.com/NodeJS", + "githubUsername": "NodeJS" + }, + { + "name": "Linus Unnebäck", + "url": "https://github.com/LinusU", + "githubUsername": "LinusU" + }, + { + "name": "wafuwafu13", + "url": "https://github.com/wafuwafu13", + "githubUsername": "wafuwafu13" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "ff17ac1347ef82ac3f00b3e6266533bf928948b2bdb61a2c5dfe7751c2b729f9", + "typeScriptVersion": "3.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..a58c0aa --- /dev/null +++ b/node_modules/@types/node/path.d.ts @@ -0,0 +1,172 @@ +declare module 'path/posix' { + import path = require('path'); + export = path; +} +declare module 'path/win32' { + import path = require('path'); + export = path; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * const path = require('path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/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 p string path to normalize. + */ + normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + 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 pathSegments string paths to join. Non-string arguments are ignored. + */ + resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + isAbsolute(p: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * 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. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + dirname(p: 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 p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + basename(p: string, ext?: 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 p the path to evaluate. + */ + extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + parse(p: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + format(pP: 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; +} 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..0e4b48f --- /dev/null +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,555 @@ +/** + * 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/) + * + * ```js + * const { PerformanceObserver, performance } = require('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/v16.9.0/lib/perf_hooks.js) + */ +declare module 'perf_hooks' { + import { AsyncResource } from 'node:async_hooks'; + type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; + 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; + } + /** + * @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. + } + /** + * _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 V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: 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. + * @param name + */ + clearMarks(name?: string): void; + /** + * 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. + * @param name + */ + mark(name?: string, options?: MarkOptions): void; + /** + * 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 + */ + measure(name: string, startMark?: string, endMark?: string): void; + measure(name: string, options: MeasureOptions): void; + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + /** + * 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. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * 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; + } + interface PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0 + * * } + * * ] + * + * 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('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * 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('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0 + * * } + * * ] + * + * 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; + 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('perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called three times synchronously. `list` contains one item. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: ReadonlyArray; + } + | { + type: EntryType; + } + ): void; + } + 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 { + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * 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 minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * 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; + } + 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 + * @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. + * + * ## Examples + * @since v15.9.0 + */ + recordDelta(): 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('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 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; +} +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..46458f4 --- /dev/null +++ b/node_modules/@types/node/process.d.ts @@ -0,0 +1,1477 @@ +declare module 'process' { + 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 { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + 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 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; + type UnhandledRejectionListener = (reason: {} | null | undefined, 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]; + bigint(): bigint; + } + 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. + * @defaul 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 '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; + }; + openStdin(): Socket; + /** + * 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 'process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```console + * $ 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. + * + * ```console + * $ node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * 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 '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 '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 'process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * 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 'process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information' + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from '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, the `options` argument is ignored. + * @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: + * + * ```console + * $ node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from '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 '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 '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 '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. + * @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 '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 '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 '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. + */ + exit(code?: number): 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`. + * @since v0.11.8 + */ + exitCode?: number | undefined; + /** + * 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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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.version` property contains the Node.js version string. + * + * ```js + * import { version } from '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 'process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '11.13.0', + * v8: '7.0.276.38-node.18', + * uv: '1.27.0', + * zlib: '1.2.11', + * brotli: '1.0.7', + * ares: '1.15.0', + * modules: '67', + * nghttp2: '1.34.0', + * napi: '4', + * llhttp: '1.1.1', + * openssl: '1.1.1b', + * cldr: '34.0', + * icu: '63.1', + * tz: '2018e', + * unicode: '11.0' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns an `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_dtrace: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * + * The `process.config` property is **not** read-only and there are existing + * modules in the ecosystem that are known to extend, modify, or entirely replace + * the value of `process.config`. + * + * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made + * read-only in a future release. + * @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 '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; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from '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 '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'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. + * + * ```js + * import { arch } from 'process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: string; + /** + * The `process.platform` property returns a string identifying the operating + * system platform on which the Node.js process is running. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from '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; + /** + * 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 '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 '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 '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 '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; + /** + * 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: 'Erbium', + * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v12.18.1/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 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?: { + swallowErrors?: 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 '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 '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 `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..345af53 --- /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/v16.9.0/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: ReadonlyArray): 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..892440b --- /dev/null +++ b/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,131 @@ +/** + * The `querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('querystring'); + * ``` + * + * The `querystring` API is considered Legacy. While it is still maintained, + * new code should use the `URLSearchParams` API instead. + * @deprecated Legacy + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/querystring.js) + */ +declare module 'querystring' { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends NodeJS.Dict | ReadonlyArray | ReadonlyArray | 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: + * + * ```js + * { + * 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..9c9258b --- /dev/null +++ b/node_modules/@types/node/readline.d.ts @@ -0,0 +1,542 @@ +/** + * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. It can be accessed + * using: + * + * ```js + * const readline = require('readline'); + * ``` + * + * The following simple example illustrates the basic use of the `readline` module. + * + * ```js + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * + * rl.question('What do you think of Node.js? ', (answer) => { + * // TODO: Log the answer in a database + * 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/v16.9.0/lib/readline.js) + */ +declare module 'readline' { + import { Abortable, EventEmitter } from 'node:events'; + 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` 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 v0.1.104 + */ + 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-v10.x/docs/api/readline.html#readline_class_interface + */ + 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-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.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 `readline.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 `readline.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 `readline.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. + * + * 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); + * ``` + * + * If this method is invoked as it's util.promisify()ed version, it returns a + * Promise that fulfills with the answer. If the question is canceled using + * an `AbortController` it will reject with an `AbortError`. + * + * ```js + * const util = require('util'); + * const question = util.promisify(rl.question).bind(rl); + * + * async function questionExample() { + * try { + * const answer = await question('What is you favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * } catch (err) { + * console.error('Question rejected', err); + * } + * } + * questionExample(); + * ``` + * @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 `readline.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 `readline.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 `readline.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 `readline.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; + /** + * 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; + } + type ReadLine = Interface; // type forwarded for backwards compatibility + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => void; + type CompleterResult = [string[], string]; + 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('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 `EOF` (Ctrl+D on + * Linux/macOS, Ctrl+Z followed by Return on + * Windows). + * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: + * + * ```js + * process.stdin.unref(); + * ``` + * @since v0.1.98 + */ + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + 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); + * ``` + * @since v0.7.7 + */ + function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + type Direction = -1 | 0 | 1; + interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given `TTY` 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`. + */ + function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given `TTY` 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`. + */ + function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given `TTY` `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`. + */ + 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` `stream`. + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('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('fs'); + * const readline = require('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('fs'); + * const readline = require('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('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('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 + * @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`. + */ + 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/repl.d.ts b/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..04f64e1 --- /dev/null +++ b/node_modules/@types/node/repl.d.ts @@ -0,0 +1,424 @@ +/** + * The `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('repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/repl.js) + */ +declare module 'repl' { + import { Interface, Completer, AsyncCompleter } 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-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.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-v10.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-v11.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('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-v10.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-v10.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-v10.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-v10.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-v10.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-v10.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('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('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-v10.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/stream.d.ts b/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..3927144 --- /dev/null +++ b/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1249 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `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` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `stream` module: + * + * ```js + * const stream = require('stream'); + * ``` + * + * The `stream` module is useful for creating new types of stream instances. It is + * usually not necessary to use the `stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/stream.js) + */ +declare module 'stream' { + import { EventEmitter, Abortable } from 'node:events'; + import * as streamPromises from 'node:stream/promises'; + import * as streamConsumers from 'node:stream/consumers'; + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + } + ): T; + } + 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 Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + 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 `readable.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 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'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` 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; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method pulls some data out of the internal buffer and + * returns it. If no data available to be read, `null` is returned. By default, + * the data will be 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('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('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.match(/\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); + * } else { + * // 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`, `Uint8Array` 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 `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('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; + _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): void; + /** + * 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; + } + 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 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; + 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. + * It is recommended that once `write()` returns false, no more chunks be written + * 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` or `Uint8Array`. 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('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` or `Uint8Array`. 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): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): void; + /** + * 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, it is recommended that calls to `writable.uncork()` be + * deferred 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): void; + /** + * 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; + } + 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 Readable implements Writable { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + /** + * 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 `false`. + * + * 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 | Blob | 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): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): void; + cork(): void; + uncork(): void; + } + 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 {} + /** + * 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. + * + * ```js + * const fs = require('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; + * } + * } + * })(); + * ``` + * @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; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * 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('stream'); + * + * 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: + * + * ```js + * const { finished } = require('stream/promises'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * `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. + * @return 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; + } + /** + * 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('stream'); + * const fs = require('fs'); + * const zlib = require('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, which can also + * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with + * an`AbortError`. + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, + * as the last argument: + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * const ac = new AbortController(); + * const signal = ac.signal; + * + * setTimeout(() => ac.abort(), 1); + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * { signal }, + * ); + * } + * + * run().catch(console.error); // AbortError + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('lowercase.txt'), + * async function* (source, signal) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield await processChunk(chunk, { signal }); + * } + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * Remember to handle the `signal` argument passed into the async generator. + * Especially in the case where the async generator is the source for the + * pipeline (i.e. first argument) or the pipeline will never complete. + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * async function * (signal) { + * await someLongRunningfn({ signal }); + * yield 'asd'; + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * `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. + * @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, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, 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 void)> + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__, 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; + } + 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..ce6c9bb --- /dev/null +++ b/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,24 @@ +// Duplicates of interface in lib.dom.ts. +// Duplicated here rather than referencing lib.dom.ts because doing so causes lib.dom.ts to be loaded for "test-all" +// Which in turn causes tests to pass that shouldn't pass. +// +// This interface is not, and should not be, exported. +interface Blob { + readonly size: number; + readonly type: string; + arrayBuffer(): Promise; + slice(start?: number, end?: number, contentType?: string): Blob; + stream(): NodeJS.ReadableStream; + text(): Promise; +} +declare module 'stream/consumers' { + import { Readable } from 'node:stream'; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterator): 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..b427073 --- /dev/null +++ b/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,42 @@ +declare module 'stream/promises' { + import { FinishedOptions, PipelineSource, PipelineTransform, PipelineDestination, PipelinePromise, PipelineOptions } 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, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline, 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..a9d75c1 --- /dev/null +++ b/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,6 @@ +declare module 'stream/web' { + // stub module, pending copy&paste from .d.ts or manual impl +} +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..584e0c5 --- /dev/null +++ b/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `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('string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); + * ``` + * + * 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('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/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 A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + write(buffer: Buffer): 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 A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + end(buffer?: Buffer): string; + } +} +declare module 'node:string_decoder' { + export * from 'string_decoder'; +} diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..1768d7f --- /dev/null +++ b/node_modules/@types/node/timers.d.ts @@ -0,0 +1,94 @@ +/** + * 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('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/v16.9.0/lib/timers.js) + */ +declare module 'timers' { + import { Abortable } from 'node:events'; + import { setTimeout as setTimeoutPromise, setImmediate as setImmediatePromise, setInterval as setIntervalPromise } 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; + } + interface Immediate extends RefCounted { + /** + * 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 + } + interface Timeout extends Timer { + /** + * 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; + } + } + function setTimeout(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timeout; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + function clearTimeout(timeoutId: NodeJS.Timeout): void; + function setInterval(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timer; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timer; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + function clearInterval(intervalId: NodeJS.Timeout): void; + function setImmediate(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + function clearImmediate(immediateId: NodeJS.Immediate): 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..fd77888 --- /dev/null +++ b/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,68 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('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. + * + * ```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; +} +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..b1f4c87 --- /dev/null +++ b/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1019 @@ +/** + * The `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('tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/tls.js) + */ +declare module 'tls' { + import { X509Certificate } from 'node:crypto'; + import * as net from 'node:net'; + 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 { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: NodeJS.Dict; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + fingerprint256: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + interface DetailedPeerCertificate extends PeerCertificate { + 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, options?: TLSSocketOptions); + /** + * Returns `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: boolean; + /** + * 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: + * + * ```json + * { + * "name": "AES128-SHA256", + * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", + * "version": "TLSv1.2" + * } + * ``` + * + * 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. + * + * Note: 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?: net.Socket | 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). + */ + 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: (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: 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: (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: 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: (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: 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: (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: 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: (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: 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: (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: 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 { + /** + * 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; + /** + * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use + * openssl dhparam to create the 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. If omitted or invalid, the parameters are + * silently discarded and DHE ciphers will not 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 can be overwritten by providing alternative function as part of + * the `options.checkServerIdentity` option 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`). + * @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 `cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('tls'); + * const fs = require('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('tls'); + * const fs = require('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 {@link createServer} and `server.addContext()`, but has no public methods. + * + * 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). + * @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}. + * + * 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 tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.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. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.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. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: ReadonlyArray; +} +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..2976eb6 --- /dev/null +++ b/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,161 @@ +/** + * The `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` trace data. + * The `async_hooks` 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.dns.native`: Enables capture of trace data for DNS queries. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.perf`: Enables capture of `Performance API` 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 `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * + * 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 `trace_events` module: + * + * ```js + * const trace_events = require('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 + * ``` + * + * 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` threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/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. + */ + 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. + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + */ + 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('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 + * @return . + */ + 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('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..3bce2d3 --- /dev/null +++ b/node_modules/@types/node/tty.d.ts @@ -0,0 +1,204 @@ +/** + * The `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('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/v16.9.0/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. Defaults to `false`. + * @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..602fca0 --- /dev/null +++ b/node_modules/@types/node/url.d.ts @@ -0,0 +1,821 @@ +/** + * The `url` module provides utilities for URL resolution and parsing. It can be + * accessed using: + * + * ```js + * import url from 'url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/url.js) + */ +declare module 'url' { + import { Blob } 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; + } + /** + * 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. + * + * Use of the legacy `url.parse()` method is discouraged. Users should + * use the WHATWG `URL` API. Because the `url.parse()` method uses a + * lenient, non-standard algorithm for parsing URL strings, security + * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and + * incorrect handling of usernames and passwords have been identified. + * @since v0.1.25 + * @deprecated Legacy: 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 object has both a `toString()` method and `href` property that return string serializations of the URL. + * These are not, however, customizable in any way. The `url.format(URL[, options])` method allows for basic + * customization of the output. + * Returns a customizable serialization of a URL `String` representation of a `WHATWG URL` object. + * + * ```js + * import url from 'url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(myURL.href); + * // Prints https://a:b@xn--g6w251d/?abc#foo + * + * console.log(myURL.toString()); + * // Prints https://a:b@xn--g6w251d/?abc#foo + * + * console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); + * // Prints 'https://測試/?abc' + * ``` + * @since v7.6.0 + * @param urlObject A `WHATWG URL` object + * @param options + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('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 + * @deprecated 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 HREF. + * + * ```js + * const url = require('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' + * ``` + * + * You can 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 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param from The Base URL being resolved against. + * @param to The HREF URL being resolved. + */ + 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}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from '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}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from '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 '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): 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 '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): 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 '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 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + auth?: boolean | undefined; + fragment?: boolean | undefined; + search?: boolean | undefined; + 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('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: Blob): string; + /** + * Removes the stored `Blob` identified by the given ID. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(objectUrl: string): void; + constructor(input: 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:82'; + * 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; + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: 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(callback: (this: TThis, value: string, name: string, searchParams: this) => 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[]; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: 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; + /** + * 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]>; + } +} +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..d0f4c17 --- /dev/null +++ b/node_modules/@types/node/util.d.ts @@ -0,0 +1,1594 @@ +/** + * The `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('util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/util.js) + */ +declare module 'util' { + import * as types from 'node:util/types'; + export interface InspectOptions { + /** + * 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; + showHidden?: boolean | undefined; + /** + * @default 2 + */ + depth?: number | null | undefined; + colors?: boolean | undefined; + customInspect?: boolean | undefined; + showProxy?: boolean | undefined; + 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; + 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; + sorted?: boolean | ((a: string, b: string) => number) | undefined; + } + export type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; + 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 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('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 + */ + export function toUSVString(string: string): string; + /** + * 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('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('util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('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('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('util'); + * const assert = require('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 }) + * ); + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MB. 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('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('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('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('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('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('util'); + * const EventEmitter = require('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('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 + * @deprecated 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('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('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('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('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('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('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('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('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('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('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 - Deprecated: 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('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('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('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('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('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('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('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 && err.hasOwnProperty('reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param original 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('util'); + * const fs = require('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('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * ``` + * + * 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('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; + } + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder('shift_jis'); + * let string = ''; + * let buffer; + * while (buffer = getNextChunkSomehow()) { + * string += decoder.decode(buffer, { stream: true }); + * } + * string += decoder.decode(); // end-of-stream + * ``` + * @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 }; + /** + * 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; + } +} +declare module 'util/types' { + export * from 'util/types'; +} +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 is an instance of a built-in `Error` type. + * + * ```js + * util.types.isNativeError(new Error()); // Returns true + * util.types.isNativeError(new TypeError()); // Returns true + * util.types.isNativeError(new RangeError()); // Returns 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..f467fcc --- /dev/null +++ b/node_modules/@types/node/v8.d.ts @@ -0,0 +1,378 @@ +/** + * The `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('v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/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; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + /** + * 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. + * + * ```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 + * } + * ``` + * @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('v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * 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. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable Stream containing the V8 heap snapshot + */ + function getHeapSnapshot(): 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. + * + * ```js + * const { writeHeapSnapshot } = require('v8'); + * const { + * Worker, + * isMainThread, + * parentPort + * } = require('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): string; + /** + * Returns an object with the following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794 + * } + * ``` + * @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. + * @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, 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, v12.22.0 + */ + function stopCoverage(): void; +} +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..a46b391 --- /dev/null +++ b/node_modules/@types/node/vm.d.ts @@ -0,0 +1,507 @@ +/** + * The `vm` module enables compiling and running code within V8 Virtual + * Machine contexts. **The `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('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/v16.9.0/lib/vm.js) + */ +declare module 'vm' { + 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 { + displayErrors?: boolean | undefined; + timeout?: number | undefined; + cachedData?: Buffer | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | 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; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate' | undefined; + } + 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; + context?: Context | 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); + /** + * 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('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('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?: RunningScriptOptions): 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('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. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutX = script.createCachedData(); + * + * script.runInThisContext(); + * + * const cacheWithX = script.createCachedData(); + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will `prepare + * that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. 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('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 `` + +[Get supported base64-js with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-base64-js?utm_source=npm-base64-js&utm_medium=referral&utm_campaign=readme) + +## methods + +`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. + +* `byteLength` - Takes a base64 string and returns length of byte array +* `toByteArray` - Takes a base64 string and returns a byte array +* `fromByteArray` - Takes a byte array and returns a base64 string + +## license + +MIT diff --git a/node_modules/base64-js/base64js.min.js b/node_modules/base64-js/base64js.min.js new file mode 100644 index 0000000..908ac83 --- /dev/null +++ b/node_modules/base64-js/base64js.min.js @@ -0,0 +1 @@ +(function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,b.base64js=a()}})(function(){return function(){function b(d,e,g){function a(j,i){if(!e[j]){if(!d[j]){var f="function"==typeof require&&require;if(!i&&f)return f(j,!0);if(h)return h(j,!0);var c=new Error("Cannot find module '"+j+"'");throw c.code="MODULE_NOT_FOUND",c}var k=e[j]={exports:{}};d[j][0].call(k.exports,function(b){var c=d[j][1][b];return a(c||b)},k,k.exports,b,d,e,g)}return e[j].exports}for(var h="function"==typeof require&&require,c=0;c>16,j[k++]=255&b>>8,j[k++]=255&b;return 2===h&&(b=l[a.charCodeAt(c)]<<2|l[a.charCodeAt(c+1)]>>4,j[k++]=255&b),1===h&&(b=l[a.charCodeAt(c)]<<10|l[a.charCodeAt(c+1)]<<4|l[a.charCodeAt(c+2)]>>2,j[k++]=255&b>>8,j[k++]=255&b),j}function g(a){return k[63&a>>18]+k[63&a>>12]+k[63&a>>6]+k[63&a]}function h(a,b,c){for(var d,e=[],f=b;fj?j:g+f));return 1===d?(b=a[c-1],e.push(k[b>>2]+k[63&b<<4]+"==")):2===d&&(b=(a[c-2]<<8)+a[c-1],e.push(k[b>>10]+k[63&b>>4]+k[63&b<<2]+"=")),e.join("")}c.byteLength=function(a){var b=d(a),c=b[0],e=b[1];return 3*(c+e)/4-e},c.toByteArray=f,c.fromByteArray=j;for(var k=[],l=[],m="undefined"==typeof Uint8Array?Array:Uint8Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,p=n.length;o 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} diff --git a/node_modules/base64-js/package.json b/node_modules/base64-js/package.json new file mode 100644 index 0000000..c3972e3 --- /dev/null +++ b/node_modules/base64-js/package.json @@ -0,0 +1,47 @@ +{ + "name": "base64-js", + "description": "Base64 encoding/decoding in pure JS", + "version": "1.5.1", + "author": "T. Jameson Little ", + "typings": "index.d.ts", + "bugs": { + "url": "https://github.com/beatgammit/base64-js/issues" + }, + "devDependencies": { + "babel-minify": "^0.5.1", + "benchmark": "^2.1.4", + "browserify": "^16.3.0", + "standard": "*", + "tape": "4.x" + }, + "homepage": "https://github.com/beatgammit/base64-js", + "keywords": [ + "base64" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/beatgammit/base64-js.git" + }, + "scripts": { + "build": "browserify -s base64js -r ./ | minify > base64js.min.js", + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/bcrypt/.editorconfig b/node_modules/bcrypt/.editorconfig new file mode 100644 index 0000000..4e12f93 --- /dev/null +++ b/node_modules/bcrypt/.editorconfig @@ -0,0 +1,19 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[{package.json,*.yml}] +indent_style = space +indent_size = 2 + +[appveyor.yml] +end_of_line = crlf + +[*.md] +trim_trailing_whitespace = false diff --git a/node_modules/bcrypt/.travis.yml b/node_modules/bcrypt/.travis.yml new file mode 100644 index 0000000..ea31b97 --- /dev/null +++ b/node_modules/bcrypt/.travis.yml @@ -0,0 +1,63 @@ +language: node_js + +services: +- docker + +env: +- LINUX_CXX=g++-4.8 + +os: +- linux +- osx + +arch: +- amd64 +- arm64 + +node_js: +- '10' +- '11' +- '12' +- '13' +- '14' +- '15' + +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-4.8 + - bc + +before_install: +- echo Building for Node $TRAVIS_NODE_VERSION +- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then export CXX=$LINUX_CXX; $CXX --version; + fi; +- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then c++ --version; fi; +- npm install -g npm@latest + +install: true + +script: +- npm test +- "./node_modules/.bin/node-pre-gyp configure" +- "./node_modules/.bin/node-pre-gyp build" +- "./node_modules/.bin/node-pre-gyp package" +- | + if [[ "$TRAVIS_OS_NAME" == "linux" ]] + then + docker run -w /src --entrypoint /bin/sh -v`pwd`:/src "node:${TRAVIS_NODE_VERSION}-alpine" test_alpine.sh + fi + +deploy: + provider: releases + skip_cleanup: true + api_key: + secure: j4gQ+m02izaw56EOd0gEStHAjCRfSCkohDWvpABiPzh1YPM9MvfEMSIvzzjV/0oMqi3Sy7eGyFv47EgQHZvouW0I8BIUzxuTCE5wP8z2SjABXCa/rz4WTppTc9d9ABq8JSdz80JxEwjmuwnYeMwWgOd7sT/VDiMxLYaXj0JWO7w= + file_glob: true + file: build/stage/kelektiv/node.bcrypt.js/releases/download/*/* + on: + node_js: '10' + repo: kelektiv/node.bcrypt.js + tags: true diff --git a/node_modules/bcrypt/CHANGELOG.md b/node_modules/bcrypt/CHANGELOG.md new file mode 100644 index 0000000..8140496 --- /dev/null +++ b/node_modules/bcrypt/CHANGELOG.md @@ -0,0 +1,171 @@ +# 5.0.1 (2021-02-22) + + * Update `node-pre-gyp` to 1.0.0 + +# 5.0.0 (2020-06-02) + + * Fix the bcrypt "wrap-around" bug. It affects passwords with lengths >= 255. + It is uncommon but it's a bug nevertheless. Previous attempts to fix the bug + was unsuccessful. + * Experimental support for z/OS + * Fix a bug related to NUL in password input + * Update `node-pre-gyp` to 0.15.0 + +# 4.0.1 (2020-02-27) + + * Fix compilation errors in Alpine linux + +# 4.0.0 (2020-02-17) + + * Switch to NAPI bcrypt + * Drop support for NodeJS 8 + +# 3.0.8 (2019-12-31) + + * Update `node-pre-gyp` to 0.14 + * Pre-built binaries for NodeJS 13 + +# 3.0.7 (2019-10-18) + + * Update `nan` to 2.14.0 + * Update `node-pre-gyp` to 0.13 + +# 3.0.6 (2019-04-11) + + * Update `nan` to 2.13.2 + +# 3.0.5 (2019-03-19) + + * Update `nan` to 2.13.1 + * NodeJS 12 compatibility + * Remove `node-pre-gyp` from bundled dependencies + +# 3.0.4-napi (2019-03-08) + + * Sync N-API bcrypt with NAN bcrypt + +# 3.0.4 (2019-02-07) + + * Fix GCC, NAN and V8 deprecation warnings + +# 3.0.3 (2018-12-19) + + * Update `nan` to 2.12.1 + +# 3.0.2 (2018-10-18) + + * Update `nan` to 2.11.1 + +# 3.0.1 (2018-09-20) + + * Update `nan` to 2.11.0 + +# 3.0.0 (2018-07-06) + + * Drop support for NodeJS <= 4 + +# 2.0.1 (2018-04-20) + + * Update `node-pre-gyp` to allow downloading prebuilt modules + +# 2.0.0 (2018-04-07) + + * Make `2b` the default bcrypt version + +# 1.1.0-napi (2018-01-21) + + * Initial support for [N-API](https://nodejs.org/api/n-api.html) + +# 1.0.3 (2016-08-23) + + * update to nan v2.6.2 for NodeJS 8 support + * Fix: use npm scripts instead of node-gyp directly. + +# 1.0.2 (2016-12-31) + + * Fix `compare` promise rejection with invalid arguments + +# 1.0.1 (2016-12-07) + + * Fix destructuring imports with promises + +# 1.0.0 (2016-12-04) + + * add Promise support (commit 2488473) + +# 0.8.7 (2016-06-09) + + * update nan to 2.3.5 for improved node v6 support + +# 0.8.6 (2016-04-20) + + * update nan for node v6 support + +# 0.8.5 (2015-08-12) + + * update to nan v2 (adds support for iojs 3) + +# 0.8.4 (2015-07-24) + + * fix deprecation warning for the Encode API + +# 0.8.3 (2015-05-06) + + * update nan to 1.8.4 for iojs 2.x support + +# 0.8.2 (2015-03-28) + + * always use callback for generating random bytes to avoid blocking + +# 0.8.1 (2015-01-18) + * update NaN to 1.5.0 for iojs support + +# 0.8.0 (2014-08-03) + * migrate to NAN for bindings + +# v0.5.0 + * Fix for issue around empty string params throwing Errors. + * Method deprecation. + * Upgrade from libeio/ev to libuv. (shtylman) + ** --- NOTE --- Breaks 0.4.x compatability + * EV_MULTIPLICITY compile flag. + +# v0.4.1 + * Thread safety fix around OpenSSL (GH-32). (bnoordhuis - through node) + * C++ code changes using delete and new instead of malloc and free. (shtylman) + * Compile options for speed, zoom. (shtylman) + * Move much of the type and variable checking to the JS. (shtylman) + +# v0.4.0 + * Added getRounds function that will tell you the number of rounds within a hash/salt + +# v0.3.2 + * Fix api issue with async salt gen first param + +# v0.3.1 + * Compile under node 0.5.x + +# v0.3.0 + * Internal Refactoring + * Remove pthread dependencies and locking + * Fix compiler warnings and a memory bug + +# v0.2.4 + * Use threadsafe functions instead of pthread mutexes + * salt validation to make sure the salt is of the correct size and format + +# v0.2.3 + * cygwin support + +# v0.2.2 + * Remove dependency on libbsd, use libssl instead + +# v0.2.0 + * Added async functionality + * API changes + * hashpw -> encrypt + * all old sync methods now end with _sync + * Removed libbsd(arc4random) dependency...now uses openssl which is more widely spread + +# v0.1.2 + * Security fix. Wasn't reading rounds in properly and was always only using 4 rounds diff --git a/node_modules/bcrypt/ISSUE_TEMPLATE.md b/node_modules/bcrypt/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..b4baa00 --- /dev/null +++ b/node_modules/bcrypt/ISSUE_TEMPLATE.md @@ -0,0 +1,18 @@ +Thanks for reporting a new issue with the node bcrypt module! + +To help you resolve your issue faster please make sure you have done the following: + +* Searched existing issues (even closed ones) for your same problem +* Make sure you have installed the required dependencies listed on the readme +* Read your npm error log for lines telling you what failed, usually it is a problem with not having the correct dependencies installed to build the native module + +Once you have done the above and are still confident that the issue is with the module, please describe it below. Some things that really help get your issue resolved faster are: + +* What went wrong? +* What did you expect to happen? +* Which version of nodejs and OS? +* If you find a bug, please write a failing test. + +Thanks! + +P.S. If it doesn't look like you read the above then your issue will likely be closed without further explanation. Sorry, but there are just too many issues opened with no useful information or questions which have been previously addressed. diff --git a/node_modules/bcrypt/LICENSE b/node_modules/bcrypt/LICENSE new file mode 100644 index 0000000..94e2ba5 --- /dev/null +++ b/node_modules/bcrypt/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Nicholas Campbell + +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. \ No newline at end of file diff --git a/node_modules/bcrypt/Makefile b/node_modules/bcrypt/Makefile new file mode 100644 index 0000000..0b49b3d --- /dev/null +++ b/node_modules/bcrypt/Makefile @@ -0,0 +1,19 @@ +TESTS = test/*.js + +all: test + +build: clean compile + +compile: + npm install . + npm run install + +test: build + @./node_modules/nodeunit/bin/nodeunit \ + $(TESTS) + +clean: + rm -Rf lib/bindings/ + + +.PHONY: clean test build diff --git a/node_modules/bcrypt/README.md b/node_modules/bcrypt/README.md new file mode 100644 index 0000000..dfa800f --- /dev/null +++ b/node_modules/bcrypt/README.md @@ -0,0 +1,374 @@ +# node.bcrypt.js +[![Build Status](https://travis-ci.org/kelektiv/node.bcrypt.js.svg?branch=master)](https://travis-ci.org/kelektiv/node.bcrypt.js) +[![Dependency Status](https://david-dm.org/kelektiv/node.bcrypt.js.svg)](https://david-dm.org/kelektiv/node.bcrypt.js) + +A library to help you hash passwords. + +You can read about [bcrypt in Wikipedia][bcryptwiki] as well as in the following article: +[How To Safely Store A Password][codahale] + +## If You Are Submitting Bugs or Issues + +Verify that the node version you are using is a _stable_ version; it has an even major release number. Unstable versions are currently not supported and issues created while using an unstable version will be closed. + +If you are on a stable version of node, please provide a sufficient code snippet or log files for installation issues. The code snippet does not require you to include confidential information. However, it must provide enough information such that the problem can be replicable. Issues which are closed without resolution often lack required information for replication. + + +## Version Compatibility + +| Node Version | Bcrypt Version | +| -------------- | ------------------| +| 0.4 | <= 0.4 | +| 0.6, 0.8, 0.10 | >= 0.5 | +| 0.11 | >= 0.8 | +| 4 | <= 2.1.0 | +| 8 | >= 1.0.3 < 4.0.0 | +| 10, 11 | >= 3 | +| 12 onwards | >= 3.0.6 | + +`node-gyp` only works with stable/released versions of node. Since the `bcrypt` module uses `node-gyp` to build and install, you'll need a stable version of node to use bcrypt. If you do not, you'll likely see an error that starts with: + +``` +gyp ERR! stack Error: "pre" versions of node cannot be installed, use the --nodedir flag instead +``` + +## Security Issues And Concerns + +> Per bcrypt implementation, only the first 72 bytes of a string are used. Any extra bytes are ignored when matching passwords. Note that this is not the first 72 *characters*. It is possible for a string to contain less than 72 characters, while taking up more than 72 bytes (e.g. a UTF-8 encoded string containing emojis). + +As should be the case with any security tool, this library should be scrutinized by anyone using it. If you find or suspect an issue with the code, please bring it to my attention and I'll spend some time trying to make sure that this tool is as secure as possible. + +To make it easier for people using this tool to analyze what has been surveyed, here is a list of BCrypt related security issues/concerns as they've come up. + +* An [issue with passwords][jtr] was found with a version of the Blowfish algorithm developed for John the Ripper. This is not present in the OpenBSD version and is thus not a problem for this module. HT [zooko][zooko]. +* Versions `< 5.0.0` suffer from bcrypt wrap-around bug and _will truncate passwords >= 255 characters leading to severely weakened passwords_. Please upgrade at earliest. See [this wiki page][wrap-around-bug] for more details. +* Versions `< 5.0.0` _do not handle NUL characters inside passwords properly leading to all subsequent characters being dropped and thus resulting in severely weakened passwords_. Please upgrade at earliest. See [this wiki page][improper-nuls] for more details. + +## Compatibility Note + +This library supports `$2a$` and `$2b$` prefix bcrypt hashes. `$2x$` and `$2y$` hashes are specific to bcrypt implementation developed for John the Ripper. In theory, they should be compatible with `$2b$` prefix. + +Compatibility with hashes generated by other languages is not 100% guaranteed due to difference in character encodings. However, it should not be an issue for most cases. + +### Migrating from v1.0.x + +Hashes generated in earlier version of `bcrypt` remain 100% supported in `v2.x.x` and later versions. In most cases, the migration should be a bump in the `package.json`. + +Hashes generated in `v2.x.x` using the defaults parameters will not work in earlier versions. + +## Dependencies + +* NodeJS +* `node-gyp` + * Please check the dependencies for this tool at: https://github.com/nodejs/node-gyp + * Windows users will need the options for c# and c++ installed with their visual studio instance. + * Python 2.x +* `OpenSSL` - This is only required to build the `bcrypt` project if you are using versions <= 0.7.7. Otherwise, we're using the builtin node crypto bindings for seed data (which use the same OpenSSL code paths we were, but don't have the external dependency). + +## Install via NPM + +``` +npm install bcrypt +``` +***Note:*** OS X users using Xcode 4.3.1 or above may need to run the following command in their terminal prior to installing if errors occur regarding xcodebuild: ```sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer``` + +_Pre-built binaries for various NodeJS versions are made available on a best-effort basis._ + +Only the current stable and supported LTS releases are actively tested against. Please note that there may be an interval between the release of the module and the availabilty of the compiled modules. + +Currently, we have pre-built binaries that support the following platforms: + +1. Windows x32 and x64 +2. Linux x64 (GlibC targets only). Pre-built binaries for MUSL targets such as Apline Linux are not available. +3. macOS + +If you face an error like this: + +``` +node-pre-gyp ERR! Tried to download(404): https://github.com/kelektiv/node.bcrypt.js/releases/download/v1.0.2/bcrypt_lib-v1.0.2-node-v48-linux-x64.tar.gz +``` + +make sure you have the appropriate dependencies installed and configured for your platform. You can find installation instructions for the dependencies for some common platforms [in this page][depsinstall]. + +## Usage + +### async (recommended) + +```javascript +const bcrypt = require('bcrypt'); +const saltRounds = 10; +const myPlaintextPassword = 's0/\/\P4$$w0rD'; +const someOtherPlaintextPassword = 'not_bacon'; +``` + +#### To hash a password: + +Technique 1 (generate a salt and hash on separate function calls): + +```javascript +bcrypt.genSalt(saltRounds, function(err, salt) { + bcrypt.hash(myPlaintextPassword, salt, function(err, hash) { + // Store hash in your password DB. + }); +}); +``` + +Technique 2 (auto-gen a salt and hash): + +```javascript +bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) { + // Store hash in your password DB. +}); +``` + +Note that both techniques achieve the same end-result. + +#### To check a password: + +```javascript +// Load hash from your password DB. +bcrypt.compare(myPlaintextPassword, hash, function(err, result) { + // result == true +}); +bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) { + // result == false +}); +``` + +[A Note on Timing Attacks](#a-note-on-timing-attacks) + +### with promises + +bcrypt uses whatever Promise implementation is available in `global.Promise`. NodeJS >= 0.12 has a native Promise implementation built in. However, this should work in any Promises/A+ compliant implementation. + +Async methods that accept a callback, return a `Promise` when callback is not specified if Promise support is available. + +```javascript +bcrypt.hash(myPlaintextPassword, saltRounds).then(function(hash) { + // Store hash in your password DB. +}); +``` +```javascript +// Load hash from your password DB. +bcrypt.compare(myPlaintextPassword, hash).then(function(result) { + // result == true +}); +bcrypt.compare(someOtherPlaintextPassword, hash).then(function(result) { + // result == false +}); +``` + +This is also compatible with `async/await` + +```javascript +async function checkUser(username, password) { + //... fetch user from a db etc. + + const match = await bcrypt.compare(password, user.passwordHash); + + if(match) { + //login + } + + //... +} +``` + +### sync + +```javascript +const bcrypt = require('bcrypt'); +const saltRounds = 10; +const myPlaintextPassword = 's0/\/\P4$$w0rD'; +const someOtherPlaintextPassword = 'not_bacon'; +``` + +#### To hash a password: + +Technique 1 (generate a salt and hash on separate function calls): + +```javascript +const salt = bcrypt.genSaltSync(saltRounds); +const hash = bcrypt.hashSync(myPlaintextPassword, salt); +// Store hash in your password DB. +``` + +Technique 2 (auto-gen a salt and hash): + +```javascript +const hash = bcrypt.hashSync(myPlaintextPassword, saltRounds); +// Store hash in your password DB. +``` + +As with async, both techniques achieve the same end-result. + +#### To check a password: + +```javascript +// Load hash from your password DB. +bcrypt.compareSync(myPlaintextPassword, hash); // true +bcrypt.compareSync(someOtherPlaintextPassword, hash); // false +``` + +[A Note on Timing Attacks](#a-note-on-timing-attacks) + +### Why is async mode recommended over sync mode? +If you are using bcrypt on a simple script, using the sync mode is perfectly fine. However, if you are using bcrypt on a server, the async mode is recommended. This is because the hashing done by bcrypt is CPU intensive, so the sync version will block the event loop and prevent your application from servicing any other inbound requests or events. The async version uses a thread pool which does not block the main event loop. + +## API + +`BCrypt.` + + * `genSaltSync(rounds, minor)` + * `rounds` - [OPTIONAL] - the cost of processing the data. (default - 10) + * `minor` - [OPTIONAL] - minor version of bcrypt to use. (default - b) + * `genSalt(rounds, minor, cb)` + * `rounds` - [OPTIONAL] - the cost of processing the data. (default - 10) + * `minor` - [OPTIONAL] - minor version of bcrypt to use. (default - b) + * `cb` - [OPTIONAL] - a callback to be fired once the salt has been generated. uses eio making it asynchronous. If `cb` is not specified, a `Promise` is returned if Promise support is available. + * `err` - First parameter to the callback detailing any errors. + * `salt` - Second parameter to the callback providing the generated salt. + * `hashSync(data, salt)` + * `data` - [REQUIRED] - the data to be encrypted. + * `salt` - [REQUIRED] - the salt to be used to hash the password. if specified as a number then a salt will be generated with the specified number of rounds and used (see example under **Usage**). + * `hash(data, salt, cb)` + * `data` - [REQUIRED] - the data to be encrypted. + * `salt` - [REQUIRED] - the salt to be used to hash the password. if specified as a number then a salt will be generated with the specified number of rounds and used (see example under **Usage**). + * `cb` - [OPTIONAL] - a callback to be fired once the data has been encrypted. uses eio making it asynchronous. If `cb` is not specified, a `Promise` is returned if Promise support is available. + * `err` - First parameter to the callback detailing any errors. + * `encrypted` - Second parameter to the callback providing the encrypted form. + * `compareSync(data, encrypted)` + * `data` - [REQUIRED] - data to compare. + * `encrypted` - [REQUIRED] - data to be compared to. + * `compare(data, encrypted, cb)` + * `data` - [REQUIRED] - data to compare. + * `encrypted` - [REQUIRED] - data to be compared to. + * `cb` - [OPTIONAL] - a callback to be fired once the data has been compared. uses eio making it asynchronous. If `cb` is not specified, a `Promise` is returned if Promise support is available. + * `err` - First parameter to the callback detailing any errors. + * `same` - Second parameter to the callback providing whether the data and encrypted forms match [true | false]. + * `getRounds(encrypted)` - return the number of rounds used to encrypt a given hash + * `encrypted` - [REQUIRED] - hash from which the number of rounds used should be extracted. + +## A Note on Rounds + +A note about the cost. When you are hashing your data the module will go through a series of rounds to give you a secure hash. The value you submit there is not just the number of rounds that the module will go through to hash your data. The module will use the value you enter and go through `2^rounds` iterations of processing. + +From @garthk, on a 2GHz core you can roughly expect: + + rounds=8 : ~40 hashes/sec + rounds=9 : ~20 hashes/sec + rounds=10: ~10 hashes/sec + rounds=11: ~5 hashes/sec + rounds=12: 2-3 hashes/sec + rounds=13: ~1 sec/hash + rounds=14: ~1.5 sec/hash + rounds=15: ~3 sec/hash + rounds=25: ~1 hour/hash + rounds=31: 2-3 days/hash + + +## A Note on Timing Attacks + +Because it's come up multiple times in this project, and other bcrypt projects, it needs to be said. The bcrypt comparison function is not susceptible to timing attacks. From codahale/bcrypt-ruby#42: + +> One of the desired properties of a cryptographic hash function is preimage attack resistance, which means there is no shortcut for generating a message which, when hashed, produces a specific digest. + +A great thread on this, in much more detail can be found @ codahale/bcrypt-ruby#43 + +If you're unfamiliar with timing attacks and want to learn more you can find a great writeup @ [A Lesson In Timing Attacks][timingatk] + +However, timing attacks are real. And, the comparison function is _not_ time safe. What that means is that it may exit the function early in the comparison process. This happens because of the above. We don't need to be careful that an attacker is going to learn anything, and our comparison function serves to provide a comparison of hashes, it is a utility to the overall purpose of the library. If you end up using it for something else we cannot guarantee the security of the comparator. Keep that in mind as you use the library. + +## Hash Info + +The characters that comprise the resultant hash are `./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$`. + +Resultant hashes will be 60 characters long and they will include the salt among other parameters, as follows: + +`$[algorithm]$[cost]$[salt][hash]` + +- 2 chars hash algorithm identifier prefix. `"$2a$" or "$2b$"` indicates BCrypt +- Cost-factor (n). Represents the exponent used to determine how many iterations 2^n +- 16-byte (128-bit) salt, base64 encoded to 22 characters +- 24-byte (192-bit) hash, base64 encoded to 31 characters + +Example: +``` +$2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa + | | | | + | | | hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa + | | | + | | salt = nOUIs5kJ7naTuTFkBy1veu + | | + | cost-factor => 10 = 2^10 rounds + | + hash-algorithm identifier => 2b = BCrypt +``` + +## Testing + +If you create a pull request, tests better pass :) + +``` +npm install +npm test +``` + +## Credits + +The code for this comes from a few sources: + +* blowfish.cc - OpenBSD +* bcrypt.cc - OpenBSD +* bcrypt::gen_salt - [gen_salt inclusion to bcrypt][bcryptgs] +* bcrypt_node.cc - me + +## Contributors + +* [Antonio Salazar Cardozo][shadowfiend] - Early MacOS X support (when we used libbsd) +* [Ben Glow][pixelglow] - Fixes for thread safety with async calls +* [Van Nguyen][thegoleffect] - Found a timing attack in the comparator +* [NewITFarmer][newitfarmer] - Initial Cygwin support +* [David Trejo][dtrejo] - packaging fixes +* [Alfred Westerveld][alfredwesterveld] - packaging fixes +* [Vincent Côté-Roy][vincentr] - Testing around concurrency issues +* [Lloyd Hilaiel][lloyd] - Documentation fixes +* [Roman Shtylman][shtylman] - Code refactoring, general rot reduction, compile options, better memory management with delete and new, and an upgrade to libuv over eio/ev. +* [Vadim Graboys][vadimg] - Code changes to support 0.5.5+ +* [Ben Noordhuis][bnoordhuis] - Fixed a thread safety issue in nodejs that was perfectly mappable to this module. +* [Nate Rajlich][tootallnate] - Bindings and build process. +* [Sean McArthur][seanmonstar] - Windows Support +* [Fanie Oosthuysen][weareu] - Windows Support +* [Amitosh Swain Mahapatra][agathver] - $2b$ hash support, ES6 Promise support +* [Nicola Del Gobbo][NickNaso] - Initial implementation with N-API + +## License +Unless stated elsewhere, file headers or otherwise, the license as stated in the LICENSE file. + +[bcryptwiki]: https://en.wikipedia.org/wiki/Bcrypt +[bcryptgs]: http://mail-index.netbsd.org/tech-crypto/2002/05/24/msg000204.html +[codahale]: http://codahale.com/how-to-safely-store-a-password/ +[gh13]: https://github.com/ncb000gt/node.bcrypt.js/issues/13 +[jtr]: http://www.openwall.com/lists/oss-security/2011/06/20/2 +[depsinstall]: https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions +[timingatk]: https://codahale.com/a-lesson-in-timing-attacks/ +[wrap-around-bug]: https://github.com/kelektiv/node.bcrypt.js/wiki/Security-Issues-and-Concerns#bcrypt-wrap-around-bug-medium-severity +[improper-nuls]: https://github.com/kelektiv/node.bcrypt.js/wiki/Security-Issues-and-Concerns#improper-nul-handling-medium-severity + +[shadowfiend]:https://github.com/Shadowfiend +[thegoleffect]:https://github.com/thegoleffect +[pixelglow]:https://github.com/pixelglow +[dtrejo]:https://github.com/dtrejo +[alfredwesterveld]:https://github.com/alfredwesterveld +[newitfarmer]:https://github.com/newitfarmer +[zooko]:https://twitter.com/zooko +[vincentr]:https://twitter.com/vincentcr +[lloyd]:https://github.com/lloyd +[shtylman]:https://github.com/shtylman +[vadimg]:https://github.com/vadimg +[bnoordhuis]:https://github.com/bnoordhuis +[tootallnate]:https://github.com/tootallnate +[seanmonstar]:https://github.com/seanmonstar +[weareu]:https://github.com/weareu +[agathver]:https://github.com/Agathver +[NickNaso]: https://github.com/NickNaso diff --git a/node_modules/bcrypt/SECURITY.md b/node_modules/bcrypt/SECURITY.md new file mode 100644 index 0000000..c132dc8 --- /dev/null +++ b/node_modules/bcrypt/SECURITY.md @@ -0,0 +1,15 @@ +# Security Policy + +As with any software, `bcrypt` is likely to have bugs. Please report any security vulnerabilities responsibly + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 5.0.x | :white_check_mark: | +| < 5.0 | :x: | + +## Reporting a Vulnerability + +If you are reporting a security vulnerability, please refrain from opening a GitHub issue and instead mail it to +one of the maintainers listed in the README. diff --git a/node_modules/bcrypt/appveyor.yml b/node_modules/bcrypt/appveyor.yml new file mode 100644 index 0000000..c39a92d --- /dev/null +++ b/node_modules/bcrypt/appveyor.yml @@ -0,0 +1,50 @@ +environment: + matrix: + - nodejs_version: "10" + platform: x64 + - nodejs_version: "10" + platform: x86 + - nodejs_version: "11" + platform: x64 + - nodejs_version: "11" + platform: x86 + - nodejs_version: "12" + platform: x64 + - nodejs_version: "12" + platform: x86 + - nodejs_version: "13" + platform: x64 + - nodejs_version: "13" + platform: x86 + - nodejs_version: "14" + platform: x64 + - nodejs_version: "14" + platform: x86 + +install: + - where npm + - where node + - ps: Install-Product node $env:nodejs_version $env:platform + - 'npm install -g npm@latest' + +build: off + +artifacts: + - path: 'build/stage/**/bcrypt*.tar.gz' + +test_script: + - node --version + - npm --version + - npm test + +after_test: + - .\node_modules\.bin\node-pre-gyp package + +on_success: + - ps: > + if ($env:NODE_PRE_GYP_GITHUB_TOKEN -ne $null -and $env:APPVEYOR_REPO_TAG_NAME -match '^v(0|[1-9]+)\.(0|[1-9]+)\.(0|[1-9]+)(-\w)?$') { + echo "Publishing $env:APPVEYOR_REPO_TAG_NAME" + npm install node-pre-gyp-github@1.4.3 + ./node_modules/.bin/node-pre-gyp-github publish --release + } + diff --git a/node_modules/bcrypt/bcrypt.js b/node_modules/bcrypt/bcrypt.js new file mode 100644 index 0000000..612f9dc --- /dev/null +++ b/node_modules/bcrypt/bcrypt.js @@ -0,0 +1,236 @@ +'use strict'; + +var nodePreGyp = require('@mapbox/node-pre-gyp'); +var path = require('path'); +var binding_path = nodePreGyp.find(path.resolve(path.join(__dirname, './package.json'))); +var bindings = require(binding_path); + +var crypto = require('crypto'); + +var promises = require('./promises'); + +/// generate a salt (sync) +/// @param {Number} [rounds] number of rounds (default 10) +/// @return {String} salt +module.exports.genSaltSync = function genSaltSync(rounds, minor) { + // default 10 rounds + if (!rounds) { + rounds = 10; + } else if (typeof rounds !== 'number') { + throw new Error('rounds must be a number'); + } + + if(!minor) { + minor = 'b'; + } else if(minor !== 'b' && minor !== 'a') { + throw new Error('minor must be either "a" or "b"'); + } + + return bindings.gen_salt_sync(minor, rounds, crypto.randomBytes(16)); +}; + +/// generate a salt +/// @param {Number} [rounds] number of rounds (default 10) +/// @param {Function} cb callback(err, salt) +module.exports.genSalt = function genSalt(rounds, minor, cb) { + var error; + + // if callback is first argument, then use defaults for others + if (typeof arguments[0] === 'function') { + // have to set callback first otherwise arguments are overriden + cb = arguments[0]; + rounds = 10; + minor = 'b'; + // callback is second argument + } else if (typeof arguments[1] === 'function') { + // have to set callback first otherwise arguments are overriden + cb = arguments[1]; + minor = 'b'; + } + + if (!cb) { + return promises.promise(genSalt, this, [rounds, minor]); + } + + // default 10 rounds + if (!rounds) { + rounds = 10; + } else if (typeof rounds !== 'number') { + // callback error asynchronously + error = new Error('rounds must be a number'); + return process.nextTick(function() { + cb(error); + }); + } + + if(!minor) { + minor = 'b' + } else if(minor !== 'b' && minor !== 'a') { + error = new Error('minor must be either "a" or "b"'); + return process.nextTick(function() { + cb(error); + }); + } + + crypto.randomBytes(16, function(error, randomBytes) { + if (error) { + cb(error); + return; + } + + bindings.gen_salt(minor, rounds, randomBytes, cb); + }); +}; + +/// hash data using a salt +/// @param {String|Buffer} data the data to encrypt +/// @param {String} salt the salt to use when hashing +/// @return {String} hash +module.exports.hashSync = function hashSync(data, salt) { + if (data == null || salt == null) { + throw new Error('data and salt arguments required'); + } + + if (!(typeof data === 'string' || data instanceof Buffer) || (typeof salt !== 'string' && typeof salt !== 'number')) { + throw new Error('data must be a string or Buffer and salt must either be a salt string or a number of rounds'); + } + + if (typeof salt === 'number') { + salt = module.exports.genSaltSync(salt); + } + + return bindings.encrypt_sync(data, salt); +}; + +/// hash data using a salt +/// @param {String|Buffer} data the data to encrypt +/// @param {String} salt the salt to use when hashing +/// @param {Function} cb callback(err, hash) +module.exports.hash = function hash(data, salt, cb) { + var error; + + if (typeof data === 'function') { + error = new Error('data must be a string or Buffer and salt must either be a salt string or a number of rounds'); + return process.nextTick(function() { + data(error); + }); + } + + if (typeof salt === 'function') { + error = new Error('data must be a string or Buffer and salt must either be a salt string or a number of rounds'); + return process.nextTick(function() { + salt(error); + }); + } + + // cb exists but is not a function + // return a rejecting promise + if (cb && typeof cb !== 'function') { + return promises.reject(new Error('cb must be a function or null to return a Promise')); + } + + if (!cb) { + return promises.promise(hash, this, [data, salt]); + } + + if (data == null || salt == null) { + error = new Error('data and salt arguments required'); + return process.nextTick(function() { + cb(error); + }); + } + + if (!(typeof data === 'string' || data instanceof Buffer) || (typeof salt !== 'string' && typeof salt !== 'number')) { + error = new Error('data must be a string or Buffer and salt must either be a salt string or a number of rounds'); + return process.nextTick(function() { + cb(error); + }); + } + + + if (typeof salt === 'number') { + return module.exports.genSalt(salt, function(err, salt) { + return bindings.encrypt(data, salt, cb); + }); + } + + return bindings.encrypt(data, salt, cb); +}; + +/// compare raw data to hash +/// @param {String|Buffer} data the data to hash and compare +/// @param {String} hash expected hash +/// @return {bool} true if hashed data matches hash +module.exports.compareSync = function compareSync(data, hash) { + if (data == null || hash == null) { + throw new Error('data and hash arguments required'); + } + + if (!(typeof data === 'string' || data instanceof Buffer) || typeof hash !== 'string') { + throw new Error('data must be a string or Buffer and hash must be a string'); + } + + return bindings.compare_sync(data, hash); +}; + +/// compare raw data to hash +/// @param {String|Buffer} data the data to hash and compare +/// @param {String} hash expected hash +/// @param {Function} cb callback(err, matched) - matched is true if hashed data matches hash +module.exports.compare = function compare(data, hash, cb) { + var error; + + if (typeof data === 'function') { + error = new Error('data and hash arguments required'); + return process.nextTick(function() { + data(error); + }); + } + + if (typeof hash === 'function') { + error = new Error('data and hash arguments required'); + return process.nextTick(function() { + hash(error); + }); + } + + // cb exists but is not a function + // return a rejecting promise + if (cb && typeof cb !== 'function') { + return promises.reject(new Error('cb must be a function or null to return a Promise')); + } + + if (!cb) { + return promises.promise(compare, this, [data, hash]); + } + + if (data == null || hash == null) { + error = new Error('data and hash arguments required'); + return process.nextTick(function() { + cb(error); + }); + } + + if (!(typeof data === 'string' || data instanceof Buffer) || typeof hash !== 'string') { + error = new Error('data and hash must be strings'); + return process.nextTick(function() { + cb(error); + }); + } + + return bindings.compare(data, hash, cb); +}; + +/// @param {String} hash extract rounds from this hash +/// @return {Number} the number of rounds used to encrypt a given hash +module.exports.getRounds = function getRounds(hash) { + if (hash == null) { + throw new Error('hash argument required'); + } + + if (typeof hash !== 'string') { + throw new Error('hash must be a string'); + } + + return bindings.get_rounds(hash); +}; diff --git a/node_modules/bcrypt/binding.gyp b/node_modules/bcrypt/binding.gyp new file mode 100644 index 0000000..986d710 --- /dev/null +++ b/node_modules/bcrypt/binding.gyp @@ -0,0 +1,57 @@ +{ + 'targets': [ + { + 'target_name': 'bcrypt_lib', + 'sources': [ + 'src/blowfish.cc', + 'src/bcrypt.cc', + 'src/bcrypt_node.cc' + ], + 'defines': [ + '_GNU_SOURCE', + ], + 'cflags!': [ '-fno-exceptions' ], + 'cflags_cc!': [ '-fno-exceptions' ], + 'include_dirs' : [ + "ryFdYf%%Lz#B-Q45D?VP8D%vq(c)HL1;-U z4X;sV-2bC9%&Px!8Juz0+)|2NK%s&Qh@-`2yfr#jR2EV5{m!}Xo1}ow@}KYdp6Bb+ zB=^0`x#ymH?z!ijyS%|GSDUg;CX)r9WYT2XfM5D^^Y{0E+07=?z>%8rQZ#X+YKi8#$ zZdmv9?_Yf5%>%~gr&Ed!wBY%tQ^p+l3;z}#=)mu{(LD!W=HIsuzRJJv9DEZnXbRRpXmoP zOR9}Ly{1!~1F{C1OwDNUP<-%bZ=f#@)^iMnvrMKOj!OTUx)Djl#b1`G8d+r___x~ZboS*9(+DMJ720{ng^Q+HXGsn&=)&hOfjvrPA7#;-A( zDpB#|Jl%y>O~cIbvhA%rVe>L^p&^>!H9ohDQD+4HZzE_9vAw0#F+0n^ll-#hS| z@#i*~+-J*drbQt0#62+snc(hIcQ`W_;1Ve4v6$sJ`Na(O$L}e2DA15ij6&mO$I8mHB2ULD>o1A%52mz z*bM#eU{jF7=Kn;S6aPEdIR67|sGkkq(L3Dr-@&HvKfor1Nt*r6{O@2>{NKT5Tnd|G z*sp~~sn&Ts_B&=wmHv0I8K1)DUl`%&<`yX|`i^id;sqECbT|LBM6#`$r~N6 zY7kGYQfTS&YOc$!MnkTG%OU@YOOk=ugCx6D?K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{YiiA`xwWtiJ7kCLh#j?K_T{6EG3)b*ACLMY>dvSaqE5_?+etfZXYpAHf5}@T zJTU}cp-)dl0<2i2rUtv9+5dB zDrZDwh-i!viAka`O9YmPK99&75p^>nE=07&h_ob8mLNDjlyg=!`m(&aAWOgu0P#tQ+qpyXkJWTj-X$m9EzvbVuDu*O)Rd zBMyvqxE*bq?L<4(&a`vwV!Pb7+Wq#hJ#J6i^S0rK{itvH2|wj${G4C(%f99J{h>eh zr~ceGI^j;VV|EgqR43EPb&8#G$LjPu!_K%f?aVtyH{6YO&2FNb>SnsRZn0bLTHStk z*d2GL-FesOg?rJS*-P|Ny-Y9HEB4AgtJm)hd*j};H}4s9-c#s#V}-4#Wm*XHcY&lcES!uaFNk#*?mUtm{B{ojcS-NYgQB0R5er0kpat9i~KjN zj;m90pg{(V*34Rh{FfpB6>DYkU!UAJChyJ3d11!0$yiP?j&qFRGUK<;*c~%&=j6jM zBi3ZJrWmO?MroN5+Gli*8JTlNWtb6ZG8$84%pBRWOs4FUCC6mQIoUBxW;Dr)DKcV? zY*;1}_Q`@{GT@x-7bf$WWW5v_FGsd3lj-_oxiJ}TPIe2E*~})3kBqBvR|v1h@MyNj z3zN^A!1MD=h+ekLSGG?4i87Xtdis6Td)CjQ}BUf}3ySy^EdT%j literal 0 HcmV?d00001 diff --git a/node_modules/bcrypt/package.json b/node_modules/bcrypt/package.json new file mode 100644 index 0000000..f42d902 --- /dev/null +++ b/node_modules/bcrypt/package.json @@ -0,0 +1,67 @@ +{ + "name": "bcrypt", + "description": "A bcrypt library for NodeJS.", + "keywords": [ + "bcrypt", + "password", + "auth", + "authentication", + "encryption", + "crypt", + "crypto" + ], + "main": "./bcrypt", + "version": "5.0.1", + "author": "Nick Campbell (https://github.com/ncb000gt)", + "engines": { + "node": ">= 10.0.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/kelektiv/node.bcrypt.js.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/kelektiv/node.bcrypt.js/issues" + }, + "scripts": { + "test": "npm install --build-from-source && nodeunit test", + "install": "node-pre-gyp install --fallback-to-build" + }, + "dependencies": { + "@mapbox/node-pre-gyp": "^1.0.0", + "node-addon-api": "^3.1.0" + }, + "devDependencies": { + "nodeunit": "^0.11.3" + }, + "contributors": [ + "Antonio Salazar Cardozo (https://github.com/Shadowfiend)", + "Van Nguyen (https://github.com/thegoleffect)", + "David Trejo (https://github.com/dtrejo)", + "Ben Glow (https://github.com/pixelglow)", + "NewITFarmer.com <> (https://github.com/newitfarmer)", + "Alfred Westerveld (https://github.com/alfredwesterveld)", + "Vincent Côté-Roy (https://github.com/vincentcr)", + "Lloyd Hilaiel (https://github.com/lloyd)", + "Roman Shtylman (https://github.com/shtylman)", + "Vadim Graboys (https://github.com/vadimg)", + "Ben Noorduis <> (https://github.com/bnoordhuis)", + "Nate Rajlich (https://github.com/tootallnate)", + "Sean McArthur (https://github.com/seanmonstar)", + "Fanie Oosthuysen (https://github.com/weareu)", + "Amitosh Swain Mahapatra (https://github.com/Agathver)", + "Corbin Crutchley (https://github.com/crutchcorn)", + "Nicola Del Gobbo (https://github.com/NickNaso)" + ], + "binary": { + "module_name": "bcrypt_lib", + "module_path": "./lib/binding/napi-v{napi_build_version}", + "package_name": "{module_name}-v{version}-napi-v{napi_build_version}-{platform}-{arch}-{libc}.tar.gz", + "host": "https://github.com", + "remote_path": "kelektiv/node.bcrypt.js/releases/download/v{version}", + "napi_versions": [ + 3 + ] + } +} diff --git a/node_modules/bcrypt/promises.js b/node_modules/bcrypt/promises.js new file mode 100644 index 0000000..cd82014 --- /dev/null +++ b/node_modules/bcrypt/promises.js @@ -0,0 +1,42 @@ +'use strict'; + +var Promise = global.Promise; + +/// encapsulate a method with a node-style callback in a Promise +/// @param {object} 'this' of the encapsulated function +/// @param {function} function to be encapsulated +/// @param {Array-like} args to be passed to the called function +/// @return {Promise} a Promise encapsulating the function +module.exports.promise = function (fn, context, args) { + + if (!Array.isArray(args)) { + args = Array.prototype.slice.call(args); + } + + if (typeof fn !== 'function') { + return Promise.reject(new Error('fn must be a function')); + } + + return new Promise(function(resolve, reject) { + args.push(function(err, data) { + if (err) { + reject(err); + } else { + resolve(data); + } + }); + + fn.apply(context, args); + }); +}; + +/// @param {err} the error to be thrown +module.exports.reject = function (err) { + return Promise.reject(err); +}; + +/// changes the promise implementation that bcrypt uses +/// @param {Promise} the implementation to use +module.exports.use = function(promise) { + Promise = promise; +}; diff --git a/node_modules/bcrypt/src/bcrypt.cc b/node_modules/bcrypt/src/bcrypt.cc new file mode 100644 index 0000000..bd8c573 --- /dev/null +++ b/node_modules/bcrypt/src/bcrypt.cc @@ -0,0 +1,315 @@ +/* $OpenBSD: bcrypt.c,v 1.31 2014/03/22 23:02:03 tedu Exp $ */ + +/* + * Copyright (c) 1997 Niels Provos + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* This password hashing algorithm was designed by David Mazieres + * and works as follows: + * + * 1. state := InitState () + * 2. state := ExpandKey (state, salt, password) + * 3. REPEAT rounds: + * state := ExpandKey (state, 0, password) + * state := ExpandKey (state, 0, salt) + * 4. ctext := "OrpheanBeholderScryDoubt" + * 5. REPEAT 64: + * ctext := Encrypt_ECB (state, ctext); + * 6. RETURN Concatenate (salt, ctext); + * + */ + +#include +#include +#include +#include + +#include "node_blf.h" + +#ifdef _WIN32 +#define snprintf _snprintf +#endif + +//#if !defined(__APPLE__) && !defined(__MACH__) +//#include "bsd/stdlib.h" +//#endif + +/* This implementation is adaptable to current computing power. + * You can have up to 2^31 rounds which should be enough for some + * time to come. + */ + +static void encode_base64(u_int8_t *, u_int8_t *, u_int16_t); +static void decode_base64(u_int8_t *, u_int16_t, u_int8_t *); + +const static char* error = ":"; + +const static u_int8_t Base64Code[] = +"./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + +const static u_int8_t index_64[128] = { + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 0, 1, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 255, 255, + 255, 255, 255, 255, 255, 2, 3, 4, 5, 6, + 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, + 255, 255, 255, 255, 255, 255, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, + 51, 52, 53, 255, 255, 255, 255, 255 +}; +#define CHAR64(c) ( (c) > 127 ? 255 : index_64[(c)]) + +static void +decode_base64(u_int8_t *buffer, u_int16_t len, u_int8_t *data) +{ + u_int8_t *bp = buffer; + u_int8_t *p = data; + u_int8_t c1, c2, c3, c4; + while (bp < buffer + len) { + c1 = CHAR64(*p); + c2 = CHAR64(*(p + 1)); + + /* Invalid data */ + if (c1 == 255 || c2 == 255) + break; + + *bp++ = (c1 << 2) | ((c2 & 0x30) >> 4); + if (bp >= buffer + len) + break; + + c3 = CHAR64(*(p + 2)); + if (c3 == 255) + break; + + *bp++ = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2); + if (bp >= buffer + len) + break; + + c4 = CHAR64(*(p + 3)); + if (c4 == 255) + break; + *bp++ = ((c3 & 0x03) << 6) | c4; + + p += 4; + } +} + +void +encode_salt(char *salt, u_int8_t *csalt, char minor, u_int16_t clen, u_int8_t logr) +{ + salt[0] = '$'; + salt[1] = BCRYPT_VERSION; + salt[2] = minor; + salt[3] = '$'; + + // Max rounds are 31 + snprintf(salt + 4, 4, "%2.2u$", logr & 0x001F); + + encode_base64((u_int8_t *) salt + 7, csalt, clen); +} + + +/* Generates a salt for this version of crypt. + Since versions may change. Keeping this here + seems sensible. + from: http://mail-index.netbsd.org/tech-crypto/2002/05/24/msg000204.html +*/ +void +bcrypt_gensalt(char minor, u_int8_t log_rounds, u_int8_t *seed, char *gsalt) +{ + if (log_rounds < 4) + log_rounds = 4; + else if (log_rounds > 31) + log_rounds = 31; + + encode_salt(gsalt, seed, minor, BCRYPT_MAXSALT, log_rounds); +} + +/* We handle $Vers$log2(NumRounds)$salt+passwd$ + i.e. $2$04$iwouldntknowwhattosayetKdJ6iFtacBqJdKe6aW7ou */ + +void +bcrypt(const char *key, size_t key_len, const char *salt, char *encrypted) +{ + blf_ctx state; + u_int32_t rounds, i, k; + u_int16_t j; + u_int8_t salt_len, logr, minor; + u_int8_t ciphertext[4 * BCRYPT_BLOCKS+1] = "OrpheanBeholderScryDoubt"; + u_int8_t csalt[BCRYPT_MAXSALT]; + u_int32_t cdata[BCRYPT_BLOCKS]; + int n; + + /* Discard "$" identifier */ + salt++; + + if (*salt > BCRYPT_VERSION) { + /* How do I handle errors ? Return ':' */ + strcpy(encrypted, error); + return; + } + + /* Check for minor versions */ + if (salt[1] != '$') { + switch (salt[1]) { + case 'a': /* 'ab' should not yield the same as 'abab' */ + case 'b': /* cap input length at 72 bytes */ + minor = salt[1]; + salt++; + break; + default: + strcpy(encrypted, error); + return; + } + } else + minor = 0; + + /* Discard version + "$" identifier */ + salt += 2; + + if (salt[2] != '$') { + /* Out of sync with passwd entry */ + strcpy(encrypted, error); + return; + } + + /* Computer power doesn't increase linear, 2^x should be fine */ + n = atoi(salt); + if (n > 31 || n < 0) { + strcpy(encrypted, error); + return; + } + logr = (u_int8_t)n; + if ((rounds = (u_int32_t) 1 << logr) < BCRYPT_MINROUNDS) { + strcpy(encrypted, error); + return; + } + + /* Discard num rounds + "$" identifier */ + salt += 3; + + if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT) { + strcpy(encrypted, error); + return; + } + + /* We dont want the base64 salt but the raw data */ + decode_base64(csalt, BCRYPT_MAXSALT, (u_int8_t *) salt); + salt_len = BCRYPT_MAXSALT; + if (minor <= 'a') + key_len = (u_int8_t)(key_len + (minor >= 'a' ? 1 : 0)); + else + { + /* cap key_len at the actual maximum supported + * length here to avoid integer wraparound */ + if (key_len > 72) + key_len = 72; + key_len++; /* include the NUL */ + } + + + /* Setting up S-Boxes and Subkeys */ + Blowfish_initstate(&state); + Blowfish_expandstate(&state, csalt, salt_len, + (u_int8_t *) key, key_len); + for (k = 0; k < rounds; k++) { + Blowfish_expand0state(&state, (u_int8_t *) key, key_len); + Blowfish_expand0state(&state, csalt, salt_len); + } + + /* This can be precomputed later */ + j = 0; + for (i = 0; i < BCRYPT_BLOCKS; i++) + cdata[i] = Blowfish_stream2word(ciphertext, 4 * BCRYPT_BLOCKS, &j); + + /* Now do the encryption */ + for (k = 0; k < 64; k++) + blf_enc(&state, cdata, BCRYPT_BLOCKS / 2); + + for (i = 0; i < BCRYPT_BLOCKS; i++) { + ciphertext[4 * i + 3] = cdata[i] & 0xff; + cdata[i] = cdata[i] >> 8; + ciphertext[4 * i + 2] = cdata[i] & 0xff; + cdata[i] = cdata[i] >> 8; + ciphertext[4 * i + 1] = cdata[i] & 0xff; + cdata[i] = cdata[i] >> 8; + ciphertext[4 * i + 0] = cdata[i] & 0xff; + } + + i = 0; + encrypted[i++] = '$'; + encrypted[i++] = BCRYPT_VERSION; + if (minor) + encrypted[i++] = minor; + encrypted[i++] = '$'; + + snprintf(encrypted + i, 4, "%2.2u$", logr & 0x001F); + + encode_base64((u_int8_t *) encrypted + i + 3, csalt, BCRYPT_MAXSALT); + encode_base64((u_int8_t *) encrypted + strlen(encrypted), ciphertext, + 4 * BCRYPT_BLOCKS - 1); + memset(&state, 0, sizeof(state)); + memset(ciphertext, 0, sizeof(ciphertext)); + memset(csalt, 0, sizeof(csalt)); + memset(cdata, 0, sizeof(cdata)); +} + +u_int32_t bcrypt_get_rounds(const char * hash) +{ + /* skip past the leading "$" */ + if (!hash || *(hash++) != '$') return 0; + + /* skip past version */ + if (0 == (*hash++)) return 0; + if (*hash && *hash != '$') hash++; + if (*hash++ != '$') return 0; + + return atoi(hash); +} + +static void +encode_base64(u_int8_t *buffer, u_int8_t *data, u_int16_t len) +{ + u_int8_t *bp = buffer; + u_int8_t *p = data; + u_int8_t c1, c2; + while (p < data + len) { + c1 = *p++; + *bp++ = Base64Code[(c1 >> 2)]; + c1 = (c1 & 0x03) << 4; + if (p >= data + len) { + *bp++ = Base64Code[c1]; + break; + } + c2 = *p++; + c1 |= (c2 >> 4) & 0x0f; + *bp++ = Base64Code[c1]; + c1 = (c2 & 0x0f) << 2; + if (p >= data + len) { + *bp++ = Base64Code[c1]; + break; + } + c2 = *p++; + c1 |= (c2 >> 6) & 0x03; + *bp++ = Base64Code[c1]; + *bp++ = Base64Code[c2 & 0x3f]; + } + *bp = '\0'; +} diff --git a/node_modules/bcrypt/src/bcrypt_node.cc b/node_modules/bcrypt/src/bcrypt_node.cc new file mode 100644 index 0000000..ce1c62c --- /dev/null +++ b/node_modules/bcrypt/src/bcrypt_node.cc @@ -0,0 +1,286 @@ +#include + +#include +#include +#include +#include // atoi + +#include "node_blf.h" + +#define NODE_LESS_THAN (!(NODE_VERSION_AT_LEAST(0, 5, 4))) + +namespace { + + bool ValidateSalt(const char* salt) { + + if (!salt || *salt != '$') { + return false; + } + + // discard $ + salt++; + + if (*salt > BCRYPT_VERSION) { + return false; + } + + if (salt[1] != '$') { + switch (salt[1]) { + case 'a': + case 'b': + salt++; + break; + default: + return false; + } + } + + // discard version + $ + salt += 2; + + if (salt[2] != '$') { + return false; + } + + int n = atoi(salt); + if (n > 31 || n < 0) { + return false; + } + + if (((uint8_t)1 << (uint8_t)n) < BCRYPT_MINROUNDS) { + return false; + } + + salt += 3; + if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT) { + return false; + } + + return true; + } + + inline char ToCharVersion(const std::string& str) { + return str[0]; + } + + /* SALT GENERATION */ + + class SaltAsyncWorker : public Napi::AsyncWorker { + public: + SaltAsyncWorker(const Napi::Function& callback, const std::string& seed, ssize_t rounds, char minor_ver) + : Napi::AsyncWorker(callback, "bcrypt:SaltAsyncWorker"), seed(seed), rounds(rounds), minor_ver(minor_ver) { + } + + ~SaltAsyncWorker() {} + + void Execute() { + bcrypt_gensalt(minor_ver, rounds, (u_int8_t *)&seed[0], salt); + } + + void OnOK() { + Napi::HandleScope scope(Env()); + Callback().Call({Env().Undefined(), Napi::String::New(Env(), salt)}); + } + + private: + std::string seed; + ssize_t rounds; + char minor_ver; + char salt[_SALT_LEN]; + }; + + Napi::Value GenerateSalt(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + if (info.Length() < 4) { + throw Napi::TypeError::New(env, "4 arguments expected"); + } + if (!info[0].IsString()) { + throw Napi::TypeError::New(env, "First argument must be a string"); + } + if (!info[2].IsBuffer() || (info[2].As>()).Length() != 16) { + throw Napi::TypeError::New(env, "Second argument must be a 16 byte Buffer"); + } + + const char minor_ver = ToCharVersion(info[0].As()); + const int32_t rounds = info[1].As(); + Napi::Buffer seed = info[2].As>(); + Napi::Function callback = info[3].As(); + SaltAsyncWorker* saltWorker = new SaltAsyncWorker(callback, std::string(seed.Data(), 16), rounds, minor_ver); + saltWorker->Queue(); + return env.Undefined(); + } + + Napi::Value GenerateSaltSync(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + if (info.Length() < 3) { + throw Napi::TypeError::New(env, "3 arguments expected"); + } + if (!info[0].IsString()) { + throw Napi::TypeError::New(env, "First argument must be a string"); + } + if (!info[2].IsBuffer() || (info[2].As>()).Length() != 16) { + throw Napi::TypeError::New(env, "Third argument must be a 16 byte Buffer"); + } + const char minor_ver = ToCharVersion(info[0].As()); + const int32_t rounds = info[1].As(); + Napi::Buffer buffer = info[2].As>(); + u_int8_t* seed = (u_int8_t*) buffer.Data(); + char salt[_SALT_LEN]; + bcrypt_gensalt(minor_ver, rounds, seed, salt); + return Napi::String::New(env, salt, strlen(salt)); + } + + inline std::string BufferToString(const Napi::Buffer &buf) { + return std::string(buf.Data(), buf.Length()); + } + + /* ENCRYPT DATA - USED TO BE HASHPW */ + + class EncryptAsyncWorker : public Napi::AsyncWorker { + public: + EncryptAsyncWorker(const Napi::Function& callback, const std::string& input, const std::string& salt) + : Napi::AsyncWorker(callback, "bcrypt:EncryptAsyncWorker"), input(input), salt(salt) { + } + + ~EncryptAsyncWorker() {} + + void Execute() { + if (!(ValidateSalt(salt.c_str()))) { + SetError("Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue"); + } + bcrypt(input.c_str(), input.length(), salt.c_str(), bcrypted); + } + + void OnOK() { + Napi::HandleScope scope(Env()); + Callback().Call({Env().Undefined(),Napi::String::New(Env(), bcrypted)}); + } + private: + std::string input; + std::string salt; + char bcrypted[_PASSWORD_LEN]; + }; + + Napi::Value Encrypt(const Napi::CallbackInfo& info) { + if (info.Length() < 3) { + throw Napi::TypeError::New(info.Env(), "3 arguments expected"); + } + std::string data = info[0].IsBuffer() + ? BufferToString(info[0].As>()) + : info[0].As(); + std::string salt = info[1].As(); + Napi::Function callback = info[2].As(); + EncryptAsyncWorker* encryptWorker = new EncryptAsyncWorker(callback, data, salt); + encryptWorker->Queue(); + return info.Env().Undefined(); + } + + Napi::Value EncryptSync(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + if (info.Length() < 2) { + throw Napi::TypeError::New(info.Env(), "2 arguments expected"); + } + std::string data = info[0].IsBuffer() + ? BufferToString(info[0].As>()) + : info[0].As(); + std::string salt = info[1].As(); + if (!(ValidateSalt(salt.c_str()))) { + throw Napi::Error::New(env, "Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue"); + } + char bcrypted[_PASSWORD_LEN]; + bcrypt(data.c_str(), data.length(), salt.c_str(), bcrypted); + return Napi::String::New(env, bcrypted, strlen(bcrypted)); + } + + /* COMPARATOR */ + inline bool CompareStrings(const char* s1, const char* s2) { + return strcmp(s1, s2) == 0; + } + + class CompareAsyncWorker : public Napi::AsyncWorker { + public: + CompareAsyncWorker(const Napi::Function& callback, const std::string& input, const std::string& encrypted) + : Napi::AsyncWorker(callback, "bcrypt:CompareAsyncWorker"), input(input), encrypted(encrypted) { + result = false; + } + + ~CompareAsyncWorker() {} + + void Execute() { + char bcrypted[_PASSWORD_LEN]; + if (ValidateSalt(encrypted.c_str())) { + bcrypt(input.c_str(), input.length(), encrypted.c_str(), bcrypted); + result = CompareStrings(bcrypted, encrypted.c_str()); + } + } + + void OnOK() { + Napi::HandleScope scope(Env()); + Callback().Call({Env().Undefined(), Napi::Boolean::New(Env(), result)}); + } + + private: + std::string input; + std::string encrypted; + bool result; + }; + + Napi::Value Compare(const Napi::CallbackInfo& info) { + if (info.Length() < 3) { + throw Napi::TypeError::New(info.Env(), "3 arguments expected"); + } + std::string input = info[0].IsBuffer() + ? BufferToString(info[0].As>()) + : info[0].As(); + std::string encrypted = info[1].As(); + Napi::Function callback = info[2].As(); + CompareAsyncWorker* compareWorker = new CompareAsyncWorker(callback, input, encrypted); + compareWorker->Queue(); + return info.Env().Undefined(); + } + + Napi::Value CompareSync(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + if (info.Length() < 2) { + throw Napi::TypeError::New(info.Env(), "2 arguments expected"); + } + std::string pw = info[0].IsBuffer() + ? BufferToString(info[0].As>()) + : info[0].As(); + std::string hash = info[1].As(); + char bcrypted[_PASSWORD_LEN]; + if (ValidateSalt(hash.c_str())) { + bcrypt(pw.c_str(), pw.length(), hash.c_str(), bcrypted); + return Napi::Boolean::New(env, CompareStrings(bcrypted, hash.c_str())); + } else { + return Napi::Boolean::New(env, false); + } + } + + Napi::Value GetRounds(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + if (info.Length() < 1) { + throw Napi::TypeError::New(env, "1 argument expected"); + } + std::string hash = info[0].As(); + u_int32_t rounds; + if (!(rounds = bcrypt_get_rounds(hash.c_str()))) { + throw Napi::Error::New(env, "invalid hash provided"); + } + return Napi::Number::New(env, rounds); + } + +} // anonymous namespace + +Napi::Object init(Napi::Env env, Napi::Object exports) { + exports.Set(Napi::String::New(env, "gen_salt_sync"), Napi::Function::New(env, GenerateSaltSync)); + exports.Set(Napi::String::New(env, "encrypt_sync"), Napi::Function::New(env, EncryptSync)); + exports.Set(Napi::String::New(env, "compare_sync"), Napi::Function::New(env, CompareSync)); + exports.Set(Napi::String::New(env, "get_rounds"), Napi::Function::New(env, GetRounds)); + exports.Set(Napi::String::New(env, "gen_salt"), Napi::Function::New(env, GenerateSalt)); + exports.Set(Napi::String::New(env, "encrypt"), Napi::Function::New(env, Encrypt)); + exports.Set(Napi::String::New(env, "compare"), Napi::Function::New(env, Compare)); + return exports; +} + +NODE_API_MODULE(NODE_GYP_MODULE_NAME, init) diff --git a/node_modules/bcrypt/src/blowfish.cc b/node_modules/bcrypt/src/blowfish.cc new file mode 100644 index 0000000..1fc6cf1 --- /dev/null +++ b/node_modules/bcrypt/src/blowfish.cc @@ -0,0 +1,679 @@ +/* $OpenBSD: blowfish.c,v 1.18 2004/11/02 17:23:26 hshoexer Exp $ */ +/* + * Blowfish block cipher for OpenBSD + * Copyright 1997 Niels Provos + * All rights reserved. + * + * Implementation advice by David Mazieres . + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Niels Provos. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * This code is derived from section 14.3 and the given source + * in section V of Applied Cryptography, second edition. + * Blowfish is an unpatented fast block cipher designed by + * Bruce Schneier. + */ + +#include "node_blf.h" + +#undef inline +#ifdef __GNUC__ +#define inline __inline +#else /* !__GNUC__ */ +#define inline +#endif /* !__GNUC__ */ + +/* Function for Feistel Networks */ + +#define F(s, x) ((((s)[ (((x)>>24)&0xFF)] \ + + (s)[0x100 + (((x)>>16)&0xFF)]) \ + ^ (s)[0x200 + (((x)>> 8)&0xFF)]) \ + + (s)[0x300 + ( (x) &0xFF)]) + +#define BLFRND(s,p,i,j,n) (i ^= F(s,j) ^ (p)[n]) + +void +Blowfish_encipher(blf_ctx *c, u_int32_t *xl, u_int32_t *xr) +{ + u_int32_t Xl; + u_int32_t Xr; + u_int32_t *s = c->S[0]; + u_int32_t *p = c->P; + + Xl = *xl; + Xr = *xr; + + Xl ^= p[0]; + BLFRND(s, p, Xr, Xl, 1); BLFRND(s, p, Xl, Xr, 2); + BLFRND(s, p, Xr, Xl, 3); BLFRND(s, p, Xl, Xr, 4); + BLFRND(s, p, Xr, Xl, 5); BLFRND(s, p, Xl, Xr, 6); + BLFRND(s, p, Xr, Xl, 7); BLFRND(s, p, Xl, Xr, 8); + BLFRND(s, p, Xr, Xl, 9); BLFRND(s, p, Xl, Xr, 10); + BLFRND(s, p, Xr, Xl, 11); BLFRND(s, p, Xl, Xr, 12); + BLFRND(s, p, Xr, Xl, 13); BLFRND(s, p, Xl, Xr, 14); + BLFRND(s, p, Xr, Xl, 15); BLFRND(s, p, Xl, Xr, 16); + + *xl = Xr ^ p[17]; + *xr = Xl; +} + +void +Blowfish_decipher(blf_ctx *c, u_int32_t *xl, u_int32_t *xr) +{ + u_int32_t Xl; + u_int32_t Xr; + u_int32_t *s = c->S[0]; + u_int32_t *p = c->P; + + Xl = *xl; + Xr = *xr; + + Xl ^= p[17]; + BLFRND(s, p, Xr, Xl, 16); BLFRND(s, p, Xl, Xr, 15); + BLFRND(s, p, Xr, Xl, 14); BLFRND(s, p, Xl, Xr, 13); + BLFRND(s, p, Xr, Xl, 12); BLFRND(s, p, Xl, Xr, 11); + BLFRND(s, p, Xr, Xl, 10); BLFRND(s, p, Xl, Xr, 9); + BLFRND(s, p, Xr, Xl, 8); BLFRND(s, p, Xl, Xr, 7); + BLFRND(s, p, Xr, Xl, 6); BLFRND(s, p, Xl, Xr, 5); + BLFRND(s, p, Xr, Xl, 4); BLFRND(s, p, Xl, Xr, 3); + BLFRND(s, p, Xr, Xl, 2); BLFRND(s, p, Xl, Xr, 1); + + *xl = Xr ^ p[0]; + *xr = Xl; +} + +void +Blowfish_initstate(blf_ctx *c) +{ + /* P-box and S-box tables initialized with digits of Pi */ + + static const blf_ctx initstate = + { { + { + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a}, + { + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7}, + { + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0}, + { + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6} + }, + { + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b + } }; + + *c = initstate; +} + +u_int32_t +Blowfish_stream2word(const u_int8_t *data, u_int16_t databytes, + u_int16_t *current) +{ + u_int8_t i; + u_int16_t j; + u_int32_t temp; + + temp = 0x00000000; + j = *current; + + for (i = 0; i < 4; i++, j++) { + if (j >= databytes) + j = 0; + temp = (temp << 8) | data[j]; + } + + *current = j; + return temp; +} + +void +Blowfish_expand0state(blf_ctx *c, const u_int8_t *key, u_int16_t keybytes) +{ + u_int16_t i; + u_int16_t j; + u_int16_t k; + u_int32_t temp; + u_int32_t datal; + u_int32_t datar; + + j = 0; + for (i = 0; i < BLF_N + 2; i++) { + /* Extract 4 int8 to 1 int32 from keystream */ + temp = Blowfish_stream2word(key, keybytes, &j); + c->P[i] = c->P[i] ^ temp; + } + + j = 0; + datal = 0x00000000; + datar = 0x00000000; + for (i = 0; i < BLF_N + 2; i += 2) { + Blowfish_encipher(c, &datal, &datar); + + c->P[i] = datal; + c->P[i + 1] = datar; + } + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + Blowfish_encipher(c, &datal, &datar); + + c->S[i][k] = datal; + c->S[i][k + 1] = datar; + } + } +} + + +void +Blowfish_expandstate(blf_ctx *c, const u_int8_t *data, u_int16_t databytes, + const u_int8_t *key, u_int16_t keybytes) +{ + u_int16_t i; + u_int16_t j; + u_int16_t k; + u_int32_t temp; + u_int32_t datal; + u_int32_t datar; + + j = 0; + for (i = 0; i < BLF_N + 2; i++) { + /* Extract 4 int8 to 1 int32 from keystream */ + temp = Blowfish_stream2word(key, keybytes, &j); + c->P[i] = c->P[i] ^ temp; + } + + j = 0; + datal = 0x00000000; + datar = 0x00000000; + for (i = 0; i < BLF_N + 2; i += 2) { + datal ^= Blowfish_stream2word(data, databytes, &j); + datar ^= Blowfish_stream2word(data, databytes, &j); + Blowfish_encipher(c, &datal, &datar); + + c->P[i] = datal; + c->P[i + 1] = datar; + } + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + datal ^= Blowfish_stream2word(data, databytes, &j); + datar ^= Blowfish_stream2word(data, databytes, &j); + Blowfish_encipher(c, &datal, &datar); + + c->S[i][k] = datal; + c->S[i][k + 1] = datar; + } + } + +} + +void +blf_key(blf_ctx *c, const u_int8_t *k, u_int16_t len) +{ + /* Initialize S-boxes and subkeys with Pi */ + Blowfish_initstate(c); + + /* Transform S-boxes and subkeys with key */ + Blowfish_expand0state(c, k, len); +} + +void +blf_enc(blf_ctx *c, u_int32_t *data, u_int16_t blocks) +{ + u_int32_t *d; + u_int16_t i; + + d = data; + for (i = 0; i < blocks; i++) { + Blowfish_encipher(c, d, d + 1); + d += 2; + } +} + +void +blf_dec(blf_ctx *c, u_int32_t *data, u_int16_t blocks) +{ + u_int32_t *d; + u_int16_t i; + + d = data; + for (i = 0; i < blocks; i++) { + Blowfish_decipher(c, d, d + 1); + d += 2; + } +} + +void +blf_ecb_encrypt(blf_ctx *c, u_int8_t *data, u_int32_t len) +{ + u_int32_t l, r; + u_int32_t i; + + for (i = 0; i < len; i += 8) { + l = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]; + r = data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]; + Blowfish_encipher(c, &l, &r); + data[0] = l >> 24 & 0xff; + data[1] = l >> 16 & 0xff; + data[2] = l >> 8 & 0xff; + data[3] = l & 0xff; + data[4] = r >> 24 & 0xff; + data[5] = r >> 16 & 0xff; + data[6] = r >> 8 & 0xff; + data[7] = r & 0xff; + data += 8; + } +} + +void +blf_ecb_decrypt(blf_ctx *c, u_int8_t *data, u_int32_t len) +{ + u_int32_t l, r; + u_int32_t i; + + for (i = 0; i < len; i += 8) { + l = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]; + r = data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]; + Blowfish_decipher(c, &l, &r); + data[0] = l >> 24 & 0xff; + data[1] = l >> 16 & 0xff; + data[2] = l >> 8 & 0xff; + data[3] = l & 0xff; + data[4] = r >> 24 & 0xff; + data[5] = r >> 16 & 0xff; + data[6] = r >> 8 & 0xff; + data[7] = r & 0xff; + data += 8; + } +} + +void +blf_cbc_encrypt(blf_ctx *c, u_int8_t *iv, u_int8_t *data, u_int32_t len) +{ + u_int32_t l, r; + u_int32_t i, j; + + for (i = 0; i < len; i += 8) { + for (j = 0; j < 8; j++) + data[j] ^= iv[j]; + l = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]; + r = data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]; + Blowfish_encipher(c, &l, &r); + data[0] = l >> 24 & 0xff; + data[1] = l >> 16 & 0xff; + data[2] = l >> 8 & 0xff; + data[3] = l & 0xff; + data[4] = r >> 24 & 0xff; + data[5] = r >> 16 & 0xff; + data[6] = r >> 8 & 0xff; + data[7] = r & 0xff; + iv = data; + data += 8; + } +} + +void +blf_cbc_decrypt(blf_ctx *c, u_int8_t *iva, u_int8_t *data, u_int32_t len) +{ + u_int32_t l, r; + u_int8_t *iv; + u_int32_t i, j; + + iv = data + len - 16; + data = data + len - 8; + for (i = len - 8; i >= 8; i -= 8) { + l = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]; + r = data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]; + Blowfish_decipher(c, &l, &r); + data[0] = l >> 24 & 0xff; + data[1] = l >> 16 & 0xff; + data[2] = l >> 8 & 0xff; + data[3] = l & 0xff; + data[4] = r >> 24 & 0xff; + data[5] = r >> 16 & 0xff; + data[6] = r >> 8 & 0xff; + data[7] = r & 0xff; + for (j = 0; j < 8; j++) + data[j] ^= iv[j]; + iv -= 8; + data -= 8; + } + l = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]; + r = data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]; + Blowfish_decipher(c, &l, &r); + data[0] = l >> 24 & 0xff; + data[1] = l >> 16 & 0xff; + data[2] = l >> 8 & 0xff; + data[3] = l & 0xff; + data[4] = r >> 24 & 0xff; + data[5] = r >> 16 & 0xff; + data[6] = r >> 8 & 0xff; + data[7] = r & 0xff; + for (j = 0; j < 8; j++) + data[j] ^= iva[j]; +} + +#if 0 +void +report(u_int32_t data[], u_int16_t len) +{ + u_int16_t i; + for (i = 0; i < len; i += 2) + printf("Block %0hd: %08lx %08lx.\n", + i / 2, data[i], data[i + 1]); +} +void +main(void) +{ + + blf_ctx c; + char key[] = "AAAAA"; + char key2[] = "abcdefghijklmnopqrstuvwxyz"; + + u_int32_t data[10]; + u_int32_t data2[] = + {0x424c4f57l, 0x46495348l}; + + u_int16_t i; + + /* First test */ + for (i = 0; i < 10; i++) + data[i] = i; + + blf_key(&c, (u_int8_t *) key, 5); + blf_enc(&c, data, 5); + blf_dec(&c, data, 1); + blf_dec(&c, data + 2, 4); + printf("Should read as 0 - 9.\n"); + report(data, 10); + + /* Second test */ + blf_key(&c, (u_int8_t *) key2, strlen(key2)); + blf_enc(&c, data2, 1); + printf("\nShould read as: 0x324ed0fe 0xf413a203.\n"); + report(data2, 2); + blf_dec(&c, data2, 1); + report(data2, 2); +} +#endif diff --git a/node_modules/bcrypt/src/node_blf.h b/node_modules/bcrypt/src/node_blf.h new file mode 100644 index 0000000..2d50a39 --- /dev/null +++ b/node_modules/bcrypt/src/node_blf.h @@ -0,0 +1,132 @@ +/* $OpenBSD: blf.h,v 1.7 2007/03/14 17:59:41 grunk Exp $ */ +/* + * Blowfish - a fast block cipher designed by Bruce Schneier + * + * Copyright 1997 Niels Provos + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Niels Provos. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _NODE_BLF_H_ +#define _NODE_BLF_H_ + +#include + +/* Solaris compatibility */ +#ifdef __sun +#define u_int8_t uint8_t +#define u_int16_t uint16_t +#define u_int32_t uint32_t +#define u_int64_t uint64_t +#endif + +#ifdef _WIN32 +#define u_int8_t unsigned __int8 +#define u_int16_t unsigned __int16 +#define u_int32_t unsigned __int32 +#define u_int64_t unsigned __int64 +#endif + +/* Windows ssize_t compatibility */ +#if defined(_WIN32) || defined(_WIN64) +# if defined(_WIN64) + typedef __int64 LONG_PTR; +# else + typedef long LONG_PTR; +# endif + typedef LONG_PTR SSIZE_T; + typedef SSIZE_T ssize_t; +#endif + +/* z/OS compatibility */ +#ifdef __MVS__ +typedef unsigned char u_int8_t; +typedef unsigned short u_int16_t; +typedef unsigned int u_int32_t; +typedef unsigned long long u_int64_t; +#endif + +#define BCRYPT_VERSION '2' +#define BCRYPT_MAXSALT 16 /* Precomputation is just so nice */ +#define BCRYPT_BLOCKS 6 /* Ciphertext blocks */ +#define BCRYPT_MINROUNDS 16 /* we have log2(rounds) in salt */ + +/* Schneier specifies a maximum key length of 56 bytes. + * This ensures that every key bit affects every cipher + * bit. However, the subkeys can hold up to 72 bytes. + * Warning: For normal blowfish encryption only 56 bytes + * of the key affect all cipherbits. + */ + +#define BLF_N 16 /* Number of Subkeys */ +#define BLF_MAXKEYLEN ((BLF_N-2)*4) /* 448 bits */ +#define BLF_MAXUTILIZED ((BLF_N+2)*4) /* 576 bits */ + +#define _PASSWORD_LEN 128 /* max length, not counting NUL */ +#define _SALT_LEN 32 /* max length */ + +/* Blowfish context */ +typedef struct BlowfishContext { + u_int32_t S[4][256]; /* S-Boxes */ + u_int32_t P[BLF_N + 2]; /* Subkeys */ +} blf_ctx; + +/* Raw access to customized Blowfish + * blf_key is just: + * Blowfish_initstate( state ) + * Blowfish_expand0state( state, key, keylen ) + */ + +void Blowfish_encipher(blf_ctx *, u_int32_t *, u_int32_t *); +void Blowfish_decipher(blf_ctx *, u_int32_t *, u_int32_t *); +void Blowfish_initstate(blf_ctx *); +void Blowfish_expand0state(blf_ctx *, const u_int8_t *, u_int16_t); +void Blowfish_expandstate +(blf_ctx *, const u_int8_t *, u_int16_t, const u_int8_t *, u_int16_t); + +/* Standard Blowfish */ + +void blf_key(blf_ctx *, const u_int8_t *, u_int16_t); +void blf_enc(blf_ctx *, u_int32_t *, u_int16_t); +void blf_dec(blf_ctx *, u_int32_t *, u_int16_t); + +void blf_ecb_encrypt(blf_ctx *, u_int8_t *, u_int32_t); +void blf_ecb_decrypt(blf_ctx *, u_int8_t *, u_int32_t); + +void blf_cbc_encrypt(blf_ctx *, u_int8_t *, u_int8_t *, u_int32_t); +void blf_cbc_decrypt(blf_ctx *, u_int8_t *, u_int8_t *, u_int32_t); + +/* Converts u_int8_t to u_int32_t */ +u_int32_t Blowfish_stream2word(const u_int8_t *, u_int16_t , u_int16_t *); + +/* bcrypt functions*/ +void bcrypt_gensalt(char, u_int8_t, u_int8_t*, char *); +void bcrypt(const char *, size_t key_len, const char *, char *); +void encode_salt(char *, u_int8_t *, char, u_int16_t, u_int8_t); +u_int32_t bcrypt_get_rounds(const char *); + +#endif diff --git a/node_modules/bcrypt/test/async.js b/node_modules/bcrypt/test/async.js new file mode 100644 index 0000000..1e10321 --- /dev/null +++ b/node_modules/bcrypt/test/async.js @@ -0,0 +1,181 @@ +var bcrypt = require('../bcrypt'); + +module.exports = { + test_salt_length: function(assert) { + assert.expect(1); + bcrypt.genSalt(10, function(err, salt) { + assert.strictEqual(29, salt.length, "Salt isn't the correct length."); + assert.done(); + }); + }, + test_salt_only_cb: function(assert) { + assert.doesNotThrow(function() {bcrypt.genSalt(function(err, salt) {});}, "Should not throw an Error. Rounds and seed length are optional."); + assert.done(); + }, + test_salt_rounds_is_string_number: function(assert) { + bcrypt.genSalt('10', void 0, function (err, salt) { + assert.ok((err instanceof Error), "Should be an Error. genSalt requires round to be of type number."); + assert.done(); + }); + }, + test_salt_rounds_is_string_non_number: function(assert) { + bcrypt.genSalt('z', function (err, salt) { + assert.ok((err instanceof Error), "Should throw an Error. genSalt requires rounds to of type number."); + assert.done(); + }); + }, + test_salt_minor: function(assert) { + assert.expect(3); + bcrypt.genSalt(10, 'a', function(err, salt) { + assert.strictEqual(29, salt.length, "Salt isn't the correct length."); + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2a'); + assert.strictEqual(split_salt[2], '10'); + assert.done(); + }); + }, + test_salt_minor_b: function(assert) { + assert.expect(3); + bcrypt.genSalt(10, 'b', function(err, salt) { + assert.strictEqual(29, salt.length, "Salt isn't the correct length."); + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '10'); + assert.done(); + }); + }, + test_hash: function(assert) { + assert.expect(1); + bcrypt.genSalt(10, function(err, salt) { + bcrypt.hash('password', salt, function(err, res) { + assert.ok(res, "Res should be defined."); + assert.done(); + }); + }); + }, + test_hash_rounds: function(assert) { + assert.expect(1); + bcrypt.hash('bacon', 8, function(err, hash) { + assert.strictEqual(bcrypt.getRounds(hash), 8, "Number of rounds should be that specified in the function call."); + assert.done(); + }); + }, + test_hash_empty_strings: function(assert) { + assert.expect(2); + bcrypt.genSalt(10, function(err, salt) { + bcrypt.hash('', salt, function(err, res) { + assert.ok(res, "Res should be defined even with an empty pw."); + bcrypt.hash('', '', function(err, res) { + if (err) { + assert.ok(err); + } else { + assert.fail(); + } + + assert.done(); + }); + }); + }); + }, + test_hash_no_params: function(assert) { + bcrypt.hash(function (err, hash) { + assert.ok(err, "Should be an error. No params."); + assert.done(); + }); + }, + test_hash_one_param: function(assert) { + bcrypt.hash('password', function (err, hash) { + assert.ok(err, "Should be an Error. No salt."); + assert.done(); + }); + }, + test_hash_salt_validity: function(assert) { + assert.expect(3); + bcrypt.hash('password', '$2a$10$somesaltyvaluertsetrse', function(err, enc) { + assert.strictEqual(err, undefined); + bcrypt.hash('password', 'some$value', function(err, enc) { + assert.notEqual(err, undefined); + assert.strictEqual(err.message, "Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue"); + assert.done(); + }); + }); + }, + test_verify_salt: function(assert) { + assert.expect(2); + bcrypt.genSalt(10, function(err, salt) { + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '10'); + assert.done(); + }); + }, + test_verify_salt_min_rounds: function(assert) { + assert.expect(2); + bcrypt.genSalt(1, function(err, salt) { + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '04'); + assert.done(); + }); + }, + test_verify_salt_max_rounds: function(assert) { + assert.expect(2); + bcrypt.genSalt(100, function(err, salt) { + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '31'); + assert.done(); + }); + }, + test_hash_compare: function(assert) { + assert.expect(3); + bcrypt.genSalt(10, function(err, salt) { + assert.strictEqual(29, salt.length, "Salt isn't the correct length."); + bcrypt.hash("test", salt, function(err, hash) { + bcrypt.compare("test", hash, function(err, res) { + assert.strictEqual(res, true, "These hashes should be equal."); + bcrypt.compare("blah", hash, function(err, res) { + assert.strictEqual(res, false, "These hashes should not be equal."); + assert.done(); + }); + }); + }); + }); + }, + test_hash_compare_empty_strings: function(assert) { + assert.expect(2); + var hash = bcrypt.hashSync("test", bcrypt.genSaltSync(10)); + + bcrypt.compare("", hash, function(err, res) { + assert.strictEqual(res, false, "These hashes should not be equal."); + bcrypt.compare("", "", function(err, res) { + assert.strictEqual(res, false, "These hashes should not be equal."); + assert.done(); + }); + }); + }, + test_hash_compare_invalid_strings: function(assert) { + var fullString = 'envy1362987212538'; + var hash = '$2a$10$XOPbrlUPQdwdJUpSrIF6X.LbE14qsMmKGhM1A8W9iqaG3vv1BD7WC'; + var wut = ':'; + bcrypt.compare(fullString, hash, function(err, res) { + assert.ok(res); + bcrypt.compare(fullString, wut, function(err, res) { + assert.ok(!res); + assert.done(); + }); + }); + }, + test_compare_no_params: function(assert) { + bcrypt.compare(function(err, hash) { + assert.ok(err, 'Should be an error. No params.'); + assert.done(); + }); + }, + test_hash_compare_one_param: function(assert) { + bcrypt.compare('password', function(err, hash) { + assert.ok(err, 'Should be an Error. No hash.'); + assert.done(); + }); + } +}; diff --git a/node_modules/bcrypt/test/implementation.js b/node_modules/bcrypt/test/implementation.js new file mode 100644 index 0000000..ad884bf --- /dev/null +++ b/node_modules/bcrypt/test/implementation.js @@ -0,0 +1,53 @@ +var bcrypt = require('../bcrypt'); + +// some tests were adapted from https://github.com/riverrun/bcrypt_elixir/blob/master/test/base_test.exs +// which are under the BSD LICENSE +module.exports = { + openwall_bcrypt_tests: function(assert) { + assert.strictEqual(bcrypt.hashSync("U*U", "$2a$05$CCCCCCCCCCCCCCCCCCCCC."), "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"); + assert.strictEqual(bcrypt.hashSync("U*U*", "$2a$05$CCCCCCCCCCCCCCCCCCCCC."), "$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK"); + assert.strictEqual(bcrypt.hashSync("U*U*U", "$2a$05$XXXXXXXXXXXXXXXXXXXXXO"), "$2a$05$XXXXXXXXXXXXXXXXXXXXXOAcXxm9kjPGEMsLznoKqmqw7tc8WCx4a"); + assert.strictEqual(bcrypt.hashSync("", "$2a$05$CCCCCCCCCCCCCCCCCCCCC."), "$2a$05$CCCCCCCCCCCCCCCCCCCCC.7uG0VCzI2bS7j6ymqJi9CdcdxiRTWNy"); + assert.strictEqual(bcrypt.hashSync("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "$2a$05$abcdefghijklmnopqrstuu"), "$2a$05$abcdefghijklmnopqrstuu5s2v8.iXieOjg/.AySBTTZIIVFJeBui"); + assert.done(); + }, + openbsd_bcrypt_tests: function(assert) { + assert.strictEqual(bcrypt.hashSync("000000000000000000000000000000000000000000000000000000000000000000000000", "$2a$05$CCCCCCCCCCCCCCCCCCCCC."), "$2a$05$CCCCCCCCCCCCCCCCCCCCC.6.O1dLNbjod2uo0DVcW.jHucKbPDdHS"); + assert.strictEqual(bcrypt.hashSync("000000000000000000000000000000000000000000000000000000000000000000000000", "$2b$05$CCCCCCCCCCCCCCCCCCCCC."), "$2b$05$CCCCCCCCCCCCCCCCCCCCC.6.O1dLNbjod2uo0DVcW.jHucKbPDdHS"); + assert.done(); + }, + test_long_passwords: function(assert) { + // bcrypt wrap-around bug in $2a$ + assert.strictEqual(bcrypt.hashSync("012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234", "$2a$05$CCCCCCCCCCCCCCCCCCCCC."), "$2a$05$CCCCCCCCCCCCCCCCCCCCC.6.O1dLNbjod2uo0DVcW.jHucKbPDdHS"); + assert.strictEqual(bcrypt.hashSync("01XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "$2a$05$CCCCCCCCCCCCCCCCCCCCC."), "$2a$05$CCCCCCCCCCCCCCCCCCCCC.6.O1dLNbjod2uo0DVcW.jHucKbPDdHS"); + + // tests for $2b$ which fixes wrap-around bugs + assert.strictEqual(bcrypt.hashSync("012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234", "$2b$05$CCCCCCCCCCCCCCCCCCCCC."), "$2b$05$CCCCCCCCCCCCCCCCCCCCC.XxrQqgBi/5Sxuq9soXzDtjIZ7w5pMfK"); + assert.strictEqual(bcrypt.hashSync("0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345", "$2b$05$CCCCCCCCCCCCCCCCCCCCC."), "$2b$05$CCCCCCCCCCCCCCCCCCCCC.XxrQqgBi/5Sxuq9soXzDtjIZ7w5pMfK"); + assert.done(); + }, + test_embedded_nulls: function(assert) { + assert.strictEqual(bcrypt.hashSync("Passw\0rd123", "$2b$05$CCCCCCCCCCCCCCCCCCCCC."), "$2b$05$CCCCCCCCCCCCCCCCCCCCC.VHy/kzL4sCcX3Ib3wN5rNGiRt.TpfxS"); + assert.strictEqual(bcrypt.hashSync("Passw\0 you can literally write anything after the NUL character", "$2b$05$CCCCCCCCCCCCCCCCCCCCC."), "$2b$05$CCCCCCCCCCCCCCCCCCCCC.4vJLJQ6nZ/70INTjjSZWQ0iyUek92tu"); + assert.strictEqual(bcrypt.hashSync(Buffer.from("Passw\0 you can literally write anything after the NUL character"), "$2b$05$CCCCCCCCCCCCCCCCCCCCC."), "$2b$05$CCCCCCCCCCCCCCCCCCCCC.4vJLJQ6nZ/70INTjjSZWQ0iyUek92tu"); + assert.done(); + }, + test_shorten_salt_to_128_bits: function(assert) { + assert.strictEqual(bcrypt.hashSync("test", "$2a$10$1234567899123456789012"), "$2a$10$123456789912345678901u.OtL1A1eGK5wmvBKUDYKvuVKI7h2XBu"); + assert.strictEqual(bcrypt.hashSync("U*U*", "$2a$05$CCCCCCCCCCCCCCCCCCCCCh"), "$2a$05$CCCCCCCCCCCCCCCCCCCCCeUQ7VjYZ2hd4bLYZdhuPpZMUpEUJDw1S"); + assert.strictEqual(bcrypt.hashSync("U*U*", "$2a$05$CCCCCCCCCCCCCCCCCCCCCM"), "$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK"); + assert.strictEqual(bcrypt.hashSync("U*U*", "$2a$05$CCCCCCCCCCCCCCCCCCCCCA"), "$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK"); + assert.done(); + }, + test_consistency: function(assert) { + assert.strictEqual(bcrypt.hashSync("ππππππππ", "$2a$10$.TtQJ4Jr6isd4Hp.mVfZeu"), "$2a$10$.TtQJ4Jr6isd4Hp.mVfZeuh6Gws4rOQ/vdBczhDx.19NFK0Y84Dle"); + assert.strictEqual(bcrypt.hashSync("p@5sw0rd", "$2b$12$zQ4CooEXdGqcwi0PHsgc8e"), "$2b$12$zQ4CooEXdGqcwi0PHsgc8eAf0DLXE/XHoBE8kCSGQ97rXwuClaPam"); + assert.strictEqual(bcrypt.hashSync("C'est bon, la vie!", "$2b$12$cbo7LZ.wxgW4yxAA5Vqlv."), "$2b$12$cbo7LZ.wxgW4yxAA5Vqlv.KR6QFPt4qCdc9RYJNXxa/rbUOp.1sw."); + assert.strictEqual(bcrypt.hashSync("ἓν οἶδα ὅτι οὐδὲν οἶδα", "$2b$12$LeHKWR2bmrazi/6P22Jpau"), "$2b$12$LeHKWR2bmrazi/6P22JpauX5my/eKwwKpWqL7L5iEByBnxNc76FRW"); + assert.strictEqual(bcrypt.hashSync(Buffer.from("ἓν οἶδα ὅτι οὐδὲν οἶδα"), "$2b$12$LeHKWR2bmrazi/6P22Jpau"), "$2b$12$LeHKWR2bmrazi/6P22JpauX5my/eKwwKpWqL7L5iEByBnxNc76FRW"); + bcrypt.hash(Buffer.from("ἓν οἶδα ὅτι οὐδὲν οἶδα"), "$2b$12$LeHKWR2bmrazi/6P22Jpau", function(err, hash) { + assert.strictEqual(hash, "$2b$12$LeHKWR2bmrazi/6P22JpauX5my/eKwwKpWqL7L5iEByBnxNc76FRW"); + assert.done(); + }); + } +} diff --git a/node_modules/bcrypt/test/promise.js b/node_modules/bcrypt/test/promise.js new file mode 100644 index 0000000..f640992 --- /dev/null +++ b/node_modules/bcrypt/test/promise.js @@ -0,0 +1,252 @@ +var bcrypt = require('../bcrypt'); +var promises = require('../promises'); + +var fail = function(assert, error) { + assert.ok(false, error); + assert.done(); +}; + +// only run these tests if Promise is available +if (typeof Promise !== 'undefined') { + module.exports = { + test_salt_returns_promise_on_no_args: function(assert) { + // make sure test passes with non-native implementations such as bluebird + // http://stackoverflow.com/questions/27746304/how-do-i-tell-if-an-object-is-a-promise + assert.strictEqual(typeof bcrypt.genSalt().then, 'function', "Should return a promise"); + assert.done(); + }, + test_salt_returns_promise_on_null_callback: function(assert) { + assert.strictEqual(typeof bcrypt.genSalt(13, null, null).then,'function', "Should return a promise"); + assert.done(); + }, + test_salt_length: function(assert) { + assert.expect(2); + bcrypt.genSalt(10).then(function(salt) { + assert.ok(salt,'salt must be defined'); + assert.strictEqual(29, salt.length, "Salt isn't the correct length."); + assert.done(); + }); + }, + test_salt_rounds_is_string_number: function(assert) { + assert.expect(1); + bcrypt.genSalt('10').then(function() { + fail(assert, "should not be resolved"); + }).catch(function(err) { + assert.ok((err instanceof Error), "Should be an Error. genSalt requires round to be of type number."); + }).then(function() { + assert.done(); + }); + }, + test_salt_rounds_is_string_non_number: function(assert) { + assert.expect(1); + bcrypt.genSalt('b').then(function() { + fail(assert, "should not be resolved"); + }).catch(function(err) { + assert.ok((err instanceof Error), "Should be an Error. genSalt requires round to be of type number."); + }).then(function() { + assert.done(); + }); + }, + test_hash_returns_promise_on_null_callback: function(assert) { + assert.strictEqual(typeof bcrypt.hash('password', 10, null).then,'function', "Should return a promise"); + assert.done(); + }, + test_hash: function(assert) { + assert.expect(1); + bcrypt.genSalt(10).then(function(salt) { + return bcrypt.hash('password', salt); + }).then(function(res) { + assert.ok(res, "Res should be defined."); + assert.done(); + }); + }, + test_hash_rounds: function(assert) { + assert.expect(1); + bcrypt.hash('bacon', 8).then(function(hash) { + assert.strictEqual(bcrypt.getRounds(hash), 8, "Number of rounds should be that specified in the function call."); + assert.done(); + }); + }, + test_hash_empty_strings: function(assert) { + assert.expect(2); + Promise.all([ + bcrypt.genSalt(10).then(function(salt) { + return bcrypt.hash('', salt); + }).then(function(res) { + assert.ok(res, "Res should be defined even with an empty pw."); + }), + bcrypt.hash('', '').then(function() { + fail(assert, "should not be resolved") + }).catch(function(err) { + assert.ok(err); + }), + ]).then(function() { + assert.done(); + }); + }, + test_hash_no_params: function(assert) { + assert.expect(1); + bcrypt.hash().then(function() { + fail(assert, "should not be resolved"); + }).catch(function(err) { + assert.ok(err, "Should be an error. No params."); + }).then(function() { + assert.done(); + }); + }, + test_hash_one_param: function(assert) { + assert.expect(1); + bcrypt.hash('password').then(function() { + fail(assert, "should not be resolved"); + }).catch(function(err) { + assert.ok(err, "Should be an error. No salt."); + }).then(function() { + assert.done(); + }); + }, + test_hash_salt_validity: function(assert) { + assert.expect(3); + Promise.all( + [ + bcrypt.hash('password', '$2a$10$somesaltyvaluertsetrse').then(function(enc) { + assert.ok(enc, "should be resolved with a value"); + }), + bcrypt.hash('password', 'some$value').then(function() { + fail(assert, "should not resolve"); + }).catch(function(err) { + assert.notEqual(err, undefined); + assert.strictEqual(err.message, "Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue"); + }) + ]).then(function() { + assert.done(); + }); + }, + test_verify_salt: function(assert) { + assert.expect(2); + bcrypt.genSalt(10).then(function(salt) { + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '10'); + assert.done(); + }); + }, + test_verify_salt_min_rounds: function(assert) { + assert.expect(2); + bcrypt.genSalt(1).then(function(salt) { + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '04'); + assert.done(); + }); + }, + test_verify_salt_max_rounds: function(assert) { + assert.expect(2); + bcrypt.genSalt(100).then(function(salt) { + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '31'); + assert.done(); + }); + }, + test_hash_compare_returns_promise_on_null_callback: function(assert) { + assert.strictEqual(typeof bcrypt.compare('password', 'something', null).then, 'function', "Should return a promise"); + assert.done(); + }, + test_hash_compare: function(assert) { + assert.expect(3); + bcrypt.genSalt(10).then(function(salt) { + assert.strictEqual(29, salt.length, "Salt isn't the correct length."); + return bcrypt.hash("test", salt); + }).then(function(hash) { + return Promise.all( + [ + bcrypt.compare("test", hash).then(function(res) { + assert.strictEqual(res, true, "These hashes should be equal."); + }), + bcrypt.compare("blah", hash).then(function(res) { + assert.strictEqual(res, false, "These hashes should not be equal."); + }) + ]).then(function() { + assert.done(); + }); + }); + }, + test_hash_compare_empty_strings: function(assert) { + assert.expect(2); + var hash = bcrypt.hashSync("test", bcrypt.genSaltSync(10)); + bcrypt.compare("", hash).then(function(res) { + assert.strictEqual(res, false, "These hashes should not be equal."); + return bcrypt.compare("", ""); + }).then(function(res) { + assert.strictEqual(res, false, "These hashes should not be equal."); + assert.done(); + }); + }, + test_hash_compare_invalid_strings: function(assert) { + var fullString = 'envy1362987212538'; + var hash = '$2a$10$XOPbrlUPQdwdJUpSrIF6X.LbE14qsMmKGhM1A8W9iqaG3vv1BD7WC'; + var wut = ':'; + Promise.all([ + bcrypt.compare(fullString, hash).then(function(res) { + assert.ok(res); + }), + bcrypt.compare(fullString, wut).then(function(res) { + assert.ok(!res); + }) + ]).then(function() { + assert.done(); + }); + }, + test_hash_compare_no_params: function(assert) { + assert.expect(1); + bcrypt.compare().then(function() { + fail(assert, 'Should not resolve'); + }).catch(function(err) { + assert.strictEqual(err.message, 'data and hash arguments required', 'Promise should be rejected when no parameters are supplied'); + }).then(function() { + assert.done(); + }); + }, + test_hash_compare_one_param: function(assert) { + assert.expect(1); + bcrypt.compare('password').then(function() { + fail(assert, 'Should not resolve'); + }).catch(function(err) { + assert.strictEqual(err.message, 'data and hash arguments required', 'Promise should be rejected when no parameters are supplied'); + }).then(function() { + assert.done(); + }); + }, + test_change_promise_impl_reject: function(assert) { + + promises.use({ + reject: function() { + return 'mock'; + } + }); + + assert.equal(promises.reject(), 'mock'); + + // need to reset the promise implementation because of require cache + promises.use(global.Promise); + assert.done(); + + }, + test_change_promise_impl_promise: function(assert) { + + promises.use({ + reject: function(err) { + assert.equal(err.message, 'fn must be a function'); + return 'mock'; + } + }); + + assert.equal(promises.promise('', '', ''), 'mock'); + + // need to reset the promise implementation because of require cache + promises.use(global.Promise); + assert.done(); + + } + }; +} diff --git a/node_modules/bcrypt/test/repetitions.js b/node_modules/bcrypt/test/repetitions.js new file mode 100644 index 0000000..f05b716 --- /dev/null +++ b/node_modules/bcrypt/test/repetitions.js @@ -0,0 +1,118 @@ +var bcrypt = require('../bcrypt'); + +var EXPECTED = 2500; //number of times to iterate these tests... + +module.exports = { + test_salt_length: function(assert) { + assert.expect(EXPECTED); + var n = 0; + for (var i = 0; i < EXPECTED; i++) { + bcrypt.genSalt(10, function(err, salt) { + assert.equals(29, salt.length, "Salt ("+salt+") isn't the correct length. It is: " + salt.length); + n++; + }); + } + + function checkVal() { + if (n == EXPECTED) { + assert.done(); + } else { + setTimeout(checkVal, 100); + } + } + setTimeout(checkVal, 100); + }, + test_hash_length: function(assert) { + assert.expect(EXPECTED); + var SALT = '$2a$04$TnjywYklQbbZjdjBgBoA4e'; + var n = 0; + for (var i = 0; i < EXPECTED; i++) { + bcrypt.hash('test', SALT, function(err, crypted) { + assert.equals(60, crypted.length, "Encrypted ("+crypted+") isn't the correct length. It is: " + crypted.length); + n++; + }); + } + + function checkVal() { + if (n == EXPECTED) { + assert.done(); + } else { + setTimeout(checkVal, 100); + } + } + setTimeout(checkVal, 100); + }, + test_compare: function(assert) { + assert.expect(EXPECTED); + var HASH = '$2a$04$TnjywYklQbbZjdjBgBoA4e9G7RJt9blgMgsCvUvus4Iv4TENB5nHy'; + var n = 0; + for (var i = 0; i < EXPECTED; i++) { + bcrypt.compare('test', HASH, function(err, match) { + assert.equal(true, match, "No match."); + n++; + }); + } + + function checkVal() { + if (n == EXPECTED) { + assert.done(); + } else { + setTimeout(checkVal, 100); + } + } + setTimeout(checkVal, 100); + }, + test_hash_and_compare: function(assert) { + assert.expect((EXPECTED-1)*3); + var salt = bcrypt.genSaltSync(4), + idx = 0, + good_done = false, + bad_done = false; + + function next() { + return test('secret' + Math.random()); + } + + function test(password) { + idx += 1; + return bcrypt.hash(password, salt, function(err, hash) { + if (err) throw err; + //console.log('\nbcrypt iter ' + idx); + + assert.ok(hash); + + bcrypt.compare(password, hash, function(err, res) { + //if (err) throw err; + assert.ok(res); + if (idx >= (EXPECTED-1)) { + good_done = true; + } + }); + + bcrypt.compare('bad' + password, hash, function(err, res) { + //if (err) throw err; + assert.ok(!res); + if (idx >= (EXPECTED-1)) { + bad_done = true; + } + }); + + if (idx < ((EXPECTED)-1)) { + next(); + } else { + function checkDone() { + if (idx >= (EXPECTED-1) && good_done && bad_done) { + assert.done(); + } else { + setTimeout(checkDone, 100); + } + } + + setTimeout(checkDone, 100); + } + }); + } + + next(); + } +}; diff --git a/node_modules/bcrypt/test/sync.js b/node_modules/bcrypt/test/sync.js new file mode 100644 index 0000000..0499823 --- /dev/null +++ b/node_modules/bcrypt/test/sync.js @@ -0,0 +1,137 @@ +var bcrypt = require('../bcrypt'); + +module.exports = { + test_salt_length: function(assert) { + var salt = bcrypt.genSaltSync(10); + assert.strictEqual(29, salt.length, "Salt isn't the correct length."); + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '10'); + assert.done(); + }, + test_salt_no_params: function(assert) { + // same as test_verify_salt except using default rounds of 10 + var salt = bcrypt.genSaltSync(); + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '10'); + assert.done(); + }, + test_salt_rounds_is_string_number: function(assert) { + assert.throws(function() {bcrypt.genSaltSync('10');}, "Should throw an Error. No params."); + assert.done(); + }, + test_salt_rounds_is_NaN: function(assert) { + assert.throws(function() {bcrypt.genSaltSync('b');}, "Should throw an Error. gen_salt requires rounds to be a number."); + assert.done(); + }, + test_salt_minor_a: function(assert) { + var salt = bcrypt.genSaltSync(10, 'a'); + assert.strictEqual(29, salt.length, "Salt isn't the correct length."); + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2a'); + assert.strictEqual(split_salt[2], '10'); + assert.done(); + }, + test_salt_minor_b: function(assert) { + var salt = bcrypt.genSaltSync(10, 'b'); + assert.strictEqual(29, salt.length, "Salt isn't the correct length."); + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '10'); + assert.done(); + }, + test_hash: function(assert) { + assert.ok(bcrypt.hashSync('password', bcrypt.genSaltSync(10)), "Shouldn't throw an Error."); + assert.done(); + }, + test_hash_rounds: function(assert) { + var hash = bcrypt.hashSync('password', 8); + assert.strictEqual(bcrypt.getRounds(hash), 8, "Number of rounds should equal 8."); + assert.done(); + }, + test_hash_empty_string: function(assert) { + assert.ok(bcrypt.hashSync('', bcrypt.genSaltSync(10)), "Shouldn't throw an Error."); + assert.throws(function() {bcrypt.hashSync('password', '')}, "Should have thrown an Error related to the salt."); + assert.throws(function() {bcrypt.hashSync('', '')}, "Should have thrown an Error related to the salt."); + assert.done(); + }, + test_hash_pw_no_params: function(assert) { + assert.throws(function() {bcrypt.hashSync();}, "Should throw an Error. No Params."); + assert.done(); + }, + test_hash_pw_one_param: function(assert) { + assert.throws(function() {bcrypt.hashSync('password');}, "Should throw an Error. No salt."); + assert.done(); + }, + test_hash_pw_not_hash_str: function(assert) { + assert.throws(function() {bcrypt.hashSync('password', {});}, "Should throw an Error. hash should be a string or number."); + assert.done(); + }, + test_hash_salt_validity: function(assert) { + assert.expect(2); + assert.ok(bcrypt.hashSync('password', '$2a$10$somesaltyvaluertsetrse')); + assert.throws(function() { + bcrypt.hashSync('password', 'some$value'); + }); + assert.done(); + }, + test_verify_salt: function(assert) { + var salt = bcrypt.genSaltSync(10); + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '10'); + assert.done(); + }, + test_verify_salt_min_rounds: function(assert) { + var salt = bcrypt.genSaltSync(1); + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '04'); + assert.done(); + }, + test_verify_salt_max_rounds: function(assert) { + var salt = bcrypt.genSaltSync(100); + var split_salt = salt.split('$'); + assert.strictEqual(split_salt[1], '2b'); + assert.strictEqual(split_salt[2], '31'); + assert.done(); + }, + test_hash_compare: function(assert) { + var salt = bcrypt.genSaltSync(10); + assert.strictEqual(29, salt.length, "Salt isn't the correct length."); + var hash = bcrypt.hashSync("test", salt); + assert.ok(bcrypt.compareSync("test", hash), "These hashes should be equal."); + assert.ok(!(bcrypt.compareSync("blah", hash)), "These hashes should not be equal."); + assert.done(); + }, + test_hash_compare_empty_strings: function(assert) { + assert.ok(!(bcrypt.compareSync("", "password")), "These hashes should not be equal."); + assert.ok(!(bcrypt.compareSync("", "")), "These hashes should not be equal."); + assert.ok(!(bcrypt.compareSync("password", "")), "These hashes should not be equal."); + assert.done(); + }, + test_hash_compare_invalid_strings: function(assert) { + var fullString = 'envy1362987212538'; + var hash = '$2a$10$XOPbrlUPQdwdJUpSrIF6X.LbE14qsMmKGhM1A8W9iqaG3vv1BD7WC'; + var wut = ':'; + bcrypt.compareSync(fullString, hash, function(err, res) { + assert.ok(res); + }); + bcrypt.compareSync(fullString, wut, function(err, res) { + assert.ok(!res) + }); + assert.done(); + }, + test_getRounds: function(assert) { + var hash = bcrypt.hashSync("test", bcrypt.genSaltSync(9)); + assert.strictEqual(9, bcrypt.getRounds(hash), "getRounds can't extract rounds"); + assert.done(); + }, + test_getRounds: function(assert) { + var hash = bcrypt.hashSync("test", bcrypt.genSaltSync(9)); + assert.strictEqual(9, bcrypt.getRounds(hash), "getRounds can't extract rounds"); + assert.throws(function() {bcrypt.getRounds(''); }, "Must pass a valid hash to getRounds"); + assert.done(); + } +}; diff --git a/node_modules/bcrypt/test_alpine.sh b/node_modules/bcrypt/test_alpine.sh new file mode 100644 index 0000000..f23af5c --- /dev/null +++ b/node_modules/bcrypt/test_alpine.sh @@ -0,0 +1,12 @@ +#!/bin/sh + +set -xe + +echo "Running on $(node -v)" + +apk add make g++ python +npm test --unsafe-perm + +./node_modules/.bin/node-pre-gyp configure +./node_modules/.bin/node-pre-gyp build +./node_modules/.bin/node-pre-gyp package diff --git a/node_modules/bcryptjs/.npmignore b/node_modules/bcryptjs/.npmignore new file mode 100644 index 0000000..e14a574 --- /dev/null +++ b/node_modules/bcryptjs/.npmignore @@ -0,0 +1,6 @@ +node_modules/ +npm-debug.log +debug.log +doco/ +tests/bench.js +*.png diff --git a/node_modules/bcryptjs/.travis.yml b/node_modules/bcryptjs/.travis.yml new file mode 100644 index 0000000..e2ed92d --- /dev/null +++ b/node_modules/bcryptjs/.travis.yml @@ -0,0 +1,18 @@ +language: node_js + +node_js: + - 0.10 + - 0.12 + - 4 + - 6 + +before_script: npm -g install testjs + +env: + - CXX=g++-4.8 +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-4.8 diff --git a/node_modules/bcryptjs/.vscode/settings.json b/node_modules/bcryptjs/.vscode/settings.json new file mode 100644 index 0000000..0c4a669 --- /dev/null +++ b/node_modules/bcryptjs/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "vsicons.presets.angular": false +} \ No newline at end of file diff --git a/node_modules/bcryptjs/LICENSE b/node_modules/bcryptjs/LICENSE new file mode 100644 index 0000000..3f6395f --- /dev/null +++ b/node_modules/bcryptjs/LICENSE @@ -0,0 +1,50 @@ +bcrypt.js +--------- +Copyright (c) 2012 Nevins Bartolomeo +Copyright (c) 2012 Shane Girish +Copyright (c) 2014 Daniel Wirtz + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +isaac.js +-------- +Copyright (c) 2012 Yves-Marie K. Rinquin + +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/bcryptjs/README.md b/node_modules/bcryptjs/README.md new file mode 100644 index 0000000..3fd7517 --- /dev/null +++ b/node_modules/bcryptjs/README.md @@ -0,0 +1,251 @@ +bcrypt.js +========= +Optimized bcrypt in JavaScript with zero dependencies. Compatible to the C++ [bcrypt](https://npmjs.org/package/bcrypt) +binding on node.js and also working in the browser. + +build static donate ❤ + + +Security considerations +----------------------- +Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the +iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with +increasing computation power. ([see](http://en.wikipedia.org/wiki/Bcrypt)) + +While bcrypt.js is compatible to the C++ bcrypt binding, it is written in pure JavaScript and thus slower ([about 30%](https://github.com/dcodeIO/bcrypt.js/wiki/Benchmark)), effectively reducing the number of iterations that can be +processed in an equal time span. + +The maximum input length is 72 bytes (note that UTF8 encoded characters use up to 4 bytes) and the length of generated +hashes is 60 characters. + +Usage +----- +The library is compatible with CommonJS and AMD loaders and is exposed globally as `dcodeIO.bcrypt` if neither is +available. + +### node.js + +On node.js, the inbuilt [crypto module](http://nodejs.org/api/crypto.html)'s randomBytes interface is used to obtain +secure random numbers. + +`npm install bcryptjs` + +```js +var bcrypt = require('bcryptjs'); +... +``` + +### Browser + +In the browser, bcrypt.js relies on [Web Crypto API](http://www.w3.org/TR/WebCryptoAPI)'s getRandomValues +interface to obtain secure random numbers. If no cryptographically secure source of randomness is available, you may +specify one through [bcrypt.setRandomFallback](https://github.com/dcodeIO/bcrypt.js#setrandomfallbackrandom). + +```js +var bcrypt = dcodeIO.bcrypt; +... +``` + +or + +```js +require.config({ + paths: { "bcrypt": "/path/to/bcrypt.js" } +}); +require(["bcrypt"], function(bcrypt) { + ... +}); +``` + +Usage - Sync +------------ +To hash a password: + +```javascript +var bcrypt = require('bcryptjs'); +var salt = bcrypt.genSaltSync(10); +var hash = bcrypt.hashSync("B4c0/\/", salt); +// Store hash in your password DB. +``` + +To check a password: + +```javascript +// Load hash from your password DB. +bcrypt.compareSync("B4c0/\/", hash); // true +bcrypt.compareSync("not_bacon", hash); // false +``` + +Auto-gen a salt and hash: + +```javascript +var hash = bcrypt.hashSync('bacon', 8); +``` + +Usage - Async +------------- +To hash a password: + +```javascript +var bcrypt = require('bcryptjs'); +bcrypt.genSalt(10, function(err, salt) { + bcrypt.hash("B4c0/\/", salt, function(err, hash) { + // Store hash in your password DB. + }); +}); +``` + +To check a password: + +```javascript +// Load hash from your password DB. +bcrypt.compare("B4c0/\/", hash, function(err, res) { + // res === true +}); +bcrypt.compare("not_bacon", hash, function(err, res) { + // res === false +}); + +// As of bcryptjs 2.4.0, compare returns a promise if callback is omitted: +bcrypt.compare("B4c0/\/", hash).then((res) => { + // res === true +}); +``` + +Auto-gen a salt and hash: + +```javascript +bcrypt.hash('bacon', 8, function(err, hash) { +}); +``` + +**Note:** Under the hood, asynchronisation splits a crypto operation into small chunks. After the completion of a chunk, the execution of the next chunk is placed on the back of [JS event loop queue](https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop), thus efficiently sharing the computational resources with the other operations in the queue. + +API +--- +### setRandomFallback(random) + +Sets the pseudo random number generator to use as a fallback if neither node's `crypto` module nor the Web Crypto +API is available. Please note: It is highly important that the PRNG used is cryptographically secure and that it is +seeded properly! + +| Parameter | Type | Description +|-----------------|-----------------|--------------- +| random | *function(number):!Array.<number>* | Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values. +| **@see** | | http://nodejs.org/api/crypto.html +| **@see** | | http://www.w3.org/TR/WebCryptoAPI/ + +**Hint:** You might use [isaac.js](https://github.com/rubycon/isaac.js) as a CSPRNG but you still have to make sure to +seed it properly. + +### genSaltSync(rounds=, seed_length=) + +Synchronously generates a salt. + +| Parameter | Type | Description +|-----------------|-----------------|--------------- +| rounds | *number* | Number of rounds to use, defaults to 10 if omitted +| seed_length | *number* | Not supported. +| **@returns** | *string* | Resulting salt +| **@throws** | *Error* | If a random fallback is required but not set + +### genSalt(rounds=, seed_length=, callback) + +Asynchronously generates a salt. + +| Parameter | Type | Description +|-----------------|-----------------|--------------- +| rounds | *number | function(Error, string=)* | Number of rounds to use, defaults to 10 if omitted +| seed_length | *number | function(Error, string=)* | Not supported. +| callback | *function(Error, string=)* | Callback receiving the error, if any, and the resulting salt +| **@returns** | *Promise* | If `callback` has been omitted +| **@throws** | *Error* | If `callback` is present but not a function + +### hashSync(s, salt=) + +Synchronously generates a hash for the given string. + +| Parameter | Type | Description +|-----------------|-----------------|--------------- +| s | *string* | String to hash +| salt | *number | string* | Salt length to generate or salt to use, default to 10 +| **@returns** | *string* | Resulting hash + +### hash(s, salt, callback, progressCallback=) + +Asynchronously generates a hash for the given string. + +| Parameter | Type | Description +|-----------------|-----------------|--------------- +| s | *string* | String to hash +| salt | *number | string* | Salt length to generate or salt to use +| callback | *function(Error, string=)* | Callback receiving the error, if any, and the resulting hash +| progressCallback | *function(number)* | Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms. +| **@returns** | *Promise* | If `callback` has been omitted +| **@throws** | *Error* | If `callback` is present but not a function + +### compareSync(s, hash) + +Synchronously tests a string against a hash. + +| Parameter | Type | Description +|-----------------|-----------------|--------------- +| s | *string* | String to compare +| hash | *string* | Hash to test against +| **@returns** | *boolean* | true if matching, otherwise false +| **@throws** | *Error* | If an argument is illegal + +### compare(s, hash, callback, progressCallback=) + +Asynchronously compares the given data against the given hash. + +| Parameter | Type | Description +|-----------------|-----------------|--------------- +| s | *string* | Data to compare +| hash | *string* | Data to be compared to +| callback | *function(Error, boolean)* | Callback receiving the error, if any, otherwise the result +| progressCallback | *function(number)* | Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms. +| **@returns** | *Promise* | If `callback` has been omitted +| **@throws** | *Error* | If `callback` is present but not a function + +### getRounds(hash) + +Gets the number of rounds used to encrypt the specified hash. + +| Parameter | Type | Description +|-----------------|-----------------|--------------- +| hash | *string* | Hash to extract the used number of rounds from +| **@returns** | *number* | Number of rounds used +| **@throws** | *Error* | If `hash` is not a string + +### getSalt(hash) + +Gets the salt portion from a hash. Does not validate the hash. + +| Parameter | Type | Description +|-----------------|-----------------|--------------- +| hash | *string* | Hash to extract the salt from +| **@returns** | *string* | Extracted salt part +| **@throws** | *Error* | If `hash` is not a string or otherwise invalid + + +Command line +------------ +`Usage: bcrypt [salt]` + +If the input has spaces inside, simply surround it with quotes. + +Downloads +--------- +* [Distributions](https://github.com/dcodeIO/bcrypt.js/tree/master/dist) +* [ZIP-Archive](https://github.com/dcodeIO/bcrypt.js/archive/master.zip) +* [Tarball](https://github.com/dcodeIO/bcrypt.js/tarball/master) + +Credits +------- +Based on work started by Shane Girish at [bcrypt-nodejs](https://github.com/shaneGirish/bcrypt-nodejs) (MIT-licensed), +which is itself based on [javascript-bcrypt](http://code.google.com/p/javascript-bcrypt/) (New BSD-licensed). + +License +------- +New-BSD / MIT ([see](https://github.com/dcodeIO/bcrypt.js/blob/master/LICENSE)) diff --git a/node_modules/bcryptjs/bin/bcrypt b/node_modules/bcryptjs/bin/bcrypt new file mode 100644 index 0000000..4cfc9d9 --- /dev/null +++ b/node_modules/bcryptjs/bin/bcrypt @@ -0,0 +1,25 @@ +#!/usr/bin/env node + +var path = require("path"), + bcrypt = require(path.join(__dirname, '..', 'index.js')), + pkg = require(path.join(__dirname, '..', 'package.json')); + +if (process.argv.length < 3) { + process.stderr.write([ // No dependencies, so we do it from hand. + "", + " |_ _ _ _ |_", + " |_)(_| \\/|_)|_ v"+pkg['version']+" (c) "+pkg['author'], + " / | " + ].join('\n')+'\n\n'+" Usage: "+path.basename(process.argv[1])+" [rounds|salt]\n"); + process.exit(1); +} else { + var salt; + if (process.argv.length > 3) { + salt = process.argv[3]; + var rounds = parseInt(salt, 10); + if (rounds == salt) + salt = bcrypt.genSaltSync(rounds); + } else + salt = bcrypt.genSaltSync(); + process.stdout.write(bcrypt.hashSync(process.argv[2], salt)+"\n"); +} diff --git a/node_modules/bcryptjs/bower.json b/node_modules/bcryptjs/bower.json new file mode 100644 index 0000000..c152405 --- /dev/null +++ b/node_modules/bcryptjs/bower.json @@ -0,0 +1,22 @@ +{ + "name": "bcryptjs", + "description": "Optimized bcrypt in plain JavaScript with zero dependencies.", + "version": "2.4.3", + "main": "dist/bcrypt.min.js", + "license": "New-BSD", + "homepage": "http://dcode.io/", + "repository": { + "type": "git", + "url": "git://github.com/dcodeIO/bcrypt.js.git" + }, + "keywords": ["bcrypt", "password", "auth", "authentication", "encryption", "crypt", "crypto"], + "dependencies": {}, + "devDependencies": {}, + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/node_modules/bcryptjs/dist/README.md b/node_modules/bcryptjs/dist/README.md new file mode 100644 index 0000000..4020f45 --- /dev/null +++ b/node_modules/bcryptjs/dist/README.md @@ -0,0 +1,15 @@ +Distributions +============= +bcrypt.js is available as the following distributions: + +* **[bcrypt.js](https://github.com/dcodeIO/bcrypt.js/blob/master/dist/bcrypt.js)** + contains the commented source code. + +* **[bcrypt.min.js](https://github.com/dcodeIO/bcrypt.js/blob/master/dist/bcrypt.min.js)** + has been compiled with Closure Compiler using advanced optimizations. + +* **[bcrypt.min.map](https://github.com/dcodeIO/bcrypt.js/blob/master/dist/bcrypt.min.map)** + contains the source map generated by Closure Compiler. + +* **[bcrypt.min.js.gz](https://github.com/dcodeIO/bcrypt.js/blob/master/dist/bcrypt.min.js.gz)** + has also been gzipped using `-9`. diff --git a/node_modules/bcryptjs/dist/bcrypt.js b/node_modules/bcryptjs/dist/bcrypt.js new file mode 100644 index 0000000..a50dbee --- /dev/null +++ b/node_modules/bcryptjs/dist/bcrypt.js @@ -0,0 +1,1379 @@ +/* + Copyright (c) 2012 Nevins Bartolomeo + Copyright (c) 2012 Shane Girish + Copyright (c) 2014 Daniel Wirtz + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @license bcrypt.js (c) 2013 Daniel Wirtz + * Released under the Apache License, Version 2.0 + * see: https://github.com/dcodeIO/bcrypt.js for details + */ +(function(global, factory) { + + /* AMD */ if (typeof define === 'function' && define["amd"]) + define([], factory); + /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"]) + module["exports"] = factory(); + /* Global */ else + (global["dcodeIO"] = global["dcodeIO"] || {})["bcrypt"] = factory(); + +}(this, function() { + "use strict"; + + /** + * bcrypt namespace. + * @type {Object.} + */ + var bcrypt = {}; + + /** + * The random implementation to use as a fallback. + * @type {?function(number):!Array.} + * @inner + */ + var randomFallback = null; + + /** + * Generates cryptographically secure random bytes. + * @function + * @param {number} len Bytes length + * @returns {!Array.} Random bytes + * @throws {Error} If no random implementation is available + * @inner + */ + function random(len) { + /* node */ if (typeof module !== 'undefined' && module && module['exports']) + try { + return require("crypto")['randomBytes'](len); + } catch (e) {} + /* WCA */ try { + var a; (self['crypto']||self['msCrypto'])['getRandomValues'](a = new Uint32Array(len)); + return Array.prototype.slice.call(a); + } catch (e) {} + /* fallback */ if (!randomFallback) + throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative"); + return randomFallback(len); + } + + // Test if any secure randomness source is available + var randomAvailable = false; + try { + random(1); + randomAvailable = true; + } catch (e) {} + + // Default fallback, if any + randomFallback = null; + /** + * Sets the pseudo random number generator to use as a fallback if neither node's `crypto` module nor the Web Crypto + * API is available. Please note: It is highly important that the PRNG used is cryptographically secure and that it + * is seeded properly! + * @param {?function(number):!Array.} random Function taking the number of bytes to generate as its + * sole argument, returning the corresponding array of cryptographically secure random byte values. + * @see http://nodejs.org/api/crypto.html + * @see http://www.w3.org/TR/WebCryptoAPI/ + */ + bcrypt.setRandomFallback = function(random) { + randomFallback = random; + }; + + /** + * Synchronously generates a salt. + * @param {number=} rounds Number of rounds to use, defaults to 10 if omitted + * @param {number=} seed_length Not supported. + * @returns {string} Resulting salt + * @throws {Error} If a random fallback is required but not set + * @expose + */ + bcrypt.genSaltSync = function(rounds, seed_length) { + rounds = rounds || GENSALT_DEFAULT_LOG2_ROUNDS; + if (typeof rounds !== 'number') + throw Error("Illegal arguments: "+(typeof rounds)+", "+(typeof seed_length)); + if (rounds < 4) + rounds = 4; + else if (rounds > 31) + rounds = 31; + var salt = []; + salt.push("$2a$"); + if (rounds < 10) + salt.push("0"); + salt.push(rounds.toString()); + salt.push('$'); + salt.push(base64_encode(random(BCRYPT_SALT_LEN), BCRYPT_SALT_LEN)); // May throw + return salt.join(''); + }; + + /** + * Asynchronously generates a salt. + * @param {(number|function(Error, string=))=} rounds Number of rounds to use, defaults to 10 if omitted + * @param {(number|function(Error, string=))=} seed_length Not supported. + * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting salt + * @returns {!Promise} If `callback` has been omitted + * @throws {Error} If `callback` is present but not a function + * @expose + */ + bcrypt.genSalt = function(rounds, seed_length, callback) { + if (typeof seed_length === 'function') + callback = seed_length, + seed_length = undefined; // Not supported. + if (typeof rounds === 'function') + callback = rounds, + rounds = undefined; + if (typeof rounds === 'undefined') + rounds = GENSALT_DEFAULT_LOG2_ROUNDS; + else if (typeof rounds !== 'number') + throw Error("illegal arguments: "+(typeof rounds)); + + function _async(callback) { + nextTick(function() { // Pretty thin, but salting is fast enough + try { + callback(null, bcrypt.genSaltSync(rounds)); + } catch (err) { + callback(err); + } + }); + } + + if (callback) { + if (typeof callback !== 'function') + throw Error("Illegal callback: "+typeof(callback)); + _async(callback); + } else + return new Promise(function(resolve, reject) { + _async(function(err, res) { + if (err) { + reject(err); + return; + } + resolve(res); + }); + }); + }; + + /** + * Synchronously generates a hash for the given string. + * @param {string} s String to hash + * @param {(number|string)=} salt Salt length to generate or salt to use, default to 10 + * @returns {string} Resulting hash + * @expose + */ + bcrypt.hashSync = function(s, salt) { + if (typeof salt === 'undefined') + salt = GENSALT_DEFAULT_LOG2_ROUNDS; + if (typeof salt === 'number') + salt = bcrypt.genSaltSync(salt); + if (typeof s !== 'string' || typeof salt !== 'string') + throw Error("Illegal arguments: "+(typeof s)+', '+(typeof salt)); + return _hash(s, salt); + }; + + /** + * Asynchronously generates a hash for the given string. + * @param {string} s String to hash + * @param {number|string} salt Salt length to generate or salt to use + * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash + * @param {function(number)=} progressCallback Callback successively called with the percentage of rounds completed + * (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms. + * @returns {!Promise} If `callback` has been omitted + * @throws {Error} If `callback` is present but not a function + * @expose + */ + bcrypt.hash = function(s, salt, callback, progressCallback) { + + function _async(callback) { + if (typeof s === 'string' && typeof salt === 'number') + bcrypt.genSalt(salt, function(err, salt) { + _hash(s, salt, callback, progressCallback); + }); + else if (typeof s === 'string' && typeof salt === 'string') + _hash(s, salt, callback, progressCallback); + else + nextTick(callback.bind(this, Error("Illegal arguments: "+(typeof s)+', '+(typeof salt)))); + } + + if (callback) { + if (typeof callback !== 'function') + throw Error("Illegal callback: "+typeof(callback)); + _async(callback); + } else + return new Promise(function(resolve, reject) { + _async(function(err, res) { + if (err) { + reject(err); + return; + } + resolve(res); + }); + }); + }; + + /** + * Compares two strings of the same length in constant time. + * @param {string} known Must be of the correct length + * @param {string} unknown Must be the same length as `known` + * @returns {boolean} + * @inner + */ + function safeStringCompare(known, unknown) { + var right = 0, + wrong = 0; + for (var i=0, k=known.length; i} UTF8 bytes + * @inner + */ + function stringToBytes(str) { + var out = [], + i = 0; + utfx.encodeUTF16toUTF8(function() { + if (i >= str.length) return null; + return str.charCodeAt(i++); + }, function(b) { + out.push(b); + }); + return out; + } + + // A base64 implementation for the bcrypt algorithm. This is partly non-standard. + + /** + * bcrypt's own non-standard base64 dictionary. + * @type {!Array.} + * @const + * @inner + **/ + var BASE64_CODE = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(''); + + /** + * @type {!Array.} + * @const + * @inner + **/ + var BASE64_INDEX = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, + 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, + -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1]; + + /** + * @type {!function(...number):string} + * @inner + */ + var stringFromCharCode = String.fromCharCode; + + /** + * Encodes a byte array to base64 with up to len bytes of input. + * @param {!Array.} b Byte array + * @param {number} len Maximum input length + * @returns {string} + * @inner + */ + function base64_encode(b, len) { + var off = 0, + rs = [], + c1, c2; + if (len <= 0 || len > b.length) + throw Error("Illegal len: "+len); + while (off < len) { + c1 = b[off++] & 0xff; + rs.push(BASE64_CODE[(c1 >> 2) & 0x3f]); + c1 = (c1 & 0x03) << 4; + if (off >= len) { + rs.push(BASE64_CODE[c1 & 0x3f]); + break; + } + c2 = b[off++] & 0xff; + c1 |= (c2 >> 4) & 0x0f; + rs.push(BASE64_CODE[c1 & 0x3f]); + c1 = (c2 & 0x0f) << 2; + if (off >= len) { + rs.push(BASE64_CODE[c1 & 0x3f]); + break; + } + c2 = b[off++] & 0xff; + c1 |= (c2 >> 6) & 0x03; + rs.push(BASE64_CODE[c1 & 0x3f]); + rs.push(BASE64_CODE[c2 & 0x3f]); + } + return rs.join(''); + } + + /** + * Decodes a base64 encoded string to up to len bytes of output. + * @param {string} s String to decode + * @param {number} len Maximum output length + * @returns {!Array.} + * @inner + */ + function base64_decode(s, len) { + var off = 0, + slen = s.length, + olen = 0, + rs = [], + c1, c2, c3, c4, o, code; + if (len <= 0) + throw Error("Illegal len: "+len); + while (off < slen - 1 && olen < len) { + code = s.charCodeAt(off++); + c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + code = s.charCodeAt(off++); + c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + if (c1 == -1 || c2 == -1) + break; + o = (c1 << 2) >>> 0; + o |= (c2 & 0x30) >> 4; + rs.push(stringFromCharCode(o)); + if (++olen >= len || off >= slen) + break; + code = s.charCodeAt(off++); + c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + if (c3 == -1) + break; + o = ((c2 & 0x0f) << 4) >>> 0; + o |= (c3 & 0x3c) >> 2; + rs.push(stringFromCharCode(o)); + if (++olen >= len || off >= slen) + break; + code = s.charCodeAt(off++); + c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + o = ((c3 & 0x03) << 6) >>> 0; + o |= c4; + rs.push(stringFromCharCode(o)); + ++olen; + } + var res = []; + for (off = 0; off + * Released under the Apache License, Version 2.0 + * see: https://github.com/dcodeIO/utfx for details + */ + var utfx = function() { + "use strict"; + + /** + * utfx namespace. + * @inner + * @type {!Object.} + */ + var utfx = {}; + + /** + * Maximum valid code point. + * @type {number} + * @const + */ + utfx.MAX_CODEPOINT = 0x10FFFF; + + /** + * Encodes UTF8 code points to UTF8 bytes. + * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point + * respectively `null` if there are no more code points left or a single numeric code point. + * @param {!function(number)} dst Bytes destination as a function successively called with the next byte + */ + utfx.encodeUTF8 = function(src, dst) { + var cp = null; + if (typeof src === 'number') + cp = src, + src = function() { return null; }; + while (cp !== null || (cp = src()) !== null) { + if (cp < 0x80) + dst(cp&0x7F); + else if (cp < 0x800) + dst(((cp>>6)&0x1F)|0xC0), + dst((cp&0x3F)|0x80); + else if (cp < 0x10000) + dst(((cp>>12)&0x0F)|0xE0), + dst(((cp>>6)&0x3F)|0x80), + dst((cp&0x3F)|0x80); + else + dst(((cp>>18)&0x07)|0xF0), + dst(((cp>>12)&0x3F)|0x80), + dst(((cp>>6)&0x3F)|0x80), + dst((cp&0x3F)|0x80); + cp = null; + } + }; + + /** + * Decodes UTF8 bytes to UTF8 code points. + * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there + * are no more bytes left. + * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point. + * @throws {RangeError} If a starting byte is invalid in UTF8 + * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the + * remaining bytes. + */ + utfx.decodeUTF8 = function(src, dst) { + var a, b, c, d, fail = function(b) { + b = b.slice(0, b.indexOf(null)); + var err = Error(b.toString()); + err.name = "TruncatedError"; + err['bytes'] = b; + throw err; + }; + while ((a = src()) !== null) { + if ((a&0x80) === 0) + dst(a); + else if ((a&0xE0) === 0xC0) + ((b = src()) === null) && fail([a, b]), + dst(((a&0x1F)<<6) | (b&0x3F)); + else if ((a&0xF0) === 0xE0) + ((b=src()) === null || (c=src()) === null) && fail([a, b, c]), + dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F)); + else if ((a&0xF8) === 0xF0) + ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]), + dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F)); + else throw RangeError("Illegal starting byte: "+a); + } + }; + + /** + * Converts UTF16 characters to UTF8 code points. + * @param {!function():number|null} src Characters source as a function returning the next char code respectively + * `null` if there are no more characters left. + * @param {!function(number)} dst Code points destination as a function successively called with each converted code + * point. + */ + utfx.UTF16toUTF8 = function(src, dst) { + var c1, c2 = null; + while (true) { + if ((c1 = c2 !== null ? c2 : src()) === null) + break; + if (c1 >= 0xD800 && c1 <= 0xDFFF) { + if ((c2 = src()) !== null) { + if (c2 >= 0xDC00 && c2 <= 0xDFFF) { + dst((c1-0xD800)*0x400+c2-0xDC00+0x10000); + c2 = null; continue; + } + } + } + dst(c1); + } + if (c2 !== null) dst(c2); + }; + + /** + * Converts UTF8 code points to UTF16 characters. + * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point + * respectively `null` if there are no more code points left or a single numeric code point. + * @param {!function(number)} dst Characters destination as a function successively called with each converted char code. + * @throws {RangeError} If a code point is out of range + */ + utfx.UTF8toUTF16 = function(src, dst) { + var cp = null; + if (typeof src === 'number') + cp = src, src = function() { return null; }; + while (cp !== null || (cp = src()) !== null) { + if (cp <= 0xFFFF) + dst(cp); + else + cp -= 0x10000, + dst((cp>>10)+0xD800), + dst((cp%0x400)+0xDC00); + cp = null; + } + }; + + /** + * Converts and encodes UTF16 characters to UTF8 bytes. + * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null` + * if there are no more characters left. + * @param {!function(number)} dst Bytes destination as a function successively called with the next byte. + */ + utfx.encodeUTF16toUTF8 = function(src, dst) { + utfx.UTF16toUTF8(src, function(cp) { + utfx.encodeUTF8(cp, dst); + }); + }; + + /** + * Decodes and converts UTF8 bytes to UTF16 characters. + * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there + * are no more bytes left. + * @param {!function(number)} dst Characters destination as a function successively called with each converted char code. + * @throws {RangeError} If a starting byte is invalid in UTF8 + * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes. + */ + utfx.decodeUTF8toUTF16 = function(src, dst) { + utfx.decodeUTF8(src, function(cp) { + utfx.UTF8toUTF16(cp, dst); + }); + }; + + /** + * Calculates the byte length of an UTF8 code point. + * @param {number} cp UTF8 code point + * @returns {number} Byte length + */ + utfx.calculateCodePoint = function(cp) { + return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4; + }; + + /** + * Calculates the number of UTF8 bytes required to store UTF8 code points. + * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively + * `null` if there are no more code points left. + * @returns {number} The number of UTF8 bytes required + */ + utfx.calculateUTF8 = function(src) { + var cp, l=0; + while ((cp = src()) !== null) + l += utfx.calculateCodePoint(cp); + return l; + }; + + /** + * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes. + * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively + * `null` if there are no more characters left. + * @returns {!Array.} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1. + */ + utfx.calculateUTF16asUTF8 = function(src) { + var n=0, l=0; + utfx.UTF16toUTF8(src, function(cp) { + ++n; l += utfx.calculateCodePoint(cp); + }); + return [n,l]; + }; + + return utfx; + }(); + + Date.now = Date.now || function() { return +new Date; }; + + /** + * @type {number} + * @const + * @inner + */ + var BCRYPT_SALT_LEN = 16; + + /** + * @type {number} + * @const + * @inner + */ + var GENSALT_DEFAULT_LOG2_ROUNDS = 10; + + /** + * @type {number} + * @const + * @inner + */ + var BLOWFISH_NUM_ROUNDS = 16; + + /** + * @type {number} + * @const + * @inner + */ + var MAX_EXECUTION_TIME = 100; + + /** + * @type {Array.} + * @const + * @inner + */ + var P_ORIG = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, + 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, + 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, + 0xb5470917, 0x9216d5d9, 0x8979fb1b + ]; + + /** + * @type {Array.} + * @const + * @inner + */ + var S_ORIG = [ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, + 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, + 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, + 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, + 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, + 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, + 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, + 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, + 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, + 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, + 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, + 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, + 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, + 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, + 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, + 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, + 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, + 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, + 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, + 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, + 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, + 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, + 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, + 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, + 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, + 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, + 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, + 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, + 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, + 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, + 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, + 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, + 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, + 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, + 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, + 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, + 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, + 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, + 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, + 0x6e85076a, 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, + 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, + 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, + 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, + 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, + 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, + 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, + 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, + 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, + 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, + 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, + 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, + 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, + 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, + 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, + 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, + 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, + 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, + 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, + 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, + 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, + 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, + 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, + 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, + 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, + 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, + 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, + 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, + 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, + 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, + 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, + 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, + 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, + 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, + 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, + 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, + 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, + 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, + 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c, + 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, + 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, + 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, + 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, + 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, + 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, + 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, + 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, + 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, + 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, + 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, + 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, + 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, + 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, + 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, + 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, + 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, + 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, + 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, + 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, + 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, + 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, + 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, + 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, + 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, + 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, + 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, + 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, + 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, + 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, + 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, + 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, + 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, + 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, + 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, + 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, + 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, + 0x92638212, 0x670efa8e, 0x406000e0, 0x3a39ce37, 0xd3faf5cf, + 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, + 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, + 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, + 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, + 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, + 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, + 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, + 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, + 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, + 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, + 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, + 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, + 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, + 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, + 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, + 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, + 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, + 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, + 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, + 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, + 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, + 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, + 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, + 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, + 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, + 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, + 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, + 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, + 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, + 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, + 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, + 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, + 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, + 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, + 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, + 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, + 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, + 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + ]; + + /** + * @type {Array.} + * @const + * @inner + */ + var C_ORIG = [ + 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, + 0x6f756274 + ]; + + /** + * @param {Array.} lr + * @param {number} off + * @param {Array.} P + * @param {Array.} S + * @returns {Array.} + * @inner + */ + function _encipher(lr, off, P, S) { // This is our bottleneck: 1714/1905 ticks / 90% - see profile.txt + var n, + l = lr[off], + r = lr[off + 1]; + + l ^= P[0]; + + /* + for (var i=0, k=BLOWFISH_NUM_ROUNDS-2; i<=k;) + // Feistel substitution on left word + n = S[l >>> 24], + n += S[0x100 | ((l >> 16) & 0xff)], + n ^= S[0x200 | ((l >> 8) & 0xff)], + n += S[0x300 | (l & 0xff)], + r ^= n ^ P[++i], + // Feistel substitution on right word + n = S[r >>> 24], + n += S[0x100 | ((r >> 16) & 0xff)], + n ^= S[0x200 | ((r >> 8) & 0xff)], + n += S[0x300 | (r & 0xff)], + l ^= n ^ P[++i]; + */ + + //The following is an unrolled version of the above loop. + //Iteration 0 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[1]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[2]; + //Iteration 1 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[3]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[4]; + //Iteration 2 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[5]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[6]; + //Iteration 3 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[7]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[8]; + //Iteration 4 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[9]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[10]; + //Iteration 5 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[11]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[12]; + //Iteration 6 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[13]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[14]; + //Iteration 7 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[15]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[16]; + + lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1]; + lr[off + 1] = l; + return lr; + } + + /** + * @param {Array.} data + * @param {number} offp + * @returns {{key: number, offp: number}} + * @inner + */ + function _streamtoword(data, offp) { + for (var i = 0, word = 0; i < 4; ++i) + word = (word << 8) | (data[offp] & 0xff), + offp = (offp + 1) % data.length; + return { key: word, offp: offp }; + } + + /** + * @param {Array.} key + * @param {Array.} P + * @param {Array.} S + * @inner + */ + function _key(key, P, S) { + var offset = 0, + lr = [0, 0], + plen = P.length, + slen = S.length, + sw; + for (var i = 0; i < plen; i++) + sw = _streamtoword(key, offset), + offset = sw.offp, + P[i] = P[i] ^ sw.key; + for (i = 0; i < plen; i += 2) + lr = _encipher(lr, 0, P, S), + P[i] = lr[0], + P[i + 1] = lr[1]; + for (i = 0; i < slen; i += 2) + lr = _encipher(lr, 0, P, S), + S[i] = lr[0], + S[i + 1] = lr[1]; + } + + /** + * Expensive key schedule Blowfish. + * @param {Array.} data + * @param {Array.} key + * @param {Array.} P + * @param {Array.} S + * @inner + */ + function _ekskey(data, key, P, S) { + var offp = 0, + lr = [0, 0], + plen = P.length, + slen = S.length, + sw; + for (var i = 0; i < plen; i++) + sw = _streamtoword(key, offp), + offp = sw.offp, + P[i] = P[i] ^ sw.key; + offp = 0; + for (i = 0; i < plen; i += 2) + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[0] ^= sw.key, + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[1] ^= sw.key, + lr = _encipher(lr, 0, P, S), + P[i] = lr[0], + P[i + 1] = lr[1]; + for (i = 0; i < slen; i += 2) + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[0] ^= sw.key, + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[1] ^= sw.key, + lr = _encipher(lr, 0, P, S), + S[i] = lr[0], + S[i + 1] = lr[1]; + } + + /** + * Internaly crypts a string. + * @param {Array.} b Bytes to crypt + * @param {Array.} salt Salt bytes to use + * @param {number} rounds Number of rounds + * @param {function(Error, Array.=)=} callback Callback receiving the error, if any, and the resulting bytes. If + * omitted, the operation will be performed synchronously. + * @param {function(number)=} progressCallback Callback called with the current progress + * @returns {!Array.|undefined} Resulting bytes if callback has been omitted, otherwise `undefined` + * @inner + */ + function _crypt(b, salt, rounds, callback, progressCallback) { + var cdata = C_ORIG.slice(), + clen = cdata.length, + err; + + // Validate + if (rounds < 4 || rounds > 31) { + err = Error("Illegal number of rounds (4-31): "+rounds); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + if (salt.length !== BCRYPT_SALT_LEN) { + err =Error("Illegal salt length: "+salt.length+" != "+BCRYPT_SALT_LEN); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + rounds = (1 << rounds) >>> 0; + + var P, S, i = 0, j; + + //Use typed arrays when available - huge speedup! + if (Int32Array) { + P = new Int32Array(P_ORIG); + S = new Int32Array(S_ORIG); + } else { + P = P_ORIG.slice(); + S = S_ORIG.slice(); + } + + _ekskey(salt, b, P, S); + + /** + * Calcualtes the next round. + * @returns {Array.|undefined} Resulting array if callback has been omitted, otherwise `undefined` + * @inner + */ + function next() { + if (progressCallback) + progressCallback(i / rounds); + if (i < rounds) { + var start = Date.now(); + for (; i < rounds;) { + i = i + 1; + _key(b, P, S); + _key(salt, P, S); + if (Date.now() - start > MAX_EXECUTION_TIME) + break; + } + } else { + for (i = 0; i < 64; i++) + for (j = 0; j < (clen >> 1); j++) + _encipher(cdata, j << 1, P, S); + var ret = []; + for (i = 0; i < clen; i++) + ret.push(((cdata[i] >> 24) & 0xff) >>> 0), + ret.push(((cdata[i] >> 16) & 0xff) >>> 0), + ret.push(((cdata[i] >> 8) & 0xff) >>> 0), + ret.push((cdata[i] & 0xff) >>> 0); + if (callback) { + callback(null, ret); + return; + } else + return ret; + } + if (callback) + nextTick(next); + } + + // Async + if (typeof callback !== 'undefined') { + next(); + + // Sync + } else { + var res; + while (true) + if (typeof(res = next()) !== 'undefined') + return res || []; + } + } + + /** + * Internally hashes a string. + * @param {string} s String to hash + * @param {?string} salt Salt to use, actually never null + * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash. If omitted, + * hashing is perormed synchronously. + * @param {function(number)=} progressCallback Callback called with the current progress + * @returns {string|undefined} Resulting hash if callback has been omitted, otherwise `undefined` + * @inner + */ + function _hash(s, salt, callback, progressCallback) { + var err; + if (typeof s !== 'string' || typeof salt !== 'string') { + err = Error("Invalid string / salt: Not a string"); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } + else + throw err; + } + + // Validate the salt + var minor, offset; + if (salt.charAt(0) !== '$' || salt.charAt(1) !== '2') { + err = Error("Invalid salt version: "+salt.substring(0,2)); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } + else + throw err; + } + if (salt.charAt(2) === '$') + minor = String.fromCharCode(0), + offset = 3; + else { + minor = salt.charAt(2); + if ((minor !== 'a' && minor !== 'b' && minor !== 'y') || salt.charAt(3) !== '$') { + err = Error("Invalid salt revision: "+salt.substring(2,4)); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + offset = 4; + } + + // Extract number of rounds + if (salt.charAt(offset + 2) > '$') { + err = Error("Missing salt rounds"); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + var r1 = parseInt(salt.substring(offset, offset + 1), 10) * 10, + r2 = parseInt(salt.substring(offset + 1, offset + 2), 10), + rounds = r1 + r2, + real_salt = salt.substring(offset + 3, offset + 25); + s += minor >= 'a' ? "\x00" : ""; + + var passwordb = stringToBytes(s), + saltb = base64_decode(real_salt, BCRYPT_SALT_LEN); + + /** + * Finishes hashing. + * @param {Array.} bytes Byte array + * @returns {string} + * @inner + */ + function finish(bytes) { + var res = []; + res.push("$2"); + if (minor >= 'a') + res.push(minor); + res.push("$"); + if (rounds < 10) + res.push("0"); + res.push(rounds.toString()); + res.push("$"); + res.push(base64_encode(saltb, saltb.length)); + res.push(base64_encode(bytes, C_ORIG.length * 4 - 1)); + return res.join(''); + } + + // Sync + if (typeof callback == 'undefined') + return finish(_crypt(passwordb, saltb, rounds)); + + // Async + else { + _crypt(passwordb, saltb, rounds, function(err, bytes) { + if (err) + callback(err, null); + else + callback(null, finish(bytes)); + }, progressCallback); + } + } + + /** + * Encodes a byte array to base64 with up to len bytes of input, using the custom bcrypt alphabet. + * @function + * @param {!Array.} b Byte array + * @param {number} len Maximum input length + * @returns {string} + * @expose + */ + bcrypt.encodeBase64 = base64_encode; + + /** + * Decodes a base64 encoded string to up to len bytes of output, using the custom bcrypt alphabet. + * @function + * @param {string} s String to decode + * @param {number} len Maximum output length + * @returns {!Array.} + * @expose + */ + bcrypt.decodeBase64 = base64_decode; + + return bcrypt; +})); diff --git a/node_modules/bcryptjs/dist/bcrypt.min.js b/node_modules/bcryptjs/dist/bcrypt.min.js new file mode 100644 index 0000000..0fd2f1e --- /dev/null +++ b/node_modules/bcryptjs/dist/bcrypt.min.js @@ -0,0 +1,48 @@ +/* + bcrypt.js (c) 2013 Daniel Wirtz + Released under the Apache License, Version 2.0 + see: https://github.com/dcodeIO/bcrypt.js for details +*/ +(function(u,r){"function"===typeof define&&define.amd?define([],r):"function"===typeof require&&"object"===typeof module&&module&&module.exports?module.exports=r():(u.dcodeIO=u.dcodeIO||{}).bcrypt=r()})(this,function(){function u(e){if("undefined"!==typeof module&&module&&module.exports)try{return require("crypto").randomBytes(e)}catch(d){}try{var c;(self.crypto||self.msCrypto).getRandomValues(c=new Uint32Array(e));return Array.prototype.slice.call(c)}catch(b){}if(!w)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative"); +return w(e)}function r(e,d){for(var c=0,b=0,a=0,f=e.length;ac?!1:0===b}function H(e){var d=[],c=0;I.encodeUTF16toUTF8(function(){return c>=e.length?null:e.charCodeAt(c++)},function(b){d.push(b)});return d}function x(e,d){var c=0,b=[],a,f;if(0>=d||d>e.length)throw Error("Illegal len: "+d);for(;c>2&63]);a=(a&3)<<4;if(c>=d){b.push(s[a&63]);break}f=e[c++]&255;a|=f>>4&15;b.push(s[a&63]);a=(f&15)<<2;if(c>=d){b.push(s[a& +63]);break}f=e[c++]&255;a|=f>>6&3;b.push(s[a&63]);b.push(s[f&63])}return b.join("")}function B(e,d){var c=0,b=e.length,a=0,f=[],g,m,h;if(0>=d)throw Error("Illegal len: "+d);for(;c>>0;h|=(m&48)>>4;f.push(z(h));if(++a>=d||c>=b)break;h=e.charCodeAt(c++);g=h>>0;h|=(g&60)>>2;f.push(z(h));if(++a>=d||c>=b)break;h=e.charCodeAt(c++);m=h>>0;h|=m;f.push(z(h));++a}b=[];for(c=0;c>>24];a+=b[256|f>>16&255];a^=b[512|f>>8&255];a+=b[768|f&255];g=g^a^c[1];a=b[g>>>24];a+=b[256|g>>16&255];a^=b[512|g>>8&255];a+=b[768|g&255];f=f^a^c[2];a=b[f>>>24];a+=b[256|f>>16&255];a^=b[512|f>>8&255];a+=b[768|f&255];g=g^a^c[3];a=b[g>>>24];a+=b[256|g>>16&255];a^=b[512|g>>8&255];a+=b[768|g&255];f=f^a^c[4];a=b[f>>>24];a+=b[256|f>>16&255];a^=b[512| +f>>8&255];a+=b[768|f&255];g=g^a^c[5];a=b[g>>>24];a+=b[256|g>>16&255];a^=b[512|g>>8&255];a+=b[768|g&255];f=f^a^c[6];a=b[f>>>24];a+=b[256|f>>16&255];a^=b[512|f>>8&255];a+=b[768|f&255];g=g^a^c[7];a=b[g>>>24];a+=b[256|g>>16&255];a^=b[512|g>>8&255];a+=b[768|g&255];f=f^a^c[8];a=b[f>>>24];a+=b[256|f>>16&255];a^=b[512|f>>8&255];a+=b[768|f&255];g=g^a^c[9];a=b[g>>>24];a+=b[256|g>>16&255];a^=b[512|g>>8&255];a+=b[768|g&255];f=f^a^c[10];a=b[f>>>24];a+=b[256|f>>16&255];a^=b[512|f>>8&255];a+=b[768|f&255];g=g^a^ +c[11];a=b[g>>>24];a+=b[256|g>>16&255];a^=b[512|g>>8&255];a+=b[768|g&255];f=f^a^c[12];a=b[f>>>24];a+=b[256|f>>16&255];a^=b[512|f>>8&255];a+=b[768|f&255];g=g^a^c[13];a=b[g>>>24];a+=b[256|g>>16&255];a^=b[512|g>>8&255];a+=b[768|g&255];f=f^a^c[14];a=b[f>>>24];a+=b[256|f>>16&255];a^=b[512|f>>8&255];a+=b[768|f&255];g=g^a^c[15];a=b[g>>>24];a+=b[256|g>>16&255];a^=b[512|g>>8&255];a+=b[768|g&255];f=f^a^c[16];e[d]=g^c[17];e[d+1]=f;return e}function t(e,d){for(var c=0,b=0;4>c;++c)b=b<<8|e[d]&255,d=(d+1)%e.length; +return{key:b,offp:d}}function C(e,d,c){for(var b=0,a=[0,0],f=d.length,g=c.length,m,h=0;hn;n++)for(y=0;y>1;y++)v(g,y<<1,l,k);h=[];for(n=0;n>24&255)>>>0),h.push((g[n]>>16&255)>>>0),h.push((g[n]>>8&255)>>>0),h.push((g[n]&255)>>>0);if(b){b(null,h);return}return h}b&&p(f)}var g=E.slice(),m=g.length,h;if(4>c||31>>0;var l,k,n=0,y;Int32Array?(l=new Int32Array(F),k=new Int32Array(G)):(l=F.slice(),k=G.slice());J(d,e,l,k);if("undefined"!==typeof b)f();else for(;;)if("undefined"!==typeof(h=f()))return h||[]}function A(e,d,c,b){function a(a){var b=[];b.push("$2");"a"<=f&&b.push(f);b.push("$");10>l&&b.push("0");b.push(l.toString());b.push("$");b.push(x(k,k.length));b.push(x(a,4* +E.length-1));return b.join("")}if("string"!==typeof e||"string"!==typeof d){b=Error("Invalid string / salt: Not a string");if(c){p(c.bind(this,b));return}throw b;}var f,g;if("$"!==d.charAt(0)||"2"!==d.charAt(1)){b=Error("Invalid salt version: "+d.substring(0,2));if(c){p(c.bind(this,b));return}throw b;}if("$"===d.charAt(2))f=String.fromCharCode(0),g=3;else{f=d.charAt(2);if("a"!==f&&"b"!==f&&"y"!==f||"$"!==d.charAt(3)){b=Error("Invalid salt revision: "+d.substring(2,4));if(c){p(c.bind(this,b));return}throw b; +}g=4}if("$"e?e=4:31e&&c.push("0");c.push(e.toString());c.push("$");c.push(x(u(16),16));return c.join("")};k.genSalt=function(e,d,c){function b(a){p(function(){try{a(null,k.genSaltSync(e))}catch(b){a(b)}})}"function"===typeof d&&(c=d,d=void 0);"function"===typeof e&&(c=e,e=void 0);if("undefined"===typeof e)e=10;else if("number"!==typeof e)throw Error("illegal arguments: "+typeof e);if(c){if("function"!==typeof c)throw Error("Illegal callback: "+ +typeof c);b(c)}else return new Promise(function(a,c){b(function(b,d){b?c(b):a(d)})})};k.hashSync=function(e,d){"undefined"===typeof d&&(d=10);"number"===typeof d&&(d=k.genSaltSync(d));if("string"!==typeof e||"string"!==typeof d)throw Error("Illegal arguments: "+typeof e+", "+typeof d);return A(e,d)};k.hash=function(e,d,c,b){function a(a){"string"===typeof e&&"number"===typeof d?k.genSalt(d,function(c,d){A(e,d,a,b)}):"string"===typeof e&&"string"===typeof d?A(e,d,a,b):p(a.bind(this,Error("Illegal arguments: "+ +typeof e+", "+typeof d)))}if(c){if("function"!==typeof c)throw Error("Illegal callback: "+typeof c);a(c)}else return new Promise(function(b,c){a(function(a,d){a?c(a):b(d)})})};k.compareSync=function(e,d){if("string"!==typeof e||"string"!==typeof d)throw Error("Illegal arguments: "+typeof e+", "+typeof d);return 60!==d.length?!1:r(k.hashSync(e,d.substr(0,d.length-31)),d)};k.compare=function(e,d,c,b){function a(a){"string"!==typeof e||"string"!==typeof d?p(a.bind(this,Error("Illegal arguments: "+typeof e+ +", "+typeof d))):60!==d.length?p(a.bind(this,null,!1)):k.hash(e,d.substr(0,29),function(b,c){b?a(b):a(null,r(c,d))},b)}if(c){if("function"!==typeof c)throw Error("Illegal callback: "+typeof c);a(c)}else return new Promise(function(b,c){a(function(a,d){a?c(a):b(d)})})};k.getRounds=function(e){if("string"!==typeof e)throw Error("Illegal arguments: "+typeof e);return parseInt(e.split("$")[2],10)};k.getSalt=function(e){if("string"!==typeof e)throw Error("Illegal arguments: "+typeof e);if(60!==e.length)throw Error("Illegal hash length: "+ +e.length+" != 60");return e.substring(0,29)};var p="undefined"!==typeof process&&process&&"function"===typeof process.nextTick?"function"===typeof setImmediate?setImmediate:process.nextTick:setTimeout,s="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),q=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,54,55,56,57,58,59,60,61,62,63,-1,-1,-1,-1,-1,-1,-1,2,3,4,5,6,7,8,9,10,11,12, +13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,-1,-1,-1,-1,-1,-1,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,-1,-1,-1,-1,-1],z=String.fromCharCode,I=function(){var e={MAX_CODEPOINT:1114111,encodeUTF8:function(d,c){var b=null;"number"===typeof d&&(b=d,d=function(){return null});for(;null!==b||null!==(b=d());)128>b?c(b&127):(2048>b?c(b>>6&31|192):(65536>b?c(b>>12&15|224):(c(b>>18&7|240),c(b>>12&63|128)),c(b>>6&63|128)),c(b&63|128)),b=null},decodeUTF8:function(d,c){for(var b, +a,f,e,k=function(a){a=a.slice(0,a.indexOf(null));var b=Error(a.toString());b.name="TruncatedError";b.bytes=a;throw b;};null!==(b=d());)if(0===(b&128))c(b);else if(192===(b&224))null===(a=d())&&k([b,a]),c((b&31)<<6|a&63);else if(224===(b&240))null!==(a=d())&&null!==(f=d())||k([b,a,f]),c((b&15)<<12|(a&63)<<6|f&63);else if(240===(b&248))null!==(a=d())&&null!==(f=d())&&null!==(e=d())||k([b,a,f,e]),c((b&7)<<18|(a&63)<<12|(f&63)<<6|e&63);else throw RangeError("Illegal starting byte: "+b);},UTF16toUTF8:function(d, +c){for(var b,a=null;null!==(b=null!==a?a:d());)55296<=b&&57343>=b&&null!==(a=d())&&56320<=a&&57343>=a?(c(1024*(b-55296)+a-56320+65536),a=null):c(b);null!==a&&c(a)},UTF8toUTF16:function(d,c){var b=null;"number"===typeof d&&(b=d,d=function(){return null});for(;null!==b||null!==(b=d());)65535>=b?c(b):(b-=65536,c((b>>10)+55296),c(b%1024+56320)),b=null},encodeUTF16toUTF8:function(d,c){e.UTF16toUTF8(d,function(b){e.encodeUTF8(b,c)})},decodeUTF8toUTF16:function(d,c){e.decodeUTF8(d,function(b){e.UTF8toUTF16(b, +c)})},calculateCodePoint:function(d){return 128>d?1:2048>d?2:65536>d?3:4},calculateUTF8:function(d){for(var c,b=0;null!==(c=d());)b+=e.calculateCodePoint(c);return b},calculateUTF16asUTF8:function(d){var c=0,b=0;e.UTF16toUTF8(d,function(a){++c;b+=e.calculateCodePoint(a)});return[c,b]}};return e}();Date.now=Date.now||function(){return+new Date};var F=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069, +3041331479,2450970073,2306472731],G=[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828, +289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486, +1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557, +442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592, +3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370, +48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946,1266315497,3048417604,3681880366,3289982499,290971E4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509, +1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880, +613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303, +2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385, +1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030, +4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055,3913112168, +2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499, +499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905, +3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651, +309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610, +1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037, +2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504,976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200, +2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241, +3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891, +3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409E3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588, +3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493, +1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462],E=[1332899944,1700884034,1701343084,1684370003,1668446532, +1869963892];k.encodeBase64=x;k.decodeBase64=B;return k}); diff --git a/node_modules/bcryptjs/dist/bcrypt.min.js.gz b/node_modules/bcryptjs/dist/bcrypt.min.js.gz new file mode 100644 index 0000000000000000000000000000000000000000..6bde4bde53a58f73d813ca1143452f52f3dfd122 GIT binary patch literal 9443 zcmV<9BpllxiwFp$mYG-r17c%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vV6@H3R87pG}jb9^VPAZcga995DkeEzPUDZDwvW zj-)>rMjZZIfz-V1?So%=#RsV^OTu^^4w9PHq35j1Si_CGuv^rB0%kbF1y7D`e8~X3vChpL1bz8^u-;wE0TeE^qnVan%J(kbS@@(>p)*pXp1;SizqjP-J1 zFa?qKzt{OUYYgP^j%EoF_~#kC9n;2#DZNV)2<0JEwc|eF40*B}7XW0>A~uDF^RcIB z(y~wC66>{@l+`-)YgJ8scNnX-GO=-g&2S8zOAIOv%jzW7Nml#8P5oT>Xp{D=L?aA5 zZTyG(b+M1^yj|Or54ls2{yOx^>iW}#LL{rQs`nd0-gBL1Puh!_f*P0qge76eBm+il z_xa2Sz1I2O?F0SQmWtZhmVO6`Hr0t;)i0Sf@H3H<(;ya&KijM^PH`zw0!*3zqIp3fu3A&M(&^ zjv3{wo4Dc}2COnxF#nl(4Xx$o!r>0}J6C4m_h{2N;7~v4dhUT4oUOJJWzW@*b?$h6 zIO$qaj(t88G3-W?&o4){ee*%lt%PE(!2oID>+udn?WVxmz-^HL;Q7YS{d6Mp>lG+u z`w@JvytY3+zyIT(#c5oLk#;~LQCo3fe@APE`R!q&8fUgrMwgWvwTlKkiY{`U8u{{vlS@4kXm006b6Uv>Zh literal 0 HcmV?d00001 diff --git a/node_modules/bcryptjs/dist/bcrypt.min.map b/node_modules/bcryptjs/dist/bcrypt.min.map new file mode 100644 index 0000000..35d0f83 --- /dev/null +++ b/node_modules/bcryptjs/dist/bcrypt.min.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"", +"lineCount":48, +"mappings":"A;;;;;AAiCC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkB,CAES,UAAtB,GAAI,MAAOC,OAAX,EAAoCA,MAAA,IAApC,CACNA,MAAA,CAAO,EAAP,CAAWD,CAAX,CADM,CAEiC,UAAvB,GAAI,MAAOE,QAAX,EAAuD,QAAvD,GAAqC,MAAOC,OAA5C,EAAmEA,MAAnE,EAA6EA,MAAA,QAA7E,CAChBA,M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,UAlMS,CAkMG,UAlMH,CAkMe,SAlMf,CAkM2B,UAlM3B,CAkMuC,SAlMvC,CAmMT,UAnMS,CAmMG,UAnMH,CAmMe,SAnMf,CAmM2B,UAnM3B,CAmMuC,UAnMvC,CAoMT,UApMS,CAoMG,UApMH,CAoMe,UApMf,CAoM2B,UApM3B,CAoMuC,UApMvC,CAqMT,UArMS,CAqMG,UArMH;AAqMe,UArMf,CAqM2B,UArM3B,CAqMuC,UArMvC,CAsMT,UAtMS,CAsMG,UAtMH,CAsMe,UAtMf,CAsM2B,UAtM3B,CAsMuC,SAtMvC,CAuMT,UAvMS,CAuMG,UAvMH,CAuMe,UAvMf,CAuM2B,UAvM3B,CAuMuC,UAvMvC,CAwMT,SAxMS,CAwMG,UAxMH,CAwMe,UAxMf,CAwM2B,UAxM3B,CAwMuC,UAxMvC,CAyMT,UAzMS,CAyMG,SAzMH,CAyMe,SAzMf,CAyM2B,SAzM3B,CAyMuC,UAzMvC,CA0MT,UA1MS,CA0MG,UA1MH,CA0Me,SA1Mf,CA0M2B,UA1M3B,CA0MuC,UA1MvC,CA2MT,UA3MS,CA2MG,UA3MH,CA2Me,SA3Mf,CA2M2B,QA3M3B,CA2MuC,QA3MvC,CA4MT,UA5MS,CA4MG,UA5MH,CA4Me,UA5Mf,CA4M2B,UA5M3B,CA4MuC,UA5MvC,CA6MT,UA7MS,CA6MG,UA7MH,CA6Me,UA7Mf,CA6M2B,SA7M3B,CAZb,CAiOIN,EAAS,CACT,UADS,CACG,UADH,CACe,UADf,CAC2B,UAD3B,CACuC,UADvC;AAET,UAFS,CAoabsB,EAAAuD,aAAA,CAAsB/H,CAUtBwE,EAAAwD,aAAA,CAAsBzH,CAEtB,OAAOiE,EAvzCQ,CATlB;", +"sources":["dist/bcrypt.js"], +"names":["global","factory","define","require","module","random","len","e","a","self","Uint32Array","Array","prototype","slice","call","randomFallback","Error","safeStringCompare","known","unknown","right","wrong","i","k","length","charCodeAt","stringToBytes","str","out","utfx","encodeUTF16toUTF8","b","push","base64_encode","off","rs","c1","c2","BASE64_CODE","join","base64_decode","s","slen","olen","o","code","BASE64_INDEX","stringFromCharCode","c3","c4","res","_encipher","lr","P","S","n","l","r","_streamtoword","data","offp","word","key","_key","offset","plen","sw","_ekskey","_crypt","salt","rounds","callback","progressCallback","next","start","Date","now","MAX_EXECUTION_TIME","j","clen","cdata","ret","nextTick","C_ORIG","err","bind","BCRYPT_SALT_LEN","Int32Array","P_ORIG","S_ORIG","_hash","finish","bytes","minor","toString","saltb","charAt","substring","String","fromCharCode","r1","parseInt","r2","real_salt","passwordb","bcrypt","setRandomFallback","bcrypt.setRandomFallback","genSaltSync","bcrypt.genSaltSync","seed_length","GENSALT_DEFAULT_LOG2_ROUNDS","genSalt","bcrypt.genSalt","_async","undefined","Promise","resolve","reject","hashSync","bcrypt.hashSync","hash","bcrypt.hash","compareSync","bcrypt.compareSync","substr","compare","bcrypt.compare","comp","getRounds","bcrypt.getRounds","split","getSalt","bcrypt.getSalt","process","setImmediate","setTimeout","utfx.encodeUTF8","src","dst","cp","utfx.decodeUTF8","c","d","fail","indexOf","name","RangeError","utfx.UTF16toUTF8","utfx.UTF8toUTF16","utfx.encodeUTF16toUTF8","UTF16toUTF8","encodeUTF8","utfx.decodeUTF8toUTF16","decodeUTF8","UTF8toUTF16","utfx.calculateCodePoint","utfx.calculateUTF8","calculateCodePoint","utfx.calculateUTF16asUTF8","encodeBase64","decodeBase64"] +} diff --git a/node_modules/bcryptjs/externs/bcrypt.js b/node_modules/bcryptjs/externs/bcrypt.js new file mode 100644 index 0000000..c458f9d --- /dev/null +++ b/node_modules/bcryptjs/externs/bcrypt.js @@ -0,0 +1,91 @@ +/* + * Copyright 2012 The Closure Compiler 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. + */ + +/** + * @fileoverview Definitions for bcrypt.js 2. + * @externs + * @author Daniel Wirtz + */ + +/** + * @type {Object.} + */ +var bcrypt = {}; + +/** + * @param {?function(number):!Array.} random + */ +bcrypt.setRandomFallback = function(random) {}; + +/** + * @param {number=} rounds + * @param {number=} seed_length + * @returns {string} + */ +bcrypt.genSaltSync = function(rounds, seed_length) {}; + +/** + * @param {(number|function(Error, ?string))=} rounds + * @param {(number|function(Error, ?string))=} seed_length + * @param {function(Error, string=)=} callback + */ +bcrypt.genSalt = function(rounds, seed_length, callback) {}; + +/** + * @param {string} s + * @param {(number|string)=} salt + * @returns {?string} + */ +bcrypt.hashSync = function(s, salt) {}; + +/** + * @param {string} s + * @param {number|string} salt + * @param {function(Error, string=)} callback + * @expose + */ +bcrypt.hash = function(s, salt, callback) {}; + +/** + * @param {string} s + * @param {string} hash + * @returns {boolean} + * @throws {Error} + */ +bcrypt.compareSync = function(s, hash) {}; + +/** + * @param {string} s + * @param {string} hash + * @param {function(Error, boolean)} callback + * @throws {Error} + */ +bcrypt.compare = function(s, hash, callback) {}; + +/** + * @param {string} hash + * @returns {number} + * @throws {Error} + */ +bcrypt.getRounds = function(hash) {}; + +/** + * @param {string} hash + * @returns {string} + * @throws {Error} + * @expose + */ +bcrypt.getSalt = function(hash) {}; diff --git a/node_modules/bcryptjs/externs/minimal-env.js b/node_modules/bcryptjs/externs/minimal-env.js new file mode 100644 index 0000000..0db9d4c --- /dev/null +++ b/node_modules/bcryptjs/externs/minimal-env.js @@ -0,0 +1,98 @@ +/** + * @fileoverview Minimal environment for bcrypt.js. + * @externs + */ + +/** + * @param {string} moduleName + * returns {*} + */ +function require(moduleName) {} + +/** + * @constructor + * @private + */ +var Module = function() {}; + +/** + * @type {*} + */ +Module.prototype.exports; + +/** + * @type {Module} + */ +var module; + +/** + * @type {string} + */ +var __dirname; + +/** + * @type {Object.} + */ +var process = {}; + +/** + * @param {function()} func + */ +process.nextTick = function(func) {}; + +/** + * @param {string} s + * @constructor + * @extends Array + */ +var Buffer = function(s) {}; + +/** + BEGIN_NODE_INCLUDE + var crypto = require('crypto'); + END_NODE_INCLUDE + */ + +/** + * @type {Object.} + */ +var crypto = {}; + +/** + * @param {number} n + * @returns {Array.} + */ +crypto.randomBytes = function(n) {}; + +/** + * @type {Object.} + */ +window.crypto = {}; + +/** + * @param {Uint8Array|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array} array + */ +window.crypto.getRandomValues = function(array) {}; + +/** + * @param {string} name + * @param {function(...[*]):*} constructor + */ +var define = function(name, constructor) {}; + +/** + * @type {boolean} + */ +define.amd; + +/** + * @param {...*} var_args + * @returns {string} + */ +String.fromCodePoint = function(var_args) {}; + +/** + * @param {number} offset + * @returns {number} + */ +String.prototype.codePointAt = function(offset) {}; diff --git a/node_modules/bcryptjs/index.js b/node_modules/bcryptjs/index.js new file mode 100644 index 0000000..f11b4e7 --- /dev/null +++ b/node_modules/bcryptjs/index.js @@ -0,0 +1,29 @@ +/* + Copyright (c) 2012 Nevins Bartolomeo + Copyright (c) 2012 Shane Girish + Copyright (c) 2013 Daniel Wirtz + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +module.exports = require("./dist/bcrypt.js"); diff --git a/node_modules/bcryptjs/package.json b/node_modules/bcryptjs/package.json new file mode 100644 index 0000000..97be5df --- /dev/null +++ b/node_modules/bcryptjs/package.json @@ -0,0 +1,47 @@ +{ + "name": "bcryptjs", + "description": "Optimized bcrypt in plain JavaScript with zero dependencies. Compatible to 'bcrypt'.", + "version": "2.4.3", + "author": "Daniel Wirtz ", + "contributors": [ + "Shane Girish (https://github.com/shaneGirish)", + "Alex Murray <> (https://github.com/alexmurray)", + "Nicolas Pelletier <> (https://github.com/NicolasPelletier)", + "Josh Rogers <> (https://github.com/geekymole)", + "Noah Isaacson (https://github.com/nisaacson)" + ], + "repository": { + "type": "url", + "url": "https://github.com/dcodeIO/bcrypt.js.git" + }, + "bugs": { + "url": "https://github.com/dcodeIO/bcrypt.js/issues" + }, + "keywords": [ + "bcrypt", + "password", + "auth", + "authentication", + "encryption", + "crypt", + "crypto" + ], + "main": "index.js", + "browser": "dist/bcrypt.js", + "dependencies": {}, + "devDependencies": { + "testjs": "~1", + "closurecompiler": "~1", + "metascript": "~0.18", + "bcrypt": "latest", + "utfx": "~1" + }, + "license": "MIT", + "scripts": { + "test": "node node_modules/testjs/bin/testjs", + "build": "node scripts/build.js", + "compile": "node node_modules/closurecompiler/bin/ccjs dist/bcrypt.js --compilation_level=SIMPLE_OPTIMIZATIONS --create_source_map=dist/bcrypt.min.map > dist/bcrypt.min.js", + "compress": "gzip -c -9 dist/bcrypt.min.js > dist/bcrypt.min.js.gz", + "make": "npm run build && npm run compile && npm run compress && npm test" + } +} diff --git a/node_modules/bcryptjs/scripts/build.js b/node_modules/bcryptjs/scripts/build.js new file mode 100644 index 0000000..7b34ea4 --- /dev/null +++ b/node_modules/bcryptjs/scripts/build.js @@ -0,0 +1,37 @@ +var MetaScript = require("metascript"), + path = require("path"), + fs = require("fs"); + +var rootDir = path.join(__dirname, ".."), + srcDir = path.join(rootDir, "src"), + distDir = path.join(rootDir, "dist"), + pkg = require(path.join(rootDir, "package.json")), + filename; + +var scope = { + VERSION: pkg.version, + ISAAC: false +}; + +// Make standard build +console.log("Building bcrypt.js with scope", JSON.stringify(scope, null, 2)); +fs.writeFileSync( + path.join(distDir, "bcrypt.js"), + MetaScript.transform(fs.readFileSync(filename = path.join(srcDir, "wrap.js")), filename, scope, srcDir) +); + +// Make isaac build - see: https://github.com/dcodeIO/bcrypt.js/issues/16 +/* scope.ISAAC = true; +console.log("Building bcrypt-isaac.js with scope", JSON.stringify(scope, null, 2)); +fs.writeFileSync( + path.join(distDir, "bcrypt-isaac.js"), + MetaScript.transform(fs.readFileSync(filename = path.join(srcDir, "bcrypt.js")), filename, scope, srcDir) +); */ + +// Update bower.json +scope = { VERSION: pkg.version }; +console.log("Updating bower.json with scope", JSON.stringify(scope, null, 2)); +fs.writeFileSync( + path.join(rootDir, "bower.json"), + MetaScript.transform(fs.readFileSync(filename = path.join(srcDir, "bower.json")), filename, scope, srcDir) +); diff --git a/node_modules/bcryptjs/src/bcrypt.js b/node_modules/bcryptjs/src/bcrypt.js new file mode 100644 index 0000000..11dedc1 --- /dev/null +++ b/node_modules/bcryptjs/src/bcrypt.js @@ -0,0 +1,327 @@ +/** + * bcrypt namespace. + * @type {Object.} + */ +var bcrypt = {}; + +/** + * The random implementation to use as a fallback. + * @type {?function(number):!Array.} + * @inner + */ +var randomFallback = null; + +/** + * Generates cryptographically secure random bytes. + * @function + * @param {number} len Bytes length + * @returns {!Array.} Random bytes + * @throws {Error} If no random implementation is available + * @inner + */ +function random(len) { + /* node */ if (typeof module !== 'undefined' && module && module['exports']) + try { + return require("crypto")['randomBytes'](len); + } catch (e) {} + /* WCA */ try { + var a; (self['crypto']||self['msCrypto'])['getRandomValues'](a = new Uint32Array(len)); + return Array.prototype.slice.call(a); + } catch (e) {} + /* fallback */ if (!randomFallback) + throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative"); + return randomFallback(len); +} + +// Test if any secure randomness source is available +var randomAvailable = false; +try { + random(1); + randomAvailable = true; +} catch (e) {} + +// Default fallback, if any +randomFallback = /*? if (ISAAC) { */function(len) { + for (var a=[], i=0; i} random Function taking the number of bytes to generate as its + * sole argument, returning the corresponding array of cryptographically secure random byte values. + * @see http://nodejs.org/api/crypto.html + * @see http://www.w3.org/TR/WebCryptoAPI/ + */ +bcrypt.setRandomFallback = function(random) { + randomFallback = random; +}; + +/** + * Synchronously generates a salt. + * @param {number=} rounds Number of rounds to use, defaults to 10 if omitted + * @param {number=} seed_length Not supported. + * @returns {string} Resulting salt + * @throws {Error} If a random fallback is required but not set + * @expose + */ +bcrypt.genSaltSync = function(rounds, seed_length) { + rounds = rounds || GENSALT_DEFAULT_LOG2_ROUNDS; + if (typeof rounds !== 'number') + throw Error("Illegal arguments: "+(typeof rounds)+", "+(typeof seed_length)); + if (rounds < 4) + rounds = 4; + else if (rounds > 31) + rounds = 31; + var salt = []; + salt.push("$2a$"); + if (rounds < 10) + salt.push("0"); + salt.push(rounds.toString()); + salt.push('$'); + salt.push(base64_encode(random(BCRYPT_SALT_LEN), BCRYPT_SALT_LEN)); // May throw + return salt.join(''); +}; + +/** + * Asynchronously generates a salt. + * @param {(number|function(Error, string=))=} rounds Number of rounds to use, defaults to 10 if omitted + * @param {(number|function(Error, string=))=} seed_length Not supported. + * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting salt + * @returns {!Promise} If `callback` has been omitted + * @throws {Error} If `callback` is present but not a function + * @expose + */ +bcrypt.genSalt = function(rounds, seed_length, callback) { + if (typeof seed_length === 'function') + callback = seed_length, + seed_length = undefined; // Not supported. + if (typeof rounds === 'function') + callback = rounds, + rounds = undefined; + if (typeof rounds === 'undefined') + rounds = GENSALT_DEFAULT_LOG2_ROUNDS; + else if (typeof rounds !== 'number') + throw Error("illegal arguments: "+(typeof rounds)); + + function _async(callback) { + nextTick(function() { // Pretty thin, but salting is fast enough + try { + callback(null, bcrypt.genSaltSync(rounds)); + } catch (err) { + callback(err); + } + }); + } + + if (callback) { + if (typeof callback !== 'function') + throw Error("Illegal callback: "+typeof(callback)); + _async(callback); + } else + return new Promise(function(resolve, reject) { + _async(function(err, res) { + if (err) { + reject(err); + return; + } + resolve(res); + }); + }); +}; + +/** + * Synchronously generates a hash for the given string. + * @param {string} s String to hash + * @param {(number|string)=} salt Salt length to generate or salt to use, default to 10 + * @returns {string} Resulting hash + * @expose + */ +bcrypt.hashSync = function(s, salt) { + if (typeof salt === 'undefined') + salt = GENSALT_DEFAULT_LOG2_ROUNDS; + if (typeof salt === 'number') + salt = bcrypt.genSaltSync(salt); + if (typeof s !== 'string' || typeof salt !== 'string') + throw Error("Illegal arguments: "+(typeof s)+', '+(typeof salt)); + return _hash(s, salt); +}; + +/** + * Asynchronously generates a hash for the given string. + * @param {string} s String to hash + * @param {number|string} salt Salt length to generate or salt to use + * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash + * @param {function(number)=} progressCallback Callback successively called with the percentage of rounds completed + * (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms. + * @returns {!Promise} If `callback` has been omitted + * @throws {Error} If `callback` is present but not a function + * @expose + */ +bcrypt.hash = function(s, salt, callback, progressCallback) { + + function _async(callback) { + if (typeof s === 'string' && typeof salt === 'number') + bcrypt.genSalt(salt, function(err, salt) { + _hash(s, salt, callback, progressCallback); + }); + else if (typeof s === 'string' && typeof salt === 'string') + _hash(s, salt, callback, progressCallback); + else + nextTick(callback.bind(this, Error("Illegal arguments: "+(typeof s)+', '+(typeof salt)))); + } + + if (callback) { + if (typeof callback !== 'function') + throw Error("Illegal callback: "+typeof(callback)); + _async(callback); + } else + return new Promise(function(resolve, reject) { + _async(function(err, res) { + if (err) { + reject(err); + return; + } + resolve(res); + }); + }); +}; + +/** + * Compares two strings of the same length in constant time. + * @param {string} known Must be of the correct length + * @param {string} unknown Must be the same length as `known` + * @returns {boolean} + * @inner + */ +function safeStringCompare(known, unknown) { + var right = 0, + wrong = 0; + for (var i=0, k=known.length; i} b Byte array + * @param {number} len Maximum input length + * @returns {string} + * @expose + */ +bcrypt.encodeBase64 = base64_encode; + +/** + * Decodes a base64 encoded string to up to len bytes of output, using the custom bcrypt alphabet. + * @function + * @param {string} s String to decode + * @param {number} len Maximum output length + * @returns {!Array.} + * @expose + */ +bcrypt.decodeBase64 = base64_decode; diff --git a/node_modules/bcryptjs/src/bcrypt/impl.js b/node_modules/bcryptjs/src/bcrypt/impl.js new file mode 100644 index 0000000..fb00aee --- /dev/null +++ b/node_modules/bcryptjs/src/bcrypt/impl.js @@ -0,0 +1,669 @@ +/** + * @type {number} + * @const + * @inner + */ +var BCRYPT_SALT_LEN = 16; + +/** + * @type {number} + * @const + * @inner + */ +var GENSALT_DEFAULT_LOG2_ROUNDS = 10; + +/** + * @type {number} + * @const + * @inner + */ +var BLOWFISH_NUM_ROUNDS = 16; + +/** + * @type {number} + * @const + * @inner + */ +var MAX_EXECUTION_TIME = 100; + +/** + * @type {Array.} + * @const + * @inner + */ +var P_ORIG = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, + 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, + 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, + 0xb5470917, 0x9216d5d9, 0x8979fb1b +]; + +/** + * @type {Array.} + * @const + * @inner + */ +var S_ORIG = [ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, + 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, + 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, + 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, + 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, + 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, + 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, + 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, + 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, + 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, + 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, + 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, + 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, + 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, + 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, + 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, + 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, + 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, + 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, + 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, + 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, + 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, + 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, + 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, + 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, + 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, + 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, + 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, + 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, + 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, + 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, + 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, + 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, + 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, + 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, + 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, + 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, + 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, + 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, + 0x6e85076a, 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, + 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, + 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, + 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, + 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, + 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, + 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, + 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, + 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, + 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, + 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, + 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, + 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, + 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, + 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, + 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, + 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, + 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, + 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, + 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, + 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, + 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, + 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, + 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, + 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, + 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, + 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, + 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, + 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, + 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, + 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, + 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, + 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, + 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, + 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, + 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, + 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, + 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, + 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c, + 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, + 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, + 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, + 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, + 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, + 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, + 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, + 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, + 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, + 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, + 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, + 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, + 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, + 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, + 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, + 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, + 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, + 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, + 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, + 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, + 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, + 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, + 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, + 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, + 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, + 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, + 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, + 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, + 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, + 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, + 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, + 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, + 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, + 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, + 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, + 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, + 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, + 0x92638212, 0x670efa8e, 0x406000e0, 0x3a39ce37, 0xd3faf5cf, + 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, + 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, + 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, + 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, + 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, + 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, + 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, + 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, + 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, + 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, + 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, + 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, + 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, + 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, + 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, + 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, + 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, + 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, + 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, + 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, + 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, + 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, + 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, + 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, + 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, + 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, + 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, + 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, + 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, + 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, + 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, + 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, + 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, + 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, + 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, + 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, + 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, + 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 +]; + +/** + * @type {Array.} + * @const + * @inner + */ +var C_ORIG = [ + 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, + 0x6f756274 +]; + +/** + * @param {Array.} lr + * @param {number} off + * @param {Array.} P + * @param {Array.} S + * @returns {Array.} + * @inner + */ +function _encipher(lr, off, P, S) { // This is our bottleneck: 1714/1905 ticks / 90% - see profile.txt + var n, + l = lr[off], + r = lr[off + 1]; + + l ^= P[0]; + + /* + for (var i=0, k=BLOWFISH_NUM_ROUNDS-2; i<=k;) + // Feistel substitution on left word + n = S[l >>> 24], + n += S[0x100 | ((l >> 16) & 0xff)], + n ^= S[0x200 | ((l >> 8) & 0xff)], + n += S[0x300 | (l & 0xff)], + r ^= n ^ P[++i], + // Feistel substitution on right word + n = S[r >>> 24], + n += S[0x100 | ((r >> 16) & 0xff)], + n ^= S[0x200 | ((r >> 8) & 0xff)], + n += S[0x300 | (r & 0xff)], + l ^= n ^ P[++i]; + */ + + //The following is an unrolled version of the above loop. + //Iteration 0 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[1]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[2]; + //Iteration 1 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[3]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[4]; + //Iteration 2 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[5]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[6]; + //Iteration 3 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[7]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[8]; + //Iteration 4 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[9]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[10]; + //Iteration 5 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[11]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[12]; + //Iteration 6 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[13]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[14]; + //Iteration 7 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[15]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[16]; + + lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1]; + lr[off + 1] = l; + return lr; +} + +/** + * @param {Array.} data + * @param {number} offp + * @returns {{key: number, offp: number}} + * @inner + */ +function _streamtoword(data, offp) { + for (var i = 0, word = 0; i < 4; ++i) + word = (word << 8) | (data[offp] & 0xff), + offp = (offp + 1) % data.length; + return { key: word, offp: offp }; +} + +/** + * @param {Array.} key + * @param {Array.} P + * @param {Array.} S + * @inner + */ +function _key(key, P, S) { + var offset = 0, + lr = [0, 0], + plen = P.length, + slen = S.length, + sw; + for (var i = 0; i < plen; i++) + sw = _streamtoword(key, offset), + offset = sw.offp, + P[i] = P[i] ^ sw.key; + for (i = 0; i < plen; i += 2) + lr = _encipher(lr, 0, P, S), + P[i] = lr[0], + P[i + 1] = lr[1]; + for (i = 0; i < slen; i += 2) + lr = _encipher(lr, 0, P, S), + S[i] = lr[0], + S[i + 1] = lr[1]; +} + +/** + * Expensive key schedule Blowfish. + * @param {Array.} data + * @param {Array.} key + * @param {Array.} P + * @param {Array.} S + * @inner + */ +function _ekskey(data, key, P, S) { + var offp = 0, + lr = [0, 0], + plen = P.length, + slen = S.length, + sw; + for (var i = 0; i < plen; i++) + sw = _streamtoword(key, offp), + offp = sw.offp, + P[i] = P[i] ^ sw.key; + offp = 0; + for (i = 0; i < plen; i += 2) + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[0] ^= sw.key, + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[1] ^= sw.key, + lr = _encipher(lr, 0, P, S), + P[i] = lr[0], + P[i + 1] = lr[1]; + for (i = 0; i < slen; i += 2) + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[0] ^= sw.key, + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[1] ^= sw.key, + lr = _encipher(lr, 0, P, S), + S[i] = lr[0], + S[i + 1] = lr[1]; +} + +/** + * Internaly crypts a string. + * @param {Array.} b Bytes to crypt + * @param {Array.} salt Salt bytes to use + * @param {number} rounds Number of rounds + * @param {function(Error, Array.=)=} callback Callback receiving the error, if any, and the resulting bytes. If + * omitted, the operation will be performed synchronously. + * @param {function(number)=} progressCallback Callback called with the current progress + * @returns {!Array.|undefined} Resulting bytes if callback has been omitted, otherwise `undefined` + * @inner + */ +function _crypt(b, salt, rounds, callback, progressCallback) { + var cdata = C_ORIG.slice(), + clen = cdata.length, + err; + + // Validate + if (rounds < 4 || rounds > 31) { + err = Error("Illegal number of rounds (4-31): "+rounds); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + if (salt.length !== BCRYPT_SALT_LEN) { + err =Error("Illegal salt length: "+salt.length+" != "+BCRYPT_SALT_LEN); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + rounds = (1 << rounds) >>> 0; + + var P, S, i = 0, j; + + //Use typed arrays when available - huge speedup! + if (Int32Array) { + P = new Int32Array(P_ORIG); + S = new Int32Array(S_ORIG); + } else { + P = P_ORIG.slice(); + S = S_ORIG.slice(); + } + + _ekskey(salt, b, P, S); + + /** + * Calcualtes the next round. + * @returns {Array.|undefined} Resulting array if callback has been omitted, otherwise `undefined` + * @inner + */ + function next() { + if (progressCallback) + progressCallback(i / rounds); + if (i < rounds) { + var start = Date.now(); + for (; i < rounds;) { + i = i + 1; + _key(b, P, S); + _key(salt, P, S); + if (Date.now() - start > MAX_EXECUTION_TIME) + break; + } + } else { + for (i = 0; i < 64; i++) + for (j = 0; j < (clen >> 1); j++) + _encipher(cdata, j << 1, P, S); + var ret = []; + for (i = 0; i < clen; i++) + ret.push(((cdata[i] >> 24) & 0xff) >>> 0), + ret.push(((cdata[i] >> 16) & 0xff) >>> 0), + ret.push(((cdata[i] >> 8) & 0xff) >>> 0), + ret.push((cdata[i] & 0xff) >>> 0); + if (callback) { + callback(null, ret); + return; + } else + return ret; + } + if (callback) + nextTick(next); + } + + // Async + if (typeof callback !== 'undefined') { + next(); + + // Sync + } else { + var res; + while (true) + if (typeof(res = next()) !== 'undefined') + return res || []; + } +} + +/** + * Internally hashes a string. + * @param {string} s String to hash + * @param {?string} salt Salt to use, actually never null + * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash. If omitted, + * hashing is perormed synchronously. + * @param {function(number)=} progressCallback Callback called with the current progress + * @returns {string|undefined} Resulting hash if callback has been omitted, otherwise `undefined` + * @inner + */ +function _hash(s, salt, callback, progressCallback) { + var err; + if (typeof s !== 'string' || typeof salt !== 'string') { + err = Error("Invalid string / salt: Not a string"); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } + else + throw err; + } + + // Validate the salt + var minor, offset; + if (salt.charAt(0) !== '$' || salt.charAt(1) !== '2') { + err = Error("Invalid salt version: "+salt.substring(0,2)); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } + else + throw err; + } + if (salt.charAt(2) === '$') + minor = String.fromCharCode(0), + offset = 3; + else { + minor = salt.charAt(2); + if ((minor !== 'a' && minor !== 'b' && minor !== 'y') || salt.charAt(3) !== '$') { + err = Error("Invalid salt revision: "+salt.substring(2,4)); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + offset = 4; + } + + // Extract number of rounds + if (salt.charAt(offset + 2) > '$') { + err = Error("Missing salt rounds"); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + var r1 = parseInt(salt.substring(offset, offset + 1), 10) * 10, + r2 = parseInt(salt.substring(offset + 1, offset + 2), 10), + rounds = r1 + r2, + real_salt = salt.substring(offset + 3, offset + 25); + s += minor >= 'a' ? "\x00" : ""; + + var passwordb = stringToBytes(s), + saltb = base64_decode(real_salt, BCRYPT_SALT_LEN); + + /** + * Finishes hashing. + * @param {Array.} bytes Byte array + * @returns {string} + * @inner + */ + function finish(bytes) { + var res = []; + res.push("$2"); + if (minor >= 'a') + res.push(minor); + res.push("$"); + if (rounds < 10) + res.push("0"); + res.push(rounds.toString()); + res.push("$"); + res.push(base64_encode(saltb, saltb.length)); + res.push(base64_encode(bytes, C_ORIG.length * 4 - 1)); + return res.join(''); + } + + // Sync + if (typeof callback == 'undefined') + return finish(_crypt(passwordb, saltb, rounds)); + + // Async + else { + _crypt(passwordb, saltb, rounds, function(err, bytes) { + if (err) + callback(err, null); + else + callback(null, finish(bytes)); + }, progressCallback); + } +} diff --git a/node_modules/bcryptjs/src/bcrypt/prng/README.md b/node_modules/bcryptjs/src/bcrypt/prng/README.md new file mode 100644 index 0000000..4735aa6 --- /dev/null +++ b/node_modules/bcryptjs/src/bcrypt/prng/README.md @@ -0,0 +1,5 @@ +Because of [reasonable security doubts](https://github.com/dcodeIO/bcrypt.js/issues/16), these files, which used to be +a part of bcrypt-isaac.js, are no longer used but are kept here for reference only. + +What is required instead is a proper way to collect entropy sources (using an intermediate stream cipher) which is then +used to seed the CSPRNG. Pick one and use `bcrypt.setRandomFallback` instead. diff --git a/node_modules/bcryptjs/src/bcrypt/prng/accum.js b/node_modules/bcryptjs/src/bcrypt/prng/accum.js new file mode 100644 index 0000000..8ea7773 --- /dev/null +++ b/node_modules/bcryptjs/src/bcrypt/prng/accum.js @@ -0,0 +1,133 @@ +/* basic entropy accumulator */ +var accum = (function() { + + var pool, // randomness pool + time, // start timestamp + last; // last step timestamp + + /* initialize with default pool */ + function init() { + pool = []; + time = new Date().getTime(); + last = time; + // use Math.random + pool.push((Math.random() * 0xffffffff)|0); + // use current time + pool.push(time|0); + } + + /* perform one step */ + function step() { + if (!to) + return; + if (pool.length >= 255) { // stop at 255 values (1 more is added on fetch) + stop(); + return; + } + var now = new Date().getTime(); + // use actual time difference + pool.push(now-last); + // always compute, occasionally use Math.random + var rnd = (Math.random() * 0xffffffff)|0; + if (now % 2) + pool[pool.length-1] += rnd; + last = now; + to = setTimeout(step, 100+Math.random()*512); // use hypothetical time difference + } + + var to = null; + + /* starts accumulating */ + function start() { + if (to) return; + to = setTimeout(step, 100+Math.random()*512); + if (console.log) + console.log("bcrypt-isaac: collecting entropy..."); + // install collectors + if (typeof window !== 'undefined' && window && window.addEventListener) + window.addEventListener("load", loadCollector, false), + window.addEventListener("mousemove", mouseCollector, false), + window.addEventListener("touchmove", touchCollector, false); + else if (typeof document !== 'undefined' && document && document.attachEvent) + document.attachEvent("onload", loadCollector), + document.attachEvent("onmousemove", mouseCollector); + } + + /* stops accumulating */ + function stop() { + if (!to) return; + clearTimeout(to); to = null; + // uninstall collectors + if (typeof window !== 'undefined' && window && window.removeEventListener) + window.removeEventListener("load", loadCollector, false), + window.removeEventListener("mousemove", mouseCollector, false), + window.removeEventListener("touchmove", touchCollector, false); + else if (typeof document !== 'undefined' && document && document.detachEvent) + document.detachEvent("onload", loadCollector), + document.detachEvent("onmousemove", mouseCollector); + } + + /* fetches the randomness pool */ + function fetch() { + // add overall time difference + pool.push((new Date().getTime()-time)|0); + var res = pool; + init(); + if (console.log) + console.log("bcrypt-isaac: using "+res.length+"/256 samples of entropy"); + // console.log(res); + return res; + } + + /* adds the current time to the top of the pool */ + function addTime() { + pool[pool.length-1] += new Date().getTime() - time; + } + + /* page load collector */ + function loadCollector() { + if (!to || pool.length >= 255) + return; + pool.push(0); + addTime(); + } + + /* mouse events collector */ + function mouseCollector(ev) { + if (!to || pool.length >= 255) + return; + try { + var x = ev.x || ev.clientX || ev.offsetX || 0, + y = ev.y || ev.clientY || ev.offsetY || 0; + if (x != 0 || y != 0) + pool[pool.length-1] += ((x-mouseCollector.last[0]) ^ (y-mouseCollector.last[1])), + addTime(), + mouseCollector.last = [x,y]; + } catch (e) {} + } + mouseCollector.last = [0,0]; + + /* touch events collector */ + function touchCollector(ev) { + if (!to || pool.length >= 255) + return; + try { + var touch = ev.touches[0] || ev.changedTouches[0]; + var x = touch.pageX || touch.clientX || 0, + y = touch.pageY || touch.clientY || 0; + if (x != 0 || y != 0) + pool[pool.length-1] += (x-touchCollector.last[0]) ^ (y-touchCollector.last[1]), + addTime(), + touchCollector.last = [x,y]; + } catch (e) {} + } + touchCollector.last = [0,0]; + + init(); + return { + "start": start, + "stop": stop, + "fetch": fetch + } + +})(); diff --git a/node_modules/bcryptjs/src/bcrypt/prng/isaac.js b/node_modules/bcryptjs/src/bcrypt/prng/isaac.js new file mode 100644 index 0000000..e33b0e5 --- /dev/null +++ b/node_modules/bcryptjs/src/bcrypt/prng/isaac.js @@ -0,0 +1,140 @@ +/* + isaac.js Copyright (c) 2012 Yves-Marie K. Rinquin + + 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. + */ + +/* isaac module pattern */ +var isaac = (function(){ + + /* internal states */ + var m = Array(256), // internal memory + acc = 0, // accumulator + brs = 0, // last result + cnt = 0, // counter + r = Array(256), // result array + gnt = 0, // generation counter + isd = false; // initially seeded + + + /* 32-bit integer safe adder */ + function add(x, y) { + var lsb = (x & 0xffff) + (y & 0xffff), + msb = (x >>> 16) + (y >>> 16) + (lsb >>> 16); + return (msb << 16) | (lsb & 0xffff); + } + + /* initialisation */ + function reset() { + acc = brs = cnt = 0; + for (var i = 0; i < 256; ++i) + m[i] = r[i] = 0; + gnt = 0; + } + + /* seeding function */ + function seed(s) { + var a, b, c, d, e, f, g, h, i; + + /* seeding the seeds of love */ + a = b = c = d = e = f = g = h = 0x9e3779b9; /* the golden ratio */ + + if (s && typeof(s) === 'number') + s = [s]; + + if (s instanceof Array) { + reset(); + for (i = 0; i < s.length; ++i) + r[i & 0xff] += typeof(s[i]) === 'number' ? s[i] : 0; + } + + /* private: seed mixer */ + function seed_mix() { + a ^= b << 11; d = add(d, a); b = add(b, c); + b ^= c >>> 2; e = add(e, b); c = add(c, d); + c ^= d << 8; f = add(f, c); d = add(d, e); + d ^= e >>> 16; g = add(g, d); e = add(e, f); + e ^= f << 10; h = add(h, e); f = add(f, g); + f ^= g >>> 4; a = add(a, f); g = add(g, h); + g ^= h << 8; b = add(b, g); h = add(h, a); + h ^= a >>> 9; c = add(c, h); a = add(a, b); + } + + for (i = 0; i < 4; i++) /* scramble it */ + seed_mix(); + + for (i = 0; i < 256; i += 8) { + if (s) /* use all the information in the seed */ + a = add(a, r[i + 0]), b = add(b, r[i + 1]), + c = add(c, r[i + 2]), d = add(d, r[i + 3]), + e = add(e, r[i + 4]), f = add(f, r[i + 5]), + g = add(g, r[i + 6]), h = add(h, r[i + 7]); + seed_mix(); + /* fill in m[] with messy stuff */ + m[i + 0] = a; m[i + 1] = b; m[i + 2] = c; m[i + 3] = d; + m[i + 4] = e; m[i + 5] = f; m[i + 6] = g; m[i + 7] = h; + } + if (s) + /* do a second pass to make all of the seed affect all of m[] */ + for (i = 0; i < 256; i += 8) + a = add(a, m[i + 0]), b = add(b, m[i + 1]), + c = add(c, m[i + 2]), d = add(d, m[i + 3]), + e = add(e, m[i + 4]), f = add(f, m[i + 5]), + g = add(g, m[i + 6]), h = add(h, m[i + 7]), + seed_mix(), + /* fill in m[] with messy stuff (again) */ + m[i + 0] = a, m[i + 1] = b, m[i + 2] = c, m[i + 3] = d, + m[i + 4] = e, m[i + 5] = f, m[i + 6] = g, m[i + 7] = h; + prng(); /* fill in the first set of results */ + gnt = 256; /* prepare to use the first set of results */; + } + + /* isaac generator, n = number of run */ + function prng(n) { + var i, x, y; + n = n && typeof(n) === 'number' ? Math.abs(Math.floor(n)) : 1; + while (n--) { + cnt = add(cnt, 1); + brs = add(brs, cnt); + for(i = 0; i < 256; i++) { + switch(i & 3) { + case 0: acc ^= acc << 13; break; + case 1: acc ^= acc >>> 6; break; + case 2: acc ^= acc << 2; break; + case 3: acc ^= acc >>> 16; break; + } + acc = add(m[(i + 128) & 0xff], acc); x = m[i]; + m[i] = y = add(m[(x >>> 2) & 0xff], add(acc, brs)); + r[i] = brs = add(m[(y >>> 10) & 0xff], x); + } + } + } + + /* return a random number between */ + return function() { + if (!isd) // seed from accumulator + isd = true, + accum.stop(), + seed(accum.fetch()); + if (!gnt--) + prng(), gnt = 255; + return r[gnt]; + }; +})(); diff --git a/node_modules/bcryptjs/src/bcrypt/util.js b/node_modules/bcryptjs/src/bcrypt/util.js new file mode 100644 index 0000000..a149f71 --- /dev/null +++ b/node_modules/bcryptjs/src/bcrypt/util.js @@ -0,0 +1,33 @@ +/** + * Continues with the callback on the next tick. + * @function + * @param {function(...[*])} callback Callback to execute + * @inner + */ +var nextTick = typeof process !== 'undefined' && process && typeof process.nextTick === 'function' + ? (typeof setImmediate === 'function' ? setImmediate : process.nextTick) + : setTimeout; + +/** + * Converts a JavaScript string to UTF8 bytes. + * @param {string} str String + * @returns {!Array.} UTF8 bytes + * @inner + */ +function stringToBytes(str) { + var out = [], + i = 0; + utfx.encodeUTF16toUTF8(function() { + if (i >= str.length) return null; + return str.charCodeAt(i++); + }, function(b) { + out.push(b); + }); + return out; +} + +//? include("util/base64.js"); + +//? include("../../node_modules/utfx/dist/utfx-embeddable.js"); + +Date.now = Date.now || function() { return +new Date; }; diff --git a/node_modules/bcryptjs/src/bcrypt/util/base64.js b/node_modules/bcryptjs/src/bcrypt/util/base64.js new file mode 100644 index 0000000..deda4af --- /dev/null +++ b/node_modules/bcryptjs/src/bcrypt/util/base64.js @@ -0,0 +1,115 @@ +// A base64 implementation for the bcrypt algorithm. This is partly non-standard. + +/** + * bcrypt's own non-standard base64 dictionary. + * @type {!Array.} + * @const + * @inner + **/ +var BASE64_CODE = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(''); + +/** + * @type {!Array.} + * @const + * @inner + **/ +var BASE64_INDEX = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, + 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, + -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1]; + +/** + * @type {!function(...number):string} + * @inner + */ +var stringFromCharCode = String.fromCharCode; + +/** + * Encodes a byte array to base64 with up to len bytes of input. + * @param {!Array.} b Byte array + * @param {number} len Maximum input length + * @returns {string} + * @inner + */ +function base64_encode(b, len) { + var off = 0, + rs = [], + c1, c2; + if (len <= 0 || len > b.length) + throw Error("Illegal len: "+len); + while (off < len) { + c1 = b[off++] & 0xff; + rs.push(BASE64_CODE[(c1 >> 2) & 0x3f]); + c1 = (c1 & 0x03) << 4; + if (off >= len) { + rs.push(BASE64_CODE[c1 & 0x3f]); + break; + } + c2 = b[off++] & 0xff; + c1 |= (c2 >> 4) & 0x0f; + rs.push(BASE64_CODE[c1 & 0x3f]); + c1 = (c2 & 0x0f) << 2; + if (off >= len) { + rs.push(BASE64_CODE[c1 & 0x3f]); + break; + } + c2 = b[off++] & 0xff; + c1 |= (c2 >> 6) & 0x03; + rs.push(BASE64_CODE[c1 & 0x3f]); + rs.push(BASE64_CODE[c2 & 0x3f]); + } + return rs.join(''); +} + +/** + * Decodes a base64 encoded string to up to len bytes of output. + * @param {string} s String to decode + * @param {number} len Maximum output length + * @returns {!Array.} + * @inner + */ +function base64_decode(s, len) { + var off = 0, + slen = s.length, + olen = 0, + rs = [], + c1, c2, c3, c4, o, code; + if (len <= 0) + throw Error("Illegal len: "+len); + while (off < slen - 1 && olen < len) { + code = s.charCodeAt(off++); + c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + code = s.charCodeAt(off++); + c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + if (c1 == -1 || c2 == -1) + break; + o = (c1 << 2) >>> 0; + o |= (c2 & 0x30) >> 4; + rs.push(stringFromCharCode(o)); + if (++olen >= len || off >= slen) + break; + code = s.charCodeAt(off++); + c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + if (c3 == -1) + break; + o = ((c2 & 0x0f) << 4) >>> 0; + o |= (c3 & 0x3c) >> 2; + rs.push(stringFromCharCode(o)); + if (++olen >= len || off >= slen) + break; + code = s.charCodeAt(off++); + c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + o = ((c3 & 0x03) << 6) >>> 0; + o |= c4; + rs.push(stringFromCharCode(o)); + ++olen; + } + var res = []; + for (off = 0; off + Copyright (c) 2012 Shane Girish + Copyright (c) 2014 Daniel Wirtz + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @license bcrypt.js (c) 2013 Daniel Wirtz + * Released under the Apache License, Version 2.0 + * see: https://github.com/dcodeIO/bcrypt.js for details + */ +(function(global, factory) { + + /* AMD */ if (typeof define === 'function' && define["amd"]) + define([], factory); + /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"]) + module["exports"] = factory(); + /* Global */ else + (global["dcodeIO"] = global["dcodeIO"] || {})["bcrypt"] = factory(); + +}(this, function() { + "use strict"; + + //? include("bcrypt.js"); + + return bcrypt; +})); diff --git a/node_modules/bcryptjs/tests/quickbrown.txt b/node_modules/bcryptjs/tests/quickbrown.txt new file mode 100644 index 0000000..81e850f --- /dev/null +++ b/node_modules/bcryptjs/tests/quickbrown.txt @@ -0,0 +1,150 @@ +Sentences that contain all letters commonly used in a language +-------------------------------------------------------------- + +Markus Kuhn -- 2012-04-11 + +This is an example of a plain-text file encoded in UTF-8. + + +Danish (da) +--------- + + Quizdeltagerne spiste jordbær med fløde, mens cirkusklovnen + Wolther spillede på xylofon. + (= Quiz contestants were eating strawbery with cream while Wolther + the circus clown played on xylophone.) + +German (de) +----------- + + Falsches Üben von Xylophonmusik quält jeden größeren Zwerg + (= Wrongful practicing of xylophone music tortures every larger dwarf) + + Zwölf Boxkämpfer jagten Eva quer über den Sylter Deich + (= Twelve boxing fighters hunted Eva across the dike of Sylt) + + Heizölrückstoßabdämpfung + (= fuel oil recoil absorber) + (jqvwxy missing, but all non-ASCII letters in one word) + +Greek (el) +---------- + + Γαζέες καὶ μυρτιὲς δὲν θὰ βρῶ πιὰ στὸ χρυσαφὶ ξέφωτο + (= No more shall I see acacias or myrtles in the golden clearing) + + Ξεσκεπάζω τὴν ψυχοφθόρα βδελυγμία + (= I uncover the soul-destroying abhorrence) + +English (en) +------------ + + The quick brown fox jumps over the lazy dog + +Spanish (es) +------------ + + El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y + frío, añoraba a su querido cachorro. + (Contains every letter and every accent, but not every combination + of vowel + acute.) + +French (fr) +----------- + + Portez ce vieux whisky au juge blond qui fume sur son île intérieure, à + côté de l'alcôve ovoïde, où les bûches se consument dans l'âtre, ce + qui lui permet de penser à la cænogenèse de l'être dont il est question + dans la cause ambiguë entendue à Moÿ, dans un capharnaüm qui, + pense-t-il, diminue çà et là la qualité de son œuvre. + + l'île exiguë + Où l'obèse jury mûr + Fête l'haï volapük, + Âne ex aéquo au whist, + Ôtez ce vœu déçu. + + Le cœur déçu mais l'âme plutôt naïve, Louÿs rêva de crapaüter en + canoë au delà des îles, près du mälström où brûlent les novæ. + +Irish Gaelic (ga) +----------------- + + D'fhuascail Íosa, Úrmhac na hÓighe Beannaithe, pór Éava agus Ádhaimh + +Hungarian (hu) +-------------- + + Árvíztűrő tükörfúrógép + (= flood-proof mirror-drilling machine, only all non-ASCII letters) + +Icelandic (is) +-------------- + + Kæmi ný öxi hér ykist þjófum nú bæði víl og ádrepa + + Sævör grét áðan því úlpan var ónýt + (some ASCII letters missing) + +Japanese (jp) +------------- + + Hiragana: (Iroha) + + いろはにほへとちりぬるを + わかよたれそつねならむ + うゐのおくやまけふこえて + あさきゆめみしゑひもせす + + Katakana: + + イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム + ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン + +Hebrew (iw) +----------- + + ? דג סקרן שט בים מאוכזב ולפתע מצא לו חברה איך הקליטה + +Polish (pl) +----------- + + Pchnąć w tę łódź jeża lub ośm skrzyń fig + (= To push a hedgehog or eight bins of figs in this boat) + +Russian (ru) +------------ + + В чащах юга жил бы цитрус? Да, но фальшивый экземпляр! + (= Would a citrus live in the bushes of south? Yes, but only a fake one!) + + Съешь же ещё этих мягких французских булок да выпей чаю + (= Eat some more of these fresh French loafs and have some tea) + +Thai (th) +--------- + + [--------------------------|------------------------] + ๏ เป็นมนุษย์สุดประเสริฐเลิศคุณค่า กว่าบรรดาฝูงสัตว์เดรัจฉาน + จงฝ่าฟันพัฒนาวิชาการ อย่าล้างผลาญฤๅเข่นฆ่าบีฑาใคร + ไม่ถือโทษโกรธแช่งซัดฮึดฮัดด่า หัดอภัยเหมือนกีฬาอัชฌาสัย + ปฏิบัติประพฤติกฎกำหนดใจ พูดจาให้จ๊ะๆ จ๋าๆ น่าฟังเอย ฯ + + [The copyright for the Thai example is owned by The Computer + Association of Thailand under the Royal Patronage of His Majesty the + King.] + +Turkish (tr) +------------ + + Pijamalı hasta, yağız şoföre çabucak güvendi. + (=Patient with pajamas, trusted swarthy driver quickly) + + +Special thanks to the people from all over the world who contributed +these sentences since 1999. + +A much larger collection of such pangrams is now available at + + http://en.wikipedia.org/wiki/List_of_pangrams + diff --git a/node_modules/bcryptjs/tests/suite.js b/node_modules/bcryptjs/tests/suite.js new file mode 100644 index 0000000..8c8afe1 --- /dev/null +++ b/node_modules/bcryptjs/tests/suite.js @@ -0,0 +1,197 @@ +var path = require("path"), + fs = require("fs"), + binding = require("bcrypt"), + bcrypt = require(path.join(__dirname, '..', 'index.js'))/*, + isaac = eval( + fs.readFileSync(path.join(__dirname, "..", "src", "bcrypt", "prng", "accum.js"))+ + fs.readFileSync(path.join(__dirname, "..", "src", "bcrypt", "prng", "isaac.js"))+ + " accum.start();"+ + " isaac" + )*/; + +module.exports = { + + "encodeBase64": function(test) { + var str = bcrypt.encodeBase64([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10], 16); + test.strictEqual(str, "..CA.uOD/eaGAOmJB.yMBu"); + test.done(); + }, + + "decodeBase64": function(test) { + var bytes = bcrypt.decodeBase64("..CA.uOD/eaGAOmJB.yMBv.", 16); + test.deepEqual(bytes, [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]); + test.done(); + }, + + "genSaltSync": function(test) { + var salt = bcrypt.genSaltSync(10); + test.ok(salt); + test.ok(typeof salt == 'string'); + test.ok(salt.length > 0); + test.done(); + }, + + "genSalt": function(test) { + bcrypt.genSalt(10, function(err, salt) { + test.ok(salt); + test.ok(typeof salt == 'string'); + test.ok(salt.length > 0); + test.done(); + }); + }, + + "hashSync": function(test) { + test.doesNotThrow(function() { + bcrypt.hashSync("hello", 10); + }); + test.notEqual(bcrypt.hashSync("hello", 10), bcrypt.hashSync("hello", 10)); + test.done(); + }, + + "hash": function(test) { + bcrypt.hash("hello", 10, function(err, hash) { + test.notOk(err); + test.ok(hash); + test.done(); + }); + }, + + "compareSync": function(test) { + var salt1 = bcrypt.genSaltSync(), + hash1 = bcrypt.hashSync("hello", salt1); // $2a$ + var salt2 = bcrypt.genSaltSync().replace(/\$2a\$/, "$2y$"), + hash2 = bcrypt.hashSync("world", salt2); + var salt3 = bcrypt.genSaltSync().replace(/\$2a\$/, "$2b$"), + hash3 = bcrypt.hashSync("hello world", salt3); + + test.strictEqual(hash1.substring(0,4), "$2a$"); + test.ok(bcrypt.compareSync("hello", hash1)); + test.notOk(bcrypt.compareSync("hello", hash2)); + test.notOk(bcrypt.compareSync("hello", hash3)); + + test.strictEqual(hash2.substring(0,4), "$2y$"); + test.ok(bcrypt.compareSync("world", hash2)); + test.notOk(bcrypt.compareSync("world", hash1)); + test.notOk(bcrypt.compareSync("world", hash3)); + + test.strictEqual(hash3.substring(0,4), "$2b$"); + test.ok(bcrypt.compareSync("hello world", hash3)); + test.notOk(bcrypt.compareSync("hello world", hash1)); + test.notOk(bcrypt.compareSync("hello world", hash2)); + + test.done(); + }, + + "compare": function(test) { + var salt1 = bcrypt.genSaltSync(), + hash1 = bcrypt.hashSync("hello", salt1); // $2a$ + var salt2 = bcrypt.genSaltSync(); + salt2 = salt2.substring(0,2)+'y'+salt2.substring(3); // $2y$ + var hash2 = bcrypt.hashSync("world", salt2); + bcrypt.compare("hello", hash1, function(err, same) { + test.notOk(err); + test.ok(same); + bcrypt.compare("hello", hash2, function(err, same) { + test.notOk(err); + test.notOk(same); + bcrypt.compare("world", hash2, function(err, same) { + test.notOk(err); + test.ok(same); + bcrypt.compare("world", hash1, function(err, same) { + test.notOk(err); + test.notOk(same); + test.done(); + }); + }); + }); + }); + }, + + "getSalt": function(test) { + var hash1 = bcrypt.hashSync("hello", bcrypt.genSaltSync()); + var salt = bcrypt.getSalt(hash1); + var hash2 = bcrypt.hashSync("hello", salt); + test.equal(hash1, hash2); + test.done(); + }, + + "getRounds": function(test) { + var hash1 = bcrypt.hashSync("hello", bcrypt.genSaltSync()); + test.equal(bcrypt.getRounds(hash1), 10); + test.done(); + }, + + "progress": function(test) { + bcrypt.genSalt(12, function(err, salt) { + test.ok(!err); + var progress = []; + bcrypt.hash("hello world", salt, function(err, hash) { + test.ok(!err); + test.ok(typeof hash === 'string'); + test.ok(progress.length >= 2); + test.strictEqual(progress[0], 0); + test.strictEqual(progress[progress.length-1], 1); + test.done(); + }, function(n) { + progress.push(n); + }); + }); + }, + + "promise": function(test) { + bcrypt.genSalt(10) + .then(function(salt) { + bcrypt.hash("hello", salt) + .then(function(hash) { + test.ok(hash); + bcrypt.compare("hello", hash) + .then(function(result) { + test.ok(result); + bcrypt.genSalt(/* no args */) + .then(function(salt) { + test.ok(salt); + test.done(); + }, function(err) { + test.fail(err, null, "promise rejected"); + }); + }, function(err) { + test.fail(err, null, "promise rejected"); + }); + }, function(err) { + test.fail(err, null, 'promise rejected'); + }); + }, function(err) { + test.fail(err, null, "promise rejected"); + }); + }, + + "compat": { + "quickbrown": function(test) { + var pass = fs.readFileSync(path.join(__dirname, "quickbrown.txt"))+"", + salt = bcrypt.genSaltSync(), + hash1 = binding.hashSync(pass, salt), + hash2 = bcrypt.hashSync(pass, salt); + test.equal(hash1, hash2); + test.done(); + }, + + "roundsOOB": function(test) { + var salt1 = bcrypt.genSaltSync(0), // $10$ like not set + salt2 = binding.genSaltSync(0); + test.strictEqual(salt1.substring(0, 7), "$2a$10$"); + test.strictEqual(salt2.substring(0, 7), "$2a$10$"); + + salt1 = bcrypt.genSaltSync(3); // $04$ is lower cap + salt2 = bcrypt.genSaltSync(3); + test.strictEqual(salt1.substring(0, 7), "$2a$04$"); + test.strictEqual(salt2.substring(0, 7), "$2a$04$"); + + salt1 = bcrypt.genSaltSync(32); // $31$ is upper cap + salt2 = bcrypt.genSaltSync(32); + test.strictEqual(salt1.substring(0, 7), "$2a$31$"); + test.strictEqual(salt2.substring(0, 7), "$2a$31$"); + + test.done(); + } + } +}; diff --git a/node_modules/body-parser/HISTORY.md b/node_modules/body-parser/HISTORY.md new file mode 100644 index 0000000..a1d3fbf --- /dev/null +++ b/node_modules/body-parser/HISTORY.md @@ -0,0 +1,609 @@ +1.19.0 / 2019-04-25 +=================== + + * deps: bytes@3.1.0 + - Add petabyte (`pb`) support + * deps: http-errors@1.7.2 + - Set constructor name when possible + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: iconv-lite@0.4.24 + - Added encoding MIK + * deps: qs@6.7.0 + - Fix parsing array brackets after index + * deps: raw-body@2.4.0 + - deps: bytes@3.1.0 + - deps: http-errors@1.7.2 + - deps: iconv-lite@0.4.24 + * deps: type-is@~1.6.17 + - deps: mime-types@~2.1.24 + - perf: prevent internal `throw` on invalid type + +1.18.3 / 2018-05-14 +=================== + + * Fix stack trace for strict json parse error + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: http-errors@~1.6.3 + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.0 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.23 + - Fix loading encoding with year appended + - Fix deprecation warnings on Node.js 10+ + * deps: qs@6.5.2 + * deps: raw-body@2.3.3 + - deps: http-errors@1.6.3 + - deps: iconv-lite@0.4.23 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +1.18.2 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: remove argument reassignment + +1.18.1 / 2017-09-12 +=================== + + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: raw-body@2.3.2 + - deps: iconv-lite@0.4.19 + +1.18.0 / 2017-09-08 +=================== + + * Fix JSON strict violation error to match native parse error + * Include the `body` property on verify errors + * Include the `type` property on all generated errors + * Use `http-errors` to set status code on errors + * deps: bytes@3.0.0 + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + * deps: qs@6.5.0 + * deps: raw-body@2.3.1 + - Use `http-errors` for standard emitted errors + - deps: bytes@3.0.0 + - deps: iconv-lite@0.4.18 + - perf: skip buffer decoding on overage chunk + * perf: prevent internal `throw` when missing charset + +1.17.2 / 2017-05-17 +=================== + + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + +1.17.1 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +1.17.0 / 2017-03-01 +=================== + + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + * deps: qs@6.3.1 + - Fix compacting nested arrays + +1.16.1 / 2017-02-10 +=================== + + * deps: debug@2.6.1 + - Fix deprecation messages in WebStorm and other editors + - Undeprecate `DEBUG_FD` set to `1` or `2` + +1.16.0 / 2017-01-17 +=================== + + * deps: debug@2.6.0 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + * deps: qs@6.2.1 + - Fix array parsing from skipping empty values + * deps: raw-body@~2.2.0 + - deps: iconv-lite@0.4.15 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +1.15.2 / 2016-06-19 +=================== + + * deps: bytes@2.4.0 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: http-errors@~1.5.0 + - Use `setprototypeof` module to replace `__proto__` setting + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: qs@6.2.0 + * deps: raw-body@~2.1.7 + - deps: bytes@2.4.0 + - perf: remove double-cleanup on happy path + * deps: type-is@~1.6.13 + - deps: mime-types@~2.1.11 + +1.15.1 / 2016-05-05 +=================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + * deps: raw-body@~2.1.6 + - deps: bytes@2.3.0 + * deps: type-is@~1.6.12 + - deps: mime-types@~2.1.10 + +1.15.0 / 2016-02-10 +=================== + + * deps: http-errors@~1.4.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.2.1 < 2' + * deps: qs@6.1.0 + * deps: type-is@~1.6.11 + - deps: mime-types@~2.1.9 + +1.14.2 / 2015-12-16 +=================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + * deps: qs@5.2.0 + * deps: raw-body@~2.1.5 + - deps: bytes@2.2.0 + - deps: iconv-lite@0.4.13 + * deps: type-is@~1.6.10 + - deps: mime-types@~2.1.8 + +1.14.1 / 2015-09-27 +=================== + + * Fix issue where invalid charset results in 400 when `verify` used + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + * deps: raw-body@~2.1.4 + - Fix masking critical errors from `iconv-lite` + - deps: iconv-lite@0.4.12 + * deps: type-is@~1.6.9 + - deps: mime-types@~2.1.7 + +1.14.0 / 2015-09-16 +=================== + + * Fix JSON strict parse error to match syntax errors + * Provide static `require` analysis in `urlencoded` parser + * deps: depd@~1.1.0 + - Support web browser loading + * deps: qs@5.1.0 + * deps: raw-body@~2.1.3 + - Fix sync callback when attaching data listener causes sync read + * deps: type-is@~1.6.8 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.6 + +1.13.3 / 2015-07-31 +=================== + + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +1.13.2 / 2015-07-05 +=================== + + * deps: iconv-lite@0.4.11 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix user-visible incompatibilities from 3.1.0 + - Fix various parsing edge cases + * deps: raw-body@~2.1.2 + - Fix error stack traces to skip `makeError` + - deps: iconv-lite@0.4.11 + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +1.13.1 / 2015-06-16 +=================== + + * deps: qs@2.4.2 + - Downgraded from 3.1.0 because of user-visible incompatibilities + +1.13.0 / 2015-06-14 +=================== + + * Add `statusCode` property on `Error`s, in addition to `status` + * Change `type` default to `application/json` for JSON parser + * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser + * Provide static `require` analysis + * Use the `http-errors` module to generate errors + * deps: bytes@2.1.0 + - Slight optimizations + * deps: iconv-lite@0.4.10 + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + - Leading BOM is now removed when decoding + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: qs@3.1.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + - Parsed object now has `null` prototype + * deps: raw-body@~2.1.1 + - Use `unpipe` module for unpiping requests + - deps: iconv-lite@0.4.10 + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: remove argument reassignment + * perf: remove delete call + +1.12.4 / 2015-05-10 +=================== + + * deps: debug@~2.2.0 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: on-finished@~2.2.1 + * deps: raw-body@~2.0.1 + - Fix a false-positive when unpiping in Node.js 0.8 + - deps: bytes@2.0.1 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +1.12.3 / 2015-04-15 +=================== + + * Slight efficiency improvement when not debugging + * deps: depd@~1.0.1 + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + * deps: raw-body@1.3.4 + - Fix hanging callback if request aborts during read + - deps: iconv-lite@0.4.8 + +1.12.2 / 2015-03-16 +=================== + + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + +1.12.1 / 2015-03-15 +=================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +1.12.0 / 2015-02-13 +=================== + + * add `debug` messages + * accept a function for the `type` option + * use `content-type` to parse `Content-Type` headers + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + * deps: raw-body@1.3.3 + - deps: iconv-lite@0.4.7 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +1.11.0 / 2015-01-30 +=================== + + * make internal `extended: true` depth limit infinity + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +1.10.2 / 2015-01-20 +=================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + * deps: raw-body@1.3.2 + - deps: iconv-lite@0.4.6 + +1.10.1 / 2015-01-01 +=================== + + * deps: on-finished@~2.2.0 + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +1.10.0 / 2014-12-02 +=================== + + * make internal `extended: true` array limit dynamic + +1.9.3 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + * deps: raw-body@1.3.1 + - deps: iconv-lite@0.4.5 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +1.9.2 / 2014-10-27 +================== + + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +1.9.1 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +1.9.0 / 2014-09-24 +================== + + * include the charset in "unsupported charset" error message + * include the encoding in "unsupported content encoding" error message + * deps: depd@~1.0.0 + +1.8.4 / 2014-09-23 +================== + + * fix content encoding to be case-insensitive + +1.8.3 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +1.8.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + +1.8.1 / 2014-09-07 +================== + + * deps: media-typer@0.3.0 + * deps: type-is@~1.5.1 + +1.8.0 / 2014-09-05 +================== + + * make empty-body-handling consistent between chunked requests + - empty `json` produces `{}` + - empty `raw` produces `new Buffer(0)` + - empty `text` produces `''` + - empty `urlencoded` produces `{}` + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: type-is@~1.5.0 + - fix `hasbody` to be true for `content-length: 0` + +1.7.0 / 2014-09-01 +================== + + * add `parameterLimit` option to `urlencoded` parser + * change `urlencoded` extended array limit to 100 + * respond with 413 when over `parameterLimit` in `urlencoded` + +1.6.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +1.6.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +1.6.5 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.6.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + +1.6.3 / 2014-08-10 +================== + + * deps: qs@1.2.1 + +1.6.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +1.6.1 / 2014-08-06 +================== + + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +1.6.0 / 2014-08-05 +================== + + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + +1.5.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.5.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.5.0 / 2014-07-20 +================== + + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + * deps: raw-body@1.3.0 + - deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + - Fix `Cannot switch to old mode now` error on Node.js 0.10+ + * deps: type-is@~1.3.2 + +1.4.3 / 2014-06-19 +================== + + * deps: type-is@1.3.1 + - fix global variable leak + +1.4.2 / 2014-06-19 +================== + + * deps: type-is@1.3.0 + - improve type parsing + +1.4.1 / 2014-06-19 +================== + + * fix urlencoded extended deprecation message + +1.4.0 / 2014-06-19 +================== + + * add `text` parser + * add `raw` parser + * check accepted charset in content-type (accepts utf-8) + * check accepted encoding in content-encoding (accepts identity) + * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed + * deprecate `urlencoded()` without provided `extended` option + * lazy-load urlencoded parsers + * parsers split into files for reduced mem usage + * support gzip and deflate bodies + - set `inflate: false` to turn off + * deps: raw-body@1.2.2 + - Support all encodings from `iconv-lite` + +1.3.1 / 2014-06-11 +================== + + * deps: type-is@1.2.1 + - Switch dependency from mime to mime-types@1.0.0 + +1.3.0 / 2014-05-31 +================== + + * add `extended` option to urlencoded parser + +1.2.2 / 2014-05-27 +================== + + * deps: raw-body@1.1.6 + - assert stream encoding on node.js 0.8 + - assert stream encoding on node.js < 0.10.6 + - deps: bytes@1 + +1.2.1 / 2014-05-26 +================== + + * invoke `next(err)` after request fully read + - prevents hung responses and socket hang ups + +1.2.0 / 2014-05-11 +================== + + * add `verify` option + * deps: type-is@1.2.0 + - support suffix matching + +1.1.2 / 2014-05-11 +================== + + * improve json parser speed + +1.1.1 / 2014-05-11 +================== + + * fix repeated limit parsing with every request + +1.1.0 / 2014-05-10 +================== + + * add `type` option + * deps: pin for safety and consistency + +1.0.2 / 2014-04-14 +================== + + * use `type-is` module + +1.0.1 / 2014-03-20 +================== + + * lower default limits to 100kb diff --git a/node_modules/body-parser/LICENSE b/node_modules/body-parser/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/body-parser/README.md b/node_modules/body-parser/README.md new file mode 100644 index 0000000..aba6297 --- /dev/null +++ b/node_modules/body-parser/README.md @@ -0,0 +1,443 @@ +# body-parser + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js body parsing middleware. + +Parse incoming request bodies in a middleware before your handlers, available +under the `req.body` property. + +**Note** As `req.body`'s shape is based on user-controlled input, all +properties and values in this object are untrusted and should be validated +before trusting. For example, `req.body.foo.toString()` may fail in multiple +ways, for example the `foo` property may not be there or may not be a string, +and `toString` may not be a function and instead a string or other user input. + +[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.org/package/busboy#readme) and + [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.org/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.org/package/formidable#readme) + * [multer](https://www.npmjs.org/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.org/package/body#readme) +- [co-body](https://www.npmjs.org/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + + + +```js +var bodyParser = require('body-parser') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body when +the `Content-Type` request header matches the `type` option, or an empty +object (`{}`) if there was no body to parse, the `Content-Type` was not matched, +or an error occurred. + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json([options]) + +Returns middleware that only parses `json` and only looks at requests where +the `Content-Type` header matches the `type` option. This parser accepts any +Unicode encoding of the body and supports automatic inflation of `gzip` and +`deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not a +function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `json`), a mime type (like `application/json`), or +a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a truthy +value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw([options]) + +Returns middleware that parses all bodies as a `Buffer` and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. +If not a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this +can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text([options]) + +Returns middleware that parses all bodies as a string and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `txt`), a mime type (like `text/plain`), or a mime +type with a wildcard (like `*/*` or `text/*`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a +truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded([options]) + +Returns middleware that only parses `urlencoded` bodies and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser accepts only UTF-8 encoding of the body and supports automatic +inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an optional `options` object that may contain +any of the following keys: + +##### extended + +The `extended` option allows to choose between parsing the URL-encoded data +with the `querystring` library (when `false`) or the `qs` library (when +`true`). The "extended" syntax allows for rich objects and arrays to be +encoded into the URL-encoded format, allowing for a JSON-like experience +with URL-encoded. For more information, please +[see the qs library](https://www.npmjs.org/package/qs#readme). + +Defaults to `true`, but using the default has been deprecated. Please +research into the difference between `qs` and `querystring` and choose the +appropriate setting. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +## Errors + +The middlewares provided by this module create errors depending on the error +condition during parsing. The errors will typically have a `status`/`statusCode` +property that contains the suggested HTTP response code, an `expose` property +to determine if the `message` property should be displayed to the client, a +`type` property to determine the type of error without matching against the +`message`, and a `body` property containing the read body, if available. + +The following are the common errors emitted, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`, the `type` property is set to +`'encoding.unsupported'`, and the `charset` property will be set to the +encoding that is unsupported. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400` +and `type` property is set to `'request.aborted'`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413` and the `type` property is set to `'entity.too.large'`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400` and the `type` property +is set to `'request.size.invalid'`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500` and the `type` property is set to `'stream.encoding.set'`. + +### too many parameters + +This error will occur when the content of the request exceeds the configured +`parameterLimit` for the `urlencoded` parser. The `status` property is set to +`413` and the `type` property is set to `'parameters.too.many'`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`, the +`type` property is set to `'charset.unsupported'`, and the `charset` property +is set to the charset that is unsupported. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`, +the `type` property is set to `'encoding.unsupported'`, and the `encoding` +property is set to the encoding that is unsupported. + +## Examples + +### Express/Connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded({ extended: false })) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(JSON.stringify(req.body, null, 2)) +}) +``` + +### Express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommended way to use body-parser with +Express. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// create application/json parser +var jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +var urlencodedParser = bodyParser.urlencoded({ extended: false }) + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + // create user in req.body +}) +``` + +### Change accepted type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/body-parser.svg +[npm-url]: https://npmjs.org/package/body-parser +[travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg +[travis-url]: https://travis-ci.org/expressjs/body-parser +[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg +[downloads-url]: https://npmjs.org/package/body-parser diff --git a/node_modules/body-parser/index.js b/node_modules/body-parser/index.js new file mode 100644 index 0000000..93c3a1f --- /dev/null +++ b/node_modules/body-parser/index.js @@ -0,0 +1,157 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('body-parser') + +/** + * Cache of loaded parsers. + * @private + */ + +var parsers = Object.create(null) + +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ + +/** + * Module exports. + * @type {Parsers} + */ + +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') + +/** + * JSON parser. + * @public + */ + +Object.defineProperty(exports, 'json', { + configurable: true, + enumerable: true, + get: createParserGetter('json') +}) + +/** + * Raw parser. + * @public + */ + +Object.defineProperty(exports, 'raw', { + configurable: true, + enumerable: true, + get: createParserGetter('raw') +}) + +/** + * Text parser. + * @public + */ + +Object.defineProperty(exports, 'text', { + configurable: true, + enumerable: true, + get: createParserGetter('text') +}) + +/** + * URL-encoded parser. + * @public + */ + +Object.defineProperty(exports, 'urlencoded', { + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ + +function bodyParser (options) { + var opts = {} + + // exclude type option + if (options) { + for (var prop in options) { + if (prop !== 'type') { + opts[prop] = options[prop] + } + } + } + + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) + } +} + +/** + * Create a getter for loading a parser. + * @private + */ + +function createParserGetter (name) { + return function get () { + return loadParser(name) + } +} + +/** + * Load a parser module. + * @private + */ + +function loadParser (parserName) { + var parser = parsers[parserName] + + if (parser !== undefined) { + return parser + } + + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = require('./lib/types/json') + break + case 'raw': + parser = require('./lib/types/raw') + break + case 'text': + parser = require('./lib/types/text') + break + case 'urlencoded': + parser = require('./lib/types/urlencoded') + break + } + + // store to prevent invoking require() + return (parsers[parserName] = parser) +} diff --git a/node_modules/body-parser/lib/read.js b/node_modules/body-parser/lib/read.js new file mode 100644 index 0000000..c102609 --- /dev/null +++ b/node_modules/body-parser/lib/read.js @@ -0,0 +1,181 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var zlib = require('zlib') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} options + * @private + */ + +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream + + // flag as parsed + req._body = true + + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // read off entire request + stream.resume() + onFinished(req, function onfinished () { + next(createError(400, _error)) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ + +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + return stream +} diff --git a/node_modules/body-parser/lib/types/json.js b/node_modules/body-parser/lib/types/json.js new file mode 100644 index 0000000..2971dc1 --- /dev/null +++ b/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,230 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:json') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ + +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex + +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function json (options) { + var opts = options || {} + + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + } + + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } + } + + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.substr(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @return {Error} + * @private + */ + +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = str.substring(0, index) + '#' + + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace('#', char), + stack: e.stack + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @private + */ + +function firstchar (str) { + return FIRST_CHAR_REGEXP.exec(str)[1] +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} + */ + +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } + } + + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message + + return error +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/lib/types/raw.js b/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 0000000..f5d1b67 --- /dev/null +++ b/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,101 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var debug = require('debug')('body-parser:raw') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw (options) { + var opts = options || {} + + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function rawParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/lib/types/text.js b/node_modules/body-parser/lib/types/text.js new file mode 100644 index 0000000..083a009 --- /dev/null +++ b/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,121 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var debug = require('debug')('body-parser:text') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function text (options) { + var opts = options || {} + + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/lib/types/urlencoded.js b/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 0000000..b2ca8f1 --- /dev/null +++ b/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,284 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:urlencoded') +var deprecate = require('depd')('body-parser') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Cache of parser modules. + */ + +var parsers = Object.create(null) + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function urlencoded (options) { + var opts = options || {} + + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } + + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + return body.length + ? queryparse(body) + : {} + } + + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the extended query parser. + * + * @param {object} options + */ + +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + var arrayLimit = Math.max(100, paramCount) + + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ + +function parameterCount (body, limit) { + var count = 0 + var index = 0 + + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ + + if (count === limit) { + return undefined + } + } + + return count +} + +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ + +function parser (name) { + var mod = parsers[name] + + if (mod !== undefined) { + return mod.parse + } + + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = require('qs') + break + case 'querystring': + mod = require('querystring') + break + } + + // store to prevent invoking require() + parsers[name] = mod + + return mod.parse +} + +/** + * Get the simple query parser. + * + * @param {object} options + */ + +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + debug('parse urlencoding') + return parse(body, undefined, undefined, { maxKeys: parameterLimit }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/package.json b/node_modules/body-parser/package.json new file mode 100644 index 0000000..269ebf2 --- /dev/null +++ b/node_modules/body-parser/package.json @@ -0,0 +1,52 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "1.19.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "expressjs/body-parser", + "dependencies": { + "bytes": "3.1.0", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.2", + "http-errors": "1.7.2", + "iconv-lite": "0.4.24", + "on-finished": "~2.3.0", + "qs": "6.7.0", + "raw-body": "2.4.0", + "type-is": "~1.6.17" + }, + "devDependencies": { + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "methods": "1.1.2", + "mocha": "6.1.4", + "safe-buffer": "5.1.2", + "supertest": "4.0.2" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/brace-expansion/LICENSE b/node_modules/brace-expansion/LICENSE new file mode 100644 index 0000000..de32266 --- /dev/null +++ b/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +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/brace-expansion/README.md b/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..6b4e0e1 --- /dev/null +++ b/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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/brace-expansion/index.js b/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..0478be8 --- /dev/null +++ b/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/node_modules/brace-expansion/package.json b/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..a18faa8 --- /dev/null +++ b/node_modules/brace-expansion/package.json @@ -0,0 +1,47 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "1.1.11", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh", + "bench": "matcha test/perf/bench.js" + }, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/bson/LICENSE.md b/node_modules/bson/LICENSE.md new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/node_modules/bson/LICENSE.md @@ -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/bson/README.md b/node_modules/bson/README.md new file mode 100644 index 0000000..cd7242f --- /dev/null +++ b/node_modules/bson/README.md @@ -0,0 +1,376 @@ +# BSON parser + +BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents. You can learn more about it in [the specification](http://bsonspec.org). + +This browser version of the BSON parser is compiled using [rollup](https://rollupjs.org/) and the current version is pre-compiled in the `dist` directory. + +This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). + +### Table of Contents +- [Usage](#usage) +- [Bugs/Feature Requests](#bugs--feature-requests) +- [Installation](#installation) +- [Documentation](#documentation) +- [FAQ](#faq) + +## Bugs / Feature Requests + +Think you've found a bug? Want to see a new feature in `bson`? Please open a case in our issue management tool, JIRA: + +1. Create an account and login: [jira.mongodb.org](https://jira.mongodb.org) +2. Navigate to the NODE project: [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE) +3. Click **Create Issue** - Please provide as much information as possible about the issue and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are **public**. + +## Usage + +To build a new version perform the following operations: + +``` +npm install +npm run build +``` + +### Node (no bundling) +A simple example of how to use BSON in `Node.js`: + +```js +const BSON = require('bson'); +const Long = BSON.Long; + +// Serialize a document +const doc = { long: Long.fromNumber(100) }; +const data = BSON.serialize(doc); +console.log('data:', data); + +// Deserialize the resulting Buffer +const doc_2 = BSON.deserialize(data); +console.log('doc_2:', doc_2); +``` + +### Browser (no bundling) + +If you are not using a bundler like webpack, you can include `dist/bson.bundle.js` using a script tag. It includes polyfills for built-in node types like `Buffer`. + +```html + + + +``` + +### Using webpack + +If using webpack, you can use your normal import/require syntax of your project to pull in the `bson` library. + +ES6 Example: + +```js +import { Long, serialize, deserialize } from 'bson'; + +// Serialize a document +const doc = { long: Long.fromNumber(100) }; +const data = serialize(doc); +console.log('data:', data); + +// De serialize it again +const doc_2 = deserialize(data); +console.log('doc_2:', doc_2); +``` + +ES5 Example: + +```js +const BSON = require('bson'); +const Long = BSON.Long; + +// Serialize a document +const doc = { long: Long.fromNumber(100) }; +const data = BSON.serialize(doc); +console.log('data:', data); + +// Deserialize the resulting Buffer +const doc_2 = BSON.deserialize(data); +console.log('doc_2:', doc_2); +``` + +Depending on your settings, webpack will under the hood resolve to one of the following: + +- `dist/bson.browser.esm.js` If your project is in the browser and using ES6 modules (Default for `webworker` and `web` targets) +- `dist/bson.browser.umd.js` If your project is in the browser and not using ES6 modules +- `dist/bson.esm.js` If your project is in Node.js and using ES6 modules (Default for `node` targets) +- `lib/bson.js` (the normal include path) If your project is in Node.js and not using ES6 modules + +For more information, see [this page on webpack's `resolve.mainFields`](https://webpack.js.org/configuration/resolve/#resolvemainfields) and [the `package.json` for this project](./package.json#L52) + +### Usage with Angular + +Starting with Angular 6, Angular CLI removed the shim for `global` and other node built-in variables (original comment [here](https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063)). If you are using BSON with Angular, you may need to add the following shim to your `polyfills.ts` file: + +```js +// In polyfills.ts +(window as any).global = window; +``` + +- [Original Comment by Angular CLI](https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063) +- [Original Source for Solution](https://stackoverflow.com/a/50488337/4930088) + +## Installation + +`npm install bson` + +## Documentation + +### Objects + +
+
EJSON : object
+
+
+ +### Functions + +
+
setInternalBufferSize(size)
+

Sets the size of the internal serialization buffer.

+
+
serialize(object)Buffer
+

Serialize a Javascript object.

+
+
serializeWithBufferAndIndex(object, buffer)Number
+

Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.

+
+
deserialize(buffer)Object
+

Deserialize data as BSON.

+
+
calculateObjectSize(object)Number
+

Calculate the bson size for a passed in Javascript object.

+
+
deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, [options])Number
+

Deserialize stream data as BSON documents.

+
+
+ + + +### EJSON + +* [EJSON](#EJSON) + + * [.parse(text, [options])](#EJSON.parse) + + * [.stringify(value, [replacer], [space], [options])](#EJSON.stringify) + + * [.serialize(bson, [options])](#EJSON.serialize) + + * [.deserialize(ejson, [options])](#EJSON.deserialize) + + + + +#### *EJSON*.parse(text, [options]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| text | string | | | +| [options] | object | | Optional settings | +| [options.relaxed] | boolean | true | Attempt to return native JS types where possible, rather than BSON types (if true) | + +Parse an Extended JSON string, constructing the JavaScript value or object described by that +string. + +**Example** +```js +const { EJSON } = require('bson'); +const text = '{ "int32": { "$numberInt": "10" } }'; + +// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } +console.log(EJSON.parse(text, { relaxed: false })); + +// prints { int32: 10 } +console.log(EJSON.parse(text)); +``` + + +#### *EJSON*.stringify(value, [replacer], [space], [options]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| value | object | | The value to convert to extended JSON | +| [replacer] | function \| array | | A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string | +| [space] | string \| number | | A String or Number object that's used to insert white space into the output JSON string for readability purposes. | +| [options] | object | | Optional settings | +| [options.relaxed] | boolean | true | Enabled Extended JSON's `relaxed` mode | +| [options.legacy] | boolean | true | Output in Extended JSON v1 | + +Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer +function is specified or optionally including only the specified properties if a replacer array +is specified. + +**Example** +```js +const { EJSON } = require('bson'); +const Int32 = require('mongodb').Int32; +const doc = { int32: new Int32(10) }; + +// prints '{"int32":{"$numberInt":"10"}}' +console.log(EJSON.stringify(doc, { relaxed: false })); + +// prints '{"int32":10}' +console.log(EJSON.stringify(doc)); +``` + + +#### *EJSON*.serialize(bson, [options]) + +| Param | Type | Description | +| --- | --- | --- | +| bson | object | The object to serialize | +| [options] | object | Optional settings passed to the `stringify` function | + +Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + + + +#### *EJSON*.deserialize(ejson, [options]) + +| Param | Type | Description | +| --- | --- | --- | +| ejson | object | The Extended JSON object to deserialize | +| [options] | object | Optional settings passed to the parse method | + +Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + + + +### setInternalBufferSize(size) + +| Param | Type | Description | +| --- | --- | --- | +| size | number | The desired size for the internal serialization buffer | + +Sets the size of the internal serialization buffer. + + + +### serialize(object) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| object | Object | | the Javascript object to serialize. | +| [options.checkKeys] | Boolean | | the serializer will check if keys are valid. | +| [options.serializeFunctions] | Boolean | false | serialize the javascript functions **(default:false)**. | +| [options.ignoreUndefined] | Boolean | true | ignore undefined fields **(default:true)**. | + +Serialize a Javascript object. + +**Returns**: Buffer - returns the Buffer object containing the serialized object. + + +### serializeWithBufferAndIndex(object, buffer) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| object | Object | | the Javascript object to serialize. | +| buffer | Buffer | | the Buffer you pre-allocated to store the serialized BSON object. | +| [options.checkKeys] | Boolean | | the serializer will check if keys are valid. | +| [options.serializeFunctions] | Boolean | false | serialize the javascript functions **(default:false)**. | +| [options.ignoreUndefined] | Boolean | true | ignore undefined fields **(default:true)**. | +| [options.index] | Number | | the index in the buffer where we wish to start serializing into. | + +Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + +**Returns**: Number - returns the index pointing to the last written byte in the buffer. + + +### deserialize(buffer) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Buffer | | the buffer containing the serialized set of BSON documents. | +| [options.evalFunctions] | Object | false | evaluate functions in the BSON document scoped to the object deserialized. | +| [options.cacheFunctions] | Object | false | cache evaluated functions for reuse. | +| [options.promoteLongs] | Object | true | when deserializing a Long will fit it into a Number if it's smaller than 53 bits | +| [options.promoteBuffers] | Object | false | when deserializing a Binary will return it as a node.js Buffer instance. | +| [options.promoteValues] | Object | false | when deserializing will promote BSON values to their Node.js closest equivalent types. | +| [options.fieldsAsRaw] | Object | | allow to specify if there what fields we wish to return as unserialized raw buffer. | +| [options.bsonRegExp] | Object | false | return BSON regular expressions as BSONRegExp instances. | +| [options.allowObjectSmallerThanBufferSize] | boolean | false | allows the buffer to be larger than the parsed BSON object | + +Deserialize data as BSON. + +**Returns**: Object - returns the deserialized Javascript Object. + + +### calculateObjectSize(object) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| object | Object | | the Javascript object to calculate the BSON byte size for. | +| [options.serializeFunctions] | Boolean | false | serialize the javascript functions **(default:false)**. | +| [options.ignoreUndefined] | Boolean | true | ignore undefined fields **(default:true)**. | + +Calculate the bson size for a passed in Javascript object. + +**Returns**: Number - returns the number of bytes the BSON object will take up. + + +### deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, [options]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| data | Buffer | | the buffer containing the serialized set of BSON documents. | +| startIndex | Number | | the start index in the data Buffer where the deserialization is to start. | +| numberOfDocuments | Number | | number of documents to deserialize. | +| documents | Array | | an array where to store the deserialized documents. | +| docStartIndex | Number | | the index in the documents array from where to start inserting documents. | +| [options] | Object | | additional options used for the deserialization. | +| [options.evalFunctions] | Object | false | evaluate functions in the BSON document scoped to the object deserialized. | +| [options.cacheFunctions] | Object | false | cache evaluated functions for reuse. | +| [options.promoteLongs] | Object | true | when deserializing a Long will fit it into a Number if it's smaller than 53 bits | +| [options.promoteBuffers] | Object | false | when deserializing a Binary will return it as a node.js Buffer instance. | +| [options.promoteValues] | Object | false | when deserializing will promote BSON values to their Node.js closest equivalent types. | +| [options.fieldsAsRaw] | Object | | allow to specify if there what fields we wish to return as unserialized raw buffer. | +| [options.bsonRegExp] | Object | false | return BSON regular expressions as BSONRegExp instances. | + +Deserialize stream data as BSON documents. + +**Returns**: Number - returns the next index in the buffer after deserialization **x** numbers of documents. + +## FAQ + +#### Why does `undefined` get converted to `null`? + +The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. + +#### How do I add custom serialization logic? + +This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. + +```javascript +const BSON = require('bson'); + +class CustomSerialize { + toBSON() { + return 42; + } +} + +const obj = { answer: new CustomSerialize() }; +// "{ answer: 42 }" +console.log(BSON.deserialize(BSON.serialize(obj))); +``` diff --git a/node_modules/bson/bower.json b/node_modules/bson/bower.json new file mode 100644 index 0000000..5f4b5f6 --- /dev/null +++ b/node_modules/bson/bower.json @@ -0,0 +1,26 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "author": "Christian Amor Kvalheim ", + "main": "./dist/bson.js", + "license": "Apache-2.0", + "moduleType": [ + "globals", + "node" + ], + "ignore": [ + "**/.*", + "alternate_parsers", + "benchmarks", + "bower_components", + "node_modules", + "test", + "tools" + ], + "version": "4.5.3" +} diff --git a/node_modules/bson/bson.d.ts b/node_modules/bson/bson.d.ts new file mode 100644 index 0000000..df0f317 --- /dev/null +++ b/node_modules/bson/bson.d.ts @@ -0,0 +1,1098 @@ +import { Buffer } from 'buffer'; +/** + * A class representation of the BSON Binary type. + * @public + */ +export declare class Binary { + _bsontype: 'Binary'; + /* Excluded from this release type: BSON_BINARY_SUBTYPE_DEFAULT */ + /** Initial buffer default size */ + static readonly BUFFER_SIZE = 256; + /** Default BSON type */ + static readonly SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + static readonly SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + static readonly SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + static readonly SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + static readonly SUBTYPE_UUID = 4; + /** MD5 BSON type */ + static readonly SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + static readonly SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + static readonly SUBTYPE_COLUMN = 7; + /** User BSON type */ + static readonly SUBTYPE_USER_DEFINED = 128; + buffer: Buffer; + sub_type: number; + position: number; + /** + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + constructor(buffer?: string | BinarySequence, subType?: number); + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + put(byteValue: string | number | Uint8Array | Buffer | number[]): void; + /** + * Writes a buffer or string to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + write(sequence: string | BinarySequence, offset: number): void; + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + read(position: number, length: number): BinarySequence; + /** + * Returns the value of this binary as a string. + * @param asRaw - Will skip converting to a string + * @remarks + * This is handy when calling this function conditionally for some key value pairs and not others + */ + value(asRaw?: boolean): string | BinarySequence; + /** the length of the binary sequence */ + length(): number; + toJSON(): string; + toString(format?: string): string; + /* Excluded from this release type: toExtendedJSON */ + toUUID(): UUID; + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} +/** @public */ +export declare interface BinaryExtended { + $binary: { + subType: string; + base64: string; + }; +} +/** @public */ +export declare interface BinaryExtendedLegacy { + $type: string; + $binary: string; +} +/** @public */ +export declare type BinarySequence = Uint8Array | Buffer | number[]; +/** + * BSON default export + * @deprecated Please use named exports + * @privateRemarks + * We want to someday deprecate the default export, + * so none of the new TS types are being exported on the default + * @public + */ +declare const BSON: { + Binary: typeof Binary; + Code: typeof Code; + DBRef: typeof DBRef; + Decimal128: typeof Decimal128; + Double: typeof Double; + Int32: typeof Int32; + Long: typeof Long; + UUID: typeof UUID; + Map: MapConstructor; + MaxKey: typeof MaxKey; + MinKey: typeof MinKey; + ObjectId: typeof ObjectId; + ObjectID: typeof ObjectId; + BSONRegExp: typeof BSONRegExp; + BSONSymbol: typeof BSONSymbol; + Timestamp: typeof Timestamp; + EJSON: typeof EJSON; + setInternalBufferSize: typeof setInternalBufferSize; + serialize: typeof serialize; + serializeWithBufferAndIndex: typeof serializeWithBufferAndIndex; + deserialize: typeof deserialize; + calculateObjectSize: typeof calculateObjectSize; + deserializeStream: typeof deserializeStream; + BSONError: typeof BSONError; + BSONTypeError: typeof BSONTypeError; +}; +export default BSON; +/* Excluded from this release type: BSON_BINARY_SUBTYPE_BYTE_ARRAY */ +/* Excluded from this release type: BSON_BINARY_SUBTYPE_COLUMN */ +/* Excluded from this release type: BSON_BINARY_SUBTYPE_DEFAULT */ +/* Excluded from this release type: BSON_BINARY_SUBTYPE_ENCRYPTED */ +/* Excluded from this release type: BSON_BINARY_SUBTYPE_FUNCTION */ +/* Excluded from this release type: BSON_BINARY_SUBTYPE_MD5 */ +/* Excluded from this release type: BSON_BINARY_SUBTYPE_USER_DEFINED */ +/* Excluded from this release type: BSON_BINARY_SUBTYPE_UUID */ +/* Excluded from this release type: BSON_BINARY_SUBTYPE_UUID_NEW */ +/* Excluded from this release type: BSON_DATA_ARRAY */ +/* Excluded from this release type: BSON_DATA_BINARY */ +/* Excluded from this release type: BSON_DATA_BOOLEAN */ +/* Excluded from this release type: BSON_DATA_CODE */ +/* Excluded from this release type: BSON_DATA_CODE_W_SCOPE */ +/* Excluded from this release type: BSON_DATA_DATE */ +/* Excluded from this release type: BSON_DATA_DBPOINTER */ +/* Excluded from this release type: BSON_DATA_DECIMAL128 */ +/* Excluded from this release type: BSON_DATA_INT */ +/* Excluded from this release type: BSON_DATA_LONG */ +/* Excluded from this release type: BSON_DATA_MAX_KEY */ +/* Excluded from this release type: BSON_DATA_MIN_KEY */ +/* Excluded from this release type: BSON_DATA_NULL */ +/* Excluded from this release type: BSON_DATA_NUMBER */ +/* Excluded from this release type: BSON_DATA_OBJECT */ +/* Excluded from this release type: BSON_DATA_OID */ +/* Excluded from this release type: BSON_DATA_REGEXP */ +/* Excluded from this release type: BSON_DATA_STRING */ +/* Excluded from this release type: BSON_DATA_SYMBOL */ +/* Excluded from this release type: BSON_DATA_TIMESTAMP */ +/* Excluded from this release type: BSON_DATA_UNDEFINED */ +/* Excluded from this release type: BSON_INT32_MAX */ +/* Excluded from this release type: BSON_INT32_MIN */ +/* Excluded from this release type: BSON_INT64_MAX */ +/* Excluded from this release type: BSON_INT64_MIN */ +/** @public */ +export declare class BSONError extends Error { + readonly name: string; +} +/** + * A class representation of the BSON RegExp type. + * @public + */ +export declare class BSONRegExp { + _bsontype: 'BSONRegExp'; + pattern: string; + options: string; + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + constructor(pattern: string, options?: string); + static parseOptions(options?: string): string; +} +/** @public */ +export declare interface BSONRegExpExtended { + $regularExpression: { + pattern: string; + options: string; + }; +} +/** @public */ +export declare interface BSONRegExpExtendedLegacy { + $regex: string | BSONRegExp; + $options: string; +} +/** + * A class representation of the BSON Symbol type. + * @public + */ +export declare class BSONSymbol { + _bsontype: 'Symbol'; + value: string; + /** + * @param value - the string representing the symbol. + */ + constructor(value: string); + /** Access the wrapped string value. */ + valueOf(): string; + toString(): string; + /* Excluded from this release type: inspect */ + toJSON(): string; +} +/** @public */ +export declare interface BSONSymbolExtended { + $symbol: string; +} +/** @public */ +export declare class BSONTypeError extends TypeError { + readonly name: string; +} +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ +export declare function calculateObjectSize(object: Document, options?: CalculateObjectSizeOptions): number; +/** @public */ +export declare type CalculateObjectSizeOptions = Pick; +/** + * A class representation of the BSON Code type. + * @public + */ +export declare class Code { + _bsontype: 'Code'; + code: string | Function; + scope?: Document; + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + constructor(code: string | Function, scope?: Document); + toJSON(): { + code: string | Function; + scope?: Document; + }; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} +/** @public */ +export declare interface CodeExtended { + $code: string | Function; + $scope?: Document; +} +/** + * A class representation of the BSON DBRef type. + * @public + */ +export declare class DBRef { + _bsontype: 'DBRef'; + collection: string; + oid: ObjectId; + db?: string; + fields: Document; + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + constructor(collection: string, oid: ObjectId, db?: string, fields?: Document); + /* Excluded from this release type: namespace */ + /* Excluded from this release type: namespace */ + toJSON(): DBRefLike & Document; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} +/** @public */ +export declare interface DBRefLike { + $ref: string; + $id: ObjectId; + $db?: string; +} +/** + * A class representation of the BSON Decimal128 type. + * @public + */ +export declare class Decimal128 { + _bsontype: 'Decimal128'; + readonly bytes: Buffer; + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + constructor(bytes: Buffer | string); + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + static fromString(representation: string): Decimal128; + /** Create a string representation of the raw Decimal128 value */ + toString(): string; + toJSON(): Decimal128Extended; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} +/** @public */ +export declare interface Decimal128Extended { + $numberDecimal: string; +} +/** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ +export declare function deserialize(buffer: Buffer | ArrayBufferView | ArrayBuffer, options?: DeserializeOptions): Document; +/** @public */ +export declare interface DeserializeOptions { + /** evaluate functions in the BSON document scoped to the object deserialized. */ + evalFunctions?: boolean; + /** cache evaluated functions for reuse. */ + cacheFunctions?: boolean; + /** + * use a crc32 code for caching, otherwise use the string of the function. + * @deprecated this option to use the crc32 function never worked as intended + * due to the fact that the crc32 function itself was never implemented. + * */ + cacheFunctionsCrc32?: boolean; + /** when deserializing a Long will fit it into a Number if it's smaller than 53 bits */ + promoteLongs?: boolean; + /** when deserializing a Binary will return it as a node.js Buffer instance. */ + promoteBuffers?: boolean; + /** when deserializing will promote BSON values to their Node.js closest equivalent types. */ + promoteValues?: boolean; + /** allow to specify if there what fields we wish to return as unserialized raw buffer. */ + fieldsAsRaw?: Document; + /** return BSON regular expressions as BSONRegExp instances. */ + bsonRegExp?: boolean; + /** allows the buffer to be larger than the parsed BSON object */ + allowObjectSmallerThanBufferSize?: boolean; + /** Offset into buffer to begin reading document from */ + index?: number; + raw?: boolean; +} +/** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ +export declare function deserializeStream(data: Buffer | ArrayBufferView | ArrayBuffer, startIndex: number, numberOfDocuments: number, documents: Document[], docStartIndex: number, options: DeserializeOptions): number; +/** @public */ +export declare interface Document { + [key: string]: any; +} +/** + * A class representation of the BSON Double type. + * @public + */ +export declare class Double { + _bsontype: 'Double'; + value: number; + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + constructor(value: number); + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + valueOf(): number; + toJSON(): number; + toString(radix?: number): string; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} +/** @public */ +export declare interface DoubleExtended { + $numberDouble: string; +} +/** + * EJSON parse / stringify API + * @public + */ +export declare namespace EJSON { + export interface Options { + /** Output using the Extended JSON v1 spec */ + legacy?: boolean; + /** Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types */ + relaxed?: boolean; + /** + * Disable Extended JSON's `relaxed` mode, which attempts to return BSON types where possible, rather than native JS types + * @deprecated Please use the relaxed property instead + */ + strict?: boolean; + } + /** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ + export function parse(text: string, options?: EJSON.Options): SerializableTypes; + export type JSONPrimitive = string | number | boolean | null; + export type SerializableTypes = Document | Array | JSONPrimitive; + /** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ + export function stringify(value: SerializableTypes, replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSON.Options, space?: string | number, options?: EJSON.Options): string; + /** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ + export function serialize(value: SerializableTypes, options?: EJSON.Options): Document; + /** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ + export function deserialize(ejson: Document, options?: EJSON.Options): SerializableTypes; +} +/** @public */ +export declare type EJSONOptions = EJSON.Options; +/** + * A class representation of a BSON Int32 type. + * @public + */ +export declare class Int32 { + _bsontype: 'Int32'; + value: number; + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + constructor(value: number | string); + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + valueOf(): number; + toString(radix?: number): string; + toJSON(): number; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} +/** @public */ +export declare interface Int32Extended { + $numberInt: string; +} +declare const kId: unique symbol; +declare const kId_2: unique symbol; +/** + * A class representing a 64-bit integer + * @public + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ +export declare class Long { + _bsontype: 'Long'; + /** An indicator used to reliably determine if an object is a Long or not. */ + __isLong__: true; + /** + * The high 32 bits as a signed value. + */ + high: number; + /** + * The low 32 bits as a signed value. + */ + low: number; + /** + * Whether unsigned or not. + */ + unsigned: boolean; + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + constructor(low?: number | bigint | string, high?: number | boolean, unsigned?: boolean); + static TWO_PWR_24: Long; + /** Maximum unsigned value. */ + static MAX_UNSIGNED_VALUE: Long; + /** Signed zero */ + static ZERO: Long; + /** Unsigned zero. */ + static UZERO: Long; + /** Signed one. */ + static ONE: Long; + /** Unsigned one. */ + static UONE: Long; + /** Signed negative one. */ + static NEG_ONE: Long; + /** Maximum signed value. */ + static MAX_VALUE: Long; + /** Minimum signed value. */ + static MIN_VALUE: Long; + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromInt(value: number, unsigned?: boolean): Long; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromNumber(value: number, unsigned?: boolean): Long; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBigInt(value: bigint, unsigned?: boolean): Long; + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + static fromString(str: string, unsigned?: boolean, radix?: number): Long; + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long; + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesLE(bytes: number[], unsigned?: boolean): Long; + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesBE(bytes: number[], unsigned?: boolean): Long; + /** + * Tests if the specified object is a Long. + */ + static isLong(value: any): value is Long; + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + static fromValue(val: number | string | { + low: number; + high: number; + unsigned?: boolean; + }, unsigned?: boolean): Long; + /** Returns the sum of this and the specified Long. */ + add(addend: string | number | Long | Timestamp): Long; + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + and(other: string | number | Long | Timestamp): Long; + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + compare(other: string | number | Long | Timestamp): 0 | 1 | -1; + /** This is an alias of {@link Long.compare} */ + comp(other: string | number | Long | Timestamp): 0 | 1 | -1; + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + divide(divisor: string | number | Long | Timestamp): Long; + /**This is an alias of {@link Long.divide} */ + div(divisor: string | number | Long | Timestamp): Long; + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + equals(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.equals} */ + eq(other: string | number | Long | Timestamp): boolean; + /** Gets the high 32 bits as a signed integer. */ + getHighBits(): number; + /** Gets the high 32 bits as an unsigned integer. */ + getHighBitsUnsigned(): number; + /** Gets the low 32 bits as a signed integer. */ + getLowBits(): number; + /** Gets the low 32 bits as an unsigned integer. */ + getLowBitsUnsigned(): number; + /** Gets the number of bits needed to represent the absolute value of this Long. */ + getNumBitsAbs(): number; + /** Tests if this Long's value is greater than the specified's. */ + greaterThan(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.greaterThan} */ + gt(other: string | number | Long | Timestamp): boolean; + /** Tests if this Long's value is greater than or equal the specified's. */ + greaterThanOrEqual(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + gte(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + ge(other: string | number | Long | Timestamp): boolean; + /** Tests if this Long's value is even. */ + isEven(): boolean; + /** Tests if this Long's value is negative. */ + isNegative(): boolean; + /** Tests if this Long's value is odd. */ + isOdd(): boolean; + /** Tests if this Long's value is positive. */ + isPositive(): boolean; + /** Tests if this Long's value equals zero. */ + isZero(): boolean; + /** Tests if this Long's value is less than the specified's. */ + lessThan(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long#lessThan}. */ + lt(other: string | number | Long | Timestamp): boolean; + /** Tests if this Long's value is less than or equal the specified's. */ + lessThanOrEqual(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.lessThanOrEqual} */ + lte(other: string | number | Long | Timestamp): boolean; + /** Returns this Long modulo the specified. */ + modulo(divisor: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.modulo} */ + mod(divisor: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.modulo} */ + rem(divisor: string | number | Long | Timestamp): Long; + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + multiply(multiplier: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.multiply} */ + mul(multiplier: string | number | Long | Timestamp): Long; + /** Returns the Negation of this Long's value. */ + negate(): Long; + /** This is an alias of {@link Long.negate} */ + neg(): Long; + /** Returns the bitwise NOT of this Long. */ + not(): Long; + /** Tests if this Long's value differs from the specified's. */ + notEquals(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.notEquals} */ + neq(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.notEquals} */ + ne(other: string | number | Long | Timestamp): boolean; + /** + * Returns the bitwise OR of this Long and the specified. + */ + or(other: number | string | Long): Long; + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftLeft(numBits: number | Long): Long; + /** This is an alias of {@link Long.shiftLeft} */ + shl(numBits: number | Long): Long; + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRight(numBits: number | Long): Long; + /** This is an alias of {@link Long.shiftRight} */ + shr(numBits: number | Long): Long; + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRightUnsigned(numBits: Long | number): Long; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shr_u(numBits: number | Long): Long; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shru(numBits: number | Long): Long; + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + subtract(subtrahend: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.subtract} */ + sub(subtrahend: string | number | Long | Timestamp): Long; + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + toInt(): number; + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + toNumber(): number; + /** Converts the Long to a BigInt (arbitrary precision). */ + toBigInt(): bigint; + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + toBytes(le?: boolean): number[]; + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + toBytesLE(): number[]; + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + toBytesBE(): number[]; + /** + * Converts this Long to signed. + */ + toSigned(): Long; + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + toString(radix?: number): string; + /** Converts this Long to unsigned. */ + toUnsigned(): Long; + /** Returns the bitwise XOR of this Long and the given one. */ + xor(other: Long | number | string): Long; + /** This is an alias of {@link Long.isZero} */ + eqz(): boolean; + /** This is an alias of {@link Long.lessThanOrEqual} */ + le(other: string | number | Long | Timestamp): boolean; + toExtendedJSON(options?: EJSONOptions): number | LongExtended; + static fromExtendedJSON(doc: { + $numberLong: string; + }, options?: EJSONOptions): number | Long; + inspect(): string; +} +/** @public */ +export declare interface LongExtended { + $numberLong: string; +} +/** @public */ +export declare type LongWithoutOverrides = new (low: unknown, high?: number, unsigned?: boolean) => { + [P in Exclude]: Long[P]; +}; +/** @public */ +export declare const LongWithoutOverridesClass: LongWithoutOverrides; +/** @public */ +declare let Map_2: MapConstructor; +export { Map_2 as Map }; +/** + * A class representation of the BSON MaxKey type. + * @public + */ +export declare class MaxKey { + _bsontype: 'MaxKey'; + constructor(); + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} +/** @public */ +export declare interface MaxKeyExtended { + $maxKey: 1; +} +/** + * A class representation of the BSON MinKey type. + * @public + */ +export declare class MinKey { + _bsontype: 'MinKey'; + constructor(); + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} +/** @public */ +export declare interface MinKeyExtended { + $minKey: 1; +} +/** + * A class representation of the BSON ObjectId type. + * @public + */ +declare class ObjectId { + _bsontype: 'ObjectId'; + /* Excluded from this release type: index */ + static cacheHexString: boolean; + /* Excluded from this release type: [kId] */ + /* Excluded from this release type: __id */ + /** + * Create an ObjectId type + * + * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number. + */ + constructor(id?: string | Buffer | number | ObjectIdLike | ObjectId); + /* + * The ObjectId bytes + * @readonly + */ + id: Buffer; + /* + * The generation time of this ObjectId instance + * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch + */ + generationTime: number; + /** Returns the ObjectId id as a 24 character hex string representation */ + toHexString(): string; + /* Excluded from this release type: getInc */ + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + static generate(time?: number): Buffer; + /** + * Converts the id into a 24 character hex string for printing + * + * @param format - The Buffer toString format parameter. + */ + toString(format?: string): string; + /** Converts to its JSON the 24 character hex string representation. */ + toJSON(): string; + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + equals(otherId: string | ObjectId | ObjectIdLike): boolean; + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + getTimestamp(): Date; + /* Excluded from this release type: createPk */ + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + static createFromTime(time: number): ObjectId; + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + static createFromHexString(hexString: string): ObjectId; + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + static isValid(id: number | string | ObjectId | Uint8Array | ObjectIdLike): boolean; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} +export { ObjectId as ObjectID }; +export { ObjectId }; +/** @public */ +export declare interface ObjectIdExtended { + $oid: string; +} +/** @public */ +export declare interface ObjectIdLike { + id: string | Buffer; + __id?: string; + toHexString(): string; +} +/** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ +export declare function serialize(object: Document, options?: SerializeOptions): Buffer; +/** @public */ +export declare interface SerializeOptions { + /** the serializer will check if keys are valid. */ + checkKeys?: boolean; + /** serialize the javascript functions **(default:false)**. */ + serializeFunctions?: boolean; + /** serialize will not emit undefined fields **(default:true)** */ + ignoreUndefined?: boolean; + /* Excluded from this release type: minInternalBufferSize */ + /** the index in the buffer where we wish to start serializing into */ + index?: number; +} +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ +export declare function serializeWithBufferAndIndex(object: Document, finalBuffer: Buffer, options?: SerializeOptions): number; +/** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer + * @public + */ +export declare function setInternalBufferSize(size: number): void; +/** @public */ +export declare class Timestamp extends LongWithoutOverridesClass { + _bsontype: 'Timestamp'; + static readonly MAX_VALUE: Long; + /** + * @param low - A 64-bit Long representing the Timestamp. + */ + constructor(long: Long); + /** + * @param value - A pair of two values indicating timestamp and increment. + */ + constructor(value: { + t: number; + i: number; + }); + /** + * @param low - the low (signed) 32 bits of the Timestamp. + * @param high - the high (signed) 32 bits of the Timestamp. + * @deprecated Please use `Timestamp({ t: high, i: low })` or `Timestamp(Long(low, high))` instead. + */ + constructor(low: number, high: number); + toJSON(): { + $timestamp: string; + }; + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + static fromInt(value: number): Timestamp; + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + static fromNumber(value: number): Timestamp; + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + static fromBits(lowBits: number, highBits: number): Timestamp; + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + static fromString(str: string, optRadix: number): Timestamp; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} +/** @public */ +export declare interface TimestampExtended { + $timestamp: { + t: number; + i: number; + }; +} +/** @public */ +export declare type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect'; +/** + * A class representation of the BSON UUID type. + * @public + */ +export declare class UUID { + _bsontype: 'UUID'; + static cacheHexString: boolean; + /* Excluded from this release type: [kId] */ + /* Excluded from this release type: __id */ + /** + * Create an UUID type + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + constructor(input?: string | Buffer | UUID); + /* + * The UUID bytes + * @readonly + */ + id: Buffer; + /** + * Generate a 16 byte uuid v4 buffer used in UUIDs + */ + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + * */ + toHexString(includeDashes?: boolean): string; + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + toString(encoding?: string): string; + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + toJSON(): string; + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + equals(otherId: string | Buffer | UUID): boolean; + /** + * Creates a Binary instance from the current UUID. + */ + toBinary(): Binary; + /** + * Generates a populated buffer containing a v4 uuid + */ + static generate(): Buffer; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + static isValid(input: string | Buffer | UUID): boolean; + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + static createFromHexString(hexString: string): UUID; + inspect(): string; +} +/** @public */ +export declare type UUIDExtended = { + $uuid: string; +}; +export {}; diff --git a/node_modules/bson/dist/bson.browser.esm.js b/node_modules/bson/dist/bson.browser.esm.js new file mode 100644 index 0000000..9176799 --- /dev/null +++ b/node_modules/bson/dist/bson.browser.esm.js @@ -0,0 +1,7428 @@ +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var byteLength_1 = byteLength; +var toByteArray_1 = toByteArray; +var fromByteArray_1 = fromByteArray; +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; +} // Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications + + +revLookup['-'.charCodeAt(0)] = 62; +revLookup['_'.charCodeAt(0)] = 63; + +function getLens(b64) { + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4'); + } // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + + + var validLen = b64.indexOf('='); + if (validLen === -1) validLen = len; + var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; +} // base64 is 4/3 + up to two characters of the original data + + +function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; +} + +function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; +} + +function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; // if there are placeholders, only get up to the last complete 4 chars + + var len = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i; + + for (i = 0; i < len; i += 4) { + tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; + arr[curByte++] = tmp >> 16 & 0xFF; + arr[curByte++] = tmp >> 8 & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; + arr[curByte++] = tmp & 0xFF; + } + + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + + return arr; +} + +function tripletToBase64(num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; +} + +function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF); + output.push(tripletToBase64(tmp)); + } + + return output.join(''); +} + +function fromByteArray(uint8) { + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + // go through the array every three bytes, we'll deal with trailing stuff later + + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); + } // pad the end with zeros, but make sure to not forget the extra bytes + + + if (extraBytes === 1) { + tmp = uint8[len - 1]; + parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '=='); + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '='); + } + + return parts.join(''); +} + +var base64Js = { + byteLength: byteLength_1, + toByteArray: toByteArray_1, + fromByteArray: fromByteArray_1 +}; + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +var read = function read(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var write = function write(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = e << mLen | m; + eLen += mLen; + + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +}; + +var ieee754 = { + read: read, + write: write +}; + +var buffer$1 = createCommonjsModule(function (module, exports) { + + var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' ? // eslint-disable-line dot-notation + Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null; + exports.Buffer = Buffer; + exports.SlowBuffer = SlowBuffer; + exports.INSPECT_MAX_BYTES = 50; + var K_MAX_LENGTH = 0x7fffffff; + exports.kMaxLength = K_MAX_LENGTH; + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ + + Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); + + if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { + console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'); + } + + function typedArraySupport() { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1); + var proto = { + foo: function foo() { + return 42; + } + }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e) { + return false; + } + } + + Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function get() { + if (!Buffer.isBuffer(this)) return undefined; + return this.buffer; + } + }); + Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function get() { + if (!Buffer.isBuffer(this)) return undefined; + return this.byteOffset; + } + }); + + function createBuffer(length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"'); + } // Return an augmented `Uint8Array` instance + + + var buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer.prototype); + return buf; + } + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + + function Buffer(arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError('The "string" argument must be of type string. Received type number'); + } + + return allocUnsafe(arg); + } + + return from(arg, encodingOrOffset, length); + } + + Buffer.poolSize = 8192; // not used by this implementation + + function from(value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset); + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value); + } + + if (value == null) { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value)); + } + + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + + if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type number'); + } + + var valueOf = value.valueOf && value.valueOf(); + + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length); + } + + var b = fromObject(value); + if (b) return b; + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length); + } + + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value)); + } + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + + + Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length); + }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: + // https://github.com/feross/buffer/pull/148 + + + Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer, Uint8Array); + + function assertSize(size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + + function alloc(size, fill, encoding) { + assertSize(size); + + if (size <= 0) { + return createBuffer(size); + } + + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + + return createBuffer(size); + } + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + + + Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding); + }; + + function allocUnsafe(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + + + Buffer.allocUnsafe = function (size) { + return allocUnsafe(size); + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + + + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size); + }; + + function fromString(string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding); + } + + var length = byteLength(string, encoding) | 0; + var buf = createBuffer(length); + var actual = buf.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual); + } + + return buf; + } + + function fromArrayLike(array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + var buf = createBuffer(length); + + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + + return buf; + } + + function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); + } + + return fromArrayLike(arrayView); + } + + function fromArrayBuffer(array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + + var buf; + + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array); + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length); + } // Return an augmented `Uint8Array` instance + + + Object.setPrototypeOf(buf, Buffer.prototype); + return buf; + } + + function fromObject(obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); + + if (buf.length === 0) { + return buf; + } + + obj.copy(buf, 0, 0, len); + return buf; + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0); + } + + return fromArrayLike(obj); + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + + function checked(length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes'); + } + + return length | 0; + } + + function SlowBuffer(length) { + if (+length != length) { + // eslint-disable-line eqeqeq + length = 0; + } + + return Buffer.alloc(+length); + } + + Buffer.isBuffer = function isBuffer(b) { + return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false + }; + + Buffer.compare = function compare(a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength); + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength); + + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); + } + + if (a === b) return 0; + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + + Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true; + + default: + return false; + } + }; + + Buffer.concat = function concat(list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + + if (list.length === 0) { + return Buffer.alloc(0); + } + + var i; + + if (length === undefined) { + length = 0; + + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer.from(buf).copy(buffer, pos); + } else { + Uint8Array.prototype.set.call(buffer, buf, pos); + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer, pos); + } + + pos += buf.length; + } + + return buffer; + }; + + function byteLength(string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length; + } + + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength; + } + + if (typeof string !== 'string') { + throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + babelHelpers["typeof"](string)); + } + + var len = string.length; + var mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion + + var loweredCase = false; + + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len; + + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length; + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2; + + case 'hex': + return len >>> 1; + + case 'base64': + return base64ToBytes(string).length; + + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8 + } + + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + + Buffer.byteLength = byteLength; + + function slowToString(encoding, start, end) { + var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + + if (start === undefined || start < 0) { + start = 0; + } // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + + + if (start > this.length) { + return ''; + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return ''; + } // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + + + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return ''; + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end); + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end); + + case 'ascii': + return asciiSlice(this, start, end); + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end); + + case 'base64': + return base64Slice(this, start, end); + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end); + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) + // to detect a Buffer instance. It's not possible to use `instanceof Buffer` + // reliably in a browserify context because there could be multiple different + // copies of the 'buffer' package in use. This method works even for Buffer + // instances that were created from another copy of the `buffer` package. + // See: https://github.com/feross/buffer/issues/154 + + + Buffer.prototype._isBuffer = true; + + function swap(b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16() { + var len = this.length; + + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits'); + } + + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + + return this; + }; + + Buffer.prototype.swap32 = function swap32() { + var len = this.length; + + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits'); + } + + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + + return this; + }; + + Buffer.prototype.swap64 = function swap64() { + var len = this.length; + + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits'); + } + + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + + return this; + }; + + Buffer.prototype.toString = function toString() { + var length = this.length; + if (length === 0) return ''; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); + }; + + Buffer.prototype.toLocaleString = Buffer.prototype.toString; + + Buffer.prototype.equals = function equals(b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); + if (this === b) return true; + return Buffer.compare(this, b) === 0; + }; + + Buffer.prototype.inspect = function inspect() { + var str = ''; + var max = exports.INSPECT_MAX_BYTES; + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); + if (this.length > max) str += ' ... '; + return ''; + }; + + if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; + } + + Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength); + } + + if (!Buffer.isBuffer(target)) { + throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + babelHelpers["typeof"](target)); + } + + if (start === undefined) { + start = 0; + } + + if (end === undefined) { + end = target ? target.length : 0; + } + + if (thisStart === undefined) { + thisStart = 0; + } + + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index'); + } + + if (thisStart >= thisEnd && start >= end) { + return 0; + } + + if (thisStart >= thisEnd) { + return -1; + } + + if (start >= end) { + return 1; + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) return 0; + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + + + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1; // Normalize byteOffset + + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + + byteOffset = +byteOffset; // Coerce to Number. + + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1; + } // Normalize byteOffset: negative offsets start from the end of the buffer + + + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + + if (byteOffset >= buffer.length) { + if (dir) return -1;else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0;else return -1; + } // Normalize val + + + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } // Finally, search either indexOf (if dir is true) or lastIndexOf + + + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1; + } + + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + + throw new TypeError('val must be string, number or Buffer'); + } + + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + + if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1; + } + + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read(buf, i) { + if (indexSize === 1) { + return buf[i]; + } else { + return buf.readUInt16BE(i * indexSize); + } + } + + var i; + + if (dir) { + var foundIndex = -1; + + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + + for (i = byteOffset; i >= 0; i--) { + var found = true; + + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + + if (found) return i; + } + } + + return -1; + } + + Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + + Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + + function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + + if (!length) { + length = remaining; + } else { + length = Number(length); + + if (length > remaining) { + length = remaining; + } + } + + var strLen = string.length; + + if (length > strLen / 2) { + length = strLen / 2; + } + + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i; + buf[offset + i] = parsed; + } + + return i; + } + + function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); + } + + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); + } + + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); + } + + function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); + } + + Buffer.prototype.write = function write(string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0; + + if (isFinite(length)) { + length = length >>> 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + } else { + throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds'); + } + + if (!encoding) encoding = 'utf8'; + var loweredCase = false; + + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length); + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length); + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length); + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length); + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length); + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON() { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64Js.fromByteArray(buf); + } else { + return base64Js.fromByteArray(buf.slice(start, end)); + } + } + + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + var i = start; + + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + + break; + + case 2: + secondByte = buf[i + 1]; + + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; + + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + + break; + + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; + + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + + break; + + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; + + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res); + } // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + + + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + } // Decode in chunks to avoid "call stack size exceeded". + + + var res = ''; + var i = 0; + + while (i < len) { + res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); + } + + return res; + } + + function asciiSlice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + + return ret; + } + + function latin1Slice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + + return ret; + } + + function hexSlice(buf, start, end) { + var len = buf.length; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + var out = ''; + + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + + return out; + } + + function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + + for (var i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + + return res; + } + + Buffer.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance + + Object.setPrototypeOf(newBuf, Buffer.prototype); + return newBuf; + }; + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + + + function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); + } + + Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val; + }; + + Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val; + }; + + Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; + }; + + Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }; + + Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }; + + Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; + }; + + Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }; + + Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + mul *= 0x80; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; + }; + + Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + + mul *= 0x80; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; + }; + + Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return this[offset]; + return (0xff - this[offset] + 1) * -1; + }; + + Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | this[offset + 1] << 8; + return val & 0x8000 ? val | 0xFFFF0000 : val; + }; + + Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | this[offset] << 8; + return val & 0x8000 ? val | 0xFFFF0000 : val; + }; + + Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }; + + Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }; + + Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4); + }; + + Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4); + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8); + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8); + }; + + function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) throw new RangeError('Index out of range'); + } + + Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = value / mul & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = value / mul & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + this[offset] = value & 0xff; + return offset + 1; + }; + + Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + + Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + return offset + 2; + }; + + Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 0xff; + return offset + 4; + }; + + Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + return offset + 4; + }; + + Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + + this[offset + i] = (value / mul >> 0) - sub & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + + this[offset + i] = (value / mul >> 0) - sub & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (value < 0) value = 0xff + value + 1; + this[offset] = value & 0xff; + return offset + 1; + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + return offset + 2; + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + return offset + 4; + }; + + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range'); + if (offset < 0) throw new RangeError('Index out of range'); + } + + function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + + Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; + + function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + + + Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer'); + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done + + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions + + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds'); + } + + if (start < 0 || start >= this.length) throw new RangeError('Index out of range'); + if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? + + if (end > this.length) end = this.length; + + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); + } + + return len; + }; // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + + + Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string'); + } + + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding); + } + + if (val.length === 1) { + var code = val.charCodeAt(0); + + if (encoding === 'utf8' && code < 128 || encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code; + } + } + } else if (typeof val === 'number') { + val = val & 255; + } else if (typeof val === 'boolean') { + val = Number(val); + } // Invalid ranges are not set to a default, so can range check early. + + + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index'); + } + + if (end <= start) { + return this; + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + if (!val) val = 0; + var i; + + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); + var len = bytes.length; + + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this; + }; // HELPER FUNCTIONS + // ================ + + + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + + function base64clean(str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not + + str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' + + if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + + while (str.length % 4 !== 0) { + str = str + '='; + } + + return str; + } + + function utf8ToBytes(string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); // is surrogate component + + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue; + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue; + } // valid lead + + + leadSurrogate = codePoint; + continue; + } // 2 leads in a row + + + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue; + } // valid surrogate pair + + + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; // encode utf8 + + if (codePoint < 0x80) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break; + bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break; + bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break; + bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); + } else { + throw new Error('Invalid code point'); + } + } + + return bytes; + } + + function asciiToBytes(str) { + var byteArray = []; + + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + + return byteArray; + } + + function utf16leToBytes(str, units) { + var c, hi, lo; + var byteArray = []; + + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray; + } + + function base64ToBytes(str) { + return base64Js.toByteArray(base64clean(str)); + } + + function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break; + dst[i + offset] = src[i]; + } + + return i; + } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass + // the `instanceof` check but they should be treated as of that type. + // See: https://github.com/feross/buffer/issues/166 + + + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; + } + + function numberIsNaN(obj) { + // For IE11 support + return obj !== obj; // eslint-disable-line no-self-compare + } // Create lookup table for `toString('hex')` + // See: https://github.com/feross/buffer/issues/219 + + + var hexSliceLookupTable = function () { + var alphabet = '0123456789abcdef'; + var table = new Array(256); + + for (var i = 0; i < 16; ++i) { + var i16 = i * 16; + + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + + return table; + }(); +}); +var buffer_1 = buffer$1.Buffer; +buffer$1.SlowBuffer; +buffer$1.INSPECT_MAX_BYTES; +buffer$1.kMaxLength; + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +/* global Reflect, Promise */ +var _extendStatics = function extendStatics(d, b) { + _extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function (d, b) { + d.__proto__ = b; + } || function (d, b) { + for (var p in b) { + if (b.hasOwnProperty(p)) d[p] = b[p]; + } + }; + + return _extendStatics(d, b); +}; + +function __extends(d, b) { + _extendStatics(d, b); + + function __() { + this.constructor = d; + } + + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +/** @public */ +var BSONError = /** @class */ (function (_super) { + __extends(BSONError, _super); + function BSONError() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(BSONError.prototype, "name", { + get: function () { + return 'BSONError'; + }, + enumerable: false, + configurable: true + }); + return BSONError; +}(Error)); +/** @public */ +var BSONTypeError = /** @class */ (function (_super) { + __extends(BSONTypeError, _super); + function BSONTypeError() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(BSONTypeError.prototype, "name", { + get: function () { + return 'BSONTypeError'; + }, + enumerable: false, + configurable: true + }); + return BSONTypeError; +}(TypeError)); + +function checkForMath(potentialGlobal) { + // eslint-disable-next-line eqeqeq + return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; +} +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +function getGlobal() { + // eslint-disable-next-line no-undef + return (checkForMath(typeof globalThis === 'object' && globalThis) || + checkForMath(typeof window === 'object' && window) || + checkForMath(typeof self === 'object' && self) || + checkForMath(typeof global === 'object' && global) || + Function('return this')()); +} + +/** + * Normalizes our expected stringified form of a function across versions of node + * @param fn - The function to stringify + */ +function normalizedFunctionString(fn) { + return fn.toString().replace('function(', 'function ('); +} +function isReactNative() { + var g = getGlobal(); + return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; +} +var insecureRandomBytes = function insecureRandomBytes(size) { + var insecureWarning = isReactNative() + ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; + console.warn(insecureWarning); + var result = buffer_1.alloc(size); + for (var i = 0; i < size; ++i) + result[i] = Math.floor(Math.random() * 256); + return result; +}; +var detectRandomBytes = function () { + if (typeof window !== 'undefined') { + // browser crypto implementation(s) + var target_1 = window.crypto || window.msCrypto; // allow for IE11 + if (target_1 && target_1.getRandomValues) { + return function (size) { return target_1.getRandomValues(buffer_1.alloc(size)); }; + } + } + if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { + // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global + return function (size) { return global.crypto.getRandomValues(buffer_1.alloc(size)); }; + } + var requiredRandomBytes; + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + requiredRandomBytes = require('crypto').randomBytes; + } + catch (e) { + // keep the fallback + } + // NOTE: in transpiled cases the above require might return null/undefined + return requiredRandomBytes || insecureRandomBytes; +}; +var randomBytes = detectRandomBytes(); +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isBigInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigInt64Array]'; +} +function isBigUInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigUint64Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +// To ensure that 0.4 of node works correctly +function isDate(d) { + return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; +} +/** + * @internal + * this is to solve the `'someKey' in x` problem where x is unknown. + * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 + */ +function isObjectLike(candidate) { + return typeof candidate === 'object' && candidate !== null; +} +function deprecate(fn, message) { + var warned = false; + function deprecated() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!warned) { + console.warn(message); + warned = true; + } + return fn.apply(this, args); + } + return deprecated; +} + +/** + * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. + * + * @param potentialBuffer - The potential buffer + * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that + * wraps a passed in Uint8Array + * @throws TypeError If anything other than a Buffer or Uint8Array is passed in + */ +function ensureBuffer(potentialBuffer) { + if (ArrayBuffer.isView(potentialBuffer)) { + return buffer_1.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + if (isAnyArrayBuffer(potentialBuffer)) { + return buffer_1.from(potentialBuffer); + } + throw new BSONTypeError('Must use either Buffer or TypedArray'); +} + +// Validation regex for v4 uuid (validates with or without dashes) +var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; +var uuidValidateString = function (str) { + return typeof str === 'string' && VALIDATION_REGEX.test(str); +}; +var uuidHexStringToBuffer = function (hexString) { + if (!uuidValidateString(hexString)) { + throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); + } + var sanitizedHexString = hexString.replace(/-/g, ''); + return buffer_1.from(sanitizedHexString, 'hex'); +}; +var bufferToUuidHexString = function (buffer, includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + return includeDashes + ? buffer.toString('hex', 0, 4) + + '-' + + buffer.toString('hex', 4, 6) + + '-' + + buffer.toString('hex', 6, 8) + + '-' + + buffer.toString('hex', 8, 10) + + '-' + + buffer.toString('hex', 10, 16) + : buffer.toString('hex'); +}; + +var BYTE_LENGTH = 16; +var kId$1 = Symbol('id'); +/** + * A class representation of the BSON UUID type. + * @public + */ +var UUID = /** @class */ (function () { + /** + * Create an UUID type + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + function UUID(input) { + if (typeof input === 'undefined') { + // The most common use case (blank id, new UUID() instance) + this.id = UUID.generate(); + } + else if (input instanceof UUID) { + this[kId$1] = buffer_1.from(input.id); + this.__id = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { + this.id = ensureBuffer(input); + } + else if (typeof input === 'string') { + this.id = uuidHexStringToBuffer(input); + } + else { + throw new BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); + } + } + Object.defineProperty(UUID.prototype, "id", { + /** + * The UUID bytes + * @readonly + */ + get: function () { + return this[kId$1]; + }, + set: function (value) { + this[kId$1] = value; + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + }, + enumerable: false, + configurable: true + }); + /** + * Generate a 16 byte uuid v4 buffer used in UUIDs + */ + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + * */ + UUID.prototype.toHexString = function (includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + var uuidHexString = bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + }; + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + UUID.prototype.toString = function (encoding) { + return encoding ? this.id.toString(encoding) : this.toHexString(); + }; + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + UUID.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + UUID.prototype.equals = function (otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return otherId.id.equals(this.id); + } + try { + return new UUID(otherId).id.equals(this.id); + } + catch (_a) { + return false; + } + }; + /** + * Creates a Binary instance from the current UUID. + */ + UUID.prototype.toBinary = function () { + return new Binary(this.id, Binary.SUBTYPE_UUID); + }; + /** + * Generates a populated buffer containing a v4 uuid + */ + UUID.generate = function () { + var bytes = randomBytes(BYTE_LENGTH); + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return buffer_1.from(bytes); + }; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + UUID.isValid = function (input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuidValidateString(input); + } + if (isUint8Array(input)) { + // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) + if (input.length !== BYTE_LENGTH) { + return false; + } + try { + // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx + // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx + return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID; + } + catch (_a) { + return false; + } + } + return false; + }; + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + UUID.createFromHexString = function (hexString) { + var buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 36 character hex string representation. + * @internal + */ + UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + UUID.prototype.inspect = function () { + return "new UUID(\"" + this.toHexString() + "\")"; + }; + return UUID; +}()); +Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); + +/** + * A class representation of the BSON Binary type. + * @public + */ +var Binary = /** @class */ (function () { + /** + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) + return new Binary(buffer, subType); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + // create an empty binary buffer + this.buffer = buffer_1.alloc(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + // string + this.buffer = buffer_1.from(buffer, 'binary'); + } + else if (Array.isArray(buffer)) { + // number[] + this.buffer = buffer_1.from(buffer); + } + else { + // Buffer | TypedArray | ArrayBuffer + this.buffer = ensureBuffer(buffer); + } + this.position = this.buffer.byteLength; + } + } + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + Binary.prototype.put = function (byteValue) { + // If it's a string and a has more than one character throw an error + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONTypeError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONTypeError('only accepts single character Uint8Array or Array'); + // Decode the byte value once + var decodedByte; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } + else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } + else { + decodedByte = byteValue[0]; + } + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + var buffer = buffer_1.alloc(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decodedByte; + } + }; + /** + * Writes a buffer or string to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + Binary.prototype.write = function (sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + sequence.length) { + var buffer = buffer_1.alloc(this.buffer.length + sequence.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + // Assign the new buffer + this.buffer = buffer; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ensureBuffer(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + this.buffer.write(sequence, offset, sequence.length, 'binary'); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + }; + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + Binary.prototype.read = function (position, length) { + length = length && length > 0 ? length : this.position; + // Let's return the data based on the type we have + return this.buffer.slice(position, position + length); + }; + /** + * Returns the value of this binary as a string. + * @param asRaw - Will skip converting to a string + * @remarks + * This is handy when calling this function conditionally for some key value pairs and not others + */ + Binary.prototype.value = function (asRaw) { + asRaw = !!asRaw; + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + // If it's a node.js buffer object + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return this.buffer.toString('binary', 0, this.position); + }; + /** the length of the binary sequence */ + Binary.prototype.length = function () { + return this.position; + }; + Binary.prototype.toJSON = function () { + return this.buffer.toString('base64'); + }; + Binary.prototype.toString = function (format) { + return this.buffer.toString(format); + }; + /** @internal */ + Binary.prototype.toExtendedJSON = function (options) { + options = options || {}; + var base64String = this.buffer.toString('base64'); + var subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + }; + Binary.prototype.toUUID = function () { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID(this.buffer.slice(0, this.position)); + } + throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); + }; + /** @internal */ + Binary.fromExtendedJSON = function (doc, options) { + options = options || {}; + var data; + var type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = buffer_1.from(doc.$binary, 'base64'); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = buffer_1.from(doc.$binary.base64, 'base64'); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); + } + return new Binary(data, type); + }; + /** @internal */ + Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Binary.prototype.inspect = function () { + var asBuffer = this.value(true); + return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; + }; + /** + * Binary default subtype + * @internal + */ + Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** Initial buffer default size */ + Binary.BUFFER_SIZE = 256; + /** Default BSON type */ + Binary.SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + Binary.SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + Binary.SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + Binary.SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + Binary.SUBTYPE_UUID = 4; + /** MD5 BSON type */ + Binary.SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + Binary.SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + Binary.SUBTYPE_COLUMN = 7; + /** User BSON type */ + Binary.SUBTYPE_USER_DEFINED = 128; + return Binary; +}()); +Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); + +/** + * A class representation of the BSON Code type. + * @public + */ +var Code = /** @class */ (function () { + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + function Code(code, scope) { + if (!(this instanceof Code)) + return new Code(code, scope); + this.code = code; + this.scope = scope; + } + Code.prototype.toJSON = function () { + return { code: this.code, scope: this.scope }; + }; + /** @internal */ + Code.prototype.toExtendedJSON = function () { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + }; + /** @internal */ + Code.fromExtendedJSON = function (doc) { + return new Code(doc.$code, doc.$scope); + }; + /** @internal */ + Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Code.prototype.inspect = function () { + var codeJson = this.toJSON(); + return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; + }; + return Code; +}()); +Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); + +/** @internal */ +function isDBRefLike(value) { + return (isObjectLike(value) && + value.$id != null && + typeof value.$ref === 'string' && + (value.$db == null || typeof value.$db === 'string')); +} +/** + * A class representation of the BSON DBRef type. + * @public + */ +var DBRef = /** @class */ (function () { + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + function DBRef(collection, oid, db, fields) { + if (!(this instanceof DBRef)) + return new DBRef(collection, oid, db, fields); + // check if namespace has been provided + var parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + Object.defineProperty(DBRef.prototype, "namespace", { + // Property provided for compatibility with the 1.x parser + // the 1.x parser used a "namespace" property, while 4.x uses "collection" + /** @internal */ + get: function () { + return this.collection; + }, + set: function (value) { + this.collection = value; + }, + enumerable: false, + configurable: true + }); + DBRef.prototype.toJSON = function () { + var o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + }; + /** @internal */ + DBRef.prototype.toExtendedJSON = function (options) { + options = options || {}; + var o = { + $ref: this.collection, + $id: this.oid + }; + if (options.legacy) { + return o; + } + if (this.db) + o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + }; + /** @internal */ + DBRef.fromExtendedJSON = function (doc) { + var copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + }; + /** @internal */ + DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + DBRef.prototype.inspect = function () { + // NOTE: if OID is an ObjectId class it will just print the oid string. + var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); + return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; + }; + return DBRef; +}()); +Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); + +/** + * wasm optimizations, to do native i64 multiplication and divide + */ +var wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module( + // prettier-ignore + new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; +} +catch (_a) { + // no wasm support +} +var TWO_PWR_16_DBL = 1 << 16; +var TWO_PWR_24_DBL = 1 << 24; +var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +/** A cache of the Long representations of small integer values. */ +var INT_CACHE = {}; +/** A cache of the Long representations of small unsigned integer values. */ +var UINT_CACHE = {}; +/** + * A class representing a 64-bit integer + * @public + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ +var Long = /** @class */ (function () { + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + function Long(low, high, unsigned) { + if (low === void 0) { low = 0; } + if (!(this instanceof Long)) + return new Long(low, high, unsigned); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } + else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } + else { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + Object.defineProperty(this, '__isLong__', { + value: true, + configurable: false, + writable: false, + enumerable: false + }); + } + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBits = function (lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + }; + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromInt = function (value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } + else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromNumber = function (value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; + } + else { + if (value <= -TWO_PWR_63_DBL) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBigInt = function (value, unsigned) { + return Long.fromString(value.toString(), unsigned); + }; + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + Long.fromString = function (str, unsigned, radix) { + if (str.length === 0) + throw Error('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + var p; + if ((p = str.indexOf('-')) > 0) + throw Error('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } + else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + }; + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + Long.fromBytes = function (bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + }; + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesLE = function (bytes, unsigned) { + return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); + }; + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesBE = function (bytes, unsigned) { + return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); + }; + /** + * Tests if the specified object is a Long. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + Long.isLong = function (value) { + return isObjectLike(value) && value['__isLong__'] === true; + }; + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + Long.fromValue = function (val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + }; + /** Returns the sum of this and the specified Long. */ + Long.prototype.add = function (addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xffff; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + Long.prototype.and = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + }; + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + Long.prototype.compare = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + // At this point the sign bits are the same + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + }; + /** This is an alias of {@link Long.compare} */ + Long.prototype.comp = function (other) { + return this.compare(other); + }; + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + Long.prototype.divide = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw Error('division by zero'); + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + // be consistent with non-wasm code path + return this; + } + var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + var approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } + else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } + else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } + else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } + else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return Long.UONE; + res = Long.UZERO; + } + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + }; + /**This is an alias of {@link Long.divide} */ + Long.prototype.div = function (divisor) { + return this.divide(divisor); + }; + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + Long.prototype.equals = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + }; + /** This is an alias of {@link Long.equals} */ + Long.prototype.eq = function (other) { + return this.equals(other); + }; + /** Gets the high 32 bits as a signed integer. */ + Long.prototype.getHighBits = function () { + return this.high; + }; + /** Gets the high 32 bits as an unsigned integer. */ + Long.prototype.getHighBitsUnsigned = function () { + return this.high >>> 0; + }; + /** Gets the low 32 bits as a signed integer. */ + Long.prototype.getLowBits = function () { + return this.low; + }; + /** Gets the low 32 bits as an unsigned integer. */ + Long.prototype.getLowBitsUnsigned = function () { + return this.low >>> 0; + }; + /** Gets the number of bits needed to represent the absolute value of this Long. */ + Long.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + // Unsigned Longs are never negative + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + var val = this.high !== 0 ? this.high : this.low; + var bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + }; + /** Tests if this Long's value is greater than the specified's. */ + Long.prototype.greaterThan = function (other) { + return this.comp(other) > 0; + }; + /** This is an alias of {@link Long.greaterThan} */ + Long.prototype.gt = function (other) { + return this.greaterThan(other); + }; + /** Tests if this Long's value is greater than or equal the specified's. */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.comp(other) >= 0; + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.gte = function (other) { + return this.greaterThanOrEqual(other); + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.ge = function (other) { + return this.greaterThanOrEqual(other); + }; + /** Tests if this Long's value is even. */ + Long.prototype.isEven = function () { + return (this.low & 1) === 0; + }; + /** Tests if this Long's value is negative. */ + Long.prototype.isNegative = function () { + return !this.unsigned && this.high < 0; + }; + /** Tests if this Long's value is odd. */ + Long.prototype.isOdd = function () { + return (this.low & 1) === 1; + }; + /** Tests if this Long's value is positive. */ + Long.prototype.isPositive = function () { + return this.unsigned || this.high >= 0; + }; + /** Tests if this Long's value equals zero. */ + Long.prototype.isZero = function () { + return this.high === 0 && this.low === 0; + }; + /** Tests if this Long's value is less than the specified's. */ + Long.prototype.lessThan = function (other) { + return this.comp(other) < 0; + }; + /** This is an alias of {@link Long#lessThan}. */ + Long.prototype.lt = function (other) { + return this.lessThan(other); + }; + /** Tests if this Long's value is less than or equal the specified's. */ + Long.prototype.lessThanOrEqual = function (other) { + return this.comp(other) <= 0; + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.lte = function (other) { + return this.lessThanOrEqual(other); + }; + /** Returns this Long modulo the specified. */ + Long.prototype.modulo = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + // use wasm support if present + if (wasm) { + var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.mod = function (divisor) { + return this.modulo(divisor); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.rem = function (divisor) { + return this.modulo(divisor); + }; + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + Long.prototype.multiply = function (multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + // use wasm support if present + if (wasm) { + var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } + else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + // If both longs are small, use float multiplication + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xffff; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** This is an alias of {@link Long.multiply} */ + Long.prototype.mul = function (multiplier) { + return this.multiply(multiplier); + }; + /** Returns the Negation of this Long's value. */ + Long.prototype.negate = function () { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + }; + /** This is an alias of {@link Long.negate} */ + Long.prototype.neg = function () { + return this.negate(); + }; + /** Returns the bitwise NOT of this Long. */ + Long.prototype.not = function () { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + }; + /** Tests if this Long's value differs from the specified's. */ + Long.prototype.notEquals = function (other) { + return !this.equals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.neq = function (other) { + return this.notEquals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.ne = function (other) { + return this.notEquals(other); + }; + /** + * Returns the bitwise OR of this Long and the specified. + */ + Long.prototype.or = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + }; + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftLeft = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + }; + /** This is an alias of {@link Long.shiftLeft} */ + Long.prototype.shl = function (numBits) { + return this.shiftLeft(numBits); + }; + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRight = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + }; + /** This is an alias of {@link Long.shiftRight} */ + Long.prototype.shr = function (numBits) { + return this.shiftRight(numBits); + }; + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRightUnsigned = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + var high = this.high; + if (numBits < 32) { + var low = this.low; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); + } + else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shr_u = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shru = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + Long.prototype.subtract = function (subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + /** This is an alias of {@link Long.subtract} */ + Long.prototype.sub = function (subtrahend) { + return this.subtract(subtrahend); + }; + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + Long.prototype.toInt = function () { + return this.unsigned ? this.low >>> 0 : this.low; + }; + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + Long.prototype.toNumber = function () { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + /** Converts the Long to a BigInt (arbitrary precision). */ + Long.prototype.toBigInt = function () { + return BigInt(this.toString()); + }; + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + Long.prototype.toBytes = function (le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + Long.prototype.toBytesLE = function () { + var hi = this.high, lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + }; + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + Long.prototype.toBytesBE = function () { + var hi = this.high, lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + }; + /** + * Converts this Long to signed. + */ + Long.prototype.toSigned = function () { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + }; + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + Long.prototype.toString = function (radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + // Unsigned Longs are never negative + if (this.eq(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } + else + return '-' + this.neg().toString(radix); + } + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + // eslint-disable-next-line @typescript-eslint/no-this-alias + var rem = this; + var result = ''; + // eslint-disable-next-line no-constant-condition + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + var digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } + }; + /** Converts this Long to unsigned. */ + Long.prototype.toUnsigned = function () { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + }; + /** Returns the bitwise XOR of this Long and the given one. */ + Long.prototype.xor = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + }; + /** This is an alias of {@link Long.isZero} */ + Long.prototype.eqz = function () { + return this.isZero(); + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.le = function (other) { + return this.lessThanOrEqual(other); + }; + /* + **************************************************************** + * BSON SPECIFIC ADDITIONS * + **************************************************************** + */ + Long.prototype.toExtendedJSON = function (options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + }; + Long.fromExtendedJSON = function (doc, options) { + var result = Long.fromString(doc.$numberLong); + return options && options.relaxed ? result.toNumber() : result; + }; + /** @internal */ + Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Long.prototype.inspect = function () { + return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")"; + }; + Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); + /** Maximum unsigned value. */ + Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); + /** Signed zero */ + Long.ZERO = Long.fromInt(0); + /** Unsigned zero. */ + Long.UZERO = Long.fromInt(0, true); + /** Signed one. */ + Long.ONE = Long.fromInt(1); + /** Unsigned one. */ + Long.UONE = Long.fromInt(1, true); + /** Signed negative one. */ + Long.NEG_ONE = Long.fromInt(-1); + /** Maximum signed value. */ + Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + /** Minimum signed value. */ + Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + return Long; +}()); +Object.defineProperty(Long.prototype, '__isLong__', { value: true }); +Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); + +var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; +var EXPONENT_MAX = 6111; +var EXPONENT_MIN = -6176; +var EXPONENT_BIAS = 6176; +var MAX_DIGITS = 34; +// Nan value bits as 32 bit values (due to lack of longs) +var NAN_BUFFER = [ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +var INF_NEGATIVE_BUFFER = [ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +var INF_POSITIVE_BUFFER = [ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +var EXPONENT_REGEX = /^([-+])?(\d+)?$/; +// Extract least significant 5 bits +var COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +var EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +var COMBINATION_INFINITY = 30; +// Value of combination field for NaN +var COMBINATION_NAN = 31; +// Detect if the value is a digit +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +// Divide two uint128 values +function divideu128(value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + for (var i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + return { quotient: value, rem: _rem }; +} +// Multiply two Long values and return the 128 bit value +function multiply64x2(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + // Return the 128 bit result + return { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + // Make values unsigned + var uhleft = left.high >>> 0; + var uhright = right.high >>> 0; + // Compare high bits first + if (uhleft < uhright) { + return true; + } + else if (uhleft === uhright) { + var ulleft = left.low >>> 0; + var ulright = right.low >>> 0; + if (ulleft < ulright) + return true; + } + return false; +} +function invalidErr(string, message) { + throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); +} +/** + * A class representation of the BSON Decimal128 type. + * @public + */ +var Decimal128 = /** @class */ (function () { + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + function Decimal128(bytes) { + if (!(this instanceof Decimal128)) + return new Decimal128(bytes); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else { + this.bytes = bytes; + } + } + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + Decimal128.fromString = function (representation) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = new Long(0, 0); + // The low 17 digits of the significand + var significandLow = new Long(0, 0); + // The biased exponent + var biasedExponent = 0; + // Read index + var index = 0; + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (representation.length >= 7000) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + // Results + var stringMatch = representation.match(PARSE_STRING_REGEXP); + var infMatch = representation.match(PARSE_INF_REGEXP); + var nanMatch = representation.match(PARSE_NAN_REGEXP); + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + // full_match = stringMatch[0] + // sign = stringMatch[1] + var unsignedNumber = stringMatch[2]; + // stringMatch[3] is undefined if a whole number (ex "1", 12") + // but defined if a number w/ decimal in it (ex "1.0, 12.2") + var e = stringMatch[4]; + var expSign = stringMatch[5]; + var expNumber = stringMatch[6]; + // they provided e, but didn't give an exponent number. for ex "1e" + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + // they provided e, but didn't give a number before it. for ex "e1" + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + // Get the negative or positive sign + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + // Check if user passed Infinity or NaN + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + else if (representation[index] === 'N') { + return new Decimal128(buffer_1.from(NAN_BUFFER)); + } + } + // Read all the digits + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) + invalidErr(representation, 'contains multiple periods'); + sawRadix = true; + index = index + 1; + continue; + } + if (nDigitsStored < 34) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + // Only store 34 digits + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + if (sawRadix && !nDigitsRead) + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + // Read exponent if exists + if (representation[index] === 'e' || representation[index] === 'E') { + // Read exponent digits + var match = representation.substr(++index).match(EXPONENT_REGEX); + // No digits read + if (!match || !match[2]) + return new Decimal128(buffer_1.from(NAN_BUFFER)); + // Get exponent + exponent = parseInt(match[0], 10); + // Adjust the index + index = index + match[0].length; + } + // Return not a number + if (representation[index]) + return new Decimal128(buffer_1.from(NAN_BUFFER)); + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } + else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (digits[firstNonZero + significantDigits - 1] === 0) { + significantDigits = significantDigits - 1; + } + } + } + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit. can only do this if < significant digits than # stored. + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } + else { + // adjust to round + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits) { + var endOfString = nDigitsRead; + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + // if negative, we need to increment again to account for - sign at start. + if (isNegative) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + if (roundBit) { + var dIdx = lastDigit; + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + } + } + } + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } + else if (lastDigit - firstDigit < 17) { + var dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + else { + var dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + significandLow = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + // Encode combination, exponent, and significand. + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } + else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + dec.low = significand.low; + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + // Encode into a buffer + var buffer = buffer_1.alloc(16); + index = 0; + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + // Return the new Decimal128 + return new Decimal128(buffer); + }; + /** Create a string representation of the raw Decimal128 value */ + Decimal128.prototype.toString = function () { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) + significand[i] = 0; + // read pointer into significand + var index = 0; + // true if the number is zero + var is_zero = false; + // the most significant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: [0, 0, 0, 0] }; + // indexing variables + var j, k; + // Output string + var string = []; + // Unpack index + index = 0; + // Buffer reference + var buffer = this.bytes; + // Unpack the low 64bits into a long + // bits 96 - 127 + var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 64 - 95 + var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack the high 64bits into a long + // bits 32 - 63 + var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 0 - 31 + var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack index + index = 0; + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + // Decode combination field and exponent + // bits 1 - 5 + var combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } + else if (combination === COMBINATION_NAN) { + return 'NaN'; + } + else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } + else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + // unbiased exponent + var exponent = biased_exponent - EXPONENT_BIAS; + // Create string of significand digits + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + if (significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0) { + is_zero = true; + } + else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Perform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + // the exponent if scientific notation is used + var scientific_exponent = significand_digits - 1 + exponent; + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + // if there are too many significant digits, we should just be treating numbers + // as + or - 0 and using the non-scientific exponent (this is for the "invalid + // representation should be treated as 0/-0" spec cases in decimal128-1.json) + if (significand_digits > 34) { + string.push("" + 0); + if (exponent > 0) + string.push('E+' + exponent); + else if (exponent < 0) + string.push('E' + exponent); + return string.join(''); + } + string.push("" + significand[index++]); + significand_digits = significand_digits - 1; + if (significand_digits) { + string.push('.'); + } + for (var i = 0; i < significand_digits; i++) { + string.push("" + significand[index++]); + } + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } + else { + string.push("" + scientific_exponent); + } + } + else { + // Regular format with no decimal place + if (exponent >= 0) { + for (var i = 0; i < significand_digits; i++) { + string.push("" + significand[index++]); + } + } + else { + var radix_position = significand_digits + exponent; + // non-zero digits before radix + if (radix_position > 0) { + for (var i = 0; i < radix_position; i++) { + string.push("" + significand[index++]); + } + } + else { + string.push('0'); + } + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push("" + significand[index++]); + } + } + } + return string.join(''); + }; + Decimal128.prototype.toJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.prototype.toExtendedJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.fromExtendedJSON = function (doc) { + return Decimal128.fromString(doc.$numberDecimal); + }; + /** @internal */ + Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Decimal128.prototype.inspect = function () { + return "new Decimal128(\"" + this.toString() + "\")"; + }; + return Decimal128; +}()); +Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); + +/** + * A class representation of the BSON Double type. + * @public + */ +var Double = /** @class */ (function () { + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + function Double(value) { + if (!(this instanceof Double)) + return new Double(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + Double.prototype.valueOf = function () { + return this.value; + }; + Double.prototype.toJSON = function () { + return this.value; + }; + Double.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + /** @internal */ + Double.prototype.toExtendedJSON = function (options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user + // explicitly provided `-0` then we need to ensure the sign makes it into the output + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: "-" + this.value.toFixed(1) }; + } + var $numberDouble; + if (Number.isInteger(this.value)) { + $numberDouble = this.value.toFixed(1); + if ($numberDouble.length >= 13) { + $numberDouble = this.value.toExponential(13).toUpperCase(); + } + } + else { + $numberDouble = this.value.toString(); + } + return { $numberDouble: $numberDouble }; + }; + /** @internal */ + Double.fromExtendedJSON = function (doc, options) { + var doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + }; + /** @internal */ + Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Double.prototype.inspect = function () { + var eJSON = this.toExtendedJSON(); + return "new Double(" + eJSON.$numberDouble + ")"; + }; + return Double; +}()); +Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); + +/** + * A class representation of a BSON Int32 type. + * @public + */ +var Int32 = /** @class */ (function () { + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + function Int32(value) { + if (!(this instanceof Int32)) + return new Int32(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { + return this.value; + }; + Int32.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + Int32.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + Int32.prototype.toExtendedJSON = function (options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + }; + /** @internal */ + Int32.fromExtendedJSON = function (doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + }; + /** @internal */ + Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Int32.prototype.inspect = function () { + return "new Int32(" + this.valueOf() + ")"; + }; + return Int32; +}()); +Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); + +/** + * A class representation of the BSON MaxKey type. + * @public + */ +var MaxKey = /** @class */ (function () { + function MaxKey() { + if (!(this instanceof MaxKey)) + return new MaxKey(); + } + /** @internal */ + MaxKey.prototype.toExtendedJSON = function () { + return { $maxKey: 1 }; + }; + /** @internal */ + MaxKey.fromExtendedJSON = function () { + return new MaxKey(); + }; + /** @internal */ + MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MaxKey.prototype.inspect = function () { + return 'new MaxKey()'; + }; + return MaxKey; +}()); +Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); + +/** + * A class representation of the BSON MinKey type. + * @public + */ +var MinKey = /** @class */ (function () { + function MinKey() { + if (!(this instanceof MinKey)) + return new MinKey(); + } + /** @internal */ + MinKey.prototype.toExtendedJSON = function () { + return { $minKey: 1 }; + }; + /** @internal */ + MinKey.fromExtendedJSON = function () { + return new MinKey(); + }; + /** @internal */ + MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MinKey.prototype.inspect = function () { + return 'new MinKey()'; + }; + return MinKey; +}()); +Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +// Unique sequence for the current process (initialized on first use) +var PROCESS_UNIQUE = null; +var kId = Symbol('id'); +/** + * A class representation of the BSON ObjectId type. + * @public + */ +var ObjectId = /** @class */ (function () { + /** + * Create an ObjectId type + * + * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number. + */ + function ObjectId(id) { + if (!(this instanceof ObjectId)) + return new ObjectId(id); + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectId) { + this[kId] = id.id; + this.__id = id.__id; + } + if (typeof id === 'object' && id && 'id' in id) { + if ('toHexString' in id && typeof id.toHexString === 'function') { + this[kId] = buffer_1.from(id.toHexString(), 'hex'); + } + else { + this[kId] = typeof id.id === 'string' ? buffer_1.from(id.id) : id.id; + } + } + // The most common use case (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined); + // If we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + if (ArrayBuffer.isView(id) && id.byteLength === 12) { + this[kId] = ensureBuffer(id); + } + if (typeof id === 'string') { + if (id.length === 12) { + var bytes = buffer_1.from(id); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + } + else if (id.length === 24 && checkForHexRegExp.test(id)) { + this[kId] = buffer_1.from(id, 'hex'); + } + else { + throw new BSONTypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters'); + } + } + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + Object.defineProperty(ObjectId.prototype, "id", { + /** + * The ObjectId bytes + * @readonly + */ + get: function () { + return this[kId]; + }, + set: function (value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = value.toString('hex'); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ObjectId.prototype, "generationTime", { + /** + * The generation time of this ObjectId instance + * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch + */ + get: function () { + return this.id.readInt32BE(0); + }, + set: function (value) { + // Encode time into first 4 bytes + this.id.writeUInt32BE(value, 0); + }, + enumerable: false, + configurable: true + }); + /** Returns the ObjectId id as a 24 character hex string representation */ + ObjectId.prototype.toHexString = function () { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + var hexString = this.id.toString('hex'); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + }; + /** + * Update the ObjectId index + * @privateRemarks + * Used in generating new ObjectId's on the driver + * @internal + */ + ObjectId.getInc = function () { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + }; + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + ObjectId.generate = function (time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + var inc = ObjectId.getInc(); + var buffer = buffer_1.alloc(12); + // 4-byte timestamp + buffer.writeUInt32BE(time, 0); + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = randomBytes(5); + } + // 5-byte process unique + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + // 3-byte counter + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + }; + /** + * Converts the id into a 24 character hex string for printing + * + * @param format - The Buffer toString format parameter. + */ + ObjectId.prototype.toString = function (format) { + // Is the id a buffer then use the buffer toString method to return the format + if (format) + return this.id.toString(format); + return this.toHexString(); + }; + /** Converts to its JSON the 24 character hex string representation. */ + ObjectId.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + ObjectId.prototype.equals = function (otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this.toString() === otherId.toString(); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id)) { + return otherId === buffer_1.prototype.toString.call(this.id, 'latin1'); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { + return buffer_1.from(otherId).equals(this.id); + } + if (typeof otherId === 'object' && + 'toHexString' in otherId && + typeof otherId.toHexString === 'function') { + return otherId.toHexString() === this.toHexString(); + } + return false; + }; + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + ObjectId.prototype.getTimestamp = function () { + var timestamp = new Date(); + var time = this.id.readUInt32BE(0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + }; + /** @internal */ + ObjectId.createPk = function () { + return new ObjectId(); + }; + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + ObjectId.createFromTime = function (time) { + var buffer = buffer_1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer.writeUInt32BE(time, 0); + // Return the new objectId + return new ObjectId(buffer); + }; + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + ObjectId.createFromHexString = function (hexString) { + // Throw an error if it's not a valid setup + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(buffer_1.from(hexString, 'hex')); + }; + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + ObjectId.isValid = function (id) { + if (id == null) + return false; + if (typeof id === 'number') { + return true; + } + if (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); + } + if (id instanceof ObjectId) { + return true; + } + if (isUint8Array(id) && id.length === 12) { + return true; + } + // Duck-Typing detection of ObjectId like objects + if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { + if (typeof id.id === 'string') { + return id.id.length === 12; + } + return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); + } + return false; + }; + /** @internal */ + ObjectId.prototype.toExtendedJSON = function () { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + }; + /** @internal */ + ObjectId.fromExtendedJSON = function (doc) { + return new ObjectId(doc.$oid); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 24 character hex string representation. + * @internal + */ + ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + ObjectId.prototype.inspect = function () { + return "new ObjectId(\"" + this.toHexString() + "\")"; + }; + /** @internal */ + ObjectId.index = ~~(Math.random() * 0xffffff); + return ObjectId; +}()); +// Deprecated methods +Object.defineProperty(ObjectId.prototype, 'generate', { + value: deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') +}); +Object.defineProperty(ObjectId.prototype, 'getInc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId.prototype, 'get_inc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId, 'get_inc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); + +function alphabetize(str) { + return str.split('').sort().join(''); +} +/** + * A class representation of the BSON RegExp type. + * @public + */ +var BSONRegExp = /** @class */ (function () { + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) + return new BSONRegExp(pattern, options); + this.pattern = pattern; + this.options = alphabetize(options !== null && options !== void 0 ? options : ''); + if (this.pattern.indexOf('\x00') !== -1) { + throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); + } + if (this.options.indexOf('\x00') !== -1) { + throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); + } + // Validate options + for (var i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u')) { + throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported"); + } + } + } + BSONRegExp.parseOptions = function (options) { + return options ? options.split('').sort().join('') : ''; + }; + /** @internal */ + BSONRegExp.prototype.toExtendedJSON = function (options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + }; + /** @internal */ + BSONRegExp.fromExtendedJSON = function (doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + // This is for $regex query operators that have extended json values. + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc; + } + } + else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); + } + throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); + }; + return BSONRegExp; +}()); +Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); + +/** + * A class representation of the BSON Symbol type. + * @public + */ +var BSONSymbol = /** @class */ (function () { + /** + * @param value - the string representing the symbol. + */ + function BSONSymbol(value) { + if (!(this instanceof BSONSymbol)) + return new BSONSymbol(value); + this.value = value; + } + /** Access the wrapped string value. */ + BSONSymbol.prototype.valueOf = function () { + return this.value; + }; + BSONSymbol.prototype.toString = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.inspect = function () { + return "new BSONSymbol(\"" + this.value + "\")"; + }; + BSONSymbol.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.toExtendedJSON = function () { + return { $symbol: this.value }; + }; + /** @internal */ + BSONSymbol.fromExtendedJSON = function (doc) { + return new BSONSymbol(doc.$symbol); + }; + /** @internal */ + BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + return BSONSymbol; +}()); +Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); + +/** @public */ +var LongWithoutOverridesClass = Long; +/** @public */ +var Timestamp = /** @class */ (function (_super) { + __extends(Timestamp, _super); + function Timestamp(low, high) { + var _this = this; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + ///@ts-expect-error + if (!(_this instanceof Timestamp)) + return new Timestamp(low, high); + if (Long.isLong(low)) { + _this = _super.call(this, low.low, low.high, true) || this; + } + else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { + _this = _super.call(this, low.i, low.t, true) || this; + } + else { + _this = _super.call(this, low, high, true) || this; + } + Object.defineProperty(_this, '_bsontype', { + value: 'Timestamp', + writable: false, + configurable: false, + enumerable: false + }); + return _this; + } + Timestamp.prototype.toJSON = function () { + return { + $timestamp: this.toString() + }; + }; + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + Timestamp.fromInt = function (value) { + return new Timestamp(Long.fromInt(value, true)); + }; + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + Timestamp.fromNumber = function (value) { + return new Timestamp(Long.fromNumber(value, true)); + }; + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + Timestamp.fromString = function (str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + }; + /** @internal */ + Timestamp.prototype.toExtendedJSON = function () { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + }; + /** @internal */ + Timestamp.fromExtendedJSON = function (doc) { + return new Timestamp(doc.$timestamp); + }; + /** @internal */ + Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Timestamp.prototype.inspect = function () { + return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })"; + }; + Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + return Timestamp; +}(LongWithoutOverridesClass)); + +function isBSONType(value) { + return (isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); +} +// INT32 boundaries +var BSON_INT32_MAX$1 = 0x7fffffff; +var BSON_INT32_MIN$1 = -0x80000000; +// INT64 boundaries +var BSON_INT64_MAX$1 = 0x7fffffffffffffff; +var BSON_INT64_MIN$1 = -0x8000000000000000; +// all the types where we don't need to do any special processing and can just pass the EJSON +//straight to type.fromExtendedJSON +var keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deserializeValue(value, options) { + if (options === void 0) { options = {}; } + if (typeof value === 'number') { + if (options.relaxed || options.legacy) { + return value; + } + // if it's an integer, should interpret as smallest BSON integer + // that can represent it exactly. (if out of range, interpret as double.) + if (Math.floor(value) === value) { + if (value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1) + return new Int32(value); + if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1) + return Long.fromNumber(value); + } + // If the number is a non-integer or out of integer range, should interpret as BSON Double. + return new Double(value); + } + // from here on out we're looking for bson types, so bail if its not an object + if (value == null || typeof value !== 'object') + return value; + // upgrade deprecated undefined to null + if (value.$undefined) + return null; + var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); + for (var i = 0; i < keys.length; i++) { + var c = keysToCodecs[keys[i]]; + if (c) + return c.fromExtendedJSON(value, options); + } + if (value.$date != null) { + var d = value.$date; + var date = new Date(); + if (options.legacy) { + if (typeof d === 'number') + date.setTime(d); + else if (typeof d === 'string') + date.setTime(Date.parse(d)); + } + else { + if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (Long.isLong(d)) + date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) + date.setTime(d); + } + return date; + } + if (value.$code != null) { + var copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return Code.fromExtendedJSON(value); + } + if (isDBRefLike(value) || value.$dbPointer) { + var v = value.$ref ? value : value.$dbPointer; + // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) + // because of the order JSON.parse goes through the document + if (v instanceof DBRef) + return v; + var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); + var valid_1 = true; + dollarKeys.forEach(function (k) { + if (['$ref', '$id', '$db'].indexOf(k) === -1) + valid_1 = false; + }); + // only make DBRef if $ keys are all valid + if (valid_1) + return DBRef.fromExtendedJSON(v); + } + return value; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeArray(array, options) { + return array.map(function (v, index) { + options.seenObjects.push({ propertyName: "index " + index, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + var isoStr = date.toISOString(); + // we should only show milliseconds in timestamp if they're non-zero + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeValue(value, options) { + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); + if (index !== -1) { + var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); + var leadingPart = props + .slice(0, index) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var alreadySeen = props[index]; + var circularPart = ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var current = props[props.length - 1]; + var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new BSONTypeError('Converting circular structure to EJSON:\n' + + (" " + leadingPart + alreadySeen + circularPart + current + "\n") + + (" " + leadingSpace + "\\" + dashes + "/")); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || isDate(value)) { + var dateNum = value.getTime(), + // is it in year range 1970-9999? + inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + // it's an integer + if (Math.floor(value) === value) { + var int32Range = value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1; + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (int32Range) + return { $numberInt: value.toString() }; + if (int64Range) + return { $numberLong: value.toString() }; + } + return { $numberDouble: value.toString() }; + } + if (value instanceof RegExp || isRegExp(value)) { + var flags = value.flags; + if (flags === undefined) { + var match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + var rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === 'object') + return serializeDocument(value, options); + return value; +} +var BSON_TYPE_MAPPINGS = { + Binary: function (o) { return new Binary(o.value(), o.sub_type); }, + Code: function (o) { return new Code(o.code, o.scope); }, + DBRef: function (o) { return new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, + Decimal128: function (o) { return new Decimal128(o.bytes); }, + Double: function (o) { return new Double(o.value); }, + Int32: function (o) { return new Int32(o.value); }, + Long: function (o) { + return Long.fromBits( + // underscore variants for 1.x backwards compatibility + o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); + }, + MaxKey: function () { return new MaxKey(); }, + MinKey: function () { return new MinKey(); }, + ObjectID: function (o) { return new ObjectId(o); }, + ObjectId: function (o) { return new ObjectId(o); }, + BSONRegExp: function (o) { return new BSONRegExp(o.pattern, o.options); }, + Symbol: function (o) { return new BSONSymbol(o.value); }, + Timestamp: function (o) { return Timestamp.fromBits(o.low, o.high); } +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + var bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + // It's a regular object. Recursively serialize its property values. + var _doc = {}; + for (var name in doc) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + _doc[name] = serializeValue(doc[name], options); + } + finally { + options.seenObjects.pop(); + } + } + return _doc; + } + else if (isBSONType(doc)) { + // the "document" is really just a BSON type object + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + // There's no EJSON serialization function on the object. It's probably an + // object created by a previous version of this library (or another library) + // that's duck-typing objects to look like they were generated by this library). + // Copy the object into this library's version of that type. + var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + // Two BSON types may have nested objects that may need to be serialized too + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } + else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + } + return outDoc.toExtendedJSON(options); + } + else { + throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} +/** + * EJSON parse / stringify API + * @public + */ +// the namespace here is used to emulate `export * as EJSON from '...'` +// which as of now (sept 2020) api-extractor does not support +// eslint-disable-next-line @typescript-eslint/no-namespace +var EJSON; +(function (EJSON) { + /** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ + function parse(text, options) { + var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); + // relaxed implies not strict + if (typeof finalOptions.relaxed === 'boolean') + finalOptions.strict = !finalOptions.relaxed; + if (typeof finalOptions.strict === 'boolean') + finalOptions.relaxed = !finalOptions.strict; + return JSON.parse(text, function (key, value) { + if (key.indexOf('\x00') !== -1) { + throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key)); + } + return deserializeValue(value, finalOptions); + }); + } + EJSON.parse = parse; + /** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ + function stringify(value, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer, space, options) { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + var doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); + } + EJSON.stringify = stringify; + /** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ + function serialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); + } + EJSON.serialize = serialize; + /** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ + function deserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); + } + EJSON.deserialize = deserialize; +})(EJSON || (EJSON = {})); + +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** @public */ +var bsonMap; +var bsonGlobal = getGlobal(); +if (bsonGlobal.Map) { + bsonMap = bsonGlobal.Map; +} +else { + // We will return a polyfill + bsonMap = /** @class */ (function () { + function Map(array) { + if (array === void 0) { array = []; } + this._keys = []; + this._values = {}; + for (var i = 0; i < array.length; i++) { + if (array[i] == null) + continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + } + Map.prototype.clear = function () { + this._keys = []; + this._values = {}; + }; + Map.prototype.delete = function (key) { + var value = this._values[key]; + if (value == null) + return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + Map.prototype.entries = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? [key, _this._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.forEach = function (callback, self) { + self = self || this; + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + Map.prototype.get = function (key) { + return this._values[key] ? this._values[key].v : undefined; + }; + Map.prototype.has = function (key) { + return this._values[key] != null; + }; + Map.prototype.keys = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.set = function (key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + Map.prototype.values = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? _this._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Object.defineProperty(Map.prototype, "size", { + get: function () { + return this._keys.length; + }, + enumerable: false, + configurable: true + }); + return Map; + }()); +} + +/** @internal */ +var BSON_INT32_MAX = 0x7fffffff; +/** @internal */ +var BSON_INT32_MIN = -0x80000000; +/** @internal */ +var BSON_INT64_MAX = Math.pow(2, 63) - 1; +/** @internal */ +var BSON_INT64_MIN = -Math.pow(2, 63); +/** + * Any integer up to 2^53 can be precisely represented by a double. + * @internal + */ +var JS_INT_MAX = Math.pow(2, 53); +/** + * Any integer down to -2^53 can be precisely represented by a double. + * @internal + */ +var JS_INT_MIN = -Math.pow(2, 53); +/** Number BSON Type @internal */ +var BSON_DATA_NUMBER = 1; +/** String BSON Type @internal */ +var BSON_DATA_STRING = 2; +/** Object BSON Type @internal */ +var BSON_DATA_OBJECT = 3; +/** Array BSON Type @internal */ +var BSON_DATA_ARRAY = 4; +/** Binary BSON Type @internal */ +var BSON_DATA_BINARY = 5; +/** Binary BSON Type @internal */ +var BSON_DATA_UNDEFINED = 6; +/** ObjectId BSON Type @internal */ +var BSON_DATA_OID = 7; +/** Boolean BSON Type @internal */ +var BSON_DATA_BOOLEAN = 8; +/** Date BSON Type @internal */ +var BSON_DATA_DATE = 9; +/** null BSON Type @internal */ +var BSON_DATA_NULL = 10; +/** RegExp BSON Type @internal */ +var BSON_DATA_REGEXP = 11; +/** Code BSON Type @internal */ +var BSON_DATA_DBPOINTER = 12; +/** Code BSON Type @internal */ +var BSON_DATA_CODE = 13; +/** Symbol BSON Type @internal */ +var BSON_DATA_SYMBOL = 14; +/** Code with Scope BSON Type @internal */ +var BSON_DATA_CODE_W_SCOPE = 15; +/** 32 bit Integer BSON Type @internal */ +var BSON_DATA_INT = 16; +/** Timestamp BSON Type @internal */ +var BSON_DATA_TIMESTAMP = 17; +/** Long BSON Type @internal */ +var BSON_DATA_LONG = 18; +/** Decimal128 BSON Type @internal */ +var BSON_DATA_DECIMAL128 = 19; +/** MinKey BSON Type @internal */ +var BSON_DATA_MIN_KEY = 0xff; +/** MaxKey BSON Type @internal */ +var BSON_DATA_MAX_KEY = 0x7f; +/** Binary Default Type @internal */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** Binary Function Type @internal */ +var BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** Binary Byte Array Type @internal */ +var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ +var BSON_BINARY_SUBTYPE_UUID = 3; +/** Binary UUID Type @internal */ +var BSON_BINARY_SUBTYPE_UUID_NEW = 4; +/** Binary MD5 Type @internal */ +var BSON_BINARY_SUBTYPE_MD5 = 5; +/** Encrypted BSON type @internal */ +var BSON_BINARY_SUBTYPE_ENCRYPTED = 6; +/** Column BSON type @internal */ +var BSON_BINARY_SUBTYPE_COLUMN = 7; +/** Binary User Defined Type @internal */ +var BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) { + var totalLength = 4 + 1; + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } + else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +/** @internal */ +function calculateElement(name, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +value, serializeFunctions, isArray, ignoreUndefined) { + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (isArray === void 0) { isArray = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = false; } + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + buffer_1.byteLength(name, 'utf8') + 1 + 4 + buffer_1.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + // 32 bit + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } + else { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } + else { + // 64 bit + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (value['_bsontype'] === 'Decimal128') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } + else if (value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.byteLength(value.code.toString(), 'utf8') + + 1); + } + } + else if (value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)); + } + } + else if (value['_bsontype'] === 'Symbol') { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + buffer_1.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1); + } + else if (value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + // Add db reference if it exists + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value['_bsontype'] === 'BSONRegExp') { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.byteLength(value.pattern, 'utf8') + + 1 + + buffer_1.byteLength(value.options, 'utf8') + + 1); + } + else { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); + } + else if (serializeFunctions) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + + 1); + } + } + } + return 0; +} + +var FIRST_BIT = 0x80; +var FIRST_TWO_BITS = 0xc0; +var FIRST_THREE_BITS = 0xe0; +var FIRST_FOUR_BITS = 0xf0; +var FIRST_FIVE_BITS = 0xf8; +var TWO_BIT_CHAR = 0xc0; +var THREE_BIT_CHAR = 0xe0; +var FOUR_BIT_CHAR = 0xf0; +var CONTINUING_CHAR = 0x80; +/** + * Determines if the passed in bytes are valid utf8 + * @param bytes - An array of 8-bit bytes. Must be indexable and have length property + * @param start - The index to start validating + * @param end - The index to end validating + */ +function validateUtf8(bytes, start, end) { + var continuation = 0; + for (var i = start; i < end; i += 1) { + var byte = bytes[i]; + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } + else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } + else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } + else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } + else { + return false; + } + } + } + return !continuation; +} + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +var functionCache = {}; +function deserialize$1(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (size < 5) { + throw new BSONError("bson size must be >= 5, is " + size); + } + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size); + } + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new BSONError("buffer length " + buffer.length + " must === bson size " + size); + } + if (size + index > buffer.byteLength) { + throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); + } + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +} +var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray) { + if (isArray === void 0) { isArray = false; } + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + // Set the start index + var startIndex = index; + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + // Read the document size + var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + var done = false; + var isPossibleDBRef = isArray ? false : null; + // While we have more left data left keep parsing + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) + break; + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + var value = void 0; + index = i + 1; + if (elementType === BSON_DATA_STRING) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + value = getValidatedString(buffer, index, index + stringSize - 1); + index = index + stringSize; + } + else if (elementType === BSON_DATA_OID) { + var oid = buffer_1.alloc(12); + buffer.copy(oid, 0, index, index + 12); + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } + else if (elementType === BSON_DATA_NUMBER) { + value = buffer.readDoubleLE(index); + index = index + 8; + } + else if (elementType === BSON_DATA_DATE) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Date(new Long(lowBits, highBits).toNumber()); + } + else if (elementType === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new BSONError('bad embedded document length in bson'); + // We have a raw value + if (raw) { + value = buffer.slice(index, index + objectSize); + } + else { + value = deserializeObject(buffer, _index, options, false); + } + index = index + objectSize; + } + else if (elementType === BSON_DATA_ARRAY) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + var arrayOptions = options; + // Stop index + var stopIndex = index + objectSize; + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) { + arrayOptions[n] = options[n]; + } + arrayOptions['raw'] = true; + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + if (buffer[index - 1] !== 0) + throw new BSONError('invalid array terminator byte'); + if (index !== stopIndex) + throw new BSONError('corrupted array bson'); + } + else if (elementType === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + // Unpack the low and high bits + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } + else { + value = long; + } + } + else if (elementType === BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = buffer_1.alloc(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { + value = decimal128.toObject(); + } + else { + value = decimal128; + } + } + else if (elementType === BSON_DATA_BINARY) { + var binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var totalBinarySize = binarySize; + var subType = buffer[index++]; + // Did we have a negative binary size, throw + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + // Is the length longer than the document + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = buffer.slice(index, index + binarySize); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } + else { + var _buffer = buffer_1.alloc(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else { + value = new Binary(_buffer, subType); + } + } + // Update the index + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + value = new RegExp(source, optionsArray.join('')); + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // Set the object + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === BSON_DATA_SYMBOL) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + var symbol = getValidatedString(buffer, index, index + stringSize - 1); + value = promoteValues ? symbol : new BSONSymbol(symbol); + index = index + stringSize; + } + else if (elementType === BSON_DATA_TIMESTAMP) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Timestamp(lowBits, highBits); + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === BSON_DATA_CODE) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + var functionString = getValidatedString(buffer, index, index + stringSize - 1); + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + } + else { + value = new Code(functionString); + } + // Update parse index position + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + // Javascript function + var functionString = getValidatedString(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + var _index = index; + // Decode the size of the object document + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + // Check if field length is too short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + // Check if totalSize field is too long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + value.scope = scopeObject; + } + else { + value = new Code(functionString, scopeObject); + } + } + else if (elementType === BSON_DATA_DBPOINTER) { + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) + throw new BSONError('bad string length in bson'); + // Namespace + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Read the oid + var oidBuffer = buffer_1.alloc(12); + buffer.copy(oidBuffer, 0, index, index + 12); + var oid = new ObjectId(oidBuffer); + // Update the index + index = index + 12; + // Upgrade to DBRef type + value = new DBRef(namespace, oid); + } + else { + throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value: value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + object[name] = value; + } + } + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + var copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} +/** + * Ensure eval is isolated, store the result in functionCache. + * + * @internal + */ +function isolateEval(functionString, functionCache, object) { + if (!functionCache) + return new Function(functionString); + // Check for cache hit, eval if missing and return cached function + if (functionCache[functionString] == null) { + functionCache[functionString] = new Function(functionString); + } + // Set the object + return functionCache[functionString].bind(object); +} +function getValidatedString(buffer, start, end) { + var value = buffer.toString('utf8', start, end); + for (var i = 0; i < value.length; i++) { + if (value.charCodeAt(i) === 0xfffd) { + if (!validateUtf8(buffer, start, end)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + return value; +} + +// Copyright (c) 2008, Fair Oaks Labs, Inc. +function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) { + var e; + var m; + var c; + var bBE = endian === 'big'; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = bBE ? nBytes - 1 : 0; + var d = bBE ? -1 : 1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } + else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } + else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } + else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } + else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + if (isNaN(value)) + m = 0; + while (mLen >= 8) { + buffer[offset + i] = m & 0xff; + i += d; + m /= 256; + mLen -= 8; + } + e = (e << mLen) | m; + if (isNaN(value)) + e += 8; + eLen += mLen; + while (eLen > 0) { + buffer[offset + i] = e & 0xff; + i += d; + e /= 256; + eLen -= 8; + } + buffer[offset + i - d] |= s * 128; +} + +var regexp = /\x00/; // eslint-disable-line no-control-regex +var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +/* + * isArray indicates if we are writing to a BSON array (type 0x04) + * which forces the "key" which really an array index as a string to be written as ascii + * This will catch any errors in index as a string generation + */ +function serializeString(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, undefined, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} +function serializeNumber(buffer, key, value, index, isArray) { + // We have an integer value + // TODO(NODE-2529): Add support for big int + if (Number.isInteger(value) && + value >= BSON_INT32_MIN && + value <= BSON_INT32_MAX) { + // If the value fits in 32 bits encode as int32 + // Set int type 32 bits or less + buffer[index++] = BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } + else { + // Encode as double + buffer[index++] = BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + } + return index; +} +function serializeNull(buffer, key, _, index, isArray) { + // Set long type + buffer[index++] = BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} +function serializeRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.ignoreCase) + buffer[index++] = 0x69; // i + if (value.global) + buffer[index++] = 0x73; // s + if (value.multiline) + buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.pattern, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, undefined, 'binary'); + } + else if (isUint8Array(value.id)) { + // Use the standard JS methods here because buffer.copy() is buggy with the + // browser polyfill + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + // Adjust index + return index + 12; +} +function serializeBuffer(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + buffer.set(ensureBuffer(value), index); + // Adjust the index + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (path === void 0) { path = []; } + for (var i = 0; i < path.length; i++) { + if (path[i] === value) + throw new BSONError('cyclic dependency detected'); + } + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index, isArray) { + buffer[index++] = BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + // Prefer the standard JS methods because their typechecking is not buggy, + // unlike the `buffer` polyfill's. + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} +function serializeLong(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} +function serializeInt32(buffer, key, value, index, isArray) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +} +function serializeDouble(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value.value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + return index; +} +function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { + buffer[index++] = BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Starting index + var startIndex = index; + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + index = endIndex - 1; + // Writ the total + var totalSize = endIndex - startIndex; + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) + size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + // Write the data to the object + buffer.set(data, index); + // Adjust the index + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var startIndex = index; + var output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (startingIndex === void 0) { startingIndex = 0; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (path === void 0) { path = []; } + startingIndex = startingIndex || 0; + path = path || []; + // Push the object to the path + path.push(object); + // Start place to serialize into + var index = startingIndex + 4; + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index, true); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } + else if (typeof value === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } + else if (typeof value === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } + else if (typeof value === 'object' && + isBSONType(value) && + value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + else if (object instanceof bsonMap || isMap(object)) { + var iterator = object.entries(); + var done = false; + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = !!entry.done; + // Are we done, then skip and terminate + if (done) + continue; + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new BSONTypeError('toBSON function did not return an object'); + } + // Iterate over all the keys + for (var key in object) { + var value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + // Remove the path + path.pop(); + // Final padding byte for object + buffer[index++] = 0x00; + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +/** @internal */ +// Default Max Size +var MAXSIZE = 1024 * 1024 * 17; +// Current Internal Temporary Serialization Buffer +var buffer = buffer_1.alloc(MAXSIZE); +/** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer + * @public + */ +function setInternalBufferSize(size) { + // Resize the internal serialization buffer if needed + if (buffer.length < size) { + buffer = buffer_1.alloc(size); + } +} +/** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ +function serialize(object, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = buffer_1.alloc(minInternalBufferSize); + } + // Attempt to serialize + var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = buffer_1.alloc(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +} +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ +function serializeWithBufferAndIndex(object, finalBuffer, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + // Attempt to serialize + var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + // Return the index + return startIndex + serializationIndex - 1; +} +/** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ +function deserialize(buffer, options) { + if (options === void 0) { options = {}; } + return deserialize$1(buffer instanceof buffer_1 ? buffer : ensureBuffer(buffer), options); +} +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ +function calculateObjectSize(object, options) { + if (options === void 0) { options = {}; } + options = options || {}; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + return calculateObjectSize$1(object, serializeFunctions, ignoreUndefined); +} +/** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + var bufferData = ensureBuffer(data); + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + // Update options with index + internalOptions.index = index; + // Parse the document at this point + documents[docStartIndex + i] = deserialize$1(bufferData, internalOptions); + // Adjust index by the document size + index = index + size; + } + // Return object containing end index of parsing and list of documents + return index; +} +/** + * BSON default export + * @deprecated Please use named exports + * @privateRemarks + * We want to someday deprecate the default export, + * so none of the new TS types are being exported on the default + * @public + */ +var BSON = { + Binary: Binary, + Code: Code, + DBRef: DBRef, + Decimal128: Decimal128, + Double: Double, + Int32: Int32, + Long: Long, + UUID: UUID, + Map: bsonMap, + MaxKey: MaxKey, + MinKey: MinKey, + ObjectId: ObjectId, + ObjectID: ObjectId, + BSONRegExp: BSONRegExp, + BSONSymbol: BSONSymbol, + Timestamp: Timestamp, + EJSON: EJSON, + setInternalBufferSize: setInternalBufferSize, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + deserialize: deserialize, + calculateObjectSize: calculateObjectSize, + deserializeStream: deserializeStream, + BSONError: BSONError, + BSONTypeError: BSONTypeError +}; + +export default BSON; +export { BSONError, BSONRegExp, BSONSymbol, BSONTypeError, BSON_BINARY_SUBTYPE_BYTE_ARRAY, BSON_BINARY_SUBTYPE_COLUMN, BSON_BINARY_SUBTYPE_DEFAULT, BSON_BINARY_SUBTYPE_ENCRYPTED, BSON_BINARY_SUBTYPE_FUNCTION, BSON_BINARY_SUBTYPE_MD5, BSON_BINARY_SUBTYPE_USER_DEFINED, BSON_BINARY_SUBTYPE_UUID, BSON_BINARY_SUBTYPE_UUID_NEW, BSON_DATA_ARRAY, BSON_DATA_BINARY, BSON_DATA_BOOLEAN, BSON_DATA_CODE, BSON_DATA_CODE_W_SCOPE, BSON_DATA_DATE, BSON_DATA_DBPOINTER, BSON_DATA_DECIMAL128, BSON_DATA_INT, BSON_DATA_LONG, BSON_DATA_MAX_KEY, BSON_DATA_MIN_KEY, BSON_DATA_NULL, BSON_DATA_NUMBER, BSON_DATA_OBJECT, BSON_DATA_OID, BSON_DATA_REGEXP, BSON_DATA_STRING, BSON_DATA_SYMBOL, BSON_DATA_TIMESTAMP, BSON_DATA_UNDEFINED, BSON_INT32_MAX, BSON_INT32_MIN, BSON_INT64_MAX, BSON_INT64_MIN, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, LongWithoutOverridesClass, bsonMap as Map, MaxKey, MinKey, ObjectId as ObjectID, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize }; +//# sourceMappingURL=bson.browser.esm.js.map diff --git a/node_modules/bson/dist/bson.browser.esm.js.map b/node_modules/bson/dist/bson.browser.esm.js.map new file mode 100644 index 0000000..5b694c0 --- /dev/null +++ b/node_modules/bson/dist/bson.browser.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.browser.esm.js","sources":["../node_modules/base64-js/index.js","../node_modules/ieee754/index.js","../node_modules/buffer/index.js","../node_modules/tslib/tslib.es6.js","../src/error.ts","../src/utils/global.ts","../src/parser/utils.ts","../src/ensure_buffer.ts","../src/uuid_utils.ts","../src/uuid.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/extended_json.ts","../src/map.ts","../src/constants.ts","../src/parser/calculate_size.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/float_parser.ts","../src/parser/serializer.ts","../src/bson.ts"],"sourcesContent":["'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n var proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n var copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n Buffer.from(buf).copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (var i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nvar hexSliceLookupTable = (function () {\n var alphabet = '0123456789abcdef'\n var table = new Array(256)\n for (var i = 0; i < 16; ++i) {\n var i16 = i * 16\n for (var j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["byteLength","toByteArray","fromByteArray","lookup","revLookup","Arr","Uint8Array","Array","code","i","len","length","charCodeAt","getLens","b64","Error","validLen","indexOf","placeHoldersLen","lens","_byteLength","tmp","arr","curByte","tripletToBase64","num","encodeChunk","uint8","start","end","output","push","join","extraBytes","parts","maxChunkLength","len2","buffer","offset","isLE","mLen","nBytes","e","m","eLen","eMax","eBias","nBits","d","s","NaN","Infinity","Math","pow","value","c","rt","abs","isNaN","floor","log","LN2","customInspectSymbol","Symbol","exports","Buffer","SlowBuffer","K_MAX_LENGTH","TYPED_ARRAY_SUPPORT","typedArraySupport","console","error","proto","foo","Object","setPrototypeOf","prototype","defineProperty","enumerable","get","isBuffer","undefined","byteOffset","createBuffer","RangeError","buf","arg","encodingOrOffset","TypeError","allocUnsafe","from","poolSize","fromString","ArrayBuffer","isView","fromArrayView","isInstance","fromArrayBuffer","SharedArrayBuffer","valueOf","b","fromObject","toPrimitive","assertSize","size","alloc","fill","encoding","checked","allocUnsafeSlow","string","isEncoding","actual","write","slice","fromArrayLike","array","arrayView","copy","obj","numberIsNaN","type","isArray","data","toString","_isBuffer","compare","a","x","y","min","String","toLowerCase","concat","list","pos","set","call","mustMatch","arguments","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","n","swap16","swap32","swap64","apply","toLocaleString","equals","inspect","str","max","INSPECT_MAX_BYTES","replace","trim","target","thisStart","thisEnd","thisCopy","targetCopy","bidirectionalIndexOf","val","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","includes","hexWrite","Number","remaining","strLen","parsed","parseInt","substr","utf8Write","blitBuffer","asciiWrite","asciiToBytes","base64Write","ucs2Write","utf16leToBytes","isFinite","toJSON","_arr","base64","res","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","decodeCodePointsArray","MAX_ARGUMENTS_LENGTH","codePoints","fromCharCode","ret","out","hexSliceLookupTable","bytes","newBuf","subarray","checkOffset","ext","readUintLE","readUIntLE","noAssert","mul","readUintBE","readUIntBE","readUint8","readUInt8","readUint16LE","readUInt16LE","readUint16BE","readUint32LE","readUInt32LE","readUint32BE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","ieee754","readFloatBE","readDoubleLE","readDoubleBE","checkInt","writeUintLE","writeUIntLE","maxBytes","writeUintBE","writeUIntBE","writeUint8","writeUInt8","writeUint16LE","writeUInt16LE","writeUint16BE","writeUInt16BE","writeUint32LE","writeUInt32LE","writeUint32BE","writeUInt32BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","checkIEEE754","writeFloat","littleEndian","writeFloatLE","writeFloatBE","writeDouble","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","INVALID_BASE64_RE","base64clean","split","units","leadSurrogate","byteArray","hi","lo","src","dst","constructor","name","alphabet","table","i16","extendStatics","__proto__","p","hasOwnProperty","__extends","__","create","kId","BSON_INT32_MAX","BSON_INT32_MIN","BSON_INT64_MAX","BSON_INT64_MIN","calculateObjectSize","constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","deserialize","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT","Map","internalSerialize","internalDeserialize","internalCalculateObjectSize"],"mappings":";;;;AAEA,gBAAkB,GAAG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K,OAAA;IACL,UAAU,YAAA;IACV,MAAM,QAAA;IACN,KAAK,OAAA;IACL,IAAI,MAAA;IACJ,IAAI,MAAA;IACJ,GAAG,SAAA;IACH,MAAM,QAAA;IACN,MAAM,QAAA;IACN,QAAQ,UAAA;IACR,QAAQ,EAAE,QAAQ;IAClB,UAAU,YAAA;IACV,UAAU,YAAA;IACV,SAAS,WAAA;IACT,KAAK,OAAA;IACL,qBAAqB,uBAAA;IACrB,SAAS,WAAA;IACT,2BAA2B,6BAAA;IAC3B,WAAW,aAAA;IACX,mBAAmB,qBAAA;IACnB,iBAAiB,mBAAA;IACjB,SAAS,WAAA;IACT,aAAa,eAAA;;;;;;"} \ No newline at end of file diff --git a/node_modules/bson/dist/bson.browser.umd.js b/node_modules/bson/dist/bson.browser.umd.js new file mode 100644 index 0000000..952b3e8 --- /dev/null +++ b/node_modules/bson/dist/bson.browser.umd.js @@ -0,0 +1,7495 @@ +(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.BSON = {})); +}(this, (function (exports) { 'use strict'; + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var byteLength_1 = byteLength; + var toByteArray_1 = toByteArray; + var fromByteArray_1 = fromByteArray; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } // Support decoding URL-safe base64 strings, as Node.js does. + // See: https://en.wikipedia.org/wiki/Base64#URL_applications + + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + + function getLens(b64) { + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4'); + } // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + + + var validLen = b64.indexOf('='); + if (validLen === -1) validLen = len; + var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; + } // base64 is 4/3 + up to two characters of the original data + + + function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + + function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + + function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; // if there are placeholders, only get up to the last complete 4 chars + + var len = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i; + + for (i = 0; i < len; i += 4) { + tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; + arr[curByte++] = tmp >> 16 & 0xFF; + arr[curByte++] = tmp >> 8 & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; + arr[curByte++] = tmp & 0xFF; + } + + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + + return arr; + } + + function tripletToBase64(num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; + } + + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF); + output.push(tripletToBase64(tmp)); + } + + return output.join(''); + } + + function fromByteArray(uint8) { + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + // go through the array every three bytes, we'll deal with trailing stuff later + + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); + } // pad the end with zeros, but make sure to not forget the extra bytes + + + if (extraBytes === 1) { + tmp = uint8[len - 1]; + parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '=='); + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '='); + } + + return parts.join(''); + } + + var base64Js = { + byteLength: byteLength_1, + toByteArray: toByteArray_1, + fromByteArray: fromByteArray_1 + }; + + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + var read = function read(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + }; + + var write = function write(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = e << mLen | m; + eLen += mLen; + + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + }; + + var ieee754 = { + read: read, + write: write + }; + + var buffer$1 = createCommonjsModule(function (module, exports) { + + var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' ? // eslint-disable-line dot-notation + Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null; + exports.Buffer = Buffer; + exports.SlowBuffer = SlowBuffer; + exports.INSPECT_MAX_BYTES = 50; + var K_MAX_LENGTH = 0x7fffffff; + exports.kMaxLength = K_MAX_LENGTH; + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ + + Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); + + if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { + console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'); + } + + function typedArraySupport() { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1); + var proto = { + foo: function foo() { + return 42; + } + }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e) { + return false; + } + } + + Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function get() { + if (!Buffer.isBuffer(this)) return undefined; + return this.buffer; + } + }); + Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function get() { + if (!Buffer.isBuffer(this)) return undefined; + return this.byteOffset; + } + }); + + function createBuffer(length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"'); + } // Return an augmented `Uint8Array` instance + + + var buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer.prototype); + return buf; + } + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + + function Buffer(arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError('The "string" argument must be of type string. Received type number'); + } + + return allocUnsafe(arg); + } + + return from(arg, encodingOrOffset, length); + } + + Buffer.poolSize = 8192; // not used by this implementation + + function from(value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset); + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value); + } + + if (value == null) { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value)); + } + + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + + if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type number'); + } + + var valueOf = value.valueOf && value.valueOf(); + + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length); + } + + var b = fromObject(value); + if (b) return b; + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length); + } + + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value)); + } + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + + + Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length); + }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: + // https://github.com/feross/buffer/pull/148 + + + Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer, Uint8Array); + + function assertSize(size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + + function alloc(size, fill, encoding) { + assertSize(size); + + if (size <= 0) { + return createBuffer(size); + } + + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + + return createBuffer(size); + } + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + + + Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding); + }; + + function allocUnsafe(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + + + Buffer.allocUnsafe = function (size) { + return allocUnsafe(size); + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + + + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size); + }; + + function fromString(string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding); + } + + var length = byteLength(string, encoding) | 0; + var buf = createBuffer(length); + var actual = buf.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual); + } + + return buf; + } + + function fromArrayLike(array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + var buf = createBuffer(length); + + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + + return buf; + } + + function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); + } + + return fromArrayLike(arrayView); + } + + function fromArrayBuffer(array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + + var buf; + + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array); + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length); + } // Return an augmented `Uint8Array` instance + + + Object.setPrototypeOf(buf, Buffer.prototype); + return buf; + } + + function fromObject(obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); + + if (buf.length === 0) { + return buf; + } + + obj.copy(buf, 0, 0, len); + return buf; + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0); + } + + return fromArrayLike(obj); + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + + function checked(length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes'); + } + + return length | 0; + } + + function SlowBuffer(length) { + if (+length != length) { + // eslint-disable-line eqeqeq + length = 0; + } + + return Buffer.alloc(+length); + } + + Buffer.isBuffer = function isBuffer(b) { + return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false + }; + + Buffer.compare = function compare(a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength); + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength); + + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); + } + + if (a === b) return 0; + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + + Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true; + + default: + return false; + } + }; + + Buffer.concat = function concat(list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + + if (list.length === 0) { + return Buffer.alloc(0); + } + + var i; + + if (length === undefined) { + length = 0; + + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer.from(buf).copy(buffer, pos); + } else { + Uint8Array.prototype.set.call(buffer, buf, pos); + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer, pos); + } + + pos += buf.length; + } + + return buffer; + }; + + function byteLength(string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length; + } + + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength; + } + + if (typeof string !== 'string') { + throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + babelHelpers["typeof"](string)); + } + + var len = string.length; + var mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion + + var loweredCase = false; + + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len; + + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length; + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2; + + case 'hex': + return len >>> 1; + + case 'base64': + return base64ToBytes(string).length; + + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8 + } + + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + + Buffer.byteLength = byteLength; + + function slowToString(encoding, start, end) { + var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + + if (start === undefined || start < 0) { + start = 0; + } // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + + + if (start > this.length) { + return ''; + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return ''; + } // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + + + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return ''; + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end); + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end); + + case 'ascii': + return asciiSlice(this, start, end); + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end); + + case 'base64': + return base64Slice(this, start, end); + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end); + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) + // to detect a Buffer instance. It's not possible to use `instanceof Buffer` + // reliably in a browserify context because there could be multiple different + // copies of the 'buffer' package in use. This method works even for Buffer + // instances that were created from another copy of the `buffer` package. + // See: https://github.com/feross/buffer/issues/154 + + + Buffer.prototype._isBuffer = true; + + function swap(b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16() { + var len = this.length; + + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits'); + } + + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + + return this; + }; + + Buffer.prototype.swap32 = function swap32() { + var len = this.length; + + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits'); + } + + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + + return this; + }; + + Buffer.prototype.swap64 = function swap64() { + var len = this.length; + + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits'); + } + + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + + return this; + }; + + Buffer.prototype.toString = function toString() { + var length = this.length; + if (length === 0) return ''; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); + }; + + Buffer.prototype.toLocaleString = Buffer.prototype.toString; + + Buffer.prototype.equals = function equals(b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); + if (this === b) return true; + return Buffer.compare(this, b) === 0; + }; + + Buffer.prototype.inspect = function inspect() { + var str = ''; + var max = exports.INSPECT_MAX_BYTES; + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); + if (this.length > max) str += ' ... '; + return ''; + }; + + if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; + } + + Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength); + } + + if (!Buffer.isBuffer(target)) { + throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + babelHelpers["typeof"](target)); + } + + if (start === undefined) { + start = 0; + } + + if (end === undefined) { + end = target ? target.length : 0; + } + + if (thisStart === undefined) { + thisStart = 0; + } + + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index'); + } + + if (thisStart >= thisEnd && start >= end) { + return 0; + } + + if (thisStart >= thisEnd) { + return -1; + } + + if (start >= end) { + return 1; + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) return 0; + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + + + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1; // Normalize byteOffset + + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + + byteOffset = +byteOffset; // Coerce to Number. + + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1; + } // Normalize byteOffset: negative offsets start from the end of the buffer + + + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + + if (byteOffset >= buffer.length) { + if (dir) return -1;else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0;else return -1; + } // Normalize val + + + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } // Finally, search either indexOf (if dir is true) or lastIndexOf + + + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1; + } + + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + + throw new TypeError('val must be string, number or Buffer'); + } + + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + + if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1; + } + + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read(buf, i) { + if (indexSize === 1) { + return buf[i]; + } else { + return buf.readUInt16BE(i * indexSize); + } + } + + var i; + + if (dir) { + var foundIndex = -1; + + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + + for (i = byteOffset; i >= 0; i--) { + var found = true; + + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + + if (found) return i; + } + } + + return -1; + } + + Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + + Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + + function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + + if (!length) { + length = remaining; + } else { + length = Number(length); + + if (length > remaining) { + length = remaining; + } + } + + var strLen = string.length; + + if (length > strLen / 2) { + length = strLen / 2; + } + + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i; + buf[offset + i] = parsed; + } + + return i; + } + + function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); + } + + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); + } + + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); + } + + function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); + } + + Buffer.prototype.write = function write(string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0; + + if (isFinite(length)) { + length = length >>> 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + } else { + throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds'); + } + + if (!encoding) encoding = 'utf8'; + var loweredCase = false; + + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length); + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length); + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length); + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length); + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length); + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON() { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64Js.fromByteArray(buf); + } else { + return base64Js.fromByteArray(buf.slice(start, end)); + } + } + + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + var i = start; + + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + + break; + + case 2: + secondByte = buf[i + 1]; + + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; + + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + + break; + + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; + + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + + break; + + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; + + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res); + } // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + + + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + } // Decode in chunks to avoid "call stack size exceeded". + + + var res = ''; + var i = 0; + + while (i < len) { + res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); + } + + return res; + } + + function asciiSlice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + + return ret; + } + + function latin1Slice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + + return ret; + } + + function hexSlice(buf, start, end) { + var len = buf.length; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + var out = ''; + + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + + return out; + } + + function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + + for (var i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + + return res; + } + + Buffer.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance + + Object.setPrototypeOf(newBuf, Buffer.prototype); + return newBuf; + }; + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + + + function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); + } + + Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val; + }; + + Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val; + }; + + Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; + }; + + Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }; + + Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }; + + Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; + }; + + Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }; + + Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + mul *= 0x80; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; + }; + + Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + + mul *= 0x80; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; + }; + + Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return this[offset]; + return (0xff - this[offset] + 1) * -1; + }; + + Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | this[offset + 1] << 8; + return val & 0x8000 ? val | 0xFFFF0000 : val; + }; + + Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | this[offset] << 8; + return val & 0x8000 ? val | 0xFFFF0000 : val; + }; + + Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }; + + Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }; + + Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4); + }; + + Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4); + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8); + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8); + }; + + function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) throw new RangeError('Index out of range'); + } + + Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = value / mul & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = value / mul & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + this[offset] = value & 0xff; + return offset + 1; + }; + + Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + + Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + return offset + 2; + }; + + Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 0xff; + return offset + 4; + }; + + Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + return offset + 4; + }; + + Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + + this[offset + i] = (value / mul >> 0) - sub & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + + this[offset + i] = (value / mul >> 0) - sub & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (value < 0) value = 0xff + value + 1; + this[offset] = value & 0xff; + return offset + 1; + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + return offset + 2; + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + return offset + 4; + }; + + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range'); + if (offset < 0) throw new RangeError('Index out of range'); + } + + function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + + Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; + + function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + + + Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer'); + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done + + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions + + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds'); + } + + if (start < 0 || start >= this.length) throw new RangeError('Index out of range'); + if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? + + if (end > this.length) end = this.length; + + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); + } + + return len; + }; // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + + + Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string'); + } + + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding); + } + + if (val.length === 1) { + var code = val.charCodeAt(0); + + if (encoding === 'utf8' && code < 128 || encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code; + } + } + } else if (typeof val === 'number') { + val = val & 255; + } else if (typeof val === 'boolean') { + val = Number(val); + } // Invalid ranges are not set to a default, so can range check early. + + + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index'); + } + + if (end <= start) { + return this; + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + if (!val) val = 0; + var i; + + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); + var len = bytes.length; + + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this; + }; // HELPER FUNCTIONS + // ================ + + + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + + function base64clean(str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not + + str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' + + if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + + while (str.length % 4 !== 0) { + str = str + '='; + } + + return str; + } + + function utf8ToBytes(string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); // is surrogate component + + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue; + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue; + } // valid lead + + + leadSurrogate = codePoint; + continue; + } // 2 leads in a row + + + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue; + } // valid surrogate pair + + + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; // encode utf8 + + if (codePoint < 0x80) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break; + bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break; + bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break; + bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); + } else { + throw new Error('Invalid code point'); + } + } + + return bytes; + } + + function asciiToBytes(str) { + var byteArray = []; + + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + + return byteArray; + } + + function utf16leToBytes(str, units) { + var c, hi, lo; + var byteArray = []; + + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray; + } + + function base64ToBytes(str) { + return base64Js.toByteArray(base64clean(str)); + } + + function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break; + dst[i + offset] = src[i]; + } + + return i; + } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass + // the `instanceof` check but they should be treated as of that type. + // See: https://github.com/feross/buffer/issues/166 + + + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; + } + + function numberIsNaN(obj) { + // For IE11 support + return obj !== obj; // eslint-disable-line no-self-compare + } // Create lookup table for `toString('hex')` + // See: https://github.com/feross/buffer/issues/219 + + + var hexSliceLookupTable = function () { + var alphabet = '0123456789abcdef'; + var table = new Array(256); + + for (var i = 0; i < 16; ++i) { + var i16 = i * 16; + + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + + return table; + }(); + }); + var buffer_1 = buffer$1.Buffer; + buffer$1.SlowBuffer; + buffer$1.INSPECT_MAX_BYTES; + buffer$1.kMaxLength; + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + + /* global Reflect, Promise */ + var _extendStatics = function extendStatics(d, b) { + _extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function (d, b) { + d.__proto__ = b; + } || function (d, b) { + for (var p in b) { + if (b.hasOwnProperty(p)) d[p] = b[p]; + } + }; + + return _extendStatics(d, b); + }; + + function __extends(d, b) { + _extendStatics(d, b); + + function __() { + this.constructor = d; + } + + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** @public */ + var BSONError = /** @class */ (function (_super) { + __extends(BSONError, _super); + function BSONError() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(BSONError.prototype, "name", { + get: function () { + return 'BSONError'; + }, + enumerable: false, + configurable: true + }); + return BSONError; + }(Error)); + /** @public */ + var BSONTypeError = /** @class */ (function (_super) { + __extends(BSONTypeError, _super); + function BSONTypeError() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(BSONTypeError.prototype, "name", { + get: function () { + return 'BSONTypeError'; + }, + enumerable: false, + configurable: true + }); + return BSONTypeError; + }(TypeError)); + + function checkForMath(potentialGlobal) { + // eslint-disable-next-line eqeqeq + return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; + } + // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 + function getGlobal() { + // eslint-disable-next-line no-undef + return (checkForMath(typeof globalThis === 'object' && globalThis) || + checkForMath(typeof window === 'object' && window) || + checkForMath(typeof self === 'object' && self) || + checkForMath(typeof global === 'object' && global) || + Function('return this')()); + } + + /** + * Normalizes our expected stringified form of a function across versions of node + * @param fn - The function to stringify + */ + function normalizedFunctionString(fn) { + return fn.toString().replace('function(', 'function ('); + } + function isReactNative() { + var g = getGlobal(); + return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; + } + var insecureRandomBytes = function insecureRandomBytes(size) { + var insecureWarning = isReactNative() + ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; + console.warn(insecureWarning); + var result = buffer_1.alloc(size); + for (var i = 0; i < size; ++i) + result[i] = Math.floor(Math.random() * 256); + return result; + }; + var detectRandomBytes = function () { + if (typeof window !== 'undefined') { + // browser crypto implementation(s) + var target_1 = window.crypto || window.msCrypto; // allow for IE11 + if (target_1 && target_1.getRandomValues) { + return function (size) { return target_1.getRandomValues(buffer_1.alloc(size)); }; + } + } + if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { + // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global + return function (size) { return global.crypto.getRandomValues(buffer_1.alloc(size)); }; + } + var requiredRandomBytes; + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + requiredRandomBytes = require('crypto').randomBytes; + } + catch (e) { + // keep the fallback + } + // NOTE: in transpiled cases the above require might return null/undefined + return requiredRandomBytes || insecureRandomBytes; + }; + var randomBytes = detectRandomBytes(); + function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); + } + function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; + } + function isBigInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigInt64Array]'; + } + function isBigUInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigUint64Array]'; + } + function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; + } + function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; + } + // To ensure that 0.4 of node works correctly + function isDate(d) { + return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; + } + /** + * @internal + * this is to solve the `'someKey' in x` problem where x is unknown. + * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 + */ + function isObjectLike(candidate) { + return typeof candidate === 'object' && candidate !== null; + } + function deprecate(fn, message) { + var warned = false; + function deprecated() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!warned) { + console.warn(message); + warned = true; + } + return fn.apply(this, args); + } + return deprecated; + } + + /** + * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. + * + * @param potentialBuffer - The potential buffer + * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that + * wraps a passed in Uint8Array + * @throws TypeError If anything other than a Buffer or Uint8Array is passed in + */ + function ensureBuffer(potentialBuffer) { + if (ArrayBuffer.isView(potentialBuffer)) { + return buffer_1.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + if (isAnyArrayBuffer(potentialBuffer)) { + return buffer_1.from(potentialBuffer); + } + throw new BSONTypeError('Must use either Buffer or TypedArray'); + } + + // Validation regex for v4 uuid (validates with or without dashes) + var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; + var uuidValidateString = function (str) { + return typeof str === 'string' && VALIDATION_REGEX.test(str); + }; + var uuidHexStringToBuffer = function (hexString) { + if (!uuidValidateString(hexString)) { + throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); + } + var sanitizedHexString = hexString.replace(/-/g, ''); + return buffer_1.from(sanitizedHexString, 'hex'); + }; + var bufferToUuidHexString = function (buffer, includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + return includeDashes + ? buffer.toString('hex', 0, 4) + + '-' + + buffer.toString('hex', 4, 6) + + '-' + + buffer.toString('hex', 6, 8) + + '-' + + buffer.toString('hex', 8, 10) + + '-' + + buffer.toString('hex', 10, 16) + : buffer.toString('hex'); + }; + + var BYTE_LENGTH = 16; + var kId$1 = Symbol('id'); + /** + * A class representation of the BSON UUID type. + * @public + */ + var UUID = /** @class */ (function () { + /** + * Create an UUID type + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + function UUID(input) { + if (typeof input === 'undefined') { + // The most common use case (blank id, new UUID() instance) + this.id = UUID.generate(); + } + else if (input instanceof UUID) { + this[kId$1] = buffer_1.from(input.id); + this.__id = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { + this.id = ensureBuffer(input); + } + else if (typeof input === 'string') { + this.id = uuidHexStringToBuffer(input); + } + else { + throw new BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); + } + } + Object.defineProperty(UUID.prototype, "id", { + /** + * The UUID bytes + * @readonly + */ + get: function () { + return this[kId$1]; + }, + set: function (value) { + this[kId$1] = value; + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + }, + enumerable: false, + configurable: true + }); + /** + * Generate a 16 byte uuid v4 buffer used in UUIDs + */ + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + * */ + UUID.prototype.toHexString = function (includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + var uuidHexString = bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + }; + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + UUID.prototype.toString = function (encoding) { + return encoding ? this.id.toString(encoding) : this.toHexString(); + }; + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + UUID.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + UUID.prototype.equals = function (otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return otherId.id.equals(this.id); + } + try { + return new UUID(otherId).id.equals(this.id); + } + catch (_a) { + return false; + } + }; + /** + * Creates a Binary instance from the current UUID. + */ + UUID.prototype.toBinary = function () { + return new Binary(this.id, Binary.SUBTYPE_UUID); + }; + /** + * Generates a populated buffer containing a v4 uuid + */ + UUID.generate = function () { + var bytes = randomBytes(BYTE_LENGTH); + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return buffer_1.from(bytes); + }; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + UUID.isValid = function (input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuidValidateString(input); + } + if (isUint8Array(input)) { + // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) + if (input.length !== BYTE_LENGTH) { + return false; + } + try { + // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx + // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx + return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID; + } + catch (_a) { + return false; + } + } + return false; + }; + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + UUID.createFromHexString = function (hexString) { + var buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 36 character hex string representation. + * @internal + */ + UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + UUID.prototype.inspect = function () { + return "new UUID(\"" + this.toHexString() + "\")"; + }; + return UUID; + }()); + Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); + + /** + * A class representation of the BSON Binary type. + * @public + */ + var Binary = /** @class */ (function () { + /** + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) + return new Binary(buffer, subType); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + // create an empty binary buffer + this.buffer = buffer_1.alloc(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + // string + this.buffer = buffer_1.from(buffer, 'binary'); + } + else if (Array.isArray(buffer)) { + // number[] + this.buffer = buffer_1.from(buffer); + } + else { + // Buffer | TypedArray | ArrayBuffer + this.buffer = ensureBuffer(buffer); + } + this.position = this.buffer.byteLength; + } + } + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + Binary.prototype.put = function (byteValue) { + // If it's a string and a has more than one character throw an error + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONTypeError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONTypeError('only accepts single character Uint8Array or Array'); + // Decode the byte value once + var decodedByte; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } + else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } + else { + decodedByte = byteValue[0]; + } + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + var buffer = buffer_1.alloc(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decodedByte; + } + }; + /** + * Writes a buffer or string to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + Binary.prototype.write = function (sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + sequence.length) { + var buffer = buffer_1.alloc(this.buffer.length + sequence.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + // Assign the new buffer + this.buffer = buffer; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ensureBuffer(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + this.buffer.write(sequence, offset, sequence.length, 'binary'); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + }; + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + Binary.prototype.read = function (position, length) { + length = length && length > 0 ? length : this.position; + // Let's return the data based on the type we have + return this.buffer.slice(position, position + length); + }; + /** + * Returns the value of this binary as a string. + * @param asRaw - Will skip converting to a string + * @remarks + * This is handy when calling this function conditionally for some key value pairs and not others + */ + Binary.prototype.value = function (asRaw) { + asRaw = !!asRaw; + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + // If it's a node.js buffer object + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return this.buffer.toString('binary', 0, this.position); + }; + /** the length of the binary sequence */ + Binary.prototype.length = function () { + return this.position; + }; + Binary.prototype.toJSON = function () { + return this.buffer.toString('base64'); + }; + Binary.prototype.toString = function (format) { + return this.buffer.toString(format); + }; + /** @internal */ + Binary.prototype.toExtendedJSON = function (options) { + options = options || {}; + var base64String = this.buffer.toString('base64'); + var subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + }; + Binary.prototype.toUUID = function () { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID(this.buffer.slice(0, this.position)); + } + throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); + }; + /** @internal */ + Binary.fromExtendedJSON = function (doc, options) { + options = options || {}; + var data; + var type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = buffer_1.from(doc.$binary, 'base64'); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = buffer_1.from(doc.$binary.base64, 'base64'); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); + } + return new Binary(data, type); + }; + /** @internal */ + Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Binary.prototype.inspect = function () { + var asBuffer = this.value(true); + return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; + }; + /** + * Binary default subtype + * @internal + */ + Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** Initial buffer default size */ + Binary.BUFFER_SIZE = 256; + /** Default BSON type */ + Binary.SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + Binary.SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + Binary.SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + Binary.SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + Binary.SUBTYPE_UUID = 4; + /** MD5 BSON type */ + Binary.SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + Binary.SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + Binary.SUBTYPE_COLUMN = 7; + /** User BSON type */ + Binary.SUBTYPE_USER_DEFINED = 128; + return Binary; + }()); + Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); + + /** + * A class representation of the BSON Code type. + * @public + */ + var Code = /** @class */ (function () { + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + function Code(code, scope) { + if (!(this instanceof Code)) + return new Code(code, scope); + this.code = code; + this.scope = scope; + } + Code.prototype.toJSON = function () { + return { code: this.code, scope: this.scope }; + }; + /** @internal */ + Code.prototype.toExtendedJSON = function () { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + }; + /** @internal */ + Code.fromExtendedJSON = function (doc) { + return new Code(doc.$code, doc.$scope); + }; + /** @internal */ + Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Code.prototype.inspect = function () { + var codeJson = this.toJSON(); + return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; + }; + return Code; + }()); + Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); + + /** @internal */ + function isDBRefLike(value) { + return (isObjectLike(value) && + value.$id != null && + typeof value.$ref === 'string' && + (value.$db == null || typeof value.$db === 'string')); + } + /** + * A class representation of the BSON DBRef type. + * @public + */ + var DBRef = /** @class */ (function () { + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + function DBRef(collection, oid, db, fields) { + if (!(this instanceof DBRef)) + return new DBRef(collection, oid, db, fields); + // check if namespace has been provided + var parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + Object.defineProperty(DBRef.prototype, "namespace", { + // Property provided for compatibility with the 1.x parser + // the 1.x parser used a "namespace" property, while 4.x uses "collection" + /** @internal */ + get: function () { + return this.collection; + }, + set: function (value) { + this.collection = value; + }, + enumerable: false, + configurable: true + }); + DBRef.prototype.toJSON = function () { + var o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + }; + /** @internal */ + DBRef.prototype.toExtendedJSON = function (options) { + options = options || {}; + var o = { + $ref: this.collection, + $id: this.oid + }; + if (options.legacy) { + return o; + } + if (this.db) + o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + }; + /** @internal */ + DBRef.fromExtendedJSON = function (doc) { + var copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + }; + /** @internal */ + DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + DBRef.prototype.inspect = function () { + // NOTE: if OID is an ObjectId class it will just print the oid string. + var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); + return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; + }; + return DBRef; + }()); + Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); + + /** + * wasm optimizations, to do native i64 multiplication and divide + */ + var wasm = undefined; + try { + wasm = new WebAssembly.Instance(new WebAssembly.Module( + // prettier-ignore + new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; + } + catch (_a) { + // no wasm support + } + var TWO_PWR_16_DBL = 1 << 16; + var TWO_PWR_24_DBL = 1 << 24; + var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; + var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; + var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + /** A cache of the Long representations of small integer values. */ + var INT_CACHE = {}; + /** A cache of the Long representations of small unsigned integer values. */ + var UINT_CACHE = {}; + /** + * A class representing a 64-bit integer + * @public + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ + var Long = /** @class */ (function () { + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + function Long(low, high, unsigned) { + if (low === void 0) { low = 0; } + if (!(this instanceof Long)) + return new Long(low, high, unsigned); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } + else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } + else { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + Object.defineProperty(this, '__isLong__', { + value: true, + configurable: false, + writable: false, + enumerable: false + }); + } + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBits = function (lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + }; + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromInt = function (value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } + else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromNumber = function (value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; + } + else { + if (value <= -TWO_PWR_63_DBL) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBigInt = function (value, unsigned) { + return Long.fromString(value.toString(), unsigned); + }; + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + Long.fromString = function (str, unsigned, radix) { + if (str.length === 0) + throw Error('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + var p; + if ((p = str.indexOf('-')) > 0) + throw Error('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } + else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + }; + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + Long.fromBytes = function (bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + }; + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesLE = function (bytes, unsigned) { + return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); + }; + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesBE = function (bytes, unsigned) { + return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); + }; + /** + * Tests if the specified object is a Long. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + Long.isLong = function (value) { + return isObjectLike(value) && value['__isLong__'] === true; + }; + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + Long.fromValue = function (val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + }; + /** Returns the sum of this and the specified Long. */ + Long.prototype.add = function (addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xffff; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + Long.prototype.and = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + }; + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + Long.prototype.compare = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + // At this point the sign bits are the same + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + }; + /** This is an alias of {@link Long.compare} */ + Long.prototype.comp = function (other) { + return this.compare(other); + }; + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + Long.prototype.divide = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw Error('division by zero'); + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + // be consistent with non-wasm code path + return this; + } + var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + var approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } + else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } + else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } + else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } + else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return Long.UONE; + res = Long.UZERO; + } + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + }; + /**This is an alias of {@link Long.divide} */ + Long.prototype.div = function (divisor) { + return this.divide(divisor); + }; + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + Long.prototype.equals = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + }; + /** This is an alias of {@link Long.equals} */ + Long.prototype.eq = function (other) { + return this.equals(other); + }; + /** Gets the high 32 bits as a signed integer. */ + Long.prototype.getHighBits = function () { + return this.high; + }; + /** Gets the high 32 bits as an unsigned integer. */ + Long.prototype.getHighBitsUnsigned = function () { + return this.high >>> 0; + }; + /** Gets the low 32 bits as a signed integer. */ + Long.prototype.getLowBits = function () { + return this.low; + }; + /** Gets the low 32 bits as an unsigned integer. */ + Long.prototype.getLowBitsUnsigned = function () { + return this.low >>> 0; + }; + /** Gets the number of bits needed to represent the absolute value of this Long. */ + Long.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + // Unsigned Longs are never negative + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + var val = this.high !== 0 ? this.high : this.low; + var bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + }; + /** Tests if this Long's value is greater than the specified's. */ + Long.prototype.greaterThan = function (other) { + return this.comp(other) > 0; + }; + /** This is an alias of {@link Long.greaterThan} */ + Long.prototype.gt = function (other) { + return this.greaterThan(other); + }; + /** Tests if this Long's value is greater than or equal the specified's. */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.comp(other) >= 0; + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.gte = function (other) { + return this.greaterThanOrEqual(other); + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.ge = function (other) { + return this.greaterThanOrEqual(other); + }; + /** Tests if this Long's value is even. */ + Long.prototype.isEven = function () { + return (this.low & 1) === 0; + }; + /** Tests if this Long's value is negative. */ + Long.prototype.isNegative = function () { + return !this.unsigned && this.high < 0; + }; + /** Tests if this Long's value is odd. */ + Long.prototype.isOdd = function () { + return (this.low & 1) === 1; + }; + /** Tests if this Long's value is positive. */ + Long.prototype.isPositive = function () { + return this.unsigned || this.high >= 0; + }; + /** Tests if this Long's value equals zero. */ + Long.prototype.isZero = function () { + return this.high === 0 && this.low === 0; + }; + /** Tests if this Long's value is less than the specified's. */ + Long.prototype.lessThan = function (other) { + return this.comp(other) < 0; + }; + /** This is an alias of {@link Long#lessThan}. */ + Long.prototype.lt = function (other) { + return this.lessThan(other); + }; + /** Tests if this Long's value is less than or equal the specified's. */ + Long.prototype.lessThanOrEqual = function (other) { + return this.comp(other) <= 0; + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.lte = function (other) { + return this.lessThanOrEqual(other); + }; + /** Returns this Long modulo the specified. */ + Long.prototype.modulo = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + // use wasm support if present + if (wasm) { + var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.mod = function (divisor) { + return this.modulo(divisor); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.rem = function (divisor) { + return this.modulo(divisor); + }; + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + Long.prototype.multiply = function (multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + // use wasm support if present + if (wasm) { + var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } + else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + // If both longs are small, use float multiplication + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xffff; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** This is an alias of {@link Long.multiply} */ + Long.prototype.mul = function (multiplier) { + return this.multiply(multiplier); + }; + /** Returns the Negation of this Long's value. */ + Long.prototype.negate = function () { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + }; + /** This is an alias of {@link Long.negate} */ + Long.prototype.neg = function () { + return this.negate(); + }; + /** Returns the bitwise NOT of this Long. */ + Long.prototype.not = function () { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + }; + /** Tests if this Long's value differs from the specified's. */ + Long.prototype.notEquals = function (other) { + return !this.equals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.neq = function (other) { + return this.notEquals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.ne = function (other) { + return this.notEquals(other); + }; + /** + * Returns the bitwise OR of this Long and the specified. + */ + Long.prototype.or = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + }; + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftLeft = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + }; + /** This is an alias of {@link Long.shiftLeft} */ + Long.prototype.shl = function (numBits) { + return this.shiftLeft(numBits); + }; + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRight = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + }; + /** This is an alias of {@link Long.shiftRight} */ + Long.prototype.shr = function (numBits) { + return this.shiftRight(numBits); + }; + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRightUnsigned = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + var high = this.high; + if (numBits < 32) { + var low = this.low; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); + } + else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shr_u = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shru = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + Long.prototype.subtract = function (subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + /** This is an alias of {@link Long.subtract} */ + Long.prototype.sub = function (subtrahend) { + return this.subtract(subtrahend); + }; + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + Long.prototype.toInt = function () { + return this.unsigned ? this.low >>> 0 : this.low; + }; + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + Long.prototype.toNumber = function () { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + /** Converts the Long to a BigInt (arbitrary precision). */ + Long.prototype.toBigInt = function () { + return BigInt(this.toString()); + }; + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + Long.prototype.toBytes = function (le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + Long.prototype.toBytesLE = function () { + var hi = this.high, lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + }; + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + Long.prototype.toBytesBE = function () { + var hi = this.high, lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + }; + /** + * Converts this Long to signed. + */ + Long.prototype.toSigned = function () { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + }; + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + Long.prototype.toString = function (radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + // Unsigned Longs are never negative + if (this.eq(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } + else + return '-' + this.neg().toString(radix); + } + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + // eslint-disable-next-line @typescript-eslint/no-this-alias + var rem = this; + var result = ''; + // eslint-disable-next-line no-constant-condition + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + var digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } + }; + /** Converts this Long to unsigned. */ + Long.prototype.toUnsigned = function () { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + }; + /** Returns the bitwise XOR of this Long and the given one. */ + Long.prototype.xor = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + }; + /** This is an alias of {@link Long.isZero} */ + Long.prototype.eqz = function () { + return this.isZero(); + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.le = function (other) { + return this.lessThanOrEqual(other); + }; + /* + **************************************************************** + * BSON SPECIFIC ADDITIONS * + **************************************************************** + */ + Long.prototype.toExtendedJSON = function (options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + }; + Long.fromExtendedJSON = function (doc, options) { + var result = Long.fromString(doc.$numberLong); + return options && options.relaxed ? result.toNumber() : result; + }; + /** @internal */ + Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Long.prototype.inspect = function () { + return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")"; + }; + Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); + /** Maximum unsigned value. */ + Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); + /** Signed zero */ + Long.ZERO = Long.fromInt(0); + /** Unsigned zero. */ + Long.UZERO = Long.fromInt(0, true); + /** Signed one. */ + Long.ONE = Long.fromInt(1); + /** Unsigned one. */ + Long.UONE = Long.fromInt(1, true); + /** Signed negative one. */ + Long.NEG_ONE = Long.fromInt(-1); + /** Maximum signed value. */ + Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + /** Minimum signed value. */ + Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + return Long; + }()); + Object.defineProperty(Long.prototype, '__isLong__', { value: true }); + Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); + + var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; + var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; + var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + var EXPONENT_MAX = 6111; + var EXPONENT_MIN = -6176; + var EXPONENT_BIAS = 6176; + var MAX_DIGITS = 34; + // Nan value bits as 32 bit values (due to lack of longs) + var NAN_BUFFER = [ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ].reverse(); + // Infinity value bits 32 bit values (due to lack of longs) + var INF_NEGATIVE_BUFFER = [ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ].reverse(); + var INF_POSITIVE_BUFFER = [ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ].reverse(); + var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + // Extract least significant 5 bits + var COMBINATION_MASK = 0x1f; + // Extract least significant 14 bits + var EXPONENT_MASK = 0x3fff; + // Value of combination field for Inf + var COMBINATION_INFINITY = 30; + // Value of combination field for NaN + var COMBINATION_NAN = 31; + // Detect if the value is a digit + function isDigit(value) { + return !isNaN(parseInt(value, 10)); + } + // Divide two uint128 values + function divideu128(value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + for (var i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + return { quotient: value, rem: _rem }; + } + // Multiply two Long values and return the 128 bit value + function multiply64x2(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + // Return the 128 bit result + return { high: productHigh, low: productLow }; + } + function lessThan(left, right) { + // Make values unsigned + var uhleft = left.high >>> 0; + var uhright = right.high >>> 0; + // Compare high bits first + if (uhleft < uhright) { + return true; + } + else if (uhleft === uhright) { + var ulleft = left.low >>> 0; + var ulright = right.low >>> 0; + if (ulleft < ulright) + return true; + } + return false; + } + function invalidErr(string, message) { + throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); + } + /** + * A class representation of the BSON Decimal128 type. + * @public + */ + var Decimal128 = /** @class */ (function () { + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + function Decimal128(bytes) { + if (!(this instanceof Decimal128)) + return new Decimal128(bytes); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else { + this.bytes = bytes; + } + } + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + Decimal128.fromString = function (representation) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = new Long(0, 0); + // The low 17 digits of the significand + var significandLow = new Long(0, 0); + // The biased exponent + var biasedExponent = 0; + // Read index + var index = 0; + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (representation.length >= 7000) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + // Results + var stringMatch = representation.match(PARSE_STRING_REGEXP); + var infMatch = representation.match(PARSE_INF_REGEXP); + var nanMatch = representation.match(PARSE_NAN_REGEXP); + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + // full_match = stringMatch[0] + // sign = stringMatch[1] + var unsignedNumber = stringMatch[2]; + // stringMatch[3] is undefined if a whole number (ex "1", 12") + // but defined if a number w/ decimal in it (ex "1.0, 12.2") + var e = stringMatch[4]; + var expSign = stringMatch[5]; + var expNumber = stringMatch[6]; + // they provided e, but didn't give an exponent number. for ex "1e" + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + // they provided e, but didn't give a number before it. for ex "e1" + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + // Get the negative or positive sign + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + // Check if user passed Infinity or NaN + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + else if (representation[index] === 'N') { + return new Decimal128(buffer_1.from(NAN_BUFFER)); + } + } + // Read all the digits + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) + invalidErr(representation, 'contains multiple periods'); + sawRadix = true; + index = index + 1; + continue; + } + if (nDigitsStored < 34) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + // Only store 34 digits + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + if (sawRadix && !nDigitsRead) + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + // Read exponent if exists + if (representation[index] === 'e' || representation[index] === 'E') { + // Read exponent digits + var match = representation.substr(++index).match(EXPONENT_REGEX); + // No digits read + if (!match || !match[2]) + return new Decimal128(buffer_1.from(NAN_BUFFER)); + // Get exponent + exponent = parseInt(match[0], 10); + // Adjust the index + index = index + match[0].length; + } + // Return not a number + if (representation[index]) + return new Decimal128(buffer_1.from(NAN_BUFFER)); + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } + else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (digits[firstNonZero + significantDigits - 1] === 0) { + significantDigits = significantDigits - 1; + } + } + } + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit. can only do this if < significant digits than # stored. + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } + else { + // adjust to round + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits) { + var endOfString = nDigitsRead; + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + // if negative, we need to increment again to account for - sign at start. + if (isNegative) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + if (roundBit) { + var dIdx = lastDigit; + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + } + } + } + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } + else if (lastDigit - firstDigit < 17) { + var dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + else { + var dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + significandLow = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + // Encode combination, exponent, and significand. + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } + else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + dec.low = significand.low; + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + // Encode into a buffer + var buffer = buffer_1.alloc(16); + index = 0; + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + // Return the new Decimal128 + return new Decimal128(buffer); + }; + /** Create a string representation of the raw Decimal128 value */ + Decimal128.prototype.toString = function () { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) + significand[i] = 0; + // read pointer into significand + var index = 0; + // true if the number is zero + var is_zero = false; + // the most significant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: [0, 0, 0, 0] }; + // indexing variables + var j, k; + // Output string + var string = []; + // Unpack index + index = 0; + // Buffer reference + var buffer = this.bytes; + // Unpack the low 64bits into a long + // bits 96 - 127 + var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 64 - 95 + var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack the high 64bits into a long + // bits 32 - 63 + var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 0 - 31 + var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack index + index = 0; + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + // Decode combination field and exponent + // bits 1 - 5 + var combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } + else if (combination === COMBINATION_NAN) { + return 'NaN'; + } + else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } + else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + // unbiased exponent + var exponent = biased_exponent - EXPONENT_BIAS; + // Create string of significand digits + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + if (significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0) { + is_zero = true; + } + else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Perform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + // the exponent if scientific notation is used + var scientific_exponent = significand_digits - 1 + exponent; + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + // if there are too many significant digits, we should just be treating numbers + // as + or - 0 and using the non-scientific exponent (this is for the "invalid + // representation should be treated as 0/-0" spec cases in decimal128-1.json) + if (significand_digits > 34) { + string.push("" + 0); + if (exponent > 0) + string.push('E+' + exponent); + else if (exponent < 0) + string.push('E' + exponent); + return string.join(''); + } + string.push("" + significand[index++]); + significand_digits = significand_digits - 1; + if (significand_digits) { + string.push('.'); + } + for (var i = 0; i < significand_digits; i++) { + string.push("" + significand[index++]); + } + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } + else { + string.push("" + scientific_exponent); + } + } + else { + // Regular format with no decimal place + if (exponent >= 0) { + for (var i = 0; i < significand_digits; i++) { + string.push("" + significand[index++]); + } + } + else { + var radix_position = significand_digits + exponent; + // non-zero digits before radix + if (radix_position > 0) { + for (var i = 0; i < radix_position; i++) { + string.push("" + significand[index++]); + } + } + else { + string.push('0'); + } + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push("" + significand[index++]); + } + } + } + return string.join(''); + }; + Decimal128.prototype.toJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.prototype.toExtendedJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.fromExtendedJSON = function (doc) { + return Decimal128.fromString(doc.$numberDecimal); + }; + /** @internal */ + Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Decimal128.prototype.inspect = function () { + return "new Decimal128(\"" + this.toString() + "\")"; + }; + return Decimal128; + }()); + Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); + + /** + * A class representation of the BSON Double type. + * @public + */ + var Double = /** @class */ (function () { + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + function Double(value) { + if (!(this instanceof Double)) + return new Double(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + Double.prototype.valueOf = function () { + return this.value; + }; + Double.prototype.toJSON = function () { + return this.value; + }; + Double.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + /** @internal */ + Double.prototype.toExtendedJSON = function (options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user + // explicitly provided `-0` then we need to ensure the sign makes it into the output + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: "-" + this.value.toFixed(1) }; + } + var $numberDouble; + if (Number.isInteger(this.value)) { + $numberDouble = this.value.toFixed(1); + if ($numberDouble.length >= 13) { + $numberDouble = this.value.toExponential(13).toUpperCase(); + } + } + else { + $numberDouble = this.value.toString(); + } + return { $numberDouble: $numberDouble }; + }; + /** @internal */ + Double.fromExtendedJSON = function (doc, options) { + var doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + }; + /** @internal */ + Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Double.prototype.inspect = function () { + var eJSON = this.toExtendedJSON(); + return "new Double(" + eJSON.$numberDouble + ")"; + }; + return Double; + }()); + Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); + + /** + * A class representation of a BSON Int32 type. + * @public + */ + var Int32 = /** @class */ (function () { + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + function Int32(value) { + if (!(this instanceof Int32)) + return new Int32(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { + return this.value; + }; + Int32.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + Int32.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + Int32.prototype.toExtendedJSON = function (options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + }; + /** @internal */ + Int32.fromExtendedJSON = function (doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + }; + /** @internal */ + Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Int32.prototype.inspect = function () { + return "new Int32(" + this.valueOf() + ")"; + }; + return Int32; + }()); + Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); + + /** + * A class representation of the BSON MaxKey type. + * @public + */ + var MaxKey = /** @class */ (function () { + function MaxKey() { + if (!(this instanceof MaxKey)) + return new MaxKey(); + } + /** @internal */ + MaxKey.prototype.toExtendedJSON = function () { + return { $maxKey: 1 }; + }; + /** @internal */ + MaxKey.fromExtendedJSON = function () { + return new MaxKey(); + }; + /** @internal */ + MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MaxKey.prototype.inspect = function () { + return 'new MaxKey()'; + }; + return MaxKey; + }()); + Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); + + /** + * A class representation of the BSON MinKey type. + * @public + */ + var MinKey = /** @class */ (function () { + function MinKey() { + if (!(this instanceof MinKey)) + return new MinKey(); + } + /** @internal */ + MinKey.prototype.toExtendedJSON = function () { + return { $minKey: 1 }; + }; + /** @internal */ + MinKey.fromExtendedJSON = function () { + return new MinKey(); + }; + /** @internal */ + MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MinKey.prototype.inspect = function () { + return 'new MinKey()'; + }; + return MinKey; + }()); + Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); + + // Regular expression that checks for hex value + var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + // Unique sequence for the current process (initialized on first use) + var PROCESS_UNIQUE = null; + var kId = Symbol('id'); + /** + * A class representation of the BSON ObjectId type. + * @public + */ + var ObjectId = /** @class */ (function () { + /** + * Create an ObjectId type + * + * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number. + */ + function ObjectId(id) { + if (!(this instanceof ObjectId)) + return new ObjectId(id); + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectId) { + this[kId] = id.id; + this.__id = id.__id; + } + if (typeof id === 'object' && id && 'id' in id) { + if ('toHexString' in id && typeof id.toHexString === 'function') { + this[kId] = buffer_1.from(id.toHexString(), 'hex'); + } + else { + this[kId] = typeof id.id === 'string' ? buffer_1.from(id.id) : id.id; + } + } + // The most common use case (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined); + // If we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + if (ArrayBuffer.isView(id) && id.byteLength === 12) { + this[kId] = ensureBuffer(id); + } + if (typeof id === 'string') { + if (id.length === 12) { + var bytes = buffer_1.from(id); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + } + else if (id.length === 24 && checkForHexRegExp.test(id)) { + this[kId] = buffer_1.from(id, 'hex'); + } + else { + throw new BSONTypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters'); + } + } + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + Object.defineProperty(ObjectId.prototype, "id", { + /** + * The ObjectId bytes + * @readonly + */ + get: function () { + return this[kId]; + }, + set: function (value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = value.toString('hex'); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ObjectId.prototype, "generationTime", { + /** + * The generation time of this ObjectId instance + * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch + */ + get: function () { + return this.id.readInt32BE(0); + }, + set: function (value) { + // Encode time into first 4 bytes + this.id.writeUInt32BE(value, 0); + }, + enumerable: false, + configurable: true + }); + /** Returns the ObjectId id as a 24 character hex string representation */ + ObjectId.prototype.toHexString = function () { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + var hexString = this.id.toString('hex'); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + }; + /** + * Update the ObjectId index + * @privateRemarks + * Used in generating new ObjectId's on the driver + * @internal + */ + ObjectId.getInc = function () { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + }; + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + ObjectId.generate = function (time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + var inc = ObjectId.getInc(); + var buffer = buffer_1.alloc(12); + // 4-byte timestamp + buffer.writeUInt32BE(time, 0); + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = randomBytes(5); + } + // 5-byte process unique + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + // 3-byte counter + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + }; + /** + * Converts the id into a 24 character hex string for printing + * + * @param format - The Buffer toString format parameter. + */ + ObjectId.prototype.toString = function (format) { + // Is the id a buffer then use the buffer toString method to return the format + if (format) + return this.id.toString(format); + return this.toHexString(); + }; + /** Converts to its JSON the 24 character hex string representation. */ + ObjectId.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + ObjectId.prototype.equals = function (otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this.toString() === otherId.toString(); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id)) { + return otherId === buffer_1.prototype.toString.call(this.id, 'latin1'); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { + return buffer_1.from(otherId).equals(this.id); + } + if (typeof otherId === 'object' && + 'toHexString' in otherId && + typeof otherId.toHexString === 'function') { + return otherId.toHexString() === this.toHexString(); + } + return false; + }; + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + ObjectId.prototype.getTimestamp = function () { + var timestamp = new Date(); + var time = this.id.readUInt32BE(0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + }; + /** @internal */ + ObjectId.createPk = function () { + return new ObjectId(); + }; + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + ObjectId.createFromTime = function (time) { + var buffer = buffer_1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer.writeUInt32BE(time, 0); + // Return the new objectId + return new ObjectId(buffer); + }; + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + ObjectId.createFromHexString = function (hexString) { + // Throw an error if it's not a valid setup + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(buffer_1.from(hexString, 'hex')); + }; + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + ObjectId.isValid = function (id) { + if (id == null) + return false; + if (typeof id === 'number') { + return true; + } + if (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); + } + if (id instanceof ObjectId) { + return true; + } + if (isUint8Array(id) && id.length === 12) { + return true; + } + // Duck-Typing detection of ObjectId like objects + if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { + if (typeof id.id === 'string') { + return id.id.length === 12; + } + return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); + } + return false; + }; + /** @internal */ + ObjectId.prototype.toExtendedJSON = function () { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + }; + /** @internal */ + ObjectId.fromExtendedJSON = function (doc) { + return new ObjectId(doc.$oid); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 24 character hex string representation. + * @internal + */ + ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + ObjectId.prototype.inspect = function () { + return "new ObjectId(\"" + this.toHexString() + "\")"; + }; + /** @internal */ + ObjectId.index = ~~(Math.random() * 0xffffff); + return ObjectId; + }()); + // Deprecated methods + Object.defineProperty(ObjectId.prototype, 'generate', { + value: deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') + }); + Object.defineProperty(ObjectId.prototype, 'getInc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') + }); + Object.defineProperty(ObjectId.prototype, 'get_inc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') + }); + Object.defineProperty(ObjectId, 'get_inc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') + }); + Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); + + function alphabetize(str) { + return str.split('').sort().join(''); + } + /** + * A class representation of the BSON RegExp type. + * @public + */ + var BSONRegExp = /** @class */ (function () { + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) + return new BSONRegExp(pattern, options); + this.pattern = pattern; + this.options = alphabetize(options !== null && options !== void 0 ? options : ''); + if (this.pattern.indexOf('\x00') !== -1) { + throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); + } + if (this.options.indexOf('\x00') !== -1) { + throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); + } + // Validate options + for (var i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u')) { + throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported"); + } + } + } + BSONRegExp.parseOptions = function (options) { + return options ? options.split('').sort().join('') : ''; + }; + /** @internal */ + BSONRegExp.prototype.toExtendedJSON = function (options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + }; + /** @internal */ + BSONRegExp.fromExtendedJSON = function (doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + // This is for $regex query operators that have extended json values. + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc; + } + } + else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); + } + throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); + }; + return BSONRegExp; + }()); + Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); + + /** + * A class representation of the BSON Symbol type. + * @public + */ + var BSONSymbol = /** @class */ (function () { + /** + * @param value - the string representing the symbol. + */ + function BSONSymbol(value) { + if (!(this instanceof BSONSymbol)) + return new BSONSymbol(value); + this.value = value; + } + /** Access the wrapped string value. */ + BSONSymbol.prototype.valueOf = function () { + return this.value; + }; + BSONSymbol.prototype.toString = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.inspect = function () { + return "new BSONSymbol(\"" + this.value + "\")"; + }; + BSONSymbol.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.toExtendedJSON = function () { + return { $symbol: this.value }; + }; + /** @internal */ + BSONSymbol.fromExtendedJSON = function (doc) { + return new BSONSymbol(doc.$symbol); + }; + /** @internal */ + BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + return BSONSymbol; + }()); + Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); + + /** @public */ + var LongWithoutOverridesClass = Long; + /** @public */ + var Timestamp = /** @class */ (function (_super) { + __extends(Timestamp, _super); + function Timestamp(low, high) { + var _this = this; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + ///@ts-expect-error + if (!(_this instanceof Timestamp)) + return new Timestamp(low, high); + if (Long.isLong(low)) { + _this = _super.call(this, low.low, low.high, true) || this; + } + else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { + _this = _super.call(this, low.i, low.t, true) || this; + } + else { + _this = _super.call(this, low, high, true) || this; + } + Object.defineProperty(_this, '_bsontype', { + value: 'Timestamp', + writable: false, + configurable: false, + enumerable: false + }); + return _this; + } + Timestamp.prototype.toJSON = function () { + return { + $timestamp: this.toString() + }; + }; + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + Timestamp.fromInt = function (value) { + return new Timestamp(Long.fromInt(value, true)); + }; + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + Timestamp.fromNumber = function (value) { + return new Timestamp(Long.fromNumber(value, true)); + }; + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + Timestamp.fromString = function (str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + }; + /** @internal */ + Timestamp.prototype.toExtendedJSON = function () { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + }; + /** @internal */ + Timestamp.fromExtendedJSON = function (doc) { + return new Timestamp(doc.$timestamp); + }; + /** @internal */ + Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Timestamp.prototype.inspect = function () { + return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })"; + }; + Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + return Timestamp; + }(LongWithoutOverridesClass)); + + function isBSONType(value) { + return (isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); + } + // INT32 boundaries + var BSON_INT32_MAX$1 = 0x7fffffff; + var BSON_INT32_MIN$1 = -0x80000000; + // INT64 boundaries + var BSON_INT64_MAX$1 = 0x7fffffffffffffff; + var BSON_INT64_MIN$1 = -0x8000000000000000; + // all the types where we don't need to do any special processing and can just pass the EJSON + //straight to type.fromExtendedJSON + var keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function deserializeValue(value, options) { + if (options === void 0) { options = {}; } + if (typeof value === 'number') { + if (options.relaxed || options.legacy) { + return value; + } + // if it's an integer, should interpret as smallest BSON integer + // that can represent it exactly. (if out of range, interpret as double.) + if (Math.floor(value) === value) { + if (value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1) + return new Int32(value); + if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1) + return Long.fromNumber(value); + } + // If the number is a non-integer or out of integer range, should interpret as BSON Double. + return new Double(value); + } + // from here on out we're looking for bson types, so bail if its not an object + if (value == null || typeof value !== 'object') + return value; + // upgrade deprecated undefined to null + if (value.$undefined) + return null; + var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); + for (var i = 0; i < keys.length; i++) { + var c = keysToCodecs[keys[i]]; + if (c) + return c.fromExtendedJSON(value, options); + } + if (value.$date != null) { + var d = value.$date; + var date = new Date(); + if (options.legacy) { + if (typeof d === 'number') + date.setTime(d); + else if (typeof d === 'string') + date.setTime(Date.parse(d)); + } + else { + if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (Long.isLong(d)) + date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) + date.setTime(d); + } + return date; + } + if (value.$code != null) { + var copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return Code.fromExtendedJSON(value); + } + if (isDBRefLike(value) || value.$dbPointer) { + var v = value.$ref ? value : value.$dbPointer; + // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) + // because of the order JSON.parse goes through the document + if (v instanceof DBRef) + return v; + var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); + var valid_1 = true; + dollarKeys.forEach(function (k) { + if (['$ref', '$id', '$db'].indexOf(k) === -1) + valid_1 = false; + }); + // only make DBRef if $ keys are all valid + if (valid_1) + return DBRef.fromExtendedJSON(v); + } + return value; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function serializeArray(array, options) { + return array.map(function (v, index) { + options.seenObjects.push({ propertyName: "index " + index, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); + } + function getISOString(date) { + var isoStr = date.toISOString(); + // we should only show milliseconds in timestamp if they're non-zero + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function serializeValue(value, options) { + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); + if (index !== -1) { + var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); + var leadingPart = props + .slice(0, index) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var alreadySeen = props[index]; + var circularPart = ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var current = props[props.length - 1]; + var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new BSONTypeError('Converting circular structure to EJSON:\n' + + (" " + leadingPart + alreadySeen + circularPart + current + "\n") + + (" " + leadingSpace + "\\" + dashes + "/")); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || isDate(value)) { + var dateNum = value.getTime(), + // is it in year range 1970-9999? + inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + // it's an integer + if (Math.floor(value) === value) { + var int32Range = value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1; + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (int32Range) + return { $numberInt: value.toString() }; + if (int64Range) + return { $numberLong: value.toString() }; + } + return { $numberDouble: value.toString() }; + } + if (value instanceof RegExp || isRegExp(value)) { + var flags = value.flags; + if (flags === undefined) { + var match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + var rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === 'object') + return serializeDocument(value, options); + return value; + } + var BSON_TYPE_MAPPINGS = { + Binary: function (o) { return new Binary(o.value(), o.sub_type); }, + Code: function (o) { return new Code(o.code, o.scope); }, + DBRef: function (o) { return new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, + Decimal128: function (o) { return new Decimal128(o.bytes); }, + Double: function (o) { return new Double(o.value); }, + Int32: function (o) { return new Int32(o.value); }, + Long: function (o) { + return Long.fromBits( + // underscore variants for 1.x backwards compatibility + o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); + }, + MaxKey: function () { return new MaxKey(); }, + MinKey: function () { return new MinKey(); }, + ObjectID: function (o) { return new ObjectId(o); }, + ObjectId: function (o) { return new ObjectId(o); }, + BSONRegExp: function (o) { return new BSONRegExp(o.pattern, o.options); }, + Symbol: function (o) { return new BSONSymbol(o.value); }, + Timestamp: function (o) { return Timestamp.fromBits(o.low, o.high); } + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + var bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + // It's a regular object. Recursively serialize its property values. + var _doc = {}; + for (var name in doc) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + _doc[name] = serializeValue(doc[name], options); + } + finally { + options.seenObjects.pop(); + } + } + return _doc; + } + else if (isBSONType(doc)) { + // the "document" is really just a BSON type object + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + // There's no EJSON serialization function on the object. It's probably an + // object created by a previous version of this library (or another library) + // that's duck-typing objects to look like they were generated by this library). + // Copy the object into this library's version of that type. + var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + // Two BSON types may have nested objects that may need to be serialized too + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } + else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + } + return outDoc.toExtendedJSON(options); + } + else { + throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } + } + /** + * EJSON parse / stringify API + * @public + */ + // the namespace here is used to emulate `export * as EJSON from '...'` + // which as of now (sept 2020) api-extractor does not support + // eslint-disable-next-line @typescript-eslint/no-namespace + exports.EJSON = void 0; + (function (EJSON) { + /** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ + function parse(text, options) { + var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); + // relaxed implies not strict + if (typeof finalOptions.relaxed === 'boolean') + finalOptions.strict = !finalOptions.relaxed; + if (typeof finalOptions.strict === 'boolean') + finalOptions.relaxed = !finalOptions.strict; + return JSON.parse(text, function (key, value) { + if (key.indexOf('\x00') !== -1) { + throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key)); + } + return deserializeValue(value, finalOptions); + }); + } + EJSON.parse = parse; + /** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ + function stringify(value, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer, space, options) { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + var doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); + } + EJSON.stringify = stringify; + /** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ + function serialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); + } + EJSON.serialize = serialize; + /** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ + function deserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); + } + EJSON.deserialize = deserialize; + })(exports.EJSON || (exports.EJSON = {})); + + /* eslint-disable @typescript-eslint/no-explicit-any */ + /** @public */ + exports.Map = void 0; + var bsonGlobal = getGlobal(); + if (bsonGlobal.Map) { + exports.Map = bsonGlobal.Map; + } + else { + // We will return a polyfill + exports.Map = /** @class */ (function () { + function Map(array) { + if (array === void 0) { array = []; } + this._keys = []; + this._values = {}; + for (var i = 0; i < array.length; i++) { + if (array[i] == null) + continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + } + Map.prototype.clear = function () { + this._keys = []; + this._values = {}; + }; + Map.prototype.delete = function (key) { + var value = this._values[key]; + if (value == null) + return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + Map.prototype.entries = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? [key, _this._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.forEach = function (callback, self) { + self = self || this; + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + Map.prototype.get = function (key) { + return this._values[key] ? this._values[key].v : undefined; + }; + Map.prototype.has = function (key) { + return this._values[key] != null; + }; + Map.prototype.keys = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.set = function (key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + Map.prototype.values = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? _this._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Object.defineProperty(Map.prototype, "size", { + get: function () { + return this._keys.length; + }, + enumerable: false, + configurable: true + }); + return Map; + }()); + } + + /** @internal */ + var BSON_INT32_MAX = 0x7fffffff; + /** @internal */ + var BSON_INT32_MIN = -0x80000000; + /** @internal */ + var BSON_INT64_MAX = Math.pow(2, 63) - 1; + /** @internal */ + var BSON_INT64_MIN = -Math.pow(2, 63); + /** + * Any integer up to 2^53 can be precisely represented by a double. + * @internal + */ + var JS_INT_MAX = Math.pow(2, 53); + /** + * Any integer down to -2^53 can be precisely represented by a double. + * @internal + */ + var JS_INT_MIN = -Math.pow(2, 53); + /** Number BSON Type @internal */ + var BSON_DATA_NUMBER = 1; + /** String BSON Type @internal */ + var BSON_DATA_STRING = 2; + /** Object BSON Type @internal */ + var BSON_DATA_OBJECT = 3; + /** Array BSON Type @internal */ + var BSON_DATA_ARRAY = 4; + /** Binary BSON Type @internal */ + var BSON_DATA_BINARY = 5; + /** Binary BSON Type @internal */ + var BSON_DATA_UNDEFINED = 6; + /** ObjectId BSON Type @internal */ + var BSON_DATA_OID = 7; + /** Boolean BSON Type @internal */ + var BSON_DATA_BOOLEAN = 8; + /** Date BSON Type @internal */ + var BSON_DATA_DATE = 9; + /** null BSON Type @internal */ + var BSON_DATA_NULL = 10; + /** RegExp BSON Type @internal */ + var BSON_DATA_REGEXP = 11; + /** Code BSON Type @internal */ + var BSON_DATA_DBPOINTER = 12; + /** Code BSON Type @internal */ + var BSON_DATA_CODE = 13; + /** Symbol BSON Type @internal */ + var BSON_DATA_SYMBOL = 14; + /** Code with Scope BSON Type @internal */ + var BSON_DATA_CODE_W_SCOPE = 15; + /** 32 bit Integer BSON Type @internal */ + var BSON_DATA_INT = 16; + /** Timestamp BSON Type @internal */ + var BSON_DATA_TIMESTAMP = 17; + /** Long BSON Type @internal */ + var BSON_DATA_LONG = 18; + /** Decimal128 BSON Type @internal */ + var BSON_DATA_DECIMAL128 = 19; + /** MinKey BSON Type @internal */ + var BSON_DATA_MIN_KEY = 0xff; + /** MaxKey BSON Type @internal */ + var BSON_DATA_MAX_KEY = 0x7f; + /** Binary Default Type @internal */ + var BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** Binary Function Type @internal */ + var BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** Binary Byte Array Type @internal */ + var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ + var BSON_BINARY_SUBTYPE_UUID = 3; + /** Binary UUID Type @internal */ + var BSON_BINARY_SUBTYPE_UUID_NEW = 4; + /** Binary MD5 Type @internal */ + var BSON_BINARY_SUBTYPE_MD5 = 5; + /** Encrypted BSON type @internal */ + var BSON_BINARY_SUBTYPE_ENCRYPTED = 6; + /** Column BSON type @internal */ + var BSON_BINARY_SUBTYPE_COLUMN = 7; + /** Binary User Defined Type @internal */ + var BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) { + var totalLength = 4 + 1; + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } + else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; + } + /** @internal */ + function calculateElement(name, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + value, serializeFunctions, isArray, ignoreUndefined) { + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (isArray === void 0) { isArray = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = false; } + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + buffer_1.byteLength(name, 'utf8') + 1 + 4 + buffer_1.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + // 32 bit + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } + else { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } + else { + // 64 bit + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (value['_bsontype'] === 'Decimal128') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } + else if (value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.byteLength(value.code.toString(), 'utf8') + + 1); + } + } + else if (value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)); + } + } + else if (value['_bsontype'] === 'Symbol') { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + buffer_1.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1); + } + else if (value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + // Add db reference if it exists + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value['_bsontype'] === 'BSONRegExp') { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.byteLength(value.pattern, 'utf8') + + 1 + + buffer_1.byteLength(value.options, 'utf8') + + 1); + } + else { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); + } + else if (serializeFunctions) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + + 1); + } + } + } + return 0; + } + + var FIRST_BIT = 0x80; + var FIRST_TWO_BITS = 0xc0; + var FIRST_THREE_BITS = 0xe0; + var FIRST_FOUR_BITS = 0xf0; + var FIRST_FIVE_BITS = 0xf8; + var TWO_BIT_CHAR = 0xc0; + var THREE_BIT_CHAR = 0xe0; + var FOUR_BIT_CHAR = 0xf0; + var CONTINUING_CHAR = 0x80; + /** + * Determines if the passed in bytes are valid utf8 + * @param bytes - An array of 8-bit bytes. Must be indexable and have length property + * @param start - The index to start validating + * @param end - The index to end validating + */ + function validateUtf8(bytes, start, end) { + var continuation = 0; + for (var i = start; i < end; i += 1) { + var byte = bytes[i]; + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } + else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } + else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } + else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } + else { + return false; + } + } + } + return !continuation; + } + + // Internal long versions + var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); + var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); + var functionCache = {}; + function deserialize$1(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (size < 5) { + throw new BSONError("bson size must be >= 5, is " + size); + } + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size); + } + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new BSONError("buffer length " + buffer.length + " must === bson size " + size); + } + if (size + index > buffer.byteLength) { + throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); + } + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); + } + var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; + function deserializeObject(buffer, index, options, isArray) { + if (isArray === void 0) { isArray = false; } + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + // Set the start index + var startIndex = index; + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + // Read the document size + var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + var done = false; + var isPossibleDBRef = isArray ? false : null; + // While we have more left data left keep parsing + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) + break; + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + var value = void 0; + index = i + 1; + if (elementType === BSON_DATA_STRING) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + value = getValidatedString(buffer, index, index + stringSize - 1); + index = index + stringSize; + } + else if (elementType === BSON_DATA_OID) { + var oid = buffer_1.alloc(12); + buffer.copy(oid, 0, index, index + 12); + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } + else if (elementType === BSON_DATA_NUMBER) { + value = buffer.readDoubleLE(index); + index = index + 8; + } + else if (elementType === BSON_DATA_DATE) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Date(new Long(lowBits, highBits).toNumber()); + } + else if (elementType === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new BSONError('bad embedded document length in bson'); + // We have a raw value + if (raw) { + value = buffer.slice(index, index + objectSize); + } + else { + value = deserializeObject(buffer, _index, options, false); + } + index = index + objectSize; + } + else if (elementType === BSON_DATA_ARRAY) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + var arrayOptions = options; + // Stop index + var stopIndex = index + objectSize; + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) { + arrayOptions[n] = options[n]; + } + arrayOptions['raw'] = true; + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + if (buffer[index - 1] !== 0) + throw new BSONError('invalid array terminator byte'); + if (index !== stopIndex) + throw new BSONError('corrupted array bson'); + } + else if (elementType === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + // Unpack the low and high bits + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } + else { + value = long; + } + } + else if (elementType === BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = buffer_1.alloc(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { + value = decimal128.toObject(); + } + else { + value = decimal128; + } + } + else if (elementType === BSON_DATA_BINARY) { + var binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var totalBinarySize = binarySize; + var subType = buffer[index++]; + // Did we have a negative binary size, throw + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + // Is the length longer than the document + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = buffer.slice(index, index + binarySize); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } + else { + var _buffer = buffer_1.alloc(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else { + value = new Binary(_buffer, subType); + } + } + // Update the index + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + value = new RegExp(source, optionsArray.join('')); + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // Set the object + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === BSON_DATA_SYMBOL) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + var symbol = getValidatedString(buffer, index, index + stringSize - 1); + value = promoteValues ? symbol : new BSONSymbol(symbol); + index = index + stringSize; + } + else if (elementType === BSON_DATA_TIMESTAMP) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Timestamp(lowBits, highBits); + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === BSON_DATA_CODE) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + var functionString = getValidatedString(buffer, index, index + stringSize - 1); + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + } + else { + value = new Code(functionString); + } + // Update parse index position + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + // Javascript function + var functionString = getValidatedString(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + var _index = index; + // Decode the size of the object document + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + // Check if field length is too short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + // Check if totalSize field is too long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + value.scope = scopeObject; + } + else { + value = new Code(functionString, scopeObject); + } + } + else if (elementType === BSON_DATA_DBPOINTER) { + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) + throw new BSONError('bad string length in bson'); + // Namespace + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Read the oid + var oidBuffer = buffer_1.alloc(12); + buffer.copy(oidBuffer, 0, index, index + 12); + var oid = new ObjectId(oidBuffer); + // Update the index + index = index + 12; + // Upgrade to DBRef type + value = new DBRef(namespace, oid); + } + else { + throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value: value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + object[name] = value; + } + } + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + var copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; + } + /** + * Ensure eval is isolated, store the result in functionCache. + * + * @internal + */ + function isolateEval(functionString, functionCache, object) { + if (!functionCache) + return new Function(functionString); + // Check for cache hit, eval if missing and return cached function + if (functionCache[functionString] == null) { + functionCache[functionString] = new Function(functionString); + } + // Set the object + return functionCache[functionString].bind(object); + } + function getValidatedString(buffer, start, end) { + var value = buffer.toString('utf8', start, end); + for (var i = 0; i < value.length; i++) { + if (value.charCodeAt(i) === 0xfffd) { + if (!validateUtf8(buffer, start, end)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + return value; + } + + // Copyright (c) 2008, Fair Oaks Labs, Inc. + function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) { + var e; + var m; + var c; + var bBE = endian === 'big'; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = bBE ? nBytes - 1 : 0; + var d = bBE ? -1 : 1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } + else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } + else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } + else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } + else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + if (isNaN(value)) + m = 0; + while (mLen >= 8) { + buffer[offset + i] = m & 0xff; + i += d; + m /= 256; + mLen -= 8; + } + e = (e << mLen) | m; + if (isNaN(value)) + e += 8; + eLen += mLen; + while (eLen > 0) { + buffer[offset + i] = e & 0xff; + i += d; + e /= 256; + eLen -= 8; + } + buffer[offset + i - d] |= s * 128; + } + + var regexp = /\x00/; // eslint-disable-line no-control-regex + var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); + /* + * isArray indicates if we are writing to a BSON array (type 0x04) + * which forces the "key" which really an array index as a string to be written as ascii + * This will catch any errors in index as a string generation + */ + function serializeString(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, undefined, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; + } + function serializeNumber(buffer, key, value, index, isArray) { + // We have an integer value + // TODO(NODE-2529): Add support for big int + if (Number.isInteger(value) && + value >= BSON_INT32_MIN && + value <= BSON_INT32_MAX) { + // If the value fits in 32 bits encode as int32 + // Set int type 32 bits or less + buffer[index++] = BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } + else { + // Encode as double + buffer[index++] = BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + } + return index; + } + function serializeNull(buffer, key, _, index, isArray) { + // Set long type + buffer[index++] = BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + } + function serializeBoolean(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + } + function serializeDate(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } + function serializeRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.ignoreCase) + buffer[index++] = 0x69; // i + if (value.global) + buffer[index++] = 0x73; // s + if (value.multiline) + buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } + function serializeBSONRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.pattern, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; + } + function serializeMinMax(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + } + function serializeObjectId(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, undefined, 'binary'); + } + else if (isUint8Array(value.id)) { + // Use the standard JS methods here because buffer.copy() is buggy with the + // browser polyfill + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + // Adjust index + return index + 12; + } + function serializeBuffer(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + buffer.set(ensureBuffer(value), index); + // Adjust the index + index = index + size; + return index; + } + function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (path === void 0) { path = []; } + for (var i = 0; i < path.length; i++) { + if (path[i] === value) + throw new BSONError('cyclic dependency detected'); + } + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + return endIndex; + } + function serializeDecimal128(buffer, key, value, index, isArray) { + buffer[index++] = BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + // Prefer the standard JS methods because their typechecking is not buggy, + // unlike the `buffer` polyfill's. + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; + } + function serializeLong(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } + function serializeInt32(buffer, key, value, index, isArray) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; + } + function serializeDouble(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value.value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + return index; + } + function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { + buffer[index++] = BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Starting index + var startIndex = index; + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + index = endIndex - 1; + // Writ the total + var totalSize = endIndex - startIndex; + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + return index; + } + function serializeBinary(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) + size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + // Write the data to the object + buffer.set(data, index); + // Adjust the index + index = index + value.position; + return index; + } + function serializeSymbol(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + } + function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var startIndex = index; + var output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; + } + function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (startingIndex === void 0) { startingIndex = 0; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (path === void 0) { path = []; } + startingIndex = startingIndex || 0; + path = path || []; + // Push the object to the path + path.push(object); + // Start place to serialize into + var index = startingIndex + 4; + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index, true); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } + else if (typeof value === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } + else if (typeof value === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } + else if (typeof value === 'object' && + isBSONType(value) && + value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + else if (object instanceof exports.Map || isMap(object)) { + var iterator = object.entries(); + var done = false; + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = !!entry.done; + // Are we done, then skip and terminate + if (done) + continue; + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new BSONTypeError('toBSON function did not return an object'); + } + // Iterate over all the keys + for (var key in object) { + var value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + // Remove the path + path.pop(); + // Final padding byte for object + buffer[index++] = 0x00; + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; + } + + /** @internal */ + // Default Max Size + var MAXSIZE = 1024 * 1024 * 17; + // Current Internal Temporary Serialization Buffer + var buffer = buffer_1.alloc(MAXSIZE); + /** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer + * @public + */ + function setInternalBufferSize(size) { + // Resize the internal serialization buffer if needed + if (buffer.length < size) { + buffer = buffer_1.alloc(size); + } + } + /** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ + function serialize(object, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = buffer_1.alloc(minInternalBufferSize); + } + // Attempt to serialize + var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = buffer_1.alloc(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; + } + /** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ + function serializeWithBufferAndIndex(object, finalBuffer, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + // Attempt to serialize + var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + // Return the index + return startIndex + serializationIndex - 1; + } + /** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ + function deserialize(buffer, options) { + if (options === void 0) { options = {}; } + return deserialize$1(buffer instanceof buffer_1 ? buffer : ensureBuffer(buffer), options); + } + /** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ + function calculateObjectSize(object, options) { + if (options === void 0) { options = {}; } + options = options || {}; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + return calculateObjectSize$1(object, serializeFunctions, ignoreUndefined); + } + /** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ + function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + var bufferData = ensureBuffer(data); + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + // Update options with index + internalOptions.index = index; + // Parse the document at this point + documents[docStartIndex + i] = deserialize$1(bufferData, internalOptions); + // Adjust index by the document size + index = index + size; + } + // Return object containing end index of parsing and list of documents + return index; + } + /** + * BSON default export + * @deprecated Please use named exports + * @privateRemarks + * We want to someday deprecate the default export, + * so none of the new TS types are being exported on the default + * @public + */ + var BSON = { + Binary: Binary, + Code: Code, + DBRef: DBRef, + Decimal128: Decimal128, + Double: Double, + Int32: Int32, + Long: Long, + UUID: UUID, + Map: exports.Map, + MaxKey: MaxKey, + MinKey: MinKey, + ObjectId: ObjectId, + ObjectID: ObjectId, + BSONRegExp: BSONRegExp, + BSONSymbol: BSONSymbol, + Timestamp: Timestamp, + EJSON: exports.EJSON, + setInternalBufferSize: setInternalBufferSize, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + deserialize: deserialize, + calculateObjectSize: calculateObjectSize, + deserializeStream: deserializeStream, + BSONError: BSONError, + BSONTypeError: BSONTypeError + }; + + exports.BSONError = BSONError; + exports.BSONRegExp = BSONRegExp; + exports.BSONSymbol = BSONSymbol; + exports.BSONTypeError = BSONTypeError; + exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = BSON_BINARY_SUBTYPE_BYTE_ARRAY; + exports.BSON_BINARY_SUBTYPE_COLUMN = BSON_BINARY_SUBTYPE_COLUMN; + exports.BSON_BINARY_SUBTYPE_DEFAULT = BSON_BINARY_SUBTYPE_DEFAULT; + exports.BSON_BINARY_SUBTYPE_ENCRYPTED = BSON_BINARY_SUBTYPE_ENCRYPTED; + exports.BSON_BINARY_SUBTYPE_FUNCTION = BSON_BINARY_SUBTYPE_FUNCTION; + exports.BSON_BINARY_SUBTYPE_MD5 = BSON_BINARY_SUBTYPE_MD5; + exports.BSON_BINARY_SUBTYPE_USER_DEFINED = BSON_BINARY_SUBTYPE_USER_DEFINED; + exports.BSON_BINARY_SUBTYPE_UUID = BSON_BINARY_SUBTYPE_UUID; + exports.BSON_BINARY_SUBTYPE_UUID_NEW = BSON_BINARY_SUBTYPE_UUID_NEW; + exports.BSON_DATA_ARRAY = BSON_DATA_ARRAY; + exports.BSON_DATA_BINARY = BSON_DATA_BINARY; + exports.BSON_DATA_BOOLEAN = BSON_DATA_BOOLEAN; + exports.BSON_DATA_CODE = BSON_DATA_CODE; + exports.BSON_DATA_CODE_W_SCOPE = BSON_DATA_CODE_W_SCOPE; + exports.BSON_DATA_DATE = BSON_DATA_DATE; + exports.BSON_DATA_DBPOINTER = BSON_DATA_DBPOINTER; + exports.BSON_DATA_DECIMAL128 = BSON_DATA_DECIMAL128; + exports.BSON_DATA_INT = BSON_DATA_INT; + exports.BSON_DATA_LONG = BSON_DATA_LONG; + exports.BSON_DATA_MAX_KEY = BSON_DATA_MAX_KEY; + exports.BSON_DATA_MIN_KEY = BSON_DATA_MIN_KEY; + exports.BSON_DATA_NULL = BSON_DATA_NULL; + exports.BSON_DATA_NUMBER = BSON_DATA_NUMBER; + exports.BSON_DATA_OBJECT = BSON_DATA_OBJECT; + exports.BSON_DATA_OID = BSON_DATA_OID; + exports.BSON_DATA_REGEXP = BSON_DATA_REGEXP; + exports.BSON_DATA_STRING = BSON_DATA_STRING; + exports.BSON_DATA_SYMBOL = BSON_DATA_SYMBOL; + exports.BSON_DATA_TIMESTAMP = BSON_DATA_TIMESTAMP; + exports.BSON_DATA_UNDEFINED = BSON_DATA_UNDEFINED; + exports.BSON_INT32_MAX = BSON_INT32_MAX; + exports.BSON_INT32_MIN = BSON_INT32_MIN; + exports.BSON_INT64_MAX = BSON_INT64_MAX; + exports.BSON_INT64_MIN = BSON_INT64_MIN; + exports.Binary = Binary; + exports.Code = Code; + exports.DBRef = DBRef; + exports.Decimal128 = Decimal128; + exports.Double = Double; + exports.Int32 = Int32; + exports.Long = Long; + exports.LongWithoutOverridesClass = LongWithoutOverridesClass; + exports.MaxKey = MaxKey; + exports.MinKey = MinKey; + exports.ObjectID = ObjectId; + exports.ObjectId = ObjectId; + exports.Timestamp = Timestamp; + exports.UUID = UUID; + exports.calculateObjectSize = calculateObjectSize; + exports.default = BSON; + exports.deserialize = deserialize; + exports.deserializeStream = deserializeStream; + exports.serialize = serialize; + exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; + exports.setInternalBufferSize = setInternalBufferSize; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=bson.browser.umd.js.map diff --git a/node_modules/bson/dist/bson.browser.umd.js.map b/node_modules/bson/dist/bson.browser.umd.js.map new file mode 100644 index 0000000..4feed15 --- /dev/null +++ b/node_modules/bson/dist/bson.browser.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.browser.umd.js","sources":["../node_modules/base64-js/index.js","../node_modules/ieee754/index.js","../node_modules/buffer/index.js","../node_modules/tslib/tslib.es6.js","../src/error.ts","../src/utils/global.ts","../src/parser/utils.ts","../src/ensure_buffer.ts","../src/uuid_utils.ts","../src/uuid.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/extended_json.ts","../src/map.ts","../src/constants.ts","../src/parser/calculate_size.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/float_parser.ts","../src/parser/serializer.ts","../src/bson.ts"],"sourcesContent":["'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n var proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n var copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n Buffer.from(buf).copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (var i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nvar hexSliceLookupTable = (function () {\n var alphabet = '0123456789abcdef'\n var table = new Array(256)\n for (var i = 0; i < 16; ++i) {\n var i16 = i * 16\n for (var j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["byteLength","toByteArray","fromByteArray","lookup","revLookup","Arr","Uint8Array","Array","code","i","len","length","charCodeAt","getLens","b64","Error","validLen","indexOf","placeHoldersLen","lens","_byteLength","tmp","arr","curByte","tripletToBase64","num","encodeChunk","uint8","start","end","output","push","join","extraBytes","parts","maxChunkLength","len2","buffer","offset","isLE","mLen","nBytes","e","m","eLen","eMax","eBias","nBits","d","s","NaN","Infinity","Math","pow","value","c","rt","abs","isNaN","floor","log","LN2","customInspectSymbol","Symbol","exports","Buffer","SlowBuffer","K_MAX_LENGTH","TYPED_ARRAY_SUPPORT","typedArraySupport","console","error","proto","foo","Object","setPrototypeOf","prototype","defineProperty","enumerable","get","isBuffer","undefined","byteOffset","createBuffer","RangeError","buf","arg","encodingOrOffset","TypeError","allocUnsafe","from","poolSize","fromString","ArrayBuffer","isView","fromArrayView","isInstance","fromArrayBuffer","SharedArrayBuffer","valueOf","b","fromObject","toPrimitive","assertSize","size","alloc","fill","encoding","checked","allocUnsafeSlow","string","isEncoding","actual","write","slice","fromArrayLike","array","arrayView","copy","obj","numberIsNaN","type","isArray","data","toString","_isBuffer","compare","a","x","y","min","String","toLowerCase","concat","list","pos","set","call","mustMatch","arguments","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","n","swap16","swap32","swap64","apply","toLocaleString","equals","inspect","str","max","INSPECT_MAX_BYTES","replace","trim","target","thisStart","thisEnd","thisCopy","targetCopy","bidirectionalIndexOf","val","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","includes","hexWrite","Number","remaining","strLen","parsed","parseInt","substr","utf8Write","blitBuffer","asciiWrite","asciiToBytes","base64Write","ucs2Write","utf16leToBytes","isFinite","toJSON","_arr","base64","res","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","decodeCodePointsArray","MAX_ARGUMENTS_LENGTH","codePoints","fromCharCode","ret","out","hexSliceLookupTable","bytes","newBuf","subarray","checkOffset","ext","readUintLE","readUIntLE","noAssert","mul","readUintBE","readUIntBE","readUint8","readUInt8","readUint16LE","readUInt16LE","readUint16BE","readUint32LE","readUInt32LE","readUint32BE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","ieee754","readFloatBE","readDoubleLE","readDoubleBE","checkInt","writeUintLE","writeUIntLE","maxBytes","writeUintBE","writeUIntBE","writeUint8","writeUInt8","writeUint16LE","writeUInt16LE","writeUint16BE","writeUInt16BE","writeUint32LE","writeUInt32LE","writeUint32BE","writeUInt32BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","checkIEEE754","writeFloat","littleEndian","writeFloatLE","writeFloatBE","writeDouble","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","INVALID_BASE64_RE","base64clean","split","units","leadSurrogate","byteArray","hi","lo","src","dst","constructor","name","alphabet","table","i16","extendStatics","__proto__","p","hasOwnProperty","__extends","__","create","kId","BSON_INT32_MAX","BSON_INT32_MIN","BSON_INT64_MAX","BSON_INT64_MIN","EJSON","bsonMap","calculateObjectSize","constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","deserialize","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT","Map","internalSerialize","internalDeserialize","internalCalculateObjectSize"],"mappings":";;;;;;;;;;CAEA,gBAAkB,GAAGA,UAArB;CACA,iBAAmB,GAAGC,WAAtB;CACA,mBAAqB,GAAGC,aAAxB;CAEA,IAAIC,MAAM,GAAG,EAAb;CACA,IAAIC,SAAS,GAAG,EAAhB;CACA,IAAIC,GAAG,GAAG,OAAOC,UAAP,KAAsB,WAAtB,GAAoCA,UAApC,GAAiDC,KAA3D;CAEA,IAAIC,IAAI,GAAG,kEAAX;;CACA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;KACT,KAAK,eAAA;KACL,qBAAqB,uBAAA;KACrB,SAAS,WAAA;KACT,2BAA2B,6BAAA;KAC3B,WAAW,aAAA;KACX,mBAAmB,qBAAA;KACnB,iBAAiB,mBAAA;KACjB,SAAS,WAAA;KACT,aAAa,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/bson/dist/bson.bundle.js b/node_modules/bson/dist/bson.bundle.js new file mode 100644 index 0000000..7fb2502 --- /dev/null +++ b/node_modules/bson/dist/bson.bundle.js @@ -0,0 +1,7494 @@ +var BSON = (function (exports) { + 'use strict'; + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var byteLength_1 = byteLength; + var toByteArray_1 = toByteArray; + var fromByteArray_1 = fromByteArray; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } // Support decoding URL-safe base64 strings, as Node.js does. + // See: https://en.wikipedia.org/wiki/Base64#URL_applications + + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + + function getLens(b64) { + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4'); + } // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + + + var validLen = b64.indexOf('='); + if (validLen === -1) validLen = len; + var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; + } // base64 is 4/3 + up to two characters of the original data + + + function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + + function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + + function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; // if there are placeholders, only get up to the last complete 4 chars + + var len = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i; + + for (i = 0; i < len; i += 4) { + tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; + arr[curByte++] = tmp >> 16 & 0xFF; + arr[curByte++] = tmp >> 8 & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; + arr[curByte++] = tmp & 0xFF; + } + + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + + return arr; + } + + function tripletToBase64(num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; + } + + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF); + output.push(tripletToBase64(tmp)); + } + + return output.join(''); + } + + function fromByteArray(uint8) { + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + // go through the array every three bytes, we'll deal with trailing stuff later + + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); + } // pad the end with zeros, but make sure to not forget the extra bytes + + + if (extraBytes === 1) { + tmp = uint8[len - 1]; + parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '=='); + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '='); + } + + return parts.join(''); + } + + var base64Js = { + byteLength: byteLength_1, + toByteArray: toByteArray_1, + fromByteArray: fromByteArray_1 + }; + + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + var read = function read(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + }; + + var write = function write(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = e << mLen | m; + eLen += mLen; + + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + }; + + var ieee754 = { + read: read, + write: write + }; + + var buffer$1 = createCommonjsModule(function (module, exports) { + + var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' ? // eslint-disable-line dot-notation + Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null; + exports.Buffer = Buffer; + exports.SlowBuffer = SlowBuffer; + exports.INSPECT_MAX_BYTES = 50; + var K_MAX_LENGTH = 0x7fffffff; + exports.kMaxLength = K_MAX_LENGTH; + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ + + Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); + + if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { + console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'); + } + + function typedArraySupport() { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1); + var proto = { + foo: function foo() { + return 42; + } + }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e) { + return false; + } + } + + Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function get() { + if (!Buffer.isBuffer(this)) return undefined; + return this.buffer; + } + }); + Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function get() { + if (!Buffer.isBuffer(this)) return undefined; + return this.byteOffset; + } + }); + + function createBuffer(length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"'); + } // Return an augmented `Uint8Array` instance + + + var buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer.prototype); + return buf; + } + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + + function Buffer(arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError('The "string" argument must be of type string. Received type number'); + } + + return allocUnsafe(arg); + } + + return from(arg, encodingOrOffset, length); + } + + Buffer.poolSize = 8192; // not used by this implementation + + function from(value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset); + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value); + } + + if (value == null) { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value)); + } + + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + + if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type number'); + } + + var valueOf = value.valueOf && value.valueOf(); + + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length); + } + + var b = fromObject(value); + if (b) return b; + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length); + } + + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value)); + } + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + + + Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length); + }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: + // https://github.com/feross/buffer/pull/148 + + + Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer, Uint8Array); + + function assertSize(size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + + function alloc(size, fill, encoding) { + assertSize(size); + + if (size <= 0) { + return createBuffer(size); + } + + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + + return createBuffer(size); + } + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + + + Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding); + }; + + function allocUnsafe(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + + + Buffer.allocUnsafe = function (size) { + return allocUnsafe(size); + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + + + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size); + }; + + function fromString(string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding); + } + + var length = byteLength(string, encoding) | 0; + var buf = createBuffer(length); + var actual = buf.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual); + } + + return buf; + } + + function fromArrayLike(array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + var buf = createBuffer(length); + + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + + return buf; + } + + function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); + } + + return fromArrayLike(arrayView); + } + + function fromArrayBuffer(array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + + var buf; + + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array); + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length); + } // Return an augmented `Uint8Array` instance + + + Object.setPrototypeOf(buf, Buffer.prototype); + return buf; + } + + function fromObject(obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); + + if (buf.length === 0) { + return buf; + } + + obj.copy(buf, 0, 0, len); + return buf; + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0); + } + + return fromArrayLike(obj); + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + + function checked(length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes'); + } + + return length | 0; + } + + function SlowBuffer(length) { + if (+length != length) { + // eslint-disable-line eqeqeq + length = 0; + } + + return Buffer.alloc(+length); + } + + Buffer.isBuffer = function isBuffer(b) { + return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false + }; + + Buffer.compare = function compare(a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength); + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength); + + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); + } + + if (a === b) return 0; + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + + Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true; + + default: + return false; + } + }; + + Buffer.concat = function concat(list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + + if (list.length === 0) { + return Buffer.alloc(0); + } + + var i; + + if (length === undefined) { + length = 0; + + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer.from(buf).copy(buffer, pos); + } else { + Uint8Array.prototype.set.call(buffer, buf, pos); + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer, pos); + } + + pos += buf.length; + } + + return buffer; + }; + + function byteLength(string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length; + } + + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength; + } + + if (typeof string !== 'string') { + throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + babelHelpers["typeof"](string)); + } + + var len = string.length; + var mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion + + var loweredCase = false; + + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len; + + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length; + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2; + + case 'hex': + return len >>> 1; + + case 'base64': + return base64ToBytes(string).length; + + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8 + } + + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + + Buffer.byteLength = byteLength; + + function slowToString(encoding, start, end) { + var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + + if (start === undefined || start < 0) { + start = 0; + } // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + + + if (start > this.length) { + return ''; + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return ''; + } // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + + + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return ''; + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end); + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end); + + case 'ascii': + return asciiSlice(this, start, end); + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end); + + case 'base64': + return base64Slice(this, start, end); + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end); + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) + // to detect a Buffer instance. It's not possible to use `instanceof Buffer` + // reliably in a browserify context because there could be multiple different + // copies of the 'buffer' package in use. This method works even for Buffer + // instances that were created from another copy of the `buffer` package. + // See: https://github.com/feross/buffer/issues/154 + + + Buffer.prototype._isBuffer = true; + + function swap(b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16() { + var len = this.length; + + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits'); + } + + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + + return this; + }; + + Buffer.prototype.swap32 = function swap32() { + var len = this.length; + + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits'); + } + + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + + return this; + }; + + Buffer.prototype.swap64 = function swap64() { + var len = this.length; + + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits'); + } + + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + + return this; + }; + + Buffer.prototype.toString = function toString() { + var length = this.length; + if (length === 0) return ''; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); + }; + + Buffer.prototype.toLocaleString = Buffer.prototype.toString; + + Buffer.prototype.equals = function equals(b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); + if (this === b) return true; + return Buffer.compare(this, b) === 0; + }; + + Buffer.prototype.inspect = function inspect() { + var str = ''; + var max = exports.INSPECT_MAX_BYTES; + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); + if (this.length > max) str += ' ... '; + return ''; + }; + + if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; + } + + Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength); + } + + if (!Buffer.isBuffer(target)) { + throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + babelHelpers["typeof"](target)); + } + + if (start === undefined) { + start = 0; + } + + if (end === undefined) { + end = target ? target.length : 0; + } + + if (thisStart === undefined) { + thisStart = 0; + } + + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index'); + } + + if (thisStart >= thisEnd && start >= end) { + return 0; + } + + if (thisStart >= thisEnd) { + return -1; + } + + if (start >= end) { + return 1; + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) return 0; + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + + + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1; // Normalize byteOffset + + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + + byteOffset = +byteOffset; // Coerce to Number. + + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1; + } // Normalize byteOffset: negative offsets start from the end of the buffer + + + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + + if (byteOffset >= buffer.length) { + if (dir) return -1;else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0;else return -1; + } // Normalize val + + + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } // Finally, search either indexOf (if dir is true) or lastIndexOf + + + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1; + } + + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + + throw new TypeError('val must be string, number or Buffer'); + } + + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + + if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1; + } + + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read(buf, i) { + if (indexSize === 1) { + return buf[i]; + } else { + return buf.readUInt16BE(i * indexSize); + } + } + + var i; + + if (dir) { + var foundIndex = -1; + + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + + for (i = byteOffset; i >= 0; i--) { + var found = true; + + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + + if (found) return i; + } + } + + return -1; + } + + Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + + Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + + function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + + if (!length) { + length = remaining; + } else { + length = Number(length); + + if (length > remaining) { + length = remaining; + } + } + + var strLen = string.length; + + if (length > strLen / 2) { + length = strLen / 2; + } + + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i; + buf[offset + i] = parsed; + } + + return i; + } + + function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); + } + + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); + } + + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); + } + + function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); + } + + Buffer.prototype.write = function write(string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0; + + if (isFinite(length)) { + length = length >>> 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + } else { + throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds'); + } + + if (!encoding) encoding = 'utf8'; + var loweredCase = false; + + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length); + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length); + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length); + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length); + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length); + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON() { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64Js.fromByteArray(buf); + } else { + return base64Js.fromByteArray(buf.slice(start, end)); + } + } + + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + var i = start; + + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + + break; + + case 2: + secondByte = buf[i + 1]; + + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; + + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + + break; + + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; + + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + + break; + + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; + + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res); + } // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + + + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + } // Decode in chunks to avoid "call stack size exceeded". + + + var res = ''; + var i = 0; + + while (i < len) { + res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); + } + + return res; + } + + function asciiSlice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + + return ret; + } + + function latin1Slice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + + return ret; + } + + function hexSlice(buf, start, end) { + var len = buf.length; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + var out = ''; + + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + + return out; + } + + function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + + for (var i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + + return res; + } + + Buffer.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance + + Object.setPrototypeOf(newBuf, Buffer.prototype); + return newBuf; + }; + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + + + function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); + } + + Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val; + }; + + Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val; + }; + + Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; + }; + + Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }; + + Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }; + + Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; + }; + + Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }; + + Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + mul *= 0x80; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; + }; + + Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + + mul *= 0x80; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; + }; + + Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return this[offset]; + return (0xff - this[offset] + 1) * -1; + }; + + Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | this[offset + 1] << 8; + return val & 0x8000 ? val | 0xFFFF0000 : val; + }; + + Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | this[offset] << 8; + return val & 0x8000 ? val | 0xFFFF0000 : val; + }; + + Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }; + + Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }; + + Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4); + }; + + Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4); + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8); + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8); + }; + + function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) throw new RangeError('Index out of range'); + } + + Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = value / mul & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = value / mul & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + this[offset] = value & 0xff; + return offset + 1; + }; + + Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + + Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + return offset + 2; + }; + + Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 0xff; + return offset + 4; + }; + + Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + return offset + 4; + }; + + Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + + this[offset + i] = (value / mul >> 0) - sub & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + + this[offset + i] = (value / mul >> 0) - sub & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (value < 0) value = 0xff + value + 1; + this[offset] = value & 0xff; + return offset + 1; + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + return offset + 2; + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + return offset + 4; + }; + + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range'); + if (offset < 0) throw new RangeError('Index out of range'); + } + + function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + + Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; + + function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + + + Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer'); + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done + + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions + + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds'); + } + + if (start < 0 || start >= this.length) throw new RangeError('Index out of range'); + if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? + + if (end > this.length) end = this.length; + + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); + } + + return len; + }; // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + + + Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string'); + } + + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding); + } + + if (val.length === 1) { + var code = val.charCodeAt(0); + + if (encoding === 'utf8' && code < 128 || encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code; + } + } + } else if (typeof val === 'number') { + val = val & 255; + } else if (typeof val === 'boolean') { + val = Number(val); + } // Invalid ranges are not set to a default, so can range check early. + + + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index'); + } + + if (end <= start) { + return this; + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + if (!val) val = 0; + var i; + + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); + var len = bytes.length; + + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this; + }; // HELPER FUNCTIONS + // ================ + + + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + + function base64clean(str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not + + str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' + + if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + + while (str.length % 4 !== 0) { + str = str + '='; + } + + return str; + } + + function utf8ToBytes(string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); // is surrogate component + + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue; + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue; + } // valid lead + + + leadSurrogate = codePoint; + continue; + } // 2 leads in a row + + + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue; + } // valid surrogate pair + + + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; // encode utf8 + + if (codePoint < 0x80) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break; + bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break; + bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break; + bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); + } else { + throw new Error('Invalid code point'); + } + } + + return bytes; + } + + function asciiToBytes(str) { + var byteArray = []; + + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + + return byteArray; + } + + function utf16leToBytes(str, units) { + var c, hi, lo; + var byteArray = []; + + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray; + } + + function base64ToBytes(str) { + return base64Js.toByteArray(base64clean(str)); + } + + function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break; + dst[i + offset] = src[i]; + } + + return i; + } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass + // the `instanceof` check but they should be treated as of that type. + // See: https://github.com/feross/buffer/issues/166 + + + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; + } + + function numberIsNaN(obj) { + // For IE11 support + return obj !== obj; // eslint-disable-line no-self-compare + } // Create lookup table for `toString('hex')` + // See: https://github.com/feross/buffer/issues/219 + + + var hexSliceLookupTable = function () { + var alphabet = '0123456789abcdef'; + var table = new Array(256); + + for (var i = 0; i < 16; ++i) { + var i16 = i * 16; + + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + + return table; + }(); + }); + var buffer_1 = buffer$1.Buffer; + buffer$1.SlowBuffer; + buffer$1.INSPECT_MAX_BYTES; + buffer$1.kMaxLength; + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + + /* global Reflect, Promise */ + var _extendStatics = function extendStatics(d, b) { + _extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function (d, b) { + d.__proto__ = b; + } || function (d, b) { + for (var p in b) { + if (b.hasOwnProperty(p)) d[p] = b[p]; + } + }; + + return _extendStatics(d, b); + }; + + function __extends(d, b) { + _extendStatics(d, b); + + function __() { + this.constructor = d; + } + + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** @public */ + var BSONError = /** @class */ (function (_super) { + __extends(BSONError, _super); + function BSONError() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(BSONError.prototype, "name", { + get: function () { + return 'BSONError'; + }, + enumerable: false, + configurable: true + }); + return BSONError; + }(Error)); + /** @public */ + var BSONTypeError = /** @class */ (function (_super) { + __extends(BSONTypeError, _super); + function BSONTypeError() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(BSONTypeError.prototype, "name", { + get: function () { + return 'BSONTypeError'; + }, + enumerable: false, + configurable: true + }); + return BSONTypeError; + }(TypeError)); + + function checkForMath(potentialGlobal) { + // eslint-disable-next-line eqeqeq + return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; + } + // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 + function getGlobal() { + // eslint-disable-next-line no-undef + return (checkForMath(typeof globalThis === 'object' && globalThis) || + checkForMath(typeof window === 'object' && window) || + checkForMath(typeof self === 'object' && self) || + checkForMath(typeof global === 'object' && global) || + Function('return this')()); + } + + /** + * Normalizes our expected stringified form of a function across versions of node + * @param fn - The function to stringify + */ + function normalizedFunctionString(fn) { + return fn.toString().replace('function(', 'function ('); + } + function isReactNative() { + var g = getGlobal(); + return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; + } + var insecureRandomBytes = function insecureRandomBytes(size) { + var insecureWarning = isReactNative() + ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; + console.warn(insecureWarning); + var result = buffer_1.alloc(size); + for (var i = 0; i < size; ++i) + result[i] = Math.floor(Math.random() * 256); + return result; + }; + var detectRandomBytes = function () { + if (typeof window !== 'undefined') { + // browser crypto implementation(s) + var target_1 = window.crypto || window.msCrypto; // allow for IE11 + if (target_1 && target_1.getRandomValues) { + return function (size) { return target_1.getRandomValues(buffer_1.alloc(size)); }; + } + } + if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { + // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global + return function (size) { return global.crypto.getRandomValues(buffer_1.alloc(size)); }; + } + var requiredRandomBytes; + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + requiredRandomBytes = require('crypto').randomBytes; + } + catch (e) { + // keep the fallback + } + // NOTE: in transpiled cases the above require might return null/undefined + return requiredRandomBytes || insecureRandomBytes; + }; + var randomBytes = detectRandomBytes(); + function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); + } + function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; + } + function isBigInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigInt64Array]'; + } + function isBigUInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigUint64Array]'; + } + function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; + } + function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; + } + // To ensure that 0.4 of node works correctly + function isDate(d) { + return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; + } + /** + * @internal + * this is to solve the `'someKey' in x` problem where x is unknown. + * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 + */ + function isObjectLike(candidate) { + return typeof candidate === 'object' && candidate !== null; + } + function deprecate(fn, message) { + var warned = false; + function deprecated() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!warned) { + console.warn(message); + warned = true; + } + return fn.apply(this, args); + } + return deprecated; + } + + /** + * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. + * + * @param potentialBuffer - The potential buffer + * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that + * wraps a passed in Uint8Array + * @throws TypeError If anything other than a Buffer or Uint8Array is passed in + */ + function ensureBuffer(potentialBuffer) { + if (ArrayBuffer.isView(potentialBuffer)) { + return buffer_1.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + if (isAnyArrayBuffer(potentialBuffer)) { + return buffer_1.from(potentialBuffer); + } + throw new BSONTypeError('Must use either Buffer or TypedArray'); + } + + // Validation regex for v4 uuid (validates with or without dashes) + var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; + var uuidValidateString = function (str) { + return typeof str === 'string' && VALIDATION_REGEX.test(str); + }; + var uuidHexStringToBuffer = function (hexString) { + if (!uuidValidateString(hexString)) { + throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); + } + var sanitizedHexString = hexString.replace(/-/g, ''); + return buffer_1.from(sanitizedHexString, 'hex'); + }; + var bufferToUuidHexString = function (buffer, includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + return includeDashes + ? buffer.toString('hex', 0, 4) + + '-' + + buffer.toString('hex', 4, 6) + + '-' + + buffer.toString('hex', 6, 8) + + '-' + + buffer.toString('hex', 8, 10) + + '-' + + buffer.toString('hex', 10, 16) + : buffer.toString('hex'); + }; + + var BYTE_LENGTH = 16; + var kId$1 = Symbol('id'); + /** + * A class representation of the BSON UUID type. + * @public + */ + var UUID = /** @class */ (function () { + /** + * Create an UUID type + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + function UUID(input) { + if (typeof input === 'undefined') { + // The most common use case (blank id, new UUID() instance) + this.id = UUID.generate(); + } + else if (input instanceof UUID) { + this[kId$1] = buffer_1.from(input.id); + this.__id = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { + this.id = ensureBuffer(input); + } + else if (typeof input === 'string') { + this.id = uuidHexStringToBuffer(input); + } + else { + throw new BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); + } + } + Object.defineProperty(UUID.prototype, "id", { + /** + * The UUID bytes + * @readonly + */ + get: function () { + return this[kId$1]; + }, + set: function (value) { + this[kId$1] = value; + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + }, + enumerable: false, + configurable: true + }); + /** + * Generate a 16 byte uuid v4 buffer used in UUIDs + */ + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + * */ + UUID.prototype.toHexString = function (includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + var uuidHexString = bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + }; + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + UUID.prototype.toString = function (encoding) { + return encoding ? this.id.toString(encoding) : this.toHexString(); + }; + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + UUID.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + UUID.prototype.equals = function (otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return otherId.id.equals(this.id); + } + try { + return new UUID(otherId).id.equals(this.id); + } + catch (_a) { + return false; + } + }; + /** + * Creates a Binary instance from the current UUID. + */ + UUID.prototype.toBinary = function () { + return new Binary(this.id, Binary.SUBTYPE_UUID); + }; + /** + * Generates a populated buffer containing a v4 uuid + */ + UUID.generate = function () { + var bytes = randomBytes(BYTE_LENGTH); + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return buffer_1.from(bytes); + }; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + UUID.isValid = function (input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuidValidateString(input); + } + if (isUint8Array(input)) { + // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) + if (input.length !== BYTE_LENGTH) { + return false; + } + try { + // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx + // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx + return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID; + } + catch (_a) { + return false; + } + } + return false; + }; + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + UUID.createFromHexString = function (hexString) { + var buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 36 character hex string representation. + * @internal + */ + UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + UUID.prototype.inspect = function () { + return "new UUID(\"" + this.toHexString() + "\")"; + }; + return UUID; + }()); + Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); + + /** + * A class representation of the BSON Binary type. + * @public + */ + var Binary = /** @class */ (function () { + /** + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) + return new Binary(buffer, subType); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + // create an empty binary buffer + this.buffer = buffer_1.alloc(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + // string + this.buffer = buffer_1.from(buffer, 'binary'); + } + else if (Array.isArray(buffer)) { + // number[] + this.buffer = buffer_1.from(buffer); + } + else { + // Buffer | TypedArray | ArrayBuffer + this.buffer = ensureBuffer(buffer); + } + this.position = this.buffer.byteLength; + } + } + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + Binary.prototype.put = function (byteValue) { + // If it's a string and a has more than one character throw an error + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONTypeError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONTypeError('only accepts single character Uint8Array or Array'); + // Decode the byte value once + var decodedByte; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } + else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } + else { + decodedByte = byteValue[0]; + } + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + var buffer = buffer_1.alloc(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decodedByte; + } + }; + /** + * Writes a buffer or string to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + Binary.prototype.write = function (sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + sequence.length) { + var buffer = buffer_1.alloc(this.buffer.length + sequence.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + // Assign the new buffer + this.buffer = buffer; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ensureBuffer(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + this.buffer.write(sequence, offset, sequence.length, 'binary'); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + }; + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + Binary.prototype.read = function (position, length) { + length = length && length > 0 ? length : this.position; + // Let's return the data based on the type we have + return this.buffer.slice(position, position + length); + }; + /** + * Returns the value of this binary as a string. + * @param asRaw - Will skip converting to a string + * @remarks + * This is handy when calling this function conditionally for some key value pairs and not others + */ + Binary.prototype.value = function (asRaw) { + asRaw = !!asRaw; + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + // If it's a node.js buffer object + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return this.buffer.toString('binary', 0, this.position); + }; + /** the length of the binary sequence */ + Binary.prototype.length = function () { + return this.position; + }; + Binary.prototype.toJSON = function () { + return this.buffer.toString('base64'); + }; + Binary.prototype.toString = function (format) { + return this.buffer.toString(format); + }; + /** @internal */ + Binary.prototype.toExtendedJSON = function (options) { + options = options || {}; + var base64String = this.buffer.toString('base64'); + var subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + }; + Binary.prototype.toUUID = function () { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID(this.buffer.slice(0, this.position)); + } + throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); + }; + /** @internal */ + Binary.fromExtendedJSON = function (doc, options) { + options = options || {}; + var data; + var type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = buffer_1.from(doc.$binary, 'base64'); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = buffer_1.from(doc.$binary.base64, 'base64'); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); + } + return new Binary(data, type); + }; + /** @internal */ + Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Binary.prototype.inspect = function () { + var asBuffer = this.value(true); + return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; + }; + /** + * Binary default subtype + * @internal + */ + Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** Initial buffer default size */ + Binary.BUFFER_SIZE = 256; + /** Default BSON type */ + Binary.SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + Binary.SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + Binary.SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + Binary.SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + Binary.SUBTYPE_UUID = 4; + /** MD5 BSON type */ + Binary.SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + Binary.SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + Binary.SUBTYPE_COLUMN = 7; + /** User BSON type */ + Binary.SUBTYPE_USER_DEFINED = 128; + return Binary; + }()); + Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); + + /** + * A class representation of the BSON Code type. + * @public + */ + var Code = /** @class */ (function () { + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + function Code(code, scope) { + if (!(this instanceof Code)) + return new Code(code, scope); + this.code = code; + this.scope = scope; + } + Code.prototype.toJSON = function () { + return { code: this.code, scope: this.scope }; + }; + /** @internal */ + Code.prototype.toExtendedJSON = function () { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + }; + /** @internal */ + Code.fromExtendedJSON = function (doc) { + return new Code(doc.$code, doc.$scope); + }; + /** @internal */ + Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Code.prototype.inspect = function () { + var codeJson = this.toJSON(); + return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; + }; + return Code; + }()); + Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); + + /** @internal */ + function isDBRefLike(value) { + return (isObjectLike(value) && + value.$id != null && + typeof value.$ref === 'string' && + (value.$db == null || typeof value.$db === 'string')); + } + /** + * A class representation of the BSON DBRef type. + * @public + */ + var DBRef = /** @class */ (function () { + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + function DBRef(collection, oid, db, fields) { + if (!(this instanceof DBRef)) + return new DBRef(collection, oid, db, fields); + // check if namespace has been provided + var parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + Object.defineProperty(DBRef.prototype, "namespace", { + // Property provided for compatibility with the 1.x parser + // the 1.x parser used a "namespace" property, while 4.x uses "collection" + /** @internal */ + get: function () { + return this.collection; + }, + set: function (value) { + this.collection = value; + }, + enumerable: false, + configurable: true + }); + DBRef.prototype.toJSON = function () { + var o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + }; + /** @internal */ + DBRef.prototype.toExtendedJSON = function (options) { + options = options || {}; + var o = { + $ref: this.collection, + $id: this.oid + }; + if (options.legacy) { + return o; + } + if (this.db) + o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + }; + /** @internal */ + DBRef.fromExtendedJSON = function (doc) { + var copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + }; + /** @internal */ + DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + DBRef.prototype.inspect = function () { + // NOTE: if OID is an ObjectId class it will just print the oid string. + var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); + return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; + }; + return DBRef; + }()); + Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); + + /** + * wasm optimizations, to do native i64 multiplication and divide + */ + var wasm = undefined; + try { + wasm = new WebAssembly.Instance(new WebAssembly.Module( + // prettier-ignore + new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; + } + catch (_a) { + // no wasm support + } + var TWO_PWR_16_DBL = 1 << 16; + var TWO_PWR_24_DBL = 1 << 24; + var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; + var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; + var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + /** A cache of the Long representations of small integer values. */ + var INT_CACHE = {}; + /** A cache of the Long representations of small unsigned integer values. */ + var UINT_CACHE = {}; + /** + * A class representing a 64-bit integer + * @public + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ + var Long = /** @class */ (function () { + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + function Long(low, high, unsigned) { + if (low === void 0) { low = 0; } + if (!(this instanceof Long)) + return new Long(low, high, unsigned); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } + else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } + else { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + Object.defineProperty(this, '__isLong__', { + value: true, + configurable: false, + writable: false, + enumerable: false + }); + } + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBits = function (lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + }; + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromInt = function (value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } + else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromNumber = function (value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; + } + else { + if (value <= -TWO_PWR_63_DBL) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBigInt = function (value, unsigned) { + return Long.fromString(value.toString(), unsigned); + }; + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + Long.fromString = function (str, unsigned, radix) { + if (str.length === 0) + throw Error('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + var p; + if ((p = str.indexOf('-')) > 0) + throw Error('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } + else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + }; + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + Long.fromBytes = function (bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + }; + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesLE = function (bytes, unsigned) { + return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); + }; + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesBE = function (bytes, unsigned) { + return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); + }; + /** + * Tests if the specified object is a Long. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + Long.isLong = function (value) { + return isObjectLike(value) && value['__isLong__'] === true; + }; + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + Long.fromValue = function (val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + }; + /** Returns the sum of this and the specified Long. */ + Long.prototype.add = function (addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xffff; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + Long.prototype.and = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + }; + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + Long.prototype.compare = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + // At this point the sign bits are the same + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + }; + /** This is an alias of {@link Long.compare} */ + Long.prototype.comp = function (other) { + return this.compare(other); + }; + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + Long.prototype.divide = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw Error('division by zero'); + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + // be consistent with non-wasm code path + return this; + } + var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + var approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } + else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } + else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } + else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } + else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return Long.UONE; + res = Long.UZERO; + } + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + }; + /**This is an alias of {@link Long.divide} */ + Long.prototype.div = function (divisor) { + return this.divide(divisor); + }; + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + Long.prototype.equals = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + }; + /** This is an alias of {@link Long.equals} */ + Long.prototype.eq = function (other) { + return this.equals(other); + }; + /** Gets the high 32 bits as a signed integer. */ + Long.prototype.getHighBits = function () { + return this.high; + }; + /** Gets the high 32 bits as an unsigned integer. */ + Long.prototype.getHighBitsUnsigned = function () { + return this.high >>> 0; + }; + /** Gets the low 32 bits as a signed integer. */ + Long.prototype.getLowBits = function () { + return this.low; + }; + /** Gets the low 32 bits as an unsigned integer. */ + Long.prototype.getLowBitsUnsigned = function () { + return this.low >>> 0; + }; + /** Gets the number of bits needed to represent the absolute value of this Long. */ + Long.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + // Unsigned Longs are never negative + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + var val = this.high !== 0 ? this.high : this.low; + var bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + }; + /** Tests if this Long's value is greater than the specified's. */ + Long.prototype.greaterThan = function (other) { + return this.comp(other) > 0; + }; + /** This is an alias of {@link Long.greaterThan} */ + Long.prototype.gt = function (other) { + return this.greaterThan(other); + }; + /** Tests if this Long's value is greater than or equal the specified's. */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.comp(other) >= 0; + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.gte = function (other) { + return this.greaterThanOrEqual(other); + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.ge = function (other) { + return this.greaterThanOrEqual(other); + }; + /** Tests if this Long's value is even. */ + Long.prototype.isEven = function () { + return (this.low & 1) === 0; + }; + /** Tests if this Long's value is negative. */ + Long.prototype.isNegative = function () { + return !this.unsigned && this.high < 0; + }; + /** Tests if this Long's value is odd. */ + Long.prototype.isOdd = function () { + return (this.low & 1) === 1; + }; + /** Tests if this Long's value is positive. */ + Long.prototype.isPositive = function () { + return this.unsigned || this.high >= 0; + }; + /** Tests if this Long's value equals zero. */ + Long.prototype.isZero = function () { + return this.high === 0 && this.low === 0; + }; + /** Tests if this Long's value is less than the specified's. */ + Long.prototype.lessThan = function (other) { + return this.comp(other) < 0; + }; + /** This is an alias of {@link Long#lessThan}. */ + Long.prototype.lt = function (other) { + return this.lessThan(other); + }; + /** Tests if this Long's value is less than or equal the specified's. */ + Long.prototype.lessThanOrEqual = function (other) { + return this.comp(other) <= 0; + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.lte = function (other) { + return this.lessThanOrEqual(other); + }; + /** Returns this Long modulo the specified. */ + Long.prototype.modulo = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + // use wasm support if present + if (wasm) { + var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.mod = function (divisor) { + return this.modulo(divisor); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.rem = function (divisor) { + return this.modulo(divisor); + }; + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + Long.prototype.multiply = function (multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + // use wasm support if present + if (wasm) { + var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } + else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + // If both longs are small, use float multiplication + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xffff; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** This is an alias of {@link Long.multiply} */ + Long.prototype.mul = function (multiplier) { + return this.multiply(multiplier); + }; + /** Returns the Negation of this Long's value. */ + Long.prototype.negate = function () { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + }; + /** This is an alias of {@link Long.negate} */ + Long.prototype.neg = function () { + return this.negate(); + }; + /** Returns the bitwise NOT of this Long. */ + Long.prototype.not = function () { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + }; + /** Tests if this Long's value differs from the specified's. */ + Long.prototype.notEquals = function (other) { + return !this.equals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.neq = function (other) { + return this.notEquals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.ne = function (other) { + return this.notEquals(other); + }; + /** + * Returns the bitwise OR of this Long and the specified. + */ + Long.prototype.or = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + }; + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftLeft = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + }; + /** This is an alias of {@link Long.shiftLeft} */ + Long.prototype.shl = function (numBits) { + return this.shiftLeft(numBits); + }; + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRight = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + }; + /** This is an alias of {@link Long.shiftRight} */ + Long.prototype.shr = function (numBits) { + return this.shiftRight(numBits); + }; + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRightUnsigned = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + var high = this.high; + if (numBits < 32) { + var low = this.low; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); + } + else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shr_u = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shru = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + Long.prototype.subtract = function (subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + /** This is an alias of {@link Long.subtract} */ + Long.prototype.sub = function (subtrahend) { + return this.subtract(subtrahend); + }; + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + Long.prototype.toInt = function () { + return this.unsigned ? this.low >>> 0 : this.low; + }; + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + Long.prototype.toNumber = function () { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + /** Converts the Long to a BigInt (arbitrary precision). */ + Long.prototype.toBigInt = function () { + return BigInt(this.toString()); + }; + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + Long.prototype.toBytes = function (le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + Long.prototype.toBytesLE = function () { + var hi = this.high, lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + }; + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + Long.prototype.toBytesBE = function () { + var hi = this.high, lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + }; + /** + * Converts this Long to signed. + */ + Long.prototype.toSigned = function () { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + }; + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + Long.prototype.toString = function (radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + // Unsigned Longs are never negative + if (this.eq(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } + else + return '-' + this.neg().toString(radix); + } + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + // eslint-disable-next-line @typescript-eslint/no-this-alias + var rem = this; + var result = ''; + // eslint-disable-next-line no-constant-condition + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + var digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } + }; + /** Converts this Long to unsigned. */ + Long.prototype.toUnsigned = function () { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + }; + /** Returns the bitwise XOR of this Long and the given one. */ + Long.prototype.xor = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + }; + /** This is an alias of {@link Long.isZero} */ + Long.prototype.eqz = function () { + return this.isZero(); + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.le = function (other) { + return this.lessThanOrEqual(other); + }; + /* + **************************************************************** + * BSON SPECIFIC ADDITIONS * + **************************************************************** + */ + Long.prototype.toExtendedJSON = function (options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + }; + Long.fromExtendedJSON = function (doc, options) { + var result = Long.fromString(doc.$numberLong); + return options && options.relaxed ? result.toNumber() : result; + }; + /** @internal */ + Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Long.prototype.inspect = function () { + return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")"; + }; + Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); + /** Maximum unsigned value. */ + Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); + /** Signed zero */ + Long.ZERO = Long.fromInt(0); + /** Unsigned zero. */ + Long.UZERO = Long.fromInt(0, true); + /** Signed one. */ + Long.ONE = Long.fromInt(1); + /** Unsigned one. */ + Long.UONE = Long.fromInt(1, true); + /** Signed negative one. */ + Long.NEG_ONE = Long.fromInt(-1); + /** Maximum signed value. */ + Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + /** Minimum signed value. */ + Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + return Long; + }()); + Object.defineProperty(Long.prototype, '__isLong__', { value: true }); + Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); + + var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; + var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; + var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + var EXPONENT_MAX = 6111; + var EXPONENT_MIN = -6176; + var EXPONENT_BIAS = 6176; + var MAX_DIGITS = 34; + // Nan value bits as 32 bit values (due to lack of longs) + var NAN_BUFFER = [ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ].reverse(); + // Infinity value bits 32 bit values (due to lack of longs) + var INF_NEGATIVE_BUFFER = [ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ].reverse(); + var INF_POSITIVE_BUFFER = [ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ].reverse(); + var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + // Extract least significant 5 bits + var COMBINATION_MASK = 0x1f; + // Extract least significant 14 bits + var EXPONENT_MASK = 0x3fff; + // Value of combination field for Inf + var COMBINATION_INFINITY = 30; + // Value of combination field for NaN + var COMBINATION_NAN = 31; + // Detect if the value is a digit + function isDigit(value) { + return !isNaN(parseInt(value, 10)); + } + // Divide two uint128 values + function divideu128(value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + for (var i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + return { quotient: value, rem: _rem }; + } + // Multiply two Long values and return the 128 bit value + function multiply64x2(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + // Return the 128 bit result + return { high: productHigh, low: productLow }; + } + function lessThan(left, right) { + // Make values unsigned + var uhleft = left.high >>> 0; + var uhright = right.high >>> 0; + // Compare high bits first + if (uhleft < uhright) { + return true; + } + else if (uhleft === uhright) { + var ulleft = left.low >>> 0; + var ulright = right.low >>> 0; + if (ulleft < ulright) + return true; + } + return false; + } + function invalidErr(string, message) { + throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); + } + /** + * A class representation of the BSON Decimal128 type. + * @public + */ + var Decimal128 = /** @class */ (function () { + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + function Decimal128(bytes) { + if (!(this instanceof Decimal128)) + return new Decimal128(bytes); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else { + this.bytes = bytes; + } + } + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + Decimal128.fromString = function (representation) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = new Long(0, 0); + // The low 17 digits of the significand + var significandLow = new Long(0, 0); + // The biased exponent + var biasedExponent = 0; + // Read index + var index = 0; + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (representation.length >= 7000) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + // Results + var stringMatch = representation.match(PARSE_STRING_REGEXP); + var infMatch = representation.match(PARSE_INF_REGEXP); + var nanMatch = representation.match(PARSE_NAN_REGEXP); + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + // full_match = stringMatch[0] + // sign = stringMatch[1] + var unsignedNumber = stringMatch[2]; + // stringMatch[3] is undefined if a whole number (ex "1", 12") + // but defined if a number w/ decimal in it (ex "1.0, 12.2") + var e = stringMatch[4]; + var expSign = stringMatch[5]; + var expNumber = stringMatch[6]; + // they provided e, but didn't give an exponent number. for ex "1e" + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + // they provided e, but didn't give a number before it. for ex "e1" + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + // Get the negative or positive sign + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + // Check if user passed Infinity or NaN + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + else if (representation[index] === 'N') { + return new Decimal128(buffer_1.from(NAN_BUFFER)); + } + } + // Read all the digits + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) + invalidErr(representation, 'contains multiple periods'); + sawRadix = true; + index = index + 1; + continue; + } + if (nDigitsStored < 34) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + // Only store 34 digits + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + if (sawRadix && !nDigitsRead) + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + // Read exponent if exists + if (representation[index] === 'e' || representation[index] === 'E') { + // Read exponent digits + var match = representation.substr(++index).match(EXPONENT_REGEX); + // No digits read + if (!match || !match[2]) + return new Decimal128(buffer_1.from(NAN_BUFFER)); + // Get exponent + exponent = parseInt(match[0], 10); + // Adjust the index + index = index + match[0].length; + } + // Return not a number + if (representation[index]) + return new Decimal128(buffer_1.from(NAN_BUFFER)); + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } + else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (digits[firstNonZero + significantDigits - 1] === 0) { + significantDigits = significantDigits - 1; + } + } + } + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit. can only do this if < significant digits than # stored. + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } + else { + // adjust to round + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits) { + var endOfString = nDigitsRead; + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + // if negative, we need to increment again to account for - sign at start. + if (isNegative) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + if (roundBit) { + var dIdx = lastDigit; + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + } + } + } + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } + else if (lastDigit - firstDigit < 17) { + var dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + else { + var dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + significandLow = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + // Encode combination, exponent, and significand. + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } + else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + dec.low = significand.low; + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + // Encode into a buffer + var buffer = buffer_1.alloc(16); + index = 0; + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + // Return the new Decimal128 + return new Decimal128(buffer); + }; + /** Create a string representation of the raw Decimal128 value */ + Decimal128.prototype.toString = function () { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) + significand[i] = 0; + // read pointer into significand + var index = 0; + // true if the number is zero + var is_zero = false; + // the most significant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: [0, 0, 0, 0] }; + // indexing variables + var j, k; + // Output string + var string = []; + // Unpack index + index = 0; + // Buffer reference + var buffer = this.bytes; + // Unpack the low 64bits into a long + // bits 96 - 127 + var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 64 - 95 + var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack the high 64bits into a long + // bits 32 - 63 + var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 0 - 31 + var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack index + index = 0; + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + // Decode combination field and exponent + // bits 1 - 5 + var combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } + else if (combination === COMBINATION_NAN) { + return 'NaN'; + } + else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } + else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + // unbiased exponent + var exponent = biased_exponent - EXPONENT_BIAS; + // Create string of significand digits + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + if (significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0) { + is_zero = true; + } + else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Perform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + // the exponent if scientific notation is used + var scientific_exponent = significand_digits - 1 + exponent; + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + // if there are too many significant digits, we should just be treating numbers + // as + or - 0 and using the non-scientific exponent (this is for the "invalid + // representation should be treated as 0/-0" spec cases in decimal128-1.json) + if (significand_digits > 34) { + string.push("" + 0); + if (exponent > 0) + string.push('E+' + exponent); + else if (exponent < 0) + string.push('E' + exponent); + return string.join(''); + } + string.push("" + significand[index++]); + significand_digits = significand_digits - 1; + if (significand_digits) { + string.push('.'); + } + for (var i = 0; i < significand_digits; i++) { + string.push("" + significand[index++]); + } + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } + else { + string.push("" + scientific_exponent); + } + } + else { + // Regular format with no decimal place + if (exponent >= 0) { + for (var i = 0; i < significand_digits; i++) { + string.push("" + significand[index++]); + } + } + else { + var radix_position = significand_digits + exponent; + // non-zero digits before radix + if (radix_position > 0) { + for (var i = 0; i < radix_position; i++) { + string.push("" + significand[index++]); + } + } + else { + string.push('0'); + } + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push("" + significand[index++]); + } + } + } + return string.join(''); + }; + Decimal128.prototype.toJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.prototype.toExtendedJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.fromExtendedJSON = function (doc) { + return Decimal128.fromString(doc.$numberDecimal); + }; + /** @internal */ + Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Decimal128.prototype.inspect = function () { + return "new Decimal128(\"" + this.toString() + "\")"; + }; + return Decimal128; + }()); + Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); + + /** + * A class representation of the BSON Double type. + * @public + */ + var Double = /** @class */ (function () { + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + function Double(value) { + if (!(this instanceof Double)) + return new Double(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + Double.prototype.valueOf = function () { + return this.value; + }; + Double.prototype.toJSON = function () { + return this.value; + }; + Double.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + /** @internal */ + Double.prototype.toExtendedJSON = function (options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user + // explicitly provided `-0` then we need to ensure the sign makes it into the output + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: "-" + this.value.toFixed(1) }; + } + var $numberDouble; + if (Number.isInteger(this.value)) { + $numberDouble = this.value.toFixed(1); + if ($numberDouble.length >= 13) { + $numberDouble = this.value.toExponential(13).toUpperCase(); + } + } + else { + $numberDouble = this.value.toString(); + } + return { $numberDouble: $numberDouble }; + }; + /** @internal */ + Double.fromExtendedJSON = function (doc, options) { + var doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + }; + /** @internal */ + Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Double.prototype.inspect = function () { + var eJSON = this.toExtendedJSON(); + return "new Double(" + eJSON.$numberDouble + ")"; + }; + return Double; + }()); + Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); + + /** + * A class representation of a BSON Int32 type. + * @public + */ + var Int32 = /** @class */ (function () { + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + function Int32(value) { + if (!(this instanceof Int32)) + return new Int32(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { + return this.value; + }; + Int32.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + Int32.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + Int32.prototype.toExtendedJSON = function (options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + }; + /** @internal */ + Int32.fromExtendedJSON = function (doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + }; + /** @internal */ + Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Int32.prototype.inspect = function () { + return "new Int32(" + this.valueOf() + ")"; + }; + return Int32; + }()); + Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); + + /** + * A class representation of the BSON MaxKey type. + * @public + */ + var MaxKey = /** @class */ (function () { + function MaxKey() { + if (!(this instanceof MaxKey)) + return new MaxKey(); + } + /** @internal */ + MaxKey.prototype.toExtendedJSON = function () { + return { $maxKey: 1 }; + }; + /** @internal */ + MaxKey.fromExtendedJSON = function () { + return new MaxKey(); + }; + /** @internal */ + MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MaxKey.prototype.inspect = function () { + return 'new MaxKey()'; + }; + return MaxKey; + }()); + Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); + + /** + * A class representation of the BSON MinKey type. + * @public + */ + var MinKey = /** @class */ (function () { + function MinKey() { + if (!(this instanceof MinKey)) + return new MinKey(); + } + /** @internal */ + MinKey.prototype.toExtendedJSON = function () { + return { $minKey: 1 }; + }; + /** @internal */ + MinKey.fromExtendedJSON = function () { + return new MinKey(); + }; + /** @internal */ + MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MinKey.prototype.inspect = function () { + return 'new MinKey()'; + }; + return MinKey; + }()); + Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); + + // Regular expression that checks for hex value + var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + // Unique sequence for the current process (initialized on first use) + var PROCESS_UNIQUE = null; + var kId = Symbol('id'); + /** + * A class representation of the BSON ObjectId type. + * @public + */ + var ObjectId = /** @class */ (function () { + /** + * Create an ObjectId type + * + * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number. + */ + function ObjectId(id) { + if (!(this instanceof ObjectId)) + return new ObjectId(id); + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectId) { + this[kId] = id.id; + this.__id = id.__id; + } + if (typeof id === 'object' && id && 'id' in id) { + if ('toHexString' in id && typeof id.toHexString === 'function') { + this[kId] = buffer_1.from(id.toHexString(), 'hex'); + } + else { + this[kId] = typeof id.id === 'string' ? buffer_1.from(id.id) : id.id; + } + } + // The most common use case (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined); + // If we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + if (ArrayBuffer.isView(id) && id.byteLength === 12) { + this[kId] = ensureBuffer(id); + } + if (typeof id === 'string') { + if (id.length === 12) { + var bytes = buffer_1.from(id); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + } + else if (id.length === 24 && checkForHexRegExp.test(id)) { + this[kId] = buffer_1.from(id, 'hex'); + } + else { + throw new BSONTypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters'); + } + } + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + Object.defineProperty(ObjectId.prototype, "id", { + /** + * The ObjectId bytes + * @readonly + */ + get: function () { + return this[kId]; + }, + set: function (value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = value.toString('hex'); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ObjectId.prototype, "generationTime", { + /** + * The generation time of this ObjectId instance + * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch + */ + get: function () { + return this.id.readInt32BE(0); + }, + set: function (value) { + // Encode time into first 4 bytes + this.id.writeUInt32BE(value, 0); + }, + enumerable: false, + configurable: true + }); + /** Returns the ObjectId id as a 24 character hex string representation */ + ObjectId.prototype.toHexString = function () { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + var hexString = this.id.toString('hex'); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + }; + /** + * Update the ObjectId index + * @privateRemarks + * Used in generating new ObjectId's on the driver + * @internal + */ + ObjectId.getInc = function () { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + }; + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + ObjectId.generate = function (time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + var inc = ObjectId.getInc(); + var buffer = buffer_1.alloc(12); + // 4-byte timestamp + buffer.writeUInt32BE(time, 0); + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = randomBytes(5); + } + // 5-byte process unique + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + // 3-byte counter + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + }; + /** + * Converts the id into a 24 character hex string for printing + * + * @param format - The Buffer toString format parameter. + */ + ObjectId.prototype.toString = function (format) { + // Is the id a buffer then use the buffer toString method to return the format + if (format) + return this.id.toString(format); + return this.toHexString(); + }; + /** Converts to its JSON the 24 character hex string representation. */ + ObjectId.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + ObjectId.prototype.equals = function (otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this.toString() === otherId.toString(); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id)) { + return otherId === buffer_1.prototype.toString.call(this.id, 'latin1'); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { + return buffer_1.from(otherId).equals(this.id); + } + if (typeof otherId === 'object' && + 'toHexString' in otherId && + typeof otherId.toHexString === 'function') { + return otherId.toHexString() === this.toHexString(); + } + return false; + }; + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + ObjectId.prototype.getTimestamp = function () { + var timestamp = new Date(); + var time = this.id.readUInt32BE(0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + }; + /** @internal */ + ObjectId.createPk = function () { + return new ObjectId(); + }; + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + ObjectId.createFromTime = function (time) { + var buffer = buffer_1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer.writeUInt32BE(time, 0); + // Return the new objectId + return new ObjectId(buffer); + }; + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + ObjectId.createFromHexString = function (hexString) { + // Throw an error if it's not a valid setup + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(buffer_1.from(hexString, 'hex')); + }; + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + ObjectId.isValid = function (id) { + if (id == null) + return false; + if (typeof id === 'number') { + return true; + } + if (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); + } + if (id instanceof ObjectId) { + return true; + } + if (isUint8Array(id) && id.length === 12) { + return true; + } + // Duck-Typing detection of ObjectId like objects + if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { + if (typeof id.id === 'string') { + return id.id.length === 12; + } + return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); + } + return false; + }; + /** @internal */ + ObjectId.prototype.toExtendedJSON = function () { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + }; + /** @internal */ + ObjectId.fromExtendedJSON = function (doc) { + return new ObjectId(doc.$oid); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 24 character hex string representation. + * @internal + */ + ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + ObjectId.prototype.inspect = function () { + return "new ObjectId(\"" + this.toHexString() + "\")"; + }; + /** @internal */ + ObjectId.index = ~~(Math.random() * 0xffffff); + return ObjectId; + }()); + // Deprecated methods + Object.defineProperty(ObjectId.prototype, 'generate', { + value: deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') + }); + Object.defineProperty(ObjectId.prototype, 'getInc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') + }); + Object.defineProperty(ObjectId.prototype, 'get_inc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') + }); + Object.defineProperty(ObjectId, 'get_inc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') + }); + Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); + + function alphabetize(str) { + return str.split('').sort().join(''); + } + /** + * A class representation of the BSON RegExp type. + * @public + */ + var BSONRegExp = /** @class */ (function () { + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) + return new BSONRegExp(pattern, options); + this.pattern = pattern; + this.options = alphabetize(options !== null && options !== void 0 ? options : ''); + if (this.pattern.indexOf('\x00') !== -1) { + throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); + } + if (this.options.indexOf('\x00') !== -1) { + throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); + } + // Validate options + for (var i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u')) { + throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported"); + } + } + } + BSONRegExp.parseOptions = function (options) { + return options ? options.split('').sort().join('') : ''; + }; + /** @internal */ + BSONRegExp.prototype.toExtendedJSON = function (options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + }; + /** @internal */ + BSONRegExp.fromExtendedJSON = function (doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + // This is for $regex query operators that have extended json values. + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc; + } + } + else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); + } + throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); + }; + return BSONRegExp; + }()); + Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); + + /** + * A class representation of the BSON Symbol type. + * @public + */ + var BSONSymbol = /** @class */ (function () { + /** + * @param value - the string representing the symbol. + */ + function BSONSymbol(value) { + if (!(this instanceof BSONSymbol)) + return new BSONSymbol(value); + this.value = value; + } + /** Access the wrapped string value. */ + BSONSymbol.prototype.valueOf = function () { + return this.value; + }; + BSONSymbol.prototype.toString = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.inspect = function () { + return "new BSONSymbol(\"" + this.value + "\")"; + }; + BSONSymbol.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.toExtendedJSON = function () { + return { $symbol: this.value }; + }; + /** @internal */ + BSONSymbol.fromExtendedJSON = function (doc) { + return new BSONSymbol(doc.$symbol); + }; + /** @internal */ + BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + return BSONSymbol; + }()); + Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); + + /** @public */ + var LongWithoutOverridesClass = Long; + /** @public */ + var Timestamp = /** @class */ (function (_super) { + __extends(Timestamp, _super); + function Timestamp(low, high) { + var _this = this; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + ///@ts-expect-error + if (!(_this instanceof Timestamp)) + return new Timestamp(low, high); + if (Long.isLong(low)) { + _this = _super.call(this, low.low, low.high, true) || this; + } + else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { + _this = _super.call(this, low.i, low.t, true) || this; + } + else { + _this = _super.call(this, low, high, true) || this; + } + Object.defineProperty(_this, '_bsontype', { + value: 'Timestamp', + writable: false, + configurable: false, + enumerable: false + }); + return _this; + } + Timestamp.prototype.toJSON = function () { + return { + $timestamp: this.toString() + }; + }; + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + Timestamp.fromInt = function (value) { + return new Timestamp(Long.fromInt(value, true)); + }; + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + Timestamp.fromNumber = function (value) { + return new Timestamp(Long.fromNumber(value, true)); + }; + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + Timestamp.fromString = function (str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + }; + /** @internal */ + Timestamp.prototype.toExtendedJSON = function () { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + }; + /** @internal */ + Timestamp.fromExtendedJSON = function (doc) { + return new Timestamp(doc.$timestamp); + }; + /** @internal */ + Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Timestamp.prototype.inspect = function () { + return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })"; + }; + Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + return Timestamp; + }(LongWithoutOverridesClass)); + + function isBSONType(value) { + return (isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); + } + // INT32 boundaries + var BSON_INT32_MAX$1 = 0x7fffffff; + var BSON_INT32_MIN$1 = -0x80000000; + // INT64 boundaries + var BSON_INT64_MAX$1 = 0x7fffffffffffffff; + var BSON_INT64_MIN$1 = -0x8000000000000000; + // all the types where we don't need to do any special processing and can just pass the EJSON + //straight to type.fromExtendedJSON + var keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function deserializeValue(value, options) { + if (options === void 0) { options = {}; } + if (typeof value === 'number') { + if (options.relaxed || options.legacy) { + return value; + } + // if it's an integer, should interpret as smallest BSON integer + // that can represent it exactly. (if out of range, interpret as double.) + if (Math.floor(value) === value) { + if (value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1) + return new Int32(value); + if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1) + return Long.fromNumber(value); + } + // If the number is a non-integer or out of integer range, should interpret as BSON Double. + return new Double(value); + } + // from here on out we're looking for bson types, so bail if its not an object + if (value == null || typeof value !== 'object') + return value; + // upgrade deprecated undefined to null + if (value.$undefined) + return null; + var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); + for (var i = 0; i < keys.length; i++) { + var c = keysToCodecs[keys[i]]; + if (c) + return c.fromExtendedJSON(value, options); + } + if (value.$date != null) { + var d = value.$date; + var date = new Date(); + if (options.legacy) { + if (typeof d === 'number') + date.setTime(d); + else if (typeof d === 'string') + date.setTime(Date.parse(d)); + } + else { + if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (Long.isLong(d)) + date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) + date.setTime(d); + } + return date; + } + if (value.$code != null) { + var copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return Code.fromExtendedJSON(value); + } + if (isDBRefLike(value) || value.$dbPointer) { + var v = value.$ref ? value : value.$dbPointer; + // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) + // because of the order JSON.parse goes through the document + if (v instanceof DBRef) + return v; + var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); + var valid_1 = true; + dollarKeys.forEach(function (k) { + if (['$ref', '$id', '$db'].indexOf(k) === -1) + valid_1 = false; + }); + // only make DBRef if $ keys are all valid + if (valid_1) + return DBRef.fromExtendedJSON(v); + } + return value; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function serializeArray(array, options) { + return array.map(function (v, index) { + options.seenObjects.push({ propertyName: "index " + index, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); + } + function getISOString(date) { + var isoStr = date.toISOString(); + // we should only show milliseconds in timestamp if they're non-zero + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function serializeValue(value, options) { + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); + if (index !== -1) { + var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); + var leadingPart = props + .slice(0, index) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var alreadySeen = props[index]; + var circularPart = ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var current = props[props.length - 1]; + var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new BSONTypeError('Converting circular structure to EJSON:\n' + + (" " + leadingPart + alreadySeen + circularPart + current + "\n") + + (" " + leadingSpace + "\\" + dashes + "/")); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || isDate(value)) { + var dateNum = value.getTime(), + // is it in year range 1970-9999? + inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + // it's an integer + if (Math.floor(value) === value) { + var int32Range = value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1; + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (int32Range) + return { $numberInt: value.toString() }; + if (int64Range) + return { $numberLong: value.toString() }; + } + return { $numberDouble: value.toString() }; + } + if (value instanceof RegExp || isRegExp(value)) { + var flags = value.flags; + if (flags === undefined) { + var match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + var rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === 'object') + return serializeDocument(value, options); + return value; + } + var BSON_TYPE_MAPPINGS = { + Binary: function (o) { return new Binary(o.value(), o.sub_type); }, + Code: function (o) { return new Code(o.code, o.scope); }, + DBRef: function (o) { return new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, + Decimal128: function (o) { return new Decimal128(o.bytes); }, + Double: function (o) { return new Double(o.value); }, + Int32: function (o) { return new Int32(o.value); }, + Long: function (o) { + return Long.fromBits( + // underscore variants for 1.x backwards compatibility + o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); + }, + MaxKey: function () { return new MaxKey(); }, + MinKey: function () { return new MinKey(); }, + ObjectID: function (o) { return new ObjectId(o); }, + ObjectId: function (o) { return new ObjectId(o); }, + BSONRegExp: function (o) { return new BSONRegExp(o.pattern, o.options); }, + Symbol: function (o) { return new BSONSymbol(o.value); }, + Timestamp: function (o) { return Timestamp.fromBits(o.low, o.high); } + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + var bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + // It's a regular object. Recursively serialize its property values. + var _doc = {}; + for (var name in doc) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + _doc[name] = serializeValue(doc[name], options); + } + finally { + options.seenObjects.pop(); + } + } + return _doc; + } + else if (isBSONType(doc)) { + // the "document" is really just a BSON type object + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + // There's no EJSON serialization function on the object. It's probably an + // object created by a previous version of this library (or another library) + // that's duck-typing objects to look like they were generated by this library). + // Copy the object into this library's version of that type. + var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + // Two BSON types may have nested objects that may need to be serialized too + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } + else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + } + return outDoc.toExtendedJSON(options); + } + else { + throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } + } + /** + * EJSON parse / stringify API + * @public + */ + // the namespace here is used to emulate `export * as EJSON from '...'` + // which as of now (sept 2020) api-extractor does not support + // eslint-disable-next-line @typescript-eslint/no-namespace + exports.EJSON = void 0; + (function (EJSON) { + /** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ + function parse(text, options) { + var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); + // relaxed implies not strict + if (typeof finalOptions.relaxed === 'boolean') + finalOptions.strict = !finalOptions.relaxed; + if (typeof finalOptions.strict === 'boolean') + finalOptions.relaxed = !finalOptions.strict; + return JSON.parse(text, function (key, value) { + if (key.indexOf('\x00') !== -1) { + throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key)); + } + return deserializeValue(value, finalOptions); + }); + } + EJSON.parse = parse; + /** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ + function stringify(value, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer, space, options) { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + var doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); + } + EJSON.stringify = stringify; + /** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ + function serialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); + } + EJSON.serialize = serialize; + /** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ + function deserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); + } + EJSON.deserialize = deserialize; + })(exports.EJSON || (exports.EJSON = {})); + + /* eslint-disable @typescript-eslint/no-explicit-any */ + /** @public */ + exports.Map = void 0; + var bsonGlobal = getGlobal(); + if (bsonGlobal.Map) { + exports.Map = bsonGlobal.Map; + } + else { + // We will return a polyfill + exports.Map = /** @class */ (function () { + function Map(array) { + if (array === void 0) { array = []; } + this._keys = []; + this._values = {}; + for (var i = 0; i < array.length; i++) { + if (array[i] == null) + continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + } + Map.prototype.clear = function () { + this._keys = []; + this._values = {}; + }; + Map.prototype.delete = function (key) { + var value = this._values[key]; + if (value == null) + return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + Map.prototype.entries = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? [key, _this._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.forEach = function (callback, self) { + self = self || this; + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + Map.prototype.get = function (key) { + return this._values[key] ? this._values[key].v : undefined; + }; + Map.prototype.has = function (key) { + return this._values[key] != null; + }; + Map.prototype.keys = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.set = function (key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + Map.prototype.values = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? _this._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Object.defineProperty(Map.prototype, "size", { + get: function () { + return this._keys.length; + }, + enumerable: false, + configurable: true + }); + return Map; + }()); + } + + /** @internal */ + var BSON_INT32_MAX = 0x7fffffff; + /** @internal */ + var BSON_INT32_MIN = -0x80000000; + /** @internal */ + var BSON_INT64_MAX = Math.pow(2, 63) - 1; + /** @internal */ + var BSON_INT64_MIN = -Math.pow(2, 63); + /** + * Any integer up to 2^53 can be precisely represented by a double. + * @internal + */ + var JS_INT_MAX = Math.pow(2, 53); + /** + * Any integer down to -2^53 can be precisely represented by a double. + * @internal + */ + var JS_INT_MIN = -Math.pow(2, 53); + /** Number BSON Type @internal */ + var BSON_DATA_NUMBER = 1; + /** String BSON Type @internal */ + var BSON_DATA_STRING = 2; + /** Object BSON Type @internal */ + var BSON_DATA_OBJECT = 3; + /** Array BSON Type @internal */ + var BSON_DATA_ARRAY = 4; + /** Binary BSON Type @internal */ + var BSON_DATA_BINARY = 5; + /** Binary BSON Type @internal */ + var BSON_DATA_UNDEFINED = 6; + /** ObjectId BSON Type @internal */ + var BSON_DATA_OID = 7; + /** Boolean BSON Type @internal */ + var BSON_DATA_BOOLEAN = 8; + /** Date BSON Type @internal */ + var BSON_DATA_DATE = 9; + /** null BSON Type @internal */ + var BSON_DATA_NULL = 10; + /** RegExp BSON Type @internal */ + var BSON_DATA_REGEXP = 11; + /** Code BSON Type @internal */ + var BSON_DATA_DBPOINTER = 12; + /** Code BSON Type @internal */ + var BSON_DATA_CODE = 13; + /** Symbol BSON Type @internal */ + var BSON_DATA_SYMBOL = 14; + /** Code with Scope BSON Type @internal */ + var BSON_DATA_CODE_W_SCOPE = 15; + /** 32 bit Integer BSON Type @internal */ + var BSON_DATA_INT = 16; + /** Timestamp BSON Type @internal */ + var BSON_DATA_TIMESTAMP = 17; + /** Long BSON Type @internal */ + var BSON_DATA_LONG = 18; + /** Decimal128 BSON Type @internal */ + var BSON_DATA_DECIMAL128 = 19; + /** MinKey BSON Type @internal */ + var BSON_DATA_MIN_KEY = 0xff; + /** MaxKey BSON Type @internal */ + var BSON_DATA_MAX_KEY = 0x7f; + /** Binary Default Type @internal */ + var BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** Binary Function Type @internal */ + var BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** Binary Byte Array Type @internal */ + var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ + var BSON_BINARY_SUBTYPE_UUID = 3; + /** Binary UUID Type @internal */ + var BSON_BINARY_SUBTYPE_UUID_NEW = 4; + /** Binary MD5 Type @internal */ + var BSON_BINARY_SUBTYPE_MD5 = 5; + /** Encrypted BSON type @internal */ + var BSON_BINARY_SUBTYPE_ENCRYPTED = 6; + /** Column BSON type @internal */ + var BSON_BINARY_SUBTYPE_COLUMN = 7; + /** Binary User Defined Type @internal */ + var BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) { + var totalLength = 4 + 1; + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } + else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; + } + /** @internal */ + function calculateElement(name, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + value, serializeFunctions, isArray, ignoreUndefined) { + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (isArray === void 0) { isArray = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = false; } + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + buffer_1.byteLength(name, 'utf8') + 1 + 4 + buffer_1.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + // 32 bit + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } + else { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } + else { + // 64 bit + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (value['_bsontype'] === 'Decimal128') { + return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } + else if (value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.byteLength(value.code.toString(), 'utf8') + + 1); + } + } + else if (value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)); + } + } + else if (value['_bsontype'] === 'Symbol') { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + buffer_1.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1); + } + else if (value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + // Add db reference if it exists + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value['_bsontype'] === 'BSONRegExp') { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.byteLength(value.pattern, 'utf8') + + 1 + + buffer_1.byteLength(value.options, 'utf8') + + 1); + } + else { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); + } + else if (serializeFunctions) { + return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + + 1); + } + } + } + return 0; + } + + var FIRST_BIT = 0x80; + var FIRST_TWO_BITS = 0xc0; + var FIRST_THREE_BITS = 0xe0; + var FIRST_FOUR_BITS = 0xf0; + var FIRST_FIVE_BITS = 0xf8; + var TWO_BIT_CHAR = 0xc0; + var THREE_BIT_CHAR = 0xe0; + var FOUR_BIT_CHAR = 0xf0; + var CONTINUING_CHAR = 0x80; + /** + * Determines if the passed in bytes are valid utf8 + * @param bytes - An array of 8-bit bytes. Must be indexable and have length property + * @param start - The index to start validating + * @param end - The index to end validating + */ + function validateUtf8(bytes, start, end) { + var continuation = 0; + for (var i = start; i < end; i += 1) { + var byte = bytes[i]; + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } + else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } + else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } + else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } + else { + return false; + } + } + } + return !continuation; + } + + // Internal long versions + var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); + var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); + var functionCache = {}; + function deserialize$1(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (size < 5) { + throw new BSONError("bson size must be >= 5, is " + size); + } + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size); + } + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new BSONError("buffer length " + buffer.length + " must === bson size " + size); + } + if (size + index > buffer.byteLength) { + throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); + } + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); + } + var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; + function deserializeObject(buffer, index, options, isArray) { + if (isArray === void 0) { isArray = false; } + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + // Set the start index + var startIndex = index; + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + // Read the document size + var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + var done = false; + var isPossibleDBRef = isArray ? false : null; + // While we have more left data left keep parsing + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) + break; + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + var value = void 0; + index = i + 1; + if (elementType === BSON_DATA_STRING) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + value = getValidatedString(buffer, index, index + stringSize - 1); + index = index + stringSize; + } + else if (elementType === BSON_DATA_OID) { + var oid = buffer_1.alloc(12); + buffer.copy(oid, 0, index, index + 12); + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } + else if (elementType === BSON_DATA_NUMBER) { + value = buffer.readDoubleLE(index); + index = index + 8; + } + else if (elementType === BSON_DATA_DATE) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Date(new Long(lowBits, highBits).toNumber()); + } + else if (elementType === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new BSONError('bad embedded document length in bson'); + // We have a raw value + if (raw) { + value = buffer.slice(index, index + objectSize); + } + else { + value = deserializeObject(buffer, _index, options, false); + } + index = index + objectSize; + } + else if (elementType === BSON_DATA_ARRAY) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + var arrayOptions = options; + // Stop index + var stopIndex = index + objectSize; + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) { + arrayOptions[n] = options[n]; + } + arrayOptions['raw'] = true; + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + if (buffer[index - 1] !== 0) + throw new BSONError('invalid array terminator byte'); + if (index !== stopIndex) + throw new BSONError('corrupted array bson'); + } + else if (elementType === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + // Unpack the low and high bits + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } + else { + value = long; + } + } + else if (elementType === BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = buffer_1.alloc(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { + value = decimal128.toObject(); + } + else { + value = decimal128; + } + } + else if (elementType === BSON_DATA_BINARY) { + var binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var totalBinarySize = binarySize; + var subType = buffer[index++]; + // Did we have a negative binary size, throw + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + // Is the length longer than the document + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = buffer.slice(index, index + binarySize); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } + else { + var _buffer = buffer_1.alloc(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else { + value = new Binary(_buffer, subType); + } + } + // Update the index + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + value = new RegExp(source, optionsArray.join('')); + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // Set the object + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === BSON_DATA_SYMBOL) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + var symbol = getValidatedString(buffer, index, index + stringSize - 1); + value = promoteValues ? symbol : new BSONSymbol(symbol); + index = index + stringSize; + } + else if (elementType === BSON_DATA_TIMESTAMP) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Timestamp(lowBits, highBits); + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === BSON_DATA_CODE) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + var functionString = getValidatedString(buffer, index, index + stringSize - 1); + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + } + else { + value = new Code(functionString); + } + // Update parse index position + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + // Javascript function + var functionString = getValidatedString(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + var _index = index; + // Decode the size of the object document + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + // Check if field length is too short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + // Check if totalSize field is too long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + value.scope = scopeObject; + } + else { + value = new Code(functionString, scopeObject); + } + } + else if (elementType === BSON_DATA_DBPOINTER) { + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) + throw new BSONError('bad string length in bson'); + // Namespace + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Read the oid + var oidBuffer = buffer_1.alloc(12); + buffer.copy(oidBuffer, 0, index, index + 12); + var oid = new ObjectId(oidBuffer); + // Update the index + index = index + 12; + // Upgrade to DBRef type + value = new DBRef(namespace, oid); + } + else { + throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value: value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + object[name] = value; + } + } + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + var copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; + } + /** + * Ensure eval is isolated, store the result in functionCache. + * + * @internal + */ + function isolateEval(functionString, functionCache, object) { + if (!functionCache) + return new Function(functionString); + // Check for cache hit, eval if missing and return cached function + if (functionCache[functionString] == null) { + functionCache[functionString] = new Function(functionString); + } + // Set the object + return functionCache[functionString].bind(object); + } + function getValidatedString(buffer, start, end) { + var value = buffer.toString('utf8', start, end); + for (var i = 0; i < value.length; i++) { + if (value.charCodeAt(i) === 0xfffd) { + if (!validateUtf8(buffer, start, end)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + return value; + } + + // Copyright (c) 2008, Fair Oaks Labs, Inc. + function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) { + var e; + var m; + var c; + var bBE = endian === 'big'; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = bBE ? nBytes - 1 : 0; + var d = bBE ? -1 : 1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } + else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } + else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } + else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } + else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + if (isNaN(value)) + m = 0; + while (mLen >= 8) { + buffer[offset + i] = m & 0xff; + i += d; + m /= 256; + mLen -= 8; + } + e = (e << mLen) | m; + if (isNaN(value)) + e += 8; + eLen += mLen; + while (eLen > 0) { + buffer[offset + i] = e & 0xff; + i += d; + e /= 256; + eLen -= 8; + } + buffer[offset + i - d] |= s * 128; + } + + var regexp = /\x00/; // eslint-disable-line no-control-regex + var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); + /* + * isArray indicates if we are writing to a BSON array (type 0x04) + * which forces the "key" which really an array index as a string to be written as ascii + * This will catch any errors in index as a string generation + */ + function serializeString(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, undefined, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; + } + function serializeNumber(buffer, key, value, index, isArray) { + // We have an integer value + // TODO(NODE-2529): Add support for big int + if (Number.isInteger(value) && + value >= BSON_INT32_MIN && + value <= BSON_INT32_MAX) { + // If the value fits in 32 bits encode as int32 + // Set int type 32 bits or less + buffer[index++] = BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } + else { + // Encode as double + buffer[index++] = BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + } + return index; + } + function serializeNull(buffer, key, _, index, isArray) { + // Set long type + buffer[index++] = BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + } + function serializeBoolean(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + } + function serializeDate(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } + function serializeRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.ignoreCase) + buffer[index++] = 0x69; // i + if (value.global) + buffer[index++] = 0x73; // s + if (value.multiline) + buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } + function serializeBSONRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.pattern, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; + } + function serializeMinMax(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + } + function serializeObjectId(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, undefined, 'binary'); + } + else if (isUint8Array(value.id)) { + // Use the standard JS methods here because buffer.copy() is buggy with the + // browser polyfill + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + // Adjust index + return index + 12; + } + function serializeBuffer(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + buffer.set(ensureBuffer(value), index); + // Adjust the index + index = index + size; + return index; + } + function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (path === void 0) { path = []; } + for (var i = 0; i < path.length; i++) { + if (path[i] === value) + throw new BSONError('cyclic dependency detected'); + } + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + return endIndex; + } + function serializeDecimal128(buffer, key, value, index, isArray) { + buffer[index++] = BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + // Prefer the standard JS methods because their typechecking is not buggy, + // unlike the `buffer` polyfill's. + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; + } + function serializeLong(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } + function serializeInt32(buffer, key, value, index, isArray) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; + } + function serializeDouble(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value.value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + return index; + } + function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { + buffer[index++] = BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Starting index + var startIndex = index; + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + index = endIndex - 1; + // Writ the total + var totalSize = endIndex - startIndex; + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + return index; + } + function serializeBinary(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) + size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + // Write the data to the object + buffer.set(data, index); + // Adjust the index + index = index + value.position; + return index; + } + function serializeSymbol(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + } + function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var startIndex = index; + var output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; + } + function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (startingIndex === void 0) { startingIndex = 0; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (path === void 0) { path = []; } + startingIndex = startingIndex || 0; + path = path || []; + // Push the object to the path + path.push(object); + // Start place to serialize into + var index = startingIndex + 4; + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index, true); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } + else if (typeof value === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } + else if (typeof value === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } + else if (typeof value === 'object' && + isBSONType(value) && + value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + else if (object instanceof exports.Map || isMap(object)) { + var iterator = object.entries(); + var done = false; + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = !!entry.done; + // Are we done, then skip and terminate + if (done) + continue; + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new BSONTypeError('toBSON function did not return an object'); + } + // Iterate over all the keys + for (var key in object) { + var value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + // Remove the path + path.pop(); + // Final padding byte for object + buffer[index++] = 0x00; + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; + } + + /** @internal */ + // Default Max Size + var MAXSIZE = 1024 * 1024 * 17; + // Current Internal Temporary Serialization Buffer + var buffer = buffer_1.alloc(MAXSIZE); + /** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer + * @public + */ + function setInternalBufferSize(size) { + // Resize the internal serialization buffer if needed + if (buffer.length < size) { + buffer = buffer_1.alloc(size); + } + } + /** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ + function serialize(object, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = buffer_1.alloc(minInternalBufferSize); + } + // Attempt to serialize + var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = buffer_1.alloc(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; + } + /** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ + function serializeWithBufferAndIndex(object, finalBuffer, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + // Attempt to serialize + var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + // Return the index + return startIndex + serializationIndex - 1; + } + /** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ + function deserialize(buffer, options) { + if (options === void 0) { options = {}; } + return deserialize$1(buffer instanceof buffer_1 ? buffer : ensureBuffer(buffer), options); + } + /** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ + function calculateObjectSize(object, options) { + if (options === void 0) { options = {}; } + options = options || {}; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + return calculateObjectSize$1(object, serializeFunctions, ignoreUndefined); + } + /** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ + function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + var bufferData = ensureBuffer(data); + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + // Update options with index + internalOptions.index = index; + // Parse the document at this point + documents[docStartIndex + i] = deserialize$1(bufferData, internalOptions); + // Adjust index by the document size + index = index + size; + } + // Return object containing end index of parsing and list of documents + return index; + } + /** + * BSON default export + * @deprecated Please use named exports + * @privateRemarks + * We want to someday deprecate the default export, + * so none of the new TS types are being exported on the default + * @public + */ + var BSON = { + Binary: Binary, + Code: Code, + DBRef: DBRef, + Decimal128: Decimal128, + Double: Double, + Int32: Int32, + Long: Long, + UUID: UUID, + Map: exports.Map, + MaxKey: MaxKey, + MinKey: MinKey, + ObjectId: ObjectId, + ObjectID: ObjectId, + BSONRegExp: BSONRegExp, + BSONSymbol: BSONSymbol, + Timestamp: Timestamp, + EJSON: exports.EJSON, + setInternalBufferSize: setInternalBufferSize, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + deserialize: deserialize, + calculateObjectSize: calculateObjectSize, + deserializeStream: deserializeStream, + BSONError: BSONError, + BSONTypeError: BSONTypeError + }; + + exports.BSONError = BSONError; + exports.BSONRegExp = BSONRegExp; + exports.BSONSymbol = BSONSymbol; + exports.BSONTypeError = BSONTypeError; + exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = BSON_BINARY_SUBTYPE_BYTE_ARRAY; + exports.BSON_BINARY_SUBTYPE_COLUMN = BSON_BINARY_SUBTYPE_COLUMN; + exports.BSON_BINARY_SUBTYPE_DEFAULT = BSON_BINARY_SUBTYPE_DEFAULT; + exports.BSON_BINARY_SUBTYPE_ENCRYPTED = BSON_BINARY_SUBTYPE_ENCRYPTED; + exports.BSON_BINARY_SUBTYPE_FUNCTION = BSON_BINARY_SUBTYPE_FUNCTION; + exports.BSON_BINARY_SUBTYPE_MD5 = BSON_BINARY_SUBTYPE_MD5; + exports.BSON_BINARY_SUBTYPE_USER_DEFINED = BSON_BINARY_SUBTYPE_USER_DEFINED; + exports.BSON_BINARY_SUBTYPE_UUID = BSON_BINARY_SUBTYPE_UUID; + exports.BSON_BINARY_SUBTYPE_UUID_NEW = BSON_BINARY_SUBTYPE_UUID_NEW; + exports.BSON_DATA_ARRAY = BSON_DATA_ARRAY; + exports.BSON_DATA_BINARY = BSON_DATA_BINARY; + exports.BSON_DATA_BOOLEAN = BSON_DATA_BOOLEAN; + exports.BSON_DATA_CODE = BSON_DATA_CODE; + exports.BSON_DATA_CODE_W_SCOPE = BSON_DATA_CODE_W_SCOPE; + exports.BSON_DATA_DATE = BSON_DATA_DATE; + exports.BSON_DATA_DBPOINTER = BSON_DATA_DBPOINTER; + exports.BSON_DATA_DECIMAL128 = BSON_DATA_DECIMAL128; + exports.BSON_DATA_INT = BSON_DATA_INT; + exports.BSON_DATA_LONG = BSON_DATA_LONG; + exports.BSON_DATA_MAX_KEY = BSON_DATA_MAX_KEY; + exports.BSON_DATA_MIN_KEY = BSON_DATA_MIN_KEY; + exports.BSON_DATA_NULL = BSON_DATA_NULL; + exports.BSON_DATA_NUMBER = BSON_DATA_NUMBER; + exports.BSON_DATA_OBJECT = BSON_DATA_OBJECT; + exports.BSON_DATA_OID = BSON_DATA_OID; + exports.BSON_DATA_REGEXP = BSON_DATA_REGEXP; + exports.BSON_DATA_STRING = BSON_DATA_STRING; + exports.BSON_DATA_SYMBOL = BSON_DATA_SYMBOL; + exports.BSON_DATA_TIMESTAMP = BSON_DATA_TIMESTAMP; + exports.BSON_DATA_UNDEFINED = BSON_DATA_UNDEFINED; + exports.BSON_INT32_MAX = BSON_INT32_MAX; + exports.BSON_INT32_MIN = BSON_INT32_MIN; + exports.BSON_INT64_MAX = BSON_INT64_MAX; + exports.BSON_INT64_MIN = BSON_INT64_MIN; + exports.Binary = Binary; + exports.Code = Code; + exports.DBRef = DBRef; + exports.Decimal128 = Decimal128; + exports.Double = Double; + exports.Int32 = Int32; + exports.Long = Long; + exports.LongWithoutOverridesClass = LongWithoutOverridesClass; + exports.MaxKey = MaxKey; + exports.MinKey = MinKey; + exports.ObjectID = ObjectId; + exports.ObjectId = ObjectId; + exports.Timestamp = Timestamp; + exports.UUID = UUID; + exports.calculateObjectSize = calculateObjectSize; + exports.default = BSON; + exports.deserialize = deserialize; + exports.deserializeStream = deserializeStream; + exports.serialize = serialize; + exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; + exports.setInternalBufferSize = setInternalBufferSize; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +}({})); +//# sourceMappingURL=bson.bundle.js.map diff --git a/node_modules/bson/dist/bson.bundle.js.map b/node_modules/bson/dist/bson.bundle.js.map new file mode 100644 index 0000000..c256564 --- /dev/null +++ b/node_modules/bson/dist/bson.bundle.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.bundle.js","sources":["../node_modules/base64-js/index.js","../node_modules/ieee754/index.js","../node_modules/buffer/index.js","../node_modules/tslib/tslib.es6.js","../src/error.ts","../src/utils/global.ts","../src/parser/utils.ts","../src/ensure_buffer.ts","../src/uuid_utils.ts","../src/uuid.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/extended_json.ts","../src/map.ts","../src/constants.ts","../src/parser/calculate_size.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/float_parser.ts","../src/parser/serializer.ts","../src/bson.ts"],"sourcesContent":["'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n var proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n var copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n Buffer.from(buf).copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (var i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nvar hexSliceLookupTable = (function () {\n var alphabet = '0123456789abcdef'\n var table = new Array(256)\n for (var i = 0; i < 16; ++i) {\n var i16 = i * 16\n for (var j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["byteLength","toByteArray","fromByteArray","lookup","revLookup","Arr","Uint8Array","Array","code","i","len","length","charCodeAt","getLens","b64","Error","validLen","indexOf","placeHoldersLen","lens","_byteLength","tmp","arr","curByte","tripletToBase64","num","encodeChunk","uint8","start","end","output","push","join","extraBytes","parts","maxChunkLength","len2","buffer","offset","isLE","mLen","nBytes","e","m","eLen","eMax","eBias","nBits","d","s","NaN","Infinity","Math","pow","value","c","rt","abs","isNaN","floor","log","LN2","customInspectSymbol","Symbol","exports","Buffer","SlowBuffer","K_MAX_LENGTH","TYPED_ARRAY_SUPPORT","typedArraySupport","console","error","proto","foo","Object","setPrototypeOf","prototype","defineProperty","enumerable","get","isBuffer","undefined","byteOffset","createBuffer","RangeError","buf","arg","encodingOrOffset","TypeError","allocUnsafe","from","poolSize","fromString","ArrayBuffer","isView","fromArrayView","isInstance","fromArrayBuffer","SharedArrayBuffer","valueOf","b","fromObject","toPrimitive","assertSize","size","alloc","fill","encoding","checked","allocUnsafeSlow","string","isEncoding","actual","write","slice","fromArrayLike","array","arrayView","copy","obj","numberIsNaN","type","isArray","data","toString","_isBuffer","compare","a","x","y","min","String","toLowerCase","concat","list","pos","set","call","mustMatch","arguments","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","n","swap16","swap32","swap64","apply","toLocaleString","equals","inspect","str","max","INSPECT_MAX_BYTES","replace","trim","target","thisStart","thisEnd","thisCopy","targetCopy","bidirectionalIndexOf","val","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","includes","hexWrite","Number","remaining","strLen","parsed","parseInt","substr","utf8Write","blitBuffer","asciiWrite","asciiToBytes","base64Write","ucs2Write","utf16leToBytes","isFinite","toJSON","_arr","base64","res","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","decodeCodePointsArray","MAX_ARGUMENTS_LENGTH","codePoints","fromCharCode","ret","out","hexSliceLookupTable","bytes","newBuf","subarray","checkOffset","ext","readUintLE","readUIntLE","noAssert","mul","readUintBE","readUIntBE","readUint8","readUInt8","readUint16LE","readUInt16LE","readUint16BE","readUint32LE","readUInt32LE","readUint32BE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","ieee754","readFloatBE","readDoubleLE","readDoubleBE","checkInt","writeUintLE","writeUIntLE","maxBytes","writeUintBE","writeUIntBE","writeUint8","writeUInt8","writeUint16LE","writeUInt16LE","writeUint16BE","writeUInt16BE","writeUint32LE","writeUInt32LE","writeUint32BE","writeUInt32BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","checkIEEE754","writeFloat","littleEndian","writeFloatLE","writeFloatBE","writeDouble","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","INVALID_BASE64_RE","base64clean","split","units","leadSurrogate","byteArray","hi","lo","src","dst","constructor","name","alphabet","table","i16","extendStatics","__proto__","p","hasOwnProperty","__extends","__","create","kId","BSON_INT32_MAX","BSON_INT32_MIN","BSON_INT64_MAX","BSON_INT64_MIN","EJSON","bsonMap","calculateObjectSize","constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","deserialize","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT","Map","internalSerialize","internalDeserialize","internalCalculateObjectSize"],"mappings":";;;;;;;CAEA,gBAAkB,GAAGA,UAArB;CACA,iBAAmB,GAAGC,WAAtB;CACA,mBAAqB,GAAGC,aAAxB;CAEA,IAAIC,MAAM,GAAG,EAAb;CACA,IAAIC,SAAS,GAAG,EAAhB;CACA,IAAIC,GAAG,GAAG,OAAOC,UAAP,KAAsB,WAAtB,GAAoCA,UAApC,GAAiDC,KAA3D;CAEA,IAAIC,IAAI,GAAG,kEAAX;;CACA,KAAK,IAAIC,CAAC,GAAG,CAAR,EAAWC,GAAG,GAAGF,IAAI,CAACG,MAA3B,EAAmCF,CAAC,GAAGC,GAAvC,EAA4C,EAAED,CAA9C,EAAiD;CAC/CN,EAAAA,MAAM,CAACM,CAAD,CAAN,GAAYD,IAAI,CAACC,CAAD,CAAhB;CACAL,EAAAA,SAAS,CAACI,IAAI,CAACI,UAAL,CAAgBH,CAAhB,CAAD,CAAT,GAAgCA,CAAhC;CACD;CAGD;;;CACAL,SAAS,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ist/bson.esm.js new file mode 100644 index 0000000..0b6ae31 --- /dev/null +++ b/node_modules/bson/dist/bson.esm.js @@ -0,0 +1,5397 @@ +import { Buffer } from 'buffer'; + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +/* global Reflect, Promise */ +var _extendStatics = function extendStatics(d, b) { + _extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function (d, b) { + d.__proto__ = b; + } || function (d, b) { + for (var p in b) { + if (b.hasOwnProperty(p)) d[p] = b[p]; + } + }; + + return _extendStatics(d, b); +}; + +function __extends(d, b) { + _extendStatics(d, b); + + function __() { + this.constructor = d; + } + + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +/** @public */ +var BSONError = /** @class */ (function (_super) { + __extends(BSONError, _super); + function BSONError() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(BSONError.prototype, "name", { + get: function () { + return 'BSONError'; + }, + enumerable: false, + configurable: true + }); + return BSONError; +}(Error)); +/** @public */ +var BSONTypeError = /** @class */ (function (_super) { + __extends(BSONTypeError, _super); + function BSONTypeError() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(BSONTypeError.prototype, "name", { + get: function () { + return 'BSONTypeError'; + }, + enumerable: false, + configurable: true + }); + return BSONTypeError; +}(TypeError)); + +function checkForMath(potentialGlobal) { + // eslint-disable-next-line eqeqeq + return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; +} +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +function getGlobal() { + // eslint-disable-next-line no-undef + return (checkForMath(typeof globalThis === 'object' && globalThis) || + checkForMath(typeof window === 'object' && window) || + checkForMath(typeof self === 'object' && self) || + checkForMath(typeof global === 'object' && global) || + Function('return this')()); +} + +/** + * Normalizes our expected stringified form of a function across versions of node + * @param fn - The function to stringify + */ +function normalizedFunctionString(fn) { + return fn.toString().replace('function(', 'function ('); +} +function isReactNative() { + var g = getGlobal(); + return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; +} +var insecureRandomBytes = function insecureRandomBytes(size) { + var insecureWarning = isReactNative() + ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; + console.warn(insecureWarning); + var result = Buffer.alloc(size); + for (var i = 0; i < size; ++i) + result[i] = Math.floor(Math.random() * 256); + return result; +}; +var detectRandomBytes = function () { + if (typeof window !== 'undefined') { + // browser crypto implementation(s) + var target_1 = window.crypto || window.msCrypto; // allow for IE11 + if (target_1 && target_1.getRandomValues) { + return function (size) { return target_1.getRandomValues(Buffer.alloc(size)); }; + } + } + if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { + // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global + return function (size) { return global.crypto.getRandomValues(Buffer.alloc(size)); }; + } + var requiredRandomBytes; + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + requiredRandomBytes = require('crypto').randomBytes; + } + catch (e) { + // keep the fallback + } + // NOTE: in transpiled cases the above require might return null/undefined + return requiredRandomBytes || insecureRandomBytes; +}; +var randomBytes = detectRandomBytes(); +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isBigInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigInt64Array]'; +} +function isBigUInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigUint64Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +// To ensure that 0.4 of node works correctly +function isDate(d) { + return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; +} +/** + * @internal + * this is to solve the `'someKey' in x` problem where x is unknown. + * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 + */ +function isObjectLike(candidate) { + return typeof candidate === 'object' && candidate !== null; +} +function deprecate(fn, message) { + var warned = false; + function deprecated() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!warned) { + console.warn(message); + warned = true; + } + return fn.apply(this, args); + } + return deprecated; +} + +/** + * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. + * + * @param potentialBuffer - The potential buffer + * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that + * wraps a passed in Uint8Array + * @throws TypeError If anything other than a Buffer or Uint8Array is passed in + */ +function ensureBuffer(potentialBuffer) { + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + if (isAnyArrayBuffer(potentialBuffer)) { + return Buffer.from(potentialBuffer); + } + throw new BSONTypeError('Must use either Buffer or TypedArray'); +} + +// Validation regex for v4 uuid (validates with or without dashes) +var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; +var uuidValidateString = function (str) { + return typeof str === 'string' && VALIDATION_REGEX.test(str); +}; +var uuidHexStringToBuffer = function (hexString) { + if (!uuidValidateString(hexString)) { + throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); + } + var sanitizedHexString = hexString.replace(/-/g, ''); + return Buffer.from(sanitizedHexString, 'hex'); +}; +var bufferToUuidHexString = function (buffer, includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + return includeDashes + ? buffer.toString('hex', 0, 4) + + '-' + + buffer.toString('hex', 4, 6) + + '-' + + buffer.toString('hex', 6, 8) + + '-' + + buffer.toString('hex', 8, 10) + + '-' + + buffer.toString('hex', 10, 16) + : buffer.toString('hex'); +}; + +var BYTE_LENGTH = 16; +var kId$1 = Symbol('id'); +/** + * A class representation of the BSON UUID type. + * @public + */ +var UUID = /** @class */ (function () { + /** + * Create an UUID type + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + function UUID(input) { + if (typeof input === 'undefined') { + // The most common use case (blank id, new UUID() instance) + this.id = UUID.generate(); + } + else if (input instanceof UUID) { + this[kId$1] = Buffer.from(input.id); + this.__id = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { + this.id = ensureBuffer(input); + } + else if (typeof input === 'string') { + this.id = uuidHexStringToBuffer(input); + } + else { + throw new BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); + } + } + Object.defineProperty(UUID.prototype, "id", { + /** + * The UUID bytes + * @readonly + */ + get: function () { + return this[kId$1]; + }, + set: function (value) { + this[kId$1] = value; + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + }, + enumerable: false, + configurable: true + }); + /** + * Generate a 16 byte uuid v4 buffer used in UUIDs + */ + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + * */ + UUID.prototype.toHexString = function (includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + var uuidHexString = bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + }; + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + UUID.prototype.toString = function (encoding) { + return encoding ? this.id.toString(encoding) : this.toHexString(); + }; + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + UUID.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + UUID.prototype.equals = function (otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return otherId.id.equals(this.id); + } + try { + return new UUID(otherId).id.equals(this.id); + } + catch (_a) { + return false; + } + }; + /** + * Creates a Binary instance from the current UUID. + */ + UUID.prototype.toBinary = function () { + return new Binary(this.id, Binary.SUBTYPE_UUID); + }; + /** + * Generates a populated buffer containing a v4 uuid + */ + UUID.generate = function () { + var bytes = randomBytes(BYTE_LENGTH); + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return Buffer.from(bytes); + }; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + UUID.isValid = function (input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuidValidateString(input); + } + if (isUint8Array(input)) { + // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) + if (input.length !== BYTE_LENGTH) { + return false; + } + try { + // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx + // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx + return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID; + } + catch (_a) { + return false; + } + } + return false; + }; + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + UUID.createFromHexString = function (hexString) { + var buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 36 character hex string representation. + * @internal + */ + UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + UUID.prototype.inspect = function () { + return "new UUID(\"" + this.toHexString() + "\")"; + }; + return UUID; +}()); +Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); + +/** + * A class representation of the BSON Binary type. + * @public + */ +var Binary = /** @class */ (function () { + /** + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) + return new Binary(buffer, subType); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + // create an empty binary buffer + this.buffer = Buffer.alloc(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + // string + this.buffer = Buffer.from(buffer, 'binary'); + } + else if (Array.isArray(buffer)) { + // number[] + this.buffer = Buffer.from(buffer); + } + else { + // Buffer | TypedArray | ArrayBuffer + this.buffer = ensureBuffer(buffer); + } + this.position = this.buffer.byteLength; + } + } + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + Binary.prototype.put = function (byteValue) { + // If it's a string and a has more than one character throw an error + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONTypeError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONTypeError('only accepts single character Uint8Array or Array'); + // Decode the byte value once + var decodedByte; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } + else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } + else { + decodedByte = byteValue[0]; + } + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + var buffer = Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decodedByte; + } + }; + /** + * Writes a buffer or string to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + Binary.prototype.write = function (sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + sequence.length) { + var buffer = Buffer.alloc(this.buffer.length + sequence.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + // Assign the new buffer + this.buffer = buffer; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ensureBuffer(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + this.buffer.write(sequence, offset, sequence.length, 'binary'); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + }; + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + Binary.prototype.read = function (position, length) { + length = length && length > 0 ? length : this.position; + // Let's return the data based on the type we have + return this.buffer.slice(position, position + length); + }; + /** + * Returns the value of this binary as a string. + * @param asRaw - Will skip converting to a string + * @remarks + * This is handy when calling this function conditionally for some key value pairs and not others + */ + Binary.prototype.value = function (asRaw) { + asRaw = !!asRaw; + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + // If it's a node.js buffer object + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return this.buffer.toString('binary', 0, this.position); + }; + /** the length of the binary sequence */ + Binary.prototype.length = function () { + return this.position; + }; + Binary.prototype.toJSON = function () { + return this.buffer.toString('base64'); + }; + Binary.prototype.toString = function (format) { + return this.buffer.toString(format); + }; + /** @internal */ + Binary.prototype.toExtendedJSON = function (options) { + options = options || {}; + var base64String = this.buffer.toString('base64'); + var subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + }; + Binary.prototype.toUUID = function () { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID(this.buffer.slice(0, this.position)); + } + throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); + }; + /** @internal */ + Binary.fromExtendedJSON = function (doc, options) { + options = options || {}; + var data; + var type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = Buffer.from(doc.$binary, 'base64'); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = Buffer.from(doc.$binary.base64, 'base64'); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); + } + return new Binary(data, type); + }; + /** @internal */ + Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Binary.prototype.inspect = function () { + var asBuffer = this.value(true); + return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; + }; + /** + * Binary default subtype + * @internal + */ + Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** Initial buffer default size */ + Binary.BUFFER_SIZE = 256; + /** Default BSON type */ + Binary.SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + Binary.SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + Binary.SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + Binary.SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + Binary.SUBTYPE_UUID = 4; + /** MD5 BSON type */ + Binary.SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + Binary.SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + Binary.SUBTYPE_COLUMN = 7; + /** User BSON type */ + Binary.SUBTYPE_USER_DEFINED = 128; + return Binary; +}()); +Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); + +/** + * A class representation of the BSON Code type. + * @public + */ +var Code = /** @class */ (function () { + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + function Code(code, scope) { + if (!(this instanceof Code)) + return new Code(code, scope); + this.code = code; + this.scope = scope; + } + Code.prototype.toJSON = function () { + return { code: this.code, scope: this.scope }; + }; + /** @internal */ + Code.prototype.toExtendedJSON = function () { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + }; + /** @internal */ + Code.fromExtendedJSON = function (doc) { + return new Code(doc.$code, doc.$scope); + }; + /** @internal */ + Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Code.prototype.inspect = function () { + var codeJson = this.toJSON(); + return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; + }; + return Code; +}()); +Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); + +/** @internal */ +function isDBRefLike(value) { + return (isObjectLike(value) && + value.$id != null && + typeof value.$ref === 'string' && + (value.$db == null || typeof value.$db === 'string')); +} +/** + * A class representation of the BSON DBRef type. + * @public + */ +var DBRef = /** @class */ (function () { + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + function DBRef(collection, oid, db, fields) { + if (!(this instanceof DBRef)) + return new DBRef(collection, oid, db, fields); + // check if namespace has been provided + var parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + Object.defineProperty(DBRef.prototype, "namespace", { + // Property provided for compatibility with the 1.x parser + // the 1.x parser used a "namespace" property, while 4.x uses "collection" + /** @internal */ + get: function () { + return this.collection; + }, + set: function (value) { + this.collection = value; + }, + enumerable: false, + configurable: true + }); + DBRef.prototype.toJSON = function () { + var o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + }; + /** @internal */ + DBRef.prototype.toExtendedJSON = function (options) { + options = options || {}; + var o = { + $ref: this.collection, + $id: this.oid + }; + if (options.legacy) { + return o; + } + if (this.db) + o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + }; + /** @internal */ + DBRef.fromExtendedJSON = function (doc) { + var copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + }; + /** @internal */ + DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + DBRef.prototype.inspect = function () { + // NOTE: if OID is an ObjectId class it will just print the oid string. + var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); + return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; + }; + return DBRef; +}()); +Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); + +/** + * wasm optimizations, to do native i64 multiplication and divide + */ +var wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module( + // prettier-ignore + new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; +} +catch (_a) { + // no wasm support +} +var TWO_PWR_16_DBL = 1 << 16; +var TWO_PWR_24_DBL = 1 << 24; +var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +/** A cache of the Long representations of small integer values. */ +var INT_CACHE = {}; +/** A cache of the Long representations of small unsigned integer values. */ +var UINT_CACHE = {}; +/** + * A class representing a 64-bit integer + * @public + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ +var Long = /** @class */ (function () { + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + function Long(low, high, unsigned) { + if (low === void 0) { low = 0; } + if (!(this instanceof Long)) + return new Long(low, high, unsigned); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } + else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } + else { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + Object.defineProperty(this, '__isLong__', { + value: true, + configurable: false, + writable: false, + enumerable: false + }); + } + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBits = function (lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + }; + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromInt = function (value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } + else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromNumber = function (value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; + } + else { + if (value <= -TWO_PWR_63_DBL) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBigInt = function (value, unsigned) { + return Long.fromString(value.toString(), unsigned); + }; + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + Long.fromString = function (str, unsigned, radix) { + if (str.length === 0) + throw Error('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + var p; + if ((p = str.indexOf('-')) > 0) + throw Error('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } + else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + }; + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + Long.fromBytes = function (bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + }; + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesLE = function (bytes, unsigned) { + return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); + }; + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesBE = function (bytes, unsigned) { + return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); + }; + /** + * Tests if the specified object is a Long. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + Long.isLong = function (value) { + return isObjectLike(value) && value['__isLong__'] === true; + }; + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + Long.fromValue = function (val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + }; + /** Returns the sum of this and the specified Long. */ + Long.prototype.add = function (addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xffff; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + Long.prototype.and = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + }; + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + Long.prototype.compare = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + // At this point the sign bits are the same + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + }; + /** This is an alias of {@link Long.compare} */ + Long.prototype.comp = function (other) { + return this.compare(other); + }; + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + Long.prototype.divide = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw Error('division by zero'); + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + // be consistent with non-wasm code path + return this; + } + var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + var approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } + else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } + else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } + else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } + else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return Long.UONE; + res = Long.UZERO; + } + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + }; + /**This is an alias of {@link Long.divide} */ + Long.prototype.div = function (divisor) { + return this.divide(divisor); + }; + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + Long.prototype.equals = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + }; + /** This is an alias of {@link Long.equals} */ + Long.prototype.eq = function (other) { + return this.equals(other); + }; + /** Gets the high 32 bits as a signed integer. */ + Long.prototype.getHighBits = function () { + return this.high; + }; + /** Gets the high 32 bits as an unsigned integer. */ + Long.prototype.getHighBitsUnsigned = function () { + return this.high >>> 0; + }; + /** Gets the low 32 bits as a signed integer. */ + Long.prototype.getLowBits = function () { + return this.low; + }; + /** Gets the low 32 bits as an unsigned integer. */ + Long.prototype.getLowBitsUnsigned = function () { + return this.low >>> 0; + }; + /** Gets the number of bits needed to represent the absolute value of this Long. */ + Long.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + // Unsigned Longs are never negative + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + var val = this.high !== 0 ? this.high : this.low; + var bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + }; + /** Tests if this Long's value is greater than the specified's. */ + Long.prototype.greaterThan = function (other) { + return this.comp(other) > 0; + }; + /** This is an alias of {@link Long.greaterThan} */ + Long.prototype.gt = function (other) { + return this.greaterThan(other); + }; + /** Tests if this Long's value is greater than or equal the specified's. */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.comp(other) >= 0; + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.gte = function (other) { + return this.greaterThanOrEqual(other); + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.ge = function (other) { + return this.greaterThanOrEqual(other); + }; + /** Tests if this Long's value is even. */ + Long.prototype.isEven = function () { + return (this.low & 1) === 0; + }; + /** Tests if this Long's value is negative. */ + Long.prototype.isNegative = function () { + return !this.unsigned && this.high < 0; + }; + /** Tests if this Long's value is odd. */ + Long.prototype.isOdd = function () { + return (this.low & 1) === 1; + }; + /** Tests if this Long's value is positive. */ + Long.prototype.isPositive = function () { + return this.unsigned || this.high >= 0; + }; + /** Tests if this Long's value equals zero. */ + Long.prototype.isZero = function () { + return this.high === 0 && this.low === 0; + }; + /** Tests if this Long's value is less than the specified's. */ + Long.prototype.lessThan = function (other) { + return this.comp(other) < 0; + }; + /** This is an alias of {@link Long#lessThan}. */ + Long.prototype.lt = function (other) { + return this.lessThan(other); + }; + /** Tests if this Long's value is less than or equal the specified's. */ + Long.prototype.lessThanOrEqual = function (other) { + return this.comp(other) <= 0; + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.lte = function (other) { + return this.lessThanOrEqual(other); + }; + /** Returns this Long modulo the specified. */ + Long.prototype.modulo = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + // use wasm support if present + if (wasm) { + var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.mod = function (divisor) { + return this.modulo(divisor); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.rem = function (divisor) { + return this.modulo(divisor); + }; + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + Long.prototype.multiply = function (multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + // use wasm support if present + if (wasm) { + var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } + else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + // If both longs are small, use float multiplication + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xffff; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** This is an alias of {@link Long.multiply} */ + Long.prototype.mul = function (multiplier) { + return this.multiply(multiplier); + }; + /** Returns the Negation of this Long's value. */ + Long.prototype.negate = function () { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + }; + /** This is an alias of {@link Long.negate} */ + Long.prototype.neg = function () { + return this.negate(); + }; + /** Returns the bitwise NOT of this Long. */ + Long.prototype.not = function () { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + }; + /** Tests if this Long's value differs from the specified's. */ + Long.prototype.notEquals = function (other) { + return !this.equals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.neq = function (other) { + return this.notEquals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.ne = function (other) { + return this.notEquals(other); + }; + /** + * Returns the bitwise OR of this Long and the specified. + */ + Long.prototype.or = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + }; + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftLeft = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + }; + /** This is an alias of {@link Long.shiftLeft} */ + Long.prototype.shl = function (numBits) { + return this.shiftLeft(numBits); + }; + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRight = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + }; + /** This is an alias of {@link Long.shiftRight} */ + Long.prototype.shr = function (numBits) { + return this.shiftRight(numBits); + }; + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRightUnsigned = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + var high = this.high; + if (numBits < 32) { + var low = this.low; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); + } + else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shr_u = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shru = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + Long.prototype.subtract = function (subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + /** This is an alias of {@link Long.subtract} */ + Long.prototype.sub = function (subtrahend) { + return this.subtract(subtrahend); + }; + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + Long.prototype.toInt = function () { + return this.unsigned ? this.low >>> 0 : this.low; + }; + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + Long.prototype.toNumber = function () { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + /** Converts the Long to a BigInt (arbitrary precision). */ + Long.prototype.toBigInt = function () { + return BigInt(this.toString()); + }; + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + Long.prototype.toBytes = function (le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + Long.prototype.toBytesLE = function () { + var hi = this.high, lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + }; + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + Long.prototype.toBytesBE = function () { + var hi = this.high, lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + }; + /** + * Converts this Long to signed. + */ + Long.prototype.toSigned = function () { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + }; + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + Long.prototype.toString = function (radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + // Unsigned Longs are never negative + if (this.eq(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } + else + return '-' + this.neg().toString(radix); + } + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + // eslint-disable-next-line @typescript-eslint/no-this-alias + var rem = this; + var result = ''; + // eslint-disable-next-line no-constant-condition + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + var digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } + }; + /** Converts this Long to unsigned. */ + Long.prototype.toUnsigned = function () { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + }; + /** Returns the bitwise XOR of this Long and the given one. */ + Long.prototype.xor = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + }; + /** This is an alias of {@link Long.isZero} */ + Long.prototype.eqz = function () { + return this.isZero(); + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.le = function (other) { + return this.lessThanOrEqual(other); + }; + /* + **************************************************************** + * BSON SPECIFIC ADDITIONS * + **************************************************************** + */ + Long.prototype.toExtendedJSON = function (options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + }; + Long.fromExtendedJSON = function (doc, options) { + var result = Long.fromString(doc.$numberLong); + return options && options.relaxed ? result.toNumber() : result; + }; + /** @internal */ + Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Long.prototype.inspect = function () { + return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")"; + }; + Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); + /** Maximum unsigned value. */ + Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); + /** Signed zero */ + Long.ZERO = Long.fromInt(0); + /** Unsigned zero. */ + Long.UZERO = Long.fromInt(0, true); + /** Signed one. */ + Long.ONE = Long.fromInt(1); + /** Unsigned one. */ + Long.UONE = Long.fromInt(1, true); + /** Signed negative one. */ + Long.NEG_ONE = Long.fromInt(-1); + /** Maximum signed value. */ + Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + /** Minimum signed value. */ + Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + return Long; +}()); +Object.defineProperty(Long.prototype, '__isLong__', { value: true }); +Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); + +var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; +var EXPONENT_MAX = 6111; +var EXPONENT_MIN = -6176; +var EXPONENT_BIAS = 6176; +var MAX_DIGITS = 34; +// Nan value bits as 32 bit values (due to lack of longs) +var NAN_BUFFER = [ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +var INF_NEGATIVE_BUFFER = [ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +var INF_POSITIVE_BUFFER = [ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +var EXPONENT_REGEX = /^([-+])?(\d+)?$/; +// Extract least significant 5 bits +var COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +var EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +var COMBINATION_INFINITY = 30; +// Value of combination field for NaN +var COMBINATION_NAN = 31; +// Detect if the value is a digit +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +// Divide two uint128 values +function divideu128(value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + for (var i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + return { quotient: value, rem: _rem }; +} +// Multiply two Long values and return the 128 bit value +function multiply64x2(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + // Return the 128 bit result + return { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + // Make values unsigned + var uhleft = left.high >>> 0; + var uhright = right.high >>> 0; + // Compare high bits first + if (uhleft < uhright) { + return true; + } + else if (uhleft === uhright) { + var ulleft = left.low >>> 0; + var ulright = right.low >>> 0; + if (ulleft < ulright) + return true; + } + return false; +} +function invalidErr(string, message) { + throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); +} +/** + * A class representation of the BSON Decimal128 type. + * @public + */ +var Decimal128 = /** @class */ (function () { + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + function Decimal128(bytes) { + if (!(this instanceof Decimal128)) + return new Decimal128(bytes); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else { + this.bytes = bytes; + } + } + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + Decimal128.fromString = function (representation) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = new Long(0, 0); + // The low 17 digits of the significand + var significandLow = new Long(0, 0); + // The biased exponent + var biasedExponent = 0; + // Read index + var index = 0; + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (representation.length >= 7000) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + // Results + var stringMatch = representation.match(PARSE_STRING_REGEXP); + var infMatch = representation.match(PARSE_INF_REGEXP); + var nanMatch = representation.match(PARSE_NAN_REGEXP); + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + // full_match = stringMatch[0] + // sign = stringMatch[1] + var unsignedNumber = stringMatch[2]; + // stringMatch[3] is undefined if a whole number (ex "1", 12") + // but defined if a number w/ decimal in it (ex "1.0, 12.2") + var e = stringMatch[4]; + var expSign = stringMatch[5]; + var expNumber = stringMatch[6]; + // they provided e, but didn't give an exponent number. for ex "1e" + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + // they provided e, but didn't give a number before it. for ex "e1" + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + // Get the negative or positive sign + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + // Check if user passed Infinity or NaN + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + else if (representation[index] === 'N') { + return new Decimal128(Buffer.from(NAN_BUFFER)); + } + } + // Read all the digits + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) + invalidErr(representation, 'contains multiple periods'); + sawRadix = true; + index = index + 1; + continue; + } + if (nDigitsStored < 34) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + // Only store 34 digits + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + if (sawRadix && !nDigitsRead) + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + // Read exponent if exists + if (representation[index] === 'e' || representation[index] === 'E') { + // Read exponent digits + var match = representation.substr(++index).match(EXPONENT_REGEX); + // No digits read + if (!match || !match[2]) + return new Decimal128(Buffer.from(NAN_BUFFER)); + // Get exponent + exponent = parseInt(match[0], 10); + // Adjust the index + index = index + match[0].length; + } + // Return not a number + if (representation[index]) + return new Decimal128(Buffer.from(NAN_BUFFER)); + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } + else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (digits[firstNonZero + significantDigits - 1] === 0) { + significantDigits = significantDigits - 1; + } + } + } + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit. can only do this if < significant digits than # stored. + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } + else { + // adjust to round + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits) { + var endOfString = nDigitsRead; + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + // if negative, we need to increment again to account for - sign at start. + if (isNegative) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + if (roundBit) { + var dIdx = lastDigit; + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + } + } + } + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } + else if (lastDigit - firstDigit < 17) { + var dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + else { + var dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + significandLow = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + // Encode combination, exponent, and significand. + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } + else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + dec.low = significand.low; + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + // Encode into a buffer + var buffer = Buffer.alloc(16); + index = 0; + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + // Return the new Decimal128 + return new Decimal128(buffer); + }; + /** Create a string representation of the raw Decimal128 value */ + Decimal128.prototype.toString = function () { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) + significand[i] = 0; + // read pointer into significand + var index = 0; + // true if the number is zero + var is_zero = false; + // the most significant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: [0, 0, 0, 0] }; + // indexing variables + var j, k; + // Output string + var string = []; + // Unpack index + index = 0; + // Buffer reference + var buffer = this.bytes; + // Unpack the low 64bits into a long + // bits 96 - 127 + var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 64 - 95 + var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack the high 64bits into a long + // bits 32 - 63 + var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 0 - 31 + var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack index + index = 0; + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + // Decode combination field and exponent + // bits 1 - 5 + var combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } + else if (combination === COMBINATION_NAN) { + return 'NaN'; + } + else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } + else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + // unbiased exponent + var exponent = biased_exponent - EXPONENT_BIAS; + // Create string of significand digits + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + if (significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0) { + is_zero = true; + } + else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Perform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + // the exponent if scientific notation is used + var scientific_exponent = significand_digits - 1 + exponent; + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + // if there are too many significant digits, we should just be treating numbers + // as + or - 0 and using the non-scientific exponent (this is for the "invalid + // representation should be treated as 0/-0" spec cases in decimal128-1.json) + if (significand_digits > 34) { + string.push("" + 0); + if (exponent > 0) + string.push('E+' + exponent); + else if (exponent < 0) + string.push('E' + exponent); + return string.join(''); + } + string.push("" + significand[index++]); + significand_digits = significand_digits - 1; + if (significand_digits) { + string.push('.'); + } + for (var i = 0; i < significand_digits; i++) { + string.push("" + significand[index++]); + } + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } + else { + string.push("" + scientific_exponent); + } + } + else { + // Regular format with no decimal place + if (exponent >= 0) { + for (var i = 0; i < significand_digits; i++) { + string.push("" + significand[index++]); + } + } + else { + var radix_position = significand_digits + exponent; + // non-zero digits before radix + if (radix_position > 0) { + for (var i = 0; i < radix_position; i++) { + string.push("" + significand[index++]); + } + } + else { + string.push('0'); + } + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push("" + significand[index++]); + } + } + } + return string.join(''); + }; + Decimal128.prototype.toJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.prototype.toExtendedJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.fromExtendedJSON = function (doc) { + return Decimal128.fromString(doc.$numberDecimal); + }; + /** @internal */ + Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Decimal128.prototype.inspect = function () { + return "new Decimal128(\"" + this.toString() + "\")"; + }; + return Decimal128; +}()); +Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); + +/** + * A class representation of the BSON Double type. + * @public + */ +var Double = /** @class */ (function () { + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + function Double(value) { + if (!(this instanceof Double)) + return new Double(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + Double.prototype.valueOf = function () { + return this.value; + }; + Double.prototype.toJSON = function () { + return this.value; + }; + Double.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + /** @internal */ + Double.prototype.toExtendedJSON = function (options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user + // explicitly provided `-0` then we need to ensure the sign makes it into the output + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: "-" + this.value.toFixed(1) }; + } + var $numberDouble; + if (Number.isInteger(this.value)) { + $numberDouble = this.value.toFixed(1); + if ($numberDouble.length >= 13) { + $numberDouble = this.value.toExponential(13).toUpperCase(); + } + } + else { + $numberDouble = this.value.toString(); + } + return { $numberDouble: $numberDouble }; + }; + /** @internal */ + Double.fromExtendedJSON = function (doc, options) { + var doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + }; + /** @internal */ + Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Double.prototype.inspect = function () { + var eJSON = this.toExtendedJSON(); + return "new Double(" + eJSON.$numberDouble + ")"; + }; + return Double; +}()); +Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); + +/** + * A class representation of a BSON Int32 type. + * @public + */ +var Int32 = /** @class */ (function () { + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + function Int32(value) { + if (!(this instanceof Int32)) + return new Int32(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { + return this.value; + }; + Int32.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + Int32.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + Int32.prototype.toExtendedJSON = function (options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + }; + /** @internal */ + Int32.fromExtendedJSON = function (doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + }; + /** @internal */ + Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Int32.prototype.inspect = function () { + return "new Int32(" + this.valueOf() + ")"; + }; + return Int32; +}()); +Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); + +/** + * A class representation of the BSON MaxKey type. + * @public + */ +var MaxKey = /** @class */ (function () { + function MaxKey() { + if (!(this instanceof MaxKey)) + return new MaxKey(); + } + /** @internal */ + MaxKey.prototype.toExtendedJSON = function () { + return { $maxKey: 1 }; + }; + /** @internal */ + MaxKey.fromExtendedJSON = function () { + return new MaxKey(); + }; + /** @internal */ + MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MaxKey.prototype.inspect = function () { + return 'new MaxKey()'; + }; + return MaxKey; +}()); +Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); + +/** + * A class representation of the BSON MinKey type. + * @public + */ +var MinKey = /** @class */ (function () { + function MinKey() { + if (!(this instanceof MinKey)) + return new MinKey(); + } + /** @internal */ + MinKey.prototype.toExtendedJSON = function () { + return { $minKey: 1 }; + }; + /** @internal */ + MinKey.fromExtendedJSON = function () { + return new MinKey(); + }; + /** @internal */ + MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MinKey.prototype.inspect = function () { + return 'new MinKey()'; + }; + return MinKey; +}()); +Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +// Unique sequence for the current process (initialized on first use) +var PROCESS_UNIQUE = null; +var kId = Symbol('id'); +/** + * A class representation of the BSON ObjectId type. + * @public + */ +var ObjectId = /** @class */ (function () { + /** + * Create an ObjectId type + * + * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number. + */ + function ObjectId(id) { + if (!(this instanceof ObjectId)) + return new ObjectId(id); + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectId) { + this[kId] = id.id; + this.__id = id.__id; + } + if (typeof id === 'object' && id && 'id' in id) { + if ('toHexString' in id && typeof id.toHexString === 'function') { + this[kId] = Buffer.from(id.toHexString(), 'hex'); + } + else { + this[kId] = typeof id.id === 'string' ? Buffer.from(id.id) : id.id; + } + } + // The most common use case (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined); + // If we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + if (ArrayBuffer.isView(id) && id.byteLength === 12) { + this[kId] = ensureBuffer(id); + } + if (typeof id === 'string') { + if (id.length === 12) { + var bytes = Buffer.from(id); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + } + else if (id.length === 24 && checkForHexRegExp.test(id)) { + this[kId] = Buffer.from(id, 'hex'); + } + else { + throw new BSONTypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters'); + } + } + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + Object.defineProperty(ObjectId.prototype, "id", { + /** + * The ObjectId bytes + * @readonly + */ + get: function () { + return this[kId]; + }, + set: function (value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = value.toString('hex'); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ObjectId.prototype, "generationTime", { + /** + * The generation time of this ObjectId instance + * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch + */ + get: function () { + return this.id.readInt32BE(0); + }, + set: function (value) { + // Encode time into first 4 bytes + this.id.writeUInt32BE(value, 0); + }, + enumerable: false, + configurable: true + }); + /** Returns the ObjectId id as a 24 character hex string representation */ + ObjectId.prototype.toHexString = function () { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + var hexString = this.id.toString('hex'); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + }; + /** + * Update the ObjectId index + * @privateRemarks + * Used in generating new ObjectId's on the driver + * @internal + */ + ObjectId.getInc = function () { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + }; + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + ObjectId.generate = function (time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + var inc = ObjectId.getInc(); + var buffer = Buffer.alloc(12); + // 4-byte timestamp + buffer.writeUInt32BE(time, 0); + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = randomBytes(5); + } + // 5-byte process unique + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + // 3-byte counter + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + }; + /** + * Converts the id into a 24 character hex string for printing + * + * @param format - The Buffer toString format parameter. + */ + ObjectId.prototype.toString = function (format) { + // Is the id a buffer then use the buffer toString method to return the format + if (format) + return this.id.toString(format); + return this.toHexString(); + }; + /** Converts to its JSON the 24 character hex string representation. */ + ObjectId.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + ObjectId.prototype.equals = function (otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this.toString() === otherId.toString(); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id)) { + return otherId === Buffer.prototype.toString.call(this.id, 'latin1'); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { + return Buffer.from(otherId).equals(this.id); + } + if (typeof otherId === 'object' && + 'toHexString' in otherId && + typeof otherId.toHexString === 'function') { + return otherId.toHexString() === this.toHexString(); + } + return false; + }; + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + ObjectId.prototype.getTimestamp = function () { + var timestamp = new Date(); + var time = this.id.readUInt32BE(0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + }; + /** @internal */ + ObjectId.createPk = function () { + return new ObjectId(); + }; + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + ObjectId.createFromTime = function (time) { + var buffer = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer.writeUInt32BE(time, 0); + // Return the new objectId + return new ObjectId(buffer); + }; + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + ObjectId.createFromHexString = function (hexString) { + // Throw an error if it's not a valid setup + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(Buffer.from(hexString, 'hex')); + }; + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + ObjectId.isValid = function (id) { + if (id == null) + return false; + if (typeof id === 'number') { + return true; + } + if (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); + } + if (id instanceof ObjectId) { + return true; + } + if (isUint8Array(id) && id.length === 12) { + return true; + } + // Duck-Typing detection of ObjectId like objects + if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { + if (typeof id.id === 'string') { + return id.id.length === 12; + } + return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); + } + return false; + }; + /** @internal */ + ObjectId.prototype.toExtendedJSON = function () { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + }; + /** @internal */ + ObjectId.fromExtendedJSON = function (doc) { + return new ObjectId(doc.$oid); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 24 character hex string representation. + * @internal + */ + ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + ObjectId.prototype.inspect = function () { + return "new ObjectId(\"" + this.toHexString() + "\")"; + }; + /** @internal */ + ObjectId.index = ~~(Math.random() * 0xffffff); + return ObjectId; +}()); +// Deprecated methods +Object.defineProperty(ObjectId.prototype, 'generate', { + value: deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') +}); +Object.defineProperty(ObjectId.prototype, 'getInc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId.prototype, 'get_inc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId, 'get_inc', { + value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); + +function alphabetize(str) { + return str.split('').sort().join(''); +} +/** + * A class representation of the BSON RegExp type. + * @public + */ +var BSONRegExp = /** @class */ (function () { + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) + return new BSONRegExp(pattern, options); + this.pattern = pattern; + this.options = alphabetize(options !== null && options !== void 0 ? options : ''); + if (this.pattern.indexOf('\x00') !== -1) { + throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); + } + if (this.options.indexOf('\x00') !== -1) { + throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); + } + // Validate options + for (var i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u')) { + throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported"); + } + } + } + BSONRegExp.parseOptions = function (options) { + return options ? options.split('').sort().join('') : ''; + }; + /** @internal */ + BSONRegExp.prototype.toExtendedJSON = function (options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + }; + /** @internal */ + BSONRegExp.fromExtendedJSON = function (doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + // This is for $regex query operators that have extended json values. + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc; + } + } + else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); + } + throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); + }; + return BSONRegExp; +}()); +Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); + +/** + * A class representation of the BSON Symbol type. + * @public + */ +var BSONSymbol = /** @class */ (function () { + /** + * @param value - the string representing the symbol. + */ + function BSONSymbol(value) { + if (!(this instanceof BSONSymbol)) + return new BSONSymbol(value); + this.value = value; + } + /** Access the wrapped string value. */ + BSONSymbol.prototype.valueOf = function () { + return this.value; + }; + BSONSymbol.prototype.toString = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.inspect = function () { + return "new BSONSymbol(\"" + this.value + "\")"; + }; + BSONSymbol.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.toExtendedJSON = function () { + return { $symbol: this.value }; + }; + /** @internal */ + BSONSymbol.fromExtendedJSON = function (doc) { + return new BSONSymbol(doc.$symbol); + }; + /** @internal */ + BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + return BSONSymbol; +}()); +Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); + +/** @public */ +var LongWithoutOverridesClass = Long; +/** @public */ +var Timestamp = /** @class */ (function (_super) { + __extends(Timestamp, _super); + function Timestamp(low, high) { + var _this = this; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + ///@ts-expect-error + if (!(_this instanceof Timestamp)) + return new Timestamp(low, high); + if (Long.isLong(low)) { + _this = _super.call(this, low.low, low.high, true) || this; + } + else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { + _this = _super.call(this, low.i, low.t, true) || this; + } + else { + _this = _super.call(this, low, high, true) || this; + } + Object.defineProperty(_this, '_bsontype', { + value: 'Timestamp', + writable: false, + configurable: false, + enumerable: false + }); + return _this; + } + Timestamp.prototype.toJSON = function () { + return { + $timestamp: this.toString() + }; + }; + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + Timestamp.fromInt = function (value) { + return new Timestamp(Long.fromInt(value, true)); + }; + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + Timestamp.fromNumber = function (value) { + return new Timestamp(Long.fromNumber(value, true)); + }; + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + Timestamp.fromString = function (str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + }; + /** @internal */ + Timestamp.prototype.toExtendedJSON = function () { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + }; + /** @internal */ + Timestamp.fromExtendedJSON = function (doc) { + return new Timestamp(doc.$timestamp); + }; + /** @internal */ + Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Timestamp.prototype.inspect = function () { + return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })"; + }; + Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + return Timestamp; +}(LongWithoutOverridesClass)); + +function isBSONType(value) { + return (isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); +} +// INT32 boundaries +var BSON_INT32_MAX$1 = 0x7fffffff; +var BSON_INT32_MIN$1 = -0x80000000; +// INT64 boundaries +var BSON_INT64_MAX$1 = 0x7fffffffffffffff; +var BSON_INT64_MIN$1 = -0x8000000000000000; +// all the types where we don't need to do any special processing and can just pass the EJSON +//straight to type.fromExtendedJSON +var keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deserializeValue(value, options) { + if (options === void 0) { options = {}; } + if (typeof value === 'number') { + if (options.relaxed || options.legacy) { + return value; + } + // if it's an integer, should interpret as smallest BSON integer + // that can represent it exactly. (if out of range, interpret as double.) + if (Math.floor(value) === value) { + if (value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1) + return new Int32(value); + if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1) + return Long.fromNumber(value); + } + // If the number is a non-integer or out of integer range, should interpret as BSON Double. + return new Double(value); + } + // from here on out we're looking for bson types, so bail if its not an object + if (value == null || typeof value !== 'object') + return value; + // upgrade deprecated undefined to null + if (value.$undefined) + return null; + var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); + for (var i = 0; i < keys.length; i++) { + var c = keysToCodecs[keys[i]]; + if (c) + return c.fromExtendedJSON(value, options); + } + if (value.$date != null) { + var d = value.$date; + var date = new Date(); + if (options.legacy) { + if (typeof d === 'number') + date.setTime(d); + else if (typeof d === 'string') + date.setTime(Date.parse(d)); + } + else { + if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (Long.isLong(d)) + date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) + date.setTime(d); + } + return date; + } + if (value.$code != null) { + var copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return Code.fromExtendedJSON(value); + } + if (isDBRefLike(value) || value.$dbPointer) { + var v = value.$ref ? value : value.$dbPointer; + // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) + // because of the order JSON.parse goes through the document + if (v instanceof DBRef) + return v; + var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); + var valid_1 = true; + dollarKeys.forEach(function (k) { + if (['$ref', '$id', '$db'].indexOf(k) === -1) + valid_1 = false; + }); + // only make DBRef if $ keys are all valid + if (valid_1) + return DBRef.fromExtendedJSON(v); + } + return value; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeArray(array, options) { + return array.map(function (v, index) { + options.seenObjects.push({ propertyName: "index " + index, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + var isoStr = date.toISOString(); + // we should only show milliseconds in timestamp if they're non-zero + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeValue(value, options) { + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); + if (index !== -1) { + var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); + var leadingPart = props + .slice(0, index) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var alreadySeen = props[index]; + var circularPart = ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var current = props[props.length - 1]; + var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new BSONTypeError('Converting circular structure to EJSON:\n' + + (" " + leadingPart + alreadySeen + circularPart + current + "\n") + + (" " + leadingSpace + "\\" + dashes + "/")); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || isDate(value)) { + var dateNum = value.getTime(), + // is it in year range 1970-9999? + inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + // it's an integer + if (Math.floor(value) === value) { + var int32Range = value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1; + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (int32Range) + return { $numberInt: value.toString() }; + if (int64Range) + return { $numberLong: value.toString() }; + } + return { $numberDouble: value.toString() }; + } + if (value instanceof RegExp || isRegExp(value)) { + var flags = value.flags; + if (flags === undefined) { + var match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + var rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === 'object') + return serializeDocument(value, options); + return value; +} +var BSON_TYPE_MAPPINGS = { + Binary: function (o) { return new Binary(o.value(), o.sub_type); }, + Code: function (o) { return new Code(o.code, o.scope); }, + DBRef: function (o) { return new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, + Decimal128: function (o) { return new Decimal128(o.bytes); }, + Double: function (o) { return new Double(o.value); }, + Int32: function (o) { return new Int32(o.value); }, + Long: function (o) { + return Long.fromBits( + // underscore variants for 1.x backwards compatibility + o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); + }, + MaxKey: function () { return new MaxKey(); }, + MinKey: function () { return new MinKey(); }, + ObjectID: function (o) { return new ObjectId(o); }, + ObjectId: function (o) { return new ObjectId(o); }, + BSONRegExp: function (o) { return new BSONRegExp(o.pattern, o.options); }, + Symbol: function (o) { return new BSONSymbol(o.value); }, + Timestamp: function (o) { return Timestamp.fromBits(o.low, o.high); } +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + var bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + // It's a regular object. Recursively serialize its property values. + var _doc = {}; + for (var name in doc) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + _doc[name] = serializeValue(doc[name], options); + } + finally { + options.seenObjects.pop(); + } + } + return _doc; + } + else if (isBSONType(doc)) { + // the "document" is really just a BSON type object + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + // There's no EJSON serialization function on the object. It's probably an + // object created by a previous version of this library (or another library) + // that's duck-typing objects to look like they were generated by this library). + // Copy the object into this library's version of that type. + var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + // Two BSON types may have nested objects that may need to be serialized too + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } + else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + } + return outDoc.toExtendedJSON(options); + } + else { + throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} +/** + * EJSON parse / stringify API + * @public + */ +// the namespace here is used to emulate `export * as EJSON from '...'` +// which as of now (sept 2020) api-extractor does not support +// eslint-disable-next-line @typescript-eslint/no-namespace +var EJSON; +(function (EJSON) { + /** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ + function parse(text, options) { + var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); + // relaxed implies not strict + if (typeof finalOptions.relaxed === 'boolean') + finalOptions.strict = !finalOptions.relaxed; + if (typeof finalOptions.strict === 'boolean') + finalOptions.relaxed = !finalOptions.strict; + return JSON.parse(text, function (key, value) { + if (key.indexOf('\x00') !== -1) { + throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key)); + } + return deserializeValue(value, finalOptions); + }); + } + EJSON.parse = parse; + /** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ + function stringify(value, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer, space, options) { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + var doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); + } + EJSON.stringify = stringify; + /** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ + function serialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); + } + EJSON.serialize = serialize; + /** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ + function deserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); + } + EJSON.deserialize = deserialize; +})(EJSON || (EJSON = {})); + +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** @public */ +var bsonMap; +var bsonGlobal = getGlobal(); +if (bsonGlobal.Map) { + bsonMap = bsonGlobal.Map; +} +else { + // We will return a polyfill + bsonMap = /** @class */ (function () { + function Map(array) { + if (array === void 0) { array = []; } + this._keys = []; + this._values = {}; + for (var i = 0; i < array.length; i++) { + if (array[i] == null) + continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + } + Map.prototype.clear = function () { + this._keys = []; + this._values = {}; + }; + Map.prototype.delete = function (key) { + var value = this._values[key]; + if (value == null) + return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + Map.prototype.entries = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? [key, _this._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.forEach = function (callback, self) { + self = self || this; + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + Map.prototype.get = function (key) { + return this._values[key] ? this._values[key].v : undefined; + }; + Map.prototype.has = function (key) { + return this._values[key] != null; + }; + Map.prototype.keys = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.set = function (key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + Map.prototype.values = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? _this._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Object.defineProperty(Map.prototype, "size", { + get: function () { + return this._keys.length; + }, + enumerable: false, + configurable: true + }); + return Map; + }()); +} + +/** @internal */ +var BSON_INT32_MAX = 0x7fffffff; +/** @internal */ +var BSON_INT32_MIN = -0x80000000; +/** @internal */ +var BSON_INT64_MAX = Math.pow(2, 63) - 1; +/** @internal */ +var BSON_INT64_MIN = -Math.pow(2, 63); +/** + * Any integer up to 2^53 can be precisely represented by a double. + * @internal + */ +var JS_INT_MAX = Math.pow(2, 53); +/** + * Any integer down to -2^53 can be precisely represented by a double. + * @internal + */ +var JS_INT_MIN = -Math.pow(2, 53); +/** Number BSON Type @internal */ +var BSON_DATA_NUMBER = 1; +/** String BSON Type @internal */ +var BSON_DATA_STRING = 2; +/** Object BSON Type @internal */ +var BSON_DATA_OBJECT = 3; +/** Array BSON Type @internal */ +var BSON_DATA_ARRAY = 4; +/** Binary BSON Type @internal */ +var BSON_DATA_BINARY = 5; +/** Binary BSON Type @internal */ +var BSON_DATA_UNDEFINED = 6; +/** ObjectId BSON Type @internal */ +var BSON_DATA_OID = 7; +/** Boolean BSON Type @internal */ +var BSON_DATA_BOOLEAN = 8; +/** Date BSON Type @internal */ +var BSON_DATA_DATE = 9; +/** null BSON Type @internal */ +var BSON_DATA_NULL = 10; +/** RegExp BSON Type @internal */ +var BSON_DATA_REGEXP = 11; +/** Code BSON Type @internal */ +var BSON_DATA_DBPOINTER = 12; +/** Code BSON Type @internal */ +var BSON_DATA_CODE = 13; +/** Symbol BSON Type @internal */ +var BSON_DATA_SYMBOL = 14; +/** Code with Scope BSON Type @internal */ +var BSON_DATA_CODE_W_SCOPE = 15; +/** 32 bit Integer BSON Type @internal */ +var BSON_DATA_INT = 16; +/** Timestamp BSON Type @internal */ +var BSON_DATA_TIMESTAMP = 17; +/** Long BSON Type @internal */ +var BSON_DATA_LONG = 18; +/** Decimal128 BSON Type @internal */ +var BSON_DATA_DECIMAL128 = 19; +/** MinKey BSON Type @internal */ +var BSON_DATA_MIN_KEY = 0xff; +/** MaxKey BSON Type @internal */ +var BSON_DATA_MAX_KEY = 0x7f; +/** Binary Default Type @internal */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** Binary Function Type @internal */ +var BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** Binary Byte Array Type @internal */ +var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ +var BSON_BINARY_SUBTYPE_UUID = 3; +/** Binary UUID Type @internal */ +var BSON_BINARY_SUBTYPE_UUID_NEW = 4; +/** Binary MD5 Type @internal */ +var BSON_BINARY_SUBTYPE_MD5 = 5; +/** Encrypted BSON type @internal */ +var BSON_BINARY_SUBTYPE_ENCRYPTED = 6; +/** Column BSON type @internal */ +var BSON_BINARY_SUBTYPE_COLUMN = 7; +/** Binary User Defined Type @internal */ +var BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) { + var totalLength = 4 + 1; + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } + else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +/** @internal */ +function calculateElement(name, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +value, serializeFunctions, isArray, ignoreUndefined) { + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (isArray === void 0) { isArray = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = false; } + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } + else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } + else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } + else if (value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1); + } + } + else if (value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)); + } + } + else if (value['_bsontype'] === 'Symbol') { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + Buffer.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1); + } + else if (value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + // Add db reference if it exists + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value['_bsontype'] === 'BSONRegExp') { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.pattern, 'utf8') + + 1 + + Buffer.byteLength(value.options, 'utf8') + + 1); + } + else { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); + } + else if (serializeFunctions) { + return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1); + } + } + } + return 0; +} + +var FIRST_BIT = 0x80; +var FIRST_TWO_BITS = 0xc0; +var FIRST_THREE_BITS = 0xe0; +var FIRST_FOUR_BITS = 0xf0; +var FIRST_FIVE_BITS = 0xf8; +var TWO_BIT_CHAR = 0xc0; +var THREE_BIT_CHAR = 0xe0; +var FOUR_BIT_CHAR = 0xf0; +var CONTINUING_CHAR = 0x80; +/** + * Determines if the passed in bytes are valid utf8 + * @param bytes - An array of 8-bit bytes. Must be indexable and have length property + * @param start - The index to start validating + * @param end - The index to end validating + */ +function validateUtf8(bytes, start, end) { + var continuation = 0; + for (var i = start; i < end; i += 1) { + var byte = bytes[i]; + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } + else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } + else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } + else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } + else { + return false; + } + } + } + return !continuation; +} + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +var functionCache = {}; +function deserialize$1(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (size < 5) { + throw new BSONError("bson size must be >= 5, is " + size); + } + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size); + } + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new BSONError("buffer length " + buffer.length + " must === bson size " + size); + } + if (size + index > buffer.byteLength) { + throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); + } + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +} +var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray) { + if (isArray === void 0) { isArray = false; } + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + // Set the start index + var startIndex = index; + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + // Read the document size + var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + var done = false; + var isPossibleDBRef = isArray ? false : null; + // While we have more left data left keep parsing + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) + break; + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + var value = void 0; + index = i + 1; + if (elementType === BSON_DATA_STRING) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + value = getValidatedString(buffer, index, index + stringSize - 1); + index = index + stringSize; + } + else if (elementType === BSON_DATA_OID) { + var oid = Buffer.alloc(12); + buffer.copy(oid, 0, index, index + 12); + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } + else if (elementType === BSON_DATA_NUMBER) { + value = buffer.readDoubleLE(index); + index = index + 8; + } + else if (elementType === BSON_DATA_DATE) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Date(new Long(lowBits, highBits).toNumber()); + } + else if (elementType === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new BSONError('bad embedded document length in bson'); + // We have a raw value + if (raw) { + value = buffer.slice(index, index + objectSize); + } + else { + value = deserializeObject(buffer, _index, options, false); + } + index = index + objectSize; + } + else if (elementType === BSON_DATA_ARRAY) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + var arrayOptions = options; + // Stop index + var stopIndex = index + objectSize; + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) { + arrayOptions[n] = options[n]; + } + arrayOptions['raw'] = true; + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + if (buffer[index - 1] !== 0) + throw new BSONError('invalid array terminator byte'); + if (index !== stopIndex) + throw new BSONError('corrupted array bson'); + } + else if (elementType === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + // Unpack the low and high bits + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } + else { + value = long; + } + } + else if (elementType === BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = Buffer.alloc(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { + value = decimal128.toObject(); + } + else { + value = decimal128; + } + } + else if (elementType === BSON_DATA_BINARY) { + var binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var totalBinarySize = binarySize; + var subType = buffer[index++]; + // Did we have a negative binary size, throw + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + // Is the length longer than the document + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = buffer.slice(index, index + binarySize); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } + else { + var _buffer = Buffer.alloc(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else { + value = new Binary(_buffer, subType); + } + } + // Update the index + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + value = new RegExp(source, optionsArray.join('')); + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // Set the object + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === BSON_DATA_SYMBOL) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + var symbol = getValidatedString(buffer, index, index + stringSize - 1); + value = promoteValues ? symbol : new BSONSymbol(symbol); + index = index + stringSize; + } + else if (elementType === BSON_DATA_TIMESTAMP) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Timestamp(lowBits, highBits); + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === BSON_DATA_CODE) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + var functionString = getValidatedString(buffer, index, index + stringSize - 1); + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + } + else { + value = new Code(functionString); + } + // Update parse index position + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + // Javascript function + var functionString = getValidatedString(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + var _index = index; + // Decode the size of the object document + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + // Check if field length is too short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + // Check if totalSize field is too long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + value.scope = scopeObject; + } + else { + value = new Code(functionString, scopeObject); + } + } + else if (elementType === BSON_DATA_DBPOINTER) { + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) + throw new BSONError('bad string length in bson'); + // Namespace + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Read the oid + var oidBuffer = Buffer.alloc(12); + buffer.copy(oidBuffer, 0, index, index + 12); + var oid = new ObjectId(oidBuffer); + // Update the index + index = index + 12; + // Upgrade to DBRef type + value = new DBRef(namespace, oid); + } + else { + throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value: value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + object[name] = value; + } + } + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + var copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} +/** + * Ensure eval is isolated, store the result in functionCache. + * + * @internal + */ +function isolateEval(functionString, functionCache, object) { + if (!functionCache) + return new Function(functionString); + // Check for cache hit, eval if missing and return cached function + if (functionCache[functionString] == null) { + functionCache[functionString] = new Function(functionString); + } + // Set the object + return functionCache[functionString].bind(object); +} +function getValidatedString(buffer, start, end) { + var value = buffer.toString('utf8', start, end); + for (var i = 0; i < value.length; i++) { + if (value.charCodeAt(i) === 0xfffd) { + if (!validateUtf8(buffer, start, end)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + return value; +} + +// Copyright (c) 2008, Fair Oaks Labs, Inc. +function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) { + var e; + var m; + var c; + var bBE = endian === 'big'; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = bBE ? nBytes - 1 : 0; + var d = bBE ? -1 : 1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } + else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } + else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } + else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } + else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + if (isNaN(value)) + m = 0; + while (mLen >= 8) { + buffer[offset + i] = m & 0xff; + i += d; + m /= 256; + mLen -= 8; + } + e = (e << mLen) | m; + if (isNaN(value)) + e += 8; + eLen += mLen; + while (eLen > 0) { + buffer[offset + i] = e & 0xff; + i += d; + e /= 256; + eLen -= 8; + } + buffer[offset + i - d] |= s * 128; +} + +var regexp = /\x00/; // eslint-disable-line no-control-regex +var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +/* + * isArray indicates if we are writing to a BSON array (type 0x04) + * which forces the "key" which really an array index as a string to be written as ascii + * This will catch any errors in index as a string generation + */ +function serializeString(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, undefined, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} +function serializeNumber(buffer, key, value, index, isArray) { + // We have an integer value + // TODO(NODE-2529): Add support for big int + if (Number.isInteger(value) && + value >= BSON_INT32_MIN && + value <= BSON_INT32_MAX) { + // If the value fits in 32 bits encode as int32 + // Set int type 32 bits or less + buffer[index++] = BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } + else { + // Encode as double + buffer[index++] = BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + } + return index; +} +function serializeNull(buffer, key, _, index, isArray) { + // Set long type + buffer[index++] = BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} +function serializeRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.ignoreCase) + buffer[index++] = 0x69; // i + if (value.global) + buffer[index++] = 0x73; // s + if (value.multiline) + buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.pattern, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, undefined, 'binary'); + } + else if (isUint8Array(value.id)) { + // Use the standard JS methods here because buffer.copy() is buggy with the + // browser polyfill + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + // Adjust index + return index + 12; +} +function serializeBuffer(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + buffer.set(ensureBuffer(value), index); + // Adjust the index + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (path === void 0) { path = []; } + for (var i = 0; i < path.length; i++) { + if (path[i] === value) + throw new BSONError('cyclic dependency detected'); + } + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index, isArray) { + buffer[index++] = BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + // Prefer the standard JS methods because their typechecking is not buggy, + // unlike the `buffer` polyfill's. + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} +function serializeLong(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} +function serializeInt32(buffer, key, value, index, isArray) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +} +function serializeDouble(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value.value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + return index; +} +function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { + buffer[index++] = BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Starting index + var startIndex = index; + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + index = endIndex - 1; + // Writ the total + var totalSize = endIndex - startIndex; + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) + size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + // Write the data to the object + buffer.set(data, index); + // Adjust the index + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var startIndex = index; + var output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (startingIndex === void 0) { startingIndex = 0; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (path === void 0) { path = []; } + startingIndex = startingIndex || 0; + path = path || []; + // Push the object to the path + path.push(object); + // Start place to serialize into + var index = startingIndex + 4; + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index, true); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } + else if (typeof value === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } + else if (typeof value === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } + else if (typeof value === 'object' && + isBSONType(value) && + value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + else if (object instanceof bsonMap || isMap(object)) { + var iterator = object.entries(); + var done = false; + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = !!entry.done; + // Are we done, then skip and terminate + if (done) + continue; + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new BSONTypeError('toBSON function did not return an object'); + } + // Iterate over all the keys + for (var key in object) { + var value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') + throw new BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + // Remove the path + path.pop(); + // Final padding byte for object + buffer[index++] = 0x00; + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +/** @internal */ +// Default Max Size +var MAXSIZE = 1024 * 1024 * 17; +// Current Internal Temporary Serialization Buffer +var buffer = Buffer.alloc(MAXSIZE); +/** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer + * @public + */ +function setInternalBufferSize(size) { + // Resize the internal serialization buffer if needed + if (buffer.length < size) { + buffer = Buffer.alloc(size); + } +} +/** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ +function serialize(object, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = Buffer.alloc(minInternalBufferSize); + } + // Attempt to serialize + var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = Buffer.alloc(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +} +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ +function serializeWithBufferAndIndex(object, finalBuffer, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + // Attempt to serialize + var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + // Return the index + return startIndex + serializationIndex - 1; +} +/** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ +function deserialize(buffer, options) { + if (options === void 0) { options = {}; } + return deserialize$1(buffer instanceof Buffer ? buffer : ensureBuffer(buffer), options); +} +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ +function calculateObjectSize(object, options) { + if (options === void 0) { options = {}; } + options = options || {}; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + return calculateObjectSize$1(object, serializeFunctions, ignoreUndefined); +} +/** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + var bufferData = ensureBuffer(data); + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + // Update options with index + internalOptions.index = index; + // Parse the document at this point + documents[docStartIndex + i] = deserialize$1(bufferData, internalOptions); + // Adjust index by the document size + index = index + size; + } + // Return object containing end index of parsing and list of documents + return index; +} +/** + * BSON default export + * @deprecated Please use named exports + * @privateRemarks + * We want to someday deprecate the default export, + * so none of the new TS types are being exported on the default + * @public + */ +var BSON = { + Binary: Binary, + Code: Code, + DBRef: DBRef, + Decimal128: Decimal128, + Double: Double, + Int32: Int32, + Long: Long, + UUID: UUID, + Map: bsonMap, + MaxKey: MaxKey, + MinKey: MinKey, + ObjectId: ObjectId, + ObjectID: ObjectId, + BSONRegExp: BSONRegExp, + BSONSymbol: BSONSymbol, + Timestamp: Timestamp, + EJSON: EJSON, + setInternalBufferSize: setInternalBufferSize, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + deserialize: deserialize, + calculateObjectSize: calculateObjectSize, + deserializeStream: deserializeStream, + BSONError: BSONError, + BSONTypeError: BSONTypeError +}; + +export default BSON; +export { BSONError, BSONRegExp, BSONSymbol, BSONTypeError, BSON_BINARY_SUBTYPE_BYTE_ARRAY, BSON_BINARY_SUBTYPE_COLUMN, BSON_BINARY_SUBTYPE_DEFAULT, BSON_BINARY_SUBTYPE_ENCRYPTED, BSON_BINARY_SUBTYPE_FUNCTION, BSON_BINARY_SUBTYPE_MD5, BSON_BINARY_SUBTYPE_USER_DEFINED, BSON_BINARY_SUBTYPE_UUID, BSON_BINARY_SUBTYPE_UUID_NEW, BSON_DATA_ARRAY, BSON_DATA_BINARY, BSON_DATA_BOOLEAN, BSON_DATA_CODE, BSON_DATA_CODE_W_SCOPE, BSON_DATA_DATE, BSON_DATA_DBPOINTER, BSON_DATA_DECIMAL128, BSON_DATA_INT, BSON_DATA_LONG, BSON_DATA_MAX_KEY, BSON_DATA_MIN_KEY, BSON_DATA_NULL, BSON_DATA_NUMBER, BSON_DATA_OBJECT, BSON_DATA_OID, BSON_DATA_REGEXP, BSON_DATA_STRING, BSON_DATA_SYMBOL, BSON_DATA_TIMESTAMP, BSON_DATA_UNDEFINED, BSON_INT32_MAX, BSON_INT32_MIN, BSON_INT64_MAX, BSON_INT64_MIN, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, LongWithoutOverridesClass, bsonMap as Map, MaxKey, MinKey, ObjectId as ObjectID, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize }; +//# sourceMappingURL=bson.esm.js.map diff --git a/node_modules/bson/dist/bson.esm.js.map b/node_modules/bson/dist/bson.esm.js.map new file mode 100644 index 0000000..3d30ec4 --- /dev/null +++ b/node_modules/bson/dist/bson.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.esm.js","sources":["../node_modules/tslib/tslib.es6.js","../src/error.ts","../src/utils/global.ts","../src/parser/utils.ts","../src/ensure_buffer.ts","../src/uuid_utils.ts","../src/uuid.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/extended_json.ts","../src/map.ts","../src/constants.ts","../src/parser/calculate_size.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/float_parser.ts","../src/parser/serializer.ts","../src/bson.ts"],"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 */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","hasOwnProperty","__extends","__","constructor","prototype","create","kId","BSON_INT32_MAX","BSON_INT32_MIN","BSON_INT64_MAX","BSON_INT64_MIN","calculateObjectSize","constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","deserialize","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT","Map","internalSerialize","internalDeserialize","internalCalculateObjectSize"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AAEA,IAAIA,cAAa,GAAG,uBAASC,CAAT,EAAYC,CAAZ,EAAe;AAC/BF,EAAAA,cAAa,GAAG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AC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;aAC5B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;;QAEhC,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;;QAE9B,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,GAAGD,aAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;;QAEhF,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;KACtB;;IAGD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;;;;IAQM,IAAI,GAAG;IACX,MAAM,QAAA;IACN,IAAI,MAAA;IACJ,KAAK,OAAA;IACL,UAAU,YAAA;IACV,MAAM,QAAA;IACN,KAAK,OAAA;IACL,IAAI,MAAA;IACJ,IAAI,MAAA;IACJ,GAAG,SAAA;IACH,MAAM,QAAA;IACN,MAAM,QAAA;IACN,QAAQ,UAAA;IACR,QAAQ,EAAE,QAAQ;IAClB,UAAU,YAAA;IACV,UAAU,YAAA;IACV,SAAS,WAAA;IACT,KAAK,OAAA;IACL,qBAAqB,uBAAA;IACrB,SAAS,WAAA;IACT,2BAA2B,6BAAA;IAC3B,WAAW,aAAA;IACX,mBAAmB,qBAAA;IACnB,iBAAiB,mBAAA;IACjB,SAAS,WAAA;IACT,aAAa,eAAA;;;;;;"} \ No newline at end of file diff --git a/node_modules/bson/etc/prepare.js b/node_modules/bson/etc/prepare.js new file mode 100644 index 0000000..91e6f3a --- /dev/null +++ b/node_modules/bson/etc/prepare.js @@ -0,0 +1,19 @@ +#! /usr/bin/env node +var cp = require('child_process'); +var fs = require('fs'); + +var nodeMajorVersion = +process.version.match(/^v(\d+)\.\d+/)[1]; + +if (fs.existsSync('src') && nodeMajorVersion >= 10) { + cp.spawnSync('npm', ['run', 'build'], { stdio: 'inherit', shell: true }); +} else { + if (!fs.existsSync('lib')) { + console.warn('BSON: No compiled javascript present, the library is not installed correctly.'); + if (nodeMajorVersion < 10) { + console.warn( + 'This library can only be compiled in nodejs version 10 or later, currently running: ' + + nodeMajorVersion + ); + } + } +} diff --git a/node_modules/bson/lib/binary.js b/node_modules/bson/lib/binary.js new file mode 100644 index 0000000..4aadc5a --- /dev/null +++ b/node_modules/bson/lib/binary.js @@ -0,0 +1,239 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Binary = void 0; +var buffer_1 = require("buffer"); +var ensure_buffer_1 = require("./ensure_buffer"); +var uuid_utils_1 = require("./uuid_utils"); +var uuid_1 = require("./uuid"); +var error_1 = require("./error"); +/** + * A class representation of the BSON Binary type. + * @public + */ +var Binary = /** @class */ (function () { + /** + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) + return new Binary(buffer, subType); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new error_1.BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + // create an empty binary buffer + this.buffer = buffer_1.Buffer.alloc(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + // string + this.buffer = buffer_1.Buffer.from(buffer, 'binary'); + } + else if (Array.isArray(buffer)) { + // number[] + this.buffer = buffer_1.Buffer.from(buffer); + } + else { + // Buffer | TypedArray | ArrayBuffer + this.buffer = ensure_buffer_1.ensureBuffer(buffer); + } + this.position = this.buffer.byteLength; + } + } + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + Binary.prototype.put = function (byteValue) { + // If it's a string and a has more than one character throw an error + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new error_1.BSONTypeError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new error_1.BSONTypeError('only accepts single character Uint8Array or Array'); + // Decode the byte value once + var decodedByte; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } + else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } + else { + decodedByte = byteValue[0]; + } + if (decodedByte < 0 || decodedByte > 255) { + throw new error_1.BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + var buffer = buffer_1.Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decodedByte; + } + }; + /** + * Writes a buffer or string to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + Binary.prototype.write = function (sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + sequence.length) { + var buffer = buffer_1.Buffer.alloc(this.buffer.length + sequence.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + // Assign the new buffer + this.buffer = buffer; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ensure_buffer_1.ensureBuffer(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + this.buffer.write(sequence, offset, sequence.length, 'binary'); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + }; + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + Binary.prototype.read = function (position, length) { + length = length && length > 0 ? length : this.position; + // Let's return the data based on the type we have + return this.buffer.slice(position, position + length); + }; + /** + * Returns the value of this binary as a string. + * @param asRaw - Will skip converting to a string + * @remarks + * This is handy when calling this function conditionally for some key value pairs and not others + */ + Binary.prototype.value = function (asRaw) { + asRaw = !!asRaw; + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + // If it's a node.js buffer object + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return this.buffer.toString('binary', 0, this.position); + }; + /** the length of the binary sequence */ + Binary.prototype.length = function () { + return this.position; + }; + Binary.prototype.toJSON = function () { + return this.buffer.toString('base64'); + }; + Binary.prototype.toString = function (format) { + return this.buffer.toString(format); + }; + /** @internal */ + Binary.prototype.toExtendedJSON = function (options) { + options = options || {}; + var base64String = this.buffer.toString('base64'); + var subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + }; + Binary.prototype.toUUID = function () { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new uuid_1.UUID(this.buffer.slice(0, this.position)); + } + throw new error_1.BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); + }; + /** @internal */ + Binary.fromExtendedJSON = function (doc, options) { + options = options || {}; + var data; + var type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = buffer_1.Buffer.from(doc.$binary, 'base64'); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = buffer_1.Buffer.from(doc.$binary.base64, 'base64'); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = uuid_utils_1.uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new error_1.BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); + } + return new Binary(data, type); + }; + /** @internal */ + Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Binary.prototype.inspect = function () { + var asBuffer = this.value(true); + return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; + }; + /** + * Binary default subtype + * @internal + */ + Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** Initial buffer default size */ + Binary.BUFFER_SIZE = 256; + /** Default BSON type */ + Binary.SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + Binary.SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + Binary.SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + Binary.SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + Binary.SUBTYPE_UUID = 4; + /** MD5 BSON type */ + Binary.SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + Binary.SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + Binary.SUBTYPE_COLUMN = 7; + /** User BSON type */ + Binary.SUBTYPE_USER_DEFINED = 128; + return Binary; +}()); +exports.Binary = Binary; +Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); +//# sourceMappingURL=binary.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/binary.js.map b/node_modules/bson/lib/binary.js.map new file mode 100644 index 0000000..a59b7f6 --- /dev/null +++ b/node_modules/bson/lib/binary.js.map @@ -0,0 +1 @@ +{"version":3,"file":"binary.js","sourceRoot":"","sources":["../src/binary.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iDAA+C;AAC/C,2CAAqD;AACrD,+BAA4C;AAE5C,iCAAmD;AAmBnD;;;GAGG;AACH;IAkCE;;;OAGG;IACH,gBAAY,MAAgC,EAAE,OAAgB;QAC5D,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC;YAAE,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAElE,IACE,CAAC,CAAC,MAAM,IAAI,IAAI,CAAC;YACjB,CAAC,CAAC,OAAO,MAAM,KAAK,QAAQ,CAAC;YAC7B,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC;YAC3B,CAAC,CAAC,M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CAAC;IACtC,uBAAuB;IACP,qBAAc,GAAG,CAAC,CAAC;IACnC,qBAAqB;IACL,2BAAoB,GAAG,GAAG,CAAC;IAmO7C,aAAC;CAAA,AA/PD,IA+PC;AA/PY,wBAAM;AAiQnB,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/bson.js b/node_modules/bson/lib/bson.js new file mode 100644 index 0000000..88cc59e --- /dev/null +++ b/node_modules/bson/lib/bson.js @@ -0,0 +1,252 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BSONRegExp = exports.MaxKey = exports.MinKey = exports.Int32 = exports.Double = exports.Timestamp = exports.Long = exports.UUID = exports.ObjectId = exports.Binary = exports.DBRef = exports.BSONSymbol = exports.Map = exports.Code = exports.LongWithoutOverridesClass = exports.EJSON = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_STRING = exports.BSON_DATA_REGEXP = exports.BSON_DATA_OID = exports.BSON_DATA_OBJECT = exports.BSON_DATA_NUMBER = exports.BSON_DATA_NULL = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_LONG = exports.BSON_DATA_INT = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_DATE = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_CODE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_BINARY_SUBTYPE_COLUMN = exports.BSON_BINARY_SUBTYPE_ENCRYPTED = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = void 0; +exports.deserializeStream = exports.calculateObjectSize = exports.deserialize = exports.serializeWithBufferAndIndex = exports.serialize = exports.setInternalBufferSize = exports.BSONTypeError = exports.BSONError = exports.ObjectID = exports.Decimal128 = void 0; +var buffer_1 = require("buffer"); +var binary_1 = require("./binary"); +Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return binary_1.Binary; } }); +var code_1 = require("./code"); +Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return code_1.Code; } }); +var db_ref_1 = require("./db_ref"); +Object.defineProperty(exports, "DBRef", { enumerable: true, get: function () { return db_ref_1.DBRef; } }); +var decimal128_1 = require("./decimal128"); +Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function () { return decimal128_1.Decimal128; } }); +var double_1 = require("./double"); +Object.defineProperty(exports, "Double", { enumerable: true, get: function () { return double_1.Double; } }); +var ensure_buffer_1 = require("./ensure_buffer"); +var extended_json_1 = require("./extended_json"); +var int_32_1 = require("./int_32"); +Object.defineProperty(exports, "Int32", { enumerable: true, get: function () { return int_32_1.Int32; } }); +var long_1 = require("./long"); +Object.defineProperty(exports, "Long", { enumerable: true, get: function () { return long_1.Long; } }); +var map_1 = require("./map"); +Object.defineProperty(exports, "Map", { enumerable: true, get: function () { return map_1.Map; } }); +var max_key_1 = require("./max_key"); +Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function () { return max_key_1.MaxKey; } }); +var min_key_1 = require("./min_key"); +Object.defineProperty(exports, "MinKey", { enumerable: true, get: function () { return min_key_1.MinKey; } }); +var objectid_1 = require("./objectid"); +Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function () { return objectid_1.ObjectId; } }); +Object.defineProperty(exports, "ObjectID", { enumerable: true, get: function () { return objectid_1.ObjectId; } }); +var error_1 = require("./error"); +var calculate_size_1 = require("./parser/calculate_size"); +// Parts of the parser +var deserializer_1 = require("./parser/deserializer"); +var serializer_1 = require("./parser/serializer"); +var regexp_1 = require("./regexp"); +Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function () { return regexp_1.BSONRegExp; } }); +var symbol_1 = require("./symbol"); +Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function () { return symbol_1.BSONSymbol; } }); +var timestamp_1 = require("./timestamp"); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return timestamp_1.Timestamp; } }); +var uuid_1 = require("./uuid"); +Object.defineProperty(exports, "UUID", { enumerable: true, get: function () { return uuid_1.UUID; } }); +var constants_1 = require("./constants"); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_BYTE_ARRAY", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_BYTE_ARRAY; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_DEFAULT", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_DEFAULT; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_FUNCTION", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_FUNCTION; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_MD5", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_MD5; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_USER_DEFINED", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_USER_DEFINED; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_UUID; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID_NEW", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_UUID_NEW; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_ENCRYPTED", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_ENCRYPTED; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_COLUMN", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_COLUMN; } }); +Object.defineProperty(exports, "BSON_DATA_ARRAY", { enumerable: true, get: function () { return constants_1.BSON_DATA_ARRAY; } }); +Object.defineProperty(exports, "BSON_DATA_BINARY", { enumerable: true, get: function () { return constants_1.BSON_DATA_BINARY; } }); +Object.defineProperty(exports, "BSON_DATA_BOOLEAN", { enumerable: true, get: function () { return constants_1.BSON_DATA_BOOLEAN; } }); +Object.defineProperty(exports, "BSON_DATA_CODE", { enumerable: true, get: function () { return constants_1.BSON_DATA_CODE; } }); +Object.defineProperty(exports, "BSON_DATA_CODE_W_SCOPE", { enumerable: true, get: function () { return constants_1.BSON_DATA_CODE_W_SCOPE; } }); +Object.defineProperty(exports, "BSON_DATA_DATE", { enumerable: true, get: function () { return constants_1.BSON_DATA_DATE; } }); +Object.defineProperty(exports, "BSON_DATA_DBPOINTER", { enumerable: true, get: function () { return constants_1.BSON_DATA_DBPOINTER; } }); +Object.defineProperty(exports, "BSON_DATA_DECIMAL128", { enumerable: true, get: function () { return constants_1.BSON_DATA_DECIMAL128; } }); +Object.defineProperty(exports, "BSON_DATA_INT", { enumerable: true, get: function () { return constants_1.BSON_DATA_INT; } }); +Object.defineProperty(exports, "BSON_DATA_LONG", { enumerable: true, get: function () { return constants_1.BSON_DATA_LONG; } }); +Object.defineProperty(exports, "BSON_DATA_MAX_KEY", { enumerable: true, get: function () { return constants_1.BSON_DATA_MAX_KEY; } }); +Object.defineProperty(exports, "BSON_DATA_MIN_KEY", { enumerable: true, get: function () { return constants_1.BSON_DATA_MIN_KEY; } }); +Object.defineProperty(exports, "BSON_DATA_NULL", { enumerable: true, get: function () { return constants_1.BSON_DATA_NULL; } }); +Object.defineProperty(exports, "BSON_DATA_NUMBER", { enumerable: true, get: function () { return constants_1.BSON_DATA_NUMBER; } }); +Object.defineProperty(exports, "BSON_DATA_OBJECT", { enumerable: true, get: function () { return constants_1.BSON_DATA_OBJECT; } }); +Object.defineProperty(exports, "BSON_DATA_OID", { enumerable: true, get: function () { return constants_1.BSON_DATA_OID; } }); +Object.defineProperty(exports, "BSON_DATA_REGEXP", { enumerable: true, get: function () { return constants_1.BSON_DATA_REGEXP; } }); +Object.defineProperty(exports, "BSON_DATA_STRING", { enumerable: true, get: function () { return constants_1.BSON_DATA_STRING; } }); +Object.defineProperty(exports, "BSON_DATA_SYMBOL", { enumerable: true, get: function () { return constants_1.BSON_DATA_SYMBOL; } }); +Object.defineProperty(exports, "BSON_DATA_TIMESTAMP", { enumerable: true, get: function () { return constants_1.BSON_DATA_TIMESTAMP; } }); +Object.defineProperty(exports, "BSON_DATA_UNDEFINED", { enumerable: true, get: function () { return constants_1.BSON_DATA_UNDEFINED; } }); +Object.defineProperty(exports, "BSON_INT32_MAX", { enumerable: true, get: function () { return constants_1.BSON_INT32_MAX; } }); +Object.defineProperty(exports, "BSON_INT32_MIN", { enumerable: true, get: function () { return constants_1.BSON_INT32_MIN; } }); +Object.defineProperty(exports, "BSON_INT64_MAX", { enumerable: true, get: function () { return constants_1.BSON_INT64_MAX; } }); +Object.defineProperty(exports, "BSON_INT64_MIN", { enumerable: true, get: function () { return constants_1.BSON_INT64_MIN; } }); +var extended_json_2 = require("./extended_json"); +Object.defineProperty(exports, "EJSON", { enumerable: true, get: function () { return extended_json_2.EJSON; } }); +var timestamp_2 = require("./timestamp"); +Object.defineProperty(exports, "LongWithoutOverridesClass", { enumerable: true, get: function () { return timestamp_2.LongWithoutOverridesClass; } }); +var error_2 = require("./error"); +Object.defineProperty(exports, "BSONError", { enumerable: true, get: function () { return error_2.BSONError; } }); +Object.defineProperty(exports, "BSONTypeError", { enumerable: true, get: function () { return error_2.BSONTypeError; } }); +/** @internal */ +// Default Max Size +var MAXSIZE = 1024 * 1024 * 17; +// Current Internal Temporary Serialization Buffer +var buffer = buffer_1.Buffer.alloc(MAXSIZE); +/** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer + * @public + */ +function setInternalBufferSize(size) { + // Resize the internal serialization buffer if needed + if (buffer.length < size) { + buffer = buffer_1.Buffer.alloc(size); + } +} +exports.setInternalBufferSize = setInternalBufferSize; +/** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ +function serialize(object, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = buffer_1.Buffer.alloc(minInternalBufferSize); + } + // Attempt to serialize + var serializationIndex = serializer_1.serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = buffer_1.Buffer.alloc(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +} +exports.serialize = serialize; +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ +function serializeWithBufferAndIndex(object, finalBuffer, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + // Attempt to serialize + var serializationIndex = serializer_1.serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + // Return the index + return startIndex + serializationIndex - 1; +} +exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; +/** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ +function deserialize(buffer, options) { + if (options === void 0) { options = {}; } + return deserializer_1.deserialize(buffer instanceof buffer_1.Buffer ? buffer : ensure_buffer_1.ensureBuffer(buffer), options); +} +exports.deserialize = deserialize; +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ +function calculateObjectSize(object, options) { + if (options === void 0) { options = {}; } + options = options || {}; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + return calculate_size_1.calculateObjectSize(object, serializeFunctions, ignoreUndefined); +} +exports.calculateObjectSize = calculateObjectSize; +/** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + var bufferData = ensure_buffer_1.ensureBuffer(data); + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + // Update options with index + internalOptions.index = index; + // Parse the document at this point + documents[docStartIndex + i] = deserializer_1.deserialize(bufferData, internalOptions); + // Adjust index by the document size + index = index + size; + } + // Return object containing end index of parsing and list of documents + return index; +} +exports.deserializeStream = deserializeStream; +/** + * BSON default export + * @deprecated Please use named exports + * @privateRemarks + * We want to someday deprecate the default export, + * so none of the new TS types are being exported on the default + * @public + */ +var BSON = { + Binary: binary_1.Binary, + Code: code_1.Code, + DBRef: db_ref_1.DBRef, + Decimal128: decimal128_1.Decimal128, + Double: double_1.Double, + Int32: int_32_1.Int32, + Long: long_1.Long, + UUID: uuid_1.UUID, + Map: map_1.Map, + MaxKey: max_key_1.MaxKey, + MinKey: min_key_1.MinKey, + ObjectId: objectid_1.ObjectId, + ObjectID: objectid_1.ObjectId, + BSONRegExp: regexp_1.BSONRegExp, + BSONSymbol: symbol_1.BSONSymbol, + Timestamp: timestamp_1.Timestamp, + EJSON: extended_json_1.EJSON, + setInternalBufferSize: setInternalBufferSize, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + deserialize: deserialize, + calculateObjectSize: calculateObjectSize, + deserializeStream: deserializeStream, + BSONError: error_1.BSONError, + BSONTypeError: error_1.BSONTypeError +}; +exports.default = BSON; +//# sourceMappingURL=bson.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/bson.js.map b/node_modules/bson/lib/bson.js.map new file mode 100644 index 0000000..a195407 --- /dev/null +++ b/node_modules/bson/lib/bson.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.js","sourceRoot":"","sources":["../src/bson.ts"],"names":[],"mappings":";;;;AAAA,iCAAgC;AAChC,mCAAkC;AAoFhC,uFApFO,eAAM,OAoFP;AAnFR,+BAA8B;AA+E5B,qFA/EO,WAAI,OA+EP;AA9EN,mCAAiC;AAiF/B,sFAjFO,cAAK,OAiFP;AAhFP,2CAA0C;AA2FxC,2FA3FO,uBAAU,OA2FP;AA1FZ,mCAAkC;AAqFhC,uFArFO,eAAM,OAqFP;AApFR,iDAA+C;AAC/C,iDA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AA;IACN,QAAQ,qBAAA;IACR,QAAQ,EAAE,mBAAQ;IAClB,UAAU,qBAAA;IACV,UAAU,qBAAA;IACV,SAAS,uBAAA;IACT,KAAK,uBAAA;IACL,qBAAqB,uBAAA;IACrB,SAAS,WAAA;IACT,2BAA2B,6BAAA;IAC3B,WAAW,aAAA;IACX,mBAAmB,qBAAA;IACnB,iBAAiB,mBAAA;IACjB,SAAS,mBAAA;IACT,aAAa,uBAAA;CACd,CAAC;AACF,kBAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/code.js b/node_modules/bson/lib/code.js new file mode 100644 index 0000000..4e6dc07 --- /dev/null +++ b/node_modules/bson/lib/code.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Code = void 0; +/** + * A class representation of the BSON Code type. + * @public + */ +var Code = /** @class */ (function () { + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + function Code(code, scope) { + if (!(this instanceof Code)) + return new Code(code, scope); + this.code = code; + this.scope = scope; + } + Code.prototype.toJSON = function () { + return { code: this.code, scope: this.scope }; + }; + /** @internal */ + Code.prototype.toExtendedJSON = function () { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + }; + /** @internal */ + Code.fromExtendedJSON = function (doc) { + return new Code(doc.$code, doc.$scope); + }; + /** @internal */ + Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Code.prototype.inspect = function () { + var codeJson = this.toJSON(); + return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; + }; + return Code; +}()); +exports.Code = Code; +Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); +//# sourceMappingURL=code.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/code.js.map b/node_modules/bson/lib/code.js.map new file mode 100644 index 0000000..e1bf73f --- /dev/null +++ b/node_modules/bson/lib/code.js.map @@ -0,0 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CAAC;IACH,WAAC;AAAD,CAAC,AA7CD,IA6CC;AA7CY,oBAAI;AA+CjB,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/constants.js b/node_modules/bson/lib/constants.js new file mode 100644 index 0000000..ff8b68d --- /dev/null +++ b/node_modules/bson/lib/constants.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_COLUMN = exports.BSON_BINARY_SUBTYPE_ENCRYPTED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_LONG = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_INT = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_CODE = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_REGEXP = exports.BSON_DATA_NULL = exports.BSON_DATA_DATE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_OID = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_DATA_OBJECT = exports.BSON_DATA_STRING = exports.BSON_DATA_NUMBER = exports.JS_INT_MIN = exports.JS_INT_MAX = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = void 0; +/** @internal */ +exports.BSON_INT32_MAX = 0x7fffffff; +/** @internal */ +exports.BSON_INT32_MIN = -0x80000000; +/** @internal */ +exports.BSON_INT64_MAX = Math.pow(2, 63) - 1; +/** @internal */ +exports.BSON_INT64_MIN = -Math.pow(2, 63); +/** + * Any integer up to 2^53 can be precisely represented by a double. + * @internal + */ +exports.JS_INT_MAX = Math.pow(2, 53); +/** + * Any integer down to -2^53 can be precisely represented by a double. + * @internal + */ +exports.JS_INT_MIN = -Math.pow(2, 53); +/** Number BSON Type @internal */ +exports.BSON_DATA_NUMBER = 1; +/** String BSON Type @internal */ +exports.BSON_DATA_STRING = 2; +/** Object BSON Type @internal */ +exports.BSON_DATA_OBJECT = 3; +/** Array BSON Type @internal */ +exports.BSON_DATA_ARRAY = 4; +/** Binary BSON Type @internal */ +exports.BSON_DATA_BINARY = 5; +/** Binary BSON Type @internal */ +exports.BSON_DATA_UNDEFINED = 6; +/** ObjectId BSON Type @internal */ +exports.BSON_DATA_OID = 7; +/** Boolean BSON Type @internal */ +exports.BSON_DATA_BOOLEAN = 8; +/** Date BSON Type @internal */ +exports.BSON_DATA_DATE = 9; +/** null BSON Type @internal */ +exports.BSON_DATA_NULL = 10; +/** RegExp BSON Type @internal */ +exports.BSON_DATA_REGEXP = 11; +/** Code BSON Type @internal */ +exports.BSON_DATA_DBPOINTER = 12; +/** Code BSON Type @internal */ +exports.BSON_DATA_CODE = 13; +/** Symbol BSON Type @internal */ +exports.BSON_DATA_SYMBOL = 14; +/** Code with Scope BSON Type @internal */ +exports.BSON_DATA_CODE_W_SCOPE = 15; +/** 32 bit Integer BSON Type @internal */ +exports.BSON_DATA_INT = 16; +/** Timestamp BSON Type @internal */ +exports.BSON_DATA_TIMESTAMP = 17; +/** Long BSON Type @internal */ +exports.BSON_DATA_LONG = 18; +/** Decimal128 BSON Type @internal */ +exports.BSON_DATA_DECIMAL128 = 19; +/** MinKey BSON Type @internal */ +exports.BSON_DATA_MIN_KEY = 0xff; +/** MaxKey BSON Type @internal */ +exports.BSON_DATA_MAX_KEY = 0x7f; +/** Binary Default Type @internal */ +exports.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** Binary Function Type @internal */ +exports.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** Binary Byte Array Type @internal */ +exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ +exports.BSON_BINARY_SUBTYPE_UUID = 3; +/** Binary UUID Type @internal */ +exports.BSON_BINARY_SUBTYPE_UUID_NEW = 4; +/** Binary MD5 Type @internal */ +exports.BSON_BINARY_SUBTYPE_MD5 = 5; +/** Encrypted BSON type @internal */ +exports.BSON_BINARY_SUBTYPE_ENCRYPTED = 6; +/** Column BSON type @internal */ +exports.BSON_BINARY_SUBTYPE_COLUMN = 7; +/** Binary User Defined Type @internal */ +exports.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/constants.js.map b/node_modules/bson/lib/constants.js.map new file mode 100644 index 0000000..3b9c0ca --- /dev/null +++ b/node_modules/bson/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAA,gBAAgB;AACH,QAAA,cAAc,GAAG,UAAU,CAAC;AACzC,gBAAgB;AACH,QAAA,cAAc,GAAG,CAAC,UAAU,CAAC;AAC1C,gBAAgB;AACH,QAAA,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;AAClD,gBAAgB;AACH,QAAA,cAAc,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAE/C;;;GAGG;AACU,QAAA,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAE1C;;;GAGG;AACU,QAAA,UAAU,GAAG,CAAC,IAAI,CAAC,GAA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AAA,4BAA4B,GAAG,CAAC,CAAC;AAE9C,uCAAuC;AAC1B,QAAA,8BAA8B,GAAG,CAAC,CAAC;AAEhD,gGAAgG;AACnF,QAAA,wBAAwB,GAAG,CAAC,CAAC;AAE1C,iCAAiC;AACpB,QAAA,4BAA4B,GAAG,CAAC,CAAC;AAE9C,gCAAgC;AACnB,QAAA,uBAAuB,GAAG,CAAC,CAAC;AAEzC,oCAAoC;AACvB,QAAA,6BAA6B,GAAG,CAAC,CAAC;AAE/C,iCAAiC;AACpB,QAAA,0BAA0B,GAAG,CAAC,CAAC;AAE5C,yCAAyC;AAC5B,QAAA,gCAAgC,GAAG,GAAG,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/db_ref.js b/node_modules/bson/lib/db_ref.js new file mode 100644 index 0000000..ea7f157 --- /dev/null +++ b/node_modules/bson/lib/db_ref.js @@ -0,0 +1,96 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DBRef = exports.isDBRefLike = void 0; +var utils_1 = require("./parser/utils"); +/** @internal */ +function isDBRefLike(value) { + return (utils_1.isObjectLike(value) && + value.$id != null && + typeof value.$ref === 'string' && + (value.$db == null || typeof value.$db === 'string')); +} +exports.isDBRefLike = isDBRefLike; +/** + * A class representation of the BSON DBRef type. + * @public + */ +var DBRef = /** @class */ (function () { + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + function DBRef(collection, oid, db, fields) { + if (!(this instanceof DBRef)) + return new DBRef(collection, oid, db, fields); + // check if namespace has been provided + var parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + Object.defineProperty(DBRef.prototype, "namespace", { + // Property provided for compatibility with the 1.x parser + // the 1.x parser used a "namespace" property, while 4.x uses "collection" + /** @internal */ + get: function () { + return this.collection; + }, + set: function (value) { + this.collection = value; + }, + enumerable: false, + configurable: true + }); + DBRef.prototype.toJSON = function () { + var o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + }; + /** @internal */ + DBRef.prototype.toExtendedJSON = function (options) { + options = options || {}; + var o = { + $ref: this.collection, + $id: this.oid + }; + if (options.legacy) { + return o; + } + if (this.db) + o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + }; + /** @internal */ + DBRef.fromExtendedJSON = function (doc) { + var copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + }; + /** @internal */ + DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + DBRef.prototype.inspect = function () { + // NOTE: if OID is an ObjectId class it will just print the oid string. + var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); + return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; + }; + return DBRef; +}()); +exports.DBRef = DBRef; +Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); +//# sourceMappingURL=db_ref.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/db_ref.js.map b/node_modules/bson/lib/db_ref.js.map new file mode 100644 index 0000000..359088f --- /dev/null +++ b/node_modules/bson/lib/db_ref.js.map @@ -0,0 +1 @@ +{"version":3,"file":"db_ref.js","sourceRoot":"","sources":["../src/db_ref.ts"],"names":[],"mappings":";;;AAGA,wCAA8C;AAS9C,gBAAgB;AAChB,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,CACL,oBAAY,CAAC,KAAK,CAAC;QACnB,KAAK,CAAC,GAAG,IAAI,IAAI;QACjB,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,CAAC,KAAK,CAAC,GAAG,IAAI,IAAI,IAAI,OAAO,KAAK,CAAC,GAA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AoB,GAAG,YACxD,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,SAAM,IAAI,CAAC,EAAE,OAAG,CAAC,CAAC,CAAC,EAAE,OAC9B,CAAC;IACN,CAAC;IACH,YAAC;AAAD,CAAC,AA9FD,IA8FC;AA9FY,sBAAK;AAgGlB,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/decimal128.js b/node_modules/bson/lib/decimal128.js new file mode 100644 index 0000000..8df4db7 --- /dev/null +++ b/node_modules/bson/lib/decimal128.js @@ -0,0 +1,661 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Decimal128 = void 0; +var buffer_1 = require("buffer"); +var error_1 = require("./error"); +var long_1 = require("./long"); +var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; +var EXPONENT_MAX = 6111; +var EXPONENT_MIN = -6176; +var EXPONENT_BIAS = 6176; +var MAX_DIGITS = 34; +// Nan value bits as 32 bit values (due to lack of longs) +var NAN_BUFFER = [ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +var INF_NEGATIVE_BUFFER = [ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +var INF_POSITIVE_BUFFER = [ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +var EXPONENT_REGEX = /^([-+])?(\d+)?$/; +// Extract least significant 5 bits +var COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +var EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +var COMBINATION_INFINITY = 30; +// Value of combination field for NaN +var COMBINATION_NAN = 31; +// Detect if the value is a digit +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +// Divide two uint128 values +function divideu128(value) { + var DIVISOR = long_1.Long.fromNumber(1000 * 1000 * 1000); + var _rem = long_1.Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + for (var i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new long_1.Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + return { quotient: value, rem: _rem }; +} +// Multiply two Long values and return the 128 bit value +function multiply64x2(left, right) { + if (!left && !right) { + return { high: long_1.Long.fromNumber(0), low: long_1.Long.fromNumber(0) }; + } + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new long_1.Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new long_1.Long(right.getLowBits(), 0); + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new long_1.Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new long_1.Long(productLow.getLowBits(), 0)); + // Return the 128 bit result + return { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + // Make values unsigned + var uhleft = left.high >>> 0; + var uhright = right.high >>> 0; + // Compare high bits first + if (uhleft < uhright) { + return true; + } + else if (uhleft === uhright) { + var ulleft = left.low >>> 0; + var ulright = right.low >>> 0; + if (ulleft < ulright) + return true; + } + return false; +} +function invalidErr(string, message) { + throw new error_1.BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); +} +/** + * A class representation of the BSON Decimal128 type. + * @public + */ +var Decimal128 = /** @class */ (function () { + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + function Decimal128(bytes) { + if (!(this instanceof Decimal128)) + return new Decimal128(bytes); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else { + this.bytes = bytes; + } + } + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + Decimal128.fromString = function (representation) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = new long_1.Long(0, 0); + // The low 17 digits of the significand + var significandLow = new long_1.Long(0, 0); + // The biased exponent + var biasedExponent = 0; + // Read index + var index = 0; + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (representation.length >= 7000) { + throw new error_1.BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + // Results + var stringMatch = representation.match(PARSE_STRING_REGEXP); + var infMatch = representation.match(PARSE_INF_REGEXP); + var nanMatch = representation.match(PARSE_NAN_REGEXP); + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new error_1.BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + // full_match = stringMatch[0] + // sign = stringMatch[1] + var unsignedNumber = stringMatch[2]; + // stringMatch[3] is undefined if a whole number (ex "1", 12") + // but defined if a number w/ decimal in it (ex "1.0, 12.2") + var e = stringMatch[4]; + var expSign = stringMatch[5]; + var expNumber = stringMatch[6]; + // they provided e, but didn't give an exponent number. for ex "1e" + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + // they provided e, but didn't give a number before it. for ex "e1" + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + // Get the negative or positive sign + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + // Check if user passed Infinity or NaN + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(buffer_1.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + else if (representation[index] === 'N') { + return new Decimal128(buffer_1.Buffer.from(NAN_BUFFER)); + } + } + // Read all the digits + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) + invalidErr(representation, 'contains multiple periods'); + sawRadix = true; + index = index + 1; + continue; + } + if (nDigitsStored < 34) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + // Only store 34 digits + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + if (sawRadix && !nDigitsRead) + throw new error_1.BSONTypeError('' + representation + ' not a valid Decimal128 string'); + // Read exponent if exists + if (representation[index] === 'e' || representation[index] === 'E') { + // Read exponent digits + var match = representation.substr(++index).match(EXPONENT_REGEX); + // No digits read + if (!match || !match[2]) + return new Decimal128(buffer_1.Buffer.from(NAN_BUFFER)); + // Get exponent + exponent = parseInt(match[0], 10); + // Adjust the index + index = index + match[0].length; + } + // Return not a number + if (representation[index]) + return new Decimal128(buffer_1.Buffer.from(NAN_BUFFER)); + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } + else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (digits[firstNonZero + significantDigits - 1] === 0) { + significantDigits = significantDigits - 1; + } + } + } + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit. can only do this if < significant digits than # stored. + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } + else { + // adjust to round + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits) { + var endOfString = nDigitsRead; + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + // if negative, we need to increment again to account for - sign at start. + if (isNegative) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + if (roundBit) { + var dIdx = lastDigit; + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(buffer_1.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + } + } + } + // Encode significand + // The high 17 digits of the significand + significandHigh = long_1.Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = long_1.Long.fromNumber(0); + // read a zero + if (significantDigits === 0) { + significandHigh = long_1.Long.fromNumber(0); + significandLow = long_1.Long.fromNumber(0); + } + else if (lastDigit - firstDigit < 17) { + var dIdx = firstDigit; + significandLow = long_1.Long.fromNumber(digits[dIdx++]); + significandHigh = new long_1.Long(0, 0); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(long_1.Long.fromNumber(10)); + significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx])); + } + } + else { + var dIdx = firstDigit; + significandHigh = long_1.Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(long_1.Long.fromNumber(10)); + significandHigh = significandHigh.add(long_1.Long.fromNumber(digits[dIdx])); + } + significandLow = long_1.Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(long_1.Long.fromNumber(10)); + significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx])); + } + } + var significand = multiply64x2(significandHigh, long_1.Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(long_1.Long.fromNumber(1)); + } + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: long_1.Long.fromNumber(0), high: long_1.Long.fromNumber(0) }; + // Encode combination, exponent, and significand. + if (significand.high.shiftRightUnsigned(49).and(long_1.Long.fromNumber(1)).equals(long_1.Long.fromNumber(1))) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(long_1.Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent).and(long_1.Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x7fffffffffff))); + } + else { + dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x1ffffffffffff))); + } + dec.low = significand.low; + // Encode sign + if (isNegative) { + dec.high = dec.high.or(long_1.Long.fromString('9223372036854775808')); + } + // Encode into a buffer + var buffer = buffer_1.Buffer.alloc(16); + index = 0; + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + // Return the new Decimal128 + return new Decimal128(buffer); + }; + /** Create a string representation of the raw Decimal128 value */ + Decimal128.prototype.toString = function () { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) + significand[i] = 0; + // read pointer into significand + var index = 0; + // true if the number is zero + var is_zero = false; + // the most significant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: [0, 0, 0, 0] }; + // indexing variables + var j, k; + // Output string + var string = []; + // Unpack index + index = 0; + // Buffer reference + var buffer = this.bytes; + // Unpack the low 64bits into a long + // bits 96 - 127 + var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 64 - 95 + var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack the high 64bits into a long + // bits 32 - 63 + var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 0 - 31 + var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack index + index = 0; + // Create the state of the decimal + var dec = { + low: new long_1.Long(low, midl), + high: new long_1.Long(midh, high) + }; + if (dec.high.lessThan(long_1.Long.ZERO)) { + string.push('-'); + } + // Decode combination field and exponent + // bits 1 - 5 + var combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } + else if (combination === COMBINATION_NAN) { + return 'NaN'; + } + else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } + else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + // unbiased exponent + var exponent = biased_exponent - EXPONENT_BIAS; + // Create string of significand digits + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + if (significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0) { + is_zero = true; + } + else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Perform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + // the exponent if scientific notation is used + var scientific_exponent = significand_digits - 1 + exponent; + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + // if there are too many significant digits, we should just be treating numbers + // as + or - 0 and using the non-scientific exponent (this is for the "invalid + // representation should be treated as 0/-0" spec cases in decimal128-1.json) + if (significand_digits > 34) { + string.push("" + 0); + if (exponent > 0) + string.push('E+' + exponent); + else if (exponent < 0) + string.push('E' + exponent); + return string.join(''); + } + string.push("" + significand[index++]); + significand_digits = significand_digits - 1; + if (significand_digits) { + string.push('.'); + } + for (var i = 0; i < significand_digits; i++) { + string.push("" + significand[index++]); + } + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } + else { + string.push("" + scientific_exponent); + } + } + else { + // Regular format with no decimal place + if (exponent >= 0) { + for (var i = 0; i < significand_digits; i++) { + string.push("" + significand[index++]); + } + } + else { + var radix_position = significand_digits + exponent; + // non-zero digits before radix + if (radix_position > 0) { + for (var i = 0; i < radix_position; i++) { + string.push("" + significand[index++]); + } + } + else { + string.push('0'); + } + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push("" + significand[index++]); + } + } + } + return string.join(''); + }; + Decimal128.prototype.toJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.prototype.toExtendedJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.fromExtendedJSON = function (doc) { + return Decimal128.fromString(doc.$numberDecimal); + }; + /** @internal */ + Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Decimal128.prototype.inspect = function () { + return "new Decimal128(\"" + this.toString() + "\")"; + }; + return Decimal128; +}()); +exports.Decimal128 = Decimal128; +Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); +//# sourceMappingURL=decimal128.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/decimal128.js.map b/node_modules/bson/lib/decimal128.js.map new file mode 100644 index 0000000..361d621 --- /dev/null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,OAAO,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACzB,CAAC;IAED,2BAAM,GAAN;QACE,OAAO,EAAE,cAAc,EAAE,IAAI,CAAC,QAAQ,EAAE,EAAE,CAAC;IAC7C,CAAC;IAED,gBAAgB;IAChB,mCAAc,GAAd;QACE,OAAO,EAAE,cAAc,EAAE,IAAI,CAAC,QAAQ,EAAE,EAAE,CAAC;IAC7C,CAAC;IAED,gBAAgB;IACT,2BAAgB,GAAvB,UAAwB,GAAuB;QAC7C,OAAO,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IACnD,CAAC;IAED,gBAAgB;IAChB,qBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,4BAAO,GAAP;QACE,OAAO,sBAAmB,IAAI,CAAC,QAAQ,EAAE,QAAI,CAAC;IAChD,CAAC;IACH,iBAAC;AAAD,CAAC,AAnoBD,IAmoBC;AAnoBY,gCAAU;AAqoBvB,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/double.js b/node_modules/bson/lib/double.js new file mode 100644 index 0000000..5a2ce61 --- /dev/null +++ b/node_modules/bson/lib/double.js @@ -0,0 +1,75 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Double = void 0; +/** + * A class representation of the BSON Double type. + * @public + */ +var Double = /** @class */ (function () { + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + function Double(value) { + if (!(this instanceof Double)) + return new Double(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + Double.prototype.valueOf = function () { + return this.value; + }; + Double.prototype.toJSON = function () { + return this.value; + }; + Double.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + /** @internal */ + Double.prototype.toExtendedJSON = function (options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user + // explicitly provided `-0` then we need to ensure the sign makes it into the output + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: "-" + this.value.toFixed(1) }; + } + var $numberDouble; + if (Number.isInteger(this.value)) { + $numberDouble = this.value.toFixed(1); + if ($numberDouble.length >= 13) { + $numberDouble = this.value.toExponential(13).toUpperCase(); + } + } + else { + $numberDouble = this.value.toString(); + } + return { $numberDouble: $numberDouble }; + }; + /** @internal */ + Double.fromExtendedJSON = function (doc, options) { + var doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + }; + /** @internal */ + Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Double.prototype.inspect = function () { + var eJSON = this.toExtendedJSON(); + return "new Double(" + eJSON.$numberDouble + ")"; + }; + return Double; +}()); +exports.Double = Double; +Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); +//# sourceMappingURL=double.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/double.js.map b/node_modules/bson/lib/double.js.map new file mode 100644 index 0000000..a89a67e --- /dev/null +++ b/node_modules/bson/lib/double.js.map @@ -0,0 +1 @@ +{"version":3,"file":"double.js","sourceRoot":"","sources":["../src/double.ts"],"names":[],"mappings":";;;AAOA;;;GAGG;AACH;IAIE;;;;OAIG;IACH,gBAAY,KAAa;QACvB,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC;YAAE,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;QAExD,IAAK,KAAiB,YAAY,MAAM,EAAE;YACxC,KAAK,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;SACzB;QAED,IAAI,CAAC,KAAK,GAAG,CAAC,KAAK,CAAC;IACtB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OAAsB;QACjE,IAAM,WAAW,GAAG,UAAU,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAClD,OAAO,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,WAAW,CAAC,CAAC;IAC5E,CAAC;IAED,gBAAgB;IAChB,iBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,wBAAO,GAAP;QACE,IAAM,KAAK,GAAG,IAAI,CAAC,cAAc,EAAoB,CAAC;QACtD,OAAO,gBAAc,KAAK,CAAC,aAAa,MAAG,CAAC;IAC9C,CAAC;IACH,aAAC;AAAD,CAAC,AA5ED,IA4EC;AA5EY,wBAAM;AA8EnB,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/ensure_buffer.js b/node_modules/bson/lib/ensure_buffer.js new file mode 100644 index 0000000..633bd59 --- /dev/null +++ b/node_modules/bson/lib/ensure_buffer.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ensureBuffer = void 0; +var buffer_1 = require("buffer"); +var error_1 = require("./error"); +var utils_1 = require("./parser/utils"); +/** + * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. + * + * @param potentialBuffer - The potential buffer + * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that + * wraps a passed in Uint8Array + * @throws TypeError If anything other than a Buffer or Uint8Array is passed in + */ +function ensureBuffer(potentialBuffer) { + if (ArrayBuffer.isView(potentialBuffer)) { + return buffer_1.Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + if (utils_1.isAnyArrayBuffer(potentialBuffer)) { + return buffer_1.Buffer.from(potentialBuffer); + } + throw new error_1.BSONTypeError('Must use either Buffer or TypedArray'); +} +exports.ensureBuffer = ensureBuffer; +//# sourceMappingURL=ensure_buffer.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/ensure_buffer.js.map b/node_modules/bson/lib/ensure_buffer.js.map new file mode 100644 index 0000000..82bcfd3 --- /dev/null +++ b/node_modules/bson/lib/ensure_buffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ensure_buffer.js","sourceRoot":"","sources":["../src/ensure_buffer.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iCAAwC;AACxC,wCAAkD;AAElD;;;;;;;GAOG;AACH,SAAgB,YAAY,CAAC,eAAuD;IAClF,IAAI,WAAW,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE;QACvC,OAAO,eAAM,CAAC,IAAI,CAChB,eAAe,CAAC,MAAM,EACtB,eAAe,CAAC,UAAU,EAC1B,eAAe,CAAC,UAAU,CAC3B,CAAC;KACH;IAED,IAAI,wBAAgB,CAAC,eAAe,CAAC,EAAE;QACrC,OAAO,eAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;KACrC;IAED,MAAM,IAAI,qBAAa,CAAC,sCAAsC,CAAC,CAAC;AAClE,CAAC;AAdD,oCAcC"} \ No newline at end of file diff --git a/node_modules/bson/lib/error.js b/node_modules/bson/lib/error.js new file mode 100644 index 0000000..2f9e04c --- /dev/null +++ b/node_modules/bson/lib/error.js @@ -0,0 +1,51 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + 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); + }; + return function (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 __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BSONTypeError = exports.BSONError = void 0; +/** @public */ +var BSONError = /** @class */ (function (_super) { + __extends(BSONError, _super); + function BSONError() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(BSONError.prototype, "name", { + get: function () { + return 'BSONError'; + }, + enumerable: false, + configurable: true + }); + return BSONError; +}(Error)); +exports.BSONError = BSONError; +/** @public */ +var BSONTypeError = /** @class */ (function (_super) { + __extends(BSONTypeError, _super); + function BSONTypeError() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(BSONTypeError.prototype, "name", { + get: function () { + return 'BSONTypeError'; + }, + enumerable: false, + configurable: true + }); + return BSONTypeError; +}(TypeError)); +exports.BSONTypeError = BSONTypeError; +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/error.js.map b/node_modules/bson/lib/error.js.map new file mode 100644 index 0000000..fca1a49 --- /dev/null +++ b/node_modules/bson/lib/error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,cAAc;AACd;IAA+B,6BAAK;IAApC;;IAIA,CAAC;IAHC,sBAAI,2BAAI;aAAR;YACE,OAAO,WAAW,CAAC;QACrB,CAAC;;;OAAA;IACH,gBAAC;AAAD,CAAC,AAJD,CAA+B,KAAK,GAInC;AAJY,8BAAS;AAMtB,cAAc;AACd;IAAmC,iCAAS;IAA5C;;IAIA,CAAC;IAHC,sBAAI,+BAAI;aAAR;YACE,OAAO,eAAe,CAAC;QACzB,CAAC;;;OAAA;IACH,oBAAC;AAAD,CAAC,AAJD,CAAmC,SAAS,GAI3C;AAJY,sCAAa"} \ No newline at end of file diff --git a/node_modules/bson/lib/extended_json.js b/node_modules/bson/lib/extended_json.js new file mode 100644 index 0000000..cf489f2 --- /dev/null +++ b/node_modules/bson/lib/extended_json.js @@ -0,0 +1,378 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EJSON = exports.isBSONType = void 0; +var binary_1 = require("./binary"); +var code_1 = require("./code"); +var db_ref_1 = require("./db_ref"); +var decimal128_1 = require("./decimal128"); +var double_1 = require("./double"); +var error_1 = require("./error"); +var int_32_1 = require("./int_32"); +var long_1 = require("./long"); +var max_key_1 = require("./max_key"); +var min_key_1 = require("./min_key"); +var objectid_1 = require("./objectid"); +var utils_1 = require("./parser/utils"); +var regexp_1 = require("./regexp"); +var symbol_1 = require("./symbol"); +var timestamp_1 = require("./timestamp"); +function isBSONType(value) { + return (utils_1.isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); +} +exports.isBSONType = isBSONType; +// INT32 boundaries +var BSON_INT32_MAX = 0x7fffffff; +var BSON_INT32_MIN = -0x80000000; +// INT64 boundaries +var BSON_INT64_MAX = 0x7fffffffffffffff; +var BSON_INT64_MIN = -0x8000000000000000; +// all the types where we don't need to do any special processing and can just pass the EJSON +//straight to type.fromExtendedJSON +var keysToCodecs = { + $oid: objectid_1.ObjectId, + $binary: binary_1.Binary, + $uuid: binary_1.Binary, + $symbol: symbol_1.BSONSymbol, + $numberInt: int_32_1.Int32, + $numberDecimal: decimal128_1.Decimal128, + $numberDouble: double_1.Double, + $numberLong: long_1.Long, + $minKey: min_key_1.MinKey, + $maxKey: max_key_1.MaxKey, + $regex: regexp_1.BSONRegExp, + $regularExpression: regexp_1.BSONRegExp, + $timestamp: timestamp_1.Timestamp +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deserializeValue(value, options) { + if (options === void 0) { options = {}; } + if (typeof value === 'number') { + if (options.relaxed || options.legacy) { + return value; + } + // if it's an integer, should interpret as smallest BSON integer + // that can represent it exactly. (if out of range, interpret as double.) + if (Math.floor(value) === value) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) + return new int_32_1.Int32(value); + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) + return long_1.Long.fromNumber(value); + } + // If the number is a non-integer or out of integer range, should interpret as BSON Double. + return new double_1.Double(value); + } + // from here on out we're looking for bson types, so bail if its not an object + if (value == null || typeof value !== 'object') + return value; + // upgrade deprecated undefined to null + if (value.$undefined) + return null; + var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); + for (var i = 0; i < keys.length; i++) { + var c = keysToCodecs[keys[i]]; + if (c) + return c.fromExtendedJSON(value, options); + } + if (value.$date != null) { + var d = value.$date; + var date = new Date(); + if (options.legacy) { + if (typeof d === 'number') + date.setTime(d); + else if (typeof d === 'string') + date.setTime(Date.parse(d)); + } + else { + if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (long_1.Long.isLong(d)) + date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) + date.setTime(d); + } + return date; + } + if (value.$code != null) { + var copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return code_1.Code.fromExtendedJSON(value); + } + if (db_ref_1.isDBRefLike(value) || value.$dbPointer) { + var v = value.$ref ? value : value.$dbPointer; + // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) + // because of the order JSON.parse goes through the document + if (v instanceof db_ref_1.DBRef) + return v; + var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); + var valid_1 = true; + dollarKeys.forEach(function (k) { + if (['$ref', '$id', '$db'].indexOf(k) === -1) + valid_1 = false; + }); + // only make DBRef if $ keys are all valid + if (valid_1) + return db_ref_1.DBRef.fromExtendedJSON(v); + } + return value; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeArray(array, options) { + return array.map(function (v, index) { + options.seenObjects.push({ propertyName: "index " + index, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + var isoStr = date.toISOString(); + // we should only show milliseconds in timestamp if they're non-zero + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeValue(value, options) { + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); + if (index !== -1) { + var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); + var leadingPart = props + .slice(0, index) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var alreadySeen = props[index]; + var circularPart = ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var current = props[props.length - 1]; + var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new error_1.BSONTypeError('Converting circular structure to EJSON:\n' + + (" " + leadingPart + alreadySeen + circularPart + current + "\n") + + (" " + leadingSpace + "\\" + dashes + "/")); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || utils_1.isDate(value)) { + var dateNum = value.getTime(), + // is it in year range 1970-9999? + inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + // it's an integer + if (Math.floor(value) === value) { + var int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX, int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX; + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (int32Range) + return { $numberInt: value.toString() }; + if (int64Range) + return { $numberLong: value.toString() }; + } + return { $numberDouble: value.toString() }; + } + if (value instanceof RegExp || utils_1.isRegExp(value)) { + var flags = value.flags; + if (flags === undefined) { + var match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + var rx = new regexp_1.BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === 'object') + return serializeDocument(value, options); + return value; +} +var BSON_TYPE_MAPPINGS = { + Binary: function (o) { return new binary_1.Binary(o.value(), o.sub_type); }, + Code: function (o) { return new code_1.Code(o.code, o.scope); }, + DBRef: function (o) { return new db_ref_1.DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, + Decimal128: function (o) { return new decimal128_1.Decimal128(o.bytes); }, + Double: function (o) { return new double_1.Double(o.value); }, + Int32: function (o) { return new int_32_1.Int32(o.value); }, + Long: function (o) { + return long_1.Long.fromBits( + // underscore variants for 1.x backwards compatibility + o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); + }, + MaxKey: function () { return new max_key_1.MaxKey(); }, + MinKey: function () { return new min_key_1.MinKey(); }, + ObjectID: function (o) { return new objectid_1.ObjectId(o); }, + ObjectId: function (o) { return new objectid_1.ObjectId(o); }, + BSONRegExp: function (o) { return new regexp_1.BSONRegExp(o.pattern, o.options); }, + Symbol: function (o) { return new symbol_1.BSONSymbol(o.value); }, + Timestamp: function (o) { return timestamp_1.Timestamp.fromBits(o.low, o.high); } +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new error_1.BSONError('not an object instance'); + var bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + // It's a regular object. Recursively serialize its property values. + var _doc = {}; + for (var name in doc) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + _doc[name] = serializeValue(doc[name], options); + } + finally { + options.seenObjects.pop(); + } + } + return _doc; + } + else if (isBSONType(doc)) { + // the "document" is really just a BSON type object + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + // There's no EJSON serialization function on the object. It's probably an + // object created by a previous version of this library (or another library) + // that's duck-typing objects to look like they were generated by this library). + // Copy the object into this library's version of that type. + var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + // Two BSON types may have nested objects that may need to be serialized too + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new code_1.Code(outDoc.code, serializeValue(outDoc.scope, options)); + } + else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new db_ref_1.DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + } + return outDoc.toExtendedJSON(options); + } + else { + throw new error_1.BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} +/** + * EJSON parse / stringify API + * @public + */ +// the namespace here is used to emulate `export * as EJSON from '...'` +// which as of now (sept 2020) api-extractor does not support +// eslint-disable-next-line @typescript-eslint/no-namespace +var EJSON; +(function (EJSON) { + /** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ + function parse(text, options) { + var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); + // relaxed implies not strict + if (typeof finalOptions.relaxed === 'boolean') + finalOptions.strict = !finalOptions.relaxed; + if (typeof finalOptions.strict === 'boolean') + finalOptions.relaxed = !finalOptions.strict; + return JSON.parse(text, function (key, value) { + if (key.indexOf('\x00') !== -1) { + throw new error_1.BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key)); + } + return deserializeValue(value, finalOptions); + }); + } + EJSON.parse = parse; + /** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ + function stringify(value, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer, space, options) { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + var doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); + } + EJSON.stringify = stringify; + /** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ + function serialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); + } + EJSON.serialize = serialize; + /** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ + function deserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); + } + EJSON.deserialize = deserialize; +})(EJSON = exports.EJSON || (exports.EJSON = {})); +//# sourceMappingURL=extended_json.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/extended_json.js.map b/node_modules/bson/lib/extended_json.js.map new file mode 100644 index 0000000..ae3a2cc --- /dev/null +++ b/node_modules/bson/lib/extended_json.js.map @@ -0,0 +1 @@ +{"version":3,"file":"extended_json.js","sourceRoot":"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,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE;YAChF,WAAW,EAAE,CAAC,EAAE,YAAY,EAAE,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC;SACrD,CAAC,CAAC;QAEH,IAAM,GAAG,GAAG,cAAc,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;QACpD,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,QAA4C,EAAE,KAAK,CAAC,CAAC;IAClF,CAAC;IAtBe,eAAS,YAsBxB,CAAA;IAED;;;;;OAKG;IACH,SAAgB,SAAS,CAAC,KAAwB,EAAE,OAAuB;QACzE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QACxB,OAAO,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;IAC/C,CAAC;IAHe,eAAS,YAGxB,CAAA;IAED;;;;;OAKG;IACH,SAAgB,WAAW,CAAC,KAAe,EAAE,OAAuB;QAClE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QACxB,OAAO,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;IAC/C,CAAC;IAHe,iBAAW,cAG1B,CAAA;AACH,CAAC,EArHgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAqHrB"} \ No newline at end of file diff --git a/node_modules/bson/lib/float_parser.js b/node_modules/bson/lib/float_parser.js new file mode 100644 index 0000000..f78a3a0 --- /dev/null +++ b/node_modules/bson/lib/float_parser.js @@ -0,0 +1,137 @@ +"use strict"; +// Copyright (c) 2008, Fair Oaks Labs, 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 Fair Oaks Labs, 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. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White +Object.defineProperty(exports, "__esModule", { value: true }); +exports.writeIEEE754 = exports.readIEEE754 = void 0; +function readIEEE754(buffer, offset, endian, mLen, nBytes) { + var e; + var m; + var bBE = endian === 'big'; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = bBE ? 0 : nBytes - 1; + var d = bBE ? 1 : -1; + var s = buffer[offset + i]; + i += d; + e = s & ((1 << -nBits) - 1); + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) + ; + m = e & ((1 << -nBits) - 1); + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) + ; + if (e === 0) { + e = 1 - eBias; + } + else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } + else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +} +exports.readIEEE754 = readIEEE754; +function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) { + var e; + var m; + var c; + var bBE = endian === 'big'; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = bBE ? nBytes - 1 : 0; + var d = bBE ? -1 : 1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } + else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } + else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } + else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } + else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + if (isNaN(value)) + m = 0; + while (mLen >= 8) { + buffer[offset + i] = m & 0xff; + i += d; + m /= 256; + mLen -= 8; + } + e = (e << mLen) | m; + if (isNaN(value)) + e += 8; + eLen += mLen; + while (eLen > 0) { + buffer[offset + i] = e & 0xff; + i += d; + e /= 256; + eLen -= 8; + } + buffer[offset + i - d] |= s * 128; +} +exports.writeIEEE754 = writeIEEE754; +//# sourceMappingURL=float_parser.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/float_parser.js.map b/node_modules/bson/lib/float_parser.js.map new file mode 100644 index 0000000..5b68843 --- /dev/null +++ b/node_modules/bson/lib/float_parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"float_parser.js","sourceRoot":"","sources":["../src/float_parser.ts"],"names":[],"mappings":";AAAA,2CAA2C;AAC3C,uBAAuB;AACvB,EAAE;AACF,qEAAqE;AACrE,8EAA8E;AAC9E,EAAE;AACF,4EAA4E;AAC5E,2DAA2D;AAC3D,EAAE;AACF,+EAA+E;AAC/E,+EAA+E;AAC/E,4DAA4D;AAC5D,EAAE;AACF,gFAAgF;AAChF,2EAA2E;AAC3E,gDAAgD;AAChD,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,4EAA4E;AAC5E,sEAAsE;AACtE,uEAAuE;AACvE,2EAA2E;AAC3E,0EAA0E;AAC1E,0EAA0E;AAC1E,6EAA6E;AAC7E,8BAA8B;AAC9B,EAAE;AACF,EAAE;AACF,+EAA+E;;;AAI/E,SAAgB,WAAW,CACzB,MAAyB,EACzB,MAAc,EACd,MAAwB,EACxB,IAAY,EACZ,MAAc;IAEd,IAAI,CAAS,CAAC;IACd,IAAI,CAAS,CAAC;IACd,IAAM,GAAG,GAAG,MAAM,KAAK,KAAK,CAAC;IAC7B,IAAM,IAAI,GAAG,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC;IACnC,IAAM,IAAI,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;IAC7B,IAAM,KAAK,GAAG,IAAI,IAAI,CAAC,CAAC;IACxB,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC;IACf,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAC7B,IAAM,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,IAAI,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,CA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QAAE,CAAC,GAAG,CAAC,CAAC;IAExB,OAAO,IAAI,IAAI,CAAC,EAAE;QAChB,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;QAC9B,CAAC,IAAI,CAAC,CAAC;QACP,CAAC,IAAI,GAAG,CAAC;QACT,IAAI,IAAI,CAAC,CAAC;KACX;IAED,CAAC,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;IAEpB,IAAI,KAAK,CAAC,KAAK,CAAC;QAAE,CAAC,IAAI,CAAC,CAAC;IAEzB,IAAI,IAAI,IAAI,CAAC;IAEb,OAAO,IAAI,GAAG,CAAC,EAAE;QACf,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;QAC9B,CAAC,IAAI,CAAC,CAAC;QACP,CAAC,IAAI,GAAG,CAAC;QACT,IAAI,IAAI,CAAC,CAAC;KACX;IAED,MAAM,CAAC,MAAM,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC;AACpC,CAAC;AA5ED,oCA4EC"} \ No newline at end of file diff --git a/node_modules/bson/lib/int_32.js b/node_modules/bson/lib/int_32.js new file mode 100644 index 0000000..0fd9ce5 --- /dev/null +++ b/node_modules/bson/lib/int_32.js @@ -0,0 +1,57 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Int32 = void 0; +/** + * A class representation of a BSON Int32 type. + * @public + */ +var Int32 = /** @class */ (function () { + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + function Int32(value) { + if (!(this instanceof Int32)) + return new Int32(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { + return this.value; + }; + Int32.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + Int32.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + Int32.prototype.toExtendedJSON = function (options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + }; + /** @internal */ + Int32.fromExtendedJSON = function (doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + }; + /** @internal */ + Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Int32.prototype.inspect = function () { + return "new Int32(" + this.valueOf() + ")"; + }; + return Int32; +}()); +exports.Int32 = Int32; +Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); +//# sourceMappingURL=int_32.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/int_32.js.map b/node_modules/bson/lib/int_32.js.map new file mode 100644 index 0000000..073ebee --- /dev/null +++ b/node_modules/bson/lib/int_32.js.map @@ -0,0 +1 @@ +{"version":3,"file":"int_32.js","sourceRoot":"","sources":["../src/int_32.ts"],"names":[],"mappings":";;;AAOA;;;GAGG;AACH;IAIE;;;;OAIG;IACH,eAAY,KAAsB;QAChC,IAAI,CAAC,CAAC,IAAI,YAAY,KAAK,CAAC;YAAE,OAAO,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;QAEtD,IAAK,KAAiB,YAAY,MAAM,EAAE;YACxC,KAAK,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;SACzB;QAED,IAAI,CAAC,KAAK,GAAG,CAAC,KAAK,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACH,uBAAO,GAAP;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,wBAAQ,GAAR,UAAS,KAAc;QACrB,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAED,sBAAM,GAAN;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,gBAAgB;IAChB,8BAAc,GAAd,UAAe,OAAsB;QACnC,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC;YAAE,OAAO,IAAI,CAAC,KAAK,CAAC;QACtE,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC;IAC/C,CAAC;IAED,gBAAgB;IACT,sBAAgB,GAAvB,UAAwB,GAAkB,EAAE,OAAsB;QAChE,OAAO,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC/F,CAAC;IAED,gBAAgB;IAChB,gBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,uBAAO,GAAP;QACE,OAAO,eAAa,IAAI,CAAC,OAAO,EAAE,MAAG,CAAC;IACxC,CAAC;IACH,YAAC;AAAD,CAAC,AAvDD,IAuDC;AAvDY,sBAAK;AAyDlB,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/long.js b/node_modules/bson/lib/long.js new file mode 100644 index 0000000..3de7b1a --- /dev/null +++ b/node_modules/bson/lib/long.js @@ -0,0 +1,899 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Long = void 0; +var utils_1 = require("./parser/utils"); +/** + * wasm optimizations, to do native i64 multiplication and divide + */ +var wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module( + // prettier-ignore + new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; +} +catch (_a) { + // no wasm support +} +var TWO_PWR_16_DBL = 1 << 16; +var TWO_PWR_24_DBL = 1 << 24; +var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +/** A cache of the Long representations of small integer values. */ +var INT_CACHE = {}; +/** A cache of the Long representations of small unsigned integer values. */ +var UINT_CACHE = {}; +/** + * A class representing a 64-bit integer + * @public + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ +var Long = /** @class */ (function () { + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + function Long(low, high, unsigned) { + if (low === void 0) { low = 0; } + if (!(this instanceof Long)) + return new Long(low, high, unsigned); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } + else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } + else { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + Object.defineProperty(this, '__isLong__', { + value: true, + configurable: false, + writable: false, + enumerable: false + }); + } + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBits = function (lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + }; + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromInt = function (value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } + else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromNumber = function (value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; + } + else { + if (value <= -TWO_PWR_63_DBL) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBigInt = function (value, unsigned) { + return Long.fromString(value.toString(), unsigned); + }; + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + Long.fromString = function (str, unsigned, radix) { + if (str.length === 0) + throw Error('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + var p; + if ((p = str.indexOf('-')) > 0) + throw Error('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } + else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + }; + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + Long.fromBytes = function (bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + }; + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesLE = function (bytes, unsigned) { + return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); + }; + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesBE = function (bytes, unsigned) { + return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); + }; + /** + * Tests if the specified object is a Long. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + Long.isLong = function (value) { + return utils_1.isObjectLike(value) && value['__isLong__'] === true; + }; + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + Long.fromValue = function (val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + }; + /** Returns the sum of this and the specified Long. */ + Long.prototype.add = function (addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xffff; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + Long.prototype.and = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + }; + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + Long.prototype.compare = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + // At this point the sign bits are the same + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + }; + /** This is an alias of {@link Long.compare} */ + Long.prototype.comp = function (other) { + return this.compare(other); + }; + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + Long.prototype.divide = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw Error('division by zero'); + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + // be consistent with non-wasm code path + return this; + } + var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + var approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } + else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } + else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } + else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } + else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return Long.UONE; + res = Long.UZERO; + } + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + }; + /**This is an alias of {@link Long.divide} */ + Long.prototype.div = function (divisor) { + return this.divide(divisor); + }; + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + Long.prototype.equals = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + }; + /** This is an alias of {@link Long.equals} */ + Long.prototype.eq = function (other) { + return this.equals(other); + }; + /** Gets the high 32 bits as a signed integer. */ + Long.prototype.getHighBits = function () { + return this.high; + }; + /** Gets the high 32 bits as an unsigned integer. */ + Long.prototype.getHighBitsUnsigned = function () { + return this.high >>> 0; + }; + /** Gets the low 32 bits as a signed integer. */ + Long.prototype.getLowBits = function () { + return this.low; + }; + /** Gets the low 32 bits as an unsigned integer. */ + Long.prototype.getLowBitsUnsigned = function () { + return this.low >>> 0; + }; + /** Gets the number of bits needed to represent the absolute value of this Long. */ + Long.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + // Unsigned Longs are never negative + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + var val = this.high !== 0 ? this.high : this.low; + var bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + }; + /** Tests if this Long's value is greater than the specified's. */ + Long.prototype.greaterThan = function (other) { + return this.comp(other) > 0; + }; + /** This is an alias of {@link Long.greaterThan} */ + Long.prototype.gt = function (other) { + return this.greaterThan(other); + }; + /** Tests if this Long's value is greater than or equal the specified's. */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.comp(other) >= 0; + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.gte = function (other) { + return this.greaterThanOrEqual(other); + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.ge = function (other) { + return this.greaterThanOrEqual(other); + }; + /** Tests if this Long's value is even. */ + Long.prototype.isEven = function () { + return (this.low & 1) === 0; + }; + /** Tests if this Long's value is negative. */ + Long.prototype.isNegative = function () { + return !this.unsigned && this.high < 0; + }; + /** Tests if this Long's value is odd. */ + Long.prototype.isOdd = function () { + return (this.low & 1) === 1; + }; + /** Tests if this Long's value is positive. */ + Long.prototype.isPositive = function () { + return this.unsigned || this.high >= 0; + }; + /** Tests if this Long's value equals zero. */ + Long.prototype.isZero = function () { + return this.high === 0 && this.low === 0; + }; + /** Tests if this Long's value is less than the specified's. */ + Long.prototype.lessThan = function (other) { + return this.comp(other) < 0; + }; + /** This is an alias of {@link Long#lessThan}. */ + Long.prototype.lt = function (other) { + return this.lessThan(other); + }; + /** Tests if this Long's value is less than or equal the specified's. */ + Long.prototype.lessThanOrEqual = function (other) { + return this.comp(other) <= 0; + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.lte = function (other) { + return this.lessThanOrEqual(other); + }; + /** Returns this Long modulo the specified. */ + Long.prototype.modulo = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + // use wasm support if present + if (wasm) { + var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.mod = function (divisor) { + return this.modulo(divisor); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.rem = function (divisor) { + return this.modulo(divisor); + }; + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + Long.prototype.multiply = function (multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + // use wasm support if present + if (wasm) { + var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } + else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + // If both longs are small, use float multiplication + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xffff; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** This is an alias of {@link Long.multiply} */ + Long.prototype.mul = function (multiplier) { + return this.multiply(multiplier); + }; + /** Returns the Negation of this Long's value. */ + Long.prototype.negate = function () { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + }; + /** This is an alias of {@link Long.negate} */ + Long.prototype.neg = function () { + return this.negate(); + }; + /** Returns the bitwise NOT of this Long. */ + Long.prototype.not = function () { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + }; + /** Tests if this Long's value differs from the specified's. */ + Long.prototype.notEquals = function (other) { + return !this.equals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.neq = function (other) { + return this.notEquals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.ne = function (other) { + return this.notEquals(other); + }; + /** + * Returns the bitwise OR of this Long and the specified. + */ + Long.prototype.or = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + }; + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftLeft = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + }; + /** This is an alias of {@link Long.shiftLeft} */ + Long.prototype.shl = function (numBits) { + return this.shiftLeft(numBits); + }; + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRight = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + }; + /** This is an alias of {@link Long.shiftRight} */ + Long.prototype.shr = function (numBits) { + return this.shiftRight(numBits); + }; + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRightUnsigned = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + var high = this.high; + if (numBits < 32) { + var low = this.low; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); + } + else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shr_u = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shru = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + Long.prototype.subtract = function (subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + /** This is an alias of {@link Long.subtract} */ + Long.prototype.sub = function (subtrahend) { + return this.subtract(subtrahend); + }; + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + Long.prototype.toInt = function () { + return this.unsigned ? this.low >>> 0 : this.low; + }; + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + Long.prototype.toNumber = function () { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + /** Converts the Long to a BigInt (arbitrary precision). */ + Long.prototype.toBigInt = function () { + return BigInt(this.toString()); + }; + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + Long.prototype.toBytes = function (le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + Long.prototype.toBytesLE = function () { + var hi = this.high, lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + }; + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + Long.prototype.toBytesBE = function () { + var hi = this.high, lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + }; + /** + * Converts this Long to signed. + */ + Long.prototype.toSigned = function () { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + }; + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + Long.prototype.toString = function (radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + // Unsigned Longs are never negative + if (this.eq(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } + else + return '-' + this.neg().toString(radix); + } + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + // eslint-disable-next-line @typescript-eslint/no-this-alias + var rem = this; + var result = ''; + // eslint-disable-next-line no-constant-condition + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + var digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } + }; + /** Converts this Long to unsigned. */ + Long.prototype.toUnsigned = function () { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + }; + /** Returns the bitwise XOR of this Long and the given one. */ + Long.prototype.xor = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + }; + /** This is an alias of {@link Long.isZero} */ + Long.prototype.eqz = function () { + return this.isZero(); + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.le = function (other) { + return this.lessThanOrEqual(other); + }; + /* + **************************************************************** + * BSON SPECIFIC ADDITIONS * + **************************************************************** + */ + Long.prototype.toExtendedJSON = function (options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + }; + Long.fromExtendedJSON = function (doc, options) { + var result = Long.fromString(doc.$numberLong); + return options && options.relaxed ? result.toNumber() : result; + }; + /** @internal */ + Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Long.prototype.inspect = function () { + return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")"; + }; + Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); + /** Maximum unsigned value. */ + Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); + /** Signed zero */ + Long.ZERO = Long.fromInt(0); + /** Unsigned zero. */ + Long.UZERO = Long.fromInt(0, true); + /** Signed one. */ + Long.ONE = Long.fromInt(1); + /** Unsigned one. */ + Long.UONE = Long.fromInt(1, true); + /** Signed negative one. */ + Long.NEG_ONE = Long.fromInt(-1); + /** Maximum signed value. */ + Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + /** Minimum signed value. */ + Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + return Long; +}()); +exports.Long = Long; +Object.defineProperty(Long.prototype, '__isLong__', { value: true }); +Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); +//# sourceMappingURL=long.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/long.js.map b/node_modules/bson/lib/long.js.map new file mode 100644 index 0000000..1d5a359 --- /dev/null +++ b/node_modules/bson/lib/long.js.map @@ -0,0 +1 @@ +{"version":3,"file":"long.js","sourceRoot":"","sources":["../src/long.ts"],"names":[],"mappings":";;;AACA,wCAA8C;AAkB9C;;GAEG;AACH,IAAI,IAAI,GAAgC,SAAS,CAAC;AAMlD,IAAI;IACF,IAAI,GAAG,IAAI,WAAW,CAAC,QAAQ,CAC7B,IAAI,WAAW,CAAC,MAAM;IACpB,kBAAkB;IAClB,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EA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BY,oBAAI;AAy6BjB,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AACrE,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/map.js b/node_modules/bson/lib/map.js new file mode 100644 index 0000000..a92ae9c --- /dev/null +++ b/node_modules/bson/lib/map.js @@ -0,0 +1,123 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-explicit-any */ +// We have an ES6 Map available, return the native instance +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Map = void 0; +var global_1 = require("./utils/global"); +/** @public */ +var bsonMap; +exports.Map = bsonMap; +var bsonGlobal = global_1.getGlobal(); +if (bsonGlobal.Map) { + exports.Map = bsonMap = bsonGlobal.Map; +} +else { + // We will return a polyfill + exports.Map = bsonMap = /** @class */ (function () { + function Map(array) { + if (array === void 0) { array = []; } + this._keys = []; + this._values = {}; + for (var i = 0; i < array.length; i++) { + if (array[i] == null) + continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + } + Map.prototype.clear = function () { + this._keys = []; + this._values = {}; + }; + Map.prototype.delete = function (key) { + var value = this._values[key]; + if (value == null) + return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + Map.prototype.entries = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? [key, _this._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.forEach = function (callback, self) { + self = self || this; + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + Map.prototype.get = function (key) { + return this._values[key] ? this._values[key].v : undefined; + }; + Map.prototype.has = function (key) { + return this._values[key] != null; + }; + Map.prototype.keys = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.set = function (key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + Map.prototype.values = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? _this._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Object.defineProperty(Map.prototype, "size", { + get: function () { + return this._keys.length; + }, + enumerable: false, + configurable: true + }); + return Map; + }()); +} +//# sourceMappingURL=map.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/map.js.map b/node_modules/bson/lib/map.js.map new file mode 100644 index 0000000..972de88 --- /dev/null +++ b/node_modules/bson/lib/map.js.map @@ -0,0 +1 @@ +{"version":3,"file":"map.js","sourceRoot":"","sources":["../src/map.ts"],"names":[],"mappings":";AAAA,uDAAuD;AACvD,2DAA2D;;;AAE3D,yCAA2C;AAE3C,cAAc;AACd,IAAI,OAAuB,CAAC;AAgHR,sBAAG;AA9GvB,IAAM,UAAU,GAAG,kBAAS,EAA4B,CAAC;AACzD,IAAI,UAAU,CAAC,GAAG,EAAE;IAClB,cAAA,OAAO,GAAG,UAAU,CAAC,GAAG,CAAC;CAC1B;KAAM;IACL,4BAA4B;IAC5B,cAAA,OAAO,GAAG;QAGR,aAAY,KAA2B;YAA3B,sBAAA,EAAA,UAA2B;YACrC,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;YAChB,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;YAElB,KAA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A;QACH,UAAC;IAAD,CAAC,AAtGS,GAsGoB,CAAC;CAChC"} \ No newline at end of file diff --git a/node_modules/bson/lib/max_key.js b/node_modules/bson/lib/max_key.js new file mode 100644 index 0000000..c889eb8 --- /dev/null +++ b/node_modules/bson/lib/max_key.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MaxKey = void 0; +/** + * A class representation of the BSON MaxKey type. + * @public + */ +var MaxKey = /** @class */ (function () { + function MaxKey() { + if (!(this instanceof MaxKey)) + return new MaxKey(); + } + /** @internal */ + MaxKey.prototype.toExtendedJSON = function () { + return { $maxKey: 1 }; + }; + /** @internal */ + MaxKey.fromExtendedJSON = function () { + return new MaxKey(); + }; + /** @internal */ + MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MaxKey.prototype.inspect = function () { + return 'new MaxKey()'; + }; + return MaxKey; +}()); +exports.MaxKey = MaxKey; +Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); +//# sourceMappingURL=max_key.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/max_key.js.map b/node_modules/bson/lib/max_key.js.map new file mode 100644 index 0000000..5bf01f9 --- /dev/null +++ b/node_modules/bson/lib/max_key.js.map @@ -0,0 +1 @@ +{"version":3,"file":"max_key.js","sourceRoot":"","sources":["../src/max_key.ts"],"names":[],"mappings":";;;AAKA;;;GAGG;AACH;IAGE;QACE,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC;YAAE,OAAO,IAAI,MAAM,EAAE,CAAC;IACrD,CAAC;IAED,gBAAgB;IAChB,+BAAc,GAAd;QACE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IACxB,CAAC;IAED,gBAAgB;IACT,uBAAgB,GAAvB;QACE,OAAO,IAAI,MAAM,EAAE,CAAC;IACtB,CAAC;IAED,gBAAgB;IAChB,iBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,wBAAO,GAAP;QACE,OAAO,cAAc,CAAC;IACxB,CAAC;IACH,aAAC;AAAD,CAAC,AAzBD,IAyBC;AAzBY,wBAAM;AA2BnB,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/min_key.js b/node_modules/bson/lib/min_key.js new file mode 100644 index 0000000..0912043 --- /dev/null +++ b/node_modules/bson/lib/min_key.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MinKey = void 0; +/** + * A class representation of the BSON MinKey type. + * @public + */ +var MinKey = /** @class */ (function () { + function MinKey() { + if (!(this instanceof MinKey)) + return new MinKey(); + } + /** @internal */ + MinKey.prototype.toExtendedJSON = function () { + return { $minKey: 1 }; + }; + /** @internal */ + MinKey.fromExtendedJSON = function () { + return new MinKey(); + }; + /** @internal */ + MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MinKey.prototype.inspect = function () { + return 'new MinKey()'; + }; + return MinKey; +}()); +exports.MinKey = MinKey; +Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); +//# sourceMappingURL=min_key.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/min_key.js.map b/node_modules/bson/lib/min_key.js.map new file mode 100644 index 0000000..753012e --- /dev/null +++ b/node_modules/bson/lib/min_key.js.map @@ -0,0 +1 @@ +{"version":3,"file":"min_key.js","sourceRoot":"","sources":["../src/min_key.ts"],"names":[],"mappings":";;;AAKA;;;GAGG;AACH;IAGE;QACE,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC;YAAE,OAAO,IAAI,MAAM,EAAE,CAAC;IACrD,CAAC;IAED,gBAAgB;IAChB,+BAAc,GAAd;QACE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IACxB,CAAC;IAED,gBAAgB;IACT,uBAAgB,GAAvB;QACE,OAAO,IAAI,MAAM,EAAE,CAAC;IACtB,CAAC;IAED,gBAAgB;IAChB,iBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,wBAAO,GAAP;QACE,OAAO,cAAc,CAAC;IACxB,CAAC;IACH,aAAC;AAAD,CAAC,AAzBD,IAyBC;AAzBY,wBAAM;AA2BnB,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/objectid.js b/node_modules/bson/lib/objectid.js new file mode 100644 index 0000000..da2da05 --- /dev/null +++ b/node_modules/bson/lib/objectid.js @@ -0,0 +1,301 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ObjectId = void 0; +var buffer_1 = require("buffer"); +var ensure_buffer_1 = require("./ensure_buffer"); +var error_1 = require("./error"); +var utils_1 = require("./parser/utils"); +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +// Unique sequence for the current process (initialized on first use) +var PROCESS_UNIQUE = null; +var kId = Symbol('id'); +/** + * A class representation of the BSON ObjectId type. + * @public + */ +var ObjectId = /** @class */ (function () { + /** + * Create an ObjectId type + * + * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number. + */ + function ObjectId(id) { + if (!(this instanceof ObjectId)) + return new ObjectId(id); + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectId) { + this[kId] = id.id; + this.__id = id.__id; + } + if (typeof id === 'object' && id && 'id' in id) { + if ('toHexString' in id && typeof id.toHexString === 'function') { + this[kId] = buffer_1.Buffer.from(id.toHexString(), 'hex'); + } + else { + this[kId] = typeof id.id === 'string' ? buffer_1.Buffer.from(id.id) : id.id; + } + } + // The most common use case (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined); + // If we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + if (ArrayBuffer.isView(id) && id.byteLength === 12) { + this[kId] = ensure_buffer_1.ensureBuffer(id); + } + if (typeof id === 'string') { + if (id.length === 12) { + var bytes = buffer_1.Buffer.from(id); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + } + else if (id.length === 24 && checkForHexRegExp.test(id)) { + this[kId] = buffer_1.Buffer.from(id, 'hex'); + } + else { + throw new error_1.BSONTypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters'); + } + } + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + Object.defineProperty(ObjectId.prototype, "id", { + /** + * The ObjectId bytes + * @readonly + */ + get: function () { + return this[kId]; + }, + set: function (value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = value.toString('hex'); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ObjectId.prototype, "generationTime", { + /** + * The generation time of this ObjectId instance + * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch + */ + get: function () { + return this.id.readInt32BE(0); + }, + set: function (value) { + // Encode time into first 4 bytes + this.id.writeUInt32BE(value, 0); + }, + enumerable: false, + configurable: true + }); + /** Returns the ObjectId id as a 24 character hex string representation */ + ObjectId.prototype.toHexString = function () { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + var hexString = this.id.toString('hex'); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + }; + /** + * Update the ObjectId index + * @privateRemarks + * Used in generating new ObjectId's on the driver + * @internal + */ + ObjectId.getInc = function () { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + }; + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + ObjectId.generate = function (time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + var inc = ObjectId.getInc(); + var buffer = buffer_1.Buffer.alloc(12); + // 4-byte timestamp + buffer.writeUInt32BE(time, 0); + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = utils_1.randomBytes(5); + } + // 5-byte process unique + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + // 3-byte counter + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + }; + /** + * Converts the id into a 24 character hex string for printing + * + * @param format - The Buffer toString format parameter. + */ + ObjectId.prototype.toString = function (format) { + // Is the id a buffer then use the buffer toString method to return the format + if (format) + return this.id.toString(format); + return this.toHexString(); + }; + /** Converts to its JSON the 24 character hex string representation. */ + ObjectId.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + ObjectId.prototype.equals = function (otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this.toString() === otherId.toString(); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + utils_1.isUint8Array(this.id)) { + return otherId === buffer_1.Buffer.prototype.toString.call(this.id, 'latin1'); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { + return buffer_1.Buffer.from(otherId).equals(this.id); + } + if (typeof otherId === 'object' && + 'toHexString' in otherId && + typeof otherId.toHexString === 'function') { + return otherId.toHexString() === this.toHexString(); + } + return false; + }; + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + ObjectId.prototype.getTimestamp = function () { + var timestamp = new Date(); + var time = this.id.readUInt32BE(0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + }; + /** @internal */ + ObjectId.createPk = function () { + return new ObjectId(); + }; + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + ObjectId.createFromTime = function (time) { + var buffer = buffer_1.Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer.writeUInt32BE(time, 0); + // Return the new objectId + return new ObjectId(buffer); + }; + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + ObjectId.createFromHexString = function (hexString) { + // Throw an error if it's not a valid setup + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new error_1.BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(buffer_1.Buffer.from(hexString, 'hex')); + }; + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + ObjectId.isValid = function (id) { + if (id == null) + return false; + if (typeof id === 'number') { + return true; + } + if (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); + } + if (id instanceof ObjectId) { + return true; + } + if (utils_1.isUint8Array(id) && id.length === 12) { + return true; + } + // Duck-Typing detection of ObjectId like objects + if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { + if (typeof id.id === 'string') { + return id.id.length === 12; + } + return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); + } + return false; + }; + /** @internal */ + ObjectId.prototype.toExtendedJSON = function () { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + }; + /** @internal */ + ObjectId.fromExtendedJSON = function (doc) { + return new ObjectId(doc.$oid); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 24 character hex string representation. + * @internal + */ + ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + ObjectId.prototype.inspect = function () { + return "new ObjectId(\"" + this.toHexString() + "\")"; + }; + /** @internal */ + ObjectId.index = ~~(Math.random() * 0xffffff); + return ObjectId; +}()); +exports.ObjectId = ObjectId; +// Deprecated methods +Object.defineProperty(ObjectId.prototype, 'generate', { + value: utils_1.deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') +}); +Object.defineProperty(ObjectId.prototype, 'getInc', { + value: utils_1.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId.prototype, 'get_inc', { + value: utils_1.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId, 'get_inc', { + value: utils_1.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); +//# sourceMappingURL=objectid.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/objectid.js.map b/node_modules/bson/lib/objectid.js.map new file mode 100644 index 0000000..8aa7374 --- /dev/null +++ b/node_modules/bson/lib/objectid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"objectid.js","sourceRoot":"","sources":["../src/objectid.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iDAA+C;AAC/C,iCAAwC;AACxC,wCAAsE;AAEtE,+CAA+C;AAC/C,IAAM,iBAAiB,GAAG,IAAI,MAAM,CAAC,mBAAmB,CAAC,CAAC;AAE1D,qEAAqE;AACrE,IAAI,cAAc,GAAsB,IAAI,CAAC;AAc7C,IAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;AAEzB;;;GAGG;AACH;IAaE;;;;OAIG;IACH,kBAAY,EAAuD;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AC,EAAvB,CAAuB,EACzC,yDAAyD,CAC1D;CACF,CAAC,CAAC;AAEH,MAAM,CAAC,cAAc,CAAC,QAAQ,CAAC,SAAS,EAAE,QAAQ,EAAE;IAClD,KAAK,EAAE,iBAAS,CAAC,cAAM,OAAA,QAAQ,CAAC,MAAM,EAAE,EAAjB,CAAiB,EAAE,mDAAmD,CAAC;CAC/F,CAAC,CAAC;AAEH,MAAM,CAAC,cAAc,CAAC,QAAQ,CAAC,SAAS,EAAE,SAAS,EAAE;IACnD,KAAK,EAAE,iBAAS,CAAC,cAAM,OAAA,QAAQ,CAAC,MAAM,EAAE,EAAjB,CAAiB,EAAE,mDAAmD,CAAC;CAC/F,CAAC,CAAC;AAEH,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,SAAS,EAAE;IACzC,KAAK,EAAE,iBAAS,CAAC,cAAM,OAAA,QAAQ,CAAC,MAAM,EAAE,EAAjB,CAAiB,EAAE,mDAAmD,CAAC;CAC/F,CAAC,CAAC;AAEH,MAAM,CAAC,cAAc,CAAC,QAAQ,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/parser/calculate_size.js b/node_modules/bson/lib/parser/calculate_size.js new file mode 100644 index 0000000..47930ae --- /dev/null +++ b/node_modules/bson/lib/parser/calculate_size.js @@ -0,0 +1,193 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.calculateObjectSize = void 0; +var buffer_1 = require("buffer"); +var binary_1 = require("../binary"); +var constants = require("../constants"); +var utils_1 = require("./utils"); +function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = 4 + 1; + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } + else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +exports.calculateObjectSize = calculateObjectSize; +/** @internal */ +function calculateElement(name, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +value, serializeFunctions, isArray, ignoreUndefined) { + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (isArray === void 0) { isArray = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = false; } + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + buffer_1.Buffer.byteLength(name, 'utf8') + 1 + 4 + buffer_1.Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && + value >= constants.JS_INT_MIN && + value <= constants.JS_INT_MAX) { + if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) { + // 32 bit + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } + else { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } + else { + // 64 bit + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || utils_1.isDate(value)) { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + utils_1.isAnyArrayBuffer(value)) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (value['_bsontype'] === 'Decimal128') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } + else if (value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.Buffer.byteLength(value.code.toString(), 'utf8') + + 1); + } + } + else if (value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)); + } + } + else if (value['_bsontype'] === 'Symbol') { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + buffer_1.Buffer.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1); + } + else if (value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + // Add db reference if it exists + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || utils_1.isRegExp(value)) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value['_bsontype'] === 'BSONRegExp') { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.Buffer.byteLength(value.pattern, 'utf8') + + 1 + + buffer_1.Buffer.byteLength(value.options, 'utf8') + + 1); + } + else { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || utils_1.isRegExp(value) || String.call(value) === '[object RegExp]') { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.Buffer.byteLength(utils_1.normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else if (serializeFunctions) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.Buffer.byteLength(utils_1.normalizedFunctionString(value), 'utf8') + + 1); + } + } + } + return 0; +} +//# sourceMappingURL=calculate_size.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/parser/calculate_size.js.map b/node_modules/bson/lib/parser/calculate_size.js.map new file mode 100644 index 0000000..f257092 --- /dev/null +++ b/node_modules/bson/lib/parser/calculate_size.js.map @@ -0,0 +1 @@ +{"version":3,"file":"calculate_size.js","sourceRoot":"","sources":["../../src/parser/calculate_size.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,oCAAmC;AAEnC,wCAA0C;AAC1C,iCAAuF;AAEvF,SAAgB,mBAAmB,CACjC,MAAgB,EAChB,kBAA4B,EAC5B,eAAyB;IAEzB,IAAI,WAAW,GAAG,CAAC,GAAG,CAAC,CAAC;IAExB,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QACzB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACtC,WAAW,IAAI,gBAAgB,CAC7B,CAAC,CAAC,QAAQ,EAAE,EACZ,MAAM,CAAC,CAAC,CAAC,EACT,kBAAkB,EAClB,IAAI,EACJ,eAAe,CAChB,CAAC;SACH;KACF;SAAM;QACL,yDAAyD;QAEzD,IAAI,MAAM,CAAC,MAAM,EAAE;YACjB,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC;SAC1B;QAED,iBAAiB;QACjB,KAAK,IAAM,GAAG,IAAI,MAAM,EAAE;YACxB,WAAW,IAAI,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,kBAAkB,EAAE,KAAK,EAAE,eAAe,CAAC,CAAC;SAC/F;KACF;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;AA/BD,kDA+BC;AAED,gBAAgB;AAChB,SAAS,gBAAgB,CACvB,IAAY;AACZ,8DAA8D;AAC9D,KAAU,EACV,kBAA0B,EAC1B,OAAe,EACf,eAAuB;IAFvB,mCAAA,EAAA,0BAA0B;IAC1B,wBAAA,EAAA,eAAe;IACf,gCAAA,EAAA,uBAAuB;IAEvB,yDAAyD;IACzD,IAAI,KAAK,IAAI,KAAK,CA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ACF;KACJ;IAED,OAAO,CAAC,CAAC;AACX,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/parser/deserializer.js b/node_modules/bson/lib/parser/deserializer.js new file mode 100644 index 0000000..d0d1f69 --- /dev/null +++ b/node_modules/bson/lib/parser/deserializer.js @@ -0,0 +1,587 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.deserialize = void 0; +var buffer_1 = require("buffer"); +var binary_1 = require("../binary"); +var code_1 = require("../code"); +var constants = require("../constants"); +var db_ref_1 = require("../db_ref"); +var decimal128_1 = require("../decimal128"); +var double_1 = require("../double"); +var error_1 = require("../error"); +var int_32_1 = require("../int_32"); +var long_1 = require("../long"); +var max_key_1 = require("../max_key"); +var min_key_1 = require("../min_key"); +var objectid_1 = require("../objectid"); +var regexp_1 = require("../regexp"); +var symbol_1 = require("../symbol"); +var timestamp_1 = require("../timestamp"); +var validate_utf8_1 = require("../validate_utf8"); +// Internal long versions +var JS_INT_MAX_LONG = long_1.Long.fromNumber(constants.JS_INT_MAX); +var JS_INT_MIN_LONG = long_1.Long.fromNumber(constants.JS_INT_MIN); +var functionCache = {}; +function deserialize(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (size < 5) { + throw new error_1.BSONError("bson size must be >= 5, is " + size); + } + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new error_1.BSONError("buffer length " + buffer.length + " must be >= bson size " + size); + } + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new error_1.BSONError("buffer length " + buffer.length + " must === bson size " + size); + } + if (size + index > buffer.byteLength) { + throw new error_1.BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); + } + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new error_1.BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +} +exports.deserialize = deserialize; +var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray) { + if (isArray === void 0) { isArray = false; } + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + // Set the start index + var startIndex = index; + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) + throw new error_1.BSONError('corrupt bson message < 5 bytes long'); + // Read the document size + var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) + throw new error_1.BSONError('corrupt bson message'); + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + var done = false; + var isPossibleDBRef = isArray ? false : null; + // While we have more left data left keep parsing + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) + break; + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.byteLength) + throw new error_1.BSONError('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + var value = void 0; + index = i + 1; + if (elementType === constants.BSON_DATA_STRING) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new error_1.BSONError('bad string length in bson'); + } + value = getValidatedString(buffer, index, index + stringSize - 1); + index = index + stringSize; + } + else if (elementType === constants.BSON_DATA_OID) { + var oid = buffer_1.Buffer.alloc(12); + buffer.copy(oid, 0, index, index + 12); + value = new objectid_1.ObjectId(oid); + index = index + 12; + } + else if (elementType === constants.BSON_DATA_INT && promoteValues === false) { + value = new int_32_1.Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === constants.BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === constants.BSON_DATA_NUMBER && promoteValues === false) { + value = new double_1.Double(buffer.readDoubleLE(index)); + index = index + 8; + } + else if (elementType === constants.BSON_DATA_NUMBER) { + value = buffer.readDoubleLE(index); + index = index + 8; + } + else if (elementType === constants.BSON_DATA_DATE) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Date(new long_1.Long(lowBits, highBits).toNumber()); + } + else if (elementType === constants.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new error_1.BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === constants.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new error_1.BSONError('bad embedded document length in bson'); + // We have a raw value + if (raw) { + value = buffer.slice(index, index + objectSize); + } + else { + value = deserializeObject(buffer, _index, options, false); + } + index = index + objectSize; + } + else if (elementType === constants.BSON_DATA_ARRAY) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + var arrayOptions = options; + // Stop index + var stopIndex = index + objectSize; + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) { + arrayOptions[n] = options[n]; + } + arrayOptions['raw'] = true; + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + if (buffer[index - 1] !== 0) + throw new error_1.BSONError('invalid array terminator byte'); + if (index !== stopIndex) + throw new error_1.BSONError('corrupted array bson'); + } + else if (elementType === constants.BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === constants.BSON_DATA_NULL) { + value = null; + } + else if (elementType === constants.BSON_DATA_LONG) { + // Unpack the low and high bits + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var long = new long_1.Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } + else { + value = long; + } + } + else if (elementType === constants.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = buffer_1.Buffer.alloc(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new decimal128_1.Decimal128(bytes); + // If we have an alternative mapper use that + if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { + value = decimal128.toObject(); + } + else { + value = decimal128; + } + } + else if (elementType === constants.BSON_DATA_BINARY) { + var binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var totalBinarySize = binarySize; + var subType = buffer[index++]; + // Did we have a negative binary size, throw + if (binarySize < 0) + throw new error_1.BSONError('Negative binary type element size found'); + // Is the length longer than the document + if (binarySize > buffer.byteLength) + throw new error_1.BSONError('Binary type size larger than document size'); + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new error_1.BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = buffer.slice(index, index + binarySize); + } + else { + value = new binary_1.Binary(buffer.slice(index, index + binarySize), subType); + } + } + else { + var _buffer = buffer_1.Buffer.alloc(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new error_1.BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else { + value = new binary_1.Binary(_buffer, subType); + } + } + // Update the index + index = index + binarySize; + } + else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new error_1.BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new error_1.BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + value = new RegExp(source, optionsArray.join('')); + } + else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new error_1.BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new error_1.BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // Set the object + value = new regexp_1.BSONRegExp(source, regExpOptions); + } + else if (elementType === constants.BSON_DATA_SYMBOL) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new error_1.BSONError('bad string length in bson'); + } + var symbol = getValidatedString(buffer, index, index + stringSize - 1); + value = promoteValues ? symbol : new symbol_1.BSONSymbol(symbol); + index = index + stringSize; + } + else if (elementType === constants.BSON_DATA_TIMESTAMP) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new timestamp_1.Timestamp(lowBits, highBits); + } + else if (elementType === constants.BSON_DATA_MIN_KEY) { + value = new min_key_1.MinKey(); + } + else if (elementType === constants.BSON_DATA_MAX_KEY) { + value = new max_key_1.MaxKey(); + } + else if (elementType === constants.BSON_DATA_CODE) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new error_1.BSONError('bad string length in bson'); + } + var functionString = getValidatedString(buffer, index, index + stringSize - 1); + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + } + else { + value = new code_1.Code(functionString); + } + // Update parse index position + index = index + stringSize; + } + else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new error_1.BSONError('code_w_scope total size shorter minimum expected length'); + } + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new error_1.BSONError('bad string length in bson'); + } + // Javascript function + var functionString = getValidatedString(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + var _index = index; + // Decode the size of the object document + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + // Check if field length is too short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new error_1.BSONError('code_w_scope total size is too short, truncating scope'); + } + // Check if totalSize field is too long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new error_1.BSONError('code_w_scope total size is too long, clips outer document'); + } + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + value.scope = scopeObject; + } + else { + value = new code_1.Code(functionString, scopeObject); + } + } + else if (elementType === constants.BSON_DATA_DBPOINTER) { + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) + throw new error_1.BSONError('bad string length in bson'); + // Namespace + if (!validate_utf8_1.validateUtf8(buffer, index, index + stringSize - 1)) { + throw new error_1.BSONError('Invalid UTF-8 string in BSON document'); + } + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Read the oid + var oidBuffer = buffer_1.Buffer.alloc(12); + buffer.copy(oidBuffer, 0, index, index + 12); + var oid = new objectid_1.ObjectId(oidBuffer); + // Update the index + index = index + 12; + // Upgrade to DBRef type + value = new db_ref_1.DBRef(namespace, oid); + } + else { + throw new error_1.BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value: value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + object[name] = value; + } + } + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) + throw new error_1.BSONError('corrupt array bson'); + throw new error_1.BSONError('corrupt object bson'); + } + // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef + if (!isPossibleDBRef) + return object; + if (db_ref_1.isDBRefLike(object)) { + var copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new db_ref_1.DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} +/** + * Ensure eval is isolated, store the result in functionCache. + * + * @internal + */ +function isolateEval(functionString, functionCache, object) { + if (!functionCache) + return new Function(functionString); + // Check for cache hit, eval if missing and return cached function + if (functionCache[functionString] == null) { + functionCache[functionString] = new Function(functionString); + } + // Set the object + return functionCache[functionString].bind(object); +} +function getValidatedString(buffer, start, end) { + var value = buffer.toString('utf8', start, end); + for (var i = 0; i < value.length; i++) { + if (value.charCodeAt(i) === 0xfffd) { + if (!validate_utf8_1.validateUtf8(buffer, start, end)) { + throw new error_1.BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + return value; +} +//# sourceMappingURL=deserializer.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/parser/deserializer.js.map b/node_modules/bson/lib/parser/deserializer.js.map new file mode 100644 index 0000000..8e82ecd --- /dev/null +++ b/node_modules/bson/lib/parser/deserializer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deserializer.js","sourceRoot":"","sources":["../../src/parser/deserializer.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,oCAAmC;AAEnC,gCAA+B;AAC/B,wCAA0C;AAC1C,oCAA0D;AAC1D,4CAA2C;AAC3C,oCAAmC;AACnC,kCAAqC;AACrC,oCAAkC;AAClC,gCAA+B;AAC/B,sCAAoC;AACpC,sCAAoC;AACpC,wCAAuC;AACvC,oCAAuC;AACvC,oCAAuC;AACvC,0CAAyC;AACzC,kDAAgD;AAgChD,yBAAyB;AACzB,IAAM,eAAe,GAAG,WAAI,CAA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QAAQ,CAAC,cAAc,CAAC,CAAC;KAC9D;IAED,iBAAiB;IACjB,OAAO,aAAa,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACpD,CAAC;AAED,SAAS,kBAAkB,CAAC,MAAc,EAAE,KAAa,EAAE,GAAW;IACpE,IAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;IAClD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACrC,IAAI,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE;YAClC,IAAI,CAAC,4BAAY,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,EAAE;gBACrC,MAAM,IAAI,iBAAS,CAAC,uCAAuC,CAAC,CAAC;aAC9D;YACD,MAAM;SACP;KACF;IACD,OAAO,KAAK,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/parser/serializer.js b/node_modules/bson/lib/parser/serializer.js new file mode 100644 index 0000000..331e9ec --- /dev/null +++ b/node_modules/bson/lib/parser/serializer.js @@ -0,0 +1,869 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.serializeInto = void 0; +var binary_1 = require("../binary"); +var constants = require("../constants"); +var ensure_buffer_1 = require("../ensure_buffer"); +var error_1 = require("../error"); +var extended_json_1 = require("../extended_json"); +var float_parser_1 = require("../float_parser"); +var long_1 = require("../long"); +var map_1 = require("../map"); +var utils_1 = require("./utils"); +var regexp = /\x00/; // eslint-disable-line no-control-regex +var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +/* + * isArray indicates if we are writing to a BSON array (type 0x04) + * which forces the "key" which really an array index as a string to be written as ascii + * This will catch any errors in index as a string generation + */ +function serializeString(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = constants.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, undefined, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} +function serializeNumber(buffer, key, value, index, isArray) { + // We have an integer value + // TODO(NODE-2529): Add support for big int + if (Number.isInteger(value) && + value >= constants.BSON_INT32_MIN && + value <= constants.BSON_INT32_MAX) { + // If the value fits in 32 bits encode as int32 + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } + else { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + float_parser_1.writeIEEE754(buffer, value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + } + return index; +} +function serializeNull(buffer, key, _, index, isArray) { + // Set long type + buffer[index++] = constants.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var dateInMilis = long_1.Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} +function serializeRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.ignoreCase) + buffer[index++] = 0x69; // i + if (value.global) + buffer[index++] = 0x73; // s + if (value.multiline) + buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.pattern, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = constants.BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = constants.BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = constants.BSON_DATA_MAX_KEY; + } + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, undefined, 'binary'); + } + else if (utils_1.isUint8Array(value.id)) { + // Use the standard JS methods here because buffer.copy() is buggy with the + // browser polyfill + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new error_1.BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + // Adjust index + return index + 12; +} +function serializeBuffer(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + buffer.set(ensure_buffer_1.ensureBuffer(value), index); + // Adjust the index + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (path === void 0) { path = []; } + for (var i = 0; i < path.length; i++) { + if (path[i] === value) + throw new error_1.BSONError('cyclic dependency detected'); + } + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index, isArray) { + buffer[index++] = constants.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + // Prefer the standard JS methods because their typechecking is not buggy, + // unlike the `buffer` polyfill's. + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} +function serializeLong(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} +function serializeInt32(buffer, key, value, index, isArray) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +} +function serializeDouble(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + float_parser_1.writeIEEE754(buffer, value.value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + return index; +} +function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { + if (_checkKeys === void 0) { _checkKeys = false; } + if (_depth === void 0) { _depth = 0; } + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = utils_1.normalizedFunctionString(value); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Starting index + var startIndex = index; + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + index = endIndex - 1; + // Writ the total + var totalSize = endIndex - startIndex; + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } + else { + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === binary_1.Binary.SUBTYPE_BYTE_ARRAY) + size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + // Write the data to the object + buffer.set(data, index); + // Adjust the index + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var startIndex = index; + var output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (startingIndex === void 0) { startingIndex = 0; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (path === void 0) { path = []; } + startingIndex = startingIndex || 0; + path = path || []; + // Push the object to the path + path.push(object); + // Start place to serialize into + var index = startingIndex + 4; + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') + throw new error_1.BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index, true); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } + else if (typeof value === 'bigint') { + throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } + else if (value instanceof Date || utils_1.isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } + else if (utils_1.isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } + else if (value instanceof RegExp || utils_1.isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } + else if (typeof value === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } + else if (typeof value === 'object' && + extended_json_1.isBSONType(value) && + value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + else if (object instanceof map_1.Map || utils_1.isMap(object)) { + var iterator = object.entries(); + var done = false; + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = !!entry.done; + // Are we done, then skip and terminate + if (done) + continue; + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint' || utils_1.isBigInt64Array(value) || utils_1.isBigUInt64Array(value)) { + throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || utils_1.isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if (utils_1.isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || utils_1.isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') + throw new error_1.BSONTypeError('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new error_1.BSONTypeError('toBSON function did not return an object'); + } + // Iterate over all the keys + for (var key in object) { + var value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') + throw new error_1.BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || utils_1.isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if (utils_1.isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || utils_1.isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + // Remove the path + path.pop(); + // Final padding byte for object + buffer[index++] = 0x00; + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} +exports.serializeInto = serializeInto; +//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/parser/serializer.js.map b/node_modules/bson/lib/parser/serializer.js.map new file mode 100644 index 0000000..834ae18 --- /dev/null +++ b/node_modules/bson/lib/parser/serializer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"serializer.js","sourceRoot":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AM,IAAI,KAAK,CAAC,WAAW,CAAC,KAAK,OAAO,EAAE;gBACzC,KAAK,GAAG,cAAc,CAAC,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;aACnD;iBAAM,IAAI,KAAK,CAAC,WAAW,CAAC,KAAK,QAAQ,IAAI,KAAK,CAAC,WAAW,CAAC,KAAK,QAAQ,EAAE;gBAC7E,KAAK,GAAG,eAAe,CAAC,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;aACpD;iBAAM,IAAI,OAAO,KAAK,CAAC,WAAW,CAAC,KAAK,WAAW,EAAE;gBACpD,MAAM,IAAI,qBAAa,CAAC,qCAAqC,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC;aACrF;SACF;KACF;IAED,kBAAkB;IAClB,IAAI,CAAC,GAAG,EAAE,CAAC;IAEX,gCAAgC;IAChC,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC;IAEvB,aAAa;IACb,IAAM,IAAI,GAAG,KAAK,GAAG,aAAa,CAAC;IACnC,+BAA+B;IAC/B,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;IACtC,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC;IAC7C,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC;IAC9C,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC;IAC9C,OAAO,KAAK,CAAC;AACf,CAAC;AAxUD,sCAwUC"} \ No newline at end of file diff --git a/node_modules/bson/lib/parser/utils.js b/node_modules/bson/lib/parser/utils.js new file mode 100644 index 0000000..88817ec --- /dev/null +++ b/node_modules/bson/lib/parser/utils.js @@ -0,0 +1,111 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.deprecate = exports.isObjectLike = exports.isDate = exports.haveBuffer = exports.isMap = exports.isRegExp = exports.isBigUInt64Array = exports.isBigInt64Array = exports.isUint8Array = exports.isAnyArrayBuffer = exports.randomBytes = exports.normalizedFunctionString = void 0; +var buffer_1 = require("buffer"); +var global_1 = require("../utils/global"); +/** + * Normalizes our expected stringified form of a function across versions of node + * @param fn - The function to stringify + */ +function normalizedFunctionString(fn) { + return fn.toString().replace('function(', 'function ('); +} +exports.normalizedFunctionString = normalizedFunctionString; +function isReactNative() { + var g = global_1.getGlobal(); + return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; +} +var insecureRandomBytes = function insecureRandomBytes(size) { + var insecureWarning = isReactNative() + ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; + console.warn(insecureWarning); + var result = buffer_1.Buffer.alloc(size); + for (var i = 0; i < size; ++i) + result[i] = Math.floor(Math.random() * 256); + return result; +}; +var detectRandomBytes = function () { + if (typeof window !== 'undefined') { + // browser crypto implementation(s) + var target_1 = window.crypto || window.msCrypto; // allow for IE11 + if (target_1 && target_1.getRandomValues) { + return function (size) { return target_1.getRandomValues(buffer_1.Buffer.alloc(size)); }; + } + } + if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { + // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global + return function (size) { return global.crypto.getRandomValues(buffer_1.Buffer.alloc(size)); }; + } + var requiredRandomBytes; + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + requiredRandomBytes = require('crypto').randomBytes; + } + catch (e) { + // keep the fallback + } + // NOTE: in transpiled cases the above require might return null/undefined + return requiredRandomBytes || insecureRandomBytes; +}; +exports.randomBytes = detectRandomBytes(); +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +exports.isAnyArrayBuffer = isAnyArrayBuffer; +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +exports.isUint8Array = isUint8Array; +function isBigInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigInt64Array]'; +} +exports.isBigInt64Array = isBigInt64Array; +function isBigUInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigUint64Array]'; +} +exports.isBigUInt64Array = isBigUInt64Array; +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +exports.isMap = isMap; +/** Call to check if your environment has `Buffer` */ +function haveBuffer() { + return typeof global !== 'undefined' && typeof global.Buffer !== 'undefined'; +} +exports.haveBuffer = haveBuffer; +// To ensure that 0.4 of node works correctly +function isDate(d) { + return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; +} +exports.isDate = isDate; +/** + * @internal + * this is to solve the `'someKey' in x` problem where x is unknown. + * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 + */ +function isObjectLike(candidate) { + return typeof candidate === 'object' && candidate !== null; +} +exports.isObjectLike = isObjectLike; +function deprecate(fn, message) { + var warned = false; + function deprecated() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!warned) { + console.warn(message); + warned = true; + } + return fn.apply(this, args); + } + return deprecated; +} +exports.deprecate = deprecate; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/parser/utils.js.map b/node_modules/bson/lib/parser/utils.js.map new file mode 100644 index 0000000..caa7cec --- /dev/null +++ b/node_modules/bson/lib/parser/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/parser/utils.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,0CAA4C;AAI5C;;;GAGG;AACH,SAAgB,wBAAwB,CAA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C;AACjE,CAAC;AAFD,4BAEC;AAED,SAAgB,KAAK,CAAC,CAAU;IAC9B,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,cAAc,CAAC;AAC9D,CAAC;AAFD,sBAEC;AAED,qDAAqD;AACrD,SAAgB,UAAU;IACxB,OAAO,OAAO,MAAM,KAAK,WAAW,IAAI,OAAO,MAAM,CAAC,MAAM,KAAK,WAAW,CAAC;AAC/E,CAAC;AAFD,gCAEC;AAED,6CAA6C;AAC7C,SAAgB,MAAM,CAAC,CAAU;IAC/B,OAAO,YAAY,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,eAAe,CAAC;AAClF,CAAC;AAFD,wBAEC;AAED;;;;GAIG;AACH,SAAgB,YAAY,CAAC,SAAkB;IAC7C,OAAO,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,KAAK,IAAI,CAAC;AAC7D,CAAC;AAFD,oCAEC;AAGD,SAAgB,SAAS,CAAqB,EAAK,EAAE,OAAe;IAClE,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,SAAS,UAAU;QAAgB,cAAkB;aAAlB,UAAkB,EAAlB,qBAAkB,EAAlB,IAAkB;YAAlB,yBAAkB;;QACnD,IAAI,CAAC,MAAM,EAAE;YACX,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACtB,MAAM,GAAG,IAAI,CAAC;SACf;QACD,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,UAA0B,CAAC;AACpC,CAAC;AAVD,8BAUC"} \ No newline at end of file diff --git a/node_modules/bson/lib/regexp.js b/node_modules/bson/lib/regexp.js new file mode 100644 index 0000000..079fb3c --- /dev/null +++ b/node_modules/bson/lib/regexp.js @@ -0,0 +1,73 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BSONRegExp = void 0; +var error_1 = require("./error"); +function alphabetize(str) { + return str.split('').sort().join(''); +} +/** + * A class representation of the BSON RegExp type. + * @public + */ +var BSONRegExp = /** @class */ (function () { + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) + return new BSONRegExp(pattern, options); + this.pattern = pattern; + this.options = alphabetize(options !== null && options !== void 0 ? options : ''); + if (this.pattern.indexOf('\x00') !== -1) { + throw new error_1.BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); + } + if (this.options.indexOf('\x00') !== -1) { + throw new error_1.BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); + } + // Validate options + for (var i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u')) { + throw new error_1.BSONError("The regular expression option [" + this.options[i] + "] is not supported"); + } + } + } + BSONRegExp.parseOptions = function (options) { + return options ? options.split('').sort().join('') : ''; + }; + /** @internal */ + BSONRegExp.prototype.toExtendedJSON = function (options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + }; + /** @internal */ + BSONRegExp.fromExtendedJSON = function (doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + // This is for $regex query operators that have extended json values. + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc; + } + } + else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); + } + throw new error_1.BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); + }; + return BSONRegExp; +}()); +exports.BSONRegExp = BSONRegExp; +Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); +//# sourceMappingURL=regexp.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/regexp.js.map b/node_modules/bson/lib/regexp.js.map new file mode 100644 index 0000000..79464b5 --- /dev/null +++ b/node_modules/bson/lib/regexp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"regexp.js","sourceRoot":"","sources":["../src/regexp.ts"],"names":[],"mappings":";;;AAAA,iCAAmD;AAGnD,SAAS,WAAW,CAAC,GAAW;IAC9B,OAAO,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACvC,CAAC;AAgBD;;;GAGG;AACH;IAKE;;;OAGG;IACH,oBAAY,OAAe,EAAE,OAAgB;QAC3C,IAAI,CAAC,CAAC,IAAI,YAAY,UAAU,CAAC;YAAE,OAAO,IAAI,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAE3E,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC,CAAC;QAE1C,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE;YACvC,MAAM,IAAI,iBAAS,CACjB,2DAAyD,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAG,CACxF,CAAC;SACH;QACD,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE;YACvC,MAAM,IAAI,iBAAS,CACjB,0DAAwD,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAG,CACvF,CAAC;SACH;QAED,mBAAmB;QACnB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,E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AM,CAAC,SAAS,KAAK,YAAY,EAAE;oBACzC,OAAO,GAA4B,CAAC;iBACrC;aACF;iBAAM;gBACL,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;aAC1E;SACF;QACD,IAAI,oBAAoB,IAAI,GAAG,EAAE;YAC/B,OAAO,IAAI,UAAU,CACnB,GAAG,CAAC,kBAAkB,CAAC,OAAO,EAC9B,UAAU,CAAC,YAAY,CAAC,GAAG,CAAC,kBAAkB,CAAC,OAAO,CAAC,CACxD,CAAC;SACH;QACD,MAAM,IAAI,qBAAa,CAAC,8CAA4C,IAAI,CAAC,SAAS,CAAC,GAAG,CAAG,CAAC,CAAC;IAC7F,CAAC;IACH,iBAAC;AAAD,CAAC,AA5ED,IA4EC;AA5EY,gCAAU;AA8EvB,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/symbol.js b/node_modules/bson/lib/symbol.js new file mode 100644 index 0000000..02ca75f --- /dev/null +++ b/node_modules/bson/lib/symbol.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BSONSymbol = void 0; +/** + * A class representation of the BSON Symbol type. + * @public + */ +var BSONSymbol = /** @class */ (function () { + /** + * @param value - the string representing the symbol. + */ + function BSONSymbol(value) { + if (!(this instanceof BSONSymbol)) + return new BSONSymbol(value); + this.value = value; + } + /** Access the wrapped string value. */ + BSONSymbol.prototype.valueOf = function () { + return this.value; + }; + BSONSymbol.prototype.toString = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.inspect = function () { + return "new BSONSymbol(\"" + this.value + "\")"; + }; + BSONSymbol.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.toExtendedJSON = function () { + return { $symbol: this.value }; + }; + /** @internal */ + BSONSymbol.fromExtendedJSON = function (doc) { + return new BSONSymbol(doc.$symbol); + }; + /** @internal */ + BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + return BSONSymbol; +}()); +exports.BSONSymbol = BSONSymbol; +Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); +//# sourceMappingURL=symbol.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/symbol.js.map b/node_modules/bson/lib/symbol.js.map new file mode 100644 index 0000000..aa55410 --- /dev/null +++ b/node_modules/bson/lib/symbol.js.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol.js","sourceRoot":"","sources":["../src/symbol.ts"],"names":[],"mappings":";;;AAKA;;;GAGG;AACH;IAIE;;OAEG;IACH,oBAAY,KAAa;QACvB,IAAI,CAAC,CAAC,IAAI,YAAY,UAAU,CAAC;YAAE,OAAO,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;QAEhE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,uCAAuC;IACvC,4BAAO,GAAP;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,6BAAQ,GAAR;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,gBAAgB;IAChB,4BAAO,GAAP;QACE,OAAO,sBAAmB,IAAI,CAAC,KAAK,QAAI,CAAC;IAC3C,CAAC;IAED,2BAAM,GAAN;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,gBAAgB;IAChB,mCAAc,GAAd;QACE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;IACjC,CAAC;IAED,gBAAgB;IACT,2BAAgB,GAAvB,UAAwB,GAAuB;QAC7C,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;IAED,gBAAgB;IAChB,qBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IACH,iBAAC;AAAD,CAAC,AA7CD,IA6CC;AA7CY,gCAAU;AA+CvB,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/timestamp.js b/node_modules/bson/lib/timestamp.js new file mode 100644 index 0000000..5750e6b --- /dev/null +++ b/node_modules/bson/lib/timestamp.js @@ -0,0 +1,99 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + 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); + }; + return function (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 __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Timestamp = exports.LongWithoutOverridesClass = void 0; +var long_1 = require("./long"); +var utils_1 = require("./parser/utils"); +/** @public */ +exports.LongWithoutOverridesClass = long_1.Long; +/** @public */ +var Timestamp = /** @class */ (function (_super) { + __extends(Timestamp, _super); + function Timestamp(low, high) { + var _this = this; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + ///@ts-expect-error + if (!(_this instanceof Timestamp)) + return new Timestamp(low, high); + if (long_1.Long.isLong(low)) { + _this = _super.call(this, low.low, low.high, true) || this; + } + else if (utils_1.isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { + _this = _super.call(this, low.i, low.t, true) || this; + } + else { + _this = _super.call(this, low, high, true) || this; + } + Object.defineProperty(_this, '_bsontype', { + value: 'Timestamp', + writable: false, + configurable: false, + enumerable: false + }); + return _this; + } + Timestamp.prototype.toJSON = function () { + return { + $timestamp: this.toString() + }; + }; + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + Timestamp.fromInt = function (value) { + return new Timestamp(long_1.Long.fromInt(value, true)); + }; + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + Timestamp.fromNumber = function (value) { + return new Timestamp(long_1.Long.fromNumber(value, true)); + }; + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + Timestamp.fromString = function (str, optRadix) { + return new Timestamp(long_1.Long.fromString(str, true, optRadix)); + }; + /** @internal */ + Timestamp.prototype.toExtendedJSON = function () { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + }; + /** @internal */ + Timestamp.fromExtendedJSON = function (doc) { + return new Timestamp(doc.$timestamp); + }; + /** @internal */ + Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Timestamp.prototype.inspect = function () { + return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })"; + }; + Timestamp.MAX_VALUE = long_1.Long.MAX_UNSIGNED_VALUE; + return Timestamp; +}(exports.LongWithoutOverridesClass)); +exports.Timestamp = Timestamp; +//# sourceMappingURL=timestamp.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/timestamp.js.map b/node_modules/bson/lib/timestamp.js.map new file mode 100644 index 0000000..fb2a59f --- /dev/null +++ b/node_modules/bson/lib/timestamp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timestamp.js","sourceRoot":"","sources":["../src/timestamp.ts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,GAAjB,UAAkB,KAAa;QAC7B,OAAO,IAAI,SAAS,CAAC,WAAI,CAAC,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;IACrD,CAAC;IAED;;;;;OAKG;IACI,kBAAQ,GAAf,UAAgB,OAAe,EAAE,QAAgB;QAC/C,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC1C,CAAC;IAED;;;;;OAKG;IACI,oBAAU,GAAjB,UAAkB,GAAW,EAAE,QAAgB;QAC7C,OAAO,IAAI,SAAS,CAAC,WAAI,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC7D,CAAC;IAED,gBAAgB;IAChB,kCAAc,GAAd;QACE,OAAO,EAAE,UAAU,EAAE,EAAE,CAAC,EAAE,IAAI,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC;IACnE,CAAC;IAED,gBAAgB;IACT,0BAAgB,GAAvB,UAAwB,GAAsB;QAC5C,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACvC,CAAC;IAED,gBAAgB;IAChB,oBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,2BAAO,GAAP;QACE,OAAO,wBAAsB,IAAI,CAAC,WAAW,EAAE,aAAQ,IAAI,CAAC,UAAU,EAAE,QAAK,CAAC;IAChF,CAAC;IAzFe,mBAAS,GAAG,WAAI,CAAC,kBAAkB,CAAC;IA0FtD,gBAAC;CAAA,AA7FD,CAA+B,iCAAyB,GA6FvD;AA7FY,8BAAS"} \ No newline at end of file diff --git a/node_modules/bson/lib/utils/global.js b/node_modules/bson/lib/utils/global.js new file mode 100644 index 0000000..30218ea --- /dev/null +++ b/node_modules/bson/lib/utils/global.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getGlobal = void 0; +function checkForMath(potentialGlobal) { + // eslint-disable-next-line eqeqeq + return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; +} +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +function getGlobal() { + // eslint-disable-next-line no-undef + return (checkForMath(typeof globalThis === 'object' && globalThis) || + checkForMath(typeof window === 'object' && window) || + checkForMath(typeof self === 'object' && self) || + checkForMath(typeof global === 'object' && global) || + Function('return this')()); +} +exports.getGlobal = getGlobal; +//# sourceMappingURL=global.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/utils/global.js.map b/node_modules/bson/lib/utils/global.js.map new file mode 100644 index 0000000..ebd51ab --- /dev/null +++ b/node_modules/bson/lib/utils/global.js.map @@ -0,0 +1 @@ +{"version":3,"file":"global.js","sourceRoot":"","sources":["../../src/utils/global.ts"],"names":[],"mappings":";;;AAMA,SAAS,YAAY,CAAC,eAAoB;IACxC,kCAAkC;IAClC,OAAO,eAAe,IAAI,eAAe,CAAC,IAAI,IAAI,IAAI,IAAI,eAAe,CAAC;AAC5E,CAAC;AAED,uEAAuE;AACvE,SAAgB,SAAS;IACvB,oCAAoC;IACpC,OAAO,CACL,YAAY,CAAC,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC;QAC1D,YAAY,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC;QAClD,YAAY,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC;QAC9C,YAAY,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC;QAClD,QAAQ,CAAC,aAAa,CAAC,EAAE,CAC1B,CAAC;AACJ,CAAC;AATD,8BASC"} \ No newline at end of file diff --git a/node_modules/bson/lib/uuid.js b/node_modules/bson/lib/uuid.js new file mode 100644 index 0000000..bd0bf38 --- /dev/null +++ b/node_modules/bson/lib/uuid.js @@ -0,0 +1,179 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UUID = void 0; +var buffer_1 = require("buffer"); +var ensure_buffer_1 = require("./ensure_buffer"); +var binary_1 = require("./binary"); +var uuid_utils_1 = require("./uuid_utils"); +var utils_1 = require("./parser/utils"); +var error_1 = require("./error"); +var BYTE_LENGTH = 16; +var kId = Symbol('id'); +/** + * A class representation of the BSON UUID type. + * @public + */ +var UUID = /** @class */ (function () { + /** + * Create an UUID type + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + function UUID(input) { + if (typeof input === 'undefined') { + // The most common use case (blank id, new UUID() instance) + this.id = UUID.generate(); + } + else if (input instanceof UUID) { + this[kId] = buffer_1.Buffer.from(input.id); + this.__id = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { + this.id = ensure_buffer_1.ensureBuffer(input); + } + else if (typeof input === 'string') { + this.id = uuid_utils_1.uuidHexStringToBuffer(input); + } + else { + throw new error_1.BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); + } + } + Object.defineProperty(UUID.prototype, "id", { + /** + * The UUID bytes + * @readonly + */ + get: function () { + return this[kId]; + }, + set: function (value) { + this[kId] = value; + if (UUID.cacheHexString) { + this.__id = uuid_utils_1.bufferToUuidHexString(value); + } + }, + enumerable: false, + configurable: true + }); + /** + * Generate a 16 byte uuid v4 buffer used in UUIDs + */ + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + * */ + UUID.prototype.toHexString = function (includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + var uuidHexString = uuid_utils_1.bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + }; + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + UUID.prototype.toString = function (encoding) { + return encoding ? this.id.toString(encoding) : this.toHexString(); + }; + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + UUID.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + UUID.prototype.equals = function (otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return otherId.id.equals(this.id); + } + try { + return new UUID(otherId).id.equals(this.id); + } + catch (_a) { + return false; + } + }; + /** + * Creates a Binary instance from the current UUID. + */ + UUID.prototype.toBinary = function () { + return new binary_1.Binary(this.id, binary_1.Binary.SUBTYPE_UUID); + }; + /** + * Generates a populated buffer containing a v4 uuid + */ + UUID.generate = function () { + var bytes = utils_1.randomBytes(BYTE_LENGTH); + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return buffer_1.Buffer.from(bytes); + }; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + UUID.isValid = function (input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuid_utils_1.uuidValidateString(input); + } + if (utils_1.isUint8Array(input)) { + // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) + if (input.length !== BYTE_LENGTH) { + return false; + } + try { + // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx + // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx + return parseInt(input[6].toString(16)[0], 10) === binary_1.Binary.SUBTYPE_UUID; + } + catch (_a) { + return false; + } + } + return false; + }; + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + UUID.createFromHexString = function (hexString) { + var buffer = uuid_utils_1.uuidHexStringToBuffer(hexString); + return new UUID(buffer); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 36 character hex string representation. + * @internal + */ + UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + UUID.prototype.inspect = function () { + return "new UUID(\"" + this.toHexString() + "\")"; + }; + return UUID; +}()); +exports.UUID = UUID; +Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); +//# sourceMappingURL=uuid.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/uuid.js.map b/node_modules/bson/lib/uuid.js.map new file mode 100644 index 0000000..6eeb216 --- /dev/null +++ b/node_modules/bson/lib/uuid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uuid.js","sourceRoot":"","sources":["../src/uuid.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iDAA+C;AAC/C,mCAAkC;AAClC,2CAAgG;AAChG,wCAA2D;AAC3D,iCAAwC;AAOxC,IAAM,WAAW,GAAG,EAAE,CAAC;AAEvB,IAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;AAEzB;;;GAGG;AACH;IAWE;;;;OAIG;IACH,cAAY,KAA8B;QACxC,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;YAChC,2DAA2D;YAC3D,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;SAC3B;aAAM,IAAI,KAAK,YAAY,IAAI,EAAE;YAChC,IAAI,CAAC,GAAG,CAAC,GAAG,eAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClC,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;SACxB;aAAM,IAAI,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,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I,KAAK,CAAC,MAAM,KAAK,WAAW,EAAE;gBAChC,OAAO,KAAK,CAAC;aACd;YAED,IAAI;gBACF,yEAAyE;gBACzE,yEAAyE;gBACzE,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,eAAM,CAAC,YAAY,CAAC;aACvE;YAAC,WAAM;gBACN,OAAO,KAAK,CAAC;aACd;SACF;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;OAGG;IACI,wBAAmB,GAA1B,UAA2B,SAAiB;QAC1C,IAAM,MAAM,GAAG,kCAAqB,CAAC,SAAS,CAAC,CAAC;QAChD,OAAO,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAED;;;;;OAKG;IACH,eAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,sBAAO,GAAP;QACE,OAAO,gBAAa,IAAI,CAAC,WAAW,EAAE,QAAI,CAAC;IAC7C,CAAC;IACH,WAAC;AAAD,CAAC,AA1LD,IA0LC;AA1LY,oBAAI;AA4LjB,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/bson/lib/uuid_utils.js b/node_modules/bson/lib/uuid_utils.js new file mode 100644 index 0000000..7ccc6ac --- /dev/null +++ b/node_modules/bson/lib/uuid_utils.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bufferToUuidHexString = exports.uuidHexStringToBuffer = exports.uuidValidateString = void 0; +var buffer_1 = require("buffer"); +var error_1 = require("./error"); +// Validation regex for v4 uuid (validates with or without dashes) +var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; +var uuidValidateString = function (str) { + return typeof str === 'string' && VALIDATION_REGEX.test(str); +}; +exports.uuidValidateString = uuidValidateString; +var uuidHexStringToBuffer = function (hexString) { + if (!exports.uuidValidateString(hexString)) { + throw new error_1.BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); + } + var sanitizedHexString = hexString.replace(/-/g, ''); + return buffer_1.Buffer.from(sanitizedHexString, 'hex'); +}; +exports.uuidHexStringToBuffer = uuidHexStringToBuffer; +var bufferToUuidHexString = function (buffer, includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + return includeDashes + ? buffer.toString('hex', 0, 4) + + '-' + + buffer.toString('hex', 4, 6) + + '-' + + buffer.toString('hex', 6, 8) + + '-' + + buffer.toString('hex', 8, 10) + + '-' + + buffer.toString('hex', 10, 16) + : buffer.toString('hex'); +}; +exports.bufferToUuidHexString = bufferToUuidHexString; +//# sourceMappingURL=uuid_utils.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/uuid_utils.js.map b/node_modules/bson/lib/uuid_utils.js.map new file mode 100644 index 0000000..0d7b1f1 --- /dev/null +++ b/node_modules/bson/lib/uuid_utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uuid_utils.js","sourceRoot":"","sources":["../src/uuid_utils.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iCAAwC;AAExC,kEAAkE;AAClE,IAAM,gBAAgB,GACpB,uHAAuH,CAAC;AAEnH,IAAM,kBAAkB,GAAG,UAAC,GAAW;IAC5C,OAAA,OAAO,GAAG,KAAK,QAAQ,IAAI,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC;AAArD,CAAqD,CAAC;AAD3C,QAAA,kBAAkB,sBACyB;AAEjD,IAAM,qBAAqB,GAAG,UAAC,SAAiB;IACrD,IAAI,CAAC,0BAAkB,CAAC,SAAS,CAAC,EAAE;QAClC,MAAM,IAAI,qBAAa,CACrB,uLAAuL,CACxL,CAAC;KACH;IAED,IAAM,kBAAkB,GAAG,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACvD,OAAO,eAAM,CAAC,IAAI,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;AAChD,CAAC,CAAC;AATW,QAAA,qBAAqB,yBAShC;AAEK,IAAM,qBAAqB,GAAG,UAAC,MAAc,EAAE,aAAoB;IAApB,8BAAA,EAAA,oBAAoB;IACxE,OAAA,aAAa;QACX,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;YAC5B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;YAC5B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;YAC5B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;YAC7B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE,CAAC;QAChC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;AAV1B,CAU0B,CAAC;AAXhB,QAAA,qBAAqB,yBAWL"} \ No newline at end of file diff --git a/node_modules/bson/lib/validate_utf8.js b/node_modules/bson/lib/validate_utf8.js new file mode 100644 index 0000000..ec78016 --- /dev/null +++ b/node_modules/bson/lib/validate_utf8.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateUtf8 = void 0; +var FIRST_BIT = 0x80; +var FIRST_TWO_BITS = 0xc0; +var FIRST_THREE_BITS = 0xe0; +var FIRST_FOUR_BITS = 0xf0; +var FIRST_FIVE_BITS = 0xf8; +var TWO_BIT_CHAR = 0xc0; +var THREE_BIT_CHAR = 0xe0; +var FOUR_BIT_CHAR = 0xf0; +var CONTINUING_CHAR = 0x80; +/** + * Determines if the passed in bytes are valid utf8 + * @param bytes - An array of 8-bit bytes. Must be indexable and have length property + * @param start - The index to start validating + * @param end - The index to end validating + */ +function validateUtf8(bytes, start, end) { + var continuation = 0; + for (var i = start; i < end; i += 1) { + var byte = bytes[i]; + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } + else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } + else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } + else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } + else { + return false; + } + } + } + return !continuation; +} +exports.validateUtf8 = validateUtf8; +//# sourceMappingURL=validate_utf8.js.map \ No newline at end of file diff --git a/node_modules/bson/lib/validate_utf8.js.map b/node_modules/bson/lib/validate_utf8.js.map new file mode 100644 index 0000000..f1e975b --- /dev/null +++ b/node_modules/bson/lib/validate_utf8.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validate_utf8.js","sourceRoot":"","sources":["../src/validate_utf8.ts"],"names":[],"mappings":";;;AAAA,IAAM,SAAS,GAAG,IAAI,CAAC;AACvB,IAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,IAAM,gBAAgB,GAAG,IAAI,CAAC;AAC9B,IAAM,eAAe,GAAG,IAAI,CAAC;AAC7B,IAAM,eAAe,GAAG,IAAI,CAAC;AAE7B,IAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,IAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,IAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,IAAM,eAAe,GAAG,IAAI,CAAC;AAE7B;;;;;GAKG;AACH,SAAgB,YAAY,CAC1B,KAAkC,EAClC,KAAa,EACb,GAAW;IAEX,IAAI,YAAY,GAAG,CAAC,CAAC;IAErB,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE;QACnC,IAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QAEtB,IAAI,YAAY,EAAE;YAChB,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC,KAAK,eAAe,EAAE;gBAC/C,OAAO,KAAK,CAAC;aACd;YACD,YAAY,IAAI,CAAC,CAAC;SACnB;aAAM,IAAI,IAAI,GAAG,SAAS,EAAE;YAC3B,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC,KAAK,YAAY,EAAE;gBAC9C,YAAY,GAAG,CAAC,CAAC;aAClB;iBAAM,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC,KAAK,cAAc,EAAE;gBACtD,YAAY,GAAG,CAAC,CAAC;aAClB;iBAAM,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC,KAAK,aAAa,EAAE;gBACrD,YAAY,GAAG,CAAC,CAAC;aAClB;iBAAM;gBACL,OAAO,KAAK,CAAC;aACd;SACF;KACF;IAED,OAAO,CAAC,YAAY,CAAC;AACvB,CAAC;AA7BD,oCA6BC"} \ No newline at end of file diff --git a/node_modules/bson/package.json b/node_modules/bson/package.json new file mode 100644 index 0000000..eed8950 --- /dev/null +++ b/node_modules/bson/package.json @@ -0,0 +1,115 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "files": [ + "lib", + "src", + "dist", + "bson.d.ts", + "etc/prepare.js", + "bower.json" + ], + "types": "bson.d.ts", + "version": "4.5.3", + "author": { + "name": "The MongoDB NodeJS Team", + "email": "dbx-node@mongodb.com" + }, + "license": "Apache-2.0", + "contributors": [], + "repository": "mongodb/js-bson", + "bugs": { + "url": "https://jira.mongodb.org/projects/NODE/issues/" + }, + "devDependencies": { + "@babel/plugin-external-helpers": "^7.10.4", + "@babel/preset-env": "^7.11.0", + "@istanbuljs/nyc-config-typescript": "^1.0.1", + "@microsoft/api-extractor": "^7.11.2", + "@rollup/plugin-babel": "^5.2.0", + "@rollup/plugin-commonjs": "^15.0.0", + "@rollup/plugin-json": "^4.1.0", + "@rollup/plugin-node-resolve": "^9.0.0", + "@rollup/plugin-typescript": "^6.0.0", + "@typescript-eslint/eslint-plugin": "^3.10.1", + "@typescript-eslint/parser": "^3.10.1", + "array-includes": "^3.1.3", + "benchmark": "^2.1.4", + "chai": "^4.2.0", + "downlevel-dts": "^0.7.0", + "eslint": "^7.7.0", + "eslint-config-prettier": "^6.11.0", + "eslint-plugin-prettier": "^3.1.4", + "eslint-plugin-tsdoc": "^0.2.6", + "karma": "^6.3.4", + "karma-chai": "^0.1.0", + "karma-chrome-launcher": "^3.1.0", + "karma-mocha": "^2.0.1", + "karma-mocha-reporter": "^2.2.5", + "karma-rollup-preprocessor": "^7.0.5", + "mocha": "5.2.0", + "node-fetch": "^2.6.1", + "nyc": "^15.1.0", + "object.entries": "^1.1.4", + "prettier": "^2.1.1", + "rimraf": "^3.0.2", + "rollup": "^2.26.5", + "rollup-plugin-commonjs": "^10.1.0", + "rollup-plugin-node-globals": "^1.4.0", + "rollup-plugin-node-polyfills": "^0.2.1", + "rollup-plugin-polyfill-node": "^0.7.0", + "standard-version": "^9.3.0", + "ts-node": "^9.0.0", + "tsd": "^0.17.0", + "typedoc": "^0.21.2", + "typescript": "^4.0.2", + "typescript-cached-transpile": "0.0.6", + "uuid": "^8.3.2" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "strict": true, + "target": "esnext", + "module": "commonjs", + "moduleResolution": "node" + } + }, + "config": { + "native": false + }, + "main": "lib/bson.js", + "module": "dist/bson.esm.js", + "browser": { + "./lib/bson.js": "./dist/bson.browser.umd.js", + "./dist/bson.esm.js": "./dist/bson.browser.esm.js" + }, + "engines": { + "node": ">=6.9.0" + }, + "scripts": { + "docs": "typedoc", + "test": "npm run build && npm run test-node && npm run test-browser", + "test-node": "mocha test/node test/*_tests.js", + "test-tsd": "npm run build:dts && tsd", + "test-browser": "karma start karma.conf.js", + "build:ts": "tsc", + "build:dts": "npm run build:ts && api-extractor run --typescript-compiler-folder node_modules/typescript --local && rimraf 'lib/**/*.d.ts*' && downlevel-dts bson.d.ts bson.d.ts", + "build:bundle": "rollup -c rollup.config.js", + "build": "npm run build:dts && npm run build:bundle", + "lint": "eslint -v && eslint --ext '.js,.ts' --max-warnings=0 src test && tsc -v && tsc --noEmit && npm run test-tsd", + "format": "eslint --ext '.js,.ts' src test --fix", + "coverage": "nyc npm run test-node", + "coverage:html": "npm run coverage && open ./coverage/index.html", + "prepare": "node etc/prepare.js", + "release": "standard-version -i HISTORY.md" + }, + "dependencies": { + "buffer": "^5.6.0" + } +} diff --git a/node_modules/bson/src/binary.ts b/node_modules/bson/src/binary.ts new file mode 100644 index 0000000..2b82893 --- /dev/null +++ b/node_modules/bson/src/binary.ts @@ -0,0 +1,286 @@ +import { Buffer } from 'buffer'; +import { ensureBuffer } from './ensure_buffer'; +import { uuidHexStringToBuffer } from './uuid_utils'; +import { UUID, UUIDExtended } from './uuid'; +import type { EJSONOptions } from './extended_json'; +import { BSONError, BSONTypeError } from './error'; + +/** @public */ +export type BinarySequence = Uint8Array | Buffer | number[]; + +/** @public */ +export interface BinaryExtendedLegacy { + $type: string; + $binary: string; +} + +/** @public */ +export interface BinaryExtended { + $binary: { + subType: string; + base64: string; + }; +} + +/** + * A class representation of the BSON Binary type. + * @public + */ +export class Binary { + _bsontype!: 'Binary'; + + /** + * Binary default subtype + * @internal + */ + private static readonly BSON_BINARY_SUBTYPE_DEFAULT = 0; + + /** Initial buffer default size */ + static readonly BUFFER_SIZE = 256; + /** Default BSON type */ + static readonly SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + static readonly SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + static readonly SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + static readonly SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + static readonly SUBTYPE_UUID = 4; + /** MD5 BSON type */ + static readonly SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + static readonly SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + static readonly SUBTYPE_COLUMN = 7; + /** User BSON type */ + static readonly SUBTYPE_USER_DEFINED = 128; + + buffer!: Buffer; + sub_type!: number; + position!: number; + + /** + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + constructor(buffer?: string | BinarySequence, subType?: number) { + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + if ( + !(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer) + ) { + throw new BSONTypeError( + 'Binary can only be constructed from string, Buffer, TypedArray, or Array' + ); + } + + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + + if (buffer == null) { + // create an empty binary buffer + this.buffer = Buffer.alloc(Binary.BUFFER_SIZE); + this.position = 0; + } else { + if (typeof buffer === 'string') { + // string + this.buffer = Buffer.from(buffer, 'binary'); + } else if (Array.isArray(buffer)) { + // number[] + this.buffer = Buffer.from(buffer); + } else { + // Buffer | TypedArray | ArrayBuffer + this.buffer = ensureBuffer(buffer); + } + + this.position = this.buffer.byteLength; + } + } + + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + put(byteValue: string | number | Uint8Array | Buffer | number[]): void { + // If it's a string and a has more than one character throw an error + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONTypeError('only accepts single character String'); + } else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONTypeError('only accepts single character Uint8Array or Array'); + + // Decode the byte value once + let decodedByte: number; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } else { + decodedByte = byteValue[0]; + } + + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); + } + + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decodedByte; + } else { + const buffer = Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decodedByte; + } + } + + /** + * Writes a buffer or string to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + write(sequence: string | BinarySequence, offset: number): void { + offset = typeof offset === 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + sequence.length) { + const buffer = Buffer.alloc(this.buffer.length + sequence.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + + // Assign the new buffer + this.buffer = buffer; + } + + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ensureBuffer(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } else if (typeof sequence === 'string') { + this.buffer.write(sequence, offset, sequence.length, 'binary'); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + } + + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + read(position: number, length: number): BinarySequence { + length = length && length > 0 ? length : this.position; + + // Let's return the data based on the type we have + return this.buffer.slice(position, position + length); + } + + /** + * Returns the value of this binary as a string. + * @param asRaw - Will skip converting to a string + * @remarks + * This is handy when calling this function conditionally for some key value pairs and not others + */ + value(asRaw?: boolean): string | BinarySequence { + asRaw = !!asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + + // If it's a node.js buffer object + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return this.buffer.toString('binary', 0, this.position); + } + + /** the length of the binary sequence */ + length(): number { + return this.position; + } + + toJSON(): string { + return this.buffer.toString('base64'); + } + + toString(format?: string): string { + return this.buffer.toString(format); + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): BinaryExtendedLegacy | BinaryExtended { + options = options || {}; + const base64String = this.buffer.toString('base64'); + + const subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + } + + toUUID(): UUID { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID(this.buffer.slice(0, this.position)); + } + + throw new BSONError( + `Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.` + ); + } + + /** @internal */ + static fromExtendedJSON( + doc: BinaryExtendedLegacy | BinaryExtended | UUIDExtended, + options?: EJSONOptions + ): Binary { + options = options || {}; + let data: Buffer | undefined; + let type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = Buffer.from(doc.$binary, 'base64'); + } else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = Buffer.from(doc.$binary.base64, 'base64'); + } + } + } else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONTypeError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return new Binary(data, type); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + const asBuffer = this.value(true); + return `new Binary(Buffer.from("${asBuffer.toString('hex')}", "hex"), ${this.sub_type})`; + } +} + +Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); diff --git a/node_modules/bson/src/bson.ts b/node_modules/bson/src/bson.ts new file mode 100644 index 0000000..924235a --- /dev/null +++ b/node_modules/bson/src/bson.ts @@ -0,0 +1,335 @@ +import { Buffer } from 'buffer'; +import { Binary } from './binary'; +import { Code } from './code'; +import { DBRef } from './db_ref'; +import { Decimal128 } from './decimal128'; +import { Double } from './double'; +import { ensureBuffer } from './ensure_buffer'; +import { EJSON } from './extended_json'; +import { Int32 } from './int_32'; +import { Long } from './long'; +import { Map } from './map'; +import { MaxKey } from './max_key'; +import { MinKey } from './min_key'; +import { ObjectId } from './objectid'; +import { BSONError, BSONTypeError } from './error'; +import { calculateObjectSize as internalCalculateObjectSize } from './parser/calculate_size'; +// Parts of the parser +import { deserialize as internalDeserialize, DeserializeOptions } from './parser/deserializer'; +import { serializeInto as internalSerialize, SerializeOptions } from './parser/serializer'; +import { BSONRegExp } from './regexp'; +import { BSONSymbol } from './symbol'; +import { Timestamp } from './timestamp'; +import { UUID } from './uuid'; +export { BinaryExtended, BinaryExtendedLegacy, BinarySequence } from './binary'; +export { CodeExtended } from './code'; +export { + BSON_BINARY_SUBTYPE_BYTE_ARRAY, + BSON_BINARY_SUBTYPE_DEFAULT, + BSON_BINARY_SUBTYPE_FUNCTION, + BSON_BINARY_SUBTYPE_MD5, + BSON_BINARY_SUBTYPE_USER_DEFINED, + BSON_BINARY_SUBTYPE_UUID, + BSON_BINARY_SUBTYPE_UUID_NEW, + BSON_BINARY_SUBTYPE_ENCRYPTED, + BSON_BINARY_SUBTYPE_COLUMN, + BSON_DATA_ARRAY, + BSON_DATA_BINARY, + BSON_DATA_BOOLEAN, + BSON_DATA_CODE, + BSON_DATA_CODE_W_SCOPE, + BSON_DATA_DATE, + BSON_DATA_DBPOINTER, + BSON_DATA_DECIMAL128, + BSON_DATA_INT, + BSON_DATA_LONG, + BSON_DATA_MAX_KEY, + BSON_DATA_MIN_KEY, + BSON_DATA_NULL, + BSON_DATA_NUMBER, + BSON_DATA_OBJECT, + BSON_DATA_OID, + BSON_DATA_REGEXP, + BSON_DATA_STRING, + BSON_DATA_SYMBOL, + BSON_DATA_TIMESTAMP, + BSON_DATA_UNDEFINED, + BSON_INT32_MAX, + BSON_INT32_MIN, + BSON_INT64_MAX, + BSON_INT64_MIN +} from './constants'; +export { DBRefLike } from './db_ref'; +export { Decimal128Extended } from './decimal128'; +export { DoubleExtended } from './double'; +export { EJSON, EJSONOptions } from './extended_json'; +export { Int32Extended } from './int_32'; +export { LongExtended } from './long'; +export { MaxKeyExtended } from './max_key'; +export { MinKeyExtended } from './min_key'; +export { ObjectIdExtended, ObjectIdLike } from './objectid'; +export { BSONRegExpExtended, BSONRegExpExtendedLegacy } from './regexp'; +export { BSONSymbolExtended } from './symbol'; +export { + LongWithoutOverrides, + LongWithoutOverridesClass, + TimestampExtended, + TimestampOverrides +} from './timestamp'; +export { UUIDExtended } from './uuid'; +export { SerializeOptions, DeserializeOptions }; +export { + Code, + Map, + BSONSymbol, + DBRef, + Binary, + ObjectId, + UUID, + Long, + Timestamp, + Double, + Int32, + MinKey, + MaxKey, + BSONRegExp, + Decimal128, + // In 4.0.0 and 4.0.1, this property name was changed to ObjectId to match the class name. + // This caused interoperability problems with previous versions of the library, so in + // later builds we changed it back to ObjectID (capital D) to match legacy implementations. + ObjectId as ObjectID +}; +export { BSONError, BSONTypeError } from './error'; + +/** @public */ +export interface Document { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [key: string]: any; +} + +/** @internal */ +// Default Max Size +const MAXSIZE = 1024 * 1024 * 17; + +// Current Internal Temporary Serialization Buffer +let buffer = Buffer.alloc(MAXSIZE); + +/** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer + * @public + */ +export function setInternalBufferSize(size: number): void { + // Resize the internal serialization buffer if needed + if (buffer.length < size) { + buffer = Buffer.alloc(size); + } +} + +/** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ +export function serialize(object: Document, options: SerializeOptions = {}): Buffer { + // Unpack the options + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const minInternalBufferSize = + typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = Buffer.alloc(minInternalBufferSize); + } + + // Attempt to serialize + const serializationIndex = internalSerialize( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + [] + ); + + // Create the final buffer + const finishedBuffer = Buffer.alloc(serializationIndex); + + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + + // Return the buffer + return finishedBuffer; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ +export function serializeWithBufferAndIndex( + object: Document, + finalBuffer: Buffer, + options: SerializeOptions = {} +): number { + // Unpack the options + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + const serializationIndex = internalSerialize( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined + ); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + + // Return the index + return startIndex + serializationIndex - 1; +} + +/** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ +export function deserialize( + buffer: Buffer | ArrayBufferView | ArrayBuffer, + options: DeserializeOptions = {} +): Document { + return internalDeserialize(buffer instanceof Buffer ? buffer : ensureBuffer(buffer), options); +} + +/** @public */ +export type CalculateObjectSizeOptions = Pick< + SerializeOptions, + 'serializeFunctions' | 'ignoreUndefined' +>; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ +export function calculateObjectSize( + object: Document, + options: CalculateObjectSizeOptions = {} +): number { + options = options || {}; + + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined); +} + +/** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ +export function deserializeStream( + data: Buffer | ArrayBufferView | ArrayBuffer, + startIndex: number, + numberOfDocuments: number, + documents: Document[], + docStartIndex: number, + options: DeserializeOptions +): number { + const internalOptions = Object.assign( + { allowObjectSmallerThanBufferSize: true, index: 0 }, + options + ); + const bufferData = ensureBuffer(data); + + let index = startIndex; + // Loop over all documents + for (let i = 0; i < numberOfDocuments; i++) { + // Find size of the document + const size = + bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + // Update options with index + internalOptions.index = index; + // Parse the document at this point + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * BSON default export + * @deprecated Please use named exports + * @privateRemarks + * We want to someday deprecate the default export, + * so none of the new TS types are being exported on the default + * @public + */ +const BSON = { + Binary, + Code, + DBRef, + Decimal128, + Double, + Int32, + Long, + UUID, + Map, + MaxKey, + MinKey, + ObjectId, + ObjectID: ObjectId, + BSONRegExp, + BSONSymbol, + Timestamp, + EJSON, + setInternalBufferSize, + serialize, + serializeWithBufferAndIndex, + deserialize, + calculateObjectSize, + deserializeStream, + BSONError, + BSONTypeError +}; +export default BSON; diff --git a/node_modules/bson/src/code.ts b/node_modules/bson/src/code.ts new file mode 100644 index 0000000..1307d88 --- /dev/null +++ b/node_modules/bson/src/code.ts @@ -0,0 +1,60 @@ +import type { Document } from './bson'; + +/** @public */ +export interface CodeExtended { + $code: string | Function; + $scope?: Document; +} + +/** + * A class representation of the BSON Code type. + * @public + */ +export class Code { + _bsontype!: 'Code'; + + code!: string | Function; + scope?: Document; + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + constructor(code: string | Function, scope?: Document) { + if (!(this instanceof Code)) return new Code(code, scope); + + this.code = code; + this.scope = scope; + } + + toJSON(): { code: string | Function; scope?: Document } { + return { code: this.code, scope: this.scope }; + } + + /** @internal */ + toExtendedJSON(): CodeExtended { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + + return { $code: this.code }; + } + + /** @internal */ + static fromExtendedJSON(doc: CodeExtended): Code { + return new Code(doc.$code, doc.$scope); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + const codeJson = this.toJSON(); + return `new Code("${codeJson.code}"${ + codeJson.scope ? `, ${JSON.stringify(codeJson.scope)}` : '' + })`; + } +} + +Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); diff --git a/node_modules/bson/src/constants.ts b/node_modules/bson/src/constants.ts new file mode 100644 index 0000000..6af63e6 --- /dev/null +++ b/node_modules/bson/src/constants.ts @@ -0,0 +1,110 @@ +/** @internal */ +export const BSON_INT32_MAX = 0x7fffffff; +/** @internal */ +export const BSON_INT32_MIN = -0x80000000; +/** @internal */ +export const BSON_INT64_MAX = Math.pow(2, 63) - 1; +/** @internal */ +export const BSON_INT64_MIN = -Math.pow(2, 63); + +/** + * Any integer up to 2^53 can be precisely represented by a double. + * @internal + */ +export const JS_INT_MAX = Math.pow(2, 53); + +/** + * Any integer down to -2^53 can be precisely represented by a double. + * @internal + */ +export const JS_INT_MIN = -Math.pow(2, 53); + +/** Number BSON Type @internal */ +export const BSON_DATA_NUMBER = 1; + +/** String BSON Type @internal */ +export const BSON_DATA_STRING = 2; + +/** Object BSON Type @internal */ +export const BSON_DATA_OBJECT = 3; + +/** Array BSON Type @internal */ +export const BSON_DATA_ARRAY = 4; + +/** Binary BSON Type @internal */ +export const BSON_DATA_BINARY = 5; + +/** Binary BSON Type @internal */ +export const BSON_DATA_UNDEFINED = 6; + +/** ObjectId BSON Type @internal */ +export const BSON_DATA_OID = 7; + +/** Boolean BSON Type @internal */ +export const BSON_DATA_BOOLEAN = 8; + +/** Date BSON Type @internal */ +export const BSON_DATA_DATE = 9; + +/** null BSON Type @internal */ +export const BSON_DATA_NULL = 10; + +/** RegExp BSON Type @internal */ +export const BSON_DATA_REGEXP = 11; + +/** Code BSON Type @internal */ +export const BSON_DATA_DBPOINTER = 12; + +/** Code BSON Type @internal */ +export const BSON_DATA_CODE = 13; + +/** Symbol BSON Type @internal */ +export const BSON_DATA_SYMBOL = 14; + +/** Code with Scope BSON Type @internal */ +export const BSON_DATA_CODE_W_SCOPE = 15; + +/** 32 bit Integer BSON Type @internal */ +export const BSON_DATA_INT = 16; + +/** Timestamp BSON Type @internal */ +export const BSON_DATA_TIMESTAMP = 17; + +/** Long BSON Type @internal */ +export const BSON_DATA_LONG = 18; + +/** Decimal128 BSON Type @internal */ +export const BSON_DATA_DECIMAL128 = 19; + +/** MinKey BSON Type @internal */ +export const BSON_DATA_MIN_KEY = 0xff; + +/** MaxKey BSON Type @internal */ +export const BSON_DATA_MAX_KEY = 0x7f; + +/** Binary Default Type @internal */ +export const BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** Binary Function Type @internal */ +export const BSON_BINARY_SUBTYPE_FUNCTION = 1; + +/** Binary Byte Array Type @internal */ +export const BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + +/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ +export const BSON_BINARY_SUBTYPE_UUID = 3; + +/** Binary UUID Type @internal */ +export const BSON_BINARY_SUBTYPE_UUID_NEW = 4; + +/** Binary MD5 Type @internal */ +export const BSON_BINARY_SUBTYPE_MD5 = 5; + +/** Encrypted BSON type @internal */ +export const BSON_BINARY_SUBTYPE_ENCRYPTED = 6; + +/** Column BSON type @internal */ +export const BSON_BINARY_SUBTYPE_COLUMN = 7; + +/** Binary User Defined Type @internal */ +export const BSON_BINARY_SUBTYPE_USER_DEFINED = 128; diff --git a/node_modules/bson/src/db_ref.ts b/node_modules/bson/src/db_ref.ts new file mode 100644 index 0000000..4097eec --- /dev/null +++ b/node_modules/bson/src/db_ref.ts @@ -0,0 +1,123 @@ +import type { Document } from './bson'; +import type { EJSONOptions } from './extended_json'; +import type { ObjectId } from './objectid'; +import { isObjectLike } from './parser/utils'; + +/** @public */ +export interface DBRefLike { + $ref: string; + $id: ObjectId; + $db?: string; +} + +/** @internal */ +export function isDBRefLike(value: unknown): value is DBRefLike { + return ( + isObjectLike(value) && + value.$id != null && + typeof value.$ref === 'string' && + (value.$db == null || typeof value.$db === 'string') + ); +} + +/** + * A class representation of the BSON DBRef type. + * @public + */ +export class DBRef { + _bsontype!: 'DBRef'; + + collection!: string; + oid!: ObjectId; + db?: string; + fields!: Document; + + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + constructor(collection: string, oid: ObjectId, db?: string, fields?: Document) { + if (!(this instanceof DBRef)) return new DBRef(collection, oid, db, fields); + + // check if namespace has been provided + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + collection = parts.shift()!; + } + + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + + // Property provided for compatibility with the 1.x parser + // the 1.x parser used a "namespace" property, while 4.x uses "collection" + + /** @internal */ + get namespace(): string { + return this.collection; + } + + set namespace(value: string) { + this.collection = value; + } + + toJSON(): DBRefLike & Document { + const o = Object.assign( + { + $ref: this.collection, + $id: this.oid + }, + this.fields + ); + + if (this.db != null) o.$db = this.db; + return o; + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): DBRefLike { + options = options || {}; + let o: DBRefLike = { + $ref: this.collection, + $id: this.oid + }; + + if (options.legacy) { + return o; + } + + if (this.db) o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + } + + /** @internal */ + static fromExtendedJSON(doc: DBRefLike): DBRef { + const copy = Object.assign({}, doc) as Partial; + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + // NOTE: if OID is an ObjectId class it will just print the oid string. + const oid = + this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); + return `new DBRef("${this.namespace}", new ObjectId("${oid}")${ + this.db ? `, "${this.db}"` : '' + })`; + } +} + +Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); diff --git a/node_modules/bson/src/decimal128.ts b/node_modules/bson/src/decimal128.ts new file mode 100644 index 0000000..0427dad --- /dev/null +++ b/node_modules/bson/src/decimal128.ts @@ -0,0 +1,766 @@ +import { Buffer } from 'buffer'; +import { BSONTypeError } from './error'; +import { Long } from './long'; + +const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + +const EXPONENT_MAX = 6111; +const EXPONENT_MIN = -6176; +const EXPONENT_BIAS = 6176; +const MAX_DIGITS = 34; + +// Nan value bits as 32 bit values (due to lack of longs) +const NAN_BUFFER = [ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +const INF_NEGATIVE_BUFFER = [ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +const INF_POSITIVE_BUFFER = [ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); + +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; + +// Extract least significant 5 bits +const COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +const EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +const COMBINATION_INFINITY = 30; +// Value of combination field for NaN +const COMBINATION_NAN = 31; + +// Detect if the value is a digit +function isDigit(value: string): boolean { + return !isNaN(parseInt(value, 10)); +} + +// Divide two uint128 values +function divideu128(value: { parts: [number, number, number, number] }) { + const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + let _rem = Long.fromNumber(0); + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (let i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; +} + +// Multiply two Long values and return the 128 bit value +function multiply64x2(left: Long, right: Long): { high: Long; low: Long } { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + const leftHigh = left.shiftRightUnsigned(32); + const leftLow = new Long(left.getLowBits(), 0); + const rightHigh = right.shiftRightUnsigned(32); + const rightLow = new Long(right.getLowBits(), 0); + + let productHigh = leftHigh.multiply(rightHigh); + let productMid = leftHigh.multiply(rightLow); + const productMid2 = leftLow.multiply(rightHigh); + let productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; +} + +function lessThan(left: Long, right: Long): boolean { + // Make values unsigned + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + const ulleft = left.low >>> 0; + const ulright = right.low >>> 0; + if (ulleft < ulright) return true; + } + + return false; +} + +function invalidErr(string: string, message: string) { + throw new BSONTypeError(`"${string}" is not a valid Decimal128 string - ${message}`); +} + +/** @public */ +export interface Decimal128Extended { + $numberDecimal: string; +} + +/** + * A class representation of the BSON Decimal128 type. + * @public + */ +export class Decimal128 { + _bsontype!: 'Decimal128'; + + readonly bytes!: Buffer; + + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + constructor(bytes: Buffer | string) { + if (!(this instanceof Decimal128)) return new Decimal128(bytes); + + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } else { + this.bytes = bytes; + } + } + + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + static fromString(representation: string): Decimal128 { + // Parse state tracking + let isNegative = false; + let sawRadix = false; + let foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + let significantDigits = 0; + // Total number of significand digits read + let nDigitsRead = 0; + // Total number of digits (no leading zeros) + let nDigits = 0; + // The number of the digits after radix + let radixPosition = 0; + // The index of the first non-zero in *str* + let firstNonZero = 0; + + // Digits Array + const digits = [0]; + // The number of digits in digits + let nDigitsStored = 0; + // Insertion pointer for digits + let digitsInsert = 0; + // The index of the first non-zero digit + let firstDigit = 0; + // The index of the last digit + let lastDigit = 0; + + // Exponent + let exponent = 0; + // loop index over array + let i = 0; + // The high 17 digits of the significand + let significandHigh = new Long(0, 0); + // The low 17 digits of the significand + let significandLow = new Long(0, 0); + // The biased exponent + let biasedExponent = 0; + + // Read index + let index = 0; + + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (representation.length >= 7000) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + + // Results + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + + if (stringMatch) { + // full_match = stringMatch[0] + // sign = stringMatch[1] + + const unsignedNumber = stringMatch[2]; + // stringMatch[3] is undefined if a whole number (ex "1", 12") + // but defined if a number w/ decimal in it (ex "1.0, 12.2") + + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + + // they provided e, but didn't give an exponent number. for ex "1e" + if (e && expNumber === undefined) invalidErr(representation, 'missing exponent power'); + + // they provided e, but didn't give a number before it. for ex "e1" + if (e && unsignedNumber === undefined) invalidErr(representation, 'missing exponent base'); + + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + + // Get the negative or positive sign + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (representation[index] === 'N') { + return new Decimal128(Buffer.from(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) invalidErr(representation, 'contains multiple periods'); + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) nDigits = nDigits + 1; + if (sawRadix) radixPosition = radixPosition + 1; + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + + // Read exponent if exists + if (representation[index] === 'e' || representation[index] === 'E') { + // Read exponent digits + const match = representation.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) return new Decimal128(Buffer.from(NAN_BUFFER)); + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (representation[index]) return new Decimal128(Buffer.from(NAN_BUFFER)); + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (digits[firstNonZero + significantDigits - 1] === 0) { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit. can only do this if < significant digits than # stored. + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + // if negative, we need to increment again to account for - sign at start. + if (isNegative) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + let roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + let dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128( + Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) + ); + } + } + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + let dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + let dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if ( + significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1)) + ) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or( + Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) + ); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + const buffer = Buffer.alloc(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); + } + + /** Create a string representation of the raw Decimal128 value */ + toString(): string { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // decoded biased exponent (14 bits) + let biased_exponent; + // the number of significand digits + let significand_digits = 0; + // the base-10 digits in the significand + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + let index = 0; + + // true if the number is zero + let is_zero = false; + + // the most significant significand bits (50-46) + let significand_msb; + // temporary storage for significand decoding + let significand128: { parts: [number, number, number, number] } = { parts: [0, 0, 0, 0] }; + // indexing variables + let j, k; + + // Output string + const string: string[] = []; + + // Unpack index + index = 0; + + // Buffer reference + const buffer = this.bytes; + + // Unpack the low 64bits into a long + // bits 96 - 127 + const low = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 64 - 95 + const midl = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack the high 64bits into a long + // bits 32 - 63 + const midh = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 0 - 31 + const high = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack index + index = 0; + + // Create the state of the decimal + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + // bits 1 - 5 + const combination = (high >> 26) & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + + // unbiased exponent + const exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if ( + significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0 + ) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + let least_digits = 0; + // Perform the divide + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + // the exponent if scientific notation is used + const scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + + // if there are too many significant digits, we should just be treating numbers + // as + or - 0 and using the non-scientific exponent (this is for the "invalid + // representation should be treated as 0/-0" spec cases in decimal128-1.json) + if (significand_digits > 34) { + string.push(`${0}`); + if (exponent > 0) string.push('E+' + exponent); + else if (exponent < 0) string.push('E' + exponent); + return string.join(''); + } + + string.push(`${significand[index++]}`); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(`${scientific_exponent}`); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } else { + let radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(`${significand[index++]}`); + } + } + } + + return string.join(''); + } + + toJSON(): Decimal128Extended { + return { $numberDecimal: this.toString() }; + } + + /** @internal */ + toExtendedJSON(): Decimal128Extended { + return { $numberDecimal: this.toString() }; + } + + /** @internal */ + static fromExtendedJSON(doc: Decimal128Extended): Decimal128 { + return Decimal128.fromString(doc.$numberDecimal); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Decimal128("${this.toString()}")`; + } +} + +Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); diff --git a/node_modules/bson/src/double.ts b/node_modules/bson/src/double.ts new file mode 100644 index 0000000..d792064 --- /dev/null +++ b/node_modules/bson/src/double.ts @@ -0,0 +1,90 @@ +import type { EJSONOptions } from './extended_json'; + +/** @public */ +export interface DoubleExtended { + $numberDouble: string; +} + +/** + * A class representation of the BSON Double type. + * @public + */ +export class Double { + _bsontype!: 'Double'; + + value!: number; + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + constructor(value: number) { + if (!(this instanceof Double)) return new Double(value); + + if ((value as unknown) instanceof Number) { + value = value.valueOf(); + } + + this.value = +value; + } + + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + valueOf(): number { + return this.value; + } + + toJSON(): number { + return this.value; + } + + toString(radix?: number): string { + return this.value.toString(radix); + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): number | DoubleExtended { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + + // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user + // explicitly provided `-0` then we need to ensure the sign makes it into the output + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: `-${this.value.toFixed(1)}` }; + } + + let $numberDouble: string; + if (Number.isInteger(this.value)) { + $numberDouble = this.value.toFixed(1); + if ($numberDouble.length >= 13) { + $numberDouble = this.value.toExponential(13).toUpperCase(); + } + } else { + $numberDouble = this.value.toString(); + } + + return { $numberDouble }; + } + + /** @internal */ + static fromExtendedJSON(doc: DoubleExtended, options?: EJSONOptions): number | Double { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + const eJSON = this.toExtendedJSON() as DoubleExtended; + return `new Double(${eJSON.$numberDouble})`; + } +} + +Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); diff --git a/node_modules/bson/src/ensure_buffer.ts b/node_modules/bson/src/ensure_buffer.ts new file mode 100644 index 0000000..d2b9783 --- /dev/null +++ b/node_modules/bson/src/ensure_buffer.ts @@ -0,0 +1,27 @@ +import { Buffer } from 'buffer'; +import { BSONTypeError } from './error'; +import { isAnyArrayBuffer } from './parser/utils'; + +/** + * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. + * + * @param potentialBuffer - The potential buffer + * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that + * wraps a passed in Uint8Array + * @throws TypeError If anything other than a Buffer or Uint8Array is passed in + */ +export function ensureBuffer(potentialBuffer: Buffer | ArrayBufferView | ArrayBuffer): Buffer { + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from( + potentialBuffer.buffer, + potentialBuffer.byteOffset, + potentialBuffer.byteLength + ); + } + + if (isAnyArrayBuffer(potentialBuffer)) { + return Buffer.from(potentialBuffer); + } + + throw new BSONTypeError('Must use either Buffer or TypedArray'); +} diff --git a/node_modules/bson/src/error.ts b/node_modules/bson/src/error.ts new file mode 100644 index 0000000..b9071d5 --- /dev/null +++ b/node_modules/bson/src/error.ts @@ -0,0 +1,13 @@ +/** @public */ +export class BSONError extends Error { + get name(): string { + return 'BSONError'; + } +} + +/** @public */ +export class BSONTypeError extends TypeError { + get name(): string { + return 'BSONTypeError'; + } +} diff --git a/node_modules/bson/src/extended_json.ts b/node_modules/bson/src/extended_json.ts new file mode 100644 index 0000000..e904643 --- /dev/null +++ b/node_modules/bson/src/extended_json.ts @@ -0,0 +1,451 @@ +import { Binary } from './binary'; +import type { Document } from './bson'; +import { Code } from './code'; +import { DBRef, isDBRefLike } from './db_ref'; +import { Decimal128 } from './decimal128'; +import { Double } from './double'; +import { BSONError, BSONTypeError } from './error'; +import { Int32 } from './int_32'; +import { Long } from './long'; +import { MaxKey } from './max_key'; +import { MinKey } from './min_key'; +import { ObjectId } from './objectid'; +import { isDate, isObjectLike, isRegExp } from './parser/utils'; +import { BSONRegExp } from './regexp'; +import { BSONSymbol } from './symbol'; +import { Timestamp } from './timestamp'; + +/** @public */ +export type EJSONOptions = EJSON.Options; + +/** @internal */ +type BSONType = + | Binary + | Code + | DBRef + | Decimal128 + | Double + | Int32 + | Long + | MaxKey + | MinKey + | ObjectId + | BSONRegExp + | BSONSymbol + | Timestamp; + +export function isBSONType(value: unknown): value is BSONType { + return ( + isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string' + ); +} + +// INT32 boundaries +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +// INT64 boundaries +const BSON_INT64_MAX = 0x7fffffffffffffff; +const BSON_INT64_MIN = -0x8000000000000000; + +// all the types where we don't need to do any special processing and can just pass the EJSON +//straight to type.fromExtendedJSON +const keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp +} as const; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deserializeValue(value: any, options: EJSON.Options = {}) { + if (typeof value === 'number') { + if (options.relaxed || options.legacy) { + return value; + } + + // if it's an integer, should interpret as smallest BSON integer + // that can represent it exactly. (if out of range, interpret as double.) + if (Math.floor(value) === value) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) return new Int32(value); + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) return Long.fromNumber(value); + } + + // If the number is a non-integer or out of integer range, should interpret as BSON Double. + return new Double(value); + } + + // from here on out we're looking for bson types, so bail if its not an object + if (value == null || typeof value !== 'object') return value; + + // upgrade deprecated undefined to null + if (value.$undefined) return null; + + const keys = Object.keys(value).filter( + k => k.startsWith('$') && value[k] != null + ) as (keyof typeof keysToCodecs)[]; + for (let i = 0; i < keys.length; i++) { + const c = keysToCodecs[keys[i]]; + if (c) return c.fromExtendedJSON(value, options); + } + + if (value.$date != null) { + const d = value.$date; + const date = new Date(); + + if (options.legacy) { + if (typeof d === 'number') date.setTime(d); + else if (typeof d === 'string') date.setTime(Date.parse(d)); + } else { + if (typeof d === 'string') date.setTime(Date.parse(d)); + else if (Long.isLong(d)) date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) date.setTime(d); + } + return date; + } + + if (value.$code != null) { + const copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + + return Code.fromExtendedJSON(value); + } + + if (isDBRefLike(value) || value.$dbPointer) { + const v = value.$ref ? value : value.$dbPointer; + + // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) + // because of the order JSON.parse goes through the document + if (v instanceof DBRef) return v; + + const dollarKeys = Object.keys(v).filter(k => k.startsWith('$')); + let valid = true; + dollarKeys.forEach(k => { + if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false; + }); + + // only make DBRef if $ keys are all valid + if (valid) return DBRef.fromExtendedJSON(v); + } + + return value; +} + +type EJSONSerializeOptions = EJSON.Options & { + seenObjects: { obj: unknown; propertyName: string }[]; +}; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeArray(array: any[], options: EJSONSerializeOptions): any[] { + return array.map((v: unknown, index: number) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } finally { + options.seenObjects.pop(); + } + }); +} + +function getISOString(date: Date) { + const isoStr = date.toISOString(); + // we should only show milliseconds in timestamp if they're non-zero + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeValue(value: any, options: EJSONSerializeOptions): any { + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + const index = options.seenObjects.findIndex(entry => entry.obj === value); + if (index !== -1) { + const props = options.seenObjects.map(entry => entry.propertyName); + const leadingPart = props + .slice(0, index) + .map(prop => `${prop} -> `) + .join(''); + const alreadySeen = props[index]; + const circularPart = + ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(prop => `${prop} -> `) + .join(''); + const current = props[props.length - 1]; + const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + const dashes = '-'.repeat( + circularPart.length + (alreadySeen.length + current.length) / 2 - 1 + ); + + throw new BSONTypeError( + 'Converting circular structure to EJSON:\n' + + ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` + + ` ${leadingSpace}\\${dashes}/` + ); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + + if (Array.isArray(value)) return serializeArray(value, options); + + if (value === undefined) return null; + + if (value instanceof Date || isDate(value)) { + const dateNum = value.getTime(), + // is it in year range 1970-9999? + inRange = dateNum > -1 && dateNum < 253402318800000; + + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + // it's an integer + if (Math.floor(value) === value) { + const int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX, + int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX; + + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (int32Range) return { $numberInt: value.toString() }; + if (int64Range) return { $numberLong: value.toString() }; + } + return { $numberDouble: value.toString() }; + } + + if (value instanceof RegExp || isRegExp(value)) { + let flags = value.flags; + if (flags === undefined) { + const match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + + const rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + + if (value != null && typeof value === 'object') return serializeDocument(value, options); + return value; +} + +const BSON_TYPE_MAPPINGS = { + Binary: (o: Binary) => new Binary(o.value(), o.sub_type), + Code: (o: Code) => new Code(o.code, o.scope), + DBRef: (o: DBRef) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), // "namespace" for 1.x library backwards compat + Decimal128: (o: Decimal128) => new Decimal128(o.bytes), + Double: (o: Double) => new Double(o.value), + Int32: (o: Int32) => new Int32(o.value), + Long: ( + o: Long & { + low_: number; + high_: number; + unsigned_: boolean | undefined; + } + ) => + Long.fromBits( + // underscore variants for 1.x backwards compatibility + o.low != null ? o.low : o.low_, + o.low != null ? o.high : o.high_, + o.low != null ? o.unsigned : o.unsigned_ + ), + MaxKey: () => new MaxKey(), + MinKey: () => new MinKey(), + ObjectID: (o: ObjectId) => new ObjectId(o), + ObjectId: (o: ObjectId) => new ObjectId(o), // support 4.0.0/4.0.1 before _bsontype was reverted back to ObjectID + BSONRegExp: (o: BSONRegExp) => new BSONRegExp(o.pattern, o.options), + Symbol: (o: BSONSymbol) => new BSONSymbol(o.value), + Timestamp: (o: Timestamp) => Timestamp.fromBits(o.low, o.high) +} as const; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeDocument(doc: any, options: EJSONSerializeOptions) { + if (doc == null || typeof doc !== 'object') throw new BSONError('not an object instance'); + + const bsontype: BSONType['_bsontype'] = doc._bsontype; + if (typeof bsontype === 'undefined') { + // It's a regular object. Recursively serialize its property values. + const _doc: Document = {}; + for (const name in doc) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + _doc[name] = serializeValue(doc[name], options); + } finally { + options.seenObjects.pop(); + } + } + return _doc; + } else if (isBSONType(doc)) { + // the "document" is really just a BSON type object + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let outDoc: any = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + // There's no EJSON serialization function on the object. It's probably an + // object created by a previous version of this library (or another library) + // that's duck-typing objects to look like they were generated by this library). + // Copy the object into this library's version of that type. + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + + // Two BSON types may have nested objects that may need to be serialized too + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new DBRef( + serializeValue(outDoc.collection, options), + serializeValue(outDoc.oid, options), + serializeValue(outDoc.db, options), + serializeValue(outDoc.fields, options) + ); + } + + return outDoc.toExtendedJSON(options); + } else { + throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} + +/** + * EJSON parse / stringify API + * @public + */ +// the namespace here is used to emulate `export * as EJSON from '...'` +// which as of now (sept 2020) api-extractor does not support +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace EJSON { + export interface Options { + /** Output using the Extended JSON v1 spec */ + legacy?: boolean; + /** Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types */ + relaxed?: boolean; + /** + * Disable Extended JSON's `relaxed` mode, which attempts to return BSON types where possible, rather than native JS types + * @deprecated Please use the relaxed property instead + */ + strict?: boolean; + } + + /** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ + export function parse(text: string, options?: EJSON.Options): SerializableTypes { + const finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); + + // relaxed implies not strict + if (typeof finalOptions.relaxed === 'boolean') finalOptions.strict = !finalOptions.relaxed; + if (typeof finalOptions.strict === 'boolean') finalOptions.relaxed = !finalOptions.strict; + + return JSON.parse(text, (key, value) => { + if (key.indexOf('\x00') !== -1) { + throw new BSONError( + `BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}` + ); + } + return deserializeValue(value, finalOptions); + }); + } + + export type JSONPrimitive = string | number | boolean | null; + export type SerializableTypes = Document | Array | JSONPrimitive; + + /** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ + export function stringify( + value: SerializableTypes, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSON.Options, + space?: string | number, + options?: EJSON.Options + ): string { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer as Parameters[1], space); + } + + /** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ + export function serialize(value: SerializableTypes, options?: EJSON.Options): Document { + options = options || {}; + return JSON.parse(stringify(value, options)); + } + + /** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ + export function deserialize(ejson: Document, options?: EJSON.Options): SerializableTypes { + options = options || {}; + return parse(JSON.stringify(ejson), options); + } +} diff --git a/node_modules/bson/src/float_parser.ts b/node_modules/bson/src/float_parser.ts new file mode 100644 index 0000000..c881f4c --- /dev/null +++ b/node_modules/bson/src/float_parser.ts @@ -0,0 +1,152 @@ +// Copyright (c) 2008, Fair Oaks Labs, 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 Fair Oaks Labs, 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. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +type NumericalSequence = { [index: number]: number }; + +export function readIEEE754( + buffer: NumericalSequence, + offset: number, + endian: 'big' | 'little', + mLen: number, + nBytes: number +): number { + let e: number; + let m: number; + const bBE = endian === 'big'; + const eLen = nBytes * 8 - mLen - 1; + const eMax = (1 << eLen) - 1; + const eBias = eMax >> 1; + let nBits = -7; + let i = bBE ? 0 : nBytes - 1; + const d = bBE ? 1 : -1; + let s = buffer[offset + i]; + + i += d; + + e = s & ((1 << -nBits) - 1); + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << -nBits) - 1); + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +} + +export function writeIEEE754( + buffer: NumericalSequence, + value: number, + offset: number, + endian: 'big' | 'little', + mLen: number, + nBytes: number +): void { + let e: number; + let m: number; + let c: number; + const bBE = endian === 'big'; + let eLen = nBytes * 8 - mLen - 1; + const eMax = (1 << eLen) - 1; + const eBias = eMax >> 1; + const rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + let i = bBE ? nBytes - 1 : 0; + const d = bBE ? -1 : 1; + const s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + if (isNaN(value)) m = 0; + + while (mLen >= 8) { + buffer[offset + i] = m & 0xff; + i += d; + m /= 256; + mLen -= 8; + } + + e = (e << mLen) | m; + + if (isNaN(value)) e += 8; + + eLen += mLen; + + while (eLen > 0) { + buffer[offset + i] = e & 0xff; + i += d; + e /= 256; + eLen -= 8; + } + + buffer[offset + i - d] |= s * 128; +} diff --git a/node_modules/bson/src/int_32.ts b/node_modules/bson/src/int_32.ts new file mode 100644 index 0000000..4e58a01 --- /dev/null +++ b/node_modules/bson/src/int_32.ts @@ -0,0 +1,69 @@ +import type { EJSONOptions } from './extended_json'; + +/** @public */ +export interface Int32Extended { + $numberInt: string; +} + +/** + * A class representation of a BSON Int32 type. + * @public + */ +export class Int32 { + _bsontype!: 'Int32'; + + value!: number; + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + constructor(value: number | string) { + if (!(this instanceof Int32)) return new Int32(value); + + if ((value as unknown) instanceof Number) { + value = value.valueOf(); + } + + this.value = +value; + } + + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + valueOf(): number { + return this.value; + } + + toString(radix?: number): string { + return this.value.toString(radix); + } + + toJSON(): number { + return this.value; + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): number | Int32Extended { + if (options && (options.relaxed || options.legacy)) return this.value; + return { $numberInt: this.value.toString() }; + } + + /** @internal */ + static fromExtendedJSON(doc: Int32Extended, options?: EJSONOptions): number | Int32 { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Int32(${this.valueOf()})`; + } +} + +Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); diff --git a/node_modules/bson/src/long.ts b/node_modules/bson/src/long.ts new file mode 100644 index 0000000..6f79fae --- /dev/null +++ b/node_modules/bson/src/long.ts @@ -0,0 +1,1014 @@ +import type { EJSONOptions } from './extended_json'; +import { isObjectLike } from './parser/utils'; +import type { Timestamp } from './timestamp'; + +interface LongWASMHelpers { + /** Gets the high bits of the last operation performed */ + get_high(): number; + div_u(lowBits: number, highBits: number, lowBitsDivisor: number, highBitsDivisor: number): number; + div_s(lowBits: number, highBits: number, lowBitsDivisor: number, highBitsDivisor: number): number; + rem_u(lowBits: number, highBits: number, lowBitsDivisor: number, highBitsDivisor: number): number; + rem_s(lowBits: number, highBits: number, lowBitsDivisor: number, highBitsDivisor: number): number; + mul( + lowBits: number, + highBits: number, + lowBitsMultiplier: number, + highBitsMultiplier: number + ): number; +} + +/** + * wasm optimizations, to do native i64 multiplication and divide + */ +let wasm: LongWASMHelpers | undefined = undefined; + +/* We do not want to have to include DOM types just for this check */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +declare const WebAssembly: any; + +try { + wasm = new WebAssembly.Instance( + new WebAssembly.Module( + // prettier-ignore + new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11]) + ), + {} + ).exports as unknown as LongWASMHelpers; +} catch { + // no wasm support +} + +const TWO_PWR_16_DBL = 1 << 16; +const TWO_PWR_24_DBL = 1 << 24; +const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + +/** A cache of the Long representations of small integer values. */ +const INT_CACHE: { [key: number]: Long } = {}; + +/** A cache of the Long representations of small unsigned integer values. */ +const UINT_CACHE: { [key: number]: Long } = {}; + +/** @public */ +export interface LongExtended { + $numberLong: string; +} + +/** + * A class representing a 64-bit integer + * @public + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ +export class Long { + _bsontype!: 'Long'; + + /** An indicator used to reliably determine if an object is a Long or not. */ + __isLong__!: true; + + /** + * The high 32 bits as a signed value. + */ + high!: number; + + /** + * The low 32 bits as a signed value. + */ + low!: number; + + /** + * Whether unsigned or not. + */ + unsigned!: boolean; + + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + constructor(low: number | bigint | string = 0, high?: number | boolean, unsigned?: boolean) { + if (!(this instanceof Long)) return new Long(low, high, unsigned); + + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } else { + this.low = low | 0; + this.high = (high as number) | 0; + this.unsigned = !!unsigned; + } + + Object.defineProperty(this, '__isLong__', { + value: true, + configurable: false, + writable: false, + enumerable: false + }); + } + + static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); + + /** Maximum unsigned value. */ + static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); + /** Signed zero */ + static ZERO = Long.fromInt(0); + /** Unsigned zero. */ + static UZERO = Long.fromInt(0, true); + /** Signed one. */ + static ONE = Long.fromInt(1); + /** Unsigned one. */ + static UONE = Long.fromInt(1, true); + /** Signed negative one. */ + static NEG_ONE = Long.fromInt(-1); + /** Maximum signed value. */ + static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + /** Minimum signed value. */ + static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long { + return new Long(lowBits, highBits, unsigned); + } + + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromInt(value: number, unsigned?: boolean): Long { + let obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) INT_CACHE[value] = obj; + return obj; + } + } + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromNumber(value: number, unsigned?: boolean): Long { + if (isNaN(value)) return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) return Long.UZERO; + if (value >= TWO_PWR_64_DBL) return Long.MAX_UNSIGNED_VALUE; + } else { + if (value <= -TWO_PWR_63_DBL) return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) return Long.MAX_VALUE; + } + if (value < 0) return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + } + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBigInt(value: bigint, unsigned?: boolean): Long { + return Long.fromString(value.toString(), unsigned); + } + + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + static fromString(str: string, unsigned?: boolean, radix?: number): Long { + if (str.length === 0) throw Error('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + (radix = unsigned), (unsigned = false); + } else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) throw RangeError('radix'); + + let p; + if ((p = str.indexOf('-')) > 0) throw Error('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + const radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + let result = Long.ZERO; + for (let i = 0; i < str.length; i += 8) { + const size = Math.min(8, str.length - i), + value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + const power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesLE(bytes: number[], unsigned?: boolean): Long { + return new Long( + bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), + bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), + unsigned + ); + } + + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesBE(bytes: number[], unsigned?: boolean): Long { + return new Long( + (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], + (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], + unsigned + ); + } + + /** + * Tests if the specified object is a Long. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + static isLong(value: any): value is Long { + return isObjectLike(value) && value['__isLong__'] === true; + } + + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + static fromValue( + val: number | string | { low: number; high: number; unsigned?: boolean }, + unsigned?: boolean + ): Long { + if (typeof val === 'number') return Long.fromNumber(val, unsigned); + if (typeof val === 'string') return Long.fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return Long.fromBits( + val.low, + val.high, + typeof unsigned === 'boolean' ? unsigned : val.unsigned + ); + } + + /** Returns the sum of this and the specified Long. */ + add(addend: string | number | Long | Timestamp): Long { + if (!Long.isLong(addend)) addend = Long.fromValue(addend); + + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + + const b48 = addend.high >>> 16; + const b32 = addend.high & 0xffff; + const b16 = addend.low >>> 16; + const b00 = addend.low & 0xffff; + + let c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + and(other: string | number | Long | Timestamp): Long { + if (!Long.isLong(other)) other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + compare(other: string | number | Long | Timestamp): 0 | 1 | -1 { + if (!Long.isLong(other)) other = Long.fromValue(other); + if (this.eq(other)) return 0; + const thisNeg = this.isNegative(), + otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) return -1; + if (!thisNeg && otherNeg) return 1; + // At this point the sign bits are the same + if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + + /** This is an alias of {@link Long.compare} */ + comp(other: string | number | Long | Timestamp): 0 | 1 | -1 { + return this.compare(other); + } + + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + divide(divisor: string | number | Long | Timestamp): Long { + if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor); + if (divisor.isZero()) throw Error('division by zero'); + + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if ( + !this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1 + ) { + // be consistent with non-wasm code path + return this; + } + const low = (this.unsigned ? wasm.div_u : wasm.div_s)( + this.low, + this.high, + divisor.low, + divisor.high + ); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + + if (this.isZero()) return this.unsigned ? Long.UZERO : Long.ZERO; + let approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) return Long.MIN_VALUE; + // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(Long.MIN_VALUE)) return Long.ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + const halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(Long.MIN_VALUE)) return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) divisor = divisor.toUnsigned(); + if (divisor.gt(this)) return Long.UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return Long.UONE; + res = Long.UZERO; + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + let approxRes = Long.fromNumber(approx); + let approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) approxRes = Long.ONE; + + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + + /**This is an alias of {@link Long.divide} */ + div(divisor: string | number | Long | Timestamp): Long { + return this.divide(divisor); + } + + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + equals(other: string | number | Long | Timestamp): boolean { + if (!Long.isLong(other)) other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + } + + /** This is an alias of {@link Long.equals} */ + eq(other: string | number | Long | Timestamp): boolean { + return this.equals(other); + } + + /** Gets the high 32 bits as a signed integer. */ + getHighBits(): number { + return this.high; + } + + /** Gets the high 32 bits as an unsigned integer. */ + getHighBitsUnsigned(): number { + return this.high >>> 0; + } + + /** Gets the low 32 bits as a signed integer. */ + getLowBits(): number { + return this.low; + } + + /** Gets the low 32 bits as an unsigned integer. */ + getLowBitsUnsigned(): number { + return this.low >>> 0; + } + + /** Gets the number of bits needed to represent the absolute value of this Long. */ + getNumBitsAbs(): number { + if (this.isNegative()) { + // Unsigned Longs are never negative + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit: number; + for (bit = 31; bit > 0; bit--) if ((val & (1 << bit)) !== 0) break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + + /** Tests if this Long's value is greater than the specified's. */ + greaterThan(other: string | number | Long | Timestamp): boolean { + return this.comp(other) > 0; + } + + /** This is an alias of {@link Long.greaterThan} */ + gt(other: string | number | Long | Timestamp): boolean { + return this.greaterThan(other); + } + + /** Tests if this Long's value is greater than or equal the specified's. */ + greaterThanOrEqual(other: string | number | Long | Timestamp): boolean { + return this.comp(other) >= 0; + } + + /** This is an alias of {@link Long.greaterThanOrEqual} */ + gte(other: string | number | Long | Timestamp): boolean { + return this.greaterThanOrEqual(other); + } + /** This is an alias of {@link Long.greaterThanOrEqual} */ + ge(other: string | number | Long | Timestamp): boolean { + return this.greaterThanOrEqual(other); + } + + /** Tests if this Long's value is even. */ + isEven(): boolean { + return (this.low & 1) === 0; + } + + /** Tests if this Long's value is negative. */ + isNegative(): boolean { + return !this.unsigned && this.high < 0; + } + + /** Tests if this Long's value is odd. */ + isOdd(): boolean { + return (this.low & 1) === 1; + } + + /** Tests if this Long's value is positive. */ + isPositive(): boolean { + return this.unsigned || this.high >= 0; + } + + /** Tests if this Long's value equals zero. */ + isZero(): boolean { + return this.high === 0 && this.low === 0; + } + + /** Tests if this Long's value is less than the specified's. */ + lessThan(other: string | number | Long | Timestamp): boolean { + return this.comp(other) < 0; + } + + /** This is an alias of {@link Long#lessThan}. */ + lt(other: string | number | Long | Timestamp): boolean { + return this.lessThan(other); + } + + /** Tests if this Long's value is less than or equal the specified's. */ + lessThanOrEqual(other: string | number | Long | Timestamp): boolean { + return this.comp(other) <= 0; + } + + /** This is an alias of {@link Long.lessThanOrEqual} */ + lte(other: string | number | Long | Timestamp): boolean { + return this.lessThanOrEqual(other); + } + + /** Returns this Long modulo the specified. */ + modulo(divisor: string | number | Long | Timestamp): Long { + if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor); + + // use wasm support if present + if (wasm) { + const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)( + this.low, + this.high, + divisor.low, + divisor.high + ); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + + return this.sub(this.div(divisor).mul(divisor)); + } + + /** This is an alias of {@link Long.modulo} */ + mod(divisor: string | number | Long | Timestamp): Long { + return this.modulo(divisor); + } + /** This is an alias of {@link Long.modulo} */ + rem(divisor: string | number | Long | Timestamp): Long { + return this.modulo(divisor); + } + + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + multiply(multiplier: string | number | Long | Timestamp): Long { + if (this.isZero()) return Long.ZERO; + if (!Long.isLong(multiplier)) multiplier = Long.fromValue(multiplier); + + // use wasm support if present + if (wasm) { + const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + + if (multiplier.isZero()) return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + + if (this.isNegative()) { + if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); + else return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg(); + + // If both longs are small, use float multiplication + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + + const b48 = multiplier.high >>> 16; + const b32 = multiplier.high & 0xffff; + const b16 = multiplier.low >>> 16; + const b00 = multiplier.low & 0xffff; + + let c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + + /** This is an alias of {@link Long.multiply} */ + mul(multiplier: string | number | Long | Timestamp): Long { + return this.multiply(multiplier); + } + + /** Returns the Negation of this Long's value. */ + negate(): Long { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + + /** This is an alias of {@link Long.negate} */ + neg(): Long { + return this.negate(); + } + + /** Returns the bitwise NOT of this Long. */ + not(): Long { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + + /** Tests if this Long's value differs from the specified's. */ + notEquals(other: string | number | Long | Timestamp): boolean { + return !this.equals(other); + } + + /** This is an alias of {@link Long.notEquals} */ + neq(other: string | number | Long | Timestamp): boolean { + return this.notEquals(other); + } + /** This is an alias of {@link Long.notEquals} */ + ne(other: string | number | Long | Timestamp): boolean { + return this.notEquals(other); + } + + /** + * Returns the bitwise OR of this Long and the specified. + */ + or(other: number | string | Long): Long { + if (!Long.isLong(other)) other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftLeft(numBits: number | Long): Long { + if (Long.isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return Long.fromBits( + this.low << numBits, + (this.high << numBits) | (this.low >>> (32 - numBits)), + this.unsigned + ); + else return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + } + + /** This is an alias of {@link Long.shiftLeft} */ + shl(numBits: number | Long): Long { + return this.shiftLeft(numBits); + } + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRight(numBits: number | Long): Long { + if (Long.isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return Long.fromBits( + (this.low >>> numBits) | (this.high << (32 - numBits)), + this.high >> numBits, + this.unsigned + ); + else return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + } + + /** This is an alias of {@link Long.shiftRight} */ + shr(numBits: number | Long): Long { + return this.shiftRight(numBits); + } + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRightUnsigned(numBits: Long | number): Long { + if (Long.isLong(numBits)) numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) return this; + else { + const high = this.high; + if (numBits < 32) { + const low = this.low; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits, + this.unsigned + ); + } else if (numBits === 32) return Long.fromBits(high, 0, this.unsigned); + else return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + } + + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shr_u(numBits: number | Long): Long { + return this.shiftRightUnsigned(numBits); + } + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shru(numBits: number | Long): Long { + return this.shiftRightUnsigned(numBits); + } + + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + subtract(subtrahend: string | number | Long | Timestamp): Long { + if (!Long.isLong(subtrahend)) subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + + /** This is an alias of {@link Long.subtract} */ + sub(subtrahend: string | number | Long | Timestamp): Long { + return this.subtract(subtrahend); + } + + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + toInt(): number { + return this.unsigned ? this.low >>> 0 : this.low; + } + + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + toNumber(): number { + if (this.unsigned) return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + + /** Converts the Long to a BigInt (arbitrary precision). */ + toBigInt(): bigint { + return BigInt(this.toString()); + } + + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + toBytes(le?: boolean): number[] { + return le ? this.toBytesLE() : this.toBytesBE(); + } + + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + toBytesLE(): number[] { + const hi = this.high, + lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + } + + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + toBytesBE(): number[] { + const hi = this.high, + lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + } + + /** + * Converts this Long to signed. + */ + toSigned(): Long { + if (!this.unsigned) return this; + return Long.fromBits(this.low, this.high, false); + } + + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + toString(radix?: number): string { + radix = radix || 10; + if (radix < 2 || 36 < radix) throw RangeError('radix'); + if (this.isZero()) return '0'; + if (this.isNegative()) { + // Unsigned Longs are never negative + if (this.eq(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + const radixLong = Long.fromNumber(radix), + div = this.div(radixLong), + rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } else return '-' + this.neg().toString(radix); + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + // eslint-disable-next-line @typescript-eslint/no-this-alias + let rem: Long = this; + let result = ''; + // eslint-disable-next-line no-constant-condition + while (true) { + const remDiv = rem.div(radixToPower); + const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + let digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) digits = '0' + digits; + result = '' + digits + result; + } + } + } + + /** Converts this Long to unsigned. */ + toUnsigned(): Long { + if (this.unsigned) return this; + return Long.fromBits(this.low, this.high, true); + } + + /** Returns the bitwise XOR of this Long and the given one. */ + xor(other: Long | number | string): Long { + if (!Long.isLong(other)) other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + + /** This is an alias of {@link Long.isZero} */ + eqz(): boolean { + return this.isZero(); + } + + /** This is an alias of {@link Long.lessThanOrEqual} */ + le(other: string | number | Long | Timestamp): boolean { + return this.lessThanOrEqual(other); + } + + /* + **************************************************************** + * BSON SPECIFIC ADDITIONS * + **************************************************************** + */ + toExtendedJSON(options?: EJSONOptions): number | LongExtended { + if (options && options.relaxed) return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc: { $numberLong: string }, options?: EJSONOptions): number | Long { + const result = Long.fromString(doc.$numberLong); + return options && options.relaxed ? result.toNumber() : result; + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; + } +} + +Object.defineProperty(Long.prototype, '__isLong__', { value: true }); +Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); diff --git a/node_modules/bson/src/map.ts b/node_modules/bson/src/map.ts new file mode 100644 index 0000000..ba00329 --- /dev/null +++ b/node_modules/bson/src/map.ts @@ -0,0 +1,119 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// We have an ES6 Map available, return the native instance + +import { getGlobal } from './utils/global'; + +/** @public */ +let bsonMap: MapConstructor; + +const bsonGlobal = getGlobal<{ Map?: MapConstructor }>(); +if (bsonGlobal.Map) { + bsonMap = bsonGlobal.Map; +} else { + // We will return a polyfill + bsonMap = class Map { + private _keys: string[]; + private _values: Record; + constructor(array: [string, any][] = []) { + this._keys = []; + this._values = {}; + + for (let i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + const entry = array[i]; + const key = entry[0]; + const value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + } + clear() { + this._keys = []; + this._values = {}; + } + delete(key: string) { + const value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + } + entries() { + let index = 0; + + return { + next: () => { + const key = this._keys[index++]; + return { + value: key !== undefined ? [key, this._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + } + forEach(callback: (this: this, value: any, key: string, self: this) => void, self?: this) { + self = self || this; + + for (let i = 0; i < this._keys.length; i++) { + const key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + } + get(key: string) { + return this._values[key] ? this._values[key].v : undefined; + } + has(key: string) { + return this._values[key] != null; + } + keys() { + let index = 0; + + return { + next: () => { + const key = this._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + } + set(key: string, value: any) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + } + values() { + let index = 0; + + return { + next: () => { + const key = this._keys[index++]; + return { + value: key !== undefined ? this._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + } + get size() { + return this._keys.length; + } + } as unknown as MapConstructor; +} + +export { bsonMap as Map }; diff --git a/node_modules/bson/src/max_key.ts b/node_modules/bson/src/max_key.ts new file mode 100644 index 0000000..fcfc5be --- /dev/null +++ b/node_modules/bson/src/max_key.ts @@ -0,0 +1,37 @@ +/** @public */ +export interface MaxKeyExtended { + $maxKey: 1; +} + +/** + * A class representation of the BSON MaxKey type. + * @public + */ +export class MaxKey { + _bsontype!: 'MaxKey'; + + constructor() { + if (!(this instanceof MaxKey)) return new MaxKey(); + } + + /** @internal */ + toExtendedJSON(): MaxKeyExtended { + return { $maxKey: 1 }; + } + + /** @internal */ + static fromExtendedJSON(): MaxKey { + return new MaxKey(); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return 'new MaxKey()'; + } +} + +Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); diff --git a/node_modules/bson/src/min_key.ts b/node_modules/bson/src/min_key.ts new file mode 100644 index 0000000..f1647fc --- /dev/null +++ b/node_modules/bson/src/min_key.ts @@ -0,0 +1,37 @@ +/** @public */ +export interface MinKeyExtended { + $minKey: 1; +} + +/** + * A class representation of the BSON MinKey type. + * @public + */ +export class MinKey { + _bsontype!: 'MinKey'; + + constructor() { + if (!(this instanceof MinKey)) return new MinKey(); + } + + /** @internal */ + toExtendedJSON(): MinKeyExtended { + return { $minKey: 1 }; + } + + /** @internal */ + static fromExtendedJSON(): MinKey { + return new MinKey(); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return 'new MinKey()'; + } +} + +Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); diff --git a/node_modules/bson/src/objectid.ts b/node_modules/bson/src/objectid.ts new file mode 100644 index 0000000..a13165e --- /dev/null +++ b/node_modules/bson/src/objectid.ts @@ -0,0 +1,369 @@ +import { Buffer } from 'buffer'; +import { ensureBuffer } from './ensure_buffer'; +import { BSONTypeError } from './error'; +import { deprecate, isUint8Array, randomBytes } from './parser/utils'; + +// Regular expression that checks for hex value +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + +// Unique sequence for the current process (initialized on first use) +let PROCESS_UNIQUE: Uint8Array | null = null; + +/** @public */ +export interface ObjectIdLike { + id: string | Buffer; + __id?: string; + toHexString(): string; +} + +/** @public */ +export interface ObjectIdExtended { + $oid: string; +} + +const kId = Symbol('id'); + +/** + * A class representation of the BSON ObjectId type. + * @public + */ +export class ObjectId { + _bsontype!: 'ObjectId'; + + /** @internal */ + static index = ~~(Math.random() * 0xffffff); + + static cacheHexString: boolean; + + /** ObjectId Bytes @internal */ + private [kId]: Buffer; + /** ObjectId hexString cache @internal */ + private __id?: string; + + /** + * Create an ObjectId type + * + * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number. + */ + constructor(id?: string | Buffer | number | ObjectIdLike | ObjectId) { + if (!(this instanceof ObjectId)) return new ObjectId(id); + + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectId) { + this[kId] = id.id; + this.__id = id.__id; + } + + if (typeof id === 'object' && id && 'id' in id) { + if ('toHexString' in id && typeof id.toHexString === 'function') { + this[kId] = Buffer.from(id.toHexString(), 'hex'); + } else { + this[kId] = typeof id.id === 'string' ? Buffer.from(id.id) : id.id; + } + } + + // The most common use case (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined); + // If we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + + if (ArrayBuffer.isView(id) && id.byteLength === 12) { + this[kId] = ensureBuffer(id); + } + + if (typeof id === 'string') { + if (id.length === 12) { + const bytes = Buffer.from(id); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + } else if (id.length === 24 && checkForHexRegExp.test(id)) { + this[kId] = Buffer.from(id, 'hex'); + } else { + throw new BSONTypeError( + 'Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters' + ); + } + } + + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + + /** + * The ObjectId bytes + * @readonly + */ + get id(): Buffer { + return this[kId]; + } + + set id(value: Buffer) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = value.toString('hex'); + } + } + + /** + * The generation time of this ObjectId instance + * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch + */ + get generationTime(): number { + return this.id.readInt32BE(0); + } + + set generationTime(value: number) { + // Encode time into first 4 bytes + this.id.writeUInt32BE(value, 0); + } + + /** Returns the ObjectId id as a 24 character hex string representation */ + toHexString(): string { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + + const hexString = this.id.toString('hex'); + + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + + return hexString; + } + + /** + * Update the ObjectId index + * @privateRemarks + * Used in generating new ObjectId's on the driver + * @internal + */ + static getInc(): number { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + static generate(time?: number): Buffer { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + + const inc = ObjectId.getInc(); + const buffer = Buffer.alloc(12); + + // 4-byte timestamp + buffer.writeUInt32BE(time, 0); + + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = randomBytes(5); + } + + // 5-byte process unique + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + + // 3-byte counter + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + + return buffer; + } + + /** + * Converts the id into a 24 character hex string for printing + * + * @param format - The Buffer toString format parameter. + */ + toString(format?: string): string { + // Is the id a buffer then use the buffer toString method to return the format + if (format) return this.id.toString(format); + return this.toHexString(); + } + + /** Converts to its JSON the 24 character hex string representation. */ + toJSON(): string { + return this.toHexString(); + } + + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + equals(otherId: string | ObjectId | ObjectIdLike): boolean { + if (otherId === undefined || otherId === null) { + return false; + } + + if (otherId instanceof ObjectId) { + return this.toString() === otherId.toString(); + } + + if ( + typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id) + ) { + return otherId === Buffer.prototype.toString.call(this.id, 'latin1'); + } + + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } + + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { + return Buffer.from(otherId).equals(this.id); + } + + if ( + typeof otherId === 'object' && + 'toHexString' in otherId && + typeof otherId.toHexString === 'function' + ) { + return otherId.toHexString() === this.toHexString(); + } + + return false; + } + + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + getTimestamp(): Date { + const timestamp = new Date(); + const time = this.id.readUInt32BE(0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + + /** @internal */ + static createPk(): ObjectId { + return new ObjectId(); + } + + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + static createFromTime(time: number): ObjectId { + const buffer = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer.writeUInt32BE(time, 0); + // Return the new objectId + return new ObjectId(buffer); + } + + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + static createFromHexString(hexString: string): ObjectId { + // Throw an error if it's not a valid setup + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONTypeError( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + return new ObjectId(Buffer.from(hexString, 'hex')); + } + + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + static isValid(id: number | string | ObjectId | Uint8Array | ObjectIdLike): boolean { + if (id == null) return false; + + if (typeof id === 'number') { + return true; + } + + if (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); + } + + if (id instanceof ObjectId) { + return true; + } + + if (isUint8Array(id) && id.length === 12) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { + if (typeof id.id === 'string') { + return id.id.length === 12; + } + return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); + } + + return false; + } + + /** @internal */ + toExtendedJSON(): ObjectIdExtended { + if (this.toHexString) return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + + /** @internal */ + static fromExtendedJSON(doc: ObjectIdExtended): ObjectId { + return new ObjectId(doc.$oid); + } + + /** + * Converts to a string representation of this Id. + * + * @returns return the 24 character hex string representation. + * @internal + */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new ObjectId("${this.toHexString()}")`; + } +} + +// Deprecated methods +Object.defineProperty(ObjectId.prototype, 'generate', { + value: deprecate( + (time: number) => ObjectId.generate(time), + 'Please use the static `ObjectId.generate(time)` instead' + ) +}); + +Object.defineProperty(ObjectId.prototype, 'getInc', { + value: deprecate(() => ObjectId.getInc(), 'Please use the static `ObjectId.getInc()` instead') +}); + +Object.defineProperty(ObjectId.prototype, 'get_inc', { + value: deprecate(() => ObjectId.getInc(), 'Please use the static `ObjectId.getInc()` instead') +}); + +Object.defineProperty(ObjectId, 'get_inc', { + value: deprecate(() => ObjectId.getInc(), 'Please use the static `ObjectId.getInc()` instead') +}); + +Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); diff --git a/node_modules/bson/src/parser/calculate_size.ts b/node_modules/bson/src/parser/calculate_size.ts new file mode 100644 index 0000000..6a67d44 --- /dev/null +++ b/node_modules/bson/src/parser/calculate_size.ts @@ -0,0 +1,227 @@ +import { Buffer } from 'buffer'; +import { Binary } from '../binary'; +import type { Document } from '../bson'; +import * as constants from '../constants'; +import { isAnyArrayBuffer, isDate, isRegExp, normalizedFunctionString } from './utils'; + +export function calculateObjectSize( + object: Document, + serializeFunctions?: boolean, + ignoreUndefined?: boolean +): number { + let totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + totalLength += calculateElement( + i.toString(), + object[i], + serializeFunctions, + true, + ignoreUndefined + ); + } + } else { + // If we have toBSON defined, override the current object + + if (object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for (const key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; +} + +/** @internal */ +function calculateElement( + name: string, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + value: any, + serializeFunctions = false, + isArray = false, + ignoreUndefined = false +) { + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if ( + Math.floor(value) === value && + value >= constants.JS_INT_MIN && + value <= constants.JS_INT_MAX + ) { + if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if ( + ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value) + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength + ); + } else if ( + value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + ); + } + } else if (value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) + ); + } + } else if (value['_bsontype'] === 'Symbol') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + Buffer.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1 + ); + } else if (value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + const ordered_values = Object.assign( + { + $ref: value.collection, + $id: value.oid + }, + value.fields + ); + + // Add db reference if it exists + if (value.db != null) { + ordered_values['$db'] = value.db; + } + + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) + ); + } else if (value instanceof RegExp || isRegExp(value)) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else if (value['_bsontype'] === 'BSONRegExp') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.pattern, 'utf8') + + 1 + + Buffer.byteLength(value.options, 'utf8') + + 1 + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1 + ); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else if (serializeFunctions) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + ); + } + } + } + + return 0; +} diff --git a/node_modules/bson/src/parser/deserializer.ts b/node_modules/bson/src/parser/deserializer.ts new file mode 100644 index 0000000..3ba0549 --- /dev/null +++ b/node_modules/bson/src/parser/deserializer.ts @@ -0,0 +1,684 @@ +import { Buffer } from 'buffer'; +import { Binary } from '../binary'; +import type { Document } from '../bson'; +import { Code } from '../code'; +import * as constants from '../constants'; +import { DBRef, DBRefLike, isDBRefLike } from '../db_ref'; +import { Decimal128 } from '../decimal128'; +import { Double } from '../double'; +import { BSONError } from '../error'; +import { Int32 } from '../int_32'; +import { Long } from '../long'; +import { MaxKey } from '../max_key'; +import { MinKey } from '../min_key'; +import { ObjectId } from '../objectid'; +import { BSONRegExp } from '../regexp'; +import { BSONSymbol } from '../symbol'; +import { Timestamp } from '../timestamp'; +import { validateUtf8 } from '../validate_utf8'; + +/** @public */ +export interface DeserializeOptions { + /** evaluate functions in the BSON document scoped to the object deserialized. */ + evalFunctions?: boolean; + /** cache evaluated functions for reuse. */ + cacheFunctions?: boolean; + /** + * use a crc32 code for caching, otherwise use the string of the function. + * @deprecated this option to use the crc32 function never worked as intended + * due to the fact that the crc32 function itself was never implemented. + * */ + cacheFunctionsCrc32?: boolean; + /** when deserializing a Long will fit it into a Number if it's smaller than 53 bits */ + promoteLongs?: boolean; + /** when deserializing a Binary will return it as a node.js Buffer instance. */ + promoteBuffers?: boolean; + /** when deserializing will promote BSON values to their Node.js closest equivalent types. */ + promoteValues?: boolean; + /** allow to specify if there what fields we wish to return as unserialized raw buffer. */ + fieldsAsRaw?: Document; + /** return BSON regular expressions as BSONRegExp instances. */ + bsonRegExp?: boolean; + /** allows the buffer to be larger than the parsed BSON object */ + allowObjectSmallerThanBufferSize?: boolean; + /** Offset into buffer to begin reading document from */ + index?: number; + + raw?: boolean; +} + +// Internal long versions +const JS_INT_MAX_LONG = Long.fromNumber(constants.JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(constants.JS_INT_MIN); + +const functionCache: { [hash: string]: Function } = {}; + +export function deserialize( + buffer: Buffer, + options: DeserializeOptions, + isArray?: boolean +): Document { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + // Read the document size + const size = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + + if (size < 5) { + throw new BSONError(`bson size must be >= 5, is ${size}`); + } + + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`); + } + + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`); + } + + if (size + index > buffer.byteLength) { + throw new BSONError( + `(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})` + ); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new BSONError( + "One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00" + ); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +} + +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; + +function deserializeObject( + buffer: Buffer, + index: number, + options: DeserializeOptions, + isArray = false +) { + const evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + const cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + const raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + const promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + const promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + const promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + const startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new BSONError('corrupt bson message < 5 bytes long'); + + // Read the document size + const size = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new BSONError('corrupt bson message'); + + // Create holding object + const object: Document = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + let arrayIndex = 0; + const done = false; + + let isPossibleDBRef = isArray ? false : null; + + // While we have more left data left keep parsing + while (!done) { + // Read the type + const elementType = buffer[index++]; + + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + let i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.byteLength) throw new BSONError('Bad BSON Document: illegal CString'); + const name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + if (isPossibleDBRef !== false && (name as string)[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name as string); + } + let value; + + index = i + 1; + + if (elementType === constants.BSON_DATA_STRING) { + const stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + + value = getValidatedString(buffer, index, index + stringSize - 1); + + index = index + stringSize; + } else if (elementType === constants.BSON_DATA_OID) { + const oid = Buffer.alloc(12); + buffer.copy(oid, 0, index, index + 12); + value = new ObjectId(oid); + index = index + 12; + } else if (elementType === constants.BSON_DATA_INT && promoteValues === false) { + value = new Int32( + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) + ); + } else if (elementType === constants.BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } else if (elementType === constants.BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if (elementType === constants.BSON_DATA_NUMBER) { + value = buffer.readDoubleLE(index); + index = index + 8; + } else if (elementType === constants.BSON_DATA_DATE) { + const lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === constants.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } else if (elementType === constants.BSON_DATA_OBJECT) { + const _index = index; + const objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new BSONError('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + value = buffer.slice(index, index + objectSize); + } else { + value = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if (elementType === constants.BSON_DATA_ARRAY) { + const _index = index; + const objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + let arrayOptions = options; + + // Stop index + const stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (const n in options) { + ( + arrayOptions as { + [key: string]: DeserializeOptions[keyof DeserializeOptions]; + } + )[n] = options[n as keyof DeserializeOptions]; + } + arrayOptions['raw'] = true; + } + + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new BSONError('invalid array terminator byte'); + if (index !== stopIndex) throw new BSONError('corrupted array bson'); + } else if (elementType === constants.BSON_DATA_UNDEFINED) { + value = undefined; + } else if (elementType === constants.BSON_DATA_NULL) { + value = null; + } else if (elementType === constants.BSON_DATA_LONG) { + // Unpack the low and high bits + const lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } else { + value = long; + } + } else if (elementType === constants.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + const bytes = Buffer.alloc(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + const decimal128 = new Decimal128(bytes) as Decimal128 | { toObject(): unknown }; + // If we have an alternative mapper use that + if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { + value = decimal128.toObject(); + } else { + value = decimal128; + } + } else if (elementType === constants.BSON_DATA_BINARY) { + let binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const totalBinarySize = binarySize; + const subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new BSONError('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + + if (promoteBuffers && promoteValues) { + value = buffer.slice(index, index + binarySize); + } else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + const _buffer = Buffer.alloc(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + value = _buffer; + } else { + value = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + const optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + value = new RegExp(source, optionsArray.join('')); + } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + value = new BSONRegExp(source, regExpOptions); + } else if (elementType === constants.BSON_DATA_SYMBOL) { + const stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + const symbol = getValidatedString(buffer, index, index + stringSize - 1); + value = promoteValues ? symbol : new BSONSymbol(symbol); + index = index + stringSize; + } else if (elementType === constants.BSON_DATA_TIMESTAMP) { + const lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + + value = new Timestamp(lowBits, highBits); + } else if (elementType === constants.BSON_DATA_MIN_KEY) { + value = new MinKey(); + } else if (elementType === constants.BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } else if (elementType === constants.BSON_DATA_CODE) { + const stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + const functionString = getValidatedString(buffer, index, index + stringSize - 1); + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } else { + value = isolateEval(functionString); + } + } else { + value = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) { + const totalSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + const stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + + // Javascript function + const functionString = getValidatedString(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + const _index = index; + // Decode the size of the object document + const objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + const scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is too short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + + // Check if totalSize field is too long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } else { + value = isolateEval(functionString); + } + + value.scope = scopeObject; + } else { + value = new Code(functionString, scopeObject); + } + } else if (elementType === constants.BSON_DATA_DBPOINTER) { + // Get the code string size + const stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new BSONError('bad string length in bson'); + // Namespace + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + const namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + const oidBuffer = Buffer.alloc(12); + buffer.copy(oidBuffer, 0, index, index + 12); + const oid = new ObjectId(oidBuffer); + + // Update the index + index = index + 12; + + // Upgrade to DBRef type + value = new DBRef(namespace, oid); + } else { + throw new BSONError( + 'Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"' + ); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } else { + object[name] = value; + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + + // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef + if (!isPossibleDBRef) return object; + + if (isDBRefLike(object)) { + const copy = Object.assign({}, object) as Partial; + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + + return object; +} + +/** + * Ensure eval is isolated, store the result in functionCache. + * + * @internal + */ +function isolateEval( + functionString: string, + functionCache?: { [hash: string]: Function }, + object?: Document +) { + if (!functionCache) return new Function(functionString); + // Check for cache hit, eval if missing and return cached function + if (functionCache[functionString] == null) { + functionCache[functionString] = new Function(functionString); + } + + // Set the object + return functionCache[functionString].bind(object); +} + +function getValidatedString(buffer: Buffer, start: number, end: number) { + const value = buffer.toString('utf8', start, end); + for (let i = 0; i < value.length; i++) { + if (value.charCodeAt(i) === 0xfffd) { + if (!validateUtf8(buffer, start, end)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + return value; +} diff --git a/node_modules/bson/src/parser/serializer.ts b/node_modules/bson/src/parser/serializer.ts new file mode 100644 index 0000000..db9e015 --- /dev/null +++ b/node_modules/bson/src/parser/serializer.ts @@ -0,0 +1,1071 @@ +import type { Buffer } from 'buffer'; +import { Binary } from '../binary'; +import type { BSONSymbol, DBRef, Document, MaxKey } from '../bson'; +import type { Code } from '../code'; +import * as constants from '../constants'; +import type { DBRefLike } from '../db_ref'; +import type { Decimal128 } from '../decimal128'; +import type { Double } from '../double'; +import { ensureBuffer } from '../ensure_buffer'; +import { BSONError, BSONTypeError } from '../error'; +import { isBSONType } from '../extended_json'; +import { writeIEEE754 } from '../float_parser'; +import type { Int32 } from '../int_32'; +import { Long } from '../long'; +import { Map } from '../map'; +import type { MinKey } from '../min_key'; +import type { ObjectId } from '../objectid'; +import type { BSONRegExp } from '../regexp'; +import { + isBigInt64Array, + isBigUInt64Array, + isDate, + isMap, + isRegExp, + isUint8Array, + normalizedFunctionString +} from './utils'; + +/** @public */ +export interface SerializeOptions { + /** the serializer will check if keys are valid. */ + checkKeys?: boolean; + /** serialize the javascript functions **(default:false)**. */ + serializeFunctions?: boolean; + /** serialize will not emit undefined fields **(default:true)** */ + ignoreUndefined?: boolean; + /** @internal Resize internal buffer */ + minInternalBufferSize?: number; + /** the index in the buffer where we wish to start serializing into */ + index?: number; +} + +const regexp = /\x00/; // eslint-disable-line no-control-regex +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); + +/* + * isArray indicates if we are writing to a BSON array (type 0x04) + * which forces the "key" which really an array index as a string to be written as ascii + * This will catch any errors in index as a string generation + */ + +function serializeString( + buffer: Buffer, + key: string, + value: string, + index: number, + isArray?: boolean +) { + // Encode String type + buffer[index++] = constants.BSON_DATA_STRING; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + const size = buffer.write(value, index + 4, undefined, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} + +function serializeNumber( + buffer: Buffer, + key: string, + value: number, + index: number, + isArray?: boolean +) { + // We have an integer value + // TODO(NODE-2529): Add support for big int + if ( + Number.isInteger(value) && + value >= constants.BSON_INT32_MIN && + value <= constants.BSON_INT32_MAX + ) { + // If the value fits in 32 bits encode as int32 + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + } + + return index; +} + +function serializeNull(buffer: Buffer, key: string, _: unknown, index: number, isArray?: boolean) { + // Set long type + buffer[index++] = constants.BSON_DATA_NULL; + + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +function serializeBoolean( + buffer: Buffer, + key: string, + value: boolean, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_BOOLEAN; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} + +function serializeDate(buffer: Buffer, key: string, value: Date, index: number, isArray?: boolean) { + // Write the type + buffer[index++] = constants.BSON_DATA_DATE; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +function serializeRegExp( + buffer: Buffer, + key: string, + value: RegExp, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.global) buffer[index++] = 0x73; // s + if (value.multiline) buffer[index++] = 0x6d; // m + + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +function serializeBSONRegExp( + buffer: Buffer, + key: string, + value: BSONRegExp, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +function serializeMinMax( + buffer: Buffer, + key: string, + value: MinKey | MaxKey, + index: number, + isArray?: boolean +) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = constants.BSON_DATA_NULL; + } else if (value._bsontype === 'MinKey') { + buffer[index++] = constants.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = constants.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +function serializeObjectId( + buffer: Buffer, + key: string, + value: ObjectId, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_OID; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, undefined, 'binary'); + } else if (isUint8Array(value.id)) { + // Use the standard JS methods here because buffer.copy() is buggy with the + // browser polyfill + buffer.set(value.id.subarray(0, 12), index); + } else { + throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Adjust index + return index + 12; +} + +function serializeBuffer( + buffer: Buffer, + key: string, + value: Buffer | Uint8Array, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + const size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + buffer.set(ensureBuffer(value), index); + // Adjust the index + index = index + size; + return index; +} + +function serializeObject( + buffer: Buffer, + key: string, + value: Document, + index: number, + checkKeys = false, + depth = 0, + serializeFunctions = false, + ignoreUndefined = true, + isArray = false, + path: Document[] = [] +) { + for (let i = 0; i < path.length; i++) { + if (path[i] === value) throw new BSONError('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto( + buffer, + value, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined, + path + ); + // Pop stack + path.pop(); + return endIndex; +} + +function serializeDecimal128( + buffer: Buffer, + key: string, + value: Decimal128, + index: number, + isArray?: boolean +) { + buffer[index++] = constants.BSON_DATA_DECIMAL128; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + // Prefer the standard JS methods because their typechecking is not buggy, + // unlike the `buffer` polyfill's. + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} + +function serializeLong(buffer: Buffer, key: string, value: Long, index: number, isArray?: boolean) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +function serializeInt32( + buffer: Buffer, + key: string, + value: Int32 | number, + index: number, + isArray?: boolean +) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +} + +function serializeDouble( + buffer: Buffer, + key: string, + value: Double, + index: number, + isArray?: boolean +) { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write float + writeIEEE754(buffer, value.value, index, 'little', 52, 8); + + // Adjust index + index = index + 8; + return index; +} + +function serializeFunction( + buffer: Buffer, + key: string, + value: Function, + index: number, + _checkKeys = false, + _depth = 0, + isArray?: boolean +) { + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + const functionString = normalizedFunctionString(value); + + // Write the string + const size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} + +function serializeCode( + buffer: Buffer, + key: string, + value: Code, + index: number, + checkKeys = false, + depth = 0, + serializeFunctions = false, + ignoreUndefined = true, + isArray = false +) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + let startIndex = index; + + // Serialize the function + // Get the function string + const functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + const codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + const endIndex = serializeInto( + buffer, + value.scope, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined + ); + index = endIndex - 1; + + // Writ the total + const totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + const functionString = value.code.toString(); + // Write the string + const size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +} + +function serializeBinary( + buffer: Buffer, + key: string, + value: Binary, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + const data = value.value(true) as Buffer | Uint8Array; + // Calculate size + let size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + buffer.set(data, index); + // Adjust the index + index = index + value.position; + return index; +} + +function serializeSymbol( + buffer: Buffer, + key: string, + value: BSONSymbol, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_SYMBOL; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + const size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} + +function serializeDBRef( + buffer: Buffer, + key: string, + value: DBRef, + index: number, + depth: number, + serializeFunctions: boolean, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_OBJECT; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + let startIndex = index; + let output: DBRefLike = { + $ref: value.collection || value.namespace, // "namespace" was what library 1.x called "collection" + $id: value.oid + }; + + if (value.db != null) { + output.$db = value.db; + } + + output = Object.assign(output, value.fields); + const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); + + // Calculate object size + const size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +} + +export function serializeInto( + buffer: Buffer, + object: Document, + checkKeys = false, + startingIndex = 0, + depth = 0, + serializeFunctions = false, + ignoreUndefined = true, + path: Document[] = [] +): number { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + let index = startingIndex + 4; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (let i = 0; i < object.length; i++) { + const key = '' + i; + let value = object[i]; + + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (typeof value === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (typeof value === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true, + path + ); + } else if ( + typeof value === 'object' && + isBSONType(value) && + value._bsontype === 'Decimal128' + ) { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true + ); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + + while (!done) { + // Unpack the next entry + const entry = iterator.next(); + done = !!entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + const key = entry.value[0]; + const value = entry.value[1]; + + // Check the type of the value + const type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') throw new BSONTypeError('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new BSONTypeError('toBSON function did not return an object'); + } + + // Iterate over all the keys + for (const key in object) { + let value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + + // Check the type of the value + const type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + const size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} diff --git a/node_modules/bson/src/parser/utils.ts b/node_modules/bson/src/parser/utils.ts new file mode 100644 index 0000000..2cd128a --- /dev/null +++ b/node_modules/bson/src/parser/utils.ts @@ -0,0 +1,123 @@ +import { Buffer } from 'buffer'; +import { getGlobal } from '../utils/global'; + +type RandomBytesFunction = (size: number) => Uint8Array; + +/** + * Normalizes our expected stringified form of a function across versions of node + * @param fn - The function to stringify + */ +export function normalizedFunctionString(fn: Function): string { + return fn.toString().replace('function(', 'function ('); +} + +function isReactNative() { + const g = getGlobal<{ navigator?: { product?: string } }>(); + return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; +} + +const insecureRandomBytes: RandomBytesFunction = function insecureRandomBytes(size: number) { + const insecureWarning = isReactNative() + ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; + console.warn(insecureWarning); + + const result = Buffer.alloc(size); + for (let i = 0; i < size; ++i) result[i] = Math.floor(Math.random() * 256); + return result; +}; + +/* We do not want to have to include DOM types just for this check */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +declare let window: any; +declare let require: Function; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +declare let global: any; +declare const self: unknown; + +const detectRandomBytes = (): RandomBytesFunction => { + if (typeof window !== 'undefined') { + // browser crypto implementation(s) + const target = window.crypto || window.msCrypto; // allow for IE11 + if (target && target.getRandomValues) { + return size => target.getRandomValues(Buffer.alloc(size)); + } + } + + if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { + // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global + return size => global.crypto.getRandomValues(Buffer.alloc(size)); + } + + let requiredRandomBytes: RandomBytesFunction | null | undefined; + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + requiredRandomBytes = require('crypto').randomBytes; + } catch (e) { + // keep the fallback + } + + // NOTE: in transpiled cases the above require might return null/undefined + + return requiredRandomBytes || insecureRandomBytes; +}; + +export const randomBytes = detectRandomBytes(); + +export function isAnyArrayBuffer(value: unknown): value is ArrayBuffer { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes( + Object.prototype.toString.call(value) + ); +} + +export function isUint8Array(value: unknown): value is Uint8Array { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} + +export function isBigInt64Array(value: unknown): value is BigInt64Array { + return Object.prototype.toString.call(value) === '[object BigInt64Array]'; +} + +export function isBigUInt64Array(value: unknown): value is BigUint64Array { + return Object.prototype.toString.call(value) === '[object BigUint64Array]'; +} + +export function isRegExp(d: unknown): d is RegExp { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} + +export function isMap(d: unknown): d is Map { + return Object.prototype.toString.call(d) === '[object Map]'; +} + +/** Call to check if your environment has `Buffer` */ +export function haveBuffer(): boolean { + return typeof global !== 'undefined' && typeof global.Buffer !== 'undefined'; +} + +// To ensure that 0.4 of node works correctly +export function isDate(d: unknown): d is Date { + return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; +} + +/** + * @internal + * this is to solve the `'someKey' in x` problem where x is unknown. + * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 + */ +export function isObjectLike(candidate: unknown): candidate is Record { + return typeof candidate === 'object' && candidate !== null; +} + +declare let console: { warn(...message: unknown[]): void }; +export function deprecate(fn: T, message: string): T { + let warned = false; + function deprecated(this: unknown, ...args: unknown[]) { + if (!warned) { + console.warn(message); + warned = true; + } + return fn.apply(this, args); + } + return deprecated as unknown as T; +} diff --git a/node_modules/bson/src/regexp.ts b/node_modules/bson/src/regexp.ts new file mode 100644 index 0000000..7151bec --- /dev/null +++ b/node_modules/bson/src/regexp.ts @@ -0,0 +1,104 @@ +import { BSONError, BSONTypeError } from './error'; +import type { EJSONOptions } from './extended_json'; + +function alphabetize(str: string): string { + return str.split('').sort().join(''); +} + +/** @public */ +export interface BSONRegExpExtendedLegacy { + $regex: string | BSONRegExp; + $options: string; +} + +/** @public */ +export interface BSONRegExpExtended { + $regularExpression: { + pattern: string; + options: string; + }; +} + +/** + * A class representation of the BSON RegExp type. + * @public + */ +export class BSONRegExp { + _bsontype!: 'BSONRegExp'; + + pattern!: string; + options!: string; + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + constructor(pattern: string, options?: string) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(pattern, options); + + this.pattern = pattern; + this.options = alphabetize(options ?? ''); + + if (this.pattern.indexOf('\x00') !== -1) { + throw new BSONError( + `BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}` + ); + } + if (this.options.indexOf('\x00') !== -1) { + throw new BSONError( + `BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}` + ); + } + + // Validate options + for (let i = 0; i < this.options.length; i++) { + if ( + !( + this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u' + ) + ) { + throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`); + } + } + } + + static parseOptions(options?: string): string { + return options ? options.split('').sort().join('') : ''; + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): BSONRegExpExtendedLegacy | BSONRegExpExtended { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + + /** @internal */ + static fromExtendedJSON(doc: BSONRegExpExtendedLegacy | BSONRegExpExtended): BSONRegExp { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + // This is for $regex query operators that have extended json values. + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc as unknown as BSONRegExp; + } + } else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp( + doc.$regularExpression.pattern, + BSONRegExp.parseOptions(doc.$regularExpression.options) + ); + } + throw new BSONTypeError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } +} + +Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); diff --git a/node_modules/bson/src/symbol.ts b/node_modules/bson/src/symbol.ts new file mode 100644 index 0000000..10601b0 --- /dev/null +++ b/node_modules/bson/src/symbol.ts @@ -0,0 +1,57 @@ +/** @public */ +export interface BSONSymbolExtended { + $symbol: string; +} + +/** + * A class representation of the BSON Symbol type. + * @public + */ +export class BSONSymbol { + _bsontype!: 'Symbol'; + + value!: string; + /** + * @param value - the string representing the symbol. + */ + constructor(value: string) { + if (!(this instanceof BSONSymbol)) return new BSONSymbol(value); + + this.value = value; + } + + /** Access the wrapped string value. */ + valueOf(): string { + return this.value; + } + + toString(): string { + return this.value; + } + + /** @internal */ + inspect(): string { + return `new BSONSymbol("${this.value}")`; + } + + toJSON(): string { + return this.value; + } + + /** @internal */ + toExtendedJSON(): BSONSymbolExtended { + return { $symbol: this.value }; + } + + /** @internal */ + static fromExtendedJSON(doc: BSONSymbolExtended): BSONSymbol { + return new BSONSymbol(doc.$symbol); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } +} + +Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); diff --git a/node_modules/bson/src/timestamp.ts b/node_modules/bson/src/timestamp.ts new file mode 100644 index 0000000..e6eb470 --- /dev/null +++ b/node_modules/bson/src/timestamp.ts @@ -0,0 +1,116 @@ +import { Long } from './long'; +import { isObjectLike } from './parser/utils'; + +/** @public */ +export type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect'; +/** @public */ +export type LongWithoutOverrides = new (low: unknown, high?: number, unsigned?: boolean) => { + [P in Exclude]: Long[P]; +}; +/** @public */ +export const LongWithoutOverridesClass: LongWithoutOverrides = + Long as unknown as LongWithoutOverrides; + +/** @public */ +export interface TimestampExtended { + $timestamp: { + t: number; + i: number; + }; +} + +/** @public */ +export class Timestamp extends LongWithoutOverridesClass { + _bsontype!: 'Timestamp'; + + static readonly MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + + /** + * @param low - A 64-bit Long representing the Timestamp. + */ + constructor(long: Long); + /** + * @param value - A pair of two values indicating timestamp and increment. + */ + constructor(value: { t: number; i: number }); + /** + * @param low - the low (signed) 32 bits of the Timestamp. + * @param high - the high (signed) 32 bits of the Timestamp. + * @deprecated Please use `Timestamp({ t: high, i: low })` or `Timestamp(Long(low, high))` instead. + */ + constructor(low: number, high: number); + constructor(low: number | Long | { t: number; i: number }, high?: number) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + ///@ts-expect-error + if (!(this instanceof Timestamp)) return new Timestamp(low, high); + + if (Long.isLong(low)) { + super(low.low, low.high, true); + } else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { + super(low.i, low.t, true); + } else { + super(low, high, true); + } + Object.defineProperty(this, '_bsontype', { + value: 'Timestamp', + writable: false, + configurable: false, + enumerable: false + }); + } + + toJSON(): { $timestamp: string } { + return { + $timestamp: this.toString() + }; + } + + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + static fromInt(value: number): Timestamp { + return new Timestamp(Long.fromInt(value, true)); + } + + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + static fromNumber(value: number): Timestamp { + return new Timestamp(Long.fromNumber(value, true)); + } + + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + static fromBits(lowBits: number, highBits: number): Timestamp { + return new Timestamp(lowBits, highBits); + } + + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + static fromString(str: string, optRadix: number): Timestamp { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + + /** @internal */ + toExtendedJSON(): TimestampExtended { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + + /** @internal */ + static fromExtendedJSON(doc: TimestampExtended): Timestamp { + return new Timestamp(doc.$timestamp); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`; + } +} diff --git a/node_modules/bson/src/utils/global.ts b/node_modules/bson/src/utils/global.ts new file mode 100644 index 0000000..8b18e85 --- /dev/null +++ b/node_modules/bson/src/utils/global.ts @@ -0,0 +1,22 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* We do not want to have to include DOM types just for this check */ +declare const window: unknown; +declare const self: unknown; +declare const global: unknown; + +function checkForMath(potentialGlobal: any) { + // eslint-disable-next-line eqeqeq + return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; +} + +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +export function getGlobal>(): T { + // eslint-disable-next-line no-undef + return ( + checkForMath(typeof globalThis === 'object' && globalThis) || + checkForMath(typeof window === 'object' && window) || + checkForMath(typeof self === 'object' && self) || + checkForMath(typeof global === 'object' && global) || + Function('return this')() + ); +} diff --git a/node_modules/bson/src/uuid.ts b/node_modules/bson/src/uuid.ts new file mode 100644 index 0000000..596baf3 --- /dev/null +++ b/node_modules/bson/src/uuid.ts @@ -0,0 +1,209 @@ +import { Buffer } from 'buffer'; +import { ensureBuffer } from './ensure_buffer'; +import { Binary } from './binary'; +import { bufferToUuidHexString, uuidHexStringToBuffer, uuidValidateString } from './uuid_utils'; +import { isUint8Array, randomBytes } from './parser/utils'; +import { BSONTypeError } from './error'; + +/** @public */ +export type UUIDExtended = { + $uuid: string; +}; + +const BYTE_LENGTH = 16; + +const kId = Symbol('id'); + +/** + * A class representation of the BSON UUID type. + * @public + */ +export class UUID { + // This property is not meant for direct serialization, but simply an indication that this type originates from this package. + _bsontype!: 'UUID'; + + static cacheHexString: boolean; + + /** UUID Bytes @internal */ + private [kId]: Buffer; + /** UUID hexString cache @internal */ + private __id?: string; + + /** + * Create an UUID type + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + constructor(input?: string | Buffer | UUID) { + if (typeof input === 'undefined') { + // The most common use case (blank id, new UUID() instance) + this.id = UUID.generate(); + } else if (input instanceof UUID) { + this[kId] = Buffer.from(input.id); + this.__id = input.__id; + } else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { + this.id = ensureBuffer(input); + } else if (typeof input === 'string') { + this.id = uuidHexStringToBuffer(input); + } else { + throw new BSONTypeError( + 'Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).' + ); + } + } + + /** + * The UUID bytes + * @readonly + */ + get id(): Buffer { + return this[kId]; + } + + set id(value: Buffer) { + this[kId] = value; + + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + } + + /** + * Generate a 16 byte uuid v4 buffer used in UUIDs + */ + + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + * */ + toHexString(includeDashes = true): string { + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + + const uuidHexString = bufferToUuidHexString(this.id, includeDashes); + + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + + return uuidHexString; + } + + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + toString(encoding?: string): string { + return encoding ? this.id.toString(encoding) : this.toHexString(); + } + + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + toJSON(): string { + return this.toHexString(); + } + + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + equals(otherId: string | Buffer | UUID): boolean { + if (!otherId) { + return false; + } + + if (otherId instanceof UUID) { + return otherId.id.equals(this.id); + } + + try { + return new UUID(otherId).id.equals(this.id); + } catch { + return false; + } + } + + /** + * Creates a Binary instance from the current UUID. + */ + toBinary(): Binary { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + + /** + * Generates a populated buffer containing a v4 uuid + */ + static generate(): Buffer { + const bytes = randomBytes(BYTE_LENGTH); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + + return Buffer.from(bytes); + } + + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + static isValid(input: string | Buffer | UUID): boolean { + if (!input) { + return false; + } + + if (input instanceof UUID) { + return true; + } + + if (typeof input === 'string') { + return uuidValidateString(input); + } + + if (isUint8Array(input)) { + // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) + if (input.length !== BYTE_LENGTH) { + return false; + } + + try { + // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx + // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx + return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID; + } catch { + return false; + } + } + + return false; + } + + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + static createFromHexString(hexString: string): UUID { + const buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + } + + /** + * Converts to a string representation of this Id. + * + * @returns return the 36 character hex string representation. + * @internal + */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new UUID("${this.toHexString()}")`; + } +} + +Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); diff --git a/node_modules/bson/src/uuid_utils.ts b/node_modules/bson/src/uuid_utils.ts new file mode 100644 index 0000000..f37b065 --- /dev/null +++ b/node_modules/bson/src/uuid_utils.ts @@ -0,0 +1,33 @@ +import { Buffer } from 'buffer'; +import { BSONTypeError } from './error'; + +// Validation regex for v4 uuid (validates with or without dashes) +const VALIDATION_REGEX = + /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; + +export const uuidValidateString = (str: string): boolean => + typeof str === 'string' && VALIDATION_REGEX.test(str); + +export const uuidHexStringToBuffer = (hexString: string): Buffer => { + if (!uuidValidateString(hexString)) { + throw new BSONTypeError( + 'UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".' + ); + } + + const sanitizedHexString = hexString.replace(/-/g, ''); + return Buffer.from(sanitizedHexString, 'hex'); +}; + +export const bufferToUuidHexString = (buffer: Buffer, includeDashes = true): string => + includeDashes + ? buffer.toString('hex', 0, 4) + + '-' + + buffer.toString('hex', 4, 6) + + '-' + + buffer.toString('hex', 6, 8) + + '-' + + buffer.toString('hex', 8, 10) + + '-' + + buffer.toString('hex', 10, 16) + : buffer.toString('hex'); diff --git a/node_modules/bson/src/validate_utf8.ts b/node_modules/bson/src/validate_utf8.ts new file mode 100644 index 0000000..e1da934 --- /dev/null +++ b/node_modules/bson/src/validate_utf8.ts @@ -0,0 +1,47 @@ +const FIRST_BIT = 0x80; +const FIRST_TWO_BITS = 0xc0; +const FIRST_THREE_BITS = 0xe0; +const FIRST_FOUR_BITS = 0xf0; +const FIRST_FIVE_BITS = 0xf8; + +const TWO_BIT_CHAR = 0xc0; +const THREE_BIT_CHAR = 0xe0; +const FOUR_BIT_CHAR = 0xf0; +const CONTINUING_CHAR = 0x80; + +/** + * Determines if the passed in bytes are valid utf8 + * @param bytes - An array of 8-bit bytes. Must be indexable and have length property + * @param start - The index to start validating + * @param end - The index to end validating + */ +export function validateUtf8( + bytes: { [index: number]: number }, + start: number, + end: number +): boolean { + let continuation = 0; + + for (let i = start; i < end; i += 1) { + const byte = bytes[i]; + + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } else { + return false; + } + } + } + + return !continuation; +} diff --git a/node_modules/buffer-equal-constant-time/.npmignore b/node_modules/buffer-equal-constant-time/.npmignore new file mode 100644 index 0000000..34e4f5c --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.npmignore @@ -0,0 +1,2 @@ +.*.sw[mnop] +node_modules/ diff --git a/node_modules/buffer-equal-constant-time/.travis.yml b/node_modules/buffer-equal-constant-time/.travis.yml new file mode 100644 index 0000000..78e1c01 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: +- "0.11" +- "0.10" diff --git a/node_modules/buffer-equal-constant-time/LICENSE.txt b/node_modules/buffer-equal-constant-time/LICENSE.txt new file mode 100644 index 0000000..9a064f3 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (c) 2013, GoInstant Inc., a salesforce.com company +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 salesforce.com, nor GoInstant, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/buffer-equal-constant-time/README.md b/node_modules/buffer-equal-constant-time/README.md new file mode 100644 index 0000000..4f227f5 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/README.md @@ -0,0 +1,50 @@ +# buffer-equal-constant-time + +Constant-time `Buffer` comparison for node.js. Should work with browserify too. + +[![Build Status](https://travis-ci.org/goinstant/buffer-equal-constant-time.png?branch=master)](https://travis-ci.org/goinstant/buffer-equal-constant-time) + +```sh + npm install buffer-equal-constant-time +``` + +# Usage + +```js + var bufferEq = require('buffer-equal-constant-time'); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (bufferEq(a,b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +If you'd like to install an `.equal()` method onto the node.js `Buffer` and +`SlowBuffer` prototypes: + +```js + require('buffer-equal-constant-time').install(); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (a.equal(b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +To get rid of the installed `.equal()` method, call `.restore()`: + +```js + require('buffer-equal-constant-time').restore(); +``` + +# Legal + +© 2013 GoInstant Inc., a salesforce.com company + +Licensed under the BSD 3-clause license. diff --git a/node_modules/buffer-equal-constant-time/index.js b/node_modules/buffer-equal-constant-time/index.js new file mode 100644 index 0000000..5462c1f --- /dev/null +++ b/node_modules/buffer-equal-constant-time/index.js @@ -0,0 +1,41 @@ +/*jshint node:true */ +'use strict'; +var Buffer = require('buffer').Buffer; // browserify +var SlowBuffer = require('buffer').SlowBuffer; + +module.exports = bufferEq; + +function bufferEq(a, b) { + + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } + + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } + + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} + +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; +}; + +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; +}; diff --git a/node_modules/buffer-equal-constant-time/package.json b/node_modules/buffer-equal-constant-time/package.json new file mode 100644 index 0000000..17c7de2 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/package.json @@ -0,0 +1,21 @@ +{ + "name": "buffer-equal-constant-time", + "version": "1.0.1", + "description": "Constant-time comparison of Buffers", + "main": "index.js", + "scripts": { + "test": "mocha test.js" + }, + "repository": "git@github.com:goinstant/buffer-equal-constant-time.git", + "keywords": [ + "buffer", + "equal", + "constant-time", + "crypto" + ], + "author": "GoInstant Inc., a salesforce.com company", + "license": "BSD-3-Clause", + "devDependencies": { + "mocha": "~1.15.1" + } +} diff --git a/node_modules/buffer-equal-constant-time/test.js b/node_modules/buffer-equal-constant-time/test.js new file mode 100644 index 0000000..0bc972d --- /dev/null +++ b/node_modules/buffer-equal-constant-time/test.js @@ -0,0 +1,42 @@ +/*jshint node:true */ +'use strict'; + +var bufferEq = require('./index'); +var assert = require('assert'); + +describe('buffer-equal-constant-time', function() { + var a = new Buffer('asdfasdf123456'); + var b = new Buffer('asdfasdf123456'); + var c = new Buffer('asdfasdf'); + + describe('bufferEq', function() { + it('says a == b', function() { + assert.strictEqual(bufferEq(a, b), true); + }); + + it('says a != c', function() { + assert.strictEqual(bufferEq(a, c), false); + }); + }); + + describe('install/restore', function() { + before(function() { + bufferEq.install(); + }); + after(function() { + bufferEq.restore(); + }); + + it('installed an .equal method', function() { + var SlowBuffer = require('buffer').SlowBuffer; + assert.ok(Buffer.prototype.equal); + assert.ok(SlowBuffer.prototype.equal); + }); + + it('infected existing Buffers', function() { + assert.strictEqual(a.equal(b), true); + assert.strictEqual(a.equal(c), false); + }); + }); + +}); diff --git a/node_modules/buffer/AUTHORS.md b/node_modules/buffer/AUTHORS.md new file mode 100644 index 0000000..22eb171 --- /dev/null +++ b/node_modules/buffer/AUTHORS.md @@ -0,0 +1,70 @@ +# Authors + +#### Ordered by first contribution. + +- Romain Beauxis (toots@rastageeks.org) +- Tobias Koppers (tobias.koppers@googlemail.com) +- Janus (ysangkok@gmail.com) +- Rainer Dreyer (rdrey1@gmail.com) +- Tõnis Tiigi (tonistiigi@gmail.com) +- James Halliday (mail@substack.net) +- Michael Williamson (mike@zwobble.org) +- elliottcable (github@elliottcable.name) +- rafael (rvalle@livelens.net) +- Andrew Kelley (superjoe30@gmail.com) +- Andreas Madsen (amwebdk@gmail.com) +- Mike Brevoort (mike.brevoort@pearson.com) +- Brian White (mscdex@mscdex.net) +- Feross Aboukhadijeh (feross@feross.org) +- Ruben Verborgh (ruben@verborgh.org) +- eliang (eliang.cs@gmail.com) +- Jesse Tane (jesse.tane@gmail.com) +- Alfonso Boza (alfonso@cloud.com) +- Mathias Buus (mathiasbuus@gmail.com) +- Devon Govett (devongovett@gmail.com) +- Daniel Cousens (github@dcousens.com) +- Joseph Dykstra (josephdykstra@gmail.com) +- Parsha Pourkhomami (parshap+git@gmail.com) +- Damjan Košir (damjan.kosir@gmail.com) +- daverayment (dave.rayment@gmail.com) +- kawanet (u-suke@kawa.net) +- Linus Unnebäck (linus@folkdatorn.se) +- Nolan Lawson (nolan.lawson@gmail.com) +- Calvin Metcalf (calvin.metcalf@gmail.com) +- Koki Takahashi (hakatasiloving@gmail.com) +- Guy Bedford (guybedford@gmail.com) +- Jan Schär (jscissr@gmail.com) +- RaulTsc (tomescu.raul@gmail.com) +- Matthieu Monsch (monsch@alum.mit.edu) +- Dan Ehrenberg (littledan@chromium.org) +- Kirill Fomichev (fanatid@ya.ru) +- Yusuke Kawasaki (u-suke@kawa.net) +- DC (dcposch@dcpos.ch) +- John-David Dalton (john.david.dalton@gmail.com) +- adventure-yunfei (adventure030@gmail.com) +- Emil Bay (github@tixz.dk) +- Sam Sudar (sudar.sam@gmail.com) +- Volker Mische (volker.mische@gmail.com) +- David Walton (support@geekstocks.com) +- Сковорода Никита Андреевич (chalkerx@gmail.com) +- greenkeeper[bot] (greenkeeper[bot]@users.noreply.github.com) +- ukstv (sergey.ukustov@machinomy.com) +- Renée Kooi (renee@kooi.me) +- ranbochen (ranbochen@qq.com) +- Vladimir Borovik (bobahbdb@gmail.com) +- greenkeeper[bot] (23040076+greenkeeper[bot]@users.noreply.github.com) +- kumavis (aaron@kumavis.me) +- Sergey Ukustov (sergey.ukustov@machinomy.com) +- Fei Liu (liu.feiwood@gmail.com) +- Blaine Bublitz (blaine.bublitz@gmail.com) +- clement (clement@seald.io) +- Koushik Dutta (koushd@gmail.com) +- Jordan Harband (ljharb@gmail.com) +- Niklas Mischkulnig (mischnic@users.noreply.github.com) +- Nikolai Vavilov (vvnicholas@gmail.com) +- Fedor Nezhivoi (gyzerok@users.noreply.github.com) +- Peter Newman (peternewman@users.noreply.github.com) +- mathmakgakpak (44949126+mathmakgakpak@users.noreply.github.com) +- jkkang (jkkang@smartauth.kr) + +#### Generated by bin/update-authors.sh. diff --git a/node_modules/buffer/LICENSE b/node_modules/buffer/LICENSE new file mode 100644 index 0000000..d6bf75d --- /dev/null +++ b/node_modules/buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh, and other contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/buffer/README.md b/node_modules/buffer/README.md new file mode 100644 index 0000000..9a23d7c --- /dev/null +++ b/node_modules/buffer/README.md @@ -0,0 +1,410 @@ +# buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/buffer/master.svg +[travis-url]: https://travis-ci.org/feross/buffer +[npm-image]: https://img.shields.io/npm/v/buffer.svg +[npm-url]: https://npmjs.org/package/buffer +[downloads-image]: https://img.shields.io/npm/dm/buffer.svg +[downloads-url]: https://npmjs.org/package/buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### The buffer module from [node.js](https://nodejs.org/), for the browser. + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg +[saucelabs-url]: https://saucelabs.com/u/buffer + +With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. + +The goal is to provide an API that is 100% identical to +[node's Buffer API](https://nodejs.org/api/buffer.html). Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +## features + +- Manipulate binary data like a boss, in all browsers! +- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) +- Extremely small bundle size (**6.75KB minified + gzipped**, 51.9KB with comments) +- Excellent browser support (Chrome, Firefox, Edge, Safari 9+, IE 11, iOS 9+, Android, etc.) +- Preserves Node API exactly, with one minor difference (see below) +- Square-bracket `buf[4]` notation works! +- Does not modify any browser prototypes or put anything on `window` +- Comprehensive test suite (including all buffer tests from node.js core) + +## install + +To use this module directly (without browserify), install it: + +```bash +npm install buffer +``` + +This module was previously called **native-buffer-browserify**, but please use **buffer** +from now on. + +If you do not use a bundler, you can use the [standalone script](https://bundle.run/buffer). + +## usage + +The module's API is identical to node's `Buffer` API. Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +As mentioned above, `require('buffer')` or use the `Buffer` global with +[browserify](http://browserify.org) and this module will automatically be included +in your bundle. Almost any npm module will work in the browser, even if it assumes that +the node `Buffer` API will be available. + +To depend on this module explicitly (without browserify), require it like this: + +```js +var Buffer = require('buffer/').Buffer // note: the trailing slash is important! +``` + +To require this module explicitly, use `require('buffer/')` which tells the node.js module +lookup algorithm (also used by browserify) to use the **npm module** named `buffer` +instead of the **node.js core** module named `buffer`! + + +## how does it work? + +The Buffer constructor returns instances of `Uint8Array` that have their prototype +changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, +so the returned instances will have all the node `Buffer` methods and the +`Uint8Array` methods. Square bracket notation works as expected -- it returns a +single octet. + +The `Uint8Array` prototype remains unmodified. + + +## tracking the latest node api + +This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer +API is considered **stable** in the +[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), +so it is unlikely that there will ever be breaking changes. +Nonetheless, when/if the Buffer API changes in node, this module's API will change +accordingly. + +## related packages + +- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - Reverse a buffer +- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - Bitwise xor a buffer +- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package + +## conversion packages + +### convert typed array to buffer + +Use [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) to convert any kind of typed array to a `Buffer`. Does not perform a copy, so it's super fast. + +### convert buffer to typed array + +`Buffer` is a subclass of `Uint8Array` (which is a typed array). So there is no need to explicitly convert to typed array. Just use the buffer as a `Uint8Array`. + +### convert blob to buffer + +Use [`blob-to-buffer`](https://www.npmjs.com/package/blob-to-buffer) to convert a `Blob` to a `Buffer`. + +### convert buffer to blob + +To convert a `Buffer` to a `Blob`, use the `Blob` constructor: + +```js +var blob = new Blob([ buffer ]) +``` + +Optionally, specify a mimetype: + +```js +var blob = new Blob([ buffer ], { type: 'text/html' }) +``` + +### convert arraybuffer to buffer + +To convert an `ArrayBuffer` to a `Buffer`, use the `Buffer.from` function. Does not perform a copy, so it's super fast. + +```js +var buffer = Buffer.from(arrayBuffer) +``` + +### convert buffer to arraybuffer + +To convert a `Buffer` to an `ArrayBuffer`, use the `.buffer` property (which is present on all `Uint8Array` objects): + +```js +var arrayBuffer = buffer.buffer.slice( + buffer.byteOffset, buffer.byteOffset + buffer.byteLength +) +``` + +Alternatively, use the [`to-arraybuffer`](https://www.npmjs.com/package/to-arraybuffer) module. + +## performance + +See perf tests in `/perf`. + +`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a +sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will +always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, +which is included to compare against. + +NOTE: Performance has improved since these benchmarks were taken. PR welcome to update the README. + +### Chrome 38 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | +| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | +| | | | | +| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | +| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | +| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | +| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | +| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | +| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | +| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | +| | | | | +| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | +| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | +| | | | | +| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | +| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | +| | | | | +| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | +| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | +| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | + + +### Firefox 33 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | +| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | +| | | | | +| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | +| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | +| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | +| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | +| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | +| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | +| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | +| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | +| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | +| | | | | +| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | +| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | +| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | + +### Safari 8 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | +| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | +| | | | | +| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | +| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | +| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | +| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | +| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | +| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | +| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | +| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | +| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | +| | | | | +| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | +| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | +| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | + + +### Node 0.11.14 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | +| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | +| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | +| | | | | +| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | +| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | +| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | +| | | | | +| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | +| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | +| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | +| | | | | +| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | +| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | +| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | +| | | | | +| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | +| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | +| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | +| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | +| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | +| | | | | +| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | +| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | +| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | +| | | | | +| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | +| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | +| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | +| | | | | +| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | +| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | +| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | +| | | | | +| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | +| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | +| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | +| | | | | +| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | +| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | +| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | + +### iojs 1.8.1 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | +| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | +| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | +| | | | | +| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | +| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | +| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | +| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | +| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | +| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | +| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | +| | | | | +| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | +| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | +| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | +| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | +| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | +| | | | | +| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | +| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | +| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | +| | | | | +| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | +| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | +| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | +| | | | | +| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | +| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | +| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | +| | | | | +| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | +| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | +| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | +| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | +| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | +| | | | | + +## Testing the project + +First, install the project: + + npm install + +Then, to run tests in Node.js, run: + + npm run test-node + +To test locally in a browser, you can run: + + npm run test-browser-es5-local # For ES5 browsers that don't support ES6 + npm run test-browser-es6-local # For ES6 compliant browsers + +This will print out a URL that you can then open in a browser to run the tests, using [airtap](https://www.npmjs.com/package/airtap). + +To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: + + npm test + +This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `bin/airtap-es5.yml` and `bin/airtap-es6.yml` files. + +## JavaScript Standard Style + +This module uses [JavaScript Standard Style](https://github.com/feross/standard). + +[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +To test that the code conforms to the style, `npm install` and run: + + ./node_modules/.bin/standard + +## credit + +This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). + +## Security Policies and Procedures + +The `buffer` team and community take all security bugs in `buffer` seriously. Please see our [security policies and procedures](https://github.com/feross/security) document to learn how to report issues. + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. diff --git a/node_modules/buffer/index.d.ts b/node_modules/buffer/index.d.ts new file mode 100644 index 0000000..5d1a804 --- /dev/null +++ b/node_modules/buffer/index.d.ts @@ -0,0 +1,186 @@ +export class Buffer extends Uint8Array { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + reverse(): this; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer | Uint8Array): 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'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initializing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; +} diff --git a/node_modules/buffer/index.js b/node_modules/buffer/index.js new file mode 100644 index 0000000..609cf31 --- /dev/null +++ b/node_modules/buffer/index.js @@ -0,0 +1,1817 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + var proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer.from(buf).copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (var i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +var hexSliceLookupTable = (function () { + var alphabet = '0123456789abcdef' + var table = new Array(256) + for (var i = 0; i < 16; ++i) { + var i16 = i * 16 + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() diff --git a/node_modules/buffer/package.json b/node_modules/buffer/package.json new file mode 100644 index 0000000..3b1b498 --- /dev/null +++ b/node_modules/buffer/package.json @@ -0,0 +1,96 @@ +{ + "name": "buffer", + "description": "Node.js Buffer API, for the browser", + "version": "5.7.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/buffer/issues" + }, + "contributors": [ + "Romain Beauxis ", + "James Halliday " + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + }, + "devDependencies": { + "airtap": "^3.0.0", + "benchmark": "^2.1.4", + "browserify": "^17.0.0", + "concat-stream": "^2.0.0", + "hyperquest": "^2.1.3", + "is-buffer": "^2.0.4", + "is-nan": "^1.3.0", + "split": "^1.0.1", + "standard": "*", + "tape": "^5.0.1", + "through2": "^4.0.2", + "uglify-js": "^3.11.3" + }, + "homepage": "https://github.com/feross/buffer", + "jspm": { + "map": { + "./index.js": { + "node": "@node/buffer" + } + } + }, + "keywords": [ + "arraybuffer", + "browser", + "browserify", + "buffer", + "compatible", + "dataview", + "uint8array" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/buffer.git" + }, + "scripts": { + "perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html", + "perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js", + "size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c", + "test": "standard && node ./bin/test.js", + "test-browser-es5": "airtap -- test/*.js", + "test-browser-es5-local": "airtap --local -- test/*.js", + "test-browser-es6": "airtap -- test/*.js test/node/*.js", + "test-browser-es6-local": "airtap --local -- test/*.js test/node/*.js", + "test-node": "tape test/*.js test/node/*.js", + "update-authors": "./bin/update-authors.sh" + }, + "standard": { + "ignore": [ + "test/node/**/*.js", + "test/common.js", + "test/_polyfill.js", + "perf/**/*.js" + ], + "globals": [ + "SharedArrayBuffer" + ] + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/bytes/History.md b/node_modules/bytes/History.md new file mode 100644 index 0000000..cf6a5bb --- /dev/null +++ b/node_modules/bytes/History.md @@ -0,0 +1,87 @@ +3.1.0 / 2019-01-22 +================== + + * Add petabyte (`pb`) support + +3.0.0 / 2017-08-31 +================== + + * Change "kB" to "KB" in format output + * Remove support for Node.js 0.6 + * Remove support for ComponentJS + +2.5.0 / 2017-03-24 +================== + + * Add option "unit" + +2.4.0 / 2016-06-01 +================== + + * Add option "unitSeparator" + +2.3.0 / 2016-02-15 +================== + + * Drop partial bytes on all parsed units + * Fix non-finite numbers to `.format` to return `null` + * Fix parsing byte string that looks like hex + * perf: hoist regular expressions + +2.2.0 / 2015-11-13 +================== + + * add option "decimalPlaces" + * add option "fixedDecimals" + +2.1.0 / 2015-05-21 +================== + + * add `.format` export + * add `.parse` export + +2.0.2 / 2015-05-20 +================== + + * remove map recreation + * remove unnecessary object construction + +2.0.1 / 2015-05-07 +================== + + * fix browserify require + * remove node.extend dependency + +2.0.0 / 2015-04-12 +================== + + * add option "case" + * add option "thousandsSeparator" + * return "null" on invalid parse input + * support proper round-trip: bytes(bytes(num)) === num + * units no longer case sensitive when parsing + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/node_modules/bytes/LICENSE b/node_modules/bytes/LICENSE new file mode 100644 index 0000000..63e95a9 --- /dev/null +++ b/node_modules/bytes/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015 Jed Watson + +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/bytes/Readme.md b/node_modules/bytes/Readme.md new file mode 100644 index 0000000..6ad1ec6 --- /dev/null +++ b/node_modules/bytes/Readme.md @@ -0,0 +1,126 @@ +# Bytes utility + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install bytes +``` + +## Usage + +```js +var bytes = require('bytes'); +``` + +#### bytes.format(number value, [options]): string|null + +Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is + rounded. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number` | Value in bytes | +| options | `Object` | Conversion options | + +**Options** + +| Property | Type | Description | +|-------------------|--------|-----------------------------------------------------------------------------------------| +| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | +| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | +| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `.`... Default value to `''`. | +| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). | +| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`null` | Return null upon error. String value otherwise. | + +**Example** + +```js +bytes(1024); +// output: '1KB' + +bytes(1000); +// output: '1000B' + +bytes(1000, {thousandsSeparator: ' '}); +// output: '1 000B' + +bytes(1024 * 1.7, {decimalPlaces: 0}); +// output: '2KB' + +bytes(1024, {unitSeparator: ' '}); +// output: '1 KB' + +``` + +#### bytes.parse(string|number value): number|null + +Parse the string value into an integer in bytes. If no unit is given, or `value` +is a number, it is assumed the value is in bytes. + +Supported units and abbreviations are as follows and are case-insensitive: + + * `b` for bytes + * `kb` for kilobytes + * `mb` for megabytes + * `gb` for gigabytes + * `tb` for terabytes + * `pb` for petabytes + +The units are in powers of two, not ten. This means 1kb = 1024b according to this parser. + +**Arguments** + +| Name | Type | Description | +|---------------|--------|--------------------| +| value | `string`|`number` | String to parse, or number in bytes. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | + +**Example** + +```js +bytes('1KB'); +// output: 1024 + +bytes('1024'); +// output: 1024 + +bytes(1024); +// output: 1KB +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/visionmedia/bytes.js/master +[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master +[downloads-image]: https://badgen.net/npm/dm/bytes +[downloads-url]: https://npmjs.org/package/bytes +[npm-image]: https://badgen.net/npm/node/bytes +[npm-url]: https://npmjs.org/package/bytes +[travis-image]: https://badgen.net/travis/visionmedia/bytes.js/master +[travis-url]: https://travis-ci.org/visionmedia/bytes.js diff --git a/node_modules/bytes/index.js b/node_modules/bytes/index.js new file mode 100644 index 0000000..4975bfb --- /dev/null +++ b/node_modules/bytes/index.js @@ -0,0 +1,162 @@ +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; + +/** + * Module variables. + * @private + */ + +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), +}; + +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; + +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ + +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } + + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; + + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.pb) { + unit = 'PB'; + } else if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; + } + } + + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } + + if (thousandsSeparator) { + str = str.replace(formatThousandsRegExp, thousandsSeparator); + } + + return str + unitSeparator + unit; +} + +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ + +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } + + if (typeof val !== 'string') { + return null; + } + + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; + + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + return Math.floor(map[unit] * floatValue); +} diff --git a/node_modules/bytes/package.json b/node_modules/bytes/package.json new file mode 100644 index 0000000..72ee63d --- /dev/null +++ b/node_modules/bytes/package.json @@ -0,0 +1,41 @@ +{ + "name": "bytes", + "description": "Utility to parse a string bytes to bytes and vice-versa", + "version": "3.1.0", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Jed Watson ", + "Théo FIDRY " + ], + "license": "MIT", + "keywords": [ + "byte", + "bytes", + "utility", + "parse", + "parser", + "convert", + "converter" + ], + "repository": "visionmedia/bytes.js", + "devDependencies": { + "eslint": "5.12.1", + "mocha": "5.2.0", + "nyc": "13.1.0" + }, + "files": [ + "History.md", + "LICENSE", + "Readme.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --check-leaks --reporter spec", + "test-ci": "nyc --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/child_process/README.md b/node_modules/child_process/README.md new file mode 100644 index 0000000..5e9a74c --- /dev/null +++ b/node_modules/child_process/README.md @@ -0,0 +1,9 @@ +# Security holding package + +This package name is not currently in use, but was formerly occupied +by another package. To avoid malicious use, npm is hanging on to the +package name, but loosely, and we'll probably give it to you if you +want it. + +You may adopt this package by contacting support@npmjs.com and +requesting the name. diff --git a/node_modules/child_process/package.json b/node_modules/child_process/package.json new file mode 100644 index 0000000..50ba9be --- /dev/null +++ b/node_modules/child_process/package.json @@ -0,0 +1,20 @@ +{ + "name": "child_process", + "version": "1.0.2", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/npm/security-holder.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/npm/security-holder/issues" + }, + "homepage": "https://github.com/npm/security-holder#readme" +} diff --git a/node_modules/chownr/LICENSE b/node_modules/chownr/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/chownr/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/chownr/README.md b/node_modules/chownr/README.md new file mode 100644 index 0000000..70e9a54 --- /dev/null +++ b/node_modules/chownr/README.md @@ -0,0 +1,3 @@ +Like `chown -R`. + +Takes the same arguments as `fs.chown()` diff --git a/node_modules/chownr/chownr.js b/node_modules/chownr/chownr.js new file mode 100644 index 0000000..0d40932 --- /dev/null +++ b/node_modules/chownr/chownr.js @@ -0,0 +1,167 @@ +'use strict' +const fs = require('fs') +const path = require('path') + +/* istanbul ignore next */ +const LCHOWN = fs.lchown ? 'lchown' : 'chown' +/* istanbul ignore next */ +const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' + +/* istanbul ignore next */ +const needEISDIRHandled = fs.lchown && + !process.version.match(/v1[1-9]+\./) && + !process.version.match(/v10\.[6-9]/) + +const lchownSync = (path, uid, gid) => { + try { + return fs[LCHOWNSYNC](path, uid, gid) + } catch (er) { + if (er.code !== 'ENOENT') + throw er + } +} + +/* istanbul ignore next */ +const chownSync = (path, uid, gid) => { + try { + return fs.chownSync(path, uid, gid) + } catch (er) { + if (er.code !== 'ENOENT') + throw er + } +} + +/* istanbul ignore next */ +const handleEISDIR = + needEISDIRHandled ? (path, uid, gid, cb) => er => { + // Node prior to v10 had a very questionable implementation of + // fs.lchown, which would always try to call fs.open on a directory + // Fall back to fs.chown in those cases. + if (!er || er.code !== 'EISDIR') + cb(er) + else + fs.chown(path, uid, gid, cb) + } + : (_, __, ___, cb) => cb + +/* istanbul ignore next */ +const handleEISDirSync = + needEISDIRHandled ? (path, uid, gid) => { + try { + return lchownSync(path, uid, gid) + } catch (er) { + if (er.code !== 'EISDIR') + throw er + chownSync(path, uid, gid) + } + } + : (path, uid, gid) => lchownSync(path, uid, gid) + +// fs.readdir could only accept an options object as of node v6 +const nodeVersion = process.version +let readdir = (path, options, cb) => fs.readdir(path, options, cb) +let readdirSync = (path, options) => fs.readdirSync(path, options) +/* istanbul ignore next */ +if (/^v4\./.test(nodeVersion)) + readdir = (path, options, cb) => fs.readdir(path, cb) + +const chown = (cpath, uid, gid, cb) => { + fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { + // Skip ENOENT error + cb(er && er.code !== 'ENOENT' ? er : null) + })) +} + +const chownrKid = (p, child, uid, gid, cb) => { + if (typeof child === 'string') + return fs.lstat(path.resolve(p, child), (er, stats) => { + // Skip ENOENT error + if (er) + return cb(er.code !== 'ENOENT' ? er : null) + stats.name = child + chownrKid(p, stats, uid, gid, cb) + }) + + if (child.isDirectory()) { + chownr(path.resolve(p, child.name), uid, gid, er => { + if (er) + return cb(er) + const cpath = path.resolve(p, child.name) + chown(cpath, uid, gid, cb) + }) + } else { + const cpath = path.resolve(p, child.name) + chown(cpath, uid, gid, cb) + } +} + + +const chownr = (p, uid, gid, cb) => { + readdir(p, { withFileTypes: true }, (er, children) => { + // any error other than ENOTDIR or ENOTSUP means it's not readable, + // or doesn't exist. give up. + if (er) { + if (er.code === 'ENOENT') + return cb() + else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') + return cb(er) + } + if (er || !children.length) + return chown(p, uid, gid, cb) + + let len = children.length + let errState = null + const then = er => { + if (errState) + return + if (er) + return cb(errState = er) + if (-- len === 0) + return chown(p, uid, gid, cb) + } + + children.forEach(child => chownrKid(p, child, uid, gid, then)) + }) +} + +const chownrKidSync = (p, child, uid, gid) => { + if (typeof child === 'string') { + try { + const stats = fs.lstatSync(path.resolve(p, child)) + stats.name = child + child = stats + } catch (er) { + if (er.code === 'ENOENT') + return + else + throw er + } + } + + if (child.isDirectory()) + chownrSync(path.resolve(p, child.name), uid, gid) + + handleEISDirSync(path.resolve(p, child.name), uid, gid) +} + +const chownrSync = (p, uid, gid) => { + let children + try { + children = readdirSync(p, { withFileTypes: true }) + } catch (er) { + if (er.code === 'ENOENT') + return + else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') + return handleEISDirSync(p, uid, gid) + else + throw er + } + + if (children && children.length) + children.forEach(child => chownrKidSync(p, child, uid, gid)) + + return handleEISDirSync(p, uid, gid) +} + +module.exports = chownr +chownr.sync = chownrSync diff --git a/node_modules/chownr/package.json b/node_modules/chownr/package.json new file mode 100644 index 0000000..5b0214c --- /dev/null +++ b/node_modules/chownr/package.json @@ -0,0 +1,32 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "name": "chownr", + "description": "like `chown -R`", + "version": "2.0.0", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/chownr.git" + }, + "main": "chownr.js", + "files": [ + "chownr.js" + ], + "devDependencies": { + "mkdirp": "0.3", + "rimraf": "^2.7.1", + "tap": "^14.10.6" + }, + "tap": { + "check-coverage": true + }, + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags" + }, + "license": "ISC", + "engines": { + "node": ">=10" + } +} diff --git a/node_modules/color-support/LICENSE b/node_modules/color-support/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/color-support/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/color-support/README.md b/node_modules/color-support/README.md new file mode 100644 index 0000000..f89aa17 --- /dev/null +++ b/node_modules/color-support/README.md @@ -0,0 +1,129 @@ +# color-support + +A module which will endeavor to guess your terminal's level of color +support. + +[![Build Status](https://travis-ci.org/isaacs/color-support.svg?branch=master)](https://travis-ci.org/isaacs/color-support) [![Coverage Status](https://coveralls.io/repos/github/isaacs/color-support/badge.svg?branch=master)](https://coveralls.io/github/isaacs/color-support?branch=master) + +This is similar to `supports-color`, but it does not read +`process.argv`. + +1. If not in a node environment, not supported. + +2. If stdout is not a TTY, not supported, unless the `ignoreTTY` + option is set. + +3. If the `TERM` environ is `dumb`, not supported, unless the + `ignoreDumb` option is set. + +4. If on Windows, then support 16 colors. + +5. If using Tmux, then support 256 colors. + +7. Handle continuous-integration servers. If `CI` or + `TEAMCITY_VERSION` are set in the environment, and `TRAVIS` is not + set, then color is not supported, unless `ignoreCI` option is set. + +6. Guess based on the `TERM_PROGRAM` environ. These terminals support + 16m colors: + + - `iTerm.app` version 3.x supports 16m colors, below support 256 + - `MacTerm` supports 16m colors + - `Apple_Terminal` supports 256 colors + - Have more things that belong on this list? Send a PR! + +8. Make a guess based on the `TERM` environment variable. Any + `xterm-256color` will get 256 colors. Any screen, xterm, vt100, + color, ansi, cygwin, or linux `TERM` will get 16 colors. + +9. If `COLORTERM` environment variable is set, then support 16 colors. + +10. At this point, we assume that color is not supported. + +## USAGE + +```javascript +var testColorSupport = require('color-support') +var colorSupport = testColorSupport(/* options object */) + +if (!colorSupport) { + console.log('color is not supported') +} else if (colorSupport.has16m) { + console.log('\x1b[38;2;102;194;255m16m colors\x1b[0m') +} else if (colorSupport.has256) { + console.log('\x1b[38;5;119m256 colors\x1b[0m') +} else if (colorSupport.hasBasic) { + console.log('\x1b[31mbasic colors\x1b[0m') +} else { + console.log('this is impossible, but colors are not supported') +} +``` + +If you don't have any options to set, you can also just look at the +flags which will all be set on the test function itself. (Of course, +this doesn't return a falsey value when colors aren't supported, and +doesn't allow you to set options.) + +```javascript +var colorSupport = require('color-support') + +if (colorSupport.has16m) { + console.log('\x1b[38;2;102;194;255m16m colors\x1b[0m') +} else if (colorSupport.has256) { + console.log('\x1b[38;5;119m256 colors\x1b[0m') +} else if (colorSupport.hasBasic) { + console.log('\x1b[31mbasic colors\x1b[0m') +} else { + console.log('colors are not supported') +} +``` + +## Options + +You can pass in the following options. + +* ignoreTTY - default false. Ignore the `isTTY` check. +* ignoreDumb - default false. Ignore `TERM=dumb` environ check. +* ignoreCI - default false. Ignore `CI` environ check. +* env - Object for environment vars. Defaults to `process.env`. +* stream - Stream for `isTTY` check. Defaults to `process.stdout`. +* term - String for `TERM` checking. Defaults to `env.TERM`. +* alwaysReturn - default false. Return an object when colors aren't + supported (instead of returning `false`). +* level - A number from 0 to 3. This will return a result for the + specified level. This is useful if you want to be able to set the + color support level explicitly as a number in an environment + variable or config, but then use the object flags in your program. + Except for `alwaysReturn` to return an object for level 0, all other + options are ignored, since no checking is done if a level is + explicitly set. + +## Return Value + +If no color support is available, then `false` is returned by default, +unless the `alwaysReturn` flag is set to `true`. This is so that the +simple question of "can I use colors or not" can treat any truthy +return as "yes". + +Otherwise, the return object has the following fields: + +* `level` - A number from 0 to 3 + * `0` - No color support + * `1` - Basic (16) color support + * `2` - 256 color support + * `3` - 16 million (true) color support +* `hasBasic` - Boolean +* `has256` - Boolean +* `has16m` - Boolean + +## CLI + +You can run the `color-support` bin from the command line which will +just dump the values as this module calculates them in whatever env +it's run. It takes no command line arguments. + +## Credits + +This is a spiritual, if not actual, fork of +[supports-color](http://npm.im/supports-color) by the ever prolific +[Sindre Sorhus](http://npm.im/~sindresorhus). diff --git a/node_modules/color-support/bin.js b/node_modules/color-support/bin.js new file mode 100644 index 0000000..3c0a967 --- /dev/null +++ b/node_modules/color-support/bin.js @@ -0,0 +1,3 @@ +#!/usr/bin/env node +var colorSupport = require('./')({alwaysReturn: true }) +console.log(JSON.stringify(colorSupport, null, 2)) diff --git a/node_modules/color-support/browser.js b/node_modules/color-support/browser.js new file mode 100644 index 0000000..ab5c663 --- /dev/null +++ b/node_modules/color-support/browser.js @@ -0,0 +1,14 @@ +module.exports = colorSupport({ alwaysReturn: true }, colorSupport) + +function colorSupport(options, obj) { + obj = obj || {} + options = options || {} + obj.level = 0 + obj.hasBasic = false + obj.has256 = false + obj.has16m = false + if (!options.alwaysReturn) { + return false + } + return obj +} diff --git a/node_modules/color-support/index.js b/node_modules/color-support/index.js new file mode 100644 index 0000000..6b6f3b2 --- /dev/null +++ b/node_modules/color-support/index.js @@ -0,0 +1,134 @@ +// call it on itself so we can test the export val for basic stuff +module.exports = colorSupport({ alwaysReturn: true }, colorSupport) + +function hasNone (obj, options) { + obj.level = 0 + obj.hasBasic = false + obj.has256 = false + obj.has16m = false + if (!options.alwaysReturn) { + return false + } + return obj +} + +function hasBasic (obj) { + obj.hasBasic = true + obj.has256 = false + obj.has16m = false + obj.level = 1 + return obj +} + +function has256 (obj) { + obj.hasBasic = true + obj.has256 = true + obj.has16m = false + obj.level = 2 + return obj +} + +function has16m (obj) { + obj.hasBasic = true + obj.has256 = true + obj.has16m = true + obj.level = 3 + return obj +} + +function colorSupport (options, obj) { + options = options || {} + + obj = obj || {} + + // if just requesting a specific level, then return that. + if (typeof options.level === 'number') { + switch (options.level) { + case 0: + return hasNone(obj, options) + case 1: + return hasBasic(obj) + case 2: + return has256(obj) + case 3: + return has16m(obj) + } + } + + obj.level = 0 + obj.hasBasic = false + obj.has256 = false + obj.has16m = false + + if (typeof process === 'undefined' || + !process || + !process.stdout || + !process.env || + !process.platform) { + return hasNone(obj, options) + } + + var env = options.env || process.env + var stream = options.stream || process.stdout + var term = options.term || env.TERM || '' + var platform = options.platform || process.platform + + if (!options.ignoreTTY && !stream.isTTY) { + return hasNone(obj, options) + } + + if (!options.ignoreDumb && term === 'dumb' && !env.COLORTERM) { + return hasNone(obj, options) + } + + if (platform === 'win32') { + return hasBasic(obj) + } + + if (env.TMUX) { + return has256(obj) + } + + if (!options.ignoreCI && (env.CI || env.TEAMCITY_VERSION)) { + if (env.TRAVIS) { + return has256(obj) + } else { + return hasNone(obj, options) + } + } + + // TODO: add more term programs + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + var ver = env.TERM_PROGRAM_VERSION || '0.' + if (/^[0-2]\./.test(ver)) { + return has256(obj) + } else { + return has16m(obj) + } + + case 'HyperTerm': + case 'Hyper': + return has16m(obj) + + case 'MacTerm': + return has16m(obj) + + case 'Apple_Terminal': + return has256(obj) + } + + if (/^xterm-256/.test(term)) { + return has256(obj) + } + + if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(term)) { + return hasBasic(obj) + } + + if (env.COLORTERM) { + return hasBasic(obj) + } + + return hasNone(obj, options) +} diff --git a/node_modules/color-support/package.json b/node_modules/color-support/package.json new file mode 100644 index 0000000..f3e3b77 --- /dev/null +++ b/node_modules/color-support/package.json @@ -0,0 +1,36 @@ +{ + "name": "color-support", + "version": "1.1.3", + "description": "A module which will endeavor to guess your terminal's level of color support.", + "main": "index.js", + "browser": "browser.js", + "bin": "bin.js", + "devDependencies": { + "tap": "^10.3.3" + }, + "scripts": { + "test": "tap test/*.js --100 -J", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/color-support.git" + }, + "keywords": [ + "terminal", + "color", + "support", + "xterm", + "truecolor", + "256" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "files": [ + "browser.js", + "index.js", + "bin.js" + ] +} diff --git a/node_modules/concat-map/.travis.yml b/node_modules/concat-map/.travis.yml new file mode 100644 index 0000000..f1d0f13 --- /dev/null +++ b/node_modules/concat-map/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.4 + - 0.6 diff --git a/node_modules/concat-map/LICENSE b/node_modules/concat-map/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/concat-map/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +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/concat-map/README.markdown b/node_modules/concat-map/README.markdown new file mode 100644 index 0000000..408f70a --- /dev/null +++ b/node_modules/concat-map/README.markdown @@ -0,0 +1,62 @@ +concat-map +========== + +Concatenative mapdashery. + +[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map) + +[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map) + +example +======= + +``` js +var concatMap = require('concat-map'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); +``` + +*** + +``` +[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ] +``` + +methods +======= + +``` js +var concatMap = require('concat-map') +``` + +concatMap(xs, fn) +----------------- + +Return an array of concatenated elements by calling `fn(x, i)` for each element +`x` and each index `i` in the array `xs`. + +When `fn(x, i)` returns an array, its result will be concatenated with the +result array. If `fn(x, i)` returns anything else, that value will be pushed +onto the end of the result array. + +install +======= + +With [npm](http://npmjs.org) do: + +``` +npm install concat-map +``` + +license +======= + +MIT + +notes +===== + +This module was written while sitting high above the ground in a tree. diff --git a/node_modules/concat-map/example/map.js b/node_modules/concat-map/example/map.js new file mode 100644 index 0000000..3365621 --- /dev/null +++ b/node_modules/concat-map/example/map.js @@ -0,0 +1,6 @@ +var concatMap = require('../'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); diff --git a/node_modules/concat-map/index.js b/node_modules/concat-map/index.js new file mode 100644 index 0000000..b29a781 --- /dev/null +++ b/node_modules/concat-map/index.js @@ -0,0 +1,13 @@ +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; diff --git a/node_modules/concat-map/package.json b/node_modules/concat-map/package.json new file mode 100644 index 0000000..d3640e6 --- /dev/null +++ b/node_modules/concat-map/package.json @@ -0,0 +1,43 @@ +{ + "name" : "concat-map", + "description" : "concatenative mapdashery", + "version" : "0.0.1", + "repository" : { + "type" : "git", + "url" : "git://github.com/substack/node-concat-map.git" + }, + "main" : "index.js", + "keywords" : [ + "concat", + "concatMap", + "map", + "functional", + "higher-order" + ], + "directories" : { + "example" : "example", + "test" : "test" + }, + "scripts" : { + "test" : "tape test/*.js" + }, + "devDependencies" : { + "tape" : "~2.4.0" + }, + "license" : "MIT", + "author" : { + "name" : "James Halliday", + "email" : "mail@substack.net", + "url" : "http://substack.net" + }, + "testling" : { + "files" : "test/*.js", + "browsers" : { + "ie" : [ 6, 7, 8, 9 ], + "ff" : [ 3.5, 10, 15.0 ], + "chrome" : [ 10, 22 ], + "safari" : [ 5.1 ], + "opera" : [ 12 ] + } + } +} diff --git a/node_modules/concat-map/test/map.js b/node_modules/concat-map/test/map.js new file mode 100644 index 0000000..fdbd702 --- /dev/null +++ b/node_modules/concat-map/test/map.js @@ -0,0 +1,39 @@ +var concatMap = require('../'); +var test = require('tape'); + +test('empty or not', function (t) { + var xs = [ 1, 2, 3, 4, 5, 6 ]; + var ixes = []; + var ys = concatMap(xs, function (x, ix) { + ixes.push(ix); + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; + }); + t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]); + t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]); + t.end(); +}); + +test('always something', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ]; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('scalars', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : x; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('undefs', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function () {}); + t.same(ys, [ undefined, undefined, undefined, undefined ]); + t.end(); +}); diff --git a/node_modules/console-control-strings/LICENSE b/node_modules/console-control-strings/LICENSE new file mode 100644 index 0000000..e756052 --- /dev/null +++ b/node_modules/console-control-strings/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2014, Rebecca Turner + +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/console-control-strings/README.md b/node_modules/console-control-strings/README.md new file mode 100644 index 0000000..f58cc8d --- /dev/null +++ b/node_modules/console-control-strings/README.md @@ -0,0 +1,145 @@ +# Console Control Strings + +A library of cross-platform tested terminal/console command strings for +doing things like color and cursor positioning. This is a subset of both +ansi and vt100. All control codes included work on both Windows & Unix-like +OSes, except where noted. + +## Usage + +```js +var consoleControl = require('console-control-strings') + +console.log(consoleControl.color('blue','bgRed', 'bold') + 'hi there' + consoleControl.color('reset')) +process.stdout.write(consoleControl.goto(75, 10)) +``` + +## Why Another? + +There are tons of libraries similar to this one. I wanted one that was: + +1. Very clear about compatibility goals. +2. Could emit, for instance, a start color code without an end one. +3. Returned strings w/o writing to streams. +4. Was not weighed down with other unrelated baggage. + +## Functions + +### var code = consoleControl.up(_num = 1_) + +Returns the escape sequence to move _num_ lines up. + +### var code = consoleControl.down(_num = 1_) + +Returns the escape sequence to move _num_ lines down. + +### var code = consoleControl.forward(_num = 1_) + +Returns the escape sequence to move _num_ lines righ. + +### var code = consoleControl.back(_num = 1_) + +Returns the escape sequence to move _num_ lines left. + +### var code = consoleControl.nextLine(_num = 1_) + +Returns the escape sequence to move _num_ lines down and to the beginning of +the line. + +### var code = consoleControl.previousLine(_num = 1_) + +Returns the escape sequence to move _num_ lines up and to the beginning of +the line. + +### var code = consoleControl.eraseData() + +Returns the escape sequence to erase everything from the current cursor +position to the bottom right of the screen. This is line based, so it +erases the remainder of the current line and all following lines. + +### var code = consoleControl.eraseLine() + +Returns the escape sequence to erase to the end of the current line. + +### var code = consoleControl.goto(_x_, _y_) + +Returns the escape sequence to move the cursor to the designated position. +Note that the origin is _1, 1_ not _0, 0_. + +### var code = consoleControl.gotoSOL() + +Returns the escape sequence to move the cursor to the beginning of the +current line. (That is, it returns a carriage return, `\r`.) + +### var code = consoleControl.beep() + +Returns the escape sequence to cause the termianl to beep. (That is, it +returns unicode character `\x0007`, a Control-G.) + +### var code = consoleControl.hideCursor() + +Returns the escape sequence to hide the cursor. + +### var code = consoleControl.showCursor() + +Returns the escape sequence to show the cursor. + +### var code = consoleControl.color(_colors = []_) + +### var code = consoleControl.color(_color1_, _color2_, _…_, _colorn_) + +Returns the escape sequence to set the current terminal display attributes +(mostly colors). Arguments can either be a list of attributes or an array +of attributes. The difference between passing in an array or list of colors +and calling `.color` separately for each one, is that in the former case a +single escape sequence will be produced where as in the latter each change +will have its own distinct escape sequence. Each attribute can be one of: + +* Reset: + * **reset** – Reset all attributes to the terminal default. +* Styles: + * **bold** – Display text as bold. In some terminals this means using a + bold font, in others this means changing the color. In some it means + both. + * **italic** – Display text as italic. This is not available in most Windows terminals. + * **underline** – Underline text. This is not available in most Windows Terminals. + * **inverse** – Invert the foreground and background colors. + * **stopBold** – Do not display text as bold. + * **stopItalic** – Do not display text as italic. + * **stopUnderline** – Do not underline text. + * **stopInverse** – Do not invert foreground and background. +* Colors: + * **white** + * **black** + * **blue** + * **cyan** + * **green** + * **magenta** + * **red** + * **yellow** + * **grey** / **brightBlack** + * **brightRed** + * **brightGreen** + * **brightYellow** + * **brightBlue** + * **brightMagenta** + * **brightCyan** + * **brightWhite** +* Background Colors: + * **bgWhite** + * **bgBlack** + * **bgBlue** + * **bgCyan** + * **bgGreen** + * **bgMagenta** + * **bgRed** + * **bgYellow** + * **bgGrey** / **bgBrightBlack** + * **bgBrightRed** + * **bgBrightGreen** + * **bgBrightYellow** + * **bgBrightBlue** + * **bgBrightMagenta** + * **bgBrightCyan** + * **bgBrightWhite** + diff --git a/node_modules/console-control-strings/README.md~ b/node_modules/console-control-strings/README.md~ new file mode 100644 index 0000000..6eb34e8 --- /dev/null +++ b/node_modules/console-control-strings/README.md~ @@ -0,0 +1,140 @@ +# Console Control Strings + +A library of cross-platform tested terminal/console command strings for +doing things like color and cursor positioning. This is a subset of both +ansi and vt100. All control codes included work on both Windows & Unix-like +OSes, except where noted. + +## Usage + +```js +var consoleControl = require('console-control-strings') + +console.log(consoleControl.color('blue','bgRed', 'bold') + 'hi there' + consoleControl.color('reset')) +process.stdout.write(consoleControl.goto(75, 10)) +``` + +## Why Another? + +There are tons of libraries similar to this one. I wanted one that was: + +1. Very clear about compatibility goals. +2. Could emit, for instance, a start color code without an end one. +3. Returned strings w/o writing to streams. +4. Was not weighed down with other unrelated baggage. + +## Functions + +### var code = consoleControl.up(_num = 1_) + +Returns the escape sequence to move _num_ lines up. + +### var code = consoleControl.down(_num = 1_) + +Returns the escape sequence to move _num_ lines down. + +### var code = consoleControl.forward(_num = 1_) + +Returns the escape sequence to move _num_ lines righ. + +### var code = consoleControl.back(_num = 1_) + +Returns the escape sequence to move _num_ lines left. + +### var code = consoleControl.nextLine(_num = 1_) + +Returns the escape sequence to move _num_ lines down and to the beginning of +the line. + +### var code = consoleControl.previousLine(_num = 1_) + +Returns the escape sequence to move _num_ lines up and to the beginning of +the line. + +### var code = consoleControl.eraseData() + +Returns the escape sequence to erase everything from the current cursor +position to the bottom right of the screen. This is line based, so it +erases the remainder of the current line and all following lines. + +### var code = consoleControl.eraseLine() + +Returns the escape sequence to erase to the end of the current line. + +### var code = consoleControl.goto(_x_, _y_) + +Returns the escape sequence to move the cursor to the designated position. +Note that the origin is _1, 1_ not _0, 0_. + +### var code = consoleControl.gotoSOL() + +Returns the escape sequence to move the cursor to the beginning of the +current line. (That is, it returns a carriage return, `\r`.) + +### var code = consoleControl.hideCursor() + +Returns the escape sequence to hide the cursor. + +### var code = consoleControl.showCursor() + +Returns the escape sequence to show the cursor. + +### var code = consoleControl.color(_colors = []_) + +### var code = consoleControl.color(_color1_, _color2_, _…_, _colorn_) + +Returns the escape sequence to set the current terminal display attributes +(mostly colors). Arguments can either be a list of attributes or an array +of attributes. The difference between passing in an array or list of colors +and calling `.color` separately for each one, is that in the former case a +single escape sequence will be produced where as in the latter each change +will have its own distinct escape sequence. Each attribute can be one of: + +* Reset: + * **reset** – Reset all attributes to the terminal default. +* Styles: + * **bold** – Display text as bold. In some terminals this means using a + bold font, in others this means changing the color. In some it means + both. + * **italic** – Display text as italic. This is not available in most Windows terminals. + * **underline** – Underline text. This is not available in most Windows Terminals. + * **inverse** – Invert the foreground and background colors. + * **stopBold** – Do not display text as bold. + * **stopItalic** – Do not display text as italic. + * **stopUnderline** – Do not underline text. + * **stopInverse** – Do not invert foreground and background. +* Colors: + * **white** + * **black** + * **blue** + * **cyan** + * **green** + * **magenta** + * **red** + * **yellow** + * **grey** / **brightBlack** + * **brightRed** + * **brightGreen** + * **brightYellow** + * **brightBlue** + * **brightMagenta** + * **brightCyan** + * **brightWhite** +* Background Colors: + * **bgWhite** + * **bgBlack** + * **bgBlue** + * **bgCyan** + * **bgGreen** + * **bgMagenta** + * **bgRed** + * **bgYellow** + * **bgGrey** / **bgBrightBlack** + * **bgBrightRed** + * **bgBrightGreen** + * **bgBrightYellow** + * **bgBrightBlue** + * **bgBrightMagenta** + * **bgBrightCyan** + * **bgBrightWhite** + diff --git a/node_modules/console-control-strings/index.js b/node_modules/console-control-strings/index.js new file mode 100644 index 0000000..bf89034 --- /dev/null +++ b/node_modules/console-control-strings/index.js @@ -0,0 +1,125 @@ +'use strict' + +// These tables borrowed from `ansi` + +var prefix = '\x1b[' + +exports.up = function up (num) { + return prefix + (num || '') + 'A' +} + +exports.down = function down (num) { + return prefix + (num || '') + 'B' +} + +exports.forward = function forward (num) { + return prefix + (num || '') + 'C' +} + +exports.back = function back (num) { + return prefix + (num || '') + 'D' +} + +exports.nextLine = function nextLine (num) { + return prefix + (num || '') + 'E' +} + +exports.previousLine = function previousLine (num) { + return prefix + (num || '') + 'F' +} + +exports.horizontalAbsolute = function horizontalAbsolute (num) { + if (num == null) throw new Error('horizontalAboslute requires a column to position to') + return prefix + num + 'G' +} + +exports.eraseData = function eraseData () { + return prefix + 'J' +} + +exports.eraseLine = function eraseLine () { + return prefix + 'K' +} + +exports.goto = function (x, y) { + return prefix + y + ';' + x + 'H' +} + +exports.gotoSOL = function () { + return '\r' +} + +exports.beep = function () { + return '\x07' +} + +exports.hideCursor = function hideCursor () { + return prefix + '?25l' +} + +exports.showCursor = function showCursor () { + return prefix + '?25h' +} + +var colors = { + reset: 0, +// styles + bold: 1, + italic: 3, + underline: 4, + inverse: 7, +// resets + stopBold: 22, + stopItalic: 23, + stopUnderline: 24, + stopInverse: 27, +// colors + white: 37, + black: 30, + blue: 34, + cyan: 36, + green: 32, + magenta: 35, + red: 31, + yellow: 33, + bgWhite: 47, + bgBlack: 40, + bgBlue: 44, + bgCyan: 46, + bgGreen: 42, + bgMagenta: 45, + bgRed: 41, + bgYellow: 43, + + grey: 90, + brightBlack: 90, + brightRed: 91, + brightGreen: 92, + brightYellow: 93, + brightBlue: 94, + brightMagenta: 95, + brightCyan: 96, + brightWhite: 97, + + bgGrey: 100, + bgBrightBlack: 100, + bgBrightRed: 101, + bgBrightGreen: 102, + bgBrightYellow: 103, + bgBrightBlue: 104, + bgBrightMagenta: 105, + bgBrightCyan: 106, + bgBrightWhite: 107 +} + +exports.color = function color (colorWith) { + if (arguments.length !== 1 || !Array.isArray(colorWith)) { + colorWith = Array.prototype.slice.call(arguments) + } + return prefix + colorWith.map(colorNameToCode).join(';') + 'm' +} + +function colorNameToCode (color) { + if (colors[color] != null) return colors[color] + throw new Error('Unknown color or style name: ' + color) +} diff --git a/node_modules/console-control-strings/package.json b/node_modules/console-control-strings/package.json new file mode 100644 index 0000000..eb6c62a --- /dev/null +++ b/node_modules/console-control-strings/package.json @@ -0,0 +1,27 @@ +{ + "name": "console-control-strings", + "version": "1.1.0", + "description": "A library of cross-platform tested terminal/console command strings for doing things like color and cursor positioning. This is a subset of both ansi and vt100. All control codes included work on both Windows & Unix-like OSes, except where noted.", + "main": "index.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "standard && tap test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/iarna/console-control-strings" + }, + "keywords": [], + "author": "Rebecca Turner (http://re-becca.org/)", + "license": "ISC", + "files": [ + "LICENSE", + "index.js" + ], + "devDependencies": { + "standard": "^7.1.2", + "tap": "^5.7.2" + } +} diff --git a/node_modules/content-disposition/HISTORY.md b/node_modules/content-disposition/HISTORY.md new file mode 100644 index 0000000..63a3d08 --- /dev/null +++ b/node_modules/content-disposition/HISTORY.md @@ -0,0 +1,55 @@ +0.5.3 / 2018-12-17 +================== + + * Use `safe-buffer` for improved Buffer API + +0.5.2 / 2016-12-08 +================== + + * Fix `parse` to accept any linear whitespace character + +0.5.1 / 2016-01-17 +================== + + * perf: enable strict mode + +0.5.0 / 2014-10-11 +================== + + * Add `parse` function + +0.4.0 / 2014-09-21 +================== + + * Expand non-Unicode `filename` to the full ISO-8859-1 charset + +0.3.0 / 2014-09-20 +================== + + * Add `fallback` option + * Add `type` option + +0.2.0 / 2014-09-19 +================== + + * Reduce ambiguity of file names with hex escape in buggy browsers + +0.1.2 / 2014-09-19 +================== + + * Fix periodic invalid Unicode filename header + +0.1.1 / 2014-09-19 +================== + + * Fix invalid characters appearing in `filename*` parameter + +0.1.0 / 2014-09-18 +================== + + * Make the `filename` argument optional + +0.0.0 / 2014-09-18 +================== + + * Initial release diff --git a/node_modules/content-disposition/LICENSE b/node_modules/content-disposition/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/node_modules/content-disposition/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/content-disposition/README.md b/node_modules/content-disposition/README.md new file mode 100644 index 0000000..eebef13 --- /dev/null +++ b/node_modules/content-disposition/README.md @@ -0,0 +1,148 @@ +# content-disposition + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create and parse HTTP `Content-Disposition` header + +## Installation + +```sh +$ npm install content-disposition +``` + +## API + + + +```js +var contentDisposition = require('content-disposition') +``` + +### contentDisposition(filename, options) + +Create an attachment `Content-Disposition` header value using the given file name, +if supplied. The `filename` is optional and if no file name is desired, but you +want to specify `options`, set `filename` to `undefined`. + + + +```js +res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) +``` + +**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this +header through a means different from `setHeader` in Node.js, you'll want to specify +the `'binary'` encoding in Node.js. + +#### Options + +`contentDisposition` accepts these properties in the options object. + +##### fallback + +If the `filename` option is outside ISO-8859-1, then the file name is actually +stored in a supplemental field for clients that support Unicode file names and +a ISO-8859-1 version of the file name is automatically generated. + +This specifies the ISO-8859-1 file name to override the automatic generation or +disables the generation all together, defaults to `true`. + + - A string will specify the ISO-8859-1 file name to use in place of automatic + generation. + - `false` will disable including a ISO-8859-1 file name and only include the + Unicode version (unless the file name is already ISO-8859-1). + - `true` will enable automatic generation if the file name is outside ISO-8859-1. + +If the `filename` option is ISO-8859-1 and this option is specified and has a +different value, then the `filename` option is encoded in the extended field +and this set as the fallback field, even though they are both ISO-8859-1. + +##### type + +Specifies the disposition type, defaults to `"attachment"`. This can also be +`"inline"`, or any other value (all values except inline are treated like +`attachment`, but can convey additional information if both parties agree to +it). The type is normalized to lower-case. + +### contentDisposition.parse(string) + + + +```js +var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt') +``` + +Parse a `Content-Disposition` header string. This automatically handles extended +("Unicode") parameters by decoding them and providing them under the standard +parameter name. This will return an object with the following properties (examples +are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): + + - `type`: The disposition type (always lower case). Example: `'attachment'` + + - `parameters`: An object of the parameters in the disposition (name of parameter + always lower case and extended versions replace non-extended versions). Example: + `{filename: "€ rates.txt"}` + +## Examples + +### Send a file for download + +```js +var contentDisposition = require('content-disposition') +var destroy = require('destroy') +var fs = require('fs') +var http = require('http') +var onFinished = require('on-finished') + +var filePath = '/path/to/public/plans.pdf' + +http.createServer(function onRequest (req, res) { + // set headers + res.setHeader('Content-Type', 'application/pdf') + res.setHeader('Content-Disposition', contentDisposition(filePath)) + + // send file + var stream = fs.createReadStream(filePath) + stream.pipe(res) + onFinished(res, function () { + destroy(stream) + }) +}) +``` + +## Testing + +```sh +$ npm test +``` + +## References + +- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] +- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] +- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] +- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] + +[rfc-2616]: https://tools.ietf.org/html/rfc2616 +[rfc-5987]: https://tools.ietf.org/html/rfc5987 +[rfc-6266]: https://tools.ietf.org/html/rfc6266 +[tc-2231]: http://greenbytes.de/tech/tc2231/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-disposition.svg +[npm-url]: https://npmjs.org/package/content-disposition +[node-version-image]: https://img.shields.io/node/v/content-disposition.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg +[travis-url]: https://travis-ci.org/jshttp/content-disposition +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master +[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg +[downloads-url]: https://npmjs.org/package/content-disposition diff --git a/node_modules/content-disposition/index.js b/node_modules/content-disposition/index.js new file mode 100644 index 0000000..3092a4d --- /dev/null +++ b/node_modules/content-disposition/index.js @@ -0,0 +1,458 @@ +/*! + * content-disposition + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = contentDisposition +module.exports.parse = parse + +/** + * Module dependencies. + * @private + */ + +var basename = require('path').basename +var Buffer = require('safe-buffer').Buffer + +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + * @private + */ + +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex + +/** + * RegExp to match percent encoding escape. + * @private + */ + +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g + +/** + * RegExp to match non-latin1 characters. + * @private + */ + +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + * @private + */ + +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex + +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @private + */ + +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp for various RFC 2616 grammar + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = + * @private + */ + +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ + +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + * @private + */ + +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ + +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + * @private + */ + +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex + +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @public + */ + +function contentDisposition (filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @private + */ + +function createparams (filename, fallback) { + if (filename === undefined) { + return + } + + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } + + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } + + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } + + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } + + // restrict to file base name + var name = basename(filename) + + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) + + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name + } + + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } + + return params +} + +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private + */ + +function format (obj) { + var parameters = obj.parameters + var type = obj.type + + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + // start with normalized type + var string = String(type).toLowerCase() + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val + } + } + + return string +} + +/** + * Decode a RFC 6987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @private + */ + +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) + + if (!match) { + throw new TypeError('invalid extended field value') + } + + var charset = match[1].toLowerCase() + var encoded = match[2] + var value + + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) + + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = Buffer.from(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } + + return value +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @private + */ + +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @public + */ + +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + + var match = DISPOSITION_TYPE_REGEXP.exec(string) + + if (!match) { + throw new TypeError('invalid type format') + } + + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index + + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + + params[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @private + */ + +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @private + */ + +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @private + */ + +function ustring (val) { + var str = String(val) + + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + + return 'UTF-8\'\'' + encoded +} + +/** + * Class for parsed Content-Disposition header for v8 optimization + * + * @public + * @param {string} type + * @param {object} parameters + * @constructor + */ + +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} diff --git a/node_modules/content-disposition/package.json b/node_modules/content-disposition/package.json new file mode 100644 index 0000000..814f7f3 --- /dev/null +++ b/node_modules/content-disposition/package.json @@ -0,0 +1,44 @@ +{ + "name": "content-disposition", + "description": "Create and parse Content-Disposition header", + "version": "0.5.3", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "content-disposition", + "http", + "rfc6266", + "res" + ], + "repository": "jshttp/content-disposition", + "dependencies": { + "safe-buffer": "5.1.2" + }, + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "5.10.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.14.0", + "eslint-plugin-markdown": "1.0.0-rc.1", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.0.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "5.2.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/content-type/HISTORY.md b/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..8f5cb70 --- /dev/null +++ b/node_modules/content-type/HISTORY.md @@ -0,0 +1,24 @@ +1.0.4 / 2017-09-11 +================== + + * perf: skip parameter parsing when no parameters + +1.0.3 / 2017-09-10 +================== + + * perf: remove argument reassignment + +1.0.2 / 2016-05-09 +================== + + * perf: enable strict mode + +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/node_modules/content-type/LICENSE b/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +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/content-type/README.md b/node_modules/content-type/README.md new file mode 100644 index 0000000..3ed6741 --- /dev/null +++ b/node_modules/content-type/README.md @@ -0,0 +1,92 @@ +# content-type + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a content type string. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({type: 'image/svg+xml'}) +``` + +Format an object into a content type string. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-type.svg +[npm-url]: https://npmjs.org/package/content-type +[node-version-image]: https://img.shields.io/node/v/content-type.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg +[travis-url]: https://travis-ci.org/jshttp/content-type +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-type +[downloads-image]: https://img.shields.io/npm/dm/content-type.svg +[downloads-url]: https://npmjs.org/package/content-type diff --git a/node_modules/content-type/index.js b/node_modules/content-type/index.js new file mode 100644 index 0000000..6ce03f2 --- /dev/null +++ b/node_modules/content-type/index.js @@ -0,0 +1,222 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } + + string += '; ' + param + '=' + qstring(parameters[param]) + } + } + + return string +} + +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string + + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = header.indexOf(';') + var type = index !== -1 + ? header.substr(0, index).trim() + : header.trim() + + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } + + var obj = new ContentType(type.toLowerCase()) + + // parse parameters + if (index !== -1) { + var key + var match + var value + + PARAM_REGEXP.lastIndex = index + + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + + obj.parameters[key] = value + } + + if (index !== header.length) { + throw new TypeError('invalid parameter format') + } + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + +function getcontenttype (obj) { + var header + + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] + } + + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } + + return header +} + +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } + + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') + } + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/node_modules/content-type/package.json b/node_modules/content-type/package.json new file mode 100644 index 0000000..f2d31d4 --- /dev/null +++ b/node_modules/content-type/package.json @@ -0,0 +1,40 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.4", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": "jshttp/content-type", + "devDependencies": { + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + } +} diff --git a/node_modules/cookie-signature/.npmignore b/node_modules/cookie-signature/.npmignore new file mode 100644 index 0000000..f1250e5 --- /dev/null +++ b/node_modules/cookie-signature/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/node_modules/cookie-signature/History.md b/node_modules/cookie-signature/History.md new file mode 100644 index 0000000..78513cc --- /dev/null +++ b/node_modules/cookie-signature/History.md @@ -0,0 +1,38 @@ +1.0.6 / 2015-02-03 +================== + +* use `npm test` instead of `make test` to run tests +* clearer assertion messages when checking input + + +1.0.5 / 2014-09-05 +================== + +* add license to package.json + +1.0.4 / 2014-06-25 +================== + + * corrected avoidance of timing attacks (thanks @tenbits!) + +1.0.3 / 2014-01-28 +================== + + * [incorrect] fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/cookie-signature/Readme.md b/node_modules/cookie-signature/Readme.md new file mode 100644 index 0000000..2559e84 --- /dev/null +++ b/node_modules/cookie-signature/Readme.md @@ -0,0 +1,42 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +(The MIT License) + +Copyright (c) 2012 LearnBoost <tj@learnboost.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. \ No newline at end of file diff --git a/node_modules/cookie-signature/index.js b/node_modules/cookie-signature/index.js new file mode 100644 index 0000000..b8c9463 --- /dev/null +++ b/node_modules/cookie-signature/index.js @@ -0,0 +1,51 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return sha1(mac) == sha1(val) ? str : false; +}; + +/** + * Private + */ + +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} diff --git a/node_modules/cookie-signature/package.json b/node_modules/cookie-signature/package.json new file mode 100644 index 0000000..29c4498 --- /dev/null +++ b/node_modules/cookie-signature/package.json @@ -0,0 +1,18 @@ +{ + "name": "cookie-signature", + "version": "1.0.6", + "description": "Sign and unsign cookies", + "keywords": ["cookie", "sign", "unsign"], + "author": "TJ Holowaychuk ", + "license": "MIT", + "repository": { "type": "git", "url": "https://github.com/visionmedia/node-cookie-signature.git"}, + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + }, + "main": "index" +} diff --git a/node_modules/cookie/HISTORY.md b/node_modules/cookie/HISTORY.md new file mode 100644 index 0000000..da2bf24 --- /dev/null +++ b/node_modules/cookie/HISTORY.md @@ -0,0 +1,123 @@ +0.4.0 / 2019-05-15 +================== + + * Add `SameSite=None` support + +0.3.1 / 2016-05-26 +================== + + * Fix `sameSite: true` to work with draft-7 clients + - `true` now sends `SameSite=Strict` instead of `SameSite` + +0.3.0 / 2016-05-26 +================== + + * Add `sameSite` option + - Replaces `firstPartyOnly` option, never implemented by browsers + * Improve error message when `encode` is not a function + * Improve error message when `expires` is not a `Date` + +0.2.4 / 2016-05-20 +================== + + * perf: enable strict mode + * perf: use for loop in parse + * perf: use string concatination for serialization + +0.2.3 / 2015-10-25 +================== + + * Fix cookie `Max-Age` to never be a floating point number + +0.2.2 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.2.1 / 2015-09-17 +================== + + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.2.0 / 2015-08-13 +================== + + * Add `firstPartyOnly` option + * Throw better error for invalid argument to parse + * perf: hoist regular expression + +0.1.5 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.1.4 / 2015-09-17 +================== + + * Throw better error for invalid argument to parse + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.1.3 / 2015-05-19 +================== + + * Reduce the scope of try-catch deopt + * Remove argument reassignments + +0.1.2 / 2014-04-16 +================== + + * Remove unnecessary files from npm package + +0.1.1 / 2014-02-23 +================== + + * Fix bad parse when cookie value contained a comma + * Fix support for `maxAge` of `0` + +0.1.0 / 2013-05-01 +================== + + * Add `decode` option + * Add `encode` option + +0.0.6 / 2013-04-08 +================== + + * Ignore cookie parts missing `=` + +0.0.5 / 2012-10-29 +================== + + * Return raw cookie value if value unescape errors + +0.0.4 / 2012-06-21 +================== + + * Use encode/decodeURIComponent for cookie encoding/decoding + - Improve server/client interoperability + +0.0.3 / 2012-06-06 +================== + + * Only escape special characters per the cookie RFC + +0.0.2 / 2012-06-01 +================== + + * Fix `maxAge` option to not throw error + +0.0.1 / 2012-05-28 +================== + + * Add more tests + +0.0.0 / 2012-05-28 +================== + + * Initial release diff --git a/node_modules/cookie/LICENSE b/node_modules/cookie/LICENSE new file mode 100644 index 0000000..058b6b4 --- /dev/null +++ b/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +Copyright (c) 2015 Douglas Christopher Wilson + +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/cookie/README.md b/node_modules/cookie/README.md new file mode 100644 index 0000000..857fb77 --- /dev/null +++ b/node_modules/cookie/README.md @@ -0,0 +1,253 @@ +# cookie + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Basic HTTP cookie parser and serializer for HTTP servers. + +## Installation + +```sh +$ npm install cookie +``` + +## API + +```js +var cookie = require('cookie'); +``` + +### cookie.parse(str, options) + +Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs. +The `str` argument is the string representing a `Cookie` header value and `options` is an +optional object containing additional parsing options. + +```js +var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); +// { foo: 'bar', equation: 'E=mc^2' } +``` + +#### Options + +`cookie.parse` accepts these properties in the options object. + +##### decode + +Specifies a function that will be used to decode a cookie's value. Since the value of a cookie +has a limited character set (and must be a simple string), this function can be used to decode +a previously-encoded cookie value into a JavaScript string or other object. + +The default function is the global `decodeURIComponent`, which will decode any URL-encoded +sequences into their byte representations. + +**note** if an error is thrown from this function, the original, non-decoded cookie value will +be returned as the cookie's value. + +### cookie.serialize(name, value, options) + +Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the +name for the cookie, the `value` argument is the value to set the cookie to, and the `options` +argument is an optional object containing additional serialization options. + +```js +var setCookie = cookie.serialize('foo', 'bar'); +// foo=bar +``` + +#### Options + +`cookie.serialize` accepts these properties in the options object. + +##### domain + +Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no +domain is set, and most clients will consider the cookie to apply to only the current domain. + +##### encode + +Specifies a function that will be used to encode a cookie's value. Since value of a cookie +has a limited character set (and must be a simple string), this function can be used to encode +a value into a string suited for a cookie's value. + +The default function is the global `encodeURIComponent`, which will encode a JavaScript string +into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range. + +##### expires + +Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1]. +By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and +will delete it on a condition like exiting a web browser application. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### httpOnly + +Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy, +the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not allow client-side +JavaScript to see the cookie in `document.cookie`. + +##### maxAge + +Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2]. +The given number will be converted to an integer by rounding down. By default, no maximum age is set. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### path + +Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path +is considered the ["default path"][rfc-6265-5.1.4]. + +##### sameSite + +Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-03-4.1.2.7]. + + - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + - `false` will not set the `SameSite` attribute. + - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. + - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. + - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + +More information about the different enforcement levels can be found in +[the specification][rfc-6265bis-03-4.1.2.7]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### secure + +Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy, +the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to +the server in the future if the browser does not have an HTTPS connection. + +## Example + +The following example uses this module in conjunction with the Node.js core HTTP server +to prompt a user for their name and display it back on future visits. + +```js +var cookie = require('cookie'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var url = require('url'); + +function onRequest(req, res) { + // Parse the query string + var query = url.parse(req.url, true, true).query; + + if (query && query.name) { + // Set a new cookie with the name + res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), { + httpOnly: true, + maxAge: 60 * 60 * 24 * 7 // 1 week + })); + + // Redirect back after setting cookie + res.statusCode = 302; + res.setHeader('Location', req.headers.referer || '/'); + res.end(); + return; + } + + // Parse the cookies on the request + var cookies = cookie.parse(req.headers.cookie || ''); + + // Get the visitor name set in the cookie + var name = cookies.name; + + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + + if (name) { + res.write('

Welcome back, ' + escapeHtml(name) + '!

'); + } else { + res.write('

Hello, new visitor!

'); + } + + res.write('
'); + res.write(' '); + res.end('
'); +} + +http.createServer(onRequest).listen(3000); +``` + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +``` +$ npm run bench + +> cookie@0.3.1 bench cookie +> node benchmark/index.js + + http_parser@2.8.0 + node@6.14.2 + v8@5.1.281.111 + uv@1.16.1 + zlib@1.2.11 + ares@1.10.1-DEV + icu@58.2 + modules@48 + napi@3 + openssl@1.0.2o + +> node benchmark/parse.js + + cookie.parse + + 6 tests completed. + + simple x 1,200,691 ops/sec ±1.12% (189 runs sampled) + decode x 1,012,994 ops/sec ±0.97% (186 runs sampled) + unquote x 1,074,174 ops/sec ±2.43% (186 runs sampled) + duplicates x 438,424 ops/sec ±2.17% (184 runs sampled) + 10 cookies x 147,154 ops/sec ±1.01% (186 runs sampled) + 100 cookies x 14,274 ops/sec ±1.07% (187 runs sampled) +``` + +## References + +- [RFC 6265: HTTP State Management Mechanism][rfc-6265] +- [Same-site Cookies][rfc-6265bis-03-4.1.2.7] + +[rfc-6265bis-03-4.1.2.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7 +[rfc-6265]: https://tools.ietf.org/html/rfc6265 +[rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4 +[rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1 +[rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2 +[rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3 +[rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4 +[rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5 +[rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6 +[rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3 + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master +[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master +[node-version-image]: https://badgen.net/npm/node/cookie +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/cookie +[npm-url]: https://npmjs.org/package/cookie +[npm-version-image]: https://badgen.net/npm/v/cookie +[travis-image]: https://badgen.net/travis/jshttp/cookie/master +[travis-url]: https://travis-ci.org/jshttp/cookie diff --git a/node_modules/cookie/index.js b/node_modules/cookie/index.js new file mode 100644 index 0000000..16f56c0 --- /dev/null +++ b/node_modules/cookie/index.js @@ -0,0 +1,198 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var decode = decodeURIComponent; +var encode = encodeURIComponent; +var pairSplitRegExp = /; */; + +/** + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF + */ + +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ + +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } + + var obj = {} + var opt = options || {}; + var pairs = str.split(pairSplitRegExp); + var dec = opt.decode || decode; + + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var eq_idx = pair.indexOf('='); + + // skip things that don't look like key=value + if (eq_idx < 0) { + continue; + } + + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } + } + + return obj; +} + +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } + + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } + + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + var str = name + '=' + value; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + str += '; Max-Age=' + Math.floor(maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } + + str += '; Domain=' + opt.domain; + } + + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + + str += '; Path=' + opt.path; + } + + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); + } + + str += '; Expires=' + opt.expires.toUTCString(); + } + + if (opt.httpOnly) { + str += '; HttpOnly'; + } + + if (opt.secure) { + str += '; Secure'; + } + + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; + + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + case 'none': + str += '; SameSite=None'; + break; + default: + throw new TypeError('option sameSite is invalid'); + } + } + + return str; +} + +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ + +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} diff --git a/node_modules/cookie/package.json b/node_modules/cookie/package.json new file mode 100644 index 0000000..9bfbc47 --- /dev/null +++ b/node_modules/cookie/package.json @@ -0,0 +1,40 @@ +{ + "name": "cookie", + "description": "HTTP server cookie parsing and serialization", + "version": "0.4.0", + "author": "Roman Shtylman ", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "cookie", + "cookies" + ], + "repository": "jshttp/cookie", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "5.16.0", + "eslint-plugin-markdown": "1.0.0", + "istanbul": "0.4.5", + "mocha": "6.1.4" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/debug/.coveralls.yml b/node_modules/debug/.coveralls.yml new file mode 100644 index 0000000..20a7068 --- /dev/null +++ b/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/debug/.eslintrc b/node_modules/debug/.eslintrc new file mode 100644 index 0000000..8a37ae2 --- /dev/null +++ b/node_modules/debug/.eslintrc @@ -0,0 +1,11 @@ +{ + "env": { + "browser": true, + "node": true + }, + "rules": { + "no-console": 0, + "no-empty": [1, { "allowEmptyCatch": true }] + }, + "extends": "eslint:recommended" +} diff --git a/node_modules/debug/.npmignore b/node_modules/debug/.npmignore new file mode 100644 index 0000000..5f60eec --- /dev/null +++ b/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/node_modules/debug/.travis.yml b/node_modules/debug/.travis.yml new file mode 100644 index 0000000..6c6090c --- /dev/null +++ b/node_modules/debug/.travis.yml @@ -0,0 +1,14 @@ + +language: node_js +node_js: + - "6" + - "5" + - "4" + +install: + - make node_modules + +script: + - make lint + - make test + - make coveralls diff --git a/node_modules/debug/CHANGELOG.md b/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000..eadaa18 --- /dev/null +++ b/node_modules/debug/CHANGELOG.md @@ -0,0 +1,362 @@ + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/debug/LICENSE b/node_modules/debug/LICENSE new file mode 100644 index 0000000..658c933 --- /dev/null +++ b/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +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/debug/Makefile b/node_modules/debug/Makefile new file mode 100644 index 0000000..584da8b --- /dev/null +++ b/node_modules/debug/Makefile @@ -0,0 +1,50 @@ +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# Path +PATH := node_modules/.bin:$(PATH) +SHELL := /bin/bash + +# applications +NODE ?= $(shell which node) +YARN ?= $(shell which yarn) +PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +.FORCE: + +install: node_modules + +node_modules: package.json + @NODE_ENV= $(PKG) install + @touch node_modules + +lint: .FORCE + eslint browser.js debug.js index.js node.js + +test-node: .FORCE + istanbul cover node_modules/mocha/bin/_mocha -- test/**.js + +test-browser: .FORCE + mkdir -p dist + + @$(BROWSERIFY) \ + --standalone debug \ + . > dist/debug.js + + karma start --single-run + rimraf dist + +test: .FORCE + concurrently \ + "make test-node" \ + "make test-browser" + +coveralls: + cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js + +.PHONY: all install clean distclean diff --git a/node_modules/debug/README.md b/node_modules/debug/README.md new file mode 100644 index 0000000..f67be6b --- /dev/null +++ b/node_modules/debug/README.md @@ -0,0 +1,312 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny node.js debugging utility modelled after node core's debugging technique. + +**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +#### Windows note + + On Windows the environment variable is set using the `set` command. + + ```cmd + set DEBUG=*,-not_this + ``` + + Note that PowerShell uses different syntax to set environment variables. + + ```cmd + $env:DEBUG = "*,-not_this" + ``` + +Then, run the program to be debugged as usual. + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". + +## Environment Variables + + When running through Node.js, you can set a few environment variables that will + change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + + __Note:__ The environment variables beginning with `DEBUG_` end up being + converted into an Options object that gets used with `%o`/`%O` formatters. + See the Node.js documentation for + [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) + for the complete list. + +## Formatters + + + Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + +### Custom formatters + + You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + +## Browser support + You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), + or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), + if you don't want to build it yourself. + + Debug's enable state is currently persisted by `localStorage`. + Consider the situation shown below where you have `worker:a` and `worker:b`, + and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +#### Web Inspector Colors + + Colors are also enabled on "Web Inspectors" that understand the `%c` formatting + option. These are WebKit web inspectors, Firefox ([since version + 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) + and the Firebug plugin for Firefox (any version). + + Colored output looks something like: + + ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example _stdout.js_: + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca> + +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/debug/component.json b/node_modules/debug/component.json new file mode 100644 index 0000000..9de2641 --- /dev/null +++ b/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.6.9", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "src/browser.js", + "scripts": [ + "src/browser.js", + "src/debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/node_modules/debug/karma.conf.js b/node_modules/debug/karma.conf.js new file mode 100644 index 0000000..103a82d --- /dev/null +++ b/node_modules/debug/karma.conf.js @@ -0,0 +1,70 @@ +// Karma configuration +// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) + +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'chai', 'sinon'], + + + // list of files / patterns to load in the browser + files: [ + 'dist/debug.js', + 'test/*spec.js' + ], + + + // list of files to exclude + exclude: [ + 'src/node.js' + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: Infinity + }) +} diff --git a/node_modules/debug/node.js b/node_modules/debug/node.js new file mode 100644 index 0000000..7fc36fe --- /dev/null +++ b/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/node_modules/debug/package.json b/node_modules/debug/package.json new file mode 100644 index 0000000..dc787ba --- /dev/null +++ b/node_modules/debug/package.json @@ -0,0 +1,49 @@ +{ + "name": "debug", + "version": "2.6.9", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + }, + "devDependencies": { + "browserify": "9.0.3", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^2.11.15", + "eslint": "^3.12.1", + "istanbul": "^0.4.5", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-sinon": "^1.0.5", + "mocha": "^3.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "sinon": "^1.17.6", + "sinon-chai": "^2.8.0" + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + } +} diff --git a/node_modules/debug/src/browser.js b/node_modules/debug/src/browser.js new file mode 100644 index 0000000..7106924 --- /dev/null +++ b/node_modules/debug/src/browser.js @@ -0,0 +1,185 @@ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} diff --git a/node_modules/debug/src/debug.js b/node_modules/debug/src/debug.js new file mode 100644 index 0000000..6a5e3fc --- /dev/null +++ b/node_modules/debug/src/debug.js @@ -0,0 +1,202 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/node_modules/debug/src/index.js b/node_modules/debug/src/index.js new file mode 100644 index 0000000..e12cf4d --- /dev/null +++ b/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/debug/src/inspector-log.js b/node_modules/debug/src/inspector-log.js new file mode 100644 index 0000000..60ea6c0 --- /dev/null +++ b/node_modules/debug/src/inspector-log.js @@ -0,0 +1,15 @@ +module.exports = inspectorLog; + +// black hole +const nullStream = new (require('stream').Writable)(); +nullStream._write = () => {}; + +/** + * Outputs a `console.log()` to the Node.js Inspector console *only*. + */ +function inspectorLog() { + const stdout = console._stdout; + console._stdout = nullStream; + console.log.apply(console, arguments); + console._stdout = stdout; +} diff --git a/node_modules/debug/src/node.js b/node_modules/debug/src/node.js new file mode 100644 index 0000000..b15109c --- /dev/null +++ b/node_modules/debug/src/node.js @@ -0,0 +1,248 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = require('fs'); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = require('net'); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/node_modules/delegates/.npmignore b/node_modules/delegates/.npmignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/node_modules/delegates/.npmignore @@ -0,0 +1 @@ +node_modules/ diff --git a/node_modules/delegates/History.md b/node_modules/delegates/History.md new file mode 100644 index 0000000..25959ea --- /dev/null +++ b/node_modules/delegates/History.md @@ -0,0 +1,22 @@ + +1.0.0 / 2015-12-14 +================== + + * Merge pull request #12 from kasicka/master + * Add license text + +0.1.0 / 2014-10-17 +================== + + * adds `.fluent()` to api + +0.0.3 / 2014-01-13 +================== + + * fix receiver for .method() + +0.0.2 / 2014-01-13 +================== + + * Object.defineProperty() sucks + * Initial commit diff --git a/node_modules/delegates/License b/node_modules/delegates/License new file mode 100644 index 0000000..60de60a --- /dev/null +++ b/node_modules/delegates/License @@ -0,0 +1,20 @@ +Copyright (c) 2015 TJ Holowaychuk + +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/delegates/Makefile b/node_modules/delegates/Makefile new file mode 100644 index 0000000..a9dcfd5 --- /dev/null +++ b/node_modules/delegates/Makefile @@ -0,0 +1,8 @@ + +test: + @./node_modules/.bin/mocha \ + --require should \ + --reporter spec \ + --bail + +.PHONY: test \ No newline at end of file diff --git a/node_modules/delegates/Readme.md b/node_modules/delegates/Readme.md new file mode 100644 index 0000000..ab8cf4a --- /dev/null +++ b/node_modules/delegates/Readme.md @@ -0,0 +1,94 @@ + +# delegates + + Node method and accessor delegation utilty. + +## Installation + +``` +$ npm install delegates +``` + +## Example + +```js +var delegate = require('delegates'); + +... + +delegate(proto, 'request') + .method('acceptsLanguages') + .method('acceptsEncodings') + .method('acceptsCharsets') + .method('accepts') + .method('is') + .access('querystring') + .access('idempotent') + .access('socket') + .access('length') + .access('query') + .access('search') + .access('status') + .access('method') + .access('path') + .access('body') + .access('host') + .access('url') + .getter('subdomains') + .getter('protocol') + .getter('header') + .getter('stale') + .getter('fresh') + .getter('secure') + .getter('ips') + .getter('ip') +``` + +# API + +## Delegate(proto, prop) + +Creates a delegator instance used to configure using the `prop` on the given +`proto` object. (which is usually a prototype) + +## Delegate#method(name) + +Allows the given method `name` to be accessed on the host. + +## Delegate#getter(name) + +Creates a "getter" for the property with the given `name` on the delegated +object. + +## Delegate#setter(name) + +Creates a "setter" for the property with the given `name` on the delegated +object. + +## Delegate#access(name) + +Creates an "accessor" (ie: both getter *and* setter) for the property with the +given `name` on the delegated object. + +## Delegate#fluent(name) + +A unique type of "accessor" that works for a "fluent" API. When called as a +getter, the method returns the expected value. However, if the method is called +with a value, it will return itself so it can be chained. For example: + +```js +delegate(proto, 'request') + .fluent('query') + +// getter +var q = request.query(); + +// setter (chainable) +request + .query({ a: 1 }) + .query({ b: 2 }); +``` + +# License + + MIT diff --git a/node_modules/delegates/index.js b/node_modules/delegates/index.js new file mode 100644 index 0000000..17c222d --- /dev/null +++ b/node_modules/delegates/index.js @@ -0,0 +1,121 @@ + +/** + * Expose `Delegator`. + */ + +module.exports = Delegator; + +/** + * Initialize a delegator. + * + * @param {Object} proto + * @param {String} target + * @api public + */ + +function Delegator(proto, target) { + if (!(this instanceof Delegator)) return new Delegator(proto, target); + this.proto = proto; + this.target = target; + this.methods = []; + this.getters = []; + this.setters = []; + this.fluents = []; +} + +/** + * Delegate method `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ + +Delegator.prototype.method = function(name){ + var proto = this.proto; + var target = this.target; + this.methods.push(name); + + proto[name] = function(){ + return this[target][name].apply(this[target], arguments); + }; + + return this; +}; + +/** + * Delegator accessor `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ + +Delegator.prototype.access = function(name){ + return this.getter(name).setter(name); +}; + +/** + * Delegator getter `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ + +Delegator.prototype.getter = function(name){ + var proto = this.proto; + var target = this.target; + this.getters.push(name); + + proto.__defineGetter__(name, function(){ + return this[target][name]; + }); + + return this; +}; + +/** + * Delegator setter `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ + +Delegator.prototype.setter = function(name){ + var proto = this.proto; + var target = this.target; + this.setters.push(name); + + proto.__defineSetter__(name, function(val){ + return this[target][name] = val; + }); + + return this; +}; + +/** + * Delegator fluent accessor + * + * @param {String} name + * @return {Delegator} self + * @api public + */ + +Delegator.prototype.fluent = function (name) { + var proto = this.proto; + var target = this.target; + this.fluents.push(name); + + proto[name] = function(val){ + if ('undefined' != typeof val) { + this[target][name] = val; + return this; + } else { + return this[target][name]; + } + }; + + return this; +}; diff --git a/node_modules/delegates/package.json b/node_modules/delegates/package.json new file mode 100644 index 0000000..1724038 --- /dev/null +++ b/node_modules/delegates/package.json @@ -0,0 +1,13 @@ +{ + "name": "delegates", + "version": "1.0.0", + "repository": "visionmedia/node-delegates", + "description": "delegate methods and accessors to another property", + "keywords": ["delegate", "delegation"], + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "license": "MIT" +} diff --git a/node_modules/delegates/test/index.js b/node_modules/delegates/test/index.js new file mode 100644 index 0000000..7b6e3d4 --- /dev/null +++ b/node_modules/delegates/test/index.js @@ -0,0 +1,94 @@ + +var assert = require('assert'); +var delegate = require('..'); + +describe('.method(name)', function(){ + it('should delegate methods', function(){ + var obj = {}; + + obj.request = { + foo: function(bar){ + assert(this == obj.request); + return bar; + } + }; + + delegate(obj, 'request').method('foo'); + + obj.foo('something').should.equal('something'); + }) +}) + +describe('.getter(name)', function(){ + it('should delegate getters', function(){ + var obj = {}; + + obj.request = { + get type() { + return 'text/html'; + } + } + + delegate(obj, 'request').getter('type'); + + obj.type.should.equal('text/html'); + }) +}) + +describe('.setter(name)', function(){ + it('should delegate setters', function(){ + var obj = {}; + + obj.request = { + get type() { + return this._type.toUpperCase(); + }, + + set type(val) { + this._type = val; + } + } + + delegate(obj, 'request').setter('type'); + + obj.type = 'hey'; + obj.request.type.should.equal('HEY'); + }) +}) + +describe('.access(name)', function(){ + it('should delegate getters and setters', function(){ + var obj = {}; + + obj.request = { + get type() { + return this._type.toUpperCase(); + }, + + set type(val) { + this._type = val; + } + } + + delegate(obj, 'request').access('type'); + + obj.type = 'hey'; + obj.type.should.equal('HEY'); + }) +}) + +describe('.fluent(name)', function () { + it('should delegate in a fluent fashion', function () { + var obj = { + settings: { + env: 'development' + } + }; + + delegate(obj, 'settings').fluent('env'); + + obj.env().should.equal('development'); + obj.env('production').should.equal(obj); + obj.settings.env.should.equal('production'); + }) +}) diff --git a/node_modules/denque/CHANGELOG.md b/node_modules/denque/CHANGELOG.md new file mode 100644 index 0000000..0577ebc --- /dev/null +++ b/node_modules/denque/CHANGELOG.md @@ -0,0 +1,22 @@ +## 2.0.1 + + - fix(types): incorrect return type on `size()` + +## 2.0.0 + + - fix!: `push` & `unshift` now accept `undefined` values to match behaviour of `Array` (fixes #25) (#35) + - This is only a **BREAKING** change if you are currently expecting `push(undefined)` and `unshift(undefined)` to do + nothing - the new behaviour now correctly adds undefined values to the queue. + - **Note**: behaviour of `push()` & `unshift()` (no arguments) remains unchanged (nothing gets added to the queue). + - **Note**: If you need to differentiate between `undefined` values in the queue and the return value of `pop()` then + check the queue `.length` before popping. + - fix: incorrect methods in types definition file + +## 1.5.1 + + - perf: minor performance tweak when growing queue size (#29) + +## 1.5.0 + + - feat: adds capacity option for circular buffers (#27) + diff --git a/node_modules/denque/LICENSE b/node_modules/denque/LICENSE new file mode 100644 index 0000000..c9cde92 --- /dev/null +++ b/node_modules/denque/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 2018-present Invertase Limited + + 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/denque/README.md b/node_modules/denque/README.md new file mode 100644 index 0000000..3c645d3 --- /dev/null +++ b/node_modules/denque/README.md @@ -0,0 +1,77 @@ +

+

Denque

+

+ +

+ NPM downloads + NPM version + Tests status + Coverage + License + Follow on Twitter +

+ +Denque is a well tested, extremely fast and lightweight [double-ended queue](http://en.wikipedia.org/wiki/Double-ended_queue) +implementation with zero dependencies and includes TypeScript types. + +Double-ended queues can also be used as a: + +- [Stack](http://en.wikipedia.org/wiki/Stack_\(abstract_data_type\)) +- [Queue](http://en.wikipedia.org/wiki/Queue_\(data_structure\)) + +This implementation is currently the fastest available, even faster than `double-ended-queue`, see the [benchmarks](https://docs.page/invertase/denque/benchmarks). + +Every queue operation is done at a constant `O(1)` - including random access from `.peekAt(index)`. + +**Works on all node versions >= v0.10** + +## Quick Start + +Install the package: + +```bash +npm install denque +``` + +Create and consume a queue: + +```js +const Denque = require("denque"); + +const denque = new Denque([1,2,3,4]); +denque.shift(); // 1 +denque.pop(); // 4 +``` + + +See the [API reference documentation](https://docs.page/invertase/denque/api) for more examples. + +--- + +## Who's using it? + +- [Kafka Node.js client](https://www.npmjs.com/package/kafka-node) +- [MariaDB Node.js client](https://www.npmjs.com/package/mariadb) +- [MongoDB Node.js client](https://www.npmjs.com/package/mongodb) +- [MySQL Node.js client](https://www.npmjs.com/package/mysql2) +- [Redis Node.js clients](https://www.npmjs.com/package/redis) + +... and [many more](https://www.npmjs.com/browse/depended/denque). + + +--- + +## License + +- See [LICENSE](/LICENSE) + +--- + +

+ + + +

+ Built and maintained by Invertase. +

+

diff --git a/node_modules/denque/index.d.ts b/node_modules/denque/index.d.ts new file mode 100644 index 0000000..e125dd4 --- /dev/null +++ b/node_modules/denque/index.d.ts @@ -0,0 +1,47 @@ +declare class Denque { + length: number; + + constructor(); + + constructor(array: T[]); + + constructor(array: T[], options: IDenqueOptions); + + push(item: T): number; + + unshift(item: T): number; + + pop(): T | undefined; + + shift(): T | undefined; + + peekBack(): T | undefined; + + peekFront(): T | undefined; + + peekAt(index: number): T | undefined; + + get(index: number): T | undefined; + + remove(index: number, count: number): T[]; + + removeOne(index: number): T | undefined; + + splice(index: number, count: number, ...item: T[]): T[] | undefined; + + isEmpty(): boolean; + + clear(): void; + + size(): number; + + toString(): string; + + toArray(): T[]; +} + +interface IDenqueOptions { + capacity?: number +} + +export = Denque; diff --git a/node_modules/denque/index.js b/node_modules/denque/index.js new file mode 100644 index 0000000..0e03764 --- /dev/null +++ b/node_modules/denque/index.js @@ -0,0 +1,443 @@ +'use strict'; + +/** + * Custom implementation of a double ended queue. + */ +function Denque(array, options) { + var options = options || {}; + + this._head = 0; + this._tail = 0; + this._capacity = options.capacity; + this._capacityMask = 0x3; + this._list = new Array(4); + if (Array.isArray(array)) { + this._fromArray(array); + } +} + +/** + * -------------- + * PUBLIC API + * ------------- + */ + +/** + * Returns the item at the specified index from the list. + * 0 is the first element, 1 is the second, and so on... + * Elements at negative values are that many from the end: -1 is one before the end + * (the last element), -2 is two before the end (one before last), etc. + * @param index + * @returns {*} + */ +Denque.prototype.peekAt = function peekAt(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var len = this.size(); + if (i >= len || i < -len) return undefined; + if (i < 0) i += len; + i = (this._head + i) & this._capacityMask; + return this._list[i]; +}; + +/** + * Alias for peekAt() + * @param i + * @returns {*} + */ +Denque.prototype.get = function get(i) { + return this.peekAt(i); +}; + +/** + * Returns the first item in the list without removing it. + * @returns {*} + */ +Denque.prototype.peek = function peek() { + if (this._head === this._tail) return undefined; + return this._list[this._head]; +}; + +/** + * Alias for peek() + * @returns {*} + */ +Denque.prototype.peekFront = function peekFront() { + return this.peek(); +}; + +/** + * Returns the item that is at the back of the queue without removing it. + * Uses peekAt(-1) + */ +Denque.prototype.peekBack = function peekBack() { + return this.peekAt(-1); +}; + +/** + * Returns the current length of the queue + * @return {Number} + */ +Object.defineProperty(Denque.prototype, 'length', { + get: function length() { + return this.size(); + } +}); + +/** + * Return the number of items on the list, or 0 if empty. + * @returns {number} + */ +Denque.prototype.size = function size() { + if (this._head === this._tail) return 0; + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * Add an item at the beginning of the list. + * @param item + */ +Denque.prototype.unshift = function unshift(item) { + if (arguments.length === 0) return this.size(); + var len = this._list.length; + this._head = (this._head - 1 + len) & this._capacityMask; + this._list[this._head] = item; + if (this._tail === this._head) this._growArray(); + if (this._capacity && this.size() > this._capacity) this.pop(); + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * Remove and return the first item on the list, + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.shift = function shift() { + var head = this._head; + if (head === this._tail) return undefined; + var item = this._list[head]; + this._list[head] = undefined; + this._head = (head + 1) & this._capacityMask; + if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); + return item; +}; + +/** + * Add an item to the bottom of the list. + * @param item + */ +Denque.prototype.push = function push(item) { + if (arguments.length === 0) return this.size(); + var tail = this._tail; + this._list[tail] = item; + this._tail = (tail + 1) & this._capacityMask; + if (this._tail === this._head) { + this._growArray(); + } + if (this._capacity && this.size() > this._capacity) { + this.shift(); + } + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * Remove and return the last item on the list. + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.pop = function pop() { + var tail = this._tail; + if (tail === this._head) return undefined; + var len = this._list.length; + this._tail = (tail - 1 + len) & this._capacityMask; + var item = this._list[this._tail]; + this._list[this._tail] = undefined; + if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); + return item; +}; + +/** + * Remove and return the item at the specified index from the list. + * Returns undefined if the list is empty. + * @param index + * @returns {*} + */ +Denque.prototype.removeOne = function removeOne(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size) return void 0; + if (i < 0) i += size; + i = (this._head + i) & this._capacityMask; + var item = this._list[i]; + var k; + if (index < size / 2) { + for (k = index; k > 0; k--) { + this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._head = (this._head + 1 + len) & this._capacityMask; + } else { + for (k = size - 1 - index; k > 0; k--) { + this._list[i] = this._list[i = (i + 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._tail = (this._tail - 1 + len) & this._capacityMask; + } + return item; +}; + +/** + * Remove number of items from the specified index from the list. + * Returns array of removed items. + * Returns undefined if the list is empty. + * @param index + * @param count + * @returns {array} + */ +Denque.prototype.remove = function remove(index, count) { + var i = index; + var removed; + var del_count = count; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size || count < 1) return void 0; + if (i < 0) i += size; + if (count === 1 || !count) { + removed = new Array(1); + removed[0] = this.removeOne(i); + return removed; + } + if (i === 0 && i + count >= size) { + removed = this.toArray(); + this.clear(); + return removed; + } + if (i + count > size) count = size - i; + var k; + removed = new Array(count); + for (k = 0; k < count; k++) { + removed[k] = this._list[(this._head + i + k) & this._capacityMask]; + } + i = (this._head + i) & this._capacityMask; + if (index + count === size) { + this._tail = (this._tail - count + len) & this._capacityMask; + for (k = count; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (index === 0) { + this._head = (this._head + count + len) & this._capacityMask; + for (k = count - 1; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (i < size / 2) { + this._head = (this._head + index + count + len) & this._capacityMask; + for (k = index; k > 0; k--) { + this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); + } + i = (this._head - 1 + len) & this._capacityMask; + while (del_count > 0) { + this._list[i = (i - 1 + len) & this._capacityMask] = void 0; + del_count--; + } + if (index < 0) this._tail = i; + } else { + this._tail = i; + i = (i + count + len) & this._capacityMask; + for (k = size - (count + index); k > 0; k--) { + this.push(this._list[i++]); + } + i = this._tail; + while (del_count > 0) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + del_count--; + } + } + if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); + return removed; +}; + +/** + * Native splice implementation. + * Remove number of items from the specified index from the list and/or add new elements. + * Returns array of removed items or empty array if count == 0. + * Returns undefined if the list is empty. + * + * @param index + * @param count + * @param {...*} [elements] + * @returns {array} + */ +Denque.prototype.splice = function splice(index, count) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var size = this.size(); + if (i < 0) i += size; + if (i > size) return void 0; + if (arguments.length > 2) { + var k; + var temp; + var removed; + var arg_len = arguments.length; + var len = this._list.length; + var arguments_index = 2; + if (!size || i < size / 2) { + temp = new Array(i); + for (k = 0; k < i; k++) { + temp[k] = this._list[(this._head + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i > 0) { + this._head = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._head = (this._head + i + len) & this._capacityMask; + } + while (arg_len > arguments_index) { + this.unshift(arguments[--arg_len]); + } + for (k = i; k > 0; k--) { + this.unshift(temp[k - 1]); + } + } else { + temp = new Array(size - (i + count)); + var leng = temp.length; + for (k = 0; k < leng; k++) { + temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i != size) { + this._tail = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._tail = (this._tail - leng + len) & this._capacityMask; + } + while (arguments_index < arg_len) { + this.push(arguments[arguments_index++]); + } + for (k = 0; k < leng; k++) { + this.push(temp[k]); + } + } + return removed; + } else { + return this.remove(i, count); + } +}; + +/** + * Soft clear - does not reset capacity. + */ +Denque.prototype.clear = function clear() { + this._head = 0; + this._tail = 0; +}; + +/** + * Returns true or false whether the list is empty. + * @returns {boolean} + */ +Denque.prototype.isEmpty = function isEmpty() { + return this._head === this._tail; +}; + +/** + * Returns an array of all queue items. + * @returns {Array} + */ +Denque.prototype.toArray = function toArray() { + return this._copyArray(false); +}; + +/** + * ------------- + * INTERNALS + * ------------- + */ + +/** + * Fills the queue with items from an array + * For use in the constructor + * @param array + * @private + */ +Denque.prototype._fromArray = function _fromArray(array) { + for (var i = 0; i < array.length; i++) this.push(array[i]); +}; + +/** + * + * @param fullCopy + * @returns {Array} + * @private + */ +Denque.prototype._copyArray = function _copyArray(fullCopy) { + var newArray = []; + var list = this._list; + var len = list.length; + var i; + if (fullCopy || this._head > this._tail) { + for (i = this._head; i < len; i++) newArray.push(list[i]); + for (i = 0; i < this._tail; i++) newArray.push(list[i]); + } else { + for (i = this._head; i < this._tail; i++) newArray.push(list[i]); + } + return newArray; +}; + +/** + * Grows the internal list array. + * @private + */ +Denque.prototype._growArray = function _growArray() { + if (this._head) { + // copy existing data, head to end, then beginning to tail. + this._list = this._copyArray(true); + this._head = 0; + } + + // head is at 0 and array is now full, safe to extend + this._tail = this._list.length; + + this._list.length <<= 1; + this._capacityMask = (this._capacityMask << 1) | 1; +}; + +/** + * Shrinks the internal list array. + * @private + */ +Denque.prototype._shrinkArray = function _shrinkArray() { + this._list.length >>>= 1; + this._capacityMask >>>= 1; +}; + + +module.exports = Denque; diff --git a/node_modules/denque/package.json b/node_modules/denque/package.json new file mode 100644 index 0000000..f1a0fcc --- /dev/null +++ b/node_modules/denque/package.json @@ -0,0 +1,55 @@ +{ + "name": "denque", + "version": "2.0.1", + "description": "The fastest javascript implementation of a double-ended queue. Used by the official Redis, MongoDB, MariaDB & MySQL libraries for Node.js and many other libraries. Maintains compatability with deque.", + "main": "index.js", + "engines": { + "node": ">=0.10" + }, + "keywords": [ + "data-structure", + "data-structures", + "queue", + "double", + "end", + "ended", + "deque", + "denque", + "double-ended-queue" + ], + "scripts": { + "test": "istanbul cover --report lcov _mocha && npm run typescript", + "coveralls": "cat ./coverage/lcov.info | coveralls", + "typescript": "tsc --project ./test/type/tsconfig.json", + "benchmark_thousand": "node benchmark/thousand", + "benchmark_2mil": "node benchmark/two_million", + "benchmark_splice": "node benchmark/splice", + "benchmark_remove": "node benchmark/remove", + "benchmark_removeOne": "node benchmark/removeOne" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/invertase/denque.git" + }, + "license": "Apache-2.0", + "author": { + "name": "Invertase", + "email": "oss@invertase.io", + "url": "http://github.com/invertase/" + }, + "contributors": [ + "Mike Diarmid (Salakar) " + ], + "bugs": { + "url": "https://github.com/invertase/denque/issues" + }, + "homepage": "https://docs.page/invertase/denque", + "devDependencies": { + "benchmark": "^2.1.4", + "codecov": "^3.8.3", + "double-ended-queue": "^2.1.0-0", + "istanbul": "^0.4.5", + "mocha": "^3.5.3", + "typescript": "^3.4.1" + } +} diff --git a/node_modules/depd/History.md b/node_modules/depd/History.md new file mode 100644 index 0000000..507ecb8 --- /dev/null +++ b/node_modules/depd/History.md @@ -0,0 +1,96 @@ +1.1.2 / 2018-01-11 +================== + + * perf: remove argument reassignment + * Support Node.js 0.6 to 9.x + +1.1.1 / 2017-07-27 +================== + + * Remove unnecessary `Buffer` loading + * Support Node.js 0.6 to 8.x + +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/node_modules/depd/LICENSE b/node_modules/depd/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/depd/Readme.md b/node_modules/depd/Readme.md new file mode 100644 index 0000000..7790670 --- /dev/null +++ b/node_modules/depd/Readme.md @@ -0,0 +1,280 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + + + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction () { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/depd.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg +[npm-url]: https://npmjs.org/package/depd +[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://img.shields.io/node/v/depd.svg +[node-url]: https://nodejs.org/en/download/ diff --git a/node_modules/depd/index.js b/node_modules/depd/index.js new file mode 100644 index 0000000..d758d3c --- /dev/null +++ b/node_modules/depd/index.js @@ -0,0 +1,522 @@ +/*! + * depd + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var callSiteToString = require('./lib/compat').callSiteToString +var eventListenerCount = require('./lib/compat').eventListenerCount +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() + + for (var i = 0; i < vals.length; i++) { + var val = vals[i] + + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter () { return value } + + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString (arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log (message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') +} + +/** + * Get call site location as array. + */ + +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace (obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this // eslint-disable-line no-unused-vars + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + // eslint-disable-next-line no-eval + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) + + return error +} diff --git a/node_modules/depd/lib/browser/index.js b/node_modules/depd/lib/browser/index.js new file mode 100644 index 0000000..6be45cc --- /dev/null +++ b/node_modules/depd/lib/browser/index.js @@ -0,0 +1,77 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate (message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } +} diff --git a/node_modules/depd/lib/compat/callsite-tostring.js b/node_modules/depd/lib/compat/callsite-tostring.js new file mode 100644 index 0000000..73186dc --- /dev/null +++ b/node_modules/depd/lib/compat/callsite-tostring.js @@ -0,0 +1,103 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = callSiteToString + +/** + * Format a CallSite file location to a string. + */ + +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +function callSiteToString (callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} diff --git a/node_modules/depd/lib/compat/event-listener-count.js b/node_modules/depd/lib/compat/event-listener-count.js new file mode 100644 index 0000000..3a8925d --- /dev/null +++ b/node_modules/depd/lib/compat/event-listener-count.js @@ -0,0 +1,22 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length +} diff --git a/node_modules/depd/lib/compat/index.js b/node_modules/depd/lib/compat/index.js new file mode 100644 index 0000000..955b333 --- /dev/null +++ b/node_modules/depd/lib/compat/index.js @@ -0,0 +1,79 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var EventEmitter = require('events').EventEmitter + +/** + * Module exports. + * @public + */ + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace (obj, stack) { + return stack + } + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : require('./callsite-tostring') +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || require('./event-listener-count') +}) + +/** + * Define a lazy property. + */ + +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val + } + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString (obj) { + return obj.toString() +} diff --git a/node_modules/depd/package.json b/node_modules/depd/package.json new file mode 100644 index 0000000..5e3c863 --- /dev/null +++ b/node_modules/depd/package.json @@ -0,0 +1,41 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "1.1.2", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": "dougwilson/nodejs-depd", + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "2.1.4", + "beautify-benchmark": "0.2.4", + "eslint": "3.19.0", + "eslint-config-standard": "7.1.0", + "eslint-plugin-markdown": "1.0.0-beta.7", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --no-exit test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/" + } +} diff --git a/node_modules/destroy/LICENSE b/node_modules/destroy/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/node_modules/destroy/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.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/destroy/README.md b/node_modules/destroy/README.md new file mode 100644 index 0000000..6474bc3 --- /dev/null +++ b/node_modules/destroy/README.md @@ -0,0 +1,60 @@ +# Destroy + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Destroy a stream. + +This module is meant to ensure a stream gets destroyed, handling different APIs +and Node.js bugs. + +## API + +```js +var destroy = require('destroy') +``` + +### destroy(stream) + +Destroy the given stream. In most cases, this is identical to a simple +`stream.destroy()` call. The rules are as follows for a given stream: + + 1. If the `stream` is an instance of `ReadStream`, then call `stream.destroy()` + and add a listener to the `open` event to call `stream.close()` if it is + fired. This is for a Node.js bug that will leak a file descriptor if + `.destroy()` is called before `open`. + 2. If the `stream` is not an instance of `Stream`, then nothing happens. + 3. If the `stream` has a `.destroy()` method, then call it. + +The function returns the `stream` passed in as the argument. + +## Example + +```js +var destroy = require('destroy') + +var fs = require('fs') +var stream = fs.createReadStream('package.json') + +// ... and later +destroy(stream) +``` + +[npm-image]: https://img.shields.io/npm/v/destroy.svg?style=flat-square +[npm-url]: https://npmjs.org/package/destroy +[github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square +[github-url]: https://github.com/stream-utils/destroy/tags +[travis-image]: https://img.shields.io/travis/stream-utils/destroy.svg?style=flat-square +[travis-url]: https://travis-ci.org/stream-utils/destroy +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master +[license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/destroy +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/node_modules/destroy/index.js b/node_modules/destroy/index.js new file mode 100644 index 0000000..6da2d26 --- /dev/null +++ b/node_modules/destroy/index.js @@ -0,0 +1,75 @@ +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var ReadStream = require('fs').ReadStream +var Stream = require('stream') + +/** + * Module exports. + * @public + */ + +module.exports = destroy + +/** + * Destroy a stream. + * + * @param {object} stream + * @public + */ + +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) + } + + if (!(stream instanceof Stream)) { + return stream + } + + if (typeof stream.destroy === 'function') { + stream.destroy() + } + + return stream +} + +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ + +function destroyReadStream(stream) { + stream.destroy() + + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) + } + + return stream +} + +/** + * On open handler to close stream. + * @private + */ + +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() + } +} diff --git a/node_modules/destroy/package.json b/node_modules/destroy/package.json new file mode 100644 index 0000000..024bff9 --- /dev/null +++ b/node_modules/destroy/package.json @@ -0,0 +1,37 @@ +{ + "name": "destroy", + "description": "destroy a stream if possible", + "version": "1.0.4", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "stream-utils/destroy", + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "2.3.4" + }, + "scripts": { + "test": "mocha --reporter spec", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "files": [ + "index.js", + "LICENSE" + ], + "keywords": [ + "stream", + "streams", + "destroy", + "cleanup", + "leak", + "fd" + ] +} diff --git a/node_modules/detect-libc/.npmignore b/node_modules/detect-libc/.npmignore new file mode 100644 index 0000000..8fc0e8d --- /dev/null +++ b/node_modules/detect-libc/.npmignore @@ -0,0 +1,7 @@ +.nyc_output +.travis.yml +coverage +test.js +node_modules +/.circleci +/tests/integration diff --git a/node_modules/detect-libc/LICENSE b/node_modules/detect-libc/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/node_modules/detect-libc/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/detect-libc/README.md b/node_modules/detect-libc/README.md new file mode 100644 index 0000000..3176357 --- /dev/null +++ b/node_modules/detect-libc/README.md @@ -0,0 +1,78 @@ +# detect-libc + +Node.js module to detect the C standard library (libc) implementation +family and version in use on a given Linux system. + +Provides a value suitable for use with the `LIBC` option of +[prebuild](https://www.npmjs.com/package/prebuild), +[prebuild-ci](https://www.npmjs.com/package/prebuild-ci) and +[prebuild-install](https://www.npmjs.com/package/prebuild-install), +therefore allowing build and provision of pre-compiled binaries +for musl-based Linux e.g. Alpine as well as glibc-based. + +Currently supports libc detection of `glibc` and `musl`. + +## Install + +```sh +npm install detect-libc +``` + +## Usage + +### API + +```js +const { GLIBC, MUSL, family, version, isNonGlibcLinux } = require('detect-libc'); +``` + +* `GLIBC` is a String containing the value "glibc" for comparison with `family`. +* `MUSL` is a String containing the value "musl" for comparison with `family`. +* `family` is a String representing the system libc family. +* `version` is a String representing the system libc version number. +* `isNonGlibcLinux` is a Boolean representing whether the system is a non-glibc Linux, e.g. Alpine. + +### detect-libc command line tool + +When run on a Linux system with a non-glibc libc, +the child command will be run with the `LIBC` environment variable +set to the relevant value. + +On all other platforms will run the child command as-is. + +The command line feature requires `spawnSync` provided by Node v0.12+. + +```sh +detect-libc child-command +``` + +## Integrating with prebuild + +```json + "scripts": { + "install": "detect-libc prebuild-install || node-gyp rebuild", + "test": "mocha && detect-libc prebuild-ci" + }, + "dependencies": { + "detect-libc": "^1.0.2", + "prebuild-install": "^2.2.0" + }, + "devDependencies": { + "prebuild": "^6.2.1", + "prebuild-ci": "^2.2.3" + } +``` + +## Licence + +Copyright 2017 Lovell Fuller + +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](http://www.apache.org/licenses/LICENSE-2.0.html) + +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/detect-libc/bin/detect-libc.js b/node_modules/detect-libc/bin/detect-libc.js new file mode 100644 index 0000000..5486127 --- /dev/null +++ b/node_modules/detect-libc/bin/detect-libc.js @@ -0,0 +1,18 @@ +#!/usr/bin/env node + +'use strict'; + +var spawnSync = require('child_process').spawnSync; +var libc = require('../'); + +var spawnOptions = { + env: process.env, + shell: true, + stdio: 'inherit' +}; + +if (libc.isNonGlibcLinux) { + spawnOptions.env.LIBC = process.env.LIBC || libc.family; +} + +process.exit(spawnSync(process.argv[2], process.argv.slice(3), spawnOptions).status); diff --git a/node_modules/detect-libc/lib/detect-libc.js b/node_modules/detect-libc/lib/detect-libc.js new file mode 100644 index 0000000..1855fe1 --- /dev/null +++ b/node_modules/detect-libc/lib/detect-libc.js @@ -0,0 +1,92 @@ +'use strict'; + +var platform = require('os').platform(); +var spawnSync = require('child_process').spawnSync; +var readdirSync = require('fs').readdirSync; + +var GLIBC = 'glibc'; +var MUSL = 'musl'; + +var spawnOptions = { + encoding: 'utf8', + env: process.env +}; + +if (!spawnSync) { + spawnSync = function () { + return { status: 126, stdout: '', stderr: '' }; + }; +} + +function contains (needle) { + return function (haystack) { + return haystack.indexOf(needle) !== -1; + }; +} + +function versionFromMuslLdd (out) { + return out.split(/[\r\n]+/)[1].trim().split(/\s/)[1]; +} + +function safeReaddirSync (path) { + try { + return readdirSync(path); + } catch (e) {} + return []; +} + +var family = ''; +var version = ''; +var method = ''; + +if (platform === 'linux') { + // Try getconf + var glibc = spawnSync('getconf', ['GNU_LIBC_VERSION'], spawnOptions); + if (glibc.status === 0) { + family = GLIBC; + version = glibc.stdout.trim().split(' ')[1]; + method = 'getconf'; + } else { + // Try ldd + var ldd = spawnSync('ldd', ['--version'], spawnOptions); + if (ldd.status === 0 && ldd.stdout.indexOf(MUSL) !== -1) { + family = MUSL; + version = versionFromMuslLdd(ldd.stdout); + method = 'ldd'; + } else if (ldd.status === 1 && ldd.stderr.indexOf(MUSL) !== -1) { + family = MUSL; + version = versionFromMuslLdd(ldd.stderr); + method = 'ldd'; + } else { + // Try filesystem (family only) + var lib = safeReaddirSync('/lib'); + if (lib.some(contains('-linux-gnu'))) { + family = GLIBC; + method = 'filesystem'; + } else if (lib.some(contains('libc.musl-'))) { + family = MUSL; + method = 'filesystem'; + } else if (lib.some(contains('ld-musl-'))) { + family = MUSL; + method = 'filesystem'; + } else { + var usrSbin = safeReaddirSync('/usr/sbin'); + if (usrSbin.some(contains('glibc'))) { + family = GLIBC; + method = 'filesystem'; + } + } + } + } +} + +var isNonGlibcLinux = (family !== '' && family !== GLIBC); + +module.exports = { + GLIBC: GLIBC, + MUSL: MUSL, + family: family, + version: version, + method: method, + isNonGlibcLinux: isNonGlibcLinux +}; diff --git a/node_modules/detect-libc/package.json b/node_modules/detect-libc/package.json new file mode 100644 index 0000000..cbd5cd1 --- /dev/null +++ b/node_modules/detect-libc/package.json @@ -0,0 +1,35 @@ +{ + "name": "detect-libc", + "version": "1.0.3", + "description": "Node.js module to detect the C standard library (libc) implementation family and version", + "main": "lib/detect-libc.js", + "bin": { + "detect-libc": "./bin/detect-libc.js" + }, + "scripts": { + "test": "semistandard && nyc --reporter=lcov ava" + }, + "repository": { + "type": "git", + "url": "git://github.com/lovell/detect-libc" + }, + "keywords": [ + "libc", + "glibc", + "musl" + ], + "author": "Lovell Fuller ", + "contributors": [ + "Niklas Salmoukas " + ], + "license": "Apache-2.0", + "devDependencies": { + "ava": "^0.23.0", + "nyc": "^11.3.0", + "proxyquire": "^1.8.0", + "semistandard": "^11.0.0" + }, + "engines": { + "node": ">=0.10" + } +} diff --git a/node_modules/ecdsa-sig-formatter/CODEOWNERS b/node_modules/ecdsa-sig-formatter/CODEOWNERS new file mode 100644 index 0000000..4451d3d --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/CODEOWNERS @@ -0,0 +1 @@ +* @omsmith diff --git a/node_modules/ecdsa-sig-formatter/LICENSE b/node_modules/ecdsa-sig-formatter/LICENSE new file mode 100644 index 0000000..8754ed6 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/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 2015 D2L Corporation + + 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/ecdsa-sig-formatter/README.md b/node_modules/ecdsa-sig-formatter/README.md new file mode 100644 index 0000000..daa95d6 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/README.md @@ -0,0 +1,65 @@ +# ecdsa-sig-formatter + +[![Build Status](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter.svg?branch=master)](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter) [![Coverage Status](https://coveralls.io/repos/Brightspace/node-ecdsa-sig-formatter/badge.svg)](https://coveralls.io/r/Brightspace/node-ecdsa-sig-formatter) + +Translate between JOSE and ASN.1/DER encodings for ECDSA signatures + +## Install +```sh +npm install ecdsa-sig-formatter --save +``` + +## Usage +```js +var format = require('ecdsa-sig-formatter'); + +var derSignature = '..'; // asn.1/DER encoded ecdsa signature + +var joseSignature = format.derToJose(derSignature); + +``` + +### API + +--- + +#### `.derToJose(Buffer|String signature, String alg)` -> `String` + +Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature. +Returns a _base64 url_ encoded `String`. + +* If _signature_ is a `String`, it should be _base64_ encoded +* _alg_ must be one of _ES256_, _ES384_ or _ES512_ + +--- + +#### `.joseToDer(Buffer|String signature, String alg)` -> `Buffer` + +Convert the JOSE-style concatenated signature to an ASN.1/DER encoded +signature. Returns a `Buffer` + +* If _signature_ is a `String`, it should be _base64 url_ encoded +* _alg_ must be one of _ES256_, _ES384_ or _ES512_ + +## Contributing + +1. **Fork** the repository. Committing directly against this repository is + highly discouraged. + +2. Make your modifications in a branch, updating and writing new unit tests + as necessary in the `spec` directory. + +3. Ensure that all tests pass with `npm test` + +4. `rebase` your changes against master. *Do not merge*. + +5. Submit a pull request to this repository. Wait for tests to run and someone + to chime in. + +### Code Style + +This repository is configured with [EditorConfig][EditorConfig] and +[ESLint][ESLint] rules. + +[EditorConfig]: http://editorconfig.org/ +[ESLint]: http://eslint.org diff --git a/node_modules/ecdsa-sig-formatter/package.json b/node_modules/ecdsa-sig-formatter/package.json new file mode 100644 index 0000000..6fb5ebf --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/package.json @@ -0,0 +1,46 @@ +{ + "name": "ecdsa-sig-formatter", + "version": "1.0.11", + "description": "Translate ECDSA signatures between ASN.1/DER and JOSE-style concatenation", + "main": "src/ecdsa-sig-formatter.js", + "scripts": { + "check-style": "eslint .", + "pretest": "npm run check-style", + "test": "istanbul cover --root src _mocha -- spec", + "report-cov": "cat ./coverage/lcov.info | coveralls" + }, + "typings": "./src/ecdsa-sig-formatter.d.ts", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/Brightspace/node-ecdsa-sig-formatter.git" + }, + "keywords": [ + "ecdsa", + "der", + "asn.1", + "jwt", + "jwa", + "jsonwebtoken", + "jose" + ], + "author": "D2L Corporation", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/Brightspace/node-ecdsa-sig-formatter/issues" + }, + "homepage": "https://github.com/Brightspace/node-ecdsa-sig-formatter#readme", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "devDependencies": { + "bench": "^0.3.6", + "chai": "^3.5.0", + "coveralls": "^2.11.9", + "eslint": "^2.12.0", + "eslint-config-brightspace": "^0.2.1", + "istanbul": "^0.4.3", + "jwk-to-pem": "^1.2.5", + "mocha": "^2.5.3", + "native-crypto": "^1.7.0" + } +} diff --git a/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts new file mode 100644 index 0000000..9693aa0 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts @@ -0,0 +1,17 @@ +/// + +declare module "ecdsa-sig-formatter" { + /** + * Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature. Returns a base64 url encoded String. + * If signature is a String, it should be base64 encoded + * alg must be one of ES256, ES384 or ES512 + */ + export function derToJose(signature: Buffer | string, alg: string): string; + + /** + * Convert the JOSE-style concatenated signature to an ASN.1/DER encoded signature. Returns a Buffer + * If signature is a String, it should be base64 url encoded + * alg must be one of ES256, ES384 or ES512 + */ + export function joseToDer(signature: Buffer | string, alg: string): Buffer +} diff --git a/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js new file mode 100644 index 0000000..38eeb9b --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js @@ -0,0 +1,187 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; + +var getParamBytesForAlg = require('./param-bytes-for-alg'); + +var MAX_OCTET = 0x80, + CLASS_UNIVERSAL = 0, + PRIMITIVE_BIT = 0x20, + TAG_SEQ = 0x10, + TAG_INT = 0x02, + ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), + ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); + +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } + + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); +} + +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + var maxEncodedParamLength = paramBytes + 1; + + var inputLength = signature.length; + + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } + + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } + + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } + + var rLength = signature[offset++]; + + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } + + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var rOffset = offset; + offset += rLength; + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } + + var sLength = signature[offset++]; + + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } + + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var sOffset = offset; + offset += sLength; + + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } + + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; + + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + + offset = paramBytes; + + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + + dst = dst.toString('base64'); + dst = base64Url(dst); + + return dst; +} + +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } + + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } + + return padding; +} + +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } + + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; + + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + + var shortLength = rsBytes < MAX_OCTET; + + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); + + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes; + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1; + // length, base 256 + dst[offset++] = rsBytes & 0xff; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } + + return dst; +} + +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer +}; diff --git a/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js b/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js new file mode 100644 index 0000000..9fe67ac --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js @@ -0,0 +1,23 @@ +'use strict'; + +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} + +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) +}; + +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } + + throw new Error('Unknown algorithm "' + alg + '"'); +} + +module.exports = getParamBytesForAlg; diff --git a/node_modules/ee-first/LICENSE b/node_modules/ee-first/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.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/ee-first/README.md b/node_modules/ee-first/README.md new file mode 100644 index 0000000..cbd2478 --- /dev/null +++ b/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/node_modules/ee-first/index.js b/node_modules/ee-first/index.js new file mode 100644 index 0000000..501287c --- /dev/null +++ b/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/node_modules/ee-first/package.json b/node_modules/ee-first/package.json new file mode 100644 index 0000000..b6d0b7d --- /dev/null +++ b/node_modules/ee-first/package.json @@ -0,0 +1,29 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.1.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "jonathanong/ee-first", + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/emoji-regex/LICENSE-MIT.txt b/node_modules/emoji-regex/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/emoji-regex/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/emoji-regex/README.md b/node_modules/emoji-regex/README.md new file mode 100644 index 0000000..f10e173 --- /dev/null +++ b/node_modules/emoji-regex/README.md @@ -0,0 +1,73 @@ +# emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) + +_emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. + +This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install emoji-regex +``` + +In [Node.js](https://nodejs.org/): + +```js +const emojiRegex = require('emoji-regex'); +// Note: because the regular expression has the global flag set, this module +// exports a function that returns the regex rather than exporting the regular +// expression itself, to make it impossible to (accidentally) mutate the +// original regular expression. + +const text = ` +\u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) +\u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji +\u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) +\u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier +`; + +const regex = emojiRegex(); +let match; +while (match = regex.exec(text)) { + const emoji = match[0]; + console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); +} +``` + +Console output: + +``` +Matched sequence ⌚ — code points: 1 +Matched sequence ⌚ — code points: 1 +Matched sequence ↔️ — code points: 2 +Matched sequence ↔️ — code points: 2 +Matched sequence 👩 — code points: 1 +Matched sequence 👩 — code points: 1 +Matched sequence 👩🏿 — code points: 2 +Matched sequence 👩🏿 — code points: 2 +``` + +To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: + +```js +const emojiRegex = require('emoji-regex/text.js'); +``` + +Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: + +```js +const emojiRegex = require('emoji-regex/es2015/index.js'); +const emojiRegexText = require('emoji-regex/es2015/text.js'); +``` + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +_emoji-regex_ is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/emoji-regex/es2015/index.js b/node_modules/emoji-regex/es2015/index.js new file mode 100644 index 0000000..b4cf3dc --- /dev/null +++ b/node_modules/emoji-regex/es2015/index.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = () => { + // https://mths.be/emoji + return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u{1F1FD}\u{1F1F0}|\u{1F1F4}\u{1F1F2}|\u{1F1F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1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; +}; diff --git a/node_modules/emoji-regex/es2015/text.js b/node_modules/emoji-regex/es2015/text.js new file mode 100644 index 0000000..780309d --- /dev/null +++ b/node_modules/emoji-regex/es2015/text.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = () => { + // https://mths.be/emoji + return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u{1F1FD}\u{1F1F0}|\u{1F1F4}\u{1F1F2}|\u{1F1F6}\u{1F1E6}|[#\*0-9]\uFE0F\u20E3|\u{1F1E7}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1F9}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1ED}\u{1F1EF}-\u{1F1F4}\u{1F1F7}\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FF}]|\u{1F1EA}[\u{1F1E6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-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1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CF}\u{1F9D1}-\u{1F9DD}]/gu; +}; diff --git a/node_modules/emoji-regex/index.d.ts b/node_modules/emoji-regex/index.d.ts new file mode 100644 index 0000000..1955b47 --- /dev/null +++ b/node_modules/emoji-regex/index.d.ts @@ -0,0 +1,23 @@ +declare module 'emoji-regex' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} + +declare module 'emoji-regex/text' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} + +declare module 'emoji-regex/es2015' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} + +declare module 'emoji-regex/es2015/text' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} diff --git a/node_modules/emoji-regex/index.js b/node_modules/emoji-regex/index.js new file mode 100644 index 0000000..d993a3a --- /dev/null +++ b/node_modules/emoji-regex/index.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\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\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; diff --git a/node_modules/emoji-regex/package.json b/node_modules/emoji-regex/package.json new file mode 100644 index 0000000..6d32352 --- /dev/null +++ b/node_modules/emoji-regex/package.json @@ -0,0 +1,50 @@ +{ + "name": "emoji-regex", + "version": "8.0.0", + "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", + "homepage": "https://mths.be/emoji-regex", + "main": "index.js", + "types": "index.d.ts", + "keywords": [ + "unicode", + "regex", + "regexp", + "regular expressions", + "code points", + "symbols", + "characters", + "emoji" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "repository": { + "type": "git", + "url": "https://github.com/mathiasbynens/emoji-regex.git" + }, + "bugs": "https://github.com/mathiasbynens/emoji-regex/issues", + "files": [ + "LICENSE-MIT.txt", + "index.js", + "index.d.ts", + "text.js", + "es2015/index.js", + "es2015/text.js" + ], + "scripts": { + "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src -d ./es2015; node script/inject-sequences.js", + "test": "mocha", + "test:watch": "npm run test -- --watch" + }, + "devDependencies": { + "@babel/cli": "^7.2.3", + "@babel/core": "^7.3.4", + "@babel/plugin-proposal-unicode-property-regex": "^7.2.0", + "@babel/preset-env": "^7.3.4", + "mocha": "^6.0.2", + "regexgen": "^1.3.0", + "unicode-12.0.0": "^0.7.9" + } +} diff --git a/node_modules/emoji-regex/text.js b/node_modules/emoji-regex/text.js new file mode 100644 index 0000000..0a55ce2 --- /dev/null +++ b/node_modules/emoji-regex/text.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\u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?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F?|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; diff --git a/node_modules/encodeurl/HISTORY.md b/node_modules/encodeurl/HISTORY.md new file mode 100644 index 0000000..41313b2 --- /dev/null +++ b/node_modules/encodeurl/HISTORY.md @@ -0,0 +1,14 @@ +1.0.2 / 2018-01-21 +================== + + * Fix encoding `%` as last character + +1.0.1 / 2016-06-09 +================== + + * Fix encoding unpaired surrogates at start/end of string + +1.0.0 / 2016-06-08 +================== + + * Initial release diff --git a/node_modules/encodeurl/LICENSE b/node_modules/encodeurl/LICENSE new file mode 100644 index 0000000..8812229 --- /dev/null +++ b/node_modules/encodeurl/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2016 Douglas Christopher Wilson + +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/encodeurl/README.md b/node_modules/encodeurl/README.md new file mode 100644 index 0000000..127c5a0 --- /dev/null +++ b/node_modules/encodeurl/README.md @@ -0,0 +1,128 @@ +# encodeurl + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Encode a URL to a percent-encoded form, excluding already-encoded sequences + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install encodeurl +``` + +## API + +```js +var encodeUrl = require('encodeurl') +``` + +### encodeUrl(url) + +Encode a URL to a percent-encoded form, excluding already-encoded sequences. + +This function will take an already-encoded URL and encode all the non-URL +code points (as UTF-8 byte sequences). This function will not encode the +"%" character unless it is not part of a valid sequence (`%20` will be +left as-is, but `%foo` will be encoded as `%25foo`). + +This encode is meant to be "safe" and does not throw errors. It will try as +hard as it can to properly encode the given URL, including replacing any raw, +unpaired surrogate pairs with the Unicode replacement character prior to +encoding. + +This function is _similar_ to the intrinsic function `encodeURI`, except it +will not encode the `%` character if that is part of a valid sequence, will +not encode `[` and `]` (for IPv6 hostnames) and will replace raw, unpaired +surrogate pairs with the Unicode replacement character (instead of throwing). + +## Examples + +### Encode a URL containing user-controled data + +```js +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') + +http.createServer(function onRequest (req, res) { + // get encoded form of inbound url + var url = encodeUrl(req.url) + + // create html message + var body = '

Location ' + escapeHtml(url) + ' not found

' + + // send a 404 + res.statusCode = 404 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) + res.end(body, 'utf-8') +}) +``` + +### Encode a URL for use in a header field + +```js +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var url = require('url') + +http.createServer(function onRequest (req, res) { + // parse inbound url + var href = url.parse(req) + + // set new host for redirect + href.host = 'localhost' + href.protocol = 'https:' + href.slashes = true + + // create location header + var location = encodeUrl(url.format(href)) + + // create html message + var body = '

Redirecting to new site: ' + escapeHtml(location) + '

' + + // send a 301 + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) + res.setHeader('Location', location) + res.end(body, 'utf-8') +}) +``` + +## Testing + +```sh +$ npm test +$ npm run lint +``` + +## References + +- [RFC 3986: Uniform Resource Identifier (URI): Generic Syntax][rfc-3986] +- [WHATWG URL Living Standard][whatwg-url] + +[rfc-3986]: https://tools.ietf.org/html/rfc3986 +[whatwg-url]: https://url.spec.whatwg.org/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/encodeurl.svg +[npm-url]: https://npmjs.org/package/encodeurl +[node-version-image]: https://img.shields.io/node/v/encodeurl.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/pillarjs/encodeurl.svg +[travis-url]: https://travis-ci.org/pillarjs/encodeurl +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/encodeurl.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/encodeurl?branch=master +[downloads-image]: https://img.shields.io/npm/dm/encodeurl.svg +[downloads-url]: https://npmjs.org/package/encodeurl diff --git a/node_modules/encodeurl/index.js b/node_modules/encodeurl/index.js new file mode 100644 index 0000000..fc4906c --- /dev/null +++ b/node_modules/encodeurl/index.js @@ -0,0 +1,60 @@ +/*! + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = encodeUrl + +/** + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. + * @private + */ + +var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g + +/** + * RegExp to match unmatched surrogate pair. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g + +/** + * String to replace unmatched surrogate pair with. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' + +/** + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. + * + * This function will take an already-encoded URL and encode all the non-URL + * code points. This function will not encode the "%" character unless it is + * not part of a valid sequence (`%20` will be left as-is, but `%foo` will + * be encoded as `%25foo`). + * + * This encode is meant to be "safe" and does not throw errors. It will try as + * hard as it can to properly encode the given URL, including replacing any raw, + * unpaired surrogate pairs with the Unicode replacement character prior to + * encoding. + * + * @param {string} url + * @return {string} + * @public + */ + +function encodeUrl (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) +} diff --git a/node_modules/encodeurl/package.json b/node_modules/encodeurl/package.json new file mode 100644 index 0000000..b9f25ef --- /dev/null +++ b/node_modules/encodeurl/package.json @@ -0,0 +1,40 @@ +{ + "name": "encodeurl", + "description": "Encode a URL to a percent-encoded form, excluding already-encoded sequences", + "version": "1.0.2", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "encode", + "encodeurl", + "url" + ], + "repository": "pillarjs/encodeurl", + "devDependencies": { + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.8.0", + "eslint-plugin-node": "5.2.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/escape-html/LICENSE b/node_modules/escape-html/LICENSE new file mode 100644 index 0000000..2e70de9 --- /dev/null +++ b/node_modules/escape-html/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2013 TJ Holowaychuk +Copyright (c) 2015 Andreas Lubbe +Copyright (c) 2015 Tiancheng "Timothy" Gu + +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/escape-html/Readme.md b/node_modules/escape-html/Readme.md new file mode 100644 index 0000000..653d9ea --- /dev/null +++ b/node_modules/escape-html/Readme.md @@ -0,0 +1,43 @@ + +# escape-html + + Escape string for use in HTML + +## Example + +```js +var escape = require('escape-html'); +var html = escape('foo & bar'); +// -> foo & bar +``` + +## Benchmark + +``` +$ npm run-script bench + +> escape-html@1.0.3 bench nodejs-escape-html +> node benchmark/index.js + + + http_parser@1.0 + node@0.10.33 + v8@3.14.5.9 + ares@1.9.0-DEV + uv@0.10.29 + zlib@1.2.3 + modules@11 + openssl@1.0.1j + + 1 test completed. + 2 tests completed. + 3 tests completed. + + no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled) + single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled) + many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled) +``` + +## License + + MIT \ No newline at end of file diff --git a/node_modules/escape-html/index.js b/node_modules/escape-html/index.js new file mode 100644 index 0000000..bf9e226 --- /dev/null +++ b/node_modules/escape-html/index.js @@ -0,0 +1,78 @@ +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +'use strict'; + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} diff --git a/node_modules/escape-html/package.json b/node_modules/escape-html/package.json new file mode 100644 index 0000000..57ec7bd --- /dev/null +++ b/node_modules/escape-html/package.json @@ -0,0 +1,24 @@ +{ + "name": "escape-html", + "description": "Escape string for use in HTML", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "escape", + "html", + "utility" + ], + "repository": "component/escape-html", + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4" + }, + "files": [ + "LICENSE", + "Readme.md", + "index.js" + ], + "scripts": { + "bench": "node benchmark/index.js" + } +} diff --git a/node_modules/etag/HISTORY.md b/node_modules/etag/HISTORY.md new file mode 100644 index 0000000..222b293 --- /dev/null +++ b/node_modules/etag/HISTORY.md @@ -0,0 +1,83 @@ +1.8.1 / 2017-09-12 +================== + + * perf: replace regular expression with substring + +1.8.0 / 2017-02-18 +================== + + * Use SHA1 instead of MD5 for ETag hashing + - Improves performance for larger entities + - Works with FIPS 140-2 OpenSSL configuration + +1.7.0 / 2015-06-08 +================== + + * Always include entity length in ETags for hash length extensions + * Generate non-Stats ETags using MD5 only (no longer CRC32) + * Improve stat performance by removing hashing + * Remove base64 padding in ETags to shorten + * Use MD5 instead of MD4 in weak ETags over 1KB + +1.6.0 / 2015-05-10 +================== + + * Improve support for JXcore + * Remove requirement of `atime` in the stats object + * Support "fake" stats objects in environments without `fs` + +1.5.1 / 2014-11-19 +================== + + * deps: crc@3.2.1 + - Minor fixes + +1.5.0 / 2014-10-14 +================== + + * Improve string performance + * Slightly improve speed for weak ETags over 1KB + +1.4.0 / 2014-09-21 +================== + + * Support "fake" stats objects + * Support Node.js 0.6 + +1.3.1 / 2014-09-14 +================== + + * Use the (new and improved) `crc` for crc32 + +1.3.0 / 2014-08-29 +================== + + * Default strings to strong ETags + * Improve speed for weak ETags over 1KB + +1.2.1 / 2014-08-29 +================== + + * Use the (much faster) `buffer-crc32` for crc32 + +1.2.0 / 2014-08-24 +================== + + * Add support for file stat objects + +1.1.0 / 2014-08-24 +================== + + * Add fast-path for empty entity + * Add weak ETag generation + * Shrink size of generated ETags + +1.0.1 / 2014-08-24 +================== + + * Fix behavior of string containing Unicode + +1.0.0 / 2014-05-18 +================== + + * Initial release diff --git a/node_modules/etag/LICENSE b/node_modules/etag/LICENSE new file mode 100644 index 0000000..cab251c --- /dev/null +++ b/node_modules/etag/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 Douglas Christopher Wilson + +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/etag/README.md b/node_modules/etag/README.md new file mode 100644 index 0000000..09c2169 --- /dev/null +++ b/node_modules/etag/README.md @@ -0,0 +1,159 @@ +# etag + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create simple HTTP ETags + +This module generates HTTP ETags (as defined in RFC 7232) for use in +HTTP responses. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install etag +``` + +## API + + + +```js +var etag = require('etag') +``` + +### etag(entity, [options]) + +Generate a strong ETag for the given entity. This should be the complete +body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By +default, a strong ETag is generated except for `fs.Stats`, which will +generate a weak ETag (this can be overwritten by `options.weak`). + + + +```js +res.setHeader('ETag', etag(body)) +``` + +#### Options + +`etag` accepts these properties in the options object. + +##### weak + +Specifies if the generated ETag will include the weak validator mark (that +is, the leading `W/`). The actual entity tag is the same. The default value +is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +```bash +$ npm run-script bench + +> etag@1.8.1 bench nodejs-etag +> node benchmark/index.js + + http_parser@2.7.0 + node@6.11.1 + v8@5.1.281.103 + uv@1.11.0 + zlib@1.2.11 + ares@1.10.1-DEV + icu@58.2 + modules@48 + openssl@1.0.2k + +> node benchmark/body0-100b.js + + 100B body + + 4 tests completed. + + buffer - strong x 258,647 ops/sec ±1.07% (180 runs sampled) + buffer - weak x 263,812 ops/sec ±0.61% (184 runs sampled) + string - strong x 259,955 ops/sec ±1.19% (185 runs sampled) + string - weak x 264,356 ops/sec ±1.09% (184 runs sampled) + +> node benchmark/body1-1kb.js + + 1KB body + + 4 tests completed. + + buffer - strong x 189,018 ops/sec ±1.12% (182 runs sampled) + buffer - weak x 190,586 ops/sec ±0.81% (186 runs sampled) + string - strong x 144,272 ops/sec ±0.96% (188 runs sampled) + string - weak x 145,380 ops/sec ±1.43% (187 runs sampled) + +> node benchmark/body2-5kb.js + + 5KB body + + 4 tests completed. + + buffer - strong x 92,435 ops/sec ±0.42% (188 runs sampled) + buffer - weak x 92,373 ops/sec ±0.58% (189 runs sampled) + string - strong x 48,850 ops/sec ±0.56% (186 runs sampled) + string - weak x 49,380 ops/sec ±0.56% (190 runs sampled) + +> node benchmark/body3-10kb.js + + 10KB body + + 4 tests completed. + + buffer - strong x 55,989 ops/sec ±0.93% (188 runs sampled) + buffer - weak x 56,148 ops/sec ±0.55% (190 runs sampled) + string - strong x 27,345 ops/sec ±0.43% (188 runs sampled) + string - weak x 27,496 ops/sec ±0.45% (190 runs sampled) + +> node benchmark/body4-100kb.js + + 100KB body + + 4 tests completed. + + buffer - strong x 7,083 ops/sec ±0.22% (190 runs sampled) + buffer - weak x 7,115 ops/sec ±0.26% (191 runs sampled) + string - strong x 3,068 ops/sec ±0.34% (190 runs sampled) + string - weak x 3,096 ops/sec ±0.35% (190 runs sampled) + +> node benchmark/stats.js + + stat + + 4 tests completed. + + real - strong x 871,642 ops/sec ±0.34% (189 runs sampled) + real - weak x 867,613 ops/sec ±0.39% (190 runs sampled) + fake - strong x 401,051 ops/sec ±0.40% (189 runs sampled) + fake - weak x 400,100 ops/sec ±0.47% (188 runs sampled) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/etag.svg +[npm-url]: https://npmjs.org/package/etag +[node-version-image]: https://img.shields.io/node/v/etag.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/etag/master.svg +[travis-url]: https://travis-ci.org/jshttp/etag +[coveralls-image]: https://img.shields.io/coveralls/jshttp/etag/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master +[downloads-image]: https://img.shields.io/npm/dm/etag.svg +[downloads-url]: https://npmjs.org/package/etag diff --git a/node_modules/etag/index.js b/node_modules/etag/index.js new file mode 100644 index 0000000..2a585c9 --- /dev/null +++ b/node_modules/etag/index.js @@ -0,0 +1,131 @@ +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = etag + +/** + * Module dependencies. + * @private + */ + +var crypto = require('crypto') +var Stats = require('fs').Stats + +/** + * Module variables. + * @private + */ + +var toString = Object.prototype.toString + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } + + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + + return '"' + size + '-' + mtime + '"' +} diff --git a/node_modules/etag/package.json b/node_modules/etag/package.json new file mode 100644 index 0000000..b06ab80 --- /dev/null +++ b/node_modules/etag/package.json @@ -0,0 +1,47 @@ +{ + "name": "etag", + "description": "Create simple HTTP ETags", + "version": "1.8.1", + "contributors": [ + "Douglas Christopher Wilson ", + "David Björklund " + ], + "license": "MIT", + "keywords": [ + "etag", + "http", + "res" + ], + "repository": "jshttp/etag", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5", + "safe-buffer": "5.1.1", + "seedrandom": "2.4.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/express/History.md b/node_modules/express/History.md new file mode 100644 index 0000000..6e62a6d --- /dev/null +++ b/node_modules/express/History.md @@ -0,0 +1,3477 @@ +4.17.1 / 2019-05-25 +=================== + + * Revert "Improve error message for `null`/`undefined` to `res.status`" + +4.17.0 / 2019-05-16 +=================== + + * Add `express.raw` to parse bodies into `Buffer` + * Add `express.text` to parse bodies into string + * Improve error message for non-strings to `res.sendFile` + * Improve error message for `null`/`undefined` to `res.status` + * Support multiple hosts in `X-Forwarded-Host` + * deps: accepts@~1.3.7 + * deps: body-parser@1.19.0 + - Add encoding MIK + - Add petabyte (`pb`) support + - Fix parsing array brackets after index + - deps: bytes@3.1.0 + - deps: http-errors@1.7.2 + - deps: iconv-lite@0.4.24 + - deps: qs@6.7.0 + - deps: raw-body@2.4.0 + - deps: type-is@~1.6.17 + * deps: content-disposition@0.5.3 + * deps: cookie@0.4.0 + - Add `SameSite=None` support + * deps: finalhandler@~1.1.2 + - Set stricter `Content-Security-Policy` header + - deps: parseurl@~1.3.3 + - deps: statuses@~1.5.0 + * deps: parseurl@~1.3.3 + * deps: proxy-addr@~2.0.5 + - deps: ipaddr.js@1.9.0 + * deps: qs@6.7.0 + - Fix parsing array brackets after index + * deps: range-parser@~1.2.1 + * deps: send@0.17.1 + - Set stricter CSP header in redirect & error responses + - deps: http-errors@~1.7.2 + - deps: mime@1.6.0 + - deps: ms@2.1.1 + - deps: range-parser@~1.2.1 + - deps: statuses@~1.5.0 + - perf: remove redundant `path.normalize` call + * deps: serve-static@1.14.1 + - Set stricter CSP header in redirect response + - deps: parseurl@~1.3.3 + - deps: send@0.17.1 + * deps: setprototypeof@1.1.1 + * deps: statuses@~1.5.0 + - Add `103 Early Hints` + * deps: type-is@~1.6.18 + - deps: mime-types@~2.1.24 + - perf: prevent internal `throw` on invalid type + +4.16.4 / 2018-10-10 +=================== + + * Fix issue where `"Request aborted"` may be logged in `res.sendfile` + * Fix JSDoc for `Router` constructor + * deps: body-parser@1.18.3 + - Fix deprecation warnings on Node.js 10+ + - Fix stack trace for strict json parse error + - deps: depd@~1.1.2 + - deps: http-errors@~1.6.3 + - deps: iconv-lite@0.4.23 + - deps: qs@6.5.2 + - deps: raw-body@2.3.3 + - deps: type-is@~1.6.16 + * deps: proxy-addr@~2.0.4 + - deps: ipaddr.js@1.8.0 + * deps: qs@6.5.2 + * deps: safe-buffer@5.1.2 + +4.16.3 / 2018-03-12 +=================== + + * deps: accepts@~1.3.5 + - deps: mime-types@~2.1.18 + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: finalhandler@1.1.1 + - Fix 404 output for bad / missing pathnames + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: proxy-addr@~2.0.3 + - deps: ipaddr.js@1.6.0 + * deps: send@0.16.2 + - Fix incorrect end tag in default error & redirects + - deps: depd@~1.1.2 + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: serve-static@1.13.2 + - Fix incorrect end tag in redirects + - deps: encodeurl@~1.0.2 + - deps: send@0.16.2 + * deps: statuses@~1.4.0 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +4.16.2 / 2017-10-09 +=================== + + * Fix `TypeError` in `res.send` when given `Buffer` and `ETag` header set + * perf: skip parsing of entire `X-Forwarded-Proto` header + +4.16.1 / 2017-09-29 +=================== + + * deps: send@0.16.1 + * deps: serve-static@1.13.1 + - Fix regression when `root` is incorrectly set to a file + - deps: send@0.16.1 + +4.16.0 / 2017-09-28 +=================== + + * Add `"json escape"` setting for `res.json` and `res.jsonp` + * Add `express.json` and `express.urlencoded` to parse bodies + * Add `options` argument to `res.download` + * Improve error message when autoloading invalid view engine + * Improve error messages when non-function provided as middleware + * Skip `Buffer` encoding when not generating ETag for small response + * Use `safe-buffer` for improved Buffer API + * deps: accepts@~1.3.4 + - deps: mime-types@~2.1.16 + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: finalhandler@1.1.0 + - Use `res.headersSent` when available + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: proxy-addr@~2.0.2 + - Fix trimming leading / trailing OWS in `X-Forwarded-For` + - deps: forwarded@~0.1.2 + - deps: ipaddr.js@1.5.2 + - perf: reduce overhead when no `X-Forwarded-For` header + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: send@0.16.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Fix missing `` in default error & redirects + - Set charset as "UTF-8" for .js and .json + - Use instance methods on steam to check for listeners + - deps: mime@1.4.1 + - perf: improve path validation speed + * deps: serve-static@1.13.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Set charset as "UTF-8" for .js and .json + - deps: send@0.16.0 + * deps: setprototypeof@1.1.0 + * deps: utils-merge@1.0.1 + * deps: vary@~1.1.2 + - perf: improve header token parsing speed + * perf: re-use options object when generating ETags + * perf: remove dead `.charset` set in `res.jsonp` + +4.15.5 / 2017-09-24 +=================== + + * deps: debug@2.6.9 + * deps: finalhandler@~1.0.6 + - deps: debug@2.6.9 + - deps: parseurl@~1.3.2 + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + * deps: send@0.15.6 + - Fix handling of modified headers with invalid dates + - deps: debug@2.6.9 + - deps: etag@~1.8.1 + - deps: fresh@0.5.2 + - perf: improve `If-Match` token parsing + * deps: serve-static@1.12.6 + - deps: parseurl@~1.3.2 + - deps: send@0.15.6 + - perf: improve slash collapsing + +4.15.4 / 2017-08-06 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: finalhandler@~1.0.4 + - deps: debug@2.6.8 + * deps: proxy-addr@~1.1.5 + - Fix array argument being altered + - deps: ipaddr.js@1.4.0 + * deps: qs@6.5.0 + * deps: send@0.15.4 + - deps: debug@2.6.8 + - deps: depd@~1.1.1 + - deps: http-errors@~1.6.2 + * deps: serve-static@1.12.4 + - deps: send@0.15.4 + +4.15.3 / 2017-05-16 +=================== + + * Fix error when `res.set` cannot add charset to `Content-Type` + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: finalhandler@~1.0.3 + - Fix missing `` in HTML document + - deps: debug@2.6.7 + * deps: proxy-addr@~1.1.4 + - deps: ipaddr.js@1.3.0 + * deps: send@0.15.3 + - deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: serve-static@1.12.3 + - deps: send@0.15.3 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + * deps: vary@~1.1.1 + - perf: hoist regular expression + +4.15.2 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +4.15.1 / 2017-03-05 +=================== + + * deps: send@0.15.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - Fix strict violation in broken environments + * deps: serve-static@1.12.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - deps: send@0.15.1 + +4.15.0 / 2017-03-01 +=================== + + * Add debug message when loading view engine + * Add `next("router")` to exit from router + * Fix case where `router.use` skipped requests routes did not + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Skip routing when `req.url` is not set + * Use `%o` in path debug to tell types apart + * Use `Object.create` to setup request & response prototypes + * Use `setprototypeof` module to replace `__proto__` setting + * Use `statuses` instead of `http` module for status messages + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + - Use SHA1 instead of MD5 for ETag hashing + - Works with FIPS 140-2 OpenSSL configuration + * deps: finalhandler@~1.0.0 + - Fix exception when `err` cannot be converted to a string + - Fully URL-encode the pathname in the 404 + - Only include the pathname in the 404 message + - Send complete HTML document + - Set `Content-Security-Policy: default-src 'self'` header + - deps: debug@2.6.1 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: qs@6.3.1 + - Fix array parsing from skipping empty values + - Fix compacting nested arrays + * deps: send@0.15.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: debug@2.6.1 + - deps: etag@~1.8.0 + - deps: fresh@0.5.0 + - deps: http-errors@~1.6.1 + * deps: serve-static@1.12.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Send complete HTML document in redirect response + - Set default CSP header in redirect response + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: send@0.15.0 + * perf: add fast match path for `*` route + * perf: improve `req.ips` performance + +4.14.1 / 2017-01-28 +=================== + + * deps: content-disposition@0.5.2 + * deps: finalhandler@0.5.1 + - Fix exception when `err.headers` is not an object + - deps: statuses@~1.3.1 + - perf: hoist regular expressions + - perf: remove duplicate validation path + * deps: proxy-addr@~1.1.3 + - deps: ipaddr.js@1.2.0 + * deps: send@0.14.2 + - deps: http-errors@~1.5.1 + - deps: ms@0.7.2 + - deps: statuses@~1.3.1 + * deps: serve-static@~1.11.2 + - deps: send@0.14.2 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +4.14.0 / 2016-06-16 +=================== + + * Add `acceptRanges` option to `res.sendFile`/`res.sendfile` + * Add `cacheControl` option to `res.sendFile`/`res.sendfile` + * Add `options` argument to `req.range` + - Includes the `combine` option + * Encode URL in `res.location`/`res.redirect` if not already encoded + * Fix some redirect handling in `res.sendFile`/`res.sendfile` + * Fix Windows absolute path check using forward slashes + * Improve error with invalid arguments to `req.get()` + * Improve performance for `res.json`/`res.jsonp` in most cases + * Improve `Range` header handling in `res.sendFile`/`res.sendfile` + * deps: accepts@~1.3.3 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Many performance improvements + - deps: mime-types@~2.1.11 + - deps: negotiator@0.6.1 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: cookie@0.3.1 + - Add `sameSite` option + - Fix cookie `Max-Age` to never be a floating point number + - Improve error message when `encode` is not a function + - Improve error message when `expires` is not a `Date` + - Throw better error for invalid argument to parse + - Throw on invalid values provided to `serialize` + - perf: enable strict mode + - perf: hoist regular expression + - perf: use for loop in parse + - perf: use string concatenation for serialization + * deps: finalhandler@0.5.0 + - Change invalid or non-numeric status code to 500 + - Overwrite status message to match set status code + - Prefer `err.statusCode` if `err.status` is invalid + - Set response headers from `err.headers` object + - Use `statuses` instead of `http` module for status messages + * deps: proxy-addr@~1.1.2 + - Fix accepting various invalid netmasks + - Fix IPv6-mapped IPv4 validation edge cases + - IPv4 netmasks must be contiguous + - IPv6 addresses cannot be used as a netmask + - deps: ipaddr.js@1.1.1 + * deps: qs@6.2.0 + - Add `decoder` option in `parse` function + * deps: range-parser@~1.2.0 + - Add `combine` option to combine overlapping ranges + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: send@0.14.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Correctly inherit from `Stream` class + - Fix `Content-Range` header in 416 responses when using `start`/`end` options + - Fix `Content-Range` header missing from default 416 responses + - Fix redirect error when `path` contains raw non-URL characters + - Fix redirect when `path` starts with multiple forward slashes + - Ignore non-byte `Range` headers + - deps: http-errors@~1.5.0 + - deps: range-parser@~1.2.0 + - deps: statuses@~1.3.0 + - perf: remove argument reassignment + * deps: serve-static@~1.11.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Fix redirect error when `req.url` contains raw non-URL characters + - Ignore non-byte `Range` headers + - Use status code 301 for redirects + - deps: send@0.14.1 + * deps: type-is@~1.6.13 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.11 + * deps: vary@~1.1.0 + - Only accept valid field names in the `field` argument + * perf: use strict equality when possible + +4.13.4 / 2016-01-21 +=================== + + * deps: content-disposition@0.5.1 + - perf: enable strict mode + * deps: cookie@0.1.5 + - Throw on invalid values provided to `serialize` + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: finalhandler@0.4.1 + - deps: escape-html@~1.0.3 + * deps: merge-descriptors@1.0.1 + - perf: enable strict mode + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + * deps: proxy-addr@~1.0.10 + - deps: ipaddr.js@1.0.5 + - perf: enable strict mode + * deps: range-parser@~1.0.3 + - perf: enable strict mode + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + * deps: serve-static@~1.10.2 + - deps: escape-html@~1.0.3 + - deps: parseurl@~1.3.0 + - deps: send@0.13.1 + +4.13.3 / 2015-08-02 +=================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + +4.13.2 / 2015-07-31 +=================== + + * deps: accepts@~1.2.12 + - deps: mime-types@~2.1.4 + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +4.13.1 / 2015-07-05 +=================== + + * deps: accepts@~1.2.10 + - deps: mime-types@~2.1.2 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +4.13.0 / 2015-06-20 +=================== + + * Add settings to debug output + * Fix `res.format` error when only `default` provided + * Fix issue where `next('route')` in `app.param` would incorrectly skip values + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * Simplify `res.cookie` to call `res.append` + * Use `array-flatten` module for flattening arrays + * deps: accepts@~1.2.9 + - deps: mime-types@~2.1.1 + - perf: avoid argument reassignment & argument slice + - perf: avoid negotiator recursive construction + - perf: enable strict mode + - perf: remove unnecessary bitwise operator + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: finalhandler@0.4.0 + - Fix a false-positive when unpiping in Node.js 0.8 + - Support `statusCode` property on `Error` objects + - Use `unpipe` module for unpiping requests + - deps: escape-html@1.0.2 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: path-to-regexp@0.1.6 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * deps: serve-static@~1.10.0 + - Add `fallthrough` option + - Fix reading options from options prototype + - Improve the default redirect response headers + - Malformed URLs now `next()` instead of 400 + - deps: escape-html@1.0.2 + - deps: send@0.13.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: isolate `app.render` try block + * perf: remove argument reassignments in application + * perf: remove argument reassignments in request prototype + * perf: remove argument reassignments in response prototype + * perf: remove argument reassignments in routing + * perf: remove argument reassignments in `View` + * perf: skip attempting to decode zero length string + * perf: use saved reference to `http.STATUS_CODES` + +4.12.4 / 2015-05-17 +=================== + + * deps: accepts@~1.2.7 + - deps: mime-types@~2.0.11 + - deps: negotiator@0.5.3 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: finalhandler@0.3.6 + - deps: debug@~2.2.0 + - deps: on-finished@~2.2.1 + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + * deps: serve-static@~1.9.3 + - deps: send@0.12.3 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +4.12.3 / 2015-03-17 +=================== + + * deps: accepts@~1.2.5 + - deps: mime-types@~2.0.10 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: finalhandler@0.3.4 + - deps: debug@~2.1.3 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + * deps: serve-static@~1.9.2 + - deps: send@0.12.2 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +4.12.2 / 2015-03-02 +=================== + + * Fix regression where `"Request aborted"` is logged using `res.sendFile` + +4.12.1 / 2015-03-01 +=================== + + * Fix constructing application with non-configurable prototype properties + * Fix `ECONNRESET` errors from `res.sendFile` usage + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + * Fix wrong `code` on aborted connections from `res.sendFile` + * deps: merge-descriptors@1.0.0 + +4.12.0 / 2015-02-23 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: accepts@~1.2.4 + - Fix preference sorting to be stable for long acceptable lists + - deps: mime-types@~2.0.9 + - deps: negotiator@0.5.1 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + * deps: serve-static@~1.9.1 + - deps: send@0.12.1 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +4.11.2 / 2015-02-01 +=================== + + * Fix `res.redirect` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.2.3 + - deps: mime-types@~2.0.8 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +4.11.1 / 2015-01-20 +=================== + + * deps: send@0.11.1 + - Fix root path disclosure + * deps: serve-static@~1.8.1 + - Fix redirect loop in Node.js 0.11.14 + - Fix root path disclosure + - deps: send@0.11.1 + +4.11.0 / 2015-01-13 +=================== + + * Add `res.append(field, val)` to append headers + * Deprecate leading `:` in `name` for `app.param(name, fn)` + * Deprecate `req.param()` -- use `req.params`, `req.body`, or `req.query` instead + * Deprecate `app.param(fn)` + * Fix `OPTIONS` responses to include the `HEAD` method properly + * Fix `res.sendFile` not always detecting aborted connection + * Match routes iteratively to prevent stack overflows + * deps: accepts@~1.2.2 + - deps: mime-types@~2.0.7 + - deps: negotiator@0.5.0 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + * deps: serve-static@~1.8.0 + - deps: send@0.11.0 + +4.10.8 / 2015-01-13 +=================== + + * Fix crash from error within `OPTIONS` response handler + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + +4.10.7 / 2015-01-04 +=================== + + * Fix `Allow` header for `OPTIONS` to not contain duplicate methods + * Fix incorrect "Request aborted" for `res.sendFile` when `HEAD` or 304 + * deps: debug@~2.1.1 + * deps: finalhandler@0.3.3 + - deps: debug@~2.1.1 + - deps: on-finished@~2.2.0 + * deps: methods@~1.1.1 + * deps: on-finished@~2.2.0 + * deps: serve-static@~1.7.2 + - Fix potential open redirect when mounted at root + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +4.10.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +4.10.5 / 2014-12-10 +=================== + + * Fix `res.send` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.1.4 + - deps: mime-types@~2.0.4 + * deps: type-is@~1.5.4 + - deps: mime-types@~2.0.4 + +4.10.4 / 2014-11-24 +=================== + + * Fix `res.sendfile` logging standard write errors + +4.10.3 / 2014-11-23 +=================== + + * Fix `res.sendFile` logging standard write errors + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + +4.10.2 / 2014-11-09 +=================== + + * Correctly invoke async router callback asynchronously + * deps: accepts@~1.1.3 + - deps: mime-types@~2.0.3 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +4.10.1 / 2014-10-28 +=================== + + * Fix handling of URLs containing `://` in the path + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +4.10.0 / 2014-10-23 +=================== + + * Add support for `app.set('views', array)` + - Views are looked up in sequence in array of directories + * Fix `res.send(status)` to mention `res.sendStatus(status)` + * Fix handling of invalid empty URLs + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `path.resolve` in view lookup + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + * deps: finalhandler@0.3.2 + - Terminate in progress response only on error + - Use `on-finished` to determine request status + - deps: debug@~2.1.0 + - deps: on-finished@~2.1.1 + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: send@0.10.1 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + - deps: on-finished@~2.1.1 + * deps: serve-static@~1.7.1 + - deps: send@0.10.1 + +4.9.8 / 2014-10-17 +================== + + * Fix `res.redirect` body when redirect status specified + * deps: accepts@~1.1.2 + - Fix error when media type has invalid parameter + - deps: negotiator@0.4.9 + +4.9.7 / 2014-10-10 +================== + + * Fix using same param name in array of paths + +4.9.6 / 2014-10-08 +================== + + * deps: accepts@~1.1.1 + - deps: mime-types@~2.0.2 + - deps: negotiator@0.4.8 + * deps: serve-static@~1.6.4 + - Fix redirect loop when index file serving disabled + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +4.9.5 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + * deps: serve-static@~1.6.3 + - deps: send@0.9.3 + +4.9.4 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +4.9.3 / 2014-09-18 +================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +4.9.2 / 2014-09-17 +================== + + * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path + * Improve error message for bad `app.use` arguments + +4.9.1 / 2014-09-16 +================== + + * Fix `app.use` to accept array of middleware without path + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + * deps: serve-static@~1.6.2 + - deps: send@0.9.2 + +4.9.0 / 2014-09-08 +================== + + * Add `res.sendStatus` + * Invoke callback for sendfile when client aborts + - Applies to `res.sendFile`, `res.sendfile`, and `res.download` + - `err` will be populated with request aborted error + * Support IP address host in `req.subdomains` + * Use `etag` to generate `ETag` headers + * deps: accepts@~1.1.0 + - update `mime-types` + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: finalhandler@0.2.0 + - Set `X-Content-Type-Options: nosniff` header + - deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: serve-static@~1.6.1 + - Add `lastModified` option + - deps: send@0.9.1 + * deps: type-is@~1.5.1 + - fix `hasbody` to be true for `content-length: 0` + - deps: media-typer@0.3.0 + - deps: mime-types@~2.0.1 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +4.8.8 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + * deps: serve-static@~1.5.4 + - deps: send@0.8.5 + +4.8.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +4.8.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +4.8.5 / 2014-08-18 +================== + + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + * deps: serve-static@~1.5.3 + - deps: send@0.8.3 + +4.8.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: serve-static@~1.5.2 + - deps: send@0.8.2 + +4.8.3 / 2014-08-10 +================== + + * deps: parseurl@~1.3.0 + * deps: qs@1.2.1 + * deps: serve-static@~1.5.1 + - Fix parsing of weird `req.originalUrl` values + - deps: parseurl@~1.3.0 + - deps: utils-merge@1.0.0 + +4.8.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +4.8.1 / 2014-08-06 +================== + + * fix incorrect deprecation warnings on `res.download` + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +4.8.0 / 2014-08-05 +================== + + * add `res.sendFile` + - accepts a file system path instead of a URL + - requires an absolute path or `root` option specified + * deprecate `res.sendfile` -- use `res.sendFile` instead + * support mounted app as any argument to `app.use()` + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + * deps: send@0.8.1 + - Add `extensions` option + * deps: serve-static@~1.5.0 + - Add `extensions` option + - deps: send@0.8.1 + +4.7.4 / 2014-08-04 +================== + + * fix `res.sendfile` regression for serving directory index files + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + * deps: serve-static@~1.4.4 + - deps: send@0.7.4 + +4.7.3 / 2014-08-04 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + * deps: serve-static@~1.4.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + - deps: send@0.7.3 + +4.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + * deps: serve-static@~1.4.2 + +4.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + * deps: serve-static@~1.4.1 + +4.7.0 / 2014-07-25 +================== + + * fix `req.protocol` for proxy-direct connections + * configurable query parser with `app.set('query parser', parser)` + - `app.set('query parser', 'extended')` parse with "qs" module + - `app.set('query parser', 'simple')` parse with "querystring" core module + - `app.set('query parser', false)` disable query string parsing + - `app.set('query parser', true)` enable simple parsing + * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead + * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead + * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: finalhandler@0.1.0 + - Respond after request fully read + - deps: debug@1.0.4 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + * deps: serve-static@~1.4.0 + - deps: parseurl@~1.2.0 + - deps: send@0.7.0 + * perf: prevent multiple `Buffer` creation in `res.send` + +4.6.1 / 2014-07-12 +================== + + * fix `subapp.mountpath` regression for `app.use(subapp)` + +4.6.0 / 2014-07-11 +================== + + * accept multiple callbacks to `app.use()` + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * catch errors in multiple `req.param(name, fn)` handlers + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * support non-string `path` in `app.use(path, fn)` + - supports array of paths + - supports `RegExp` + * router: fix optimization on router exit + * router: refactor location of `try` blocks + * router: speed up standard `app.use(fn)` + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: finalhandler@0.0.3 + - deps: debug@1.0.3 + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + * deps: path-to-regexp@0.1.3 + * deps: send@0.6.0 + - deps: debug@1.0.3 + * deps: serve-static@~1.3.2 + - deps: parseurl@~1.1.3 + - deps: send@0.6.0 + * perf: fix arguments reassign deopt in some `res` methods + +4.5.1 / 2014-07-06 +================== + + * fix routing regression when altering `req.method` + +4.5.0 / 2014-07-04 +================== + + * add deprecation message to non-plural `req.accepts*` + * add deprecation message to `res.send(body, status)` + * add deprecation message to `res.vary()` + * add `headers` option to `res.sendfile` + - use to set headers on successful file transfer + * add `mergeParams` option to `Router` + - merges `req.params` from parent routes + * add `req.hostname` -- correct name for what `req.host` returns + * deprecate things with `depd` module + * deprecate `req.host` -- use `req.hostname` instead + * fix behavior when handling request without routes + * fix handling when `route.all` is only route + * invoke `router.param()` only when route matches + * restore `req.params` after invoking router + * use `finalhandler` for final response handling + * use `media-typer` to alter content-type charset + * deps: accepts@~1.0.7 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + * deps: serve-static@~1.3.0 + - Accept string for `maxAge` (converted by `ms`) + - Add `setHeaders` option + - Include HTML link in redirect response + - deps: send@0.5.0 + * deps: type-is@~1.3.2 + +4.4.5 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +4.4.4 / 2014-06-20 +================== + + * fix `res.attachment` Unicode filenames in Safari + * fix "trim prefix" debug message in `express:router` + * deps: accepts@~1.0.5 + * deps: buffer-crc32@0.2.3 + +4.4.3 / 2014-06-11 +================== + + * fix persistence of modified `req.params[name]` from `app.param()` + * deps: accepts@1.0.3 + - deps: negotiator@0.4.6 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw uncatchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + * deps: serve-static@1.2.3 + - Do not throw uncatchable error on file open race condition + - deps: send@0.4.3 + +4.4.2 / 2014-06-09 +================== + + * fix catching errors from top-level handlers + * use `vary` module for `res.vary` + * deps: debug@1.0.1 + * deps: proxy-addr@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + * deps: serve-static@1.2.2 + - fix "event emitter leak" warnings + - deps: send@0.4.2 + * deps: type-is@1.2.1 + +4.4.1 / 2014-06-02 +================== + + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + * deps: serve-static@1.2.1 + - use `escape-html` for escaping + - deps: send@0.4.1 + +4.4.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * mark `res.send` ETag as weak and reduce collisions + * update accepts to 1.0.2 + - Fix interpretation when header not in request + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + * update serve-static to 1.2.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: send@0.4.0 + +4.3.2 / 2014-05-28 +================== + + * fix handling of errors from `router.param()` callbacks + +4.3.1 / 2014-05-23 +================== + + * revert "fix behavior of multiple `app.VERB` for the same path" + - this caused a regression in the order of route execution + +4.3.0 / 2014-05-21 +================== + + * add `req.baseUrl` to access the path stripped from `req.url` in routes + * fix behavior of multiple `app.VERB` for the same path + * fix issue routing requests among sub routers + * invoke `router.param()` only when necessary instead of every match + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * set proper `charset` in `Content-Type` for `res.send` + * update type-is to 1.2.0 + - support suffix matching + +4.2.0 / 2014-05-11 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * fix `req.next` when inside router instance + * include `ETag` header in `HEAD` requests + * keep previous `Content-Type` for `res.jsonp` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update debug to 0.8.0 + - add `enable()` method + - change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + - deps: negotiator@0.4.0 + * update cookie to 0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + * update send to 0.3.0 + - Accept API options in options object + - Coerce option types + - Control whether to generate etags + - Default directory access to 403 when index disabled + - Fix sending files with dots without root set + - Include file path in etag + - Make "Can't set headers after they are sent." catchable + - Send full entity-body for multi range requests + - Set etags to "weak" + - Support "If-Range" header + - Support multiple index paths + - deps: mime@1.2.11 + * update serve-static to 1.1.0 + - Accept options directly to `send` module + - Resolve relative paths at middleware setup + - Use parseurl to parse the URL from request + - deps: send@0.3.0 + * update type-is to 1.1.0 + - add non-array values support + - add `multipart` as a shorthand + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.21.2 / 2015-07-31 +=================== + + * deps: connect@2.30.2 + - deps: body-parser@~1.13.3 + - deps: compression@~1.5.2 + - deps: errorhandler@~1.4.2 + - deps: method-override@~2.3.5 + - deps: serve-index@~1.7.2 + - deps: type-is@~1.6.6 + - deps: vhost@~3.0.1 + * deps: vary@~1.0.1 + - Fix setting empty header from empty `field` + - perf: enable strict mode + - perf: remove argument reassignments + +3.21.1 / 2015-07-05 +=================== + + * deps: basic-auth@~1.0.3 + * deps: connect@2.30.1 + - deps: body-parser@~1.13.2 + - deps: compression@~1.5.1 + - deps: errorhandler@~1.4.1 + - deps: morgan@~1.6.1 + - deps: pause@0.1.0 + - deps: qs@4.0.0 + - deps: serve-index@~1.7.1 + - deps: type-is@~1.6.4 + +3.21.0 / 2015-06-18 +=================== + + * deps: basic-auth@1.0.2 + - perf: enable strict mode + - perf: hoist regular expression + - perf: parse with regular expressions + - perf: remove argument reassignment + * deps: connect@2.30.0 + - deps: body-parser@~1.13.1 + - deps: bytes@2.1.0 + - deps: compression@~1.5.0 + - deps: cookie@0.1.3 + - deps: cookie-parser@~1.3.5 + - deps: csurf@~1.8.3 + - deps: errorhandler@~1.4.0 + - deps: express-session@~1.11.3 + - deps: finalhandler@0.4.0 + - deps: fresh@0.3.0 + - deps: morgan@~1.6.0 + - deps: serve-favicon@~2.3.0 + - deps: serve-index@~1.7.0 + - deps: serve-static@~1.10.0 + - deps: type-is@~1.6.3 + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: mkdirp@0.5.1 + - Work in global strict mode + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + +3.20.3 / 2015-05-17 +=================== + + * deps: connect@2.29.2 + - deps: body-parser@~1.12.4 + - deps: compression@~1.4.4 + - deps: connect-timeout@~1.6.2 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: errorhandler@~1.3.6 + - deps: finalhandler@0.3.6 + - deps: method-override@~2.3.3 + - deps: morgan@~1.5.3 + - deps: qs@2.4.2 + - deps: response-time@~2.3.1 + - deps: serve-favicon@~2.2.1 + - deps: serve-index@~1.6.4 + - deps: serve-static@~1.9.3 + - deps: type-is@~1.6.2 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +3.20.2 / 2015-03-16 +=================== + + * deps: connect@2.29.1 + - deps: body-parser@~1.12.2 + - deps: compression@~1.4.3 + - deps: connect-timeout@~1.6.1 + - deps: debug@~2.1.3 + - deps: errorhandler@~1.3.5 + - deps: express-session@~1.10.4 + - deps: finalhandler@0.3.4 + - deps: method-override@~2.3.2 + - deps: morgan@~1.5.2 + - deps: qs@2.4.1 + - deps: serve-index@~1.6.3 + - deps: serve-static@~1.9.2 + - deps: type-is@~1.6.1 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: merge-descriptors@1.0.0 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +3.20.1 / 2015-02-28 +=================== + + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + +3.20.0 / 2015-02-18 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: connect@2.29.0 + - Use `content-type` to parse `Content-Type` headers + - deps: body-parser@~1.12.0 + - deps: compression@~1.4.1 + - deps: connect-timeout@~1.6.0 + - deps: cookie-parser@~1.3.4 + - deps: cookie-signature@1.0.6 + - deps: csurf@~1.7.0 + - deps: errorhandler@~1.3.4 + - deps: express-session@~1.10.3 + - deps: http-errors@~1.3.1 + - deps: response-time@~2.3.0 + - deps: serve-index@~1.6.2 + - deps: serve-static@~1.9.1 + - deps: type-is@~1.6.0 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +3.19.2 / 2015-02-01 +=================== + + * deps: connect@2.28.3 + - deps: compression@~1.3.1 + - deps: csurf@~1.6.6 + - deps: errorhandler@~1.3.3 + - deps: express-session@~1.10.2 + - deps: serve-index@~1.6.1 + - deps: type-is@~1.5.6 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + +3.19.1 / 2015-01-20 +=================== + + * deps: connect@2.28.2 + - deps: body-parser@~1.10.2 + - deps: serve-static@~1.8.1 + * deps: send@0.11.1 + - Fix root path disclosure + +3.19.0 / 2015-01-09 +=================== + + * Fix `OPTIONS` responses to include the `HEAD` method property + * Use `readline` for prompt in `express(1)` + * deps: commander@2.6.0 + * deps: connect@2.28.1 + - deps: body-parser@~1.10.1 + - deps: compression@~1.3.0 + - deps: connect-timeout@~1.5.0 + - deps: csurf@~1.6.4 + - deps: debug@~2.1.1 + - deps: errorhandler@~1.3.2 + - deps: express-session@~1.10.1 + - deps: finalhandler@0.3.3 + - deps: method-override@~2.3.1 + - deps: morgan@~1.5.1 + - deps: serve-favicon@~2.2.0 + - deps: serve-index@~1.6.0 + - deps: serve-static@~1.8.0 + - deps: type-is@~1.5.5 + * deps: debug@~2.1.1 + * deps: methods@~1.1.1 + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +3.18.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +3.18.5 / 2014-12-11 +=================== + + * deps: connect@2.27.6 + - deps: compression@~1.2.2 + - deps: express-session@~1.9.3 + - deps: http-errors@~1.2.8 + - deps: serve-index@~1.5.3 + - deps: type-is@~1.5.4 + +3.18.4 / 2014-11-23 +=================== + + * deps: connect@2.27.4 + - deps: body-parser@~1.9.3 + - deps: compression@~1.2.1 + - deps: errorhandler@~1.2.3 + - deps: express-session@~1.9.2 + - deps: qs@2.3.3 + - deps: serve-favicon@~2.1.7 + - deps: serve-static@~1.5.1 + - deps: type-is@~1.5.3 + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + +3.18.3 / 2014-11-09 +=================== + + * deps: connect@2.27.3 + - Correctly invoke async callback asynchronously + - deps: csurf@~1.6.3 + +3.18.2 / 2014-10-28 +=================== + + * deps: connect@2.27.2 + - Fix handling of URLs containing `://` in the path + - deps: body-parser@~1.9.2 + - deps: qs@2.3.2 + +3.18.1 / 2014-10-22 +=================== + + * Fix internal `utils.merge` deprecation warnings + * deps: connect@2.27.1 + - deps: body-parser@~1.9.1 + - deps: express-session@~1.9.1 + - deps: finalhandler@0.3.2 + - deps: morgan@~1.4.1 + - deps: qs@2.3.0 + - deps: serve-static@~1.7.1 + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +3.18.0 / 2014-10-17 +=================== + + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `etag` module to generate `ETag` headers + * deps: connect@2.27.0 + - Use `http-errors` module for creating errors + - Use `utils-merge` module for merging objects + - deps: body-parser@~1.9.0 + - deps: compression@~1.2.0 + - deps: connect-timeout@~1.4.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: express-session@~1.9.0 + - deps: finalhandler@0.3.1 + - deps: method-override@~2.3.0 + - deps: morgan@~1.4.0 + - deps: response-time@~2.2.0 + - deps: serve-favicon@~2.1.6 + - deps: serve-index@~1.5.0 + - deps: serve-static@~1.7.0 + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +3.17.8 / 2014-10-15 +=================== + + * deps: connect@2.26.6 + - deps: compression@~1.1.2 + - deps: csurf@~1.6.2 + - deps: errorhandler@~1.2.2 + +3.17.7 / 2014-10-08 +=================== + + * deps: connect@2.26.5 + - Fix accepting non-object arguments to `logger` + - deps: serve-static@~1.6.4 + +3.17.6 / 2014-10-02 +=================== + + * deps: connect@2.26.4 + - deps: morgan@~1.3.2 + - deps: type-is@~1.5.2 + +3.17.5 / 2014-09-24 +=================== + + * deps: connect@2.26.3 + - deps: body-parser@~1.8.4 + - deps: serve-favicon@~2.1.5 + - deps: serve-static@~1.6.3 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +3.17.4 / 2014-09-19 +=================== + + * deps: connect@2.26.2 + - deps: body-parser@~1.8.3 + - deps: qs@2.2.4 + +3.17.3 / 2014-09-18 +=================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +3.17.2 / 2014-09-15 +=================== + + * Use `crc` instead of `buffer-crc32` for speed + * deps: connect@2.26.1 + - deps: body-parser@~1.8.2 + - deps: depd@0.4.5 + - deps: express-session@~1.8.2 + - deps: morgan@~1.3.1 + - deps: serve-favicon@~2.1.3 + - deps: serve-static@~1.6.2 + * deps: depd@0.4.5 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +3.17.1 / 2014-09-08 +=================== + + * Fix error in `req.subdomains` on empty host + +3.17.0 / 2014-09-08 +=================== + + * Support `X-Forwarded-Host` in `req.subdomains` + * Support IP address host in `req.subdomains` + * deps: connect@2.26.0 + - deps: body-parser@~1.8.1 + - deps: compression@~1.1.0 + - deps: connect-timeout@~1.3.0 + - deps: cookie-parser@~1.3.3 + - deps: cookie-signature@1.0.5 + - deps: csurf@~1.6.1 + - deps: debug@~2.0.0 + - deps: errorhandler@~1.2.0 + - deps: express-session@~1.8.1 + - deps: finalhandler@0.2.0 + - deps: fresh@0.2.4 + - deps: media-typer@0.3.0 + - deps: method-override@~2.2.0 + - deps: morgan@~1.3.0 + - deps: qs@2.2.3 + - deps: serve-favicon@~2.1.3 + - deps: serve-index@~1.2.1 + - deps: serve-static@~1.6.1 + - deps: type-is@~1.5.1 + - deps: vhost@~3.0.0 + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +3.16.10 / 2014-09-04 +==================== + + * deps: connect@2.25.10 + - deps: serve-static@~1.5.4 + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +3.16.9 / 2014-08-29 +=================== + + * deps: connect@2.25.9 + - deps: body-parser@~1.6.7 + - deps: qs@2.2.2 + +3.16.8 / 2014-08-27 +=================== + + * deps: connect@2.25.8 + - deps: body-parser@~1.6.6 + - deps: csurf@~1.4.1 + - deps: qs@2.2.0 + +3.16.7 / 2014-08-18 +=================== + + * deps: connect@2.25.7 + - deps: body-parser@~1.6.5 + - deps: express-session@~1.7.6 + - deps: morgan@~1.2.3 + - deps: serve-static@~1.5.3 + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + +3.16.6 / 2014-08-14 +=================== + + * deps: connect@2.25.6 + - deps: body-parser@~1.6.4 + - deps: qs@1.2.2 + - deps: serve-static@~1.5.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +3.16.5 / 2014-08-11 +=================== + + * deps: connect@2.25.5 + - Fix backwards compatibility in `logger` + +3.16.4 / 2014-08-10 +=================== + + * Fix original URL parsing in `res.location` + * deps: connect@2.25.4 + - Fix `query` middleware breaking with argument + - deps: body-parser@~1.6.3 + - deps: compression@~1.0.11 + - deps: connect-timeout@~1.2.2 + - deps: express-session@~1.7.5 + - deps: method-override@~2.1.3 + - deps: on-headers@~1.0.0 + - deps: parseurl@~1.3.0 + - deps: qs@1.2.1 + - deps: response-time@~2.0.1 + - deps: serve-index@~1.1.6 + - deps: serve-static@~1.5.1 + * deps: parseurl@~1.3.0 + +3.16.3 / 2014-08-07 +=================== + + * deps: connect@2.25.3 + - deps: multiparty@3.3.2 + +3.16.2 / 2014-08-07 +=================== + + * deps: connect@2.25.2 + - deps: body-parser@~1.6.2 + - deps: qs@1.2.0 + +3.16.1 / 2014-08-06 +=================== + + * deps: connect@2.25.1 + - deps: body-parser@~1.6.1 + - deps: qs@1.1.0 + +3.16.0 / 2014-08-05 +=================== + + * deps: connect@2.25.0 + - deps: body-parser@~1.6.0 + - deps: compression@~1.0.10 + - deps: csurf@~1.4.0 + - deps: express-session@~1.7.4 + - deps: qs@1.0.2 + - deps: serve-static@~1.5.0 + * deps: send@0.8.1 + - Add `extensions` option + +3.15.3 / 2014-08-04 +=================== + + * fix `res.sendfile` regression for serving directory index files + * deps: connect@2.24.3 + - deps: serve-index@~1.1.5 + - deps: serve-static@~1.4.4 + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + +3.15.2 / 2014-07-27 +=================== + + * deps: connect@2.24.2 + - deps: body-parser@~1.5.2 + - deps: depd@0.4.4 + - deps: express-session@~1.7.2 + - deps: morgan@~1.2.2 + - deps: serve-static@~1.4.2 + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + +3.15.1 / 2014-07-26 +=================== + + * deps: connect@2.24.1 + - deps: body-parser@~1.5.1 + - deps: depd@0.4.3 + - deps: express-session@~1.7.1 + - deps: morgan@~1.2.1 + - deps: serve-index@~1.1.4 + - deps: serve-static@~1.4.1 + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + +3.15.0 / 2014-07-22 +=================== + + * Fix `req.protocol` for proxy-direct connections + * Pass options from `res.sendfile` to `send` + * deps: connect@2.24.0 + - deps: body-parser@~1.5.0 + - deps: compression@~1.0.9 + - deps: connect-timeout@~1.2.1 + - deps: debug@1.0.4 + - deps: depd@0.4.2 + - deps: express-session@~1.7.0 + - deps: finalhandler@0.1.0 + - deps: method-override@~2.1.2 + - deps: morgan@~1.2.0 + - deps: multiparty@3.3.1 + - deps: parseurl@~1.2.0 + - deps: serve-static@~1.4.0 + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +3.14.0 / 2014-07-11 +=================== + + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * deps: basic-auth@1.0.0 + - support empty password + - support empty username + * deps: connect@2.23.0 + - deps: debug@1.0.3 + - deps: express-session@~1.6.4 + - deps: method-override@~2.1.0 + - deps: parseurl@~1.1.3 + - deps: serve-static@~1.3.1 + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +3.13.0 / 2014-07-03 +=================== + + * add deprecation message to `app.configure` + * add deprecation message to `req.auth` + * use `basic-auth` to parse `Authorization` header + * deps: connect@2.22.0 + - deps: csurf@~1.3.0 + - deps: express-session@~1.6.1 + - deps: multiparty@3.3.0 + - deps: serve-static@~1.3.0 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + +3.12.1 / 2014-06-26 +=================== + + * deps: connect@2.21.1 + - deps: cookie-parser@1.3.2 + - deps: cookie-signature@1.0.4 + - deps: express-session@~1.5.2 + - deps: type-is@~1.3.2 + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +3.12.0 / 2014-06-21 +=================== + + * use `media-typer` to alter content-type charset + * deps: connect@2.21.0 + - deprecate `connect(middleware)` -- use `app.use(middleware)` instead + - deprecate `connect.createServer()` -- use `connect()` instead + - fix `res.setHeader()` patch to work with with get -> append -> set pattern + - deps: compression@~1.0.8 + - deps: errorhandler@~1.1.1 + - deps: express-session@~1.5.0 + - deps: serve-index@~1.1.3 + +3.11.0 / 2014-06-19 +=================== + + * deprecate things with `depd` module + * deps: buffer-crc32@0.2.3 + * deps: connect@2.20.2 + - deprecate `verify` option to `json` -- use `body-parser` npm module instead + - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead + - deprecate things with `depd` module + - use `finalhandler` for final response handling + - use `media-typer` to parse `content-type` for charset + - deps: body-parser@1.4.3 + - deps: connect-timeout@1.1.1 + - deps: cookie-parser@1.3.1 + - deps: csurf@1.2.2 + - deps: errorhandler@1.1.0 + - deps: express-session@1.4.0 + - deps: multiparty@3.2.9 + - deps: serve-index@1.1.2 + - deps: type-is@1.3.1 + - deps: vhost@2.0.0 + +3.10.5 / 2014-06-11 +=================== + + * deps: connect@2.19.6 + - deps: body-parser@1.3.1 + - deps: compression@1.0.7 + - deps: debug@1.0.2 + - deps: serve-index@1.1.1 + - deps: serve-static@1.2.3 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw uncatchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +3.10.4 / 2014-06-09 +=================== + + * deps: connect@2.19.5 + - fix "event emitter leak" warnings + - deps: csurf@1.2.1 + - deps: debug@1.0.1 + - deps: serve-static@1.2.2 + - deps: type-is@1.2.1 + * deps: debug@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: finished@1.2.1 + - deps: debug@1.0.1 + +3.10.3 / 2014-06-05 +=================== + + * use `vary` module for `res.vary` + * deps: connect@2.19.4 + - deps: errorhandler@1.0.2 + - deps: method-override@2.0.2 + - deps: serve-favicon@2.0.1 + * deps: debug@1.0.0 + +3.10.2 / 2014-06-03 +=================== + + * deps: connect@2.19.3 + - deps: compression@1.0.6 + +3.10.1 / 2014-06-03 +=================== + + * deps: connect@2.19.2 + - deps: compression@1.0.4 + * deps: proxy-addr@1.0.1 + +3.10.0 / 2014-06-02 +=================== + + * deps: connect@2.19.1 + - deprecate `methodOverride()` -- use `method-override` npm module instead + - deps: body-parser@1.3.0 + - deps: method-override@2.0.1 + - deps: multiparty@3.2.8 + - deps: response-time@2.0.0 + - deps: serve-static@1.2.1 + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +3.9.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * Include ETag in HEAD requests + * mark `res.send` ETag as weak and reduce collisions + * update connect to 2.18.0 + - deps: compression@1.0.3 + - deps: serve-index@1.1.0 + - deps: serve-static@1.2.0 + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + +3.8.1 / 2014-05-27 +================== + + * update connect to 2.17.3 + - deps: body-parser@1.2.2 + - deps: express-session@1.2.1 + - deps: method-override@1.0.2 + +3.8.0 / 2014-05-21 +================== + + * keep previous `Content-Type` for `res.jsonp` + * set proper `charset` in `Content-Type` for `res.send` + * update connect to 2.17.1 + - fix `res.charset` appending charset when `content-type` has one + - deps: express-session@1.2.0 + - deps: morgan@1.1.1 + - deps: serve-index@1.0.3 + +3.7.0 / 2014-05-18 +================== + + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * update connect to 2.16.2 + - deprecate `res.headerSent` -- use `res.headersSent` + - deprecate `res.on("header")` -- use on-headers module instead + - fix edge-case in `res.appendHeader` that would append in wrong order + - json: use body-parser + - urlencoded: use body-parser + - dep: bytes@1.0.0 + - dep: cookie-parser@1.1.0 + - dep: csurf@1.2.0 + - dep: express-session@1.1.0 + - dep: method-override@1.0.1 + +3.6.0 / 2014-05-09 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update connect to 2.15.0 + * Add `res.appendHeader` + * Call error stack even when response has been sent + * Patch `res.headerSent` to return Boolean + * Patch `res.headersSent` for node.js 0.8 + * Prevent default 404 handler after response sent + * dep: compression@1.0.2 + * dep: connect-timeout@1.1.0 + * dep: debug@^0.8.0 + * dep: errorhandler@1.0.1 + * dep: express-session@1.0.4 + * dep: morgan@1.0.1 + * dep: serve-favicon@2.0.0 + * dep: serve-index@1.0.2 + * update debug to 0.8.0 + * add `enable()` method + * change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + * update mkdirp to 0.5.0 + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes charset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. + +3.1.0 / 2013-01-25 +================== + + * add support for leading "." in "view engine" setting + * add array support to `res.set()` + * add node 0.8.x to travis.yml + * add "subdomain offset" setting for tweaking `req.subdomains` + * add `res.location(url)` implementing `res.redirect()`-like setting of Location + * use app.get() for x-powered-by setting for inheritance + * fix colons in passwords for `req.auth` + +3.0.6 / 2013-01-04 +================== + + * add http verb methods to Router + * update connect + * fix mangling of the `res.cookie()` options object + * fix jsonp whitespace escape. Closes #1132 + +3.0.5 / 2012-12-19 +================== + + * add throwing when a non-function is passed to a route + * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses + * revert "add 'etag' option" + +3.0.4 / 2012-12-05 +================== + + * add 'etag' option to disable `res.send()` Etags + * add escaping of urls in text/plain in `res.redirect()` + for old browsers interpreting as html + * change crc32 module for a more liberal license + * update connect + +3.0.3 / 2012-11-13 +================== + + * update connect + * update cookie module + * fix cookie max-age + +3.0.2 / 2012-11-08 +================== + + * add OPTIONS to cors example. Closes #1398 + * fix route chaining regression. Closes #1397 + +3.0.1 / 2012-11-01 +================== + + * update connect + +3.0.0 / 2012-10-23 +================== + + * add `make clean` + * add "Basic" check to req.auth + * add `req.auth` test coverage + * add cb && cb(payload) to `res.jsonp()`. Closes #1374 + * add backwards compat for `res.redirect()` status. Closes #1336 + * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 + * update connect + * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 + * remove non-primitive string support for `res.send()` + * fix view-locals example. Closes #1370 + * fix route-separation example + +3.0.0rc5 / 2012-09-18 +================== + + * update connect + * add redis search example + * add static-files example + * add "x-powered-by" setting (`app.disable('x-powered-by')`) + * add "application/octet-stream" redirect Accept test case. Closes #1317 + +3.0.0rc4 / 2012-08-30 +================== + + * add `res.jsonp()`. Closes #1307 + * add "verbose errors" option to error-pages example + * add another route example to express(1) so people are not so confused + * add redis online user activity tracking example + * update connect dep + * fix etag quoting. Closes #1310 + * fix error-pages 404 status + * fix jsonp callback char restrictions + * remove old OPTIONS default response + +3.0.0rc3 / 2012-08-13 +================== + + * update connect dep + * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] + * fix `res.render()` clobbering of "locals" + +3.0.0rc2 / 2012-08-03 +================== + + * add CORS example + * update connect dep + * deprecate `.createServer()` & remove old stale examples + * fix: escape `res.redirect()` link + * fix vhost example + +3.0.0rc1 / 2012-07-24 +================== + + * add more examples to view-locals + * add scheme-relative redirects (`res.redirect("//foo.com")`) support + * update cookie dep + * update connect dep + * update send dep + * fix `express(1)` -h flag, use -H for hogan. Closes #1245 + * fix `res.sendfile()` socket error handling regression + +3.0.0beta7 / 2012-07-16 +================== + + * update connect dep for `send()` root normalization regression + +3.0.0beta6 / 2012-07-13 +================== + + * add `err.view` property for view errors. Closes #1226 + * add "jsonp callback name" setting + * add support for "/foo/:bar*" non-greedy matches + * change `res.sendfile()` to use `send()` module + * change `res.send` to use "response-send" module + * remove `app.locals.use` and `res.locals.use`, use regular middleware + +3.0.0beta5 / 2012-07-03 +================== + + * add "make check" support + * add route-map example + * add `res.json(obj, status)` support back for BC + * add "methods" dep, remove internal methods module + * update connect dep + * update auth example to utilize cores pbkdf2 + * updated tests to use "supertest" + +3.0.0beta4 / 2012-06-25 +================== + + * Added `req.auth` + * Added `req.range(size)` + * Added `res.links(obj)` + * Added `res.send(body, status)` support back for backwards compat + * Added `.default()` support to `res.format()` + * Added 2xx / 304 check to `req.fresh` + * Revert "Added + support to the router" + * Fixed `res.send()` freshness check, respect res.statusCode + +3.0.0beta3 / 2012-06-15 +================== + + * Added hogan `--hjs` to express(1) [nullfirm] + * Added another example to content-negotiation + * Added `fresh` dep + * Changed: `res.send()` always checks freshness + * Fixed: expose connects mime module. Closes #1165 + +3.0.0beta2 / 2012-06-06 +================== + + * Added `+` support to the router + * Added `req.host` + * Changed `req.param()` to check route first + * Update connect dep + +3.0.0beta1 / 2012-06-01 +================== + + * Added `res.format()` callback to override default 406 behaviour + * Fixed `res.redirect()` 406. Closes #1154 + +3.0.0alpha5 / 2012-05-30 +================== + + * Added `req.ip` + * Added `{ signed: true }` option to `res.cookie()` + * Removed `res.signedCookie()` + * Changed: dont reverse `req.ips` + * Fixed "trust proxy" setting check for `req.ips` + +3.0.0alpha4 / 2012-05-09 +================== + + * Added: allow `[]` in jsonp callback. Closes #1128 + * Added `PORT` env var support in generated template. Closes #1118 [benatkin] + * Updated: connect 2.2.2 + +3.0.0alpha3 / 2012-05-04 +================== + + * Added public `app.routes`. Closes #887 + * Added _view-locals_ example + * Added _mvc_ example + * Added `res.locals.use()`. Closes #1120 + * Added conditional-GET support to `res.send()` + * Added: coerce `res.set()` values to strings + * Changed: moved `static()` in generated apps below router + * Changed: `res.send()` only set ETag when not previously set + * Changed connect 2.2.1 dep + * Changed: `make test` now runs unit / acceptance tests + * Fixed req/res proto inheritance + +3.0.0alpha2 / 2012-04-26 +================== + + * Added `make benchmark` back + * Added `res.send()` support for `String` objects + * Added client-side data exposing example + * Added `res.header()` and `req.header()` aliases for BC + * Added `express.createServer()` for BC + * Perf: memoize parsed urls + * Perf: connect 2.2.0 dep + * Changed: make `expressInit()` middleware self-aware + * Fixed: use app.get() for all core settings + * Fixed redis session example + * Fixed session example. Closes #1105 + * Fixed generated express dep. Closes #1078 + +3.0.0alpha1 / 2012-04-15 +================== + + * Added `app.locals.use(callback)` + * Added `app.locals` object + * Added `app.locals(obj)` + * Added `res.locals` object + * Added `res.locals(obj)` + * Added `res.format()` for content-negotiation + * Added `app.engine()` + * Added `res.cookie()` JSON cookie support + * Added "trust proxy" setting + * Added `req.subdomains` + * Added `req.protocol` + * Added `req.secure` + * Added `req.path` + * Added `req.ips` + * Added `req.fresh` + * Added `req.stale` + * Added comma-delimited / array support for `req.accepts()` + * Added debug instrumentation + * Added `res.set(obj)` + * Added `res.set(field, value)` + * Added `res.get(field)` + * Added `app.get(setting)`. Closes #842 + * Added `req.acceptsLanguage()` + * Added `req.acceptsCharset()` + * Added `req.accepted` + * Added `req.acceptedLanguages` + * Added `req.acceptedCharsets` + * Added "json replacer" setting + * Added "json spaces" setting + * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 + * Added `--less` support to express(1) + * Added `express.response` prototype + * Added `express.request` prototype + * Added `express.application` prototype + * Added `app.path()` + * Added `app.render()` + * Added `res.type()` to replace `res.contentType()` + * Changed: `res.redirect()` to add relative support + * Changed: enable "jsonp callback" by default + * Changed: renamed "case sensitive routes" to "case sensitive routing" + * Rewrite of all tests with mocha + * Removed "root" setting + * Removed `res.redirect('home')` support + * Removed `req.notify()` + * Removed `app.register()` + * Removed `app.redirect()` + * Removed `app.is()` + * Removed `app.helpers()` + * Removed `app.dynamicHelpers()` + * Fixed `res.sendfile()` with non-GET. Closes #723 + * Fixed express(1) public dir for windows. Closes #866 + +2.5.9/ 2012-04-02 +================== + + * Added support for PURGE request method [pbuyle] + * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] + +2.5.8 / 2012-02-08 +================== + + * Update mkdirp dep. Closes #991 + +2.5.7 / 2012-02-06 +================== + + * Fixed `app.all` duplicate DELETE requests [mscdex] + +2.5.6 / 2012-01-13 +================== + + * Updated hamljs dev dep. Closes #953 + +2.5.5 / 2012-01-08 +================== + + * Fixed: set `filename` on cached templates [matthewleon] + +2.5.4 / 2012-01-02 +================== + + * Fixed `express(1)` eol on 0.4.x. Closes #947 + +2.5.3 / 2011-12-30 +================== + + * Fixed `req.is()` when a charset is present + +2.5.2 / 2011-12-10 +================== + + * Fixed: express(1) LF -> CRLF for windows + +2.5.1 / 2011-11-17 +================== + + * Changed: updated connect to 1.8.x + * Removed sass.js support from express(1) + +2.5.0 / 2011-10-24 +================== + + * Added ./routes dir for generated app by default + * Added npm install reminder to express(1) app gen + * Added 0.5.x support + * Removed `make test-cov` since it wont work with node 0.5.x + * Fixed express(1) public dir for windows. Closes #866 + +2.4.7 / 2011-10-05 +================== + + * Added mkdirp to express(1). Closes #795 + * Added simple _json-config_ example + * Added shorthand for the parsed request's pathname via `req.path` + * Changed connect dep to 1.7.x to fix npm issue... + * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] + * Fixed `req.flash()`, only escape args + * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] + +2.4.6 / 2011-08-22 +================== + + * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] + +2.4.5 / 2011-08-19 +================== + + * Added support for routes to handle errors. Closes #809 + * Added `app.routes.all()`. Closes #803 + * Added "basepath" setting to work in conjunction with reverse proxies etc. + * Refactored `Route` to use a single array of callbacks + * Added support for multiple callbacks for `app.param()`. Closes #801 +Closes #805 + * Changed: removed .call(self) for route callbacks + * Dependency: `qs >= 0.3.1` + * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 + +2.4.4 / 2011-08-05 +================== + + * Fixed `res.header()` intention of a set, even when `undefined` + * Fixed `*`, value no longer required + * Fixed `res.send(204)` support. Closes #771 + +2.4.3 / 2011-07-14 +================== + + * Added docs for `status` option special-case. Closes #739 + * Fixed `options.filename`, exposing the view path to template engines + +2.4.2. / 2011-07-06 +================== + + * Revert "removed jsonp stripping" for XSS + +2.4.1 / 2011-07-06 +================== + + * Added `res.json()` JSONP support. Closes #737 + * Added _extending-templates_ example. Closes #730 + * Added "strict routing" setting for trailing slashes + * Added support for multiple envs in `app.configure()` calls. Closes #735 + * Changed: `res.send()` using `res.json()` + * Changed: when cookie `path === null` don't default it + * Changed; default cookie path to "home" setting. Closes #731 + * Removed _pids/logs_ creation from express(1) + +2.4.0 / 2011-06-28 +================== + + * Added chainable `res.status(code)` + * Added `res.json()`, an explicit version of `res.send(obj)` + * Added simple web-service example + +2.3.12 / 2011-06-22 +================== + + * \#express is now on freenode! come join! + * Added `req.get(field, param)` + * Added links to Japanese documentation, thanks @hideyukisaito! + * Added; the `express(1)` generated app outputs the env + * Added `content-negotiation` example + * Dependency: connect >= 1.5.1 < 2.0.0 + * Fixed view layout bug. Closes #720 + * Fixed; ignore body on 304. Closes #701 + +2.3.11 / 2011-06-04 +================== + + * Added `npm test` + * Removed generation of dummy test file from `express(1)` + * Fixed; `express(1)` adds express as a dep + * Fixed; prune on `prepublish` + +2.3.10 / 2011-05-27 +================== + + * Added `req.route`, exposing the current route + * Added _package.json_ generation support to `express(1)` + * Fixed call to `app.param()` function for optional params. Closes #682 + +2.3.9 / 2011-05-25 +================== + + * Fixed bug-ish with `../' in `res.partial()` calls + +2.3.8 / 2011-05-24 +================== + + * Fixed `app.options()` + +2.3.7 / 2011-05-23 +================== + + * Added route `Collection`, ex: `app.get('/user/:id').remove();` + * Added support for `app.param(fn)` to define param logic + * Removed `app.param()` support for callback with return value + * Removed module.parent check from express(1) generated app. Closes #670 + * Refactored router. Closes #639 + +2.3.6 / 2011-05-20 +================== + + * Changed; using devDependencies instead of git submodules + * Fixed redis session example + * Fixed markdown example + * Fixed view caching, should not be enabled in development + +2.3.5 / 2011-05-20 +================== + + * Added export `.view` as alias for `.View` + +2.3.4 / 2011-05-08 +================== + + * Added `./examples/say` + * Fixed `res.sendfile()` bug preventing the transfer of files with spaces + +2.3.3 / 2011-05-03 +================== + + * Added "case sensitive routes" option. + * Changed; split methods supported per rfc [slaskis] + * Fixed route-specific middleware when using the same callback function several times + +2.3.2 / 2011-04-27 +================== + + * Fixed view hints + +2.3.1 / 2011-04-26 +================== + + * Added `app.match()` as `app.match.all()` + * Added `app.lookup()` as `app.lookup.all()` + * Added `app.remove()` for `app.remove.all()` + * Added `app.remove.VERB()` + * Fixed template caching collision issue. Closes #644 + * Moved router over from connect and started refactor + +2.3.0 / 2011-04-25 +================== + + * Added options support to `res.clearCookie()` + * Added `res.helpers()` as alias of `res.locals()` + * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` + * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] + * Renamed "cache views" to "view cache". Closes #628 + * Fixed caching of views when using several apps. Closes #637 + * Fixed gotcha invoking `app.param()` callbacks once per route middleware. +Closes #638 + * Fixed partial lookup precedence. Closes #631 +Shaw] + +2.2.2 / 2011-04-12 +================== + + * Added second callback support for `res.download()` connection errors + * Fixed `filename` option passing to template engine + +2.2.1 / 2011-04-04 +================== + + * Added `layout(path)` helper to change the layout within a view. Closes #610 + * Fixed `partial()` collection object support. + Previously only anything with `.length` would work. + When `.length` is present one must still be aware of holes, + however now `{ collection: {foo: 'bar'}}` is valid, exposes + `keyInCollection` and `keysInCollection`. + + * Performance improved with better view caching + * Removed `request` and `response` locals + * Changed; errorHandler page title is now `Express` instead of `Connect` + +2.2.0 / 2011-03-30 +================== + + * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 + * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 + * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. + * Dependency `connect >= 1.2.0` + +2.1.1 / 2011-03-29 +================== + + * Added; expose `err.view` object when failing to locate a view + * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] + * Fixed; `res.send(undefined)` responds with 204 [aheckmann] + +2.1.0 / 2011-03-24 +================== + + * Added `/_?` partial lookup support. Closes #447 + * Added `request`, `response`, and `app` local variables + * Added `settings` local variable, containing the app's settings + * Added `req.flash()` exception if `req.session` is not available + * Added `res.send(bool)` support (json response) + * Fixed stylus example for latest version + * Fixed; wrap try/catch around `res.render()` + +2.0.0 / 2011-03-17 +================== + + * Fixed up index view path alternative. + * Changed; `res.locals()` without object returns the locals + +2.0.0rc3 / 2011-03-17 +================== + + * Added `res.locals(obj)` to compliment `res.local(key, val)` + * Added `res.partial()` callback support + * Fixed recursive error reporting issue in `res.render()` + +2.0.0rc2 / 2011-03-17 +================== + + * Changed; `partial()` "locals" are now optional + * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] + * Fixed .filename view engine option [reported by drudge] + * Fixed blog example + * Fixed `{req,res}.app` reference when mounting [Ben Weaver] + +2.0.0rc / 2011-03-14 +================== + + * Fixed; expose `HTTPSServer` constructor + * Fixed express(1) default test charset. Closes #579 [reported by secoif] + * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] + +2.0.0beta3 / 2011-03-09 +================== + + * Added support for `res.contentType()` literal + The original `res.contentType('.json')`, + `res.contentType('application/json')`, and `res.contentType('json')` + will work now. + * Added `res.render()` status option support back + * Added charset option for `res.render()` + * Added `.charset` support (via connect 1.0.4) + * Added view resolution hints when in development and a lookup fails + * Added layout lookup support relative to the page view. + For example while rendering `./views/user/index.jade` if you create + `./views/user/layout.jade` it will be used in favour of the root layout. + * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] + * Fixed; default `res.send()` string charset to utf8 + * Removed `Partial` constructor (not currently used) + +2.0.0beta2 / 2011-03-07 +================== + + * Added res.render() `.locals` support back to aid in migration process + * Fixed flash example + +2.0.0beta / 2011-03-03 +================== + + * Added HTTPS support + * Added `res.cookie()` maxAge support + * Added `req.header()` _Referrer_ / _Referer_ special-case, either works + * Added mount support for `res.redirect()`, now respects the mount-point + * Added `union()` util, taking place of `merge(clone())` combo + * Added stylus support to express(1) generated app + * Added secret to session middleware used in examples and generated app + * Added `res.local(name, val)` for progressive view locals + * Added default param support to `req.param(name, default)` + * Added `app.disabled()` and `app.enabled()` + * Added `app.register()` support for omitting leading ".", either works + * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 + * Added `app.param()` to map route params to async/sync logic + * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 + * Added extname with no leading "." support to `res.contentType()` + * Added `cache views` setting, defaulting to enabled in "production" env + * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. + * Added `req.accepts()` support for extensions + * Changed; `res.download()` and `res.sendfile()` now utilize Connect's + static file server `connect.static.send()`. + * Changed; replaced `connect.utils.mime()` with npm _mime_ module + * Changed; allow `req.query` to be pre-defined (via middleware or other parent + * Changed view partial resolution, now relative to parent view + * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. + * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 + * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` + * Fixed; using _qs_ module instead of _querystring_ + * Fixed; strip unsafe chars from jsonp callbacks + * Removed "stream threshold" setting + +1.0.8 / 2011-03-01 +================== + + * Allow `req.query` to be pre-defined (via middleware or other parent app) + * "connect": ">= 0.5.0 < 1.0.0". Closes #547 + * Removed the long deprecated __EXPRESS_ENV__ support + +1.0.7 / 2011-02-07 +================== + + * Fixed `render()` setting inheritance. + Mounted apps would not inherit "view engine" + +1.0.6 / 2011-02-07 +================== + + * Fixed `view engine` setting bug when period is in dirname + +1.0.5 / 2011-02-05 +================== + + * Added secret to generated app `session()` call + +1.0.4 / 2011-02-05 +================== + + * Added `qs` dependency to _package.json_ + * Fixed namespaced `require()`s for latest connect support + +1.0.3 / 2011-01-13 +================== + + * Remove unsafe characters from JSONP callback names [Ryan Grove] + +1.0.2 / 2011-01-10 +================== + + * Removed nested require, using `connect.router` + +1.0.1 / 2010-12-29 +================== + + * Fixed for middleware stacked via `createServer()` + previously the `foo` middleware passed to `createServer(foo)` + would not have access to Express methods such as `res.send()` + or props like `req.query` etc. + +1.0.0 / 2010-11-16 +================== + + * Added; deduce partial object names from the last segment. + For example by default `partial('forum/post', postObject)` will + give you the _post_ object, providing a meaningful default. + * Added http status code string representation to `res.redirect()` body + * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. + * Added `req.is()` to aid in content negotiation + * Added partial local inheritance [suggested by masylum]. Closes #102 + providing access to parent template locals. + * Added _-s, --session[s]_ flag to express(1) to add session related middleware + * Added _--template_ flag to express(1) to specify the + template engine to use. + * Added _--css_ flag to express(1) to specify the + stylesheet engine to use (or just plain css by default). + * Added `app.all()` support [thanks aheckmann] + * Added partial direct object support. + You may now `partial('user', user)` providing the "user" local, + vs previously `partial('user', { object: user })`. + * Added _route-separation_ example since many people question ways + to do this with CommonJS modules. Also view the _blog_ example for + an alternative. + * Performance; caching view path derived partial object names + * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 + * Fixed jsonp support; _text/javascript_ as per mailinglist discussion + +1.0.0rc4 / 2010-10-14 +================== + + * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 + * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) + * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] + * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] + * Added `partial()` support for array-like collections. Closes #434 + * Added support for swappable querystring parsers + * Added session usage docs. Closes #443 + * Added dynamic helper caching. Closes #439 [suggested by maritz] + * Added authentication example + * Added basic Range support to `res.sendfile()` (and `res.download()` etc) + * Changed; `express(1)` generated app using 2 spaces instead of 4 + * Default env to "development" again [aheckmann] + * Removed _context_ option is no more, use "scope" + * Fixed; exposing _./support_ libs to examples so they can run without installs + * Fixed mvc example + +1.0.0rc3 / 2010-09-20 +================== + + * Added confirmation for `express(1)` app generation. Closes #391 + * Added extending of flash formatters via `app.flashFormatters` + * Added flash formatter support. Closes #411 + * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" + * Added _stream threshold_ setting for `res.sendfile()` + * Added `res.send()` __HEAD__ support + * Added `res.clearCookie()` + * Added `res.cookie()` + * Added `res.render()` headers option + * Added `res.redirect()` response bodies + * Added `res.render()` status option support. Closes #425 [thanks aheckmann] + * Fixed `res.sendfile()` responding with 403 on malicious path + * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ + * Fixed; mounted apps settings now inherit from parent app [aheckmann] + * Fixed; stripping Content-Length / Content-Type when 204 + * Fixed `res.send()` 204. Closes #419 + * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 + * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] + + +1.0.0rc2 / 2010-08-17 +================== + + * Added `app.register()` for template engine mapping. Closes #390 + * Added `res.render()` callback support as second argument (no options) + * Added callback support to `res.download()` + * Added callback support for `res.sendfile()` + * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` + * Added "partials" setting to docs + * Added default expresso tests to `express(1)` generated app. Closes #384 + * Fixed `res.sendfile()` error handling, defer via `next()` + * Fixed `res.render()` callback when a layout is used [thanks guillermo] + * Fixed; `make install` creating ~/.node_libraries when not present + * Fixed issue preventing error handlers from being defined anywhere. Closes #387 + +1.0.0rc / 2010-07-28 +================== + + * Added mounted hook. Closes #369 + * Added connect dependency to _package.json_ + + * Removed "reload views" setting and support code + development env never caches, production always caches. + + * Removed _param_ in route callbacks, signature is now + simply (req, res, next), previously (req, res, params, next). + Use _req.params_ for path captures, _req.query_ for GET params. + + * Fixed "home" setting + * Fixed middleware/router precedence issue. Closes #366 + * Fixed; _configure()_ callbacks called immediately. Closes #368 + +1.0.0beta2 / 2010-07-23 +================== + + * Added more examples + * Added; exporting `Server` constructor + * Added `Server#helpers()` for view locals + * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 + * Added support for absolute view paths + * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 + * Added Guillermo Rauch to the contributor list + * Added support for "as" for non-collection partials. Closes #341 + * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] + * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] + * Fixed instanceof `Array` checks, now `Array.isArray()` + * Fixed express(1) expansion of public dirs. Closes #348 + * Fixed middleware precedence. Closes #345 + * Fixed view watcher, now async [thanks aheckmann] + +1.0.0beta / 2010-07-15 +================== + + * Re-write + - much faster + - much lighter + - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs + +0.14.0 / 2010-06-15 +================== + + * Utilize relative requires + * Added Static bufferSize option [aheckmann] + * Fixed caching of view and partial subdirectories [aheckmann] + * Fixed mime.type() comments now that ".ext" is not supported + * Updated haml submodule + * Updated class submodule + * Removed bin/express + +0.13.0 / 2010-06-01 +================== + + * Added node v0.1.97 compatibility + * Added support for deleting cookies via Request#cookie('key', null) + * Updated haml submodule + * Fixed not-found page, now using using charset utf-8 + * Fixed show-exceptions page, now using using charset utf-8 + * Fixed view support due to fs.readFile Buffers + * Changed; mime.type() no longer accepts ".type" due to node extname() changes + +0.12.0 / 2010-05-22 +================== + + * Added node v0.1.96 compatibility + * Added view `helpers` export which act as additional local variables + * Updated haml submodule + * Changed ETag; removed inode, modified time only + * Fixed LF to CRLF for setting multiple cookies + * Fixed cookie compilation; values are now urlencoded + * Fixed cookies parsing; accepts quoted values and url escaped cookies + +0.11.0 / 2010-05-06 +================== + + * Added support for layouts using different engines + - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) + - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' + - this.render('page.html.haml', { layout: false }) // no layout + * Updated ext submodule + * Updated haml submodule + * Fixed EJS partial support by passing along the context. Issue #307 + +0.10.1 / 2010-05-03 +================== + + * Fixed binary uploads. + +0.10.0 / 2010-04-30 +================== + + * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s + encoding is set to 'utf8' or 'utf-8'. + * Added "encoding" option to Request#render(). Closes #299 + * Added "dump exceptions" setting, which is enabled by default. + * Added simple ejs template engine support + * Added error response support for text/plain, application/json. Closes #297 + * Added callback function param to Request#error() + * Added Request#sendHead() + * Added Request#stream() + * Added support for Request#respond(304, null) for empty response bodies + * Added ETag support to Request#sendfile() + * Added options to Request#sendfile(), passed to fs.createReadStream() + * Added filename arg to Request#download() + * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request + * Performance enhanced by preventing several calls to toLowerCase() in Router#match() + * Changed; Request#sendfile() now streams + * Changed; Renamed Request#halt() to Request#respond(). Closes #289 + * Changed; Using sys.inspect() instead of JSON.encode() for error output + * Changed; run() returns the http.Server instance. Closes #298 + * Changed; Defaulting Server#host to null (INADDR_ANY) + * Changed; Logger "common" format scale of 0.4f + * Removed Logger "request" format + * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found + * Fixed several issues with http client + * Fixed Logger Content-Length output + * Fixed bug preventing Opera from retaining the generated session id. Closes #292 + +0.9.0 / 2010-04-14 +================== + + * Added DSL level error() route support + * Added DSL level notFound() route support + * Added Request#error() + * Added Request#notFound() + * Added Request#render() callback function. Closes #258 + * Added "max upload size" setting + * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 + * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js + * Added callback function support to Request#halt() as 3rd/4th arg + * Added preprocessing of route param wildcards using param(). Closes #251 + * Added view partial support (with collections etc) + * Fixed bug preventing falsey params (such as ?page=0). Closes #286 + * Fixed setting of multiple cookies. Closes #199 + * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) + * Changed; session cookie is now httpOnly + * Changed; Request is no longer global + * Changed; Event is no longer global + * Changed; "sys" module is no longer global + * Changed; moved Request#download to Static plugin where it belongs + * Changed; Request instance created before body parsing. Closes #262 + * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 + * Changed; Pre-caching view partials in memory when "cache view partials" is enabled + * Updated support to node --version 0.1.90 + * Updated dependencies + * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) + * Removed utils.mixin(); use Object#mergeDeep() + +0.8.0 / 2010-03-19 +================== + + * Added coffeescript example app. Closes #242 + * Changed; cache api now async friendly. Closes #240 + * Removed deprecated 'express/static' support. Use 'express/plugins/static' + +0.7.6 / 2010-03-19 +================== + + * Added Request#isXHR. Closes #229 + * Added `make install` (for the executable) + * Added `express` executable for setting up simple app templates + * Added "GET /public/*" to Static plugin, defaulting to /public + * Added Static plugin + * Fixed; Request#render() only calls cache.get() once + * Fixed; Namespacing View caches with "view:" + * Fixed; Namespacing Static caches with "static:" + * Fixed; Both example apps now use the Static plugin + * Fixed set("views"). Closes #239 + * Fixed missing space for combined log format + * Deprecated Request#sendfile() and 'express/static' + * Removed Server#running + +0.7.5 / 2010-03-16 +================== + + * Added Request#flash() support without args, now returns all flashes + * Updated ext submodule + +0.7.4 / 2010-03-16 +================== + + * Fixed session reaper + * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) + +0.7.3 / 2010-03-16 +================== + + * Added package.json + * Fixed requiring of haml / sass due to kiwi removal + +0.7.2 / 2010-03-16 +================== + + * Fixed GIT submodules (HAH!) + +0.7.1 / 2010-03-16 +================== + + * Changed; Express now using submodules again until a PM is adopted + * Changed; chat example using millisecond conversions from ext + +0.7.0 / 2010-03-15 +================== + + * Added Request#pass() support (finds the next matching route, or the given path) + * Added Logger plugin (default "common" format replaces CommonLogger) + * Removed Profiler plugin + * Removed CommonLogger plugin + +0.6.0 / 2010-03-11 +================== + + * Added seed.yml for kiwi package management support + * Added HTTP client query string support when method is GET. Closes #205 + + * Added support for arbitrary view engines. + For example "foo.engine.html" will now require('engine'), + the exports from this module are cached after the first require(). + + * Added async plugin support + + * Removed usage of RESTful route funcs as http client + get() etc, use http.get() and friends + + * Removed custom exceptions + +0.5.0 / 2010-03-10 +================== + + * Added ext dependency (library of js extensions) + * Removed extname() / basename() utils. Use path module + * Removed toArray() util. Use arguments.values + * Removed escapeRegexp() util. Use RegExp.escape() + * Removed process.mixin() dependency. Use utils.mixin() + * Removed Collection + * Removed ElementCollection + * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) + +0.4.0 / 2010-02-11 +================== + + * Added flash() example to sample upload app + * Added high level restful http client module (express/http) + * Changed; RESTful route functions double as HTTP clients. Closes #69 + * Changed; throwing error when routes are added at runtime + * Changed; defaulting render() context to the current Request. Closes #197 + * Updated haml submodule + +0.3.0 / 2010-02-11 +================== + + * Updated haml / sass submodules. Closes #200 + * Added flash message support. Closes #64 + * Added accepts() now allows multiple args. fixes #117 + * Added support for plugins to halt. Closes #189 + * Added alternate layout support. Closes #119 + * Removed Route#run(). Closes #188 + * Fixed broken specs due to use(Cookie) missing + +0.2.1 / 2010-02-05 +================== + + * Added "plot" format option for Profiler (for gnuplot processing) + * Added request number to Profiler plugin + * Fixed binary encoding for multipart file uploads, was previously defaulting to UTF8 + * Fixed issue with routes not firing when not files are present. Closes #184 + * Fixed process.Promise -> events.Promise + +0.2.0 / 2010-02-03 +================== + + * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 + * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 + * Added expiration support to cache api with reaper. Closes #133 + * Added cache Store.Memory#reap() + * Added Cache; cache api now uses first class Cache instances + * Added abstract session Store. Closes #172 + * Changed; cache Memory.Store#get() utilizing Collection + * Renamed MemoryStore -> Store.Memory + * Fixed use() of the same plugin several time will always use latest options. Closes #176 + +0.1.0 / 2010-02-03 +================== + + * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context + * Updated node support to 0.1.27 Closes #169 + * Updated dirname(__filename) -> __dirname + * Updated libxmljs support to v0.2.0 + * Added session support with memory store / reaping + * Added quick uid() helper + * Added multi-part upload support + * Added Sass.js support / submodule + * Added production env caching view contents and static files + * Added static file caching. Closes #136 + * Added cache plugin with memory stores + * Added support to StaticFile so that it works with non-textual files. + * Removed dirname() helper + * Removed several globals (now their modules must be required) + +0.0.2 / 2010-01-10 +================== + + * Added view benchmarks; currently haml vs ejs + * Added Request#attachment() specs. Closes #116 + * Added use of node's parseQuery() util. Closes #123 + * Added `make init` for submodules + * Updated Haml + * Updated sample chat app to show messages on load + * Updated libxmljs parseString -> parseHtmlString + * Fixed `make init` to work with older versions of git + * Fixed specs can now run independent specs for those who can't build deps. Closes #127 + * Fixed issues introduced by the node url module changes. Closes 126. + * Fixed two assertions failing due to Collection#keys() returning strings + * Fixed faulty Collection#toArray() spec due to keys() returning strings + * Fixed `make test` now builds libxmljs.node before testing + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/express/LICENSE b/node_modules/express/LICENSE new file mode 100644 index 0000000..aa927e4 --- /dev/null +++ b/node_modules/express/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2009-2014 TJ Holowaychuk +Copyright (c) 2013-2014 Roman Shtylman +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/express/Readme.md b/node_modules/express/Readme.md new file mode 100644 index 0000000..1f91297 --- /dev/null +++ b/node_modules/express/Readme.md @@ -0,0 +1,155 @@ +[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) + + Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). + + [![NPM Version][npm-image]][npm-url] + [![NPM Downloads][downloads-image]][downloads-url] + [![Linux Build][travis-image]][travis-url] + [![Windows Build][appveyor-image]][appveyor-url] + [![Test Coverage][coveralls-image]][coveralls-url] + +```js +const express = require('express') +const app = express() + +app.get('/', function (req, res) { + res.send('Hello World') +}) + +app.listen(3000) +``` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). + +Before installing, [download and install Node.js](https://nodejs.org/en/download/). +Node.js 0.10 or higher is required. + +Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install express +``` + +Follow [our installing guide](http://expressjs.com/en/starter/installing.html) +for more information. + +## Features + + * Robust routing + * Focus on high performance + * Super-high test coverage + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Executable for generating applications quickly + +## Docs & Community + + * [Website and Documentation](http://expressjs.com/) - [[website repo](https://github.com/expressjs/expressjs.com)] + * [#express](https://webchat.freenode.net/?channels=express) on freenode IRC + * [GitHub Organization](https://github.com/expressjs) for Official Middleware & Modules + * Visit the [Wiki](https://github.com/expressjs/express/wiki) + * [Google Group](https://groups.google.com/group/express-js) for discussion + * [Gitter](https://gitter.im/expressjs/express) for support and discussion + +**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/expressjs/express/wiki/New-features-in-4.x). + +### Security Issues + +If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md). + +## Quick Start + + The quickest way to get started with express is to utilize the executable [`express(1)`](https://github.com/expressjs/generator) to generate an application as shown below: + + Install the executable. The executable's major version will match Express's: + +```bash +$ npm install -g express-generator@4 +``` + + Create the app: + +```bash +$ express /tmp/foo && cd /tmp/foo +``` + + Install dependencies: + +```bash +$ npm install +``` + + Start the server: + +```bash +$ npm start +``` + + View the website at: http://localhost:3000 + +## Philosophy + + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, web sites, hybrids, or public + HTTP APIs. + + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js), + you can quickly craft your perfect framework. + +## Examples + + To view the examples, clone the Express repo and install the dependencies: + +```bash +$ git clone git://github.com/expressjs/express.git --depth 1 +$ cd express +$ npm install +``` + + Then run whichever example you want: + +```bash +$ node examples/content-negotiation +``` + +## Tests + + To run the test suite, first install the dependencies, then run `npm test`: + +```bash +$ npm install +$ npm test +``` + +## Contributing + +[Contributing Guide](Contributing.md) + +## People + +The original author of Express is [TJ Holowaychuk](https://github.com/tj) + +The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) + +[List of all contributors](https://github.com/expressjs/express/graphs/contributors) + +## License + + [MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/express.svg +[npm-url]: https://npmjs.org/package/express +[downloads-image]: https://img.shields.io/npm/dm/express.svg +[downloads-url]: https://npmjs.org/package/express +[travis-image]: https://img.shields.io/travis/expressjs/express/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/express +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/express/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express +[coveralls-image]: https://img.shields.io/coveralls/expressjs/express/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master diff --git a/node_modules/express/index.js b/node_modules/express/index.js new file mode 100644 index 0000000..d219b0c --- /dev/null +++ b/node_modules/express/index.js @@ -0,0 +1,11 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +module.exports = require('./lib/express'); diff --git a/node_modules/express/lib/application.js b/node_modules/express/lib/application.js new file mode 100644 index 0000000..91f77d2 --- /dev/null +++ b/node_modules/express/lib/application.js @@ -0,0 +1,644 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var finalhandler = require('finalhandler'); +var Router = require('./router'); +var methods = require('methods'); +var middleware = require('./middleware/init'); +var query = require('./middleware/query'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('http'); +var compileETag = require('./utils').compileETag; +var compileQueryParser = require('./utils').compileQueryParser; +var compileTrust = require('./utils').compileTrust; +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var merge = require('utils-merge'); +var resolve = require('path').resolve; +var setPrototypeOf = require('setprototypeof') +var slice = Array.prototype.slice; + +/** + * Application prototype. + */ + +var app = exports = module.exports = {}; + +/** + * Variable for trust proxy inheritance back-compat + * @private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ + +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; + + this.defaultConfiguration(); +}; + +/** + * Initialize application configuration. + * @private + */ + +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; + + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + this.set('subdomain offset', 2); + this.set('trust proxy', false); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); + + debug('booting in %s mode', env); + + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } + + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; + +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private + */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ + +app.handle = function handle(req, res, callback) { + var router = this._router; + + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } + + router.handle(req, res, done); +}; + +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ + +app.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') + } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + setPrototypeOf(req, orig.request) + setPrototypeOf(res, orig.response) + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; +}; + +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @public + */ + +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.ejs" file Express will invoke the following internally: + * + * app.engine('ejs', require('ejs').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } + + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; + + // store engine + this.engines[extension] = fn; + + return this; +}; + +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.param = function param(name, fn) { + this.lazyrouter(); + + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } + + return this; + } + + this._router.param(name, fn); + + return this; +}; + +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.set('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + + debug('set "%s" to %o', setting, val); + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public + */ + +app.all = function all(path) { + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ + +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge app.locals + merge(renderOptions, this.locals); + + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } + + // merge options + merge(renderOptions, opts); + + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + + // render + tryRender(view, renderOptions, done); +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ + +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Try rendering a view. + * @private + */ + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} diff --git a/node_modules/express/lib/express.js b/node_modules/express/lib/express.js new file mode 100644 index 0000000..d188a16 --- /dev/null +++ b/node_modules/express/lib/express.js @@ -0,0 +1,116 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var bodyParser = require('body-parser') +var EventEmitter = require('events').EventEmitter; +var mixin = require('merge-descriptors'); +var proto = require('./application'); +var Route = require('./router/route'); +var Router = require('./router'); +var req = require('./request'); +var res = require('./response'); + +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.json = bodyParser.json +exports.query = require('./middleware/query'); +exports.raw = bodyParser.raw +exports.static = require('serve-static'); +exports.text = bodyParser.text +exports.urlencoded = bodyParser.urlencoded + +/** + * Replace removed middleware with an appropriate error message. + */ + +var removedMiddlewares = [ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache' +] + +removedMiddlewares.forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); diff --git a/node_modules/express/lib/middleware/init.js b/node_modules/express/lib/middleware/init.js new file mode 100644 index 0000000..dfd0427 --- /dev/null +++ b/node_modules/express/lib/middleware/init.js @@ -0,0 +1,43 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var setPrototypeOf = require('setprototypeof') + +/** + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ + +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; + + setPrototypeOf(req, app.request) + setPrototypeOf(res, app.response) + + res.locals = res.locals || Object.create(null); + + next(); + }; +}; + diff --git a/node_modules/express/lib/middleware/query.js b/node_modules/express/lib/middleware/query.js new file mode 100644 index 0000000..7e91669 --- /dev/null +++ b/node_modules/express/lib/middleware/query.js @@ -0,0 +1,47 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var merge = require('utils-merge') +var parseUrl = require('parseurl'); +var qs = require('qs'); + +/** + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; + + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } + + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; + } + + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); + }; +}; diff --git a/node_modules/express/lib/request.js b/node_modules/express/lib/request.js new file mode 100644 index 0000000..a9400ef --- /dev/null +++ b/node_modules/express/lib/request.js @@ -0,0 +1,525 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var accepts = require('accepts'); +var deprecate = require('depd')('express'); +var isIP = require('net').isIP; +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); + +/** + * Request prototype. + * @public + */ + +var req = Object.create(http.IncomingMessage.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = req + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ + +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); + } + + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); + } + + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ + +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ + +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + +/** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. + * + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. + * + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + * + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} + * @public + */ + +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; + +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ + +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; + + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; + + return defaultValue; +}; + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } + + return typeis(this, arr); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ + +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + var header = this.get('X-Forwarded-Proto') || proto + var index = header.indexOf(',') + + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); + +/** + * Short-hand for: + * + * req.protocol === 'https' + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); + +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ + +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() + + return addrs +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ + +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); + + if (!host || !trust(this.connection.remoteAddress, 0)) { + host = this.get('Host'); + } else if (host.indexOf(',') !== -1) { + // Note: X-Forwarded-Host is normally only ever a + // single value, but this is to be safe. + host = host.substring(0, host.indexOf(',')).trimRight() + } + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return index !== -1 + ? host.substring(0, index) + : host; +}); + +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode + + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((status >= 200 && status < 300) || 304 === status) { + return fresh(this.headers, { + 'etag': res.get('ETag'), + 'last-modified': res.get('Last-Modified') + }) + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +} diff --git a/node_modules/express/lib/response.js b/node_modules/express/lib/response.js new file mode 100644 index 0000000..c9f08cd --- /dev/null +++ b/node_modules/express/lib/response.js @@ -0,0 +1,1142 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('safe-buffer').Buffer +var contentDisposition = require('content-disposition'); +var deprecate = require('depd')('express'); +var encodeUrl = require('encodeurl'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var isAbsolute = require('./utils').isAbsolute; +var onFinished = require('on-finished'); +var path = require('path'); +var statuses = require('statuses') +var merge = require('utils-merge'); +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var setCharset = require('./utils').setCharset; +var cookie = require('cookie'); +var send = require('send'); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = require('vary'); + +/** + * Response prototype. + * @public + */ + +var res = Object.create(http.ServerResponse.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = res + +/** + * Module variables. + * @private + */ + +var charsetRegExp = /;\s*charset\s*=/; + +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ + +res.status = function status(code) { + this.statusCode = code; + return this; +}; + +/** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public + */ + +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; + +/** + * Send a response. + * + * Examples: + * + * res.send(Buffer.from('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public + */ + +res.send = function send(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; + + // settings + var app = this.app; + + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } + } + + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statuses[chunk] + } + + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } + + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } + + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' + + // populate Content-Length + var len + if (chunk !== undefined) { + if (Buffer.isBuffer(chunk)) { + // get length of Buffer + len = chunk.length + } else if (!generateETag && chunk.length < 1000) { + // just calculate length when no ETag + small chunk + len = Buffer.byteLength(chunk, encoding) + } else { + // convert chunk to Buffer and calculate + chunk = Buffer.from(chunk, encoding) + encoding = undefined; + len = chunk.length + } + + this.set('Content-Length', len); + } + + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } + } + + // freshness + if (req.fresh) this.statusCode = 304; + + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } + + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + + return this; +}; + +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.json = function json(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } + + return this.send(body); +}; + +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.jsonp = function jsonp(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + var callback = this.req.query[app.get('jsonp callback name')]; + + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } + + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); + + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); + + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } + + return this.send(body); +}; + +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ + +res.sendStatus = function sendStatus(statusCode) { + var body = statuses[statusCode] || String(statusCode) + + this.statusCode = statusCode; + this.type('txt'); + + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } + + if (typeof path !== 'string') { + throw new TypeError('path must be a string to res.sendFile') + } + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } + + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // create file stream + var file = send(req, path, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * Optionally providing an `options` object to use with `res.sendFile()`. + * This function will set the `Content-Disposition` header, overriding + * any `Content-Disposition` header passed as header options in order + * to set the attachment and filename. + * + * This method uses `res.sendFile()`. + * + * @public + */ + +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null + + // support function as second or third arg + if (typeof filename === 'function') { + done = filename; + name = null; + opts = null + } else if (typeof options === 'function') { + done = options + opts = null + } + + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // merge user-provided headers + if (opts && opts.headers) { + var keys = Object.keys(opts.headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key.toLowerCase() !== 'content-disposition') { + headers[key] = opts.headers[key] + } + } + } + + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers + + // Resolve the full path for sendFile + var fullPath = resolve(path); + + // send file + return this.sendFile(fullPath, opts, done) +}; + +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ + +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; + + return this.set('Content-Type', ct); +}; + +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param {Object} obj + * @return {ServerResponse} for chaining + * @public + */ + +res.format = function(obj){ + var req = this.req; + var next = req.next; + + var fn = obj.default; + if (fn) delete obj.default; + var keys = Object.keys(obj); + + var key = keys.length > 0 + ? req.accepts(keys) + : false; + + this.vary("Accept"); + + if (key) { + this.set('Content-Type', normalizeType(key).value); + obj[key](req, this, next); + } else if (fn) { + fn(); + } else { + var err = new Error('Not Acceptable'); + err.status = err.statusCode = 406; + err.types = normalizeTypes(keys).map(function(o){ return o.value }); + next(err); + } + + return this; +}; + +/** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param {String} filename + * @return {ServerResponse} + * @public + */ + +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); + } + + this.set('Content-Disposition', contentDisposition(filename)); + + return this; +}; + +/** + * Append additional header `field` with value `val`. + * + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; + + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val]; + } + + return this.set(field, value); +}; + +/** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + * + * @param {String|Object} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); + + // add charset to content-type + if (field.toLowerCase() === 'content-type') { + if (Array.isArray(value)) { + throw new TypeError('Content-Type cannot be set to an Array'); + } + if (!charsetRegExp.test(value)) { + var charset = mime.charsets.lookup(value.split(';')[0]); + if (charset) value += '; charset=' + charset.toLowerCase(); + } + } + + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; + +/** + * Get value for header `field`. + * + * @param {String} field + * @return {String} + * @public + */ + +res.get = function(field){ + return this.getHeader(field); +}; + +/** + * Clear cookie `name`. + * + * @param {String} name + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.clearCookie = function clearCookie(name, options) { + var opts = merge({ expires: new Date(1), path: '/' }, options); + + return this.cookie(name, '', opts); +}; + +/** + * Set cookie `name` to `value`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // same as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * + * @param {String} name + * @param {String|Object} value + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.cookie = function (name, value, options) { + var opts = merge({}, options); + var secret = this.req.secret; + var signed = opts.signed; + + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); + } + + var val = typeof value === 'object' + ? 'j:' + JSON.stringify(value) + : String(value); + + if (signed) { + val = 's:' + sign(val, secret); + } + + if ('maxAge' in opts) { + opts.expires = new Date(Date.now() + opts.maxAge); + opts.maxAge /= 1000; + } + + if (opts.path == null) { + opts.path = '/'; + } + + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + + return this; +}; + +/** + * Set the location header to `url`. + * + * The given `url` can also be "back", which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); + * + * @param {String} url + * @return {ServerResponse} for chaining + * @public + */ + +res.location = function location(url) { + var loc = url; + + // "back" is an alias for the referrer + if (url === 'back') { + loc = this.req.get('Referrer') || '/'; + } + + // set location + return this.set('Location', encodeUrl(loc)); +}; + +/** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + * + * @public + */ + +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; + + // allow status / url + if (arguments.length === 2) { + if (typeof arguments[0] === 'number') { + status = arguments[0]; + address = arguments[1]; + } else { + deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); + status = arguments[1]; + } + } + + // Set location header + address = this.location(address).get('Location'); + + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses[status] + '. Redirecting to ' + address + }, + + html: function(){ + var u = escapeHtml(address); + body = '

' + statuses[status] + '. Redirecting to ' + u + '

' + }, + + default: function(){ + body = ''; + } + }); + + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ + +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } + + vary(this, field); + + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ + +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge res.locals + opts._locals = self.locals; + + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, opts, done); +}; + +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; + + // request aborted + function onaborted() { + if (done) return; + done = true; + + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); + } + + // directory + function ondirectory() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + callback(); + } + + // file + function onfile() { + streaming = false; + } + + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; + + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } + + if (done) return; + done = true; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} + +/** + * Stringify JSON, like JSON.stringify, but v8 optimized, with the + * ability to escape characters that can trigger HTML sniffing. + * + * @param {*} value + * @param {function} replaces + * @param {number} spaces + * @param {boolean} escape + * @returns {string} + * @private + */ + +function stringify (value, replacer, spaces, escape) { + // v8 checks arguments.length for optimizing simple call + // https://bugs.chromium.org/p/v8/issues/detail?id=4730 + var json = replacer || spaces + ? JSON.stringify(value, replacer, spaces) + : JSON.stringify(value); + + if (escape) { + json = json.replace(/[<>&]/g, function (c) { + switch (c.charCodeAt(0)) { + case 0x3c: + return '\\u003c' + case 0x3e: + return '\\u003e' + case 0x26: + return '\\u0026' + /* istanbul ignore next: unreachable default */ + default: + return c + } + }) + } + + return json +} diff --git a/node_modules/express/lib/router/index.js b/node_modules/express/lib/router/index.js new file mode 100644 index 0000000..69e6d38 --- /dev/null +++ b/node_modules/express/lib/router/index.js @@ -0,0 +1,662 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Route = require('./route'); +var Layer = require('./layer'); +var methods = require('methods'); +var mixin = require('utils-merge'); +var debug = require('debug')('express:router'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var parseUrl = require('parseurl'); +var setPrototypeOf = require('setprototypeof') + +/** + * Module variables. + * @private + */ + +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} [options] + * @return {Router} which is an callable function + * @public + */ + +var proto = module.exports = function(options) { + var opts = options || {}; + + function router(req, res, next) { + router.handle(req, res, next); + } + + // mixin Router class functions + setPrototypeOf(router, proto) + + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; + + return router; +}; + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; + } + + // apply param functions + var params = this._params; + var len = params.length; + var ret; + + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); + name = name.substr(1); + } + + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } + + // ensure we end up with a + // middleware function + if ('function' !== typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } + + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; + +/** + * Dispatch a req, res into the router. + * @private + */ + +proto.handle = function handle(req, res, out) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + + var idx = 0; + var protohost = getProtohost(req.url) || '' + var removed = ''; + var slashAdded = false; + var paramcalled = {}; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); + } + + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; + + next(); + + function next(err) { + var layerError = err === 'route' + ? null + : err; + + // remove added slash + if (slashAdded) { + req.url = req.url.substr(1); + slashAdded = false; + } + + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.substr(protohost.length); + removed = ''; + } + + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } + + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } + + // get pathname of request + var path = getPathname(req); + + if (path == null) { + return done(layerError); + } + + // find next matching layer + var layer; + var match; + var route; + + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; + + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; + } + + if (match !== true) { + continue; + } + + if (!route) { + // process non-route handlers normally + continue; + } + + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } + + var method = req.method; + var has_method = route._handles_method(method); + + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } + + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + continue; + } + } + + // no match + if (match !== true) { + return done(layerError); + } + + // store route for dispatch on change + if (route) { + req.route = route; + } + + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; + + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + return next(layerError || err); + } + + if (route) { + return layer.handle_request(req, res, next); + } + + trim_prefix(layer, layerError, layerPath, path); + }); + } + + function trim_prefix(layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path breaks on a path separator + var c = path[layerPath.length] + if (c && c !== '/' && c !== '.') return next(layerError) + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); + + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Process any parameters for the layer. + * @private + */ + +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; + + // captured parameters from the layer, keys and values + var keys = layer.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); + } + + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; + + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } + + if (i >= keys.length ) { + return done(); + } + + paramIndex = 0; + key = keys[i++]; + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; + + if (paramVal === undefined || !paramCallbacks) { + return param(); + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; + + // next param + return param(paramCalled.error); + } + + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + + paramCallback(); + } + + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; + + // store updated value + paramCalled.value = req.params[key.name]; + + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } + + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } + } + + param(); +}; + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ + +proto.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var callbacks = flatten(slice.call(arguments, offset)); + + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires a middleware function') + } + + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; + + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) + } + + // add the middleware + debug('use %o %s', path, fn.name || '') + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; + + this.stack.push(layer); + } + + return this; +}; + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public + */ + +proto.route = function route(path) { + var route = new Route(path); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); + + layer.route = route; + + this.stack.push(layer); + return route; +}; + +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +// append methods to a list of methods +function appendMethods(list, addition) { + for (var i = 0; i < addition.length; i++) { + var method = addition[i]; + if (list.indexOf(method) === -1) { + list.push(method); + } + } +} + +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; + } +} + +// Get get protocol + host for a URL +function getProtohost(url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } + + var searchIndex = url.indexOf('?') + var pathLength = searchIndex !== -1 + ? searchIndex + : url.length + var fqdnIndex = url.substr(0, pathLength).indexOf('://') + + return fqdnIndex !== -1 + ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined +} + +// get type for error message +function gettype(obj) { + var type = typeof obj; + + if (type !== 'object') { + return type; + } + + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); +} + +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ + +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; + } +} + +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; + } + + // make copy of parent for base + var obj = mixin({}, parent); + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } + + var i = 0; + var o = 0; + + // determine numeric gaps + while (i in params) { + i++; + } + + while (o in parent) { + o++; + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } + + return mixin(obj, params); +} + +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); + + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } + + return function () { + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } + + return fn.apply(this, arguments); + }; +} + +// send an OPTIONS response +function sendOptionsResponse(res, options, next) { + try { + var body = options.join(','); + res.set('Allow', body); + res.send(body); + } catch (err) { + next(err); + } +} + +// wrap a function +function wrap(old, fn) { + return function proxy() { + var args = new Array(arguments.length + 1); + + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; +} diff --git a/node_modules/express/lib/router/layer.js b/node_modules/express/lib/router/layer.js new file mode 100644 index 0000000..4dc8e86 --- /dev/null +++ b/node_modules/express/lib/router/layer.js @@ -0,0 +1,181 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var pathRegexp = require('path-to-regexp'); +var debug = require('debug')('express:router:layer'); + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Module exports. + * @public + */ + +module.exports = Layer; + +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } + + debug('new %o', path) + var opts = options || {}; + + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); + + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false +} + +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; + + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } + + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; + + if (fn.length > 3) { + // not a standard request handler + return next(); + } + + try { + fn(req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match(path) { + var match + + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.regexp.fast_slash) { + this.params = {} + this.path = '' + return true + } + + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true + } + + // match the path + match = this.regexp.exec(path) + } + + if (!match) { + this.params = undefined; + this.path = undefined; + return false; + } + + // store values + this.params = {}; + this.path = match[0] + + var keys = this.keys; + var params = this.params; + + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) + + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } + + return true; +}; + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ + +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } + + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } + + throw err; + } +} diff --git a/node_modules/express/lib/router/route.js b/node_modules/express/lib/router/route.js new file mode 100644 index 0000000..178df0d --- /dev/null +++ b/node_modules/express/lib/router/route.js @@ -0,0 +1,216 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:router:route'); +var flatten = require('array-flatten'); +var Layer = require('./layer'); +var methods = require('methods'); + +/** + * Module variables. + * @private + */ + +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Module exports. + * @public + */ + +module.exports = Route; + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @public + */ + +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %o', path) + + // route handlers for various http methods + this.methods = {}; +} + +/** + * Determine if the route handles a given method. + * @private + */ + +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } + + var name = method.toLowerCase(); + + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } + + return Boolean(this.methods[name]); +}; + +/** + * @return {Array} supported HTTP methods + * @private + */ + +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); + + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); + } + + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); + } + + return methods; +}; + +/** + * dispatch req, res into this route + * @private + */ + +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); + } + + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + req.route = this; + + next(); + + function next(err) { + // signal to exit route + if (err && err === 'route') { + return done(); + } + + // signal to exit router + if (err && err === 'router') { + return done(err) + } + + var layer = stack[idx++]; + if (!layer) { + return done(err); + } + + if (layer.method && layer.method !== method) { + return next(err); + } + + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires a callback function but got a ' + type + throw new TypeError(msg); + } + + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); + } + + return this; +}; + +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires a callback function but got a ' + type + throw new Error(msg); + } + + debug('%s %o', method, this.path) + + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); + } + + return this; + }; +}); diff --git a/node_modules/express/lib/utils.js b/node_modules/express/lib/utils.js new file mode 100644 index 0000000..bd81ac7 --- /dev/null +++ b/node_modules/express/lib/utils.js @@ -0,0 +1,306 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @api private + */ + +var Buffer = require('safe-buffer').Buffer +var contentDisposition = require('content-disposition'); +var contentType = require('content-type'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var mime = require('send').mime; +var etag = require('etag'); +var proxyaddr = require('proxy-addr'); +var qs = require('qs'); +var querystring = require('querystring'); + +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = createETagGenerator({ weak: false }) + +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = createETagGenerator({ weak: true }) + +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +exports.isAbsolute = function(path){ + if ('/' === path[0]) return true; + if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path + if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; + +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ + +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; + +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' === pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } + } + + return ret; +} + +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; +} + +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; +} + +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } + + return proxyaddr.compile(val || []); +} + +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ + +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; + +/** + * Create an ETag generator function, generating ETags with + * the given options. + * + * @param {object} options + * @return {function} + * @private + */ + +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body + + return etag(buf, options) + } +} + +/** + * Parse an extended query string with qs. + * + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; +} diff --git a/node_modules/express/lib/view.js b/node_modules/express/lib/view.js new file mode 100644 index 0000000..cf101ca --- /dev/null +++ b/node_modules/express/lib/view.js @@ -0,0 +1,182 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:view'); +var path = require('path'); +var fs = require('fs'); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; + +/** + * Module exports. + * @public + */ + +module.exports = View; + +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public + */ + +function View(name, options) { + var opts = options || {}; + + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + + var fileName = name; + + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; + + fileName += this.ext; + } + + if (!opts.engines[this.ext]) { + // load engine + var mod = this.ext.substr(1) + debug('require "%s"', mod) + + // default engine export + var fn = require(mod).__express + + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') + } + + opts.engines[this.ext] = fn + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} + +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ + +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); + + debug('lookup "%s"', name); + + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); + } + + return path; +}; + +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} diff --git a/node_modules/express/package.json b/node_modules/express/package.json new file mode 100644 index 0000000..2979d57 --- /dev/null +++ b/node_modules/express/package.json @@ -0,0 +1,98 @@ +{ + "name": "express", + "description": "Fast, unopinionated, minimalist web framework", + "version": "4.17.1", + "author": "TJ Holowaychuk ", + "contributors": [ + "Aaron Heckmann ", + "Ciaran Jessup ", + "Douglas Christopher Wilson ", + "Guillermo Rauch ", + "Jonathan Ong ", + "Roman Shtylman ", + "Young Jae Sim " + ], + "license": "MIT", + "repository": "expressjs/express", + "homepage": "http://expressjs.com/", + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "rest", + "restful", + "router", + "app", + "api" + ], + "dependencies": { + "accepts": "~1.3.7", + "array-flatten": "1.1.1", + "body-parser": "1.19.0", + "content-disposition": "0.5.3", + "content-type": "~1.0.4", + "cookie": "0.4.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.2", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.1.2", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.5", + "qs": "6.7.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.1.2", + "send": "0.17.1", + "serve-static": "1.14.1", + "setprototypeof": "1.1.1", + "statuses": "~1.5.0", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "devDependencies": { + "after": "0.8.2", + "connect-redis": "3.4.1", + "cookie-parser": "~1.4.4", + "cookie-session": "1.3.3", + "ejs": "2.6.1", + "eslint": "2.13.1", + "express-session": "1.16.1", + "hbs": "4.0.4", + "istanbul": "0.4.5", + "marked": "0.6.2", + "method-override": "3.0.0", + "mocha": "5.2.0", + "morgan": "1.9.1", + "multiparty": "4.2.1", + "pbkdf2-password": "1.2.1", + "should": "13.2.3", + "supertest": "3.3.0", + "vhost": "~3.0.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "files": [ + "LICENSE", + "History.md", + "Readme.md", + "index.js", + "lib/" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/", + "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/" + } +} diff --git a/node_modules/finalhandler/HISTORY.md b/node_modules/finalhandler/HISTORY.md new file mode 100644 index 0000000..920c35e --- /dev/null +++ b/node_modules/finalhandler/HISTORY.md @@ -0,0 +1,187 @@ +1.1.2 / 2019-05-09 +================== + + * Set stricter `Content-Security-Policy` header + * deps: parseurl@~1.3.3 + * deps: statuses@~1.5.0 + +1.1.1 / 2018-03-06 +================== + + * Fix 404 output for bad / missing pathnames + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +1.1.0 / 2017-09-24 +================== + + * Use `res.headersSent` when available + +1.0.6 / 2017-09-22 +================== + + * deps: debug@2.6.9 + +1.0.5 / 2017-09-15 +================== + + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + +1.0.4 / 2017-08-03 +================== + + * deps: debug@2.6.8 + +1.0.3 / 2017-05-16 +================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + +1.0.2 / 2017-04-22 +================== + + * deps: debug@2.6.4 + - deps: ms@0.7.3 + +1.0.1 / 2017-03-21 +================== + + * Fix missing `` in HTML document + * deps: debug@2.6.3 + - Fix: `DEBUG_MAX_ARRAY_LENGTH` + +1.0.0 / 2017-02-15 +================== + + * Fix exception when `err` cannot be converted to a string + * Fully URL-encode the pathname in the 404 message + * Only include the pathname in the 404 message + * Send complete HTML document + * Set `Content-Security-Policy: default-src 'self'` header + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + +0.5.1 / 2016-11-12 +================== + + * Fix exception when `err.headers` is not an object + * deps: statuses@~1.3.1 + * perf: hoist regular expressions + * perf: remove duplicate validation path + +0.5.0 / 2016-06-15 +================== + + * Change invalid or non-numeric status code to 500 + * Overwrite status message to match set status code + * Prefer `err.statusCode` if `err.status` is invalid + * Set response headers from `err.headers` object + * Use `statuses` instead of `http` module for status messages + - Includes all defined status messages + +0.4.1 / 2015-12-02 +================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + +0.4.0 / 2015-06-14 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + * Support `statusCode` property on `Error` objects + * Use `unpipe` module for unpiping requests + * deps: escape-html@1.0.2 + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove argument reassignment + +0.3.6 / 2015-05-11 +================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + +0.3.5 / 2015-04-22 +================== + + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + +0.3.4 / 2015-03-15 +================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.3.3 / 2015-01-01 +================== + + * deps: debug@~2.1.1 + * deps: on-finished@~2.2.0 + +0.3.2 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.3.1 / 2014-10-16 +================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + +0.3.0 / 2014-09-17 +================== + + * Terminate in progress response only on error + * Use `on-finished` to determine request status + +0.2.0 / 2014-09-03 +================== + + * Set `X-Content-Type-Options: nosniff` header + * deps: debug@~2.0.0 + +0.1.0 / 2014-07-16 +================== + + * Respond after request fully read + - prevents hung responses and socket hang ups + * deps: debug@1.0.4 + +0.0.3 / 2014-07-11 +================== + + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.0.2 / 2014-06-19 +================== + + * Handle invalid status codes + +0.0.1 / 2014-06-05 +================== + + * deps: debug@1.0.2 + +0.0.0 / 2014-06-05 +================== + + * Extracted from connect/express diff --git a/node_modules/finalhandler/LICENSE b/node_modules/finalhandler/LICENSE new file mode 100644 index 0000000..fb30982 --- /dev/null +++ b/node_modules/finalhandler/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/finalhandler/README.md b/node_modules/finalhandler/README.md new file mode 100644 index 0000000..96327f0 --- /dev/null +++ b/node_modules/finalhandler/README.md @@ -0,0 +1,148 @@ +# finalhandler + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js function to invoke as the final step to respond to HTTP request. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install finalhandler +``` + +## API + + + +```js +var finalhandler = require('finalhandler') +``` + +### finalhandler(req, res, [options]) + +Returns function to be invoked as the final step for the given `req` and `res`. +This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will +write out a 404 response to the `res`. If it is truthy, an error response will +be written out to the `res`. + +When an error is written, the following information is added to the response: + + * The `res.statusCode` is set from `err.status` (or `err.statusCode`). If + this value is outside the 4xx or 5xx range, it will be set to 500. + * The `res.statusMessage` is set according to the status code. + * The body will be the HTML of the status code message if `env` is + `'production'`, otherwise will be `err.stack`. + * Any headers specified in an `err.headers` object. + +The final handler will also unpipe anything from `req` when it is invoked. + +#### options.env + +By default, the environment is determined by `NODE_ENV` variable, but it can be +overridden by this option. + +#### options.onerror + +Provide a function to be called with the `err` when it exists. Can be used for +writing errors to a central location without excessive function generation. Called +as `onerror(err, req, res)`. + +## Examples + +### always 404 + +```js +var finalhandler = require('finalhandler') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + done() +}) + +server.listen(3000) +``` + +### perform simple action + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) +``` + +### use with middleware-style functions + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +var serve = serveStatic('public') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + serve(req, res, done) +}) + +server.listen(3000) +``` + +### keep log of all errors + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res, { onerror: logerror }) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) + +function logerror (err) { + console.error(err.stack || err.toString()) +} +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/finalhandler.svg +[npm-url]: https://npmjs.org/package/finalhandler +[node-image]: https://img.shields.io/node/v/finalhandler.svg +[node-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/pillarjs/finalhandler.svg +[travis-url]: https://travis-ci.org/pillarjs/finalhandler +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master +[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg +[downloads-url]: https://npmjs.org/package/finalhandler diff --git a/node_modules/finalhandler/index.js b/node_modules/finalhandler/index.js new file mode 100644 index 0000000..5673507 --- /dev/null +++ b/node_modules/finalhandler/index.js @@ -0,0 +1,331 @@ +/*! + * finalhandler + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('finalhandler') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var onFinished = require('on-finished') +var parseUrl = require('parseurl') +var statuses = require('statuses') +var unpipe = require('unpipe') + +/** + * Module variables. + * @private + */ + +var DOUBLE_SPACE_REGEXP = /\x20{2}/g +var NEWLINE_REGEXP = /\n/g + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished + +/** + * Create a minimal HTML document. + * + * @param {string} message + * @private + */ + +function createHtmlDocument (message) { + var body = escapeHtml(message) + .replace(NEWLINE_REGEXP, '
') + .replace(DOUBLE_SPACE_REGEXP, '  ') + + return '\n' + + '\n' + + '\n' + + '\n' + + 'Error\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Module exports. + * @public + */ + +module.exports = finalhandler + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler (req, res, options) { + var opts = options || {} + + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' + + // get error callback + var onerror = opts.onerror + + return function (err) { + var headers + var msg + var status + + // ignore 404 on in-flight response + if (!err && headersSent(res)) { + debug('cannot 404 after headers sent') + return + } + + // unhandled error + if (err) { + // respect status code from error + status = getErrorStatusCode(err) + + if (status === undefined) { + // fallback to status code on response + status = getResponseStatusCode(res) + } else { + // respect headers from error + headers = getErrorHeaders(err) + } + + // get error message + msg = getErrorMessage(err, status, env) + } else { + // not found + status = 404 + msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) + } + + debug('default %s', status) + + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } + + // cannot actually respond + if (headersSent(res)) { + debug('cannot %d after headers sent', status) + req.socket.destroy() + return + } + + // send response + send(req, res, status, headers, msg) + } +} + +/** + * Get headers from Error object. + * + * @param {Error} err + * @return {object} + * @private + */ + +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined + } + + var headers = Object.create(null) + var keys = Object.keys(err.headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + headers[key] = err.headers[key] + } + + return headers +} + +/** + * Get message from Error object, fallback to status message. + * + * @param {Error} err + * @param {number} status + * @param {string} env + * @return {string} + * @private + */ + +function getErrorMessage (err, status, env) { + var msg + + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack + + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString() + } + } + + return msg || statuses[status] +} + +/** + * Get status code from Error object. + * + * @param {Error} err + * @return {number} + * @private + */ + +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status + } + + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode + } + + return undefined +} + +/** + * Get resource name for the request. + * + * This is typically just the original pathname of the request + * but will fallback to "resource" is that cannot be determined. + * + * @param {IncomingMessage} req + * @return {string} + * @private + */ + +function getResourceName (req) { + try { + return parseUrl.original(req).pathname + } catch (e) { + return 'resource' + } +} + +/** + * Get status code from response. + * + * @param {OutgoingMessage} res + * @return {number} + * @private + */ + +function getResponseStatusCode (res) { + var status = res.statusCode + + // default status code to 500 if outside valid range + if (typeof status !== 'number' || status < 400 || status > 599) { + status = 500 + } + + return status +} + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private + */ + +function send (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message) + + // response status + res.statusCode = status + res.statusMessage = statuses[status] + + // response headers + setHeaders(res, headers) + + // security headers + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return + } + + res.end(body, 'utf8') + } + + if (isFinished(req)) { + write() + return + } + + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() +} + +/** + * Set response headers from an object. + * + * @param {OutgoingMessage} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + if (!headers) { + return + } + + var keys = Object.keys(headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} diff --git a/node_modules/finalhandler/package.json b/node_modules/finalhandler/package.json new file mode 100644 index 0000000..79c8f3e --- /dev/null +++ b/node_modules/finalhandler/package.json @@ -0,0 +1,45 @@ +{ + "name": "finalhandler", + "description": "Node.js final http responder", + "version": "1.1.2", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "pillarjs/finalhandler", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "statuses": "~1.5.0", + "unpipe": "~1.0.0" + }, + "devDependencies": { + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "6.1.4", + "readable-stream": "2.3.6", + "safe-buffer": "5.1.2", + "supertest": "4.0.2" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + } +} diff --git a/node_modules/forwarded/HISTORY.md b/node_modules/forwarded/HISTORY.md new file mode 100644 index 0000000..381e6aa --- /dev/null +++ b/node_modules/forwarded/HISTORY.md @@ -0,0 +1,21 @@ +0.2.0 / 2021-05-31 +================== + + * Use `req.socket` over deprecated `req.connection` + +0.1.2 / 2017-09-14 +================== + + * perf: improve header parsing + * perf: reduce overhead when no `X-Forwarded-For` header + +0.1.1 / 2017-09-10 +================== + + * Fix trimming leading / trailing OWS + * perf: hoist regular expression + +0.1.0 / 2014-09-21 +================== + + * Initial release diff --git a/node_modules/forwarded/LICENSE b/node_modules/forwarded/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/node_modules/forwarded/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/forwarded/README.md b/node_modules/forwarded/README.md new file mode 100644 index 0000000..fdd220b --- /dev/null +++ b/node_modules/forwarded/README.md @@ -0,0 +1,57 @@ +# forwarded + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse HTTP X-Forwarded-For header + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install forwarded +``` + +## API + +```js +var forwarded = require('forwarded') +``` + +### forwarded(req) + +```js +var addresses = forwarded(req) +``` + +Parse the `X-Forwarded-For` header from the request. Returns an array +of the addresses, including the socket address for the `req`, in reverse +order (i.e. index `0` is the socket address and the last index is the +furthest address, typically the end-user). + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/forwarded/master?label=ci +[ci-url]: https://github.com/jshttp/forwarded/actions?query=workflow%3Aci +[npm-image]: https://img.shields.io/npm/v/forwarded.svg +[npm-url]: https://npmjs.org/package/forwarded +[node-version-image]: https://img.shields.io/node/v/forwarded.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master +[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg +[downloads-url]: https://npmjs.org/package/forwarded diff --git a/node_modules/forwarded/index.js b/node_modules/forwarded/index.js new file mode 100644 index 0000000..b2b6bdd --- /dev/null +++ b/node_modules/forwarded/index.js @@ -0,0 +1,90 @@ +/*! + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {object} req + * @return {array} + * @public + */ + +function forwarded (req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') + var socketAddr = getSocketAddr(req) + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} + +/** + * Get the socket address for a request. + * + * @param {object} req + * @return {string} + * @private + */ + +function getSocketAddr (req) { + return req.socket + ? req.socket.remoteAddress + : req.connection.remoteAddress +} + +/** + * Parse the X-Forwarded-For header. + * + * @param {string} header + * @private + */ + +function parse (header) { + var end = header.length + var list = [] + var start = header.length + + // gather addresses, backwards + for (var i = header.length - 1; i >= 0; i--) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(header.substring(start, end)) + } + start = end = i + break + default: + start = i + break + } + } + + // final address + if (start !== end) { + list.push(header.substring(start, end)) + } + + return list +} diff --git a/node_modules/forwarded/package.json b/node_modules/forwarded/package.json new file mode 100644 index 0000000..bf9c7d6 --- /dev/null +++ b/node_modules/forwarded/package.json @@ -0,0 +1,45 @@ +{ + "name": "forwarded", + "description": "Parse HTTP X-Forwarded-For header", + "version": "0.2.0", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "x-forwarded-for", + "http", + "req" + ], + "repository": "jshttp/forwarded", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "deep-equal": "1.0.1", + "eslint": "7.27.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.23.4", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/fresh/HISTORY.md b/node_modules/fresh/HISTORY.md new file mode 100644 index 0000000..4586996 --- /dev/null +++ b/node_modules/fresh/HISTORY.md @@ -0,0 +1,70 @@ +0.5.2 / 2017-09-13 +================== + + * Fix regression matching multiple ETags in `If-None-Match` + * perf: improve `If-None-Match` token parsing + +0.5.1 / 2017-09-11 +================== + + * Fix handling of modified headers with invalid dates + * perf: improve ETag match loop + +0.5.0 / 2017-02-21 +================== + + * Fix incorrect result when `If-None-Match` has both `*` and ETags + * Fix weak `ETag` matching to match spec + * perf: delay reading header values until needed + * perf: skip checking modified time if ETag check failed + * perf: skip parsing `If-None-Match` when no `ETag` header + * perf: use `Date.parse` instead of `new Date` + +0.4.0 / 2017-02-05 +================== + + * Fix false detection of `no-cache` request directive + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove duplicate conditional + * perf: remove unnecessary boolean coercions + +0.3.0 / 2015-05-12 +================== + + * Add weak `ETag` matching support + +0.2.4 / 2014-09-07 +================== + + * Support Node.js 0.6 + +0.2.3 / 2014-09-07 +================== + + * Move repository to jshttp + +0.2.2 / 2014-02-19 +================== + + * Revert "Fix for blank page on Safari reload" + +0.2.1 / 2014-01-29 +================== + + * Fix for blank page on Safari reload + +0.2.0 / 2013-08-11 +================== + + * Return stale for `Cache-Control: no-cache` + +0.1.0 / 2012-06-15 +================== + + * Add `If-None-Match: *` support + +0.0.1 / 2012-06-10 +================== + + * Initial release diff --git a/node_modules/fresh/LICENSE b/node_modules/fresh/LICENSE new file mode 100644 index 0000000..1434ade --- /dev/null +++ b/node_modules/fresh/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2016-2017 Douglas Christopher Wilson + +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/fresh/README.md b/node_modules/fresh/README.md new file mode 100644 index 0000000..1c1c680 --- /dev/null +++ b/node_modules/fresh/README.md @@ -0,0 +1,119 @@ +# fresh + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP response freshness testing + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +``` +$ npm install fresh +``` + +## API + + + +```js +var fresh = require('fresh') +``` + +### fresh(reqHeaders, resHeaders) + +Check freshness of the response using request and response headers. + +When the response is still "fresh" in the client's cache `true` is +returned, otherwise `false` is returned to indicate that the client +cache is now stale and the full response should be sent. + +When a client sends the `Cache-Control: no-cache` request header to +indicate an end-to-end reload request, this module will return `false` +to make handling these requests transparent. + +## Known Issues + +This module is designed to only follow the HTTP specifications, not +to work-around all kinda of client bugs (especially since this module +typically does not recieve enough information to understand what the +client actually is). + +There is a known issue that in certain versions of Safari, Safari +will incorrectly make a request that allows this module to validate +freshness of the resource even when Safari does not have a +representation of the resource in the cache. The module +[jumanji](https://www.npmjs.com/package/jumanji) can be used in +an Express application to work-around this issue and also provides +links to further reading on this Safari bug. + +## Example + +### API usage + + + +```js +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { 'etag': '"bar"' } +fresh(reqHeaders, resHeaders) +// => false + +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { 'etag': '"foo"' } +fresh(reqHeaders, resHeaders) +// => true +``` + +### Using with Node.js http server + +```js +var fresh = require('fresh') +var http = require('http') + +var server = http.createServer(function (req, res) { + // perform server logic + // ... including adding ETag / Last-Modified response headers + + if (isFresh(req, res)) { + // client has a fresh copy of resource + res.statusCode = 304 + res.end() + return + } + + // send the resource + res.statusCode = 200 + res.end('hello, world!') +}) + +function isFresh (req, res) { + return fresh(req.headers, { + 'etag': res.getHeader('ETag'), + 'last-modified': res.getHeader('Last-Modified') + }) +} + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/fresh.svg +[npm-url]: https://npmjs.org/package/fresh +[node-version-image]: https://img.shields.io/node/v/fresh.svg +[node-version-url]: https://nodejs.org/en/ +[travis-image]: https://img.shields.io/travis/jshttp/fresh/master.svg +[travis-url]: https://travis-ci.org/jshttp/fresh +[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master +[downloads-image]: https://img.shields.io/npm/dm/fresh.svg +[downloads-url]: https://npmjs.org/package/fresh diff --git a/node_modules/fresh/index.js b/node_modules/fresh/index.js new file mode 100644 index 0000000..d154f5a --- /dev/null +++ b/node_modules/fresh/index.js @@ -0,0 +1,137 @@ +/*! + * fresh + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2016-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to check for no-cache token in Cache-Control. + * @private + */ + +var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = fresh + +/** + * Check freshness of the response using request and response headers. + * + * @param {Object} reqHeaders + * @param {Object} resHeaders + * @return {Boolean} + * @public + */ + +function fresh (reqHeaders, resHeaders) { + // fields + var modifiedSince = reqHeaders['if-modified-since'] + var noneMatch = reqHeaders['if-none-match'] + + // unconditional request + if (!modifiedSince && !noneMatch) { + return false + } + + // Always return stale when Cache-Control: no-cache + // to support end-to-end reload requests + // https://tools.ietf.org/html/rfc2616#section-14.9.4 + var cacheControl = reqHeaders['cache-control'] + if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { + return false + } + + // if-none-match + if (noneMatch && noneMatch !== '*') { + var etag = resHeaders['etag'] + + if (!etag) { + return false + } + + var etagStale = true + var matches = parseTokenList(noneMatch) + for (var i = 0; i < matches.length; i++) { + var match = matches[i] + if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { + etagStale = false + break + } + } + + if (etagStale) { + return false + } + } + + // if-modified-since + if (modifiedSince) { + var lastModified = resHeaders['last-modified'] + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) + + if (modifiedStale) { + return false + } + } + + return true +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + // istanbul ignore next: guard against date.js Date.parse patching + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(str.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(str.substring(start, end)) + + return list +} diff --git a/node_modules/fresh/package.json b/node_modules/fresh/package.json new file mode 100644 index 0000000..c2fa0f4 --- /dev/null +++ b/node_modules/fresh/package.json @@ -0,0 +1,46 @@ +{ + "name": "fresh", + "description": "HTTP response freshness testing", + "version": "0.5.2", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "fresh", + "http", + "conditional", + "cache" + ], + "repository": "jshttp/fresh", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/fs-minipass/LICENSE b/node_modules/fs-minipass/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/fs-minipass/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/fs-minipass/README.md b/node_modules/fs-minipass/README.md new file mode 100644 index 0000000..1e61241 --- /dev/null +++ b/node_modules/fs-minipass/README.md @@ -0,0 +1,70 @@ +# fs-minipass + +Filesystem streams based on [minipass](http://npm.im/minipass). + +4 classes are exported: + +- ReadStream +- ReadStreamSync +- WriteStream +- WriteStreamSync + +When using `ReadStreamSync`, all of the data is made available +immediately upon consuming the stream. Nothing is buffered in memory +when the stream is constructed. If the stream is piped to a writer, +then it will synchronously `read()` and emit data into the writer as +fast as the writer can consume it. (That is, it will respect +backpressure.) If you call `stream.read()` then it will read the +entire file and return the contents. + +When using `WriteStreamSync`, every write is flushed to the file +synchronously. If your writes all come in a single tick, then it'll +write it all out in a single tick. It's as synchronous as you are. + +The async versions work much like their node builtin counterparts, +with the exception of introducing significantly less Stream machinery +overhead. + +## USAGE + +It's just streams, you pipe them or read() them or write() to them. + +```js +const fsm = require('fs-minipass') +const readStream = new fsm.ReadStream('file.txt') +const writeStream = new fsm.WriteStream('output.txt') +writeStream.write('some file header or whatever\n') +readStream.pipe(writeStream) +``` + +## ReadStream(path, options) + +Path string is required, but somewhat irrelevant if an open file +descriptor is passed in as an option. + +Options: + +- `fd` Pass in a numeric file descriptor, if the file is already open. +- `readSize` The size of reads to do, defaults to 16MB +- `size` The size of the file, if known. Prevents zero-byte read() + call at the end. +- `autoClose` Set to `false` to prevent the file descriptor from being + closed when the file is done being read. + +## WriteStream(path, options) + +Path string is required, but somewhat irrelevant if an open file +descriptor is passed in as an option. + +Options: + +- `fd` Pass in a numeric file descriptor, if the file is already open. +- `mode` The mode to create the file with. Defaults to `0o666`. +- `start` The position in the file to start reading. If not + specified, then the file will start writing at position zero, and be + truncated by default. +- `autoClose` Set to `false` to prevent the file descriptor from being + closed when the stream is ended. +- `flags` Flags to use when opening the file. Irrelevant if `fd` is + passed in, since file won't be opened in that case. Defaults to + `'a'` if a `pos` is specified, or `'w'` otherwise. diff --git a/node_modules/fs-minipass/index.js b/node_modules/fs-minipass/index.js new file mode 100644 index 0000000..9b0779c --- /dev/null +++ b/node_modules/fs-minipass/index.js @@ -0,0 +1,422 @@ +'use strict' +const MiniPass = require('minipass') +const EE = require('events').EventEmitter +const fs = require('fs') + +let writev = fs.writev +/* istanbul ignore next */ +if (!writev) { + // This entire block can be removed if support for earlier than Node.js + // 12.9.0 is not needed. + const binding = process.binding('fs') + const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback + + writev = (fd, iovec, pos, cb) => { + const done = (er, bw) => cb(er, bw, iovec) + const req = new FSReqWrap() + req.oncomplete = done + binding.writeBuffers(fd, iovec, pos, req) + } +} + +const _autoClose = Symbol('_autoClose') +const _close = Symbol('_close') +const _ended = Symbol('_ended') +const _fd = Symbol('_fd') +const _finished = Symbol('_finished') +const _flags = Symbol('_flags') +const _flush = Symbol('_flush') +const _handleChunk = Symbol('_handleChunk') +const _makeBuf = Symbol('_makeBuf') +const _mode = Symbol('_mode') +const _needDrain = Symbol('_needDrain') +const _onerror = Symbol('_onerror') +const _onopen = Symbol('_onopen') +const _onread = Symbol('_onread') +const _onwrite = Symbol('_onwrite') +const _open = Symbol('_open') +const _path = Symbol('_path') +const _pos = Symbol('_pos') +const _queue = Symbol('_queue') +const _read = Symbol('_read') +const _readSize = Symbol('_readSize') +const _reading = Symbol('_reading') +const _remain = Symbol('_remain') +const _size = Symbol('_size') +const _write = Symbol('_write') +const _writing = Symbol('_writing') +const _defaultFlag = Symbol('_defaultFlag') +const _errored = Symbol('_errored') + +class ReadStream extends MiniPass { + constructor (path, opt) { + opt = opt || {} + super(opt) + + this.readable = true + this.writable = false + + if (typeof path !== 'string') + throw new TypeError('path must be a string') + + this[_errored] = false + this[_fd] = typeof opt.fd === 'number' ? opt.fd : null + this[_path] = path + this[_readSize] = opt.readSize || 16*1024*1024 + this[_reading] = false + this[_size] = typeof opt.size === 'number' ? opt.size : Infinity + this[_remain] = this[_size] + this[_autoClose] = typeof opt.autoClose === 'boolean' ? + opt.autoClose : true + + if (typeof this[_fd] === 'number') + this[_read]() + else + this[_open]() + } + + get fd () { return this[_fd] } + get path () { return this[_path] } + + write () { + throw new TypeError('this is a readable stream') + } + + end () { + throw new TypeError('this is a readable stream') + } + + [_open] () { + fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) + } + + [_onopen] (er, fd) { + if (er) + this[_onerror](er) + else { + this[_fd] = fd + this.emit('open', fd) + this[_read]() + } + } + + [_makeBuf] () { + return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) + } + + [_read] () { + if (!this[_reading]) { + this[_reading] = true + const buf = this[_makeBuf]() + /* istanbul ignore if */ + if (buf.length === 0) + return process.nextTick(() => this[_onread](null, 0, buf)) + fs.read(this[_fd], buf, 0, buf.length, null, (er, br, buf) => + this[_onread](er, br, buf)) + } + } + + [_onread] (er, br, buf) { + this[_reading] = false + if (er) + this[_onerror](er) + else if (this[_handleChunk](br, buf)) + this[_read]() + } + + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) + } + } + + [_onerror] (er) { + this[_reading] = true + this[_close]() + this.emit('error', er) + } + + [_handleChunk] (br, buf) { + let ret = false + // no effect if infinite + this[_remain] -= br + if (br > 0) + ret = super.write(br < buf.length ? buf.slice(0, br) : buf) + + if (br === 0 || this[_remain] <= 0) { + ret = false + this[_close]() + super.end() + } + + return ret + } + + emit (ev, data) { + switch (ev) { + case 'prefinish': + case 'finish': + break + + case 'drain': + if (typeof this[_fd] === 'number') + this[_read]() + break + + case 'error': + if (this[_errored]) + return + this[_errored] = true + return super.emit(ev, data) + + default: + return super.emit(ev, data) + } + } +} + +class ReadStreamSync extends ReadStream { + [_open] () { + let threw = true + try { + this[_onopen](null, fs.openSync(this[_path], 'r')) + threw = false + } finally { + if (threw) + this[_close]() + } + } + + [_read] () { + let threw = true + try { + if (!this[_reading]) { + this[_reading] = true + do { + const buf = this[_makeBuf]() + /* istanbul ignore next */ + const br = buf.length === 0 ? 0 + : fs.readSync(this[_fd], buf, 0, buf.length, null) + if (!this[_handleChunk](br, buf)) + break + } while (true) + this[_reading] = false + } + threw = false + } finally { + if (threw) + this[_close]() + } + } + + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.closeSync(fd) + this.emit('close') + } + } +} + +class WriteStream extends EE { + constructor (path, opt) { + opt = opt || {} + super(opt) + this.readable = false + this.writable = true + this[_errored] = false + this[_writing] = false + this[_ended] = false + this[_needDrain] = false + this[_queue] = [] + this[_path] = path + this[_fd] = typeof opt.fd === 'number' ? opt.fd : null + this[_mode] = opt.mode === undefined ? 0o666 : opt.mode + this[_pos] = typeof opt.start === 'number' ? opt.start : null + this[_autoClose] = typeof opt.autoClose === 'boolean' ? + opt.autoClose : true + + // truncating makes no sense when writing into the middle + const defaultFlag = this[_pos] !== null ? 'r+' : 'w' + this[_defaultFlag] = opt.flags === undefined + this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags + + if (this[_fd] === null) + this[_open]() + } + + emit (ev, data) { + if (ev === 'error') { + if (this[_errored]) + return + this[_errored] = true + } + return super.emit(ev, data) + } + + + get fd () { return this[_fd] } + get path () { return this[_path] } + + [_onerror] (er) { + this[_close]() + this[_writing] = true + this.emit('error', er) + } + + [_open] () { + fs.open(this[_path], this[_flags], this[_mode], + (er, fd) => this[_onopen](er, fd)) + } + + [_onopen] (er, fd) { + if (this[_defaultFlag] && + this[_flags] === 'r+' && + er && er.code === 'ENOENT') { + this[_flags] = 'w' + this[_open]() + } else if (er) + this[_onerror](er) + else { + this[_fd] = fd + this.emit('open', fd) + this[_flush]() + } + } + + end (buf, enc) { + if (buf) + this.write(buf, enc) + + this[_ended] = true + + // synthetic after-write logic, where drain/finish live + if (!this[_writing] && !this[_queue].length && + typeof this[_fd] === 'number') + this[_onwrite](null, 0) + return this + } + + write (buf, enc) { + if (typeof buf === 'string') + buf = Buffer.from(buf, enc) + + if (this[_ended]) { + this.emit('error', new Error('write() after end()')) + return false + } + + if (this[_fd] === null || this[_writing] || this[_queue].length) { + this[_queue].push(buf) + this[_needDrain] = true + return false + } + + this[_writing] = true + this[_write](buf) + return true + } + + [_write] (buf) { + fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => + this[_onwrite](er, bw)) + } + + [_onwrite] (er, bw) { + if (er) + this[_onerror](er) + else { + if (this[_pos] !== null) + this[_pos] += bw + if (this[_queue].length) + this[_flush]() + else { + this[_writing] = false + + if (this[_ended] && !this[_finished]) { + this[_finished] = true + this[_close]() + this.emit('finish') + } else if (this[_needDrain]) { + this[_needDrain] = false + this.emit('drain') + } + } + } + } + + [_flush] () { + if (this[_queue].length === 0) { + if (this[_ended]) + this[_onwrite](null, 0) + } else if (this[_queue].length === 1) + this[_write](this[_queue].pop()) + else { + const iovec = this[_queue] + this[_queue] = [] + writev(this[_fd], iovec, this[_pos], + (er, bw) => this[_onwrite](er, bw)) + } + } + + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) + } + } +} + +class WriteStreamSync extends WriteStream { + [_open] () { + let fd + // only wrap in a try{} block if we know we'll retry, to avoid + // the rethrow obscuring the error's source frame in most cases. + if (this[_defaultFlag] && this[_flags] === 'r+') { + try { + fd = fs.openSync(this[_path], this[_flags], this[_mode]) + } catch (er) { + if (er.code === 'ENOENT') { + this[_flags] = 'w' + return this[_open]() + } else + throw er + } + } else + fd = fs.openSync(this[_path], this[_flags], this[_mode]) + + this[_onopen](null, fd) + } + + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.closeSync(fd) + this.emit('close') + } + } + + [_write] (buf) { + // throw the original, but try to close if it fails + let threw = true + try { + this[_onwrite](null, + fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) + threw = false + } finally { + if (threw) + try { this[_close]() } catch (_) {} + } + } +} + +exports.ReadStream = ReadStream +exports.ReadStreamSync = ReadStreamSync + +exports.WriteStream = WriteStream +exports.WriteStreamSync = WriteStreamSync diff --git a/node_modules/fs-minipass/package.json b/node_modules/fs-minipass/package.json new file mode 100644 index 0000000..2f2436c --- /dev/null +++ b/node_modules/fs-minipass/package.json @@ -0,0 +1,39 @@ +{ + "name": "fs-minipass", + "version": "2.1.0", + "main": "index.js", + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --follow-tags" + }, + "keywords": [], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/fs-minipass.git" + }, + "bugs": { + "url": "https://github.com/npm/fs-minipass/issues" + }, + "homepage": "https://github.com/npm/fs-minipass#readme", + "description": "fs read and write streams based on minipass", + "dependencies": { + "minipass": "^3.0.0" + }, + "devDependencies": { + "mutate-fs": "^2.0.1", + "tap": "^14.6.4" + }, + "files": [ + "index.js" + ], + "tap": { + "check-coverage": true + }, + "engines": { + "node": ">= 8" + } +} diff --git a/node_modules/fs.realpath/LICENSE b/node_modules/fs.realpath/LICENSE new file mode 100644 index 0000000..5bd884c --- /dev/null +++ b/node_modules/fs.realpath/LICENSE @@ -0,0 +1,43 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +---- + +This library bundles a version of the `fs.realpath` and `fs.realpathSync` +methods from Node.js v0.10 under the terms of the Node.js MIT license. + +Node's license follows, also included at the header of `old.js` which contains +the licensed code: + + Copyright Joyent, Inc. and other Node contributors. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. diff --git a/node_modules/fs.realpath/README.md b/node_modules/fs.realpath/README.md new file mode 100644 index 0000000..a42ceac --- /dev/null +++ b/node_modules/fs.realpath/README.md @@ -0,0 +1,33 @@ +# fs.realpath + +A backwards-compatible fs.realpath for Node v6 and above + +In Node v6, the JavaScript implementation of fs.realpath was replaced +with a faster (but less resilient) native implementation. That raises +new and platform-specific errors and cannot handle long or excessively +symlink-looping paths. + +This module handles those cases by detecting the new errors and +falling back to the JavaScript implementation. On versions of Node +prior to v6, it has no effect. + +## USAGE + +```js +var rp = require('fs.realpath') + +// async version +rp.realpath(someLongAndLoopingPath, function (er, real) { + // the ELOOP was handled, but it was a bit slower +}) + +// sync version +var real = rp.realpathSync(someLongAndLoopingPath) + +// monkeypatch at your own risk! +// This replaces the fs.realpath/fs.realpathSync builtins +rp.monkeypatch() + +// un-do the monkeypatching +rp.unmonkeypatch() +``` diff --git a/node_modules/fs.realpath/index.js b/node_modules/fs.realpath/index.js new file mode 100644 index 0000000..b09c7c7 --- /dev/null +++ b/node_modules/fs.realpath/index.js @@ -0,0 +1,66 @@ +module.exports = realpath +realpath.realpath = realpath +realpath.sync = realpathSync +realpath.realpathSync = realpathSync +realpath.monkeypatch = monkeypatch +realpath.unmonkeypatch = unmonkeypatch + +var fs = require('fs') +var origRealpath = fs.realpath +var origRealpathSync = fs.realpathSync + +var version = process.version +var ok = /^v[0-5]\./.test(version) +var old = require('./old.js') + +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) +} + +function realpath (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } + + if (typeof cache === 'function') { + cb = cache + cache = null + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb) + } else { + cb(er, result) + } + }) +} + +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } + + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } + } +} + +function monkeypatch () { + fs.realpath = realpath + fs.realpathSync = realpathSync +} + +function unmonkeypatch () { + fs.realpath = origRealpath + fs.realpathSync = origRealpathSync +} diff --git a/node_modules/fs.realpath/old.js b/node_modules/fs.realpath/old.js new file mode 100644 index 0000000..b40305e --- /dev/null +++ b/node_modules/fs.realpath/old.js @@ -0,0 +1,303 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var pathModule = require('path'); +var isWindows = process.platform === 'win32'; +var fs = require('fs'); + +// JavaScript implementation of realpath, ported from node pre-v6 + +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } + + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } +} + +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} + +var normalize = pathModule.normalize; + +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} + +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} + +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } + + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } + + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } + + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } + + if (cache) cache[original] = p; + + return p; +}; + + +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } + + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } + + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } + + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } + + return fs.lstat(base, gotStat); + } + + function gotStat(err, stat) { + if (err) return cb(err); + + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } + + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs.stat(base, function(err) { + if (err) return cb(err); + + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } + + function gotTarget(err, target, base) { + if (err) return cb(err); + + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } + + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; diff --git a/node_modules/fs.realpath/package.json b/node_modules/fs.realpath/package.json new file mode 100644 index 0000000..3edc57d --- /dev/null +++ b/node_modules/fs.realpath/package.json @@ -0,0 +1,26 @@ +{ + "name": "fs.realpath", + "version": "1.0.0", + "description": "Use node's fs.realpath, but fall back to the JS implementation if the native one fails", + "main": "index.js", + "dependencies": {}, + "devDependencies": {}, + "scripts": { + "test": "tap test/*.js --cov" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/fs.realpath.git" + }, + "keywords": [ + "realpath", + "fs", + "polyfill" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "files": [ + "old.js", + "index.js" + ] +} diff --git a/node_modules/gauge/CHANGELOG.md b/node_modules/gauge/CHANGELOG.md new file mode 100644 index 0000000..3c5cc91 --- /dev/null +++ b/node_modules/gauge/CHANGELOG.md @@ -0,0 +1,163 @@ +### v3.0.0 +* Drops support for Node v4, v6, v7 and v8 + +### v2.7.4 + +* Reset colors prior to ending a line, to eliminate flicker when a line + is trucated between start and end color sequences. + +### v2.7.3 + +* Only create our onExit handler when we're enabled and remove it when we're + disabled. This stops us from creating multiple onExit handlers when + multiple gauge objects are being used. +* Fix bug where if a theme name were given instead of a theme object, it + would crash. +* Remove supports-color because it's not actually used. Uhm. Yes, I just + updated it. >.> + +### v2.7.2 + +* Use supports-color instead of has-color (as the module has been renamed) + +### v2.7.1 + +* Bug fix: Calls to show/pulse while the progress bar is disabled should still + update our internal representation of what would be shown should it be enabled. + +### v2.7.0 + +* New feature: Add new `isEnabled` method to allow introspection of the gauge's + "enabledness" as controlled by `.enable()` and `.disable()`. + +### v2.6.0 + +* Bug fix: Don't run the code associated with `enable`/`disable` if the gauge + is already enabled or disabled respectively. This prevents leaking event + listeners, amongst other weirdness. +* New feature: Template items can have default values that will be used if no + value was otherwise passed in. + +### v2.5.3 + +* Default to `enabled` only if we have a tty. Users can always override + this by passing in the `enabled` option explicitly or by calling calling + `gauge.enable()`. + +### v2.5.2 + +* Externalized `./console-strings.js` into `console-control-strings`. + +### v2.5.1 + +* Update to `signal-exit@3.0.0`, which fixes a compatibility bug with the + node profiler. +* [#39](https://github.com/iarna/gauge/pull/39) Fix tests on 0.10 and add + a missing devDependency. ([@helloyou2012](https://github.com/helloyou2012)) + +### v2.5.0 + +* Add way to programmatically fetch a list of theme names in a themeset + (`Themeset.getThemeNames`). + +### v2.4.0 + +* Add support for setting themesets on existing gauge objects. +* Add post-IO callback to `gauge.hide()` as it is somtetimes necessary when + your terminal is interleaving output from multiple filehandles (ie, stdout + & stderr). + +### v2.3.1 + +* Fix a refactor bug in setTheme where it wasn't accepting the various types + of args it should. + +### v2.3.0 + +#### FEATURES + +* Add setTemplate & setTheme back in. +* Add support for named themes, you can now ask for things like 'colorASCII' + and 'brailleSpinner'. Of course, you can still pass in theme objects. + Additionally you can now pass in an object with `hasUnicode`, `hasColor` and + `platform` keys in order to override our guesses as to those values when + selecting a default theme from the themeset. +* Make the output stream optional (it defaults to `process.stderr` now). +* Add `setWriteTo(stream[, tty])` to change the output stream and, + optionally, tty. + +#### BUG FIXES & REFACTORING + +* Abort the display phase early if we're supposed to be hidden and we are. +* Stop printing a bunch of spaces at the end of lines, since we're already + using an erase-to-end-of-line code anyway. +* The unicode themes were missing the subsection separator. + +### v2.2.1 + +* Fix image in readme + +### v2.2.0 + +* All new themes API– reference themes by name and pass in custom themes and + themesets (themesets get platform support autodetection done on them to + select the best theme). Theme mixins let you add features to all existing + themes. +* Much, much improved test coverage. + +### v2.1.0 + +* Got rid of ░ in the default platform, noUnicode, hasColor theme. Thanks + to @yongtw123 for pointing out this had snuck in. +* Fiddled with the demo output to make it easier to see the spinner spin. Also + added prints before each platforms test output. +* I forgot to include `signal-exit` in our deps. <.< Thank you @KenanY for + finding this. Then I was lazy and made a new commit instead of using his + PR. Again, thank you for your patience @KenenY. +* Drastically speed up travis testing. +* Add a small javascript demo (demo.js) for showing off the various themes + (and testing them on diff platforms). +* Change: The subsection separator from ⁄ and / (different chars) to >. +* Fix crasher: A show or pulse without a label would cause the template renderer + to complain about a missing value. +* New feature: Add the ability to disable the clean-up-on-exit behavior. + Not something I expect to be widely desirable, but important if you have + multiple distinct gauge instances in your app. +* Use our own color support detection. + The `has-color` module proved too magic for my needs, making assumptions + as to which stream we write to and reading command line arguments. + +### v2.0.0 + +This is a major rewrite of the internals. Externally there are fewer +changes: + +* On node>0.8 gauge object now prints updates at a fixed rate. This means + that when you call `show` it may wate up to `updateInterval` ms before it + actually prints an update. You override this behavior with the + `fixedFramerate` option. +* The gauge object now keeps the cursor hidden as long as it's enabled and + shown. +* The constructor's arguments have changed, now it takes a mandatory output + stream and an optional options object. The stream no longer needs to be + an `ansi`ified stream, although it can be if you want (but we won't make + use of its special features). +* Previously the gauge was disabled by default if `process.stdout` wasn't a + tty. Now it always defaults to enabled. If you want the previous + behavior set the `enabled` option to `process.stdout.isTTY`. +* The constructor's options have changed– see the docs for details. +* Themes are entirely different. If you were using a custom theme, or + referring to one directly (eg via `Gauge.unicode` or `Gauge.ascii`) then + you'll need to change your code. You can get the equivalent of the latter + with: + ``` + var themes = require('gauge/themes') + var unicodeTheme = themes(true, true) // returns the color unicode theme for your platform + ``` + The default themes no longer use any ambiguous width characters, so even + if you choose to display those as wide your progress bar should still + display correctly. +* Templates are entirely different and if you were using a custom one, you + should consult the documentation to learn how to recreate it. If you were + using the default, be aware that it has changed and the result looks quite + a bit different. diff --git a/node_modules/gauge/LICENSE b/node_modules/gauge/LICENSE new file mode 100644 index 0000000..e756052 --- /dev/null +++ b/node_modules/gauge/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2014, Rebecca Turner + +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/gauge/README.md b/node_modules/gauge/README.md new file mode 100644 index 0000000..4757649 --- /dev/null +++ b/node_modules/gauge/README.md @@ -0,0 +1,402 @@ +gauge +===== + +A nearly stateless terminal based horizontal gauge / progress bar. + +```javascript +var Gauge = require("gauge") + +var gauge = new Gauge() + +gauge.show("working…", 0) +setTimeout(() => { gauge.pulse(); gauge.show("working…", 0.25) }, 500) +setTimeout(() => { gauge.pulse(); gauge.show("working…", 0.50) }, 1000) +setTimeout(() => { gauge.pulse(); gauge.show("working…", 0.75) }, 1500) +setTimeout(() => { gauge.pulse(); gauge.show("working…", 0.99) }, 2000) +setTimeout(() => gauge.hide(), 2300) +``` + +See also the [demos](demo.js): + +![](gauge-demo.gif) + + +### CHANGES FROM 1.x + +Gauge 2.x is breaking release, please see the [changelog] for details on +what's changed if you were previously a user of this module. + +[changelog]: CHANGELOG.md + +### THE GAUGE CLASS + +This is the typical interface to the module– it provides a pretty +fire-and-forget interface to displaying your status information. + +``` +var Gauge = require("gauge") + +var gauge = new Gauge([stream], [options]) +``` + +* **stream** – *(optional, default STDERR)* A stream that progress bar + updates are to be written to. Gauge honors backpressure and will pause + most writing if it is indicated. +* **options** – *(optional)* An option object. + +Constructs a new gauge. Gauges are drawn on a single line, and are not drawn +if **stream** isn't a tty and a tty isn't explicitly provided. + +If **stream** is a terminal or if you pass in **tty** to **options** then we +will detect terminal resizes and redraw to fit. We do this by watching for +`resize` events on the tty. (To work around a bug in versions of Node prior +to 2.5.0, we watch for them on stdout if the tty is stderr.) Resizes to +larger window sizes will be clean, but shrinking the window will always +result in some cruft. + +**IMPORTANT:** If you previously were passing in a non-tty stream but you still +want output (for example, a stream wrapped by the `ansi` module) then you +need to pass in the **tty** option below, as `gauge` needs access to +the underlying tty in order to do things like terminal resizes and terminal +width detection. + +The **options** object can have the following properties, all of which are +optional: + +* **updateInterval**: How often gauge updates should be drawn, in milliseconds. +* **fixedFramerate**: Defaults to false on node 0.8, true on everything + else. When this is true a timer is created to trigger once every + `updateInterval` ms, when false, updates are printed as soon as they come + in but updates more often than `updateInterval` are ignored. The reason + 0.8 doesn't have this set to true is that it can't `unref` its timer and + so it would stop your program from exiting– if you want to use this + feature with 0.8 just make sure you call `gauge.disable()` before you + expect your program to exit. +* **themes**: A themeset to use when selecting the theme to use. Defaults + to `gauge/themes`, see the [themes] documentation for details. +* **theme**: Select a theme for use, it can be a: + * Theme object, in which case the **themes** is not used. + * The name of a theme, which will be looked up in the current *themes* + object. + * A configuration object with any of `hasUnicode`, `hasColor` or + `platform` keys, which if will be used to override our guesses when making + a default theme selection. + + If no theme is selected then a default is picked using a combination of our + best guesses at your OS, color support and unicode support. +* **template**: Describes what you want your gauge to look like. The + default is what npm uses. Detailed [documentation] is later in this + document. +* **hideCursor**: Defaults to true. If true, then the cursor will be hidden + while the gauge is displayed. +* **tty**: The tty that you're ultimately writing to. Defaults to the same + as **stream**. This is used for detecting the width of the terminal and + resizes. The width used is `tty.columns - 1`. If no tty is available then + a width of `79` is assumed. +* **enabled**: Defaults to true if `tty` is a TTY, false otherwise. If true + the gauge starts enabled. If disabled then all update commands are + ignored and no gauge will be printed until you call `.enable()`. +* **Plumbing**: The class to use to actually generate the gauge for + printing. This defaults to `require('gauge/plumbing')` and ordinarily you + shouldn't need to override this. +* **cleanupOnExit**: Defaults to true. Ordinarily we register an exit + handler to make sure your cursor is turned back on and the progress bar + erased when your process exits, even if you Ctrl-C out or otherwise exit + unexpectedly. You can disable this and it won't register the exit handler. + +[has-unicode]: https://www.npmjs.com/package/has-unicode +[themes]: #themes +[documentation]: #templates + +#### `gauge.show(section | status, [completed])` + +The first argument is either the section, the name of the current thing +contributing to progress, or an object with keys like **section**, +**subsection** & **completed** (or any others you have types for in a custom +template). If you don't want to update or set any of these you can pass +`null` and it will be ignored. + +The second argument is the percent completed as a value between 0 and 1. +Without it, completion is just not updated. You'll also note that completion +can be passed in as part of a status object as the first argument. If both +it and the completed argument are passed in, the completed argument wins. + +#### `gauge.hide([cb])` + +Removes the gauge from the terminal. Optionally, callback `cb` after IO has +had an opportunity to happen (currently this just means after `setImmediate` +has called back.) + +It turns out this is important when you're pausing the progress bar on one +filehandle and printing to another– otherwise (with a big enough print) node +can end up printing the "end progress bar" bits to the progress bar filehandle +while other stuff is printing to another filehandle. These getting interleaved +can cause corruption in some terminals. + +#### `gauge.pulse([subsection])` + +* **subsection** – *(optional)* The specific thing that triggered this pulse + +Spins the spinner in the gauge to show output. If **subsection** is +included then it will be combined with the last name passed to `gauge.show`. + +#### `gauge.disable()` + +Hides the gauge and ignores further calls to `show` or `pulse`. + +#### `gauge.enable()` + +Shows the gauge and resumes updating when `show` or `pulse` is called. + +#### `gauge.isEnabled()` + +Returns true if the gauge is enabled. + +#### `gauge.setThemeset(themes)` + +Change the themeset to select a theme from. The same as the `themes` option +used in the constructor. The theme will be reselected from this themeset. + +#### `gauge.setTheme(theme)` + +Change the active theme, will be displayed with the next show or pulse. This can be: + +* Theme object, in which case the **themes** is not used. +* The name of a theme, which will be looked up in the current *themes* + object. +* A configuration object with any of `hasUnicode`, `hasColor` or + `platform` keys, which if will be used to override our guesses when making + a default theme selection. + +If no theme is selected then a default is picked using a combination of our +best guesses at your OS, color support and unicode support. + +#### `gauge.setTemplate(template)` + +Change the active template, will be displayed with the next show or pulse + +### Tracking Completion + +If you have more than one thing going on that you want to track completion +of, you may find the related [are-we-there-yet] helpful. It's `change` +event can be wired up to the `show` method to get a more traditional +progress bar interface. + +[are-we-there-yet]: https://www.npmjs.com/package/are-we-there-yet + +### THEMES + +``` +var themes = require('gauge/themes') + +// fetch the default color unicode theme for this platform +var ourTheme = themes({hasUnicode: true, hasColor: true}) + +// fetch the default non-color unicode theme for osx +var ourTheme = themes({hasUnicode: true, hasColor: false, platform: 'darwin'}) + +// create a new theme based on the color ascii theme for this platform +// that brackets the progress bar with arrows +var ourTheme = themes.newTheme(themes({hasUnicode: false, hasColor: true}), { + preProgressbar: '→', + postProgressbar: '←' +}) +``` + +The object returned by `gauge/themes` is an instance of the `ThemeSet` class. + +``` +var ThemeSet = require('gauge/theme-set') +var themes = new ThemeSet() +// or +var themes = require('gauge/themes') +var mythemes = themes.newThemeSet() // creates a new themeset based on the default themes +``` + +#### themes(opts) +#### themes.getDefault(opts) + +Theme objects are a function that fetches the default theme based on +platform, unicode and color support. + +Options is an object with the following properties: + +* **hasUnicode** - If true, fetch a unicode theme, if no unicode theme is + available then a non-unicode theme will be used. +* **hasColor** - If true, fetch a color theme, if no color theme is + available a non-color theme will be used. +* **platform** (optional) - Defaults to `process.platform`. If no + platform match is available then `fallback` is used instead. + +If no compatible theme can be found then an error will be thrown with a +`code` of `EMISSINGTHEME`. + +#### themes.addTheme(themeName, themeObj) +#### themes.addTheme(themeName, [parentTheme], newTheme) + +Adds a named theme to the themeset. You can pass in either a theme object, +as returned by `themes.newTheme` or the arguments you'd pass to +`themes.newTheme`. + +#### themes.getThemeNames() + +Return a list of all of the names of the themes in this themeset. Suitable +for use in `themes.getTheme(…)`. + +#### themes.getTheme(name) + +Returns the theme object from this theme set named `name`. + +If `name` does not exist in this themeset an error will be thrown with +a `code` of `EMISSINGTHEME`. + +#### themes.setDefault([opts], themeName) + +`opts` is an object with the following properties. + +* **platform** - Defaults to `'fallback'`. If your theme is platform + specific, specify that here with the platform from `process.platform`, eg, + `win32`, `darwin`, etc. +* **hasUnicode** - Defaults to `false`. If your theme uses unicode you + should set this to true. +* **hasColor** - Defaults to `false`. If your theme uses color you should + set this to true. + +`themeName` is the name of the theme (as given to `addTheme`) to use for +this set of `opts`. + +#### themes.newTheme([parentTheme,] newTheme) + +Create a new theme object based on `parentTheme`. If no `parentTheme` is +provided then a minimal parentTheme that defines functions for rendering the +activity indicator (spinner) and progress bar will be defined. (This +fallback parent is defined in `gauge/base-theme`.) + +newTheme should be a bare object– we'll start by discussing the properties +defined by the default themes: + +* **preProgressbar** - displayed prior to the progress bar, if the progress + bar is displayed. +* **postProgressbar** - displayed after the progress bar, if the progress bar + is displayed. +* **progressBarTheme** - The subtheme passed through to the progress bar + renderer, it's an object with `complete` and `remaining` properties + that are the strings you want repeated for those sections of the progress + bar. +* **activityIndicatorTheme** - The theme for the activity indicator (spinner), + this can either be a string, in which each character is a different step, or + an array of strings. +* **preSubsection** - Displayed as a separator between the `section` and + `subsection` when the latter is printed. + +More generally, themes can have any value that would be a valid value when rendering +templates. The properties in the theme are used when their name matches a type in +the template. Their values can be: + +* **strings & numbers** - They'll be included as is +* **function (values, theme, width)** - Should return what you want in your output. + *values* is an object with values provided via `gauge.show`, + *theme* is the theme specific to this item (see below) or this theme object, + and *width* is the number of characters wide your result should be. + +There are a couple of special prefixes: + +* **pre** - Is shown prior to the property, if its displayed. +* **post** - Is shown after the property, if its displayed. + +And one special suffix: + +* **Theme** - Its value is passed to a function-type item as the theme. + +#### themes.addToAllThemes(theme) + +This *mixes-in* `theme` into all themes currently defined. It also adds it +to the default parent theme for this themeset, so future themes added to +this themeset will get the values from `theme` by default. + +#### themes.newThemeSet() + +Copy the current themeset into a new one. This allows you to easily inherit +one themeset from another. + +### TEMPLATES + +A template is an array of objects and strings that, after being evaluated, +will be turned into the gauge line. The default template is: + +```javascript +[ + {type: 'progressbar', length: 20}, + {type: 'activityIndicator', kerning: 1, length: 1}, + {type: 'section', kerning: 1, default: ''}, + {type: 'subsection', kerning: 1, default: ''} +] +``` + +The various template elements can either be **plain strings**, in which case they will +be be included verbatum in the output, or objects with the following properties: + +* *type* can be any of the following plus any keys you pass into `gauge.show` plus + any keys you have on a custom theme. + * `section` – What big thing you're working on now. + * `subsection` – What component of that thing is currently working. + * `activityIndicator` – Shows a spinner using the `activityIndicatorTheme` + from your active theme. + * `progressbar` – A progress bar representing your current `completed` + using the `progressbarTheme` from your active theme. +* *kerning* – Number of spaces that must be between this item and other + items, if this item is displayed at all. +* *maxLength* – The maximum length for this element. If its value is longer it + will be truncated. +* *minLength* – The minimum length for this element. If its value is shorter it + will be padded according to the *align* value. +* *align* – (Default: left) Possible values "left", "right" and "center". Works + as you'd expect from word processors. +* *length* – Provides a single value for both *minLength* and *maxLength*. If both + *length* and *minLength or *maxLength* are specified then the latter take precedence. +* *value* – A literal value to use for this template item. +* *default* – A default value to use for this template item if a value + wasn't otherwise passed in. + +### PLUMBING + +This is the super simple, assume nothing, do no magic internals used by gauge to +implement its ordinary interface. + +``` +var Plumbing = require('gauge/plumbing') +var gauge = new Plumbing(theme, template, width) +``` + +* **theme**: The theme to use. +* **template**: The template to use. +* **width**: How wide your gauge should be + +#### `gauge.setTheme(theme)` + +Change the active theme. + +#### `gauge.setTemplate(template)` + +Change the active template. + +#### `gauge.setWidth(width)` + +Change the width to render at. + +#### `gauge.hide()` + +Return the string necessary to hide the progress bar + +#### `gauge.hideCursor()` + +Return a string to hide the cursor. + +#### `gauge.showCursor()` + +Return a string to show the cursor. + +#### `gauge.show(status)` + +Using `status` for values, render the provided template with the theme and return +a string that is suitable for printing to update the gauge. diff --git a/node_modules/gauge/base-theme.js b/node_modules/gauge/base-theme.js new file mode 100644 index 0000000..0b67638 --- /dev/null +++ b/node_modules/gauge/base-theme.js @@ -0,0 +1,14 @@ +'use strict' +var spin = require('./spin.js') +var progressBar = require('./progress-bar.js') + +module.exports = { + activityIndicator: function (values, theme, width) { + if (values.spun == null) return + return spin(theme, values.spun) + }, + progressbar: function (values, theme, width) { + if (values.completed == null) return + return progressBar(theme, width, values.completed) + } +} diff --git a/node_modules/gauge/error.js b/node_modules/gauge/error.js new file mode 100644 index 0000000..d9914ba --- /dev/null +++ b/node_modules/gauge/error.js @@ -0,0 +1,24 @@ +'use strict' +var util = require('util') + +var User = exports.User = function User (msg) { + var err = new Error(msg) + Error.captureStackTrace(err, User) + err.code = 'EGAUGE' + return err +} + +exports.MissingTemplateValue = function MissingTemplateValue (item, values) { + var err = new User(util.format('Missing template value "%s"', item.type)) + Error.captureStackTrace(err, MissingTemplateValue) + err.template = item + err.values = values + return err +} + +exports.Internal = function Internal (msg) { + var err = new Error(msg) + Error.captureStackTrace(err, Internal) + err.code = 'EGAUGEINTERNAL' + return err +} diff --git a/node_modules/gauge/has-color.js b/node_modules/gauge/has-color.js new file mode 100644 index 0000000..16cba0e --- /dev/null +++ b/node_modules/gauge/has-color.js @@ -0,0 +1,4 @@ +'use strict' +var colorSupport = require('color-support') + +module.exports = colorSupport().hasBasic diff --git a/node_modules/gauge/index.js b/node_modules/gauge/index.js new file mode 100644 index 0000000..87a4bb9 --- /dev/null +++ b/node_modules/gauge/index.js @@ -0,0 +1,233 @@ +'use strict' +var Plumbing = require('./plumbing.js') +var hasUnicode = require('has-unicode') +var hasColor = require('./has-color.js') +var onExit = require('signal-exit') +var defaultThemes = require('./themes') +var setInterval = require('./set-interval.js') +var process = require('./process.js') +var setImmediate = require('./set-immediate') + +module.exports = Gauge + +function callWith (obj, method) { + return function () { + return method.call(obj) + } +} + +function Gauge (arg1, arg2) { + var options, writeTo + if (arg1 && arg1.write) { + writeTo = arg1 + options = arg2 || {} + } else if (arg2 && arg2.write) { + writeTo = arg2 + options = arg1 || {} + } else { + writeTo = process.stderr + options = arg1 || arg2 || {} + } + + this._status = { + spun: 0, + section: '', + subsection: '' + } + this._paused = false // are we paused for back pressure? + this._disabled = true // are all progress bar updates disabled? + this._showing = false // do we WANT the progress bar on screen + this._onScreen = false // IS the progress bar on screen + this._needsRedraw = false // should we print something at next tick? + this._hideCursor = options.hideCursor == null ? true : options.hideCursor + this._fixedFramerate = options.fixedFramerate == null + ? !(/^v0\.8\./.test(process.version)) + : options.fixedFramerate + this._lastUpdateAt = null + this._updateInterval = options.updateInterval == null ? 50 : options.updateInterval + + this._themes = options.themes || defaultThemes + this._theme = options.theme + var theme = this._computeTheme(options.theme) + var template = options.template || [ + {type: 'progressbar', length: 20}, + {type: 'activityIndicator', kerning: 1, length: 1}, + {type: 'section', kerning: 1, default: ''}, + {type: 'subsection', kerning: 1, default: ''} + ] + this.setWriteTo(writeTo, options.tty) + var PlumbingClass = options.Plumbing || Plumbing + this._gauge = new PlumbingClass(theme, template, this.getWidth()) + + this._$$doRedraw = callWith(this, this._doRedraw) + this._$$handleSizeChange = callWith(this, this._handleSizeChange) + + this._cleanupOnExit = options.cleanupOnExit == null || options.cleanupOnExit + this._removeOnExit = null + + if (options.enabled || (options.enabled == null && this._tty && this._tty.isTTY)) { + this.enable() + } else { + this.disable() + } +} +Gauge.prototype = {} + +Gauge.prototype.isEnabled = function () { + return !this._disabled +} + +Gauge.prototype.setTemplate = function (template) { + this._gauge.setTemplate(template) + if (this._showing) this._requestRedraw() +} + +Gauge.prototype._computeTheme = function (theme) { + if (!theme) theme = {} + if (typeof theme === 'string') { + theme = this._themes.getTheme(theme) + } else if (theme && (Object.keys(theme).length === 0 || theme.hasUnicode != null || theme.hasColor != null)) { + var useUnicode = theme.hasUnicode == null ? hasUnicode() : theme.hasUnicode + var useColor = theme.hasColor == null ? hasColor : theme.hasColor + theme = this._themes.getDefault({hasUnicode: useUnicode, hasColor: useColor, platform: theme.platform}) + } + return theme +} + +Gauge.prototype.setThemeset = function (themes) { + this._themes = themes + this.setTheme(this._theme) +} + +Gauge.prototype.setTheme = function (theme) { + this._gauge.setTheme(this._computeTheme(theme)) + if (this._showing) this._requestRedraw() + this._theme = theme +} + +Gauge.prototype._requestRedraw = function () { + this._needsRedraw = true + if (!this._fixedFramerate) this._doRedraw() +} + +Gauge.prototype.getWidth = function () { + return ((this._tty && this._tty.columns) || 80) - 1 +} + +Gauge.prototype.setWriteTo = function (writeTo, tty) { + var enabled = !this._disabled + if (enabled) this.disable() + this._writeTo = writeTo + this._tty = tty || + (writeTo === process.stderr && process.stdout.isTTY && process.stdout) || + (writeTo.isTTY && writeTo) || + this._tty + if (this._gauge) this._gauge.setWidth(this.getWidth()) + if (enabled) this.enable() +} + +Gauge.prototype.enable = function () { + if (!this._disabled) return + this._disabled = false + if (this._tty) this._enableEvents() + if (this._showing) this.show() +} + +Gauge.prototype.disable = function () { + if (this._disabled) return + if (this._showing) { + this._lastUpdateAt = null + this._showing = false + this._doRedraw() + this._showing = true + } + this._disabled = true + if (this._tty) this._disableEvents() +} + +Gauge.prototype._enableEvents = function () { + if (this._cleanupOnExit) { + this._removeOnExit = onExit(callWith(this, this.disable)) + } + this._tty.on('resize', this._$$handleSizeChange) + if (this._fixedFramerate) { + this.redrawTracker = setInterval(this._$$doRedraw, this._updateInterval) + if (this.redrawTracker.unref) this.redrawTracker.unref() + } +} + +Gauge.prototype._disableEvents = function () { + this._tty.removeListener('resize', this._$$handleSizeChange) + if (this._fixedFramerate) clearInterval(this.redrawTracker) + if (this._removeOnExit) this._removeOnExit() +} + +Gauge.prototype.hide = function (cb) { + if (this._disabled) return cb && process.nextTick(cb) + if (!this._showing) return cb && process.nextTick(cb) + this._showing = false + this._doRedraw() + cb && setImmediate(cb) +} + +Gauge.prototype.show = function (section, completed) { + this._showing = true + if (typeof section === 'string') { + this._status.section = section + } else if (typeof section === 'object') { + var sectionKeys = Object.keys(section) + for (var ii = 0; ii < sectionKeys.length; ++ii) { + var key = sectionKeys[ii] + this._status[key] = section[key] + } + } + if (completed != null) this._status.completed = completed + if (this._disabled) return + this._requestRedraw() +} + +Gauge.prototype.pulse = function (subsection) { + this._status.subsection = subsection || '' + this._status.spun++ + if (this._disabled) return + if (!this._showing) return + this._requestRedraw() +} + +Gauge.prototype._handleSizeChange = function () { + this._gauge.setWidth(this._tty.columns - 1) + this._requestRedraw() +} + +Gauge.prototype._doRedraw = function () { + if (this._disabled || this._paused) return + if (!this._fixedFramerate) { + var now = Date.now() + if (this._lastUpdateAt && now - this._lastUpdateAt < this._updateInterval) return + this._lastUpdateAt = now + } + if (!this._showing && this._onScreen) { + this._onScreen = false + var result = this._gauge.hide() + if (this._hideCursor) { + result += this._gauge.showCursor() + } + return this._writeTo.write(result) + } + if (!this._showing && !this._onScreen) return + if (this._showing && !this._onScreen) { + this._onScreen = true + this._needsRedraw = true + if (this._hideCursor) { + this._writeTo.write(this._gauge.hideCursor()) + } + } + if (!this._needsRedraw) return + if (!this._writeTo.write(this._gauge.show(this._status))) { + this._paused = true + this._writeTo.on('drain', callWith(this, function () { + this._paused = false + this._doRedraw() + })) + } +} diff --git a/node_modules/gauge/package.json b/node_modules/gauge/package.json new file mode 100644 index 0000000..d3f0354 --- /dev/null +++ b/node_modules/gauge/package.json @@ -0,0 +1,66 @@ +{ + "name": "gauge", + "version": "3.0.2", + "description": "A terminal based horizontal guage", + "main": "index.js", + "scripts": { + "test": "standard && tap test/*.js --coverage" + }, + "repository": { + "type": "git", + "url": "https://github.com/iarna/gauge" + }, + "keywords": [ + "progressbar", + "progress", + "gauge" + ], + "author": "Rebecca Turner ", + "license": "ISC", + "bugs": { + "url": "https://github.com/npm/gauge/issues" + }, + "homepage": "https://github.com/npm/gauge", + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.2", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.1", + "object-assign": "^4.1.1", + "signal-exit": "^3.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.2" + }, + "devDependencies": { + "readable-stream": "^2.0.6", + "require-inject": "^1.4.0", + "standard": "^11.0.1", + "tap": "^12.0.1", + "through2": "^2.0.0" + }, + "files": [ + "base-theme.js", + "CHANGELOG.md", + "error.js", + "has-color.js", + "index.js", + "LICENSE", + "package.json", + "plumbing.js", + "process.js", + "progress-bar.js", + "README.md", + "render-template.js", + "set-immediate.js", + "set-interval.js", + "spin.js", + "template-item.js", + "theme-set.js", + "themes.js", + "wide-truncate.js" + ], + "engines": { + "node": ">=10" + } +} diff --git a/node_modules/gauge/plumbing.js b/node_modules/gauge/plumbing.js new file mode 100644 index 0000000..1afb4af --- /dev/null +++ b/node_modules/gauge/plumbing.js @@ -0,0 +1,48 @@ +'use strict' +var consoleControl = require('console-control-strings') +var renderTemplate = require('./render-template.js') +var validate = require('aproba') + +var Plumbing = module.exports = function (theme, template, width) { + if (!width) width = 80 + validate('OAN', [theme, template, width]) + this.showing = false + this.theme = theme + this.width = width + this.template = template +} +Plumbing.prototype = {} + +Plumbing.prototype.setTheme = function (theme) { + validate('O', [theme]) + this.theme = theme +} + +Plumbing.prototype.setTemplate = function (template) { + validate('A', [template]) + this.template = template +} + +Plumbing.prototype.setWidth = function (width) { + validate('N', [width]) + this.width = width +} + +Plumbing.prototype.hide = function () { + return consoleControl.gotoSOL() + consoleControl.eraseLine() +} + +Plumbing.prototype.hideCursor = consoleControl.hideCursor + +Plumbing.prototype.showCursor = consoleControl.showCursor + +Plumbing.prototype.show = function (status) { + var values = Object.create(this.theme) + for (var key in status) { + values[key] = status[key] + } + + return renderTemplate(this.width, this.template, values).trim() + + consoleControl.color('reset') + + consoleControl.eraseLine() + consoleControl.gotoSOL() +} diff --git a/node_modules/gauge/process.js b/node_modules/gauge/process.js new file mode 100644 index 0000000..05e8569 --- /dev/null +++ b/node_modules/gauge/process.js @@ -0,0 +1,3 @@ +'use strict' +// this exists so we can replace it during testing +module.exports = process diff --git a/node_modules/gauge/progress-bar.js b/node_modules/gauge/progress-bar.js new file mode 100644 index 0000000..1780a8a --- /dev/null +++ b/node_modules/gauge/progress-bar.js @@ -0,0 +1,35 @@ +'use strict' +var validate = require('aproba') +var renderTemplate = require('./render-template.js') +var wideTruncate = require('./wide-truncate') +var stringWidth = require('string-width') + +module.exports = function (theme, width, completed) { + validate('ONN', [theme, width, completed]) + if (completed < 0) completed = 0 + if (completed > 1) completed = 1 + if (width <= 0) return '' + var sofar = Math.round(width * completed) + var rest = width - sofar + var template = [ + {type: 'complete', value: repeat(theme.complete, sofar), length: sofar}, + {type: 'remaining', value: repeat(theme.remaining, rest), length: rest} + ] + return renderTemplate(width, template, theme) +} + +// lodash's way of repeating +function repeat (string, width) { + var result = '' + var n = width + do { + if (n % 2) { + result += string + } + n = Math.floor(n / 2) + /* eslint no-self-assign: 0 */ + string += string + } while (n && stringWidth(result) < width) + + return wideTruncate(result, width) +} diff --git a/node_modules/gauge/render-template.js b/node_modules/gauge/render-template.js new file mode 100644 index 0000000..9764c6e --- /dev/null +++ b/node_modules/gauge/render-template.js @@ -0,0 +1,178 @@ +'use strict' +var align = require('wide-align') +var validate = require('aproba') +var wideTruncate = require('./wide-truncate') +var error = require('./error') +var TemplateItem = require('./template-item') + +function renderValueWithValues (values) { + return function (item) { + return renderValue(item, values) + } +} + +var renderTemplate = module.exports = function (width, template, values) { + var items = prepareItems(width, template, values) + var rendered = items.map(renderValueWithValues(values)).join('') + return align.left(wideTruncate(rendered, width), width) +} + +function preType (item) { + var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1) + return 'pre' + cappedTypeName +} + +function postType (item) { + var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1) + return 'post' + cappedTypeName +} + +function hasPreOrPost (item, values) { + if (!item.type) return + return values[preType(item)] || values[postType(item)] +} + +function generatePreAndPost (baseItem, parentValues) { + var item = Object.assign({}, baseItem) + var values = Object.create(parentValues) + var template = [] + var pre = preType(item) + var post = postType(item) + if (values[pre]) { + template.push({value: values[pre]}) + values[pre] = null + } + item.minLength = null + item.length = null + item.maxLength = null + template.push(item) + values[item.type] = values[item.type] + if (values[post]) { + template.push({value: values[post]}) + values[post] = null + } + return function ($1, $2, length) { + return renderTemplate(length, template, values) + } +} + +function prepareItems (width, template, values) { + function cloneAndObjectify (item, index, arr) { + var cloned = new TemplateItem(item, width) + var type = cloned.type + if (cloned.value == null) { + if (!(type in values)) { + if (cloned.default == null) { + throw new error.MissingTemplateValue(cloned, values) + } else { + cloned.value = cloned.default + } + } else { + cloned.value = values[type] + } + } + if (cloned.value == null || cloned.value === '') return null + cloned.index = index + cloned.first = index === 0 + cloned.last = index === arr.length - 1 + if (hasPreOrPost(cloned, values)) cloned.value = generatePreAndPost(cloned, values) + return cloned + } + + var output = template.map(cloneAndObjectify).filter(function (item) { return item != null }) + + var remainingSpace = width + var variableCount = output.length + + function consumeSpace (length) { + if (length > remainingSpace) length = remainingSpace + remainingSpace -= length + } + + function finishSizing (item, length) { + if (item.finished) throw new error.Internal('Tried to finish template item that was already finished') + if (length === Infinity) throw new error.Internal('Length of template item cannot be infinity') + if (length != null) item.length = length + item.minLength = null + item.maxLength = null + --variableCount + item.finished = true + if (item.length == null) item.length = item.getBaseLength() + if (item.length == null) throw new error.Internal('Finished template items must have a length') + consumeSpace(item.getLength()) + } + + output.forEach(function (item) { + if (!item.kerning) return + var prevPadRight = item.first ? 0 : output[item.index - 1].padRight + if (!item.first && prevPadRight < item.kerning) item.padLeft = item.kerning - prevPadRight + if (!item.last) item.padRight = item.kerning + }) + + // Finish any that have a fixed (literal or intuited) length + output.forEach(function (item) { + if (item.getBaseLength() == null) return + finishSizing(item) + }) + + var resized = 0 + var resizing + var hunkSize + do { + resizing = false + hunkSize = Math.round(remainingSpace / variableCount) + output.forEach(function (item) { + if (item.finished) return + if (!item.maxLength) return + if (item.getMaxLength() < hunkSize) { + finishSizing(item, item.maxLength) + resizing = true + } + }) + } while (resizing && resized++ < output.length) + if (resizing) throw new error.Internal('Resize loop iterated too many times while determining maxLength') + + resized = 0 + do { + resizing = false + hunkSize = Math.round(remainingSpace / variableCount) + output.forEach(function (item) { + if (item.finished) return + if (!item.minLength) return + if (item.getMinLength() >= hunkSize) { + finishSizing(item, item.minLength) + resizing = true + } + }) + } while (resizing && resized++ < output.length) + if (resizing) throw new error.Internal('Resize loop iterated too many times while determining minLength') + + hunkSize = Math.round(remainingSpace / variableCount) + output.forEach(function (item) { + if (item.finished) return + finishSizing(item, hunkSize) + }) + + return output +} + +function renderFunction (item, values, length) { + validate('OON', arguments) + if (item.type) { + return item.value(values, values[item.type + 'Theme'] || {}, length) + } else { + return item.value(values, {}, length) + } +} + +function renderValue (item, values) { + var length = item.getBaseLength() + var value = typeof item.value === 'function' ? renderFunction(item, values, length) : item.value + if (value == null || value === '') return '' + var alignWith = align[item.align] || align.left + var leftPadding = item.padLeft ? align.left('', item.padLeft) : '' + var rightPadding = item.padRight ? align.right('', item.padRight) : '' + var truncated = wideTruncate(String(value), length) + var aligned = alignWith(truncated, length) + return leftPadding + aligned + rightPadding +} diff --git a/node_modules/gauge/set-immediate.js b/node_modules/gauge/set-immediate.js new file mode 100644 index 0000000..6650a48 --- /dev/null +++ b/node_modules/gauge/set-immediate.js @@ -0,0 +1,7 @@ +'use strict' +var process = require('./process') +try { + module.exports = setImmediate +} catch (ex) { + module.exports = process.nextTick +} diff --git a/node_modules/gauge/set-interval.js b/node_modules/gauge/set-interval.js new file mode 100644 index 0000000..5761987 --- /dev/null +++ b/node_modules/gauge/set-interval.js @@ -0,0 +1,3 @@ +'use strict' +// this exists so we can replace it during testing +module.exports = setInterval diff --git a/node_modules/gauge/spin.js b/node_modules/gauge/spin.js new file mode 100644 index 0000000..34142ee --- /dev/null +++ b/node_modules/gauge/spin.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports = function spin (spinstr, spun) { + return spinstr[spun % spinstr.length] +} diff --git a/node_modules/gauge/template-item.js b/node_modules/gauge/template-item.js new file mode 100644 index 0000000..4f02fef --- /dev/null +++ b/node_modules/gauge/template-item.js @@ -0,0 +1,72 @@ +'use strict' +var stringWidth = require('string-width') + +module.exports = TemplateItem + +function isPercent (num) { + if (typeof num !== 'string') return false + return num.slice(-1) === '%' +} + +function percent (num) { + return Number(num.slice(0, -1)) / 100 +} + +function TemplateItem (values, outputLength) { + this.overallOutputLength = outputLength + this.finished = false + this.type = null + this.value = null + this.length = null + this.maxLength = null + this.minLength = null + this.kerning = null + this.align = 'left' + this.padLeft = 0 + this.padRight = 0 + this.index = null + this.first = null + this.last = null + if (typeof values === 'string') { + this.value = values + } else { + for (var prop in values) this[prop] = values[prop] + } + // Realize percents + if (isPercent(this.length)) { + this.length = Math.round(this.overallOutputLength * percent(this.length)) + } + if (isPercent(this.minLength)) { + this.minLength = Math.round(this.overallOutputLength * percent(this.minLength)) + } + if (isPercent(this.maxLength)) { + this.maxLength = Math.round(this.overallOutputLength * percent(this.maxLength)) + } + return this +} + +TemplateItem.prototype = {} + +TemplateItem.prototype.getBaseLength = function () { + var length = this.length + if (length == null && typeof this.value === 'string' && this.maxLength == null && this.minLength == null) { + length = stringWidth(this.value) + } + return length +} + +TemplateItem.prototype.getLength = function () { + var length = this.getBaseLength() + if (length == null) return null + return length + this.padLeft + this.padRight +} + +TemplateItem.prototype.getMaxLength = function () { + if (this.maxLength == null) return null + return this.maxLength + this.padLeft + this.padRight +} + +TemplateItem.prototype.getMinLength = function () { + if (this.minLength == null) return null + return this.minLength + this.padLeft + this.padRight +} diff --git a/node_modules/gauge/theme-set.js b/node_modules/gauge/theme-set.js new file mode 100644 index 0000000..c022d61 --- /dev/null +++ b/node_modules/gauge/theme-set.js @@ -0,0 +1,114 @@ +'use strict' +var objectAssign = require('object-assign') + +module.exports = function () { + return ThemeSetProto.newThemeSet() +} + +var ThemeSetProto = {} + +ThemeSetProto.baseTheme = require('./base-theme.js') + +ThemeSetProto.newTheme = function (parent, theme) { + if (!theme) { + theme = parent + parent = this.baseTheme + } + return objectAssign({}, parent, theme) +} + +ThemeSetProto.getThemeNames = function () { + return Object.keys(this.themes) +} + +ThemeSetProto.addTheme = function (name, parent, theme) { + this.themes[name] = this.newTheme(parent, theme) +} + +ThemeSetProto.addToAllThemes = function (theme) { + var themes = this.themes + Object.keys(themes).forEach(function (name) { + objectAssign(themes[name], theme) + }) + objectAssign(this.baseTheme, theme) +} + +ThemeSetProto.getTheme = function (name) { + if (!this.themes[name]) throw this.newMissingThemeError(name) + return this.themes[name] +} + +ThemeSetProto.setDefault = function (opts, name) { + if (name == null) { + name = opts + opts = {} + } + var platform = opts.platform == null ? 'fallback' : opts.platform + var hasUnicode = !!opts.hasUnicode + var hasColor = !!opts.hasColor + if (!this.defaults[platform]) this.defaults[platform] = {true: {}, false: {}} + this.defaults[platform][hasUnicode][hasColor] = name +} + +ThemeSetProto.getDefault = function (opts) { + if (!opts) opts = {} + var platformName = opts.platform || process.platform + var platform = this.defaults[platformName] || this.defaults.fallback + var hasUnicode = !!opts.hasUnicode + var hasColor = !!opts.hasColor + if (!platform) throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor) + if (!platform[hasUnicode][hasColor]) { + if (hasUnicode && hasColor && platform[!hasUnicode][hasColor]) { + hasUnicode = false + } else if (hasUnicode && hasColor && platform[hasUnicode][!hasColor]) { + hasColor = false + } else if (hasUnicode && hasColor && platform[!hasUnicode][!hasColor]) { + hasUnicode = false + hasColor = false + } else if (hasUnicode && !hasColor && platform[!hasUnicode][hasColor]) { + hasUnicode = false + } else if (!hasUnicode && hasColor && platform[hasUnicode][!hasColor]) { + hasColor = false + } else if (platform === this.defaults.fallback) { + throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor) + } + } + if (platform[hasUnicode][hasColor]) { + return this.getTheme(platform[hasUnicode][hasColor]) + } else { + return this.getDefault(objectAssign({}, opts, {platform: 'fallback'})) + } +} + +ThemeSetProto.newMissingThemeError = function newMissingThemeError (name) { + var err = new Error('Could not find a gauge theme named "' + name + '"') + Error.captureStackTrace.call(err, newMissingThemeError) + err.theme = name + err.code = 'EMISSINGTHEME' + return err +} + +ThemeSetProto.newMissingDefaultThemeError = function newMissingDefaultThemeError (platformName, hasUnicode, hasColor) { + var err = new Error( + 'Could not find a gauge theme for your platform/unicode/color use combo:\n' + + ' platform = ' + platformName + '\n' + + ' hasUnicode = ' + hasUnicode + '\n' + + ' hasColor = ' + hasColor) + Error.captureStackTrace.call(err, newMissingDefaultThemeError) + err.platform = platformName + err.hasUnicode = hasUnicode + err.hasColor = hasColor + err.code = 'EMISSINGTHEME' + return err +} + +ThemeSetProto.newThemeSet = function () { + var themeset = function (opts) { + return themeset.getDefault(opts) + } + return objectAssign(themeset, ThemeSetProto, { + themes: objectAssign({}, this.themes), + baseTheme: objectAssign({}, this.baseTheme), + defaults: JSON.parse(JSON.stringify(this.defaults || {})) + }) +} diff --git a/node_modules/gauge/themes.js b/node_modules/gauge/themes.js new file mode 100644 index 0000000..df1184d --- /dev/null +++ b/node_modules/gauge/themes.js @@ -0,0 +1,56 @@ +'use strict' +var color = require('console-control-strings').color +var ThemeSet = require('./theme-set.js') + +var themes = module.exports = new ThemeSet() + +themes.addTheme('ASCII', { + preProgressbar: '[', + postProgressbar: ']', + progressbarTheme: { + complete: '#', + remaining: '.' + }, + activityIndicatorTheme: '-\\|/', + preSubsection: '>' +}) + +themes.addTheme('colorASCII', themes.getTheme('ASCII'), { + progressbarTheme: { + preComplete: color('bgBrightWhite', 'brightWhite'), + complete: '#', + postComplete: color('reset'), + preRemaining: color('bgBrightBlack', 'brightBlack'), + remaining: '.', + postRemaining: color('reset') + } +}) + +themes.addTheme('brailleSpinner', { + preProgressbar: '⸨', + postProgressbar: '⸩', + progressbarTheme: { + complete: '#', + remaining: '⠂' + }, + activityIndicatorTheme: '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏', + preSubsection: '>' +}) + +themes.addTheme('colorBrailleSpinner', themes.getTheme('brailleSpinner'), { + progressbarTheme: { + preComplete: color('bgBrightWhite', 'brightWhite'), + complete: '#', + postComplete: color('reset'), + preRemaining: color('bgBrightBlack', 'brightBlack'), + remaining: '⠂', + postRemaining: color('reset') + } +}) + +themes.setDefault({}, 'ASCII') +themes.setDefault({hasColor: true}, 'colorASCII') +themes.setDefault({platform: 'darwin', hasUnicode: true}, 'brailleSpinner') +themes.setDefault({platform: 'darwin', hasUnicode: true, hasColor: true}, 'colorBrailleSpinner') +themes.setDefault({platform: 'linux', hasUnicode: true}, 'brailleSpinner') +themes.setDefault({platform: 'linux', hasUnicode: true, hasColor: true}, 'colorBrailleSpinner') diff --git a/node_modules/gauge/wide-truncate.js b/node_modules/gauge/wide-truncate.js new file mode 100644 index 0000000..c531bc4 --- /dev/null +++ b/node_modules/gauge/wide-truncate.js @@ -0,0 +1,25 @@ +'use strict' +var stringWidth = require('string-width') +var stripAnsi = require('strip-ansi') + +module.exports = wideTruncate + +function wideTruncate (str, target) { + if (stringWidth(str) === 0) return str + if (target <= 0) return '' + if (stringWidth(str) <= target) return str + + // We compute the number of bytes of ansi sequences here and add + // that to our initial truncation to ensure that we don't slice one + // that we want to keep in half. + var noAnsi = stripAnsi(str) + var ansiSize = str.length + noAnsi.length + var truncated = str.slice(0, target + ansiSize) + + // we have to shrink the result to account for our ansi sequence buffer + // (if an ansi sequence was truncated) and double width characters. + while (stringWidth(truncated) > target) { + truncated = truncated.slice(0, -1) + } + return truncated +} diff --git a/node_modules/glob/LICENSE b/node_modules/glob/LICENSE new file mode 100644 index 0000000..42ca266 --- /dev/null +++ b/node_modules/glob/LICENSE @@ -0,0 +1,21 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +## Glob Logo + +Glob's logo created by Tanya Brassie , licensed +under a Creative Commons Attribution-ShareAlike 4.0 International License +https://creativecommons.org/licenses/by-sa/4.0/ diff --git a/node_modules/glob/README.md b/node_modules/glob/README.md new file mode 100644 index 0000000..83f0c83 --- /dev/null +++ b/node_modules/glob/README.md @@ -0,0 +1,378 @@ +# Glob + +Match files using the patterns the shell uses, like stars and stuff. + +[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) + +This is a glob implementation in JavaScript. It uses the `minimatch` +library to do its matching. + +![a fun cartoon logo made of glob characters](logo/glob.png) + +## Usage + +Install with npm + +``` +npm i glob +``` + +```javascript +var glob = require("glob") + +// options is optional +glob("**/*.js", options, function (er, files) { + // files is an array of filenames. + // If the `nonull` option is set, and nothing + // was found, then files is ["**/*.js"] + // er is an error object or null. +}) +``` + +## Glob Primer + +"Globs" are the patterns you type when you do stuff like `ls *.js` on +the command line, or put `build/*` in a `.gitignore` file. + +Before parsing the path part patterns, braced sections are expanded +into a set. Braced sections start with `{` and end with `}`, with any +number of comma-delimited sections within. Braced sections may contain +slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. + +The following characters have special magic meaning when used in a +path portion: + +* `*` Matches 0 or more characters in a single path portion +* `?` Matches 1 character +* `[...]` Matches a range of characters, similar to a RegExp range. + If the first character of the range is `!` or `^` then it matches + any character not in the range. +* `!(pattern|pattern|pattern)` Matches anything that does not match + any of the patterns provided. +* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the + patterns provided. +* `+(pattern|pattern|pattern)` Matches one or more occurrences of the + patterns provided. +* `*(a|b|c)` Matches zero or more occurrences of the patterns provided +* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns + provided +* `**` If a "globstar" is alone in a path portion, then it matches + zero or more directories and subdirectories searching for matches. + It does not crawl symlinked directories. + +### Dots + +If a file or directory path portion has a `.` as the first character, +then it will not match any glob pattern unless that pattern's +corresponding path part also has a `.` as its first character. + +For example, the pattern `a/.*/c` would match the file at `a/.b/c`. +However the pattern `a/*/c` would not, because `*` does not start with +a dot character. + +You can make glob treat dots as normal characters by setting +`dot:true` in the options. + +### Basename Matching + +If you set `matchBase:true` in the options, and the pattern has no +slashes in it, then it will seek for any file anywhere in the tree +with a matching basename. For example, `*.js` would match +`test/simple/basic.js`. + +### Empty Sets + +If no matching files are found, then an empty array is returned. This +differs from the shell, where the pattern itself is returned. For +example: + + $ echo a*s*d*f + a*s*d*f + +To get the bash-style behavior, set the `nonull:true` in the options. + +### See Also: + +* `man sh` +* `man bash` (Search for "Pattern Matching") +* `man 3 fnmatch` +* `man 5 gitignore` +* [minimatch documentation](https://github.com/isaacs/minimatch) + +## glob.hasMagic(pattern, [options]) + +Returns `true` if there are any special characters in the pattern, and +`false` otherwise. + +Note that the options affect the results. If `noext:true` is set in +the options object, then `+(a|b)` will not be considered a magic +pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` +then that is considered magical, unless `nobrace:true` is set in the +options. + +## glob(pattern, [options], cb) + +* `pattern` `{String}` Pattern to be matched +* `options` `{Object}` +* `cb` `{Function}` + * `err` `{Error | null}` + * `matches` `{Array}` filenames found matching the pattern + +Perform an asynchronous glob search. + +## glob.sync(pattern, [options]) + +* `pattern` `{String}` Pattern to be matched +* `options` `{Object}` +* return: `{Array}` filenames found matching the pattern + +Perform a synchronous glob search. + +## Class: glob.Glob + +Create a Glob object by instantiating the `glob.Glob` class. + +```javascript +var Glob = require("glob").Glob +var mg = new Glob(pattern, options, cb) +``` + +It's an EventEmitter, and starts walking the filesystem to find matches +immediately. + +### new glob.Glob(pattern, [options], [cb]) + +* `pattern` `{String}` pattern to search for +* `options` `{Object}` +* `cb` `{Function}` Called when an error occurs, or matches are found + * `err` `{Error | null}` + * `matches` `{Array}` filenames found matching the pattern + +Note that if the `sync` flag is set in the options, then matches will +be immediately available on the `g.found` member. + +### Properties + +* `minimatch` The minimatch object that the glob uses. +* `options` The options object passed in. +* `aborted` Boolean which is set to true when calling `abort()`. There + is no way at this time to continue a glob search after aborting, but + you can re-use the statCache to avoid having to duplicate syscalls. +* `cache` Convenience object. Each field has the following possible + values: + * `false` - Path does not exist + * `true` - Path exists + * `'FILE'` - Path exists, and is not a directory + * `'DIR'` - Path exists, and is a directory + * `[file, entries, ...]` - Path exists, is a directory, and the + array value is the results of `fs.readdir` +* `statCache` Cache of `fs.stat` results, to prevent statting the same + path multiple times. +* `symlinks` A record of which paths are symbolic links, which is + relevant in resolving `**` patterns. +* `realpathCache` An optional object which is passed to `fs.realpath` + to minimize unnecessary syscalls. It is stored on the instantiated + Glob object, and may be re-used. + +### Events + +* `end` When the matching is finished, this is emitted with all the + matches found. If the `nonull` option is set, and no match was found, + then the `matches` list contains the original pattern. The matches + are sorted, unless the `nosort` flag is set. +* `match` Every time a match is found, this is emitted with the specific + thing that matched. It is not deduplicated or resolved to a realpath. +* `error` Emitted when an unexpected error is encountered, or whenever + any fs error occurs if `options.strict` is set. +* `abort` When `abort()` is called, this event is raised. + +### Methods + +* `pause` Temporarily stop the search +* `resume` Resume the search +* `abort` Stop the search forever + +### Options + +All the options that can be passed to Minimatch can also be passed to +Glob to change pattern matching behavior. Also, some have been added, +or have glob-specific ramifications. + +All options are false by default, unless otherwise noted. + +All options are added to the Glob object, as well. + +If you are running many `glob` operations, you can pass a Glob object +as the `options` argument to a subsequent operation to shortcut some +`stat` and `readdir` calls. At the very least, you may pass in shared +`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that +parallel glob operations will be sped up by sharing information about +the filesystem. + +* `cwd` The current working directory in which to search. Defaults + to `process.cwd()`. +* `root` The place where patterns starting with `/` will be mounted + onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix + systems, and `C:\` or some such on Windows.) +* `dot` Include `.dot` files in normal matches and `globstar` matches. + Note that an explicit dot in a portion of the pattern will always + match dot files. +* `nomount` By default, a pattern starting with a forward-slash will be + "mounted" onto the root setting, so that a valid filesystem path is + returned. Set this flag to disable that behavior. +* `mark` Add a `/` character to directory matches. Note that this + requires additional stat calls. +* `nosort` Don't sort the results. +* `stat` Set to true to stat *all* results. This reduces performance + somewhat, and is completely unnecessary, unless `readdir` is presumed + to be an untrustworthy indicator of file existence. +* `silent` When an unusual error is encountered when attempting to + read a directory, a warning will be printed to stderr. Set the + `silent` option to true to suppress these warnings. +* `strict` When an unusual error is encountered when attempting to + read a directory, the process will just continue on in search of + other matches. Set the `strict` option to raise an error in these + cases. +* `cache` See `cache` property above. Pass in a previously generated + cache object to save some fs calls. +* `statCache` A cache of results of filesystem information, to prevent + unnecessary stat calls. While it should not normally be necessary + to set this, you may pass the statCache from one glob() call to the + options object of another, if you know that the filesystem will not + change between calls. (See "Race Conditions" below.) +* `symlinks` A cache of known symbolic links. You may pass in a + previously generated `symlinks` object to save `lstat` calls when + resolving `**` matches. +* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. +* `nounique` In some cases, brace-expanded patterns can result in the + same file showing up multiple times in the result set. By default, + this implementation prevents duplicates in the result set. Set this + flag to disable that behavior. +* `nonull` Set to never return an empty set, instead returning a set + containing the pattern itself. This is the default in glob(3). +* `debug` Set to enable debug logging in minimatch and glob. +* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. +* `noglobstar` Do not match `**` against multiple filenames. (Ie, + treat it as a normal `*` instead.) +* `noext` Do not match `+(a|b)` "extglob" patterns. +* `nocase` Perform a case-insensitive match. Note: on + case-insensitive filesystems, non-magic patterns will match by + default, since `stat` and `readdir` will not raise errors. +* `matchBase` Perform a basename-only match if the pattern does not + contain any slash characters. That is, `*.js` would be treated as + equivalent to `**/*.js`, matching all js files in all directories. +* `nodir` Do not match directories, only files. (Note: to match + *only* directories, simply put a `/` at the end of the pattern.) +* `ignore` Add a pattern or an array of glob patterns to exclude matches. + Note: `ignore` patterns are *always* in `dot:true` mode, regardless + of any other settings. +* `follow` Follow symlinked directories when expanding `**` patterns. + Note that this can result in a lot of duplicate references in the + presence of cyclic links. +* `realpath` Set to true to call `fs.realpath` on all of the results. + In the case of a symlink that cannot be resolved, the full absolute + path to the matched entry is returned (though it will usually be a + broken symlink) +* `absolute` Set to true to always receive absolute paths for matched + files. Unlike `realpath`, this also affects the values returned in + the `match` event. +* `fs` File-system object with Node's `fs` API. By default, the built-in + `fs` module will be used. Set to a volume provided by a library like + `memfs` to avoid using the "real" file-system. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between node-glob and other +implementations, and are intentional. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.3, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +Note that symlinked directories are not crawled as part of a `**`, +though their contents may match against subsequent portions of the +pattern. This prevents infinite loops and duplicates and the like. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then glob returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. + +### Comments and Negation + +Previously, this module let you mark a pattern as a "comment" if it +started with a `#` character, or a "negated" pattern if it started +with a `!` character. + +These options were deprecated in version 5, and removed in version 6. + +To specify things that should not match, use the `ignore` option. + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes will always +be interpreted as escape characters, not path separators. + +Results from absolute patterns such as `/foo/*` are mounted onto the +root setting using `path.join`. On windows, this will by default result +in `/foo/*` matching `C:\foo\bar.txt`. + +## Race Conditions + +Glob searching, by its very nature, is susceptible to race conditions, +since it relies on directory walking and such. + +As a result, it is possible that a file that exists when glob looks for +it may have been deleted or modified by the time it returns the result. + +As part of its internal implementation, this program caches all stat +and readdir calls that it makes, in order to cut down on system +overhead. However, this also makes it even more susceptible to races, +especially if the cache or statCache objects are reused between glob +calls. + +Users are thus advised not to use a glob result as a guarantee of +filesystem state in the face of rapid changes. For the vast majority +of operations, this is never a problem. + +## Glob Logo +Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). + +The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). + +## Contributing + +Any change to behavior (including bugfixes) must come with a test. + +Patches that fail tests or reduce performance will be rejected. + +``` +# to run tests +npm test + +# to re-generate test fixtures +npm run test-regen + +# to benchmark against bash/zsh +npm run bench + +# to profile javascript +npm run prof +``` + +![](oh-my-glob.gif) diff --git a/node_modules/glob/common.js b/node_modules/glob/common.js new file mode 100644 index 0000000..8e363b6 --- /dev/null +++ b/node_modules/glob/common.js @@ -0,0 +1,236 @@ +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + +var fs = require("fs") +var path = require("path") +var minimatch = require("minimatch") +var isAbsolute = require("path-is-absolute") +var Minimatch = minimatch.Minimatch + +function alphasort (a, b) { + return a.localeCompare(b, 'en') +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || [] + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } +} + +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { dot: true }) + } + + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {} + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern + } + + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + self.absolute = !!options.absolute + self.fs = options.fs || fs + + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) + + setupIgnores(self, options) + + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = path.resolve(options.cwd) + self.changedCwd = self.cwd !== cwd + } + + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") + + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + self.nomount = !!options.nomount + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true + options.nocomment = true + + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} + +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) + } + } + + if (!nou) + all = Object.keys(all) + + if (!self.nosort) + all = all.sort(alphasort) + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)) + var c = self.cache[e] || self.cache[makeAbs(self, e)] + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c) + return notDir + }) + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) + + self.found = all +} + +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' + + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) + + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) + } + + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/') + + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} diff --git a/node_modules/glob/glob.js b/node_modules/glob/glob.js new file mode 100644 index 0000000..afcf827 --- /dev/null +++ b/node_modules/glob/glob.js @@ -0,0 +1,787 @@ +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. + +module.exports = glob + +var rp = require('fs.realpath') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var inherits = require('inherits') +var EE = require('events').EventEmitter +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path-is-absolute') +var globSync = require('./sync.js') +var common = require('./common.js') +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = require('inflight') +var util = require('util') +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +var once = require('once') + +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + + return new Glob(pattern, options, cb) +} + +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync + +// old api surface +glob.glob = glob + +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } + + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] + } + return origin +} + +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true + + var g = new Glob(pattern, options) + var set = g.minimatch.set + + if (!pattern) + return false + + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false +} + +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options) + this._didRealPath = false + + // process each pattern in the minimatch set + var n = this.minimatch.set.length + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) + + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } + + var self = this + this._processing = 0 + + this._emitQueue = [] + this._processQueue = [] + this.paused = false + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + sync = false + + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() + } + } + } +} + +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common.finish(this) + this.emit('end', this.found) +} + +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true + + var n = this.matches.length + if (n === 0) + return this._finish() + + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) + + function next () { + if (--n === 0) + self._finish() + } +} + +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() + + var found = Object.keys(matchset) + var self = this + var n = found.length + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} + +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} + +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') + } +} + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) + } + } + } +} + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') + + if (this.aborted) + return + + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +} + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) + } + cb() +} + +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (isIgnored(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]) + return + } + + var abs = isAbsolute(e) ? e : this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) + e = abs + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) + + this.emit('match', e) +} + +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) + + if (lstatcb) + self.fs.lstat(abs, lstatcb) + + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) + } +} + +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + + var self = this + self.fs.readdir(abs, readdirCb(this, abs, cb)) +} + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) + } +} + +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + return cb(null, entries) +} + +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + this.emit('error', error) + this.abort() + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break + } + + return cb() +} + +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + + +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) + + var isSym = this.symlinks[abs] + var len = entries.length + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } + + cb() +} + +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} + +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + self.fs.lstat(abs, statcb) + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return self.fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } +} + +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() + } + + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat + + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) +} diff --git a/node_modules/glob/package.json b/node_modules/glob/package.json new file mode 100644 index 0000000..cc1a57a --- /dev/null +++ b/node_modules/glob/package.json @@ -0,0 +1,52 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "name": "glob", + "description": "a little globber", + "version": "7.2.0", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-glob.git" + }, + "main": "glob.js", + "files": [ + "glob.js", + "sync.js", + "common.js" + ], + "engines": { + "node": "*" + }, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "devDependencies": { + "memfs": "^3.2.0", + "mkdirp": "0", + "rimraf": "^2.2.8", + "tap": "^15.0.6", + "tick": "0.0.6" + }, + "tap": { + "before": "test/00-setup.js", + "after": "test/zz-cleanup.js", + "jobs": 1 + }, + "scripts": { + "prepublish": "npm run benchclean", + "profclean": "rm -f v8.log profile.txt", + "test": "tap", + "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js", + "bench": "bash benchmark.sh", + "prof": "bash prof.sh && cat profile.txt", + "benchclean": "node benchclean.js" + }, + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } +} diff --git a/node_modules/glob/sync.js b/node_modules/glob/sync.js new file mode 100644 index 0000000..4f46f90 --- /dev/null +++ b/node_modules/glob/sync.js @@ -0,0 +1,483 @@ +module.exports = globSync +globSync.GlobSync = GlobSync + +var rp = require('fs.realpath') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var Glob = require('./glob.js').Glob +var util = require('util') +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path-is-absolute') +var common = require('./common.js') +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found +} + +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts(this, pattern, options) + + if (this.noprocess) + return this + + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() +} + +GlobSync.prototype._finish = function () { + assert(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) + } + common.finish(this) +} + + +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert(this instanceof GlobSync) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} + + +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } +} + + +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return + + var abs = this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) { + e = abs + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + if (this.stat) + this._stat(e) +} + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries + var lstat + var stat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) + + return entries +} + +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries + + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, this.fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + + // mark and cache dir-ness + return entries +} + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break + } +} + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) + + var len = entries.length + var isSym = this.symlinks[abs] + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) +} + +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = this.fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat + } + } + + this.statCache[abs] = stat + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return false + + return c +} + +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} + +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} diff --git a/node_modules/has-unicode/LICENSE b/node_modules/has-unicode/LICENSE new file mode 100644 index 0000000..d42e25e --- /dev/null +++ b/node_modules/has-unicode/LICENSE @@ -0,0 +1,14 @@ +Copyright (c) 2014, Rebecca Turner + +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/has-unicode/README.md b/node_modules/has-unicode/README.md new file mode 100644 index 0000000..5a03e59 --- /dev/null +++ b/node_modules/has-unicode/README.md @@ -0,0 +1,43 @@ +has-unicode +=========== + +Try to guess if your terminal supports unicode + +```javascript +var hasUnicode = require("has-unicode") + +if (hasUnicode()) { + // the terminal probably has unicode support +} +``` +```javascript +var hasUnicode = require("has-unicode").tryHarder +hasUnicode(function(unicodeSupported) { + if (unicodeSupported) { + // the terminal probably has unicode support + } +}) +``` + +## Detecting Unicode + +What we actually detect is UTF-8 support, as that's what Node itself supports. +If you have a UTF-16 locale then you won't be detected as unicode capable. + +### Windows + +Since at least Windows 7, `cmd` and `powershell` have been unicode capable, +but unfortunately even then it's not guaranteed. In many localizations it +still uses legacy code pages and there's no facility short of running +programs or linking C++ that will let us detect this. As such, we +report any Windows installation as NOT unicode capable, and recommend +that you encourage your users to override this via config. + +### Unix Like Operating Systems + +We look at the environment variables `LC_ALL`, `LC_CTYPE`, and `LANG` in +that order. For `LC_ALL` and `LANG`, it looks for `.UTF-8` in the value. +For `LC_CTYPE` it looks to see if the value is `UTF-8`. This is sufficient +for most POSIX systems. While locale data can be put in `/etc/locale.conf` +as well, AFAIK it's always copied into the environment. + diff --git a/node_modules/has-unicode/index.js b/node_modules/has-unicode/index.js new file mode 100644 index 0000000..9b0fe44 --- /dev/null +++ b/node_modules/has-unicode/index.js @@ -0,0 +1,16 @@ +"use strict" +var os = require("os") + +var hasUnicode = module.exports = function () { + // Recent Win32 platforms (>XP) CAN support unicode in the console but + // don't have to, and in non-english locales often use traditional local + // code pages. There's no way, short of windows system calls or execing + // the chcp command line program to figure this out. As such, we default + // this to false and encourage your users to override it via config if + // appropriate. + if (os.type() == "Windows_NT") { return false } + + var isUTF8 = /UTF-?8$/i + var ctype = process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG + return isUTF8.test(ctype) +} diff --git a/node_modules/has-unicode/package.json b/node_modules/has-unicode/package.json new file mode 100644 index 0000000..ebe9d76 --- /dev/null +++ b/node_modules/has-unicode/package.json @@ -0,0 +1,30 @@ +{ + "name": "has-unicode", + "version": "2.0.1", + "description": "Try to guess if your terminal supports unicode", + "main": "index.js", + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/iarna/has-unicode" + }, + "keywords": [ + "unicode", + "terminal" + ], + "files": [ + "index.js" + ], + "author": "Rebecca Turner ", + "license": "ISC", + "bugs": { + "url": "https://github.com/iarna/has-unicode/issues" + }, + "homepage": "https://github.com/iarna/has-unicode", + "devDependencies": { + "require-inject": "^1.3.0", + "tap": "^2.3.1" + } +} diff --git a/node_modules/http-errors/HISTORY.md b/node_modules/http-errors/HISTORY.md new file mode 100644 index 0000000..efc2d4c --- /dev/null +++ b/node_modules/http-errors/HISTORY.md @@ -0,0 +1,149 @@ +2019-02-18 / 1.7.2 +================== + + * deps: setprototypeof@1.1.1 + +2018-09-08 / 1.7.1 +================== + + * Fix error creating objects in some environments + +2018-07-30 / 1.7.0 +================== + + * Set constructor name when possible + * Use `toidentifier` module to make class names + * deps: statuses@'>= 1.5.0 < 2' + +2018-03-29 / 1.6.3 +================== + + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: setprototypeof@1.1.0 + * deps: statuses@'>= 1.4.0 < 2' + +2017-08-04 / 1.6.2 +================== + + * deps: depd@1.1.1 + - Remove unnecessary `Buffer` loading + +2017-02-20 / 1.6.1 +================== + + * deps: setprototypeof@1.0.3 + - Fix shim for old browsers + +2017-02-14 / 1.6.0 +================== + + * Accept custom 4xx and 5xx status codes in factory + * Add deprecation message to `"I'mateapot"` export + * Deprecate passing status code as anything except first argument in factory + * Deprecate using non-error status codes + * Make `message` property enumerable for `HttpError`s + +2016-11-16 / 1.5.1 +================== + + * deps: inherits@2.0.3 + - Fix issue loading in browser + * deps: setprototypeof@1.0.2 + * deps: statuses@'>= 1.3.1 < 2' + +2016-05-18 / 1.5.0 +================== + + * Support new code `421 Misdirected Request` + * Use `setprototypeof` module to replace `__proto__` setting + * deps: statuses@'>= 1.3.0 < 2' + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: enable strict mode + +2016-01-28 / 1.4.0 +================== + + * Add `HttpError` export, for `err instanceof createError.HttpError` + * deps: inherits@2.0.1 + * deps: statuses@'>= 1.2.1 < 2' + - Fix message for status 451 + - Remove incorrect nginx status code + +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/node_modules/http-errors/LICENSE b/node_modules/http-errors/LICENSE new file mode 100644 index 0000000..82af4df --- /dev/null +++ b/node_modules/http-errors/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Copyright (c) 2016 Douglas Christopher Wilson doug@somethingdoug.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/http-errors/README.md b/node_modules/http-errors/README.md new file mode 100644 index 0000000..3b25481 --- /dev/null +++ b/node_modules/http-errors/README.md @@ -0,0 +1,163 @@ +# http-errors + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][node-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install http-errors +``` + +## Example + +```js +var createError = require('http-errors') +var express = require('express') +var app = express() + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')) + next() +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +### Error Properties + +- `expose` - can be used to signal if `message` should be sent to the client, + defaulting to `false` when `status` >= 500 +- `headers` - can be an object of header names to values to be sent to the + client, defaulting to `undefined`. When defined, the key names should all + be lower-cased +- `message` - the traditional error message, which should be kept short and all + single line +- `status` - the status code of the error, mirroring `statusCode` for general + compatibility +- `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + +Create a new error object with the given message `msg`. +The error object inherits from `createError.HttpError`. + + + +```js +var err = createError(404, 'This video does not exist!') +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### createError([status], [error], [properties]) + +Extend the given `error` object with `createError.HttpError` +properties. This will not alter the inheritance of the given +`error` object, and the modified `error` object is the +return value. + + + +```js +fs.readFile('foo.txt', function (err, buf) { + if (err) { + if (err.code === 'ENOENT') { + var httpError = createError(404, err, { expose: false }) + } else { + var httpError = createError(500, err) + } + } +}) +``` + +- `status` - the status code as a number +- `error` - the error object to extend +- `properties` - custom properties to attach to the object + +### new createError\[code || name\](\[msg]\)) + +Create a new error object with the given message `msg`. +The error object inherits from `createError.HttpError`. + + + +```js +var err = new createError.NotFound() +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +#### List of all constructors + +|Status Code|Constructor Name | +|-----------|-----------------------------| +|400 |BadRequest | +|401 |Unauthorized | +|402 |PaymentRequired | +|403 |Forbidden | +|404 |NotFound | +|405 |MethodNotAllowed | +|406 |NotAcceptable | +|407 |ProxyAuthenticationRequired | +|408 |RequestTimeout | +|409 |Conflict | +|410 |Gone | +|411 |LengthRequired | +|412 |PreconditionFailed | +|413 |PayloadTooLarge | +|414 |URITooLong | +|415 |UnsupportedMediaType | +|416 |RangeNotSatisfiable | +|417 |ExpectationFailed | +|418 |ImATeapot | +|421 |MisdirectedRequest | +|422 |UnprocessableEntity | +|423 |Locked | +|424 |FailedDependency | +|425 |UnorderedCollection | +|426 |UpgradeRequired | +|428 |PreconditionRequired | +|429 |TooManyRequests | +|431 |RequestHeaderFieldsTooLarge | +|451 |UnavailableForLegalReasons | +|500 |InternalServerError | +|501 |NotImplemented | +|502 |BadGateway | +|503 |ServiceUnavailable | +|504 |GatewayTimeout | +|505 |HTTPVersionNotSupported | +|506 |VariantAlsoNegotiates | +|507 |InsufficientStorage | +|508 |LoopDetected | +|509 |BandwidthLimitExceeded | +|510 |NotExtended | +|511 |NetworkAuthenticationRequired| + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/http-errors/master +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors?branch=master +[node-image]: https://badgen.net/npm/node/http-errors +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/http-errors +[npm-url]: https://npmjs.org/package/http-errors +[npm-version-image]: https://badgen.net/npm/v/http-errors +[travis-image]: https://badgen.net/travis/jshttp/http-errors/master +[travis-url]: https://travis-ci.org/jshttp/http-errors diff --git a/node_modules/http-errors/index.js b/node_modules/http-errors/index.js new file mode 100644 index 0000000..10ca4ad --- /dev/null +++ b/node_modules/http-errors/index.js @@ -0,0 +1,266 @@ +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('http-errors') +var setPrototypeOf = require('setprototypeof') +var statuses = require('statuses') +var inherits = require('inherits') +var toIdentifier = require('toidentifier') + +/** + * Module exports. + * @public + */ + +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() + +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) + +/** + * Get the code class of a status code. + * @private + */ + +function codeClass (status) { + return Number(String(status).charAt(0) + '00') +} + +/** + * Create a new HTTP Error. + * + * @returns {Error} + * @public + */ + +function createError () { + // so much arity going on ~_~ + var err + var msg + var status = 500 + var props = {} + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i] + if (arg instanceof Error) { + err = arg + status = err.status || err.statusCode || status + continue + } + switch (typeof arg) { + case 'string': + msg = arg + break + case 'number': + status = arg + if (i !== 0) { + deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') + } + break + case 'object': + props = arg + break + } + } + + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } + + if (typeof status !== 'number' || + (!statuses[status] && (status < 400 || status >= 600))) { + status = 500 + } + + // constructor + var HttpError = createError[status] || createError[codeClass(status)] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, createError) + } + + if (!HttpError || !(err instanceof HttpError) || err.status !== status) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err +} + +/** + * Create HTTP error abstract base class. + * @private + */ + +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') + } + + inherits(HttpError, Error) + + return HttpError +} + +/** + * Create a constructor for a client error. + * @private + */ + +function createClientErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' + + function ClientError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ClientError, HttpError) + nameFunc(ClientError, className) + + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true + + return ClientError +} + +/** + * Create a constructor for a server error. + * @private + */ + +function createServerErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' + + function ServerError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ServerError, HttpError) + nameFunc(ServerError, className) + + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false + + return ServerError +} + +/** + * Set the name of a function, if possible. + * @private + */ + +function nameFunc (func, name) { + var desc = Object.getOwnPropertyDescriptor(func, 'name') + + if (desc && desc.configurable) { + desc.value = name + Object.defineProperty(func, 'name', desc) + } +} + +/** + * Populate the exports object with constructors for every error class. + * @private + */ + +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses[code]) + + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break + } + + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError + } + }) + + // backwards-compatibility + exports["I'mateapot"] = deprecate.function(exports.ImATeapot, + '"I\'mateapot"; use "ImATeapot" instead') +} diff --git a/node_modules/http-errors/package.json b/node_modules/http-errors/package.json new file mode 100644 index 0000000..96cd630 --- /dev/null +++ b/node_modules/http-errors/package.json @@ -0,0 +1,49 @@ +{ + "name": "http-errors", + "description": "Create HTTP error objects", + "version": "1.7.2", + "author": "Jonathan Ong (http://jongleberry.com)", + "contributors": [ + "Alan Plum ", + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "jshttp/http-errors", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.1", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.0" + }, + "devDependencies": { + "eslint": "5.13.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.0.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "5.2.0" + }, + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md . && node ./scripts/lint-readme-list.js", + "test": "mocha --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "keywords": [ + "http", + "error" + ], + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ] +} diff --git a/node_modules/http-status/CHANGELOG.md b/node_modules/http-status/CHANGELOG.md new file mode 100644 index 0000000..a4d6cfc --- /dev/null +++ b/node_modules/http-status/CHANGELOG.md @@ -0,0 +1,80 @@ +# Changelog: HTTP Status + +## Version 1.5.0 + +* ts: support strict mode +* mocha: move config into package +* package: latest dependencies + +## Version 1.4.2 + +* package: update adaltas url + +## Version 1.4.1 + +* readme: fix api example + +## Version 1.4.0 + +* codes: add status code classes + +## Version 1.3.2 + +* 502: wrong key for name and message + +## Version 1.3.1 + +* ts: define properties as readonly + +## Version 1.3.0 + +* codes: new codes 102 and 103 +* ts: rewrite declaration type file +* ts: mocha integration + +## Version 1.2.0 + +* typescript: use primitives + +## Version 1.1.2 + +* typescript: generate correct typescript definitions file #28 + +## Version 1.1.1 + +* codes: double 420 #26 +* codes: wrong keys for 305_MESSAGE and 305_NAME #25 +* typescript: types files +* package: remove Makefile +* travis: test against Node.js 6,7,8 + +## Version 1.1.0 + +* extra: add unofficial, iis, nginx and cloudflare codes +* package: publishing process +* package: ignore lock files +* src: new code and message properties +* package: latest dependencies +* readme: add author company + +## Version 0.1.1 – Nov 13, 2012 + +- Module as a better citizen +- Makefile to compile and run tests + +## Version 0.1.1 – Dec 13, 2011 + +- Code officially under the BSD License + +## Version 0.1.0 – April 17, 2011 + +- Added reference links to HTTP specification +- Fixed naming convention for constants from `PascalCase` to `ALL_CAPS` +- Converted status codes from string to number +- Updated samples +- Updated tests +- Added this `CHANGELOG` + +## Version 0.0.1 – March 25, 2011 + +- Initial release. diff --git a/node_modules/http-status/LICENSE b/node_modules/http-status/LICENSE new file mode 100644 index 0000000..765c231 --- /dev/null +++ b/node_modules/http-status/LICENSE @@ -0,0 +1,15 @@ +Software License Agreement (BSD License) +======================================== +Copyright (c) 2008-2010, SARL Adaltas. + +All rights reserved. + +Redistribution and use of this software 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 SARL Adaltas nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the SARL Adaltas. + +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/http-status/README.md b/node_modules/http-status/README.md new file mode 100644 index 0000000..2e26164 --- /dev/null +++ b/node_modules/http-status/README.md @@ -0,0 +1,189 @@ +[![Build Status](https://secure.travis-ci.org/adaltas/node-http-status.png)](http://travis-ci.org/adaltas/node-http-status) + +# HTTP Status codes for Node + +Utility to interact with HTTP status codes. + +## Usage + +Once you require this module, you may call it with either an HTTP code or a message name. With an HTTP code, you will get the message name while with a message name you will get an HTTP code. + +### HTTP Status Codes +HTTP code names, messages, and classes are respectively accessible with the property `{code}_NAME`, `{code}_MESSAGE` and `{code}_CLASS`. This includes all statuses in the [IANA HTTP Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml), with the only addition being `418 I'm a teapot`. + +Extra status code are also made available that are not defined in the IANA registry, but used by popular software. They are grouped by category. Specific properties are exported by `http-status` under the property `extra` followed by the category name. Also, extra codes are merge with regular status codes and made available as modules available inside `http-status/lib/{category}`. + +Available categories are: + +
+
unofficial
+
This represent a list of codes which are not specified by any standard.
+
iis
+
Microsoft's Internet Information Services (IIS) web server expands the 4xx error class to signal errors with the client's request.
+
nginx
+
The NGINX web server software expands the 4xx error class to signal issues with the client's request.
+
cloudflare
+
Cloudflare's reverse proxy service expands the 5xx error class to signal issues with the origin server.
+
+ +### HTTP Status Code Classes + +In addition to HTTP status codes, this module also contains status code classes under the `classes` property. Similar to HTTP codes, you can access class names and messages with the property `{class}_NAME` and `{class}_MESSAGE` + +## API + +The API is structured as follows: + +``` +100 +100_NAME +100_MESSAGE +100_CLASS +CONTINUE +101 +101_NAME +101_MESSAGE +101_CLASS +SWITCHING_PROTOCOLS +… +classes. +├── 1xx +├── 1xx_NAME +├── 1xx_MESSAGE +├── INFORMATIONAL +├── 2xx +├── 2xx_NAME +├── 2xx_MESSAGE +├── SUCCESSFUL +├── … +extra. +├── unofficial. +│ ├── 103 +│ ├── 103_NAME +│ ├── 103_MESSAGE +│ ├── 103_CLASS +│ ├── CHECKPOINT +│ ├── … +├── iis. +│ ├── 440 +│ ├── 440_NAME +│ ├── 440_MESSAGE +│ ├── 440_CLASS +│ ├── LOGIN_TIME_OUT +│ ├── … +├── nginx. +│ ├── 444 +│ ├── 444_NAME +│ ├── 444_MESSAGE +│ ├── 444_CLASS +│ ├── NO_RESPONSE +│ ├── … +├── cloudflare. +│ ├── 520 +│ ├── 520_NAME +│ ├── 520_MESSAGE +│ ├── 520_CLASS +│ ├── UNKNOWN_ERROR +│ ├── … +``` + +For additional information, please refer to [original code](./src/index.litcoffee). + +### Example Usage + +```javascript +const status = require('http-status'); + +console.info(status.INTERNAL_SERVER_ERROR); +// Output: 500 + +console.info(status[500]); +console.info(status[status.INTERNAL_SERVER_ERROR]); +// Both output: "Internal Server Error" + +console.info(status['500_NAME']); +console.info(status[`${status.INTERNAL_SERVER_ERROR}_NAME`]); +// Both output: "INTERNAL_SERVER_ERROR" + +console.info(status['500_MESSAGE']); +console.info(status[`${status.INTERNAL_SERVER_ERROR}_MESSAGE`]); +// Both output: "A generic error message, given when an unexpected condition was encountered and no more specific message is suitable." + +console.info(status['500_CLASS']); +console.info(status[`${status.INTERNAL_SERVER_ERROR}_CLASS`]); +// Both output: "5xx" +``` + +### Example using `classes` + +```javascript +const status = require('http-status'); + +const responseCode = status.INTERNAL_SERVER_ERROR; + +switch (status[`${responseCode}_CLASS`]) { + case status.classes.INFORMATIONAL: + // The responseCode is 1xx + break; + case status.classes.SUCCESSFUL: + // The responseCode is 2xx + break; + case status.classes.REDIRECTION: + // The responseCode is 3xx + break; + case status.classes.CLIENT_ERROR: + // The responseCode is 4xx + break; + case status.classes.SERVER_ERROR: + // The responseCode is 5xx + break; + + default: + // Unknown + break; +} +``` + +### Example Using `extra` Property + +```javascript +// Accessing property from the NGINX category +const status = require('http-status'); +console.info(status.extra.nginx.NO_RESPONSE) +// Accessing default HTTP status merged with NGINX status +const status = require('http-status/lib/nginx'); +console.info(status.IM_A_TEAPOT); +console.info(status.NO_RESPONSE) +``` + +### Express Example + +```javascript +const express = require('express'), + redis = require('redis'), + status = require('http-status'); +// New Express HTTP server +const app = express.createServer(); +// Regster a route +app.get('/', (req, res) => { + const client = redis.createClient(); + client.ping((err, msg) => { + if (err) { + return res.send(status.INTERNAL_SERVER_ERROR); + } + res.send(msg, status.OK); + }); +}); +// Start the HTTP server +app.listen(3000); +``` + +## Contributors + +- David Worms: +- Daniel Gasienica: +- Rodrigo: +- Paul Vollmer: +- James Barcellano: + +This package is developed by [Adaltas](http://www.adaltas.com). diff --git a/node_modules/http-status/lib/cloudflare.js b/node_modules/http-status/lib/cloudflare.js new file mode 100644 index 0000000..46db2cd --- /dev/null +++ b/node_modules/http-status/lib/cloudflare.js @@ -0,0 +1,23 @@ +// Generated by CoffeeScript 2.5.1 +// # Cloudfare extra status codes + +// Cloudflare's reverse proxy service expands the 5xx error class to signal issues with the origin server. +var k, ref, status, v; + +status = require('.'); + +// Import default status codes. +for (k in status) { + v = status[k]; + if (k === 'extra') { + continue; + } + module.exports[k] = v; +} + +ref = status.extra.cloudflare; +// Merge default status codes with Cloudflare status codes. +for (k in ref) { + v = ref[k]; + module.exports[k] = v; +} diff --git a/node_modules/http-status/lib/iis.js b/node_modules/http-status/lib/iis.js new file mode 100644 index 0000000..3f785b7 --- /dev/null +++ b/node_modules/http-status/lib/iis.js @@ -0,0 +1,23 @@ +// Generated by CoffeeScript 2.5.1 +// # IIS extra status codes + +// Microsoft's Internet Information Services (IIS) web server expands the 4xx error class to signal errors with the client's request. +var k, ref, status, v; + +status = require('.'); + +// Import default status codes. +for (k in status) { + v = status[k]; + if (k === 'extra') { + continue; + } + module.exports[k] = v; +} + +ref = status.extra.iis; +// Merge default status codes with IIS status codes. +for (k in ref) { + v = ref[k]; + module.exports[k] = v; +} diff --git a/node_modules/http-status/lib/index.d.ts b/node_modules/http-status/lib/index.d.ts new file mode 100644 index 0000000..0c865d9 --- /dev/null +++ b/node_modules/http-status/lib/index.d.ts @@ -0,0 +1,587 @@ +export = httpStatus; + +declare const httpStatus: httpStatus.HttpStatus; + +declare namespace httpStatus { + + interface HttpStatus { + readonly [key:string]: string | number | HttpStatusClasses | HttpStatusExtra; + + readonly '100': string; + readonly '100_NAME': string; + readonly '100_MESSAGE': string; + readonly '100_CLASS': string; + readonly 'CONTINUE': number; + + readonly '101': string; + readonly '101_NAME': string; + readonly '101_MESSAGE': string; + readonly '101_CLASS': string; + readonly 'SWITCHING_PROTOCOLS': number; + + readonly '200': string; + readonly '200_NAME': string; + readonly '200_MESSAGE': string; + readonly '200_CLASS': string; + readonly 'OK': number; + + readonly '201': string; + readonly '201_NAME': string; + readonly '201_MESSAGE': string; + readonly '201_CLASS': string; + readonly 'CREATED': number; + + readonly '202': string; + readonly '202_NAME': string; + readonly '202_MESSAGE': string; + readonly '202_CLASS': string; + readonly 'ACCEPTED': number; + + readonly '203': string; + readonly '203_NAME': string; + readonly '203_MESSAGE': string; + readonly '203_CLASS': string; + readonly 'NON_AUTHORITATIVE_INFORMATION': number; + + readonly '204': string; + readonly '204_NAME': string; + readonly '204_MESSAGE': string; + readonly '204_CLASS': string; + readonly 'NO_CONTENT': number; + + readonly '205': string; + readonly '205_NAME': string; + readonly '205_MESSAGE': string; + readonly '205_CLASS': string; + readonly 'RESET_CONTENT': number; + + readonly '206': string; + readonly '206_NAME': string; + readonly '206_MESSAGE': string; + readonly '206_CLASS': string; + readonly 'PARTIAL_CONTENT': number; + + readonly '207': string; + readonly '207_NAME': string; + readonly '207_MESSAGE': string; + readonly '207_CLASS': string; + readonly 'MULTI_STATUS': number; + + readonly '208': string; + readonly '208_NAME': string; + readonly '208_MESSAGE': string; + readonly '208_CLASS': string; + readonly 'ALREADY_REPORTED': number; + + readonly '226': string; + readonly '226_NAME': string; + readonly '226_MESSAGE': string; + readonly '226_CLASS': string; + readonly 'IM_USED': number; + + readonly '300': string; + readonly '300_NAME': string; + readonly '300_MESSAGE': string; + readonly '300_CLASS': string; + readonly 'MULTIPLE_CHOICES': number; + + readonly '301': string; + readonly '301_NAME': string; + readonly '301_MESSAGE': string; + readonly '301_CLASS': string; + readonly 'MOVED_PERMANENTLY': number; + + readonly '302': string; + readonly '302_NAME': string; + readonly '302_MESSAGE': string; + readonly '302_CLASS': string; + readonly 'FOUND': number; + + readonly '303': string; + readonly '303_NAME': string; + readonly '303_MESSAGE': string; + readonly '303_CLASS': string; + readonly 'SEE_OTHER': number; + + readonly '304': string; + readonly '304_NAME': string; + readonly '304_MESSAGE': string; + readonly '304_CLASS': string; + readonly 'NOT_MODIFIED': number; + + readonly '305': string; + readonly '305_NAME': string; + readonly '305_MESSAGE': string; + readonly '305_CLASS': string; + readonly 'USE_PROXY': number; + + readonly '306': string; + readonly '306_NAME': string; + readonly '306_MESSAGE': string; + readonly '306_CLASS': string; + readonly 'SWITCH_PROXY': number; + + readonly '307': string; + readonly '307_NAME': string; + readonly '307_MESSAGE': string; + readonly '307_CLASS': string; + readonly 'TEMPORARY_REDIRECT': number; + + readonly '308': string; + readonly '308_NAME': string; + readonly '308_MESSAGE': string; + readonly '308_CLASS': string; + readonly 'PERMANENT_REDIRECT': number; + + readonly '400': string; + readonly '400_NAME': string; + readonly '400_MESSAGE': string; + readonly '400_CLASS': string; + readonly 'BAD_REQUEST': number; + + readonly '401': string; + readonly '401_NAME': string; + readonly '401_MESSAGE': string; + readonly '401_CLASS': string; + readonly 'UNAUTHORIZED': number; + + readonly '402': string; + readonly '402_NAME': string; + readonly '402_MESSAGE': string; + readonly '402_CLASS': string; + readonly 'PAYMENT_REQUIRED': number; + + readonly '403': string; + readonly '403_NAME': string; + readonly '403_MESSAGE': string; + readonly '403_CLASS': string; + readonly 'FORBIDDEN': number; + + readonly '404': string; + readonly '404_NAME': string; + readonly '404_MESSAGE': string; + readonly '404_CLASS': string; + readonly 'NOT_FOUND': number; + + readonly '405': string; + readonly '405_NAME': string; + readonly '405_MESSAGE': string; + readonly '405_CLASS': string; + readonly 'METHOD_NOT_ALLOWED': number; + + readonly '406': string; + readonly '406_NAME': string; + readonly '406_MESSAGE': string; + readonly '406_CLASS': string; + readonly 'NOT_ACCEPTABLE': number; + + readonly '407': string; + readonly '407_NAME': string; + readonly '407_MESSAGE': string; + readonly '407_CLASS': string; + readonly 'PROXY_AUTHENTICATION_REQUIRED': number; + + readonly '408': string; + readonly '408_NAME': string; + readonly '408_MESSAGE': string; + readonly '408_CLASS': string; + readonly 'REQUEST_TIMEOUT': number; + + readonly '409': string; + readonly '409_NAME': string; + readonly '409_MESSAGE': string; + readonly '409_CLASS': string; + readonly 'CONFLICT': number; + + readonly '410': string; + readonly '410_NAME': string; + readonly '410_MESSAGE': string; + readonly '410_CLASS': string; + readonly 'GONE': number; + + readonly '411': string; + readonly '411_NAME': string; + readonly '411_MESSAGE': string; + readonly '411_CLASS': string; + readonly 'LENGTH_REQUIRED': number; + + readonly '412': string; + readonly '412_NAME': string; + readonly '412_MESSAGE': string; + readonly '412_CLASS': string; + readonly 'PRECONDITION_FAILED': number; + + readonly '413': string; + readonly '413_NAME': string; + readonly '413_MESSAGE': string; + readonly '413_CLASS': string; + readonly 'REQUEST_ENTITY_TOO_LARGE': number; + + readonly '414': string; + readonly '414_NAME': string; + readonly '414_MESSAGE': string; + readonly '414_CLASS': string; + readonly 'REQUEST_URI_TOO_LONG': number; + + readonly '415': string; + readonly '415_NAME': string; + readonly '415_MESSAGE': string; + readonly '415_CLASS': string; + readonly 'UNSUPPORTED_MEDIA_TYPE': number; + + readonly '416': string; + readonly '416_NAME': string; + readonly '416_MESSAGE': string; + readonly '416_CLASS': string; + readonly 'REQUESTED_RANGE_NOT_SATISFIABLE': number; + + readonly '417': string; + readonly '417_NAME': string; + readonly '417_MESSAGE': string; + readonly '417_CLASS': string; + readonly 'EXPECTATION_FAILED': number; + + readonly '418': string; + readonly '418_NAME': string; + readonly '418_MESSAGE': string; + readonly '418_CLASS': string; + readonly 'IM_A_TEAPOT': number; + + readonly '421': string; + readonly '421_NAME': string; + readonly '421_MESSAGE': string; + readonly '421_CLASS': string; + readonly 'MISDIRECTED_REQUEST': number; + + readonly '422': string; + readonly '422_NAME': string; + readonly '422_MESSAGE': string; + readonly '422_CLASS': string; + readonly 'UNPROCESSABLE_ENTITY': number; + + readonly '423': string; + readonly '423_NAME': string; + readonly '423_MESSAGE': string; + readonly '423_CLASS': string; + readonly 'LOCKED': number; + + readonly '424': string; + readonly '424_NAME': string; + readonly '424_MESSAGE': string; + readonly '424_CLASS': string; + readonly 'FAILED_DEPENDENCY': number; + + readonly '426': string; + readonly '426_NAME': string; + readonly '426_MESSAGE': string; + readonly '426_CLASS': string; + readonly 'UPGRADE_REQUIRED': number; + + readonly '428': string; + readonly '428_NAME': string; + readonly '428_MESSAGE': string; + readonly '428_CLASS': string; + readonly 'PRECONDITION_REQUIRED': number; + + readonly '429': string; + readonly '429_NAME': string; + readonly '429_MESSAGE': string; + readonly '429_CLASS': string; + readonly 'TOO_MANY_REQUESTS': number; + + readonly '431': string; + readonly '431_NAME': string; + readonly '431_MESSAGE': string; + readonly '431_CLASS': string; + readonly 'REQUEST_HEADER_FIELDS_TOO_LARGE': number; + + readonly '451': string; + readonly '451_NAME': string; + readonly '451_MESSAGE': string; + readonly '451_CLASS': string; + readonly 'UNAVAILABLE_FOR_LEGAL_REASONS': number; + + readonly '500': string; + readonly '500_NAME': string; + readonly '500_MESSAGE': string; + readonly '500_CLASS': string; + readonly 'INTERNAL_SERVER_ERROR': number; + + readonly '501': string; + readonly '501_NAME': string; + readonly '501_MESSAGE': string; + readonly '501_CLASS': string; + readonly 'NOT_IMPLEMENTED': number; + + readonly '502': string; + readonly '_NAME': string; + readonly '_MESSAGE': string; + readonly '_CLASS': string; + readonly 'BAD_GATEWAY': number; + + readonly '503': string; + readonly '503_NAME': string; + readonly '503_MESSAGE': string; + readonly '503_CLASS': string; + readonly 'SERVICE_UNAVAILABLE': number; + + readonly '504': string; + readonly '504_NAME': string; + readonly '504_MESSAGE': string; + readonly '504_CLASS': string; + readonly 'GATEWAY_TIMEOUT': number; + + readonly '505': string; + readonly '505_NAME': string; + readonly '505_MESSAGE': string; + readonly '505_CLASS': string; + readonly 'HTTP_VERSION_NOT_SUPPORTED': number; + + readonly '506': string; + readonly '506_NAME': string; + readonly '506_MESSAGE': string; + readonly '506_CLASS': string; + readonly 'VARIANT_ALSO_NEGOTIATES': number; + + readonly '507': string; + readonly '507_NAME': string; + readonly '507_MESSAGE': string; + readonly '507_CLASS': string; + readonly 'INSUFFICIENT_STORAGE': number; + + readonly '508': string; + readonly '508_NAME': string; + readonly '508_MESSAGE': string; + readonly '508_CLASS': string; + readonly 'LOOP_DETECTED': number; + + readonly '510': string; + readonly '510_NAME': string; + readonly '510_MESSAGE': string; + readonly '510_CLASS': string; + readonly 'NOT_EXTENDED': number; + + readonly '511': string; + readonly '511_NAME': string; + readonly '511_MESSAGE': string; + readonly '511_CLASS': string; + readonly 'NETWORK_AUTHENTICATION_REQUIRED': number; + + classes: HttpStatusClasses + + extra: HttpStatusExtra + + } + + interface HttpStatusExtra { + + readonly 'unofficial': HttpStatusUnofficial; + + readonly 'iis': HttpStatusIis; + + readonly 'nginx': HttpStatusNginx; + + readonly 'cloudflare': HttpStatusCloudfare; + + } + + interface HttpStatusClasses { + readonly [key:string]: string | number; + + readonly '1xx': string; + readonly '1xx_NAME': string; + readonly '1xx_MESSAGE': string; + readonly 'INFORMATIONAL': string; + + readonly '2xx': string; + readonly '2xx_NAME': string; + readonly '2xx_MESSAGE': string; + readonly 'SUCCESSFUL': string; + + readonly '3xx': string; + readonly '3xx_NAME': string; + readonly '3xx_MESSAGE': string; + readonly 'REDIRECTION': string; + + readonly '4xx': string; + readonly '4xx_NAME': string; + readonly '4xx_MESSAGE': string; + readonly 'CLIENT_ERROR': string; + + readonly '5xx': string; + readonly '5xx_NAME': string; + readonly '5xx_MESSAGE': string; + readonly 'SERVER_ERROR': string; + + } + + interface HttpStatusUnofficial { + readonly [key:string]: string | number; + + readonly '103': string; + readonly '103_NAME': string; + readonly '103_MESSAGE': string; + readonly '103_CLASS': string; + readonly 'CHECKPOINT': number; + + readonly '420': string; + readonly '420_NAME': string; + readonly '420_MESSAGE': string; + readonly '420_CLASS': string; + readonly 'ENHANCE_YOUR_CALM': number; + + readonly '450': string; + readonly '450_NAME': string; + readonly '450_MESSAGE': string; + readonly '450_CLASS': string; + readonly 'BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS': number; + + readonly '498': string; + readonly '498_NAME': string; + readonly '498_MESSAGE': string; + readonly '498_CLASS': string; + readonly 'INVALID_TOKEN': number; + + readonly '499': string; + readonly '499_NAME': string; + readonly '499_MESSAGE': string; + readonly '499_CLASS': string; + readonly 'TOKEN_REQUIRED': number; + + readonly '509': string; + readonly '509_NAME': string; + readonly '509_MESSAGE': string; + readonly '509_CLASS': string; + readonly 'BANDWIDTH_LIMIT_EXCEEDED': number; + + readonly '530': string; + readonly '530_NAME': string; + readonly '530_MESSAGE': string; + readonly '530_CLASS': string; + readonly 'SITE_IS_FROZEN': number; + + readonly '598': string; + readonly '598_NAME': string; + readonly '598_MESSAGE': string; + readonly '598_CLASS': string; + readonly 'NETWORK_READ_TIMEOUT_ERROR': number; + + } + + interface HttpStatusIis { + readonly [key:string]: string | number; + + readonly '440': string; + readonly '440_NAME': string; + readonly '440_MESSAGE': string; + readonly '440_CLASS': string; + readonly 'LOGIN_TIME_OUT': number; + + readonly '449': string; + readonly '449_NAME': string; + readonly '449_MESSAGE': string; + readonly '449_CLASS': string; + readonly 'RETRY_WITH': number; + + readonly '451': string; + readonly '451_NAME': string; + readonly '451_MESSAGE': string; + readonly '451_CLASS': string; + readonly 'REDIRECT': number; + + } + + interface HttpStatusNginx { + readonly [key:string]: string | number; + + readonly '444': string; + readonly '444_NAME': string; + readonly '444_MESSAGE': string; + readonly '444_CLASS': string; + readonly 'NO_RESPONSE': number; + + readonly '494': string; + readonly '494_NAME': string; + readonly '494_MESSAGE': string; + readonly '494_CLASS': string; + readonly 'REQUEST_HEADER_TOO_LARGE': number; + + readonly '495': string; + readonly '495_NAME': string; + readonly '495_MESSAGE': string; + readonly '495_CLASS': string; + readonly 'SSL_CERTIFICATE_ERROR': number; + + readonly '496': string; + readonly '496_NAME': string; + readonly '496_MESSAGE': string; + readonly '496_CLASS': string; + readonly 'SSL_CERTIFICATE_REQUIRED': number; + + readonly '497': string; + readonly '497_NAME': string; + readonly '497_MESSAGE': string; + readonly '497_CLASS': string; + readonly 'HTTP_REQUEST_SENT_TO_HTTPS_PORT': number; + + readonly '499': string; + readonly '499_NAME': string; + readonly '499_MESSAGE': string; + readonly '499_CLASS': string; + readonly 'CLIENT_CLOSED_REQUEST': number; + + } + + interface HttpStatusCloudfare { + + readonly '520': string; + readonly '520_NAME': string; + readonly '520_MESSAGE': string; + readonly '520_CLASS': string; + readonly 'UNKNOWN_ERROR': number; + + readonly '521': string; + readonly '521_NAME': string; + readonly '521_MESSAGE': string; + readonly '521_CLASS': string; + readonly 'WEB_SERVER_IS_DOWN': number; + + readonly '522': string; + readonly '522_NAME': string; + readonly '522_MESSAGE': string; + readonly '522_CLASS': string; + readonly 'CONNECTION_TIMED_OUT': number; + + readonly '523': string; + readonly '523_NAME': string; + readonly '523_MESSAGE': string; + readonly '523_CLASS': string; + readonly 'ORIGIN_IS_UNREACHABLE': number; + + readonly '524': string; + readonly '524_NAME': string; + readonly '524_MESSAGE': string; + readonly '524_CLASS': string; + readonly 'A_TIMEOUT_OCCURRED': number; + + readonly '525': string; + readonly '525_NAME': string; + readonly '525_MESSAGE': string; + readonly '525_CLASS': string; + readonly 'SSL_HANDSHAKE_FAILED': number; + + readonly '526': string; + readonly '526_NAME': string; + readonly '526_MESSAGE': string; + readonly '526_CLASS': string; + readonly 'INVALID_SSL_CERTIFICATE': number; + + readonly '527': string; + readonly '527_NAME': string; + readonly '527_MESSAGE': string; + readonly '527_CLASS': string; + readonly 'RAILGUN_ERROR': number; + + } + +} diff --git a/node_modules/http-status/lib/index.js b/node_modules/http-status/lib/index.js new file mode 100644 index 0000000..44cc3e7 --- /dev/null +++ b/node_modules/http-status/lib/index.js @@ -0,0 +1,623 @@ +// Generated by CoffeeScript 2.5.1 +// # node-http-status + +// **Reference:** + +// - https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml +// - https://tools.ietf.org/html/rfc2324#section-2.3.2 + +// ## Classes + +// The first digit of the status-code defines the class of response. The last two digits do not have any categorization role. There are five values for the first digit: +var classes; + +classes = { + // 1xx - The 1xx (Informational) class of status code indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response. + '1xx': 'Informational', + '1xx_NAME': 'INFORMATIONAL', + '1xx_MESSAGE': 'Indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response.', + INFORMATIONAL: '1xx', + // 2xx - The 2xx (Successful) class of status code indicates that the client's request was successfully received, understood, and accepted. + '2xx': 'Successful', + '2xx_NAME': 'SUCCESSFUL', + '2xx_MESSAGE': 'Indicates that the client\'s request was successfully received, understood, and accepted.', + SUCCESSFUL: '2xx', + // 3xx - The 3xx (Redirection) class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. + '3xx': 'Redirection', + '3xx_NAME': 'REDIRECTION', + '3xx_MESSAGE': 'Indicates that further action needs to be taken by the user agent in order to fulfill the request.', + REDIRECTION: '3xx', + // 4xx - The 4xx (Client Error) class of status code indicates that the client seems to have erred. + '4xx': 'Client Error', + '4xx_NAME': 'CLIENT_ERROR', + '4xx_MESSAGE': 'Indicates that the client seems to have erred.', + CLIENT_ERROR: '4xx', + // 5xx - The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method. + '5xx': 'Server Error', + '5xx_NAME': 'SERVER_ERROR', + '5xx_MESSAGE': 'Indicates that the server is aware that it has erred or is incapable of performing the requested method.', + SERVER_ERROR: '5xx' +}; + +module.exports = { + classes: classes, + // ## Informational 1xx + + // Indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response. + + // 100 - The server has received the request headers and the client should proceed to send the request body. + 100: 'Continue', + '100_NAME': 'CONTINUE', + '100_MESSAGE': 'The server has received the request headers and the client should proceed to send the request body.', + '100_CLASS': classes.INFORMATIONAL, + CONTINUE: 100, + // 101 - The requester has asked the server to switch protocols and the server has agreed to do so. + 101: 'Switching Protocols', + '101_NAME': 'SWITCHING_PROTOCOLS', + '101_MESSAGE': 'The requester has asked the server to switch protocols and the server has agreed to do so.', + '101_CLASS': classes.INFORMATIONAL, + SWITCHING_PROTOCOLS: 101, + // 102 Processing (WebDAV; RFC 2518) - A WebDAV request may contain many sub-requests involving file operations, requiring a long time to complete the request. This code indicates that the server has received and is processing the request, but no response is available yet.[7] This prevents the client from timing out and assuming the request was lost. + 102: 'Processing', + '102_NAME': 'PROCESSING', + '102_MESSAGE': 'A WebDAV request may contain many sub-requests involving file operations, requiring a long time to complete the request. This code indicates that the server has received and is processing the request, but no response is available yet.[7] This prevents the client from timing out and assuming the request was lost.', + '102_CLASS': classes.INFORMATIONAL, + PROCESSING: 102, + // 103 Early Hints (RFC 8297) - Used to return some response headers before final HTTP message. + 103: 'Early Hints', + '103_NAME': 'EARLY_HINTS', + '103_MESSAGE': 'Used to return some response headers before final HTTP message.', + '103_CLASS': classes.INFORMATIONAL, + EARLY_HINTS: 103, + // ## Successful 2xx + + // Indicates that the client's request was successfully received, understood, and accepted. + + // 200 - Standard response for successful HTTP requests. + 200: 'OK', + '200_NAME': 'OK', + '200_MESSAGE': 'Standard response for successful HTTP requests.', + '200_CLASS': classes.SUCCESSFUL, + OK: 200, + // 201 - The request has been fulfilled, resulting in the creation of a new resource. + 201: 'Created', + '201_NAME': 'CREATED', + '201_MESSAGE': 'The request has been fulfilled, resulting in the creation of a new resource.', + '201_CLASS': classes.SUCCESSFUL, + CREATED: 201, + // 202 - The request has been accepted for processing, but the processing has not been completed. + 202: 'Accepted', + '202_NAME': 'ACCEPTED', + '202_MESSAGE': 'The request has been accepted for processing, but the processing has not been completed.', + '202_CLASS': classes.SUCCESSFUL, + ACCEPTED: 202, + // 203 (since HTTP/1.1) - The server is a transforming proxy (e.g. a Web accelerator) that received a 200 OK from its origin, but is returning a modified version of the origin's response. + 203: 'Non-Authoritative Information', + '203_NAME': 'NON_AUTHORITATIVE_INFORMATION', + '203_MESSAGE': 'The server is a transforming proxy (e.g. a Web accelerator) that received a 200 OK from its origin, but is returning a modified version of the origin\'s response.', + '203_CLASS': classes.SUCCESSFUL, + NON_AUTHORITATIVE_INFORMATION: 203, + // 204 - The server successfully processed the request and is not returning any content. + 204: 'No Content', + '204_NAME': 'NO_CONTENT', + '204_MESSAGE': 'The server successfully processed the request and is not returning any content.', + '204_CLASS': classes.SUCCESSFUL, + NO_CONTENT: 204, + // 205 - The server successfully processed the request, but is not returning any content. Unlike a 204 response, this response requires that the requester reset the document view. + 205: 'Reset Content', + '205_NAME': 'RESET_CONTENT', + '205_MESSAGE': 'The server successfully processed the request, but is not returning any content. Unlike a 204 response, this response requires that the requester reset the document view.', + '205_CLASS': classes.SUCCESSFUL, + RESET_CONTENT: 205, + // 206 (RFC 7233) - The server is delivering only part of the resource (byte serving) due to a range header sent by the client. + 206: 'Partial Content', + '206_NAME': 'PARTIAL_CONTENT', + '206_MESSAGE': 'The server is delivering only part of the resource (byte serving) due to a range header sent by the client.', + '206_CLASS': classes.SUCCESSFUL, + PARTIAL_CONTENT: 206, + // 207 (WebDAV; RFC 4918) - The message body that follows is by default an XML message and can contain a number of separate response codes, depending on how many sub-requests were made. + 207: 'Multi Status', + '207_NAME': 'MULTI_STATUS', + '207_MESSAGE': 'The message body that follows is by default an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.', + '207_CLASS': classes.SUCCESSFUL, + MULTI_STATUS: 207, + // 208 (WebDAV; RFC 5842) - The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response, and are not being included again. + 208: 'Already Reported', + '208_NAME': 'ALREADY_REPORTED', + '208_MESSAGE': 'The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response, and are not being included again.', + '208_CLASS': classes.SUCCESSFUL, + ALREADY_REPORTED: 208, + // 226 (RFC 3229) - The server has fulfilled a request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance. + 226: 'IM Used', + '226_NAME': 'IM_USED', + '226_MESSAGE': 'The server has fulfilled a request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.', + '226_CLASS': classes.SUCCESSFUL, + IM_USED: 226, + // ## Redirection 3xx + + // Indicates that further action needs to be taken by the user agent in order to fulfill the request. + + // 300 - Indicates multiple options for the resource from which the client may choose. + 300: 'Multiple Choices', + '300_NAME': 'MULTIPLE_CHOICES', + '300_MESSAGE': 'Indicates multiple options for the resource from which the client may choose.', + '300_CLASS': classes.REDIRECTION, + MULTIPLE_CHOICES: 300, + // 301 - This and all future requests should be directed to the given URI. + 301: 'Moved Permanently', + '301_NAME': 'MOVED_PERMANENTLY', + '301_MESSAGE': 'This and all future requests should be directed to the given URI.', + '301_CLASS': classes.REDIRECTION, + MOVED_PERMANENTLY: 301, + // 302 - This is an example of industry practice contradicting the standard. The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the two behaviours. + 302: 'Found', + '302_NAME': 'FOUND', + '302_MESSAGE': 'This is an example of industry practice contradicting the standard. The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the two behaviours.', + '302_CLASS': classes.REDIRECTION, + FOUND: 302, + // 303 (since HTTP/1.1) - The response to the request can be found under another URI using the GET method. + 303: 'See Other', + '303_NAME': 'SEE_OTHER', + '303_MESSAGE': 'The response to the request can be found under another URI using the GET method.', + '303_CLASS': classes.REDIRECTION, + SEE_OTHER: 303, + // 304 (RFC 7232) - Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match. + 304: 'Not Modified', + '304_NAME': 'NOT_MODIFIED', + '304_MESSAGE': 'Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match.', + '304_CLASS': classes.REDIRECTION, + NOT_MODIFIED: 304, + // 305 (since HTTP/1.1) - The requested resource is available only through a proxy, the address for which is provided in the response. + 305: 'Use Proxy', + '305_NAME': 'USE_PROXY', + '305_MESSAGE': 'The requested resource is available only through a proxy, the address for which is provided in the response.', + '305_CLASS': classes.REDIRECTION, + USE_PROXY: 305, + // 306 - No longer used. Originally meant "Subsequent requests should use the specified proxy. + 306: 'Switch Proxy', + '306_NAME': 'SWITCH_PROXY', + '306_MESSAGE': 'No longer used. Originally meant "Subsequent requests should use the specified proxy.', + '306_CLASS': classes.REDIRECTION, + SWITCH_PROXY: 306, + // 307 (since HTTP/1.1) - In this case, the request should be repeated with another URI; however, future requests should still use the original URI. + 307: 'Temporary Redirect', + '307_NAME': 'TEMPORARY_REDIRECT', + '307_MESSAGE': 'In this case, the request should be repeated with another URI; however, future requests should still use the original URI.', + '307_CLASS': classes.REDIRECTION, + TEMPORARY_REDIRECT: 307, + // 308 (RFC 7538) - The request and all future requests should be repeated using another URI. + 308: 'Permanent Redirect', + '308_NAME': 'PERMANENT_REDIRECT', + '308_MESSAGE': 'The request and all future requests should be repeated using another URI.', + '308_CLASS': classes.REDIRECTION, + PERMANENT_REDIRECT: 308, + // ## Client Error 4xx + + // Indicates that the client seems to have erred. + + // 400 - The server cannot or will not process the request due to an apparent client error. + 400: 'Bad Request', + '400_NAME': 'BAD_REQUEST', + '400_MESSAGE': 'The server cannot or will not process the request due to an apparent client error.', + '400_CLASS': classes.CLIENT_ERROR, + BAD_REQUEST: 400, + // 401 (RFC 7235) - Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided. + 401: 'Unauthorized', + '401_NAME': 'UNAUTHORIZED', + '401_MESSAGE': 'Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided.', + '401_CLASS': classes.CLIENT_ERROR, + UNAUTHORIZED: 401, + // 402 - Reserved for future use. The original intention was that this code might be used as part of some form of digital cash or micropayment scheme, as proposed for example by GNU Taler, but that has not yet happened, and this code is not usually used. + 402: 'Payment Required', + '402_NAME': 'PAYMENT_REQUIRED', + '402_MESSAGE': 'Reserved for future use. The original intention was that this code might be used as part of some form of digital cash or micropayment scheme, as proposed for example by GNU Taler, but that has not yet happened, and this code is not usually used.', + '402_CLASS': classes.CLIENT_ERROR, + PAYMENT_REQUIRED: 402, + // 403 - The request was valid, but the server is refusing action. + 403: 'Forbidden', + '403_NAME': 'FORBIDDEN', + '403_MESSAGE': 'The request was valid, but the server is refusing action.', + '403_CLASS': classes.CLIENT_ERROR, + FORBIDDEN: 403, + // 404 - The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible. + 404: 'Not Found', + '404_NAME': 'NOT_FOUND', + '404_MESSAGE': 'The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.', + '404_CLASS': classes.CLIENT_ERROR, + NOT_FOUND: 404, + // 405 - A request method is not supported for the requested resource. + 405: 'Method Not Allowed', + '405_NAME': 'METHOD_NOT_ALLOWED', + '405_MESSAGE': 'A request method is not supported for the requested resource.', + '405_CLASS': classes.CLIENT_ERROR, + METHOD_NOT_ALLOWED: 405, + // 406 - The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request. + 406: 'Not Acceptable', + '406_NAME': 'NOT_ACCEPTABLE', + '406_MESSAGE': 'The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request.', + '406_CLASS': classes.CLIENT_ERROR, + NOT_ACCEPTABLE: 406, + // 407 (RFC 7235) - The client must first authenticate itself with the proxy. + 407: 'Proxy Authentication Required', + '407_NAME': 'PROXY_AUTHENTICATION_REQUIRED', + '407_MESSAGE': 'The client must first authenticate itself with the proxy.', + '407_CLASS': classes.CLIENT_ERROR, + PROXY_AUTHENTICATION_REQUIRED: 407, + // 408 - The server timed out waiting for the request. + 408: 'Request Time-out', + '408_NAME': 'REQUEST_TIMEOUT', + '408_MESSAGE': 'The server timed out waiting for the request.', + '408_CLASS': classes.CLIENT_ERROR, + REQUEST_TIMEOUT: 408, + // 409 - Indicates that the request could not be processed because of conflict in the request, such as an edit conflict between multiple simultaneous updates. + 409: 'Conflict', + '409_NAME': 'CONFLICT', + '409_MESSAGE': 'Indicates that the request could not be processed because of conflict in the request, such as an edit conflict between multiple simultaneous updates.', + '409_CLASS': classes.CLIENT_ERROR, + CONFLICT: 409, + // 410 - Indicates that the resource requested is no longer available and will not be available again. + 410: 'Gone', + '410_NAME': 'GONE', + '410_MESSAGE': 'Indicates that the resource requested is no longer available and will not be available again.', + '410_CLASS': classes.CLIENT_ERROR, + GONE: 410, + // 411 - The request did not specify the length of its content, which is required by the requested resource. + 411: 'Length Required', + '411_NAME': 'LENGTH_REQUIRED', + '411_MESSAGE': 'The request did not specify the length of its content, which is required by the requested resource.', + '411_CLASS': classes.CLIENT_ERROR, + LENGTH_REQUIRED: 411, + // 412 (RFC 7232) - The server does not meet one of the preconditions that the requester put on the request. + 412: 'Precondition Failed', + '412_NAME': 'PRECONDITION_FAILED', + '412_MESSAGE': 'The server does not meet one of the preconditions that the requester put on the request.', + '412_CLASS': classes.CLIENT_ERROR, + PRECONDITION_FAILED: 412, + // 413 (RFC 7231) - The request is larger than the server is willing or able to process. Previously called "Request Entity Too Large". + 413: 'Request Entity Too Large', + '413_NAME': 'REQUEST_ENTITY_TOO_LARGE', + '413_MESSAGE': 'The request is larger than the server is willing or able to process. Previously called "Request Entity Too Large".', + '413_CLASS': classes.CLIENT_ERROR, + REQUEST_ENTITY_TOO_LARGE: 413, + // 414 (RFC 7231) - The URI provided was too long for the server to process. + 414: 'Request-URI Too Large', + '414_NAME': 'REQUEST_URI_TOO_LONG', + '414_MESSAGE': 'The URI provided was too long for the server to process.', + '414_CLASS': classes.CLIENT_ERROR, + REQUEST_URI_TOO_LONG: 414, + // 415 - The request entity has a media type which the server or resource does not support. + 415: 'Unsupported Media Type', + '415_NAME': 'UNSUPPORTED_MEDIA_TYPE', + '415_MESSAGE': 'The request entity has a media type which the server or resource does not support.', + '415_CLASS': classes.CLIENT_ERROR, + UNSUPPORTED_MEDIA_TYPE: 415, + // 416 (RFC 7233) - The client has asked for a portion of the file (byte serving), but the server cannot supply that portion. + 416: 'Requested Range not Satisfiable', + '416_NAME': 'REQUESTED_RANGE_NOT_SATISFIABLE', + '416_MESSAGE': 'The client has asked for a portion of the file (byte serving), but the server cannot supply that portion.', + '416_CLASS': classes.CLIENT_ERROR, + REQUESTED_RANGE_NOT_SATISFIABLE: 416, + // 417 - The server cannot meet the requirements of the Expect request-header field. + 417: 'Expectation Failed', + '417_NAME': 'EXPECTATION_FAILED', + '417_MESSAGE': 'The server cannot meet the requirements of the Expect request-header field.', + '417_CLASS': classes.CLIENT_ERROR, + EXPECTATION_FAILED: 417, + // 418 (RFC 2324, RFC 7168) - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout. This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by teapots requested to brew coffee. This HTTP status is used as an Easter egg in some websites, including Google.com. + 418: 'I\'m a teapot', + '418_NAME': 'IM_A_TEAPOT', + '418_MESSAGE': 'Any attempt to brew coffee with a teapot should result in the error code "418 I\'m a teapot". The resulting entity body MAY be short and stout.', + '418_CLASS': classes.CLIENT_ERROR, + IM_A_TEAPOT: 418, + // 421 (RFC 7540) - The request was directed at a server that is not able to produce a response. + 421: 'Misdirected Request', + '421_NAME': 'MISDIRECTED_REQUEST', + '421_MESSAGE': 'The request was directed at a server that is not able to produce a response.', + '421_CLASS': classes.CLIENT_ERROR, + MISDIRECTED_REQUEST: 421, + // 422 (WebDAV; RFC 4918) - The request was well-formed but was unable to be followed due to semantic errors. + 422: 'Unprocessable Entity', + '422_NAME': 'UNPROCESSABLE_ENTITY', + '422_MESSAGE': 'The request was well-formed but was unable to be followed due to semantic errors.', + '422_CLASS': classes.CLIENT_ERROR, + UNPROCESSABLE_ENTITY: 422, + // 423 (WebDAV; RFC 4918) - The resource that is being accessed is locked. + 423: 'Locked', + '423_NAME': 'LOCKED', + '423_MESSAGE': 'The resource that is being accessed is locked.', + '423_CLASS': classes.CLIENT_ERROR, + LOCKED: 423, + // 424 (WebDAV; RFC 4918) - The request failed because it depended on another request and that request failed. + 424: 'Failed Dependency', + '424_NAME': 'FAILED_DEPENDENCY', + '424_MESSAGE': 'The request failed because it depended on another request and that request failed.', + '424_CLASS': classes.CLIENT_ERROR, + FAILED_DEPENDENCY: 424, + // 426 - The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field. + 426: 'Upgrade Required', + '426_NAME': 'UPGRADE_REQUIRED', + '426_MESSAGE': 'The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field.', + '426_CLASS': classes.CLIENT_ERROR, + UPGRADE_REQUIRED: 426, + // 428 (RFC 6585) - The origin server requires the request to be conditional. + 428: 'Precondition Required', // RFC 6585 + '428_NAME': 'PRECONDITION_REQUIRED', + '428_MESSAGE': 'The origin server requires the request to be conditional.', + '428_CLASS': classes.CLIENT_ERROR, + PRECONDITION_REQUIRED: 428, + // 429 (RFC 6585) - The user has sent too many requests in a given amount of time. + 429: 'Too Many Requests', + '429_NAME': 'TOO_MANY_REQUESTS', + '429_MESSAGE': 'The user has sent too many requests in a given amount of time.', + '429_CLASS': classes.CLIENT_ERROR, + TOO_MANY_REQUESTS: 429, + // 431 (RFC 6585) - The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large. + 431: 'Request Header Fields Too Large', // RFC 6585 + '431_NAME': 'REQUEST_HEADER_FIELDS_TOO_LARGE', + '431_MESSAGE': 'The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large.', + '431_CLASS': classes.CLIENT_ERROR, + REQUEST_HEADER_FIELDS_TOO_LARGE: 431, + // 451 (RFC 7725) - A server operator has received a legal demand to deny access to a resource or to a set of resources that includes the requested resource. + 451: 'Unavailable For Legal Reasons', + '451_NAME': 'UNAVAILABLE_FOR_LEGAL_REASONS', + '451_MESSAGE': 'A server operator has received a legal demand to deny access to a resource or to a set of resources that includes the requested resource.', + '451_CLASS': classes.CLIENT_ERROR, + UNAVAILABLE_FOR_LEGAL_REASONS: 451, + // ## Server Error 5xx + + // Indicates that the server is aware that it has erred or is incapable of performing the requested method. + + // 500 - A generic error message, given when an unexpected condition was encountered and no more specific message is suitable. + 500: 'Internal Server Error', + '500_NAME': 'INTERNAL_SERVER_ERROR', + '500_MESSAGE': 'A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.', + '500_CLASS': classes.SERVER_ERROR, + INTERNAL_SERVER_ERROR: 500, + // 501 - The server either does not recognize the request method, or it lacks the ability to fulfil the request. Usually this implies future availability. + 501: 'Not Implemented', + '501_NAME': 'NOT_IMPLEMENTED', + '501_MESSAGE': 'The server either does not recognize the request method, or it lacks the ability to fulfil the request. Usually this implies future availability.', + '501_CLASS': classes.SERVER_ERROR, + NOT_IMPLEMENTED: 501, + // 502 - The server was acting as a gateway or proxy and received an invalid response from the upstream server. + 502: 'Bad Gateway', + '502_NAME': 'BAD_GATEWAY', + '502_MESSAGE': 'The server was acting as a gateway or proxy and received an invalid response from the upstream server.', + '502_CLASS': classes.SERVER_ERROR, + BAD_GATEWAY: 502, + // 503 - The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state. + 503: 'Service Unavailable', + '503_NAME': 'SERVICE_UNAVAILABLE', + '503_MESSAGE': 'The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.', + '503_CLASS': classes.SERVER_ERROR, + SERVICE_UNAVAILABLE: 503, + // 504 - The server was acting as a gateway or proxy and did not receive a timely response from the upstream server. + 504: 'Gateway Time-out', + '504_NAME': 'GATEWAY_TIMEOUT', + '504_MESSAGE': 'The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.', + '504_CLASS': classes.SERVER_ERROR, + GATEWAY_TIMEOUT: 504, + // 505 - The server does not support the HTTP protocol version used in the request. + 505: 'HTTP Version not Supported', + '505_NAME': 'HTTP_VERSION_NOT_SUPPORTED', + '505_MESSAGE': 'The server does not support the HTTP protocol version used in the request.', + '505_CLASS': classes.SERVER_ERROR, + HTTP_VERSION_NOT_SUPPORTED: 505, + // 506 (RFC 2295) - Transparent content negotiation for the request results in a circular reference. + 506: 'Variant Also Negotiates', + '506_NAME': 'VARIANT_ALSO_NEGOTIATES', + '506_MESSAGE': 'Transparent content negotiation for the request results in a circular reference.', + '506_CLASS': classes.SERVER_ERROR, + VARIANT_ALSO_NEGOTIATES: 506, + // 507 (WebDAV; RFC 4918) - The server is unable to store the representation needed to complete the request. + 507: 'Insufficient Storage', + '507_NAME': 'INSUFFICIENT_STORAGE', + '507_MESSAGE': 'The server is unable to store the representation needed to complete the request.', + '507_CLASS': classes.SERVER_ERROR, + INSUFFICIENT_STORAGE: 507, + // 508 (WebDAV; RFC 5842) - The server detected an infinite loop while processing the request. + 508: 'Loop Detected', + '508_NAME': 'LOOP_DETECTED', + '508_MESSAGE': 'The server detected an infinite loop while processing the request.', + '508_CLASS': classes.SERVER_ERROR, + LOOP_DETECTED: 508, + // 510 (RFC 2774) - Further extensions to the request are required for the server to fulfil it. + 510: 'Not Extended', + '510_NAME': 'NOT_EXTENDED', + '510_MESSAGE': 'Further extensions to the request are required for the server to fulfil it.', + '510_CLASS': classes.SERVER_ERROR, + NOT_EXTENDED: 510, + // 511 (RFC 6585) - The client needs to authenticate to gain network access. Intended for use by intercepting proxies used to control access to the network. + 511: 'Network Authentication Required', + '511_NAME': 'NETWORK_AUTHENTICATION_REQUIRED', + '511_MESSAGE': 'The client needs to authenticate to gain network access. Intended for use by intercepting proxies used to control access to the network.', + '511_CLASS': classes.SERVER_ERROR, + NETWORK_AUTHENTICATION_REQUIRED: 511, + // ## Extra code + + // Extra HTTP code implemented by vendors and other specifications. + extra: { + // ### Unofficial codes + + // The following codes are not specified by any standard. + unofficial: { + // 103 - Used in the resumable requests proposal to resume aborted PUT or POST requests. + 103: 'Checkpoint', + '103_NAME': 'CHECKPOINT', + '103_MESSAGE': 'Used in the resumable requests proposal to resume aborted PUT or POST requests.', + '103_CLASS': classes.INFORMATIONAL, + CHECKPOINT: 103, + // 419 Page Expired (Laravel Framework) - Used by the Laravel Framework when a CSRF Token is missing or expired. + 419: 'Page Expired', + '419_NAME': 'PAGE_EXPIRED', + '419_MESSAGE': 'Used by the Laravel Framework when a CSRF Token is missing or expired.', + '419_CLASS': classes.CLIENT_ERROR, + PAGE_EXPIRED: 419, + // 218 This is fine (Apache Web Server) - Used as a catch-all error condition for allowing response bodies to flow through Apache when ProxyErrorOverride is enabled. When ProxyErrorOverride is enabled in Apache, response bodies that contain a status code of 4xx or 5xx are automatically discarded by Apache in favor of a generic response or a custom response specified by the ErrorDocument directive. + 218: 'This is fine', + '218_NAME': 'THIS_IS_FINE', + '218_MESSAGE': 'Used as a catch-all error condition for allowing response bodies to flow through Apache when ProxyErrorOverride is enabled. When ProxyErrorOverride is enabled in Apache, response bodies that contain a status code of 4xx or 5xx are automatically discarded by Apache in favor of a generic response or a custom response specified by the ErrorDocument directive.', + '218_CLASS': classes.SUCCESSFUL, + THIS_IS_FINE: 218, + // 420 Enhance Your Calm (Twitter) - Returned by version 1 of the Twitter Search and Trends API when the client is being rate limited; versions 1.1 and later use the 429 Too Many Requests response code instead. + 420: 'Enhance Your Calm', + '420_NAME': 'ENHANCE_YOUR_CALM', + '420_MESSAGE': 'Returned by version 1 of the Twitter Search and Trends API when the client is being rate limited; versions 1.1 and later use the 429 Too Many Requests response code instead.', + '420_CLASS': classes.CLIENT_ERROR, + ENHANCE_YOUR_CALM: 420, + // 450 Blocked by Windows Parental (Microsoft) - The Microsoft extension code indicated when Windows Parental Controls are turned on and are blocking access to the requested webpage. + 450: 'Blocked by Windows Parental Controls', + '450_NAME': 'BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS', + '450_MESSAGE': 'The Microsoft extension code indicated when Windows Parental Controls are turned on and are blocking access to the requested webpage.', + '450_CLASS': classes.CLIENT_ERROR, + BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS: 450, + // 498 Invalid Token (Esri) - Returned by ArcGIS for Server. Code 498 indicates an expired or otherwise invalid token. + 498: 'Invalid Token', + '498_NAME': 'INVALID_TOKEN', + '498_MESSAGE': 'Returned by ArcGIS for Server. Code 498 indicates an expired or otherwise invalid token.', + '498_CLASS': classes.CLIENT_ERROR, + INVALID_TOKEN: 498, + // 499 Token Required (Esri) - Returned by ArcGIS for Server. Code 499 indicates that a token is required but was not submitted. + 499: 'Token Required', + '499_NAME': 'TOKEN_REQUIRED', + '499_MESSAGE': 'Returned by ArcGIS for Server. Code 499 indicates that a token is required but was not submitted.', + '499_CLASS': classes.CLIENT_ERROR, + TOKEN_REQUIRED: 499, + // 509 Bandwidth Limit Exceeded (Apache Web Server/cPanel) - The server has exceeded the bandwidth specified by the server administrator. + 509: 'Bandwidth Limit Exceeded', + '509_NAME': 'BANDWIDTH_LIMIT_EXCEEDED', + '509_MESSAGE': 'The server has exceeded the bandwidth specified by the server administrator.', + '509_CLASS': classes.SERVER_ERROR, + BANDWIDTH_LIMIT_EXCEEDED: 509, + // 530 Site is frozen - Used by the Pantheon web platform to indicate a site that has been frozen due to inactivity. + 530: 'Site is frozen', + '530_NAME': 'SITE_IS_FROZEN', + '530_MESSAGE': 'Used by the Pantheon web platform to indicate a site that has been frozen due to inactivity.', + '530_CLASS': classes.SERVER_ERROR, + SITE_IS_FROZEN: 530, + // 598 (Informal convention) Network read timeout error - Used by some HTTP proxies to signal a network read timeout behind the proxy to a client in front of the proxy. + 598: 'Network read timeout error', + '598_NAME': 'NETWORK_READ_TIMEOUT_ERROR', + '598_MESSAGE': 'Used by some HTTP proxies to signal a network read timeout behind the proxy to a client in front of the proxy.', + '598_CLASS': classes.SERVER_ERROR, + NETWORK_READ_TIMEOUT_ERROR: 598 + }, + // ### Internet Information Services (IIS) + + // Microsoft's Internet Information Services (IIS) web server expands the 4xx error space to signal errors with the client's request. + iis: { + // 440 - The client's session has expired and must log in again. + 440: 'Login Time-out', + '440_NAME': 'LOGIN_TIME_OUT', + '440_MESSAGE': 'The client\'s session has expired and must log in again.', + '440_CLASS': classes.CLIENT_ERROR, + LOGIN_TIME_OUT: 440, + // 449 - The server cannot honour the request because the user has not provided the required information. + 449: 'Retry With', + '449_NAME': 'RETRY_WITH', + '449_MESSAGE': 'The server cannot honour the request because the user has not provided the required information.', + '449_CLASS': classes.CLIENT_ERROR, + RETRY_WITH: 449, + // 451 - Used in Exchange ActiveSync when either a more efficient server is available or the server cannot access the users' mailbox. + 451: 'Redirect', + '451_NAME': 'REDIRECT', + '451_MESSAGE': 'Used in Exchange ActiveSync when either a more efficient server is available or the server cannot access the users\' mailbox.', + '451_CLASS': classes.CLIENT_ERROR, + REDIRECT: 451 + }, + // ### NGINX + + // The NGINX web server software expands the 4xx error space to signal issues with the client's request. + nginx: { + // 444 - Used internally to instruct the server to return no information to the client and close the connection immediately. + 444: 'No Response', + '444_NAME': 'NO_RESPONSE', + '444_MESSAGE': 'Used internally to instruct the server to return no information to the client and close the connection immediately.', + '444_CLASS': classes.CLIENT_ERROR, + NO_RESPONSE: 444, + // 494 - Client sent too large request or too long header line. + 494: 'Request header too large', + '494_NAME': 'REQUEST_HEADER_TOO_LARGE', + '494_MESSAGE': 'Client sent too large request or too long header line.', + '494_CLASS': classes.CLIENT_ERROR, + REQUEST_HEADER_TOO_LARGE: 494, + // 495 - An expansion of the 400 Bad Request response code, used when the client has provided an invalid client certificate. + 495: 'SSL Certificate Error', + '495_NAME': 'SSL_CERTIFICATE_ERROR', + '495_MESSAGE': 'An expansion of the 400 Bad Request response code, used when the client has provided an invalid client certificate.', + '495_CLASS': classes.CLIENT_ERROR, + SSL_CERTIFICATE_ERROR: 495, + // 496 - An expansion of the 400 Bad Request response code, used when a client certificate is required but not provided. + 496: 'SSL Certificate Required', + '496_NAME': 'SSL_CERTIFICATE_REQUIRED', + '496_MESSAGE': 'An expansion of the 400 Bad Request response code, used when a client certificate is required but not provided.', + '496_CLASS': classes.CLIENT_ERROR, + SSL_CERTIFICATE_REQUIRED: 496, + // 497 - An expansion of the 400 Bad Request response code, used when the client has made a HTTP request to a port listening for HTTPS requests. + 497: 'HTTP Request Sent to HTTPS Port', + '497_NAME': 'HTTP_REQUEST_SENT_TO_HTTPS_PORT', + '497_MESSAGE': 'An expansion of the 400 Bad Request response code, used when the client has made a HTTP request to a port listening for HTTPS requests.', + '497_CLASS': classes.CLIENT_ERROR, + HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497, + // 499 - Used when the client has closed the request before the server could send a response. + 499: 'Client Closed Request', + '499_NAME': 'CLIENT_CLOSED_REQUEST', + '499_MESSAGE': 'Used when the client has closed the request before the server could send a response.', + '499_CLASS': classes.CLIENT_ERROR, + CLIENT_CLOSED_REQUEST: 499 + }, + // ### Cloudflare + + // Cloudflare's reverse proxy service expands the 5xx series of errors space to signal issues with the origin server. + cloudflare: { + // 520 - The 520 error is used as a "catch-all response for when the origin server returns something unexpected", listing connection resets, large headers, and empty or invalid responses as common triggers. + 520: 'Unknown Error', + '520_NAME': 'UNKNOWN_ERROR', + '520_MESSAGE': 'The 520 error is used as a "catch-all response for when the origin server returns something unexpected", listing connection resets, large headers, and empty or invalid responses as common triggers.', + '520_CLASS': classes.SERVER_ERROR, + UNKNOWN_ERROR: 520, + // 521 - The origin server has refused the connection from Cloudflare. + 521: 'Web Server Is Down', + '521_NAME': 'WEB_SERVER_IS_DOWN', + '521_MESSAGE': 'The origin server has refused the connection from Cloudflare.', + '521_CLASS': classes.SERVER_ERROR, + WEB_SERVER_IS_DOWN: 521, + // 522 - Cloudflare could not negotiate a TCP handshake with the origin server. + 522: 'Connection Timed Out', + '522_NAME': 'CONNECTION_TIMED_OUT', + '522_MESSAGE': 'Cloudflare could not negotiate a TCP handshake with the origin server.', + '522_CLASS': classes.SERVER_ERROR, + CONNECTION_TIMED_OUT: 522, + // 523 - Cloudflare could not reach the origin server. + 523: 'Origin Is Unreachable', + '523_NAME': 'ORIGIN_IS_UNREACHABLE', + '523_MESSAGE': 'Cloudflare could not reach the origin server.', + '523_CLASS': classes.SERVER_ERROR, + ORIGIN_IS_UNREACHABLE: 523, + // 524 - Cloudflare was able to complete a TCP connection to the origin server, but did not receive a timely HTTP response. + 524: 'A Timeout Occurred', + '524_NAME': 'A_TIMEOUT_OCCURRED', + '524_MESSAGE': 'Cloudflare was able to complete a TCP connection to the origin server, but did not receive a timely HTTP response.', + '524_CLASS': classes.SERVER_ERROR, + A_TIMEOUT_OCCURRED: 524, + // 525 - Cloudflare could not negotiate a SSL/TLS handshake with the origin server. + 525: 'SSL Handshake Failed', + '525_NAME': 'SSL_HANDSHAKE_FAILED', + '525_MESSAGE': 'Cloudflare could not negotiate a SSL/TLS handshake with the origin server.', + '525_CLASS': classes.SERVER_ERROR, + SSL_HANDSHAKE_FAILED: 525, + // 526 - Cloudflare could not validate the SSL/TLS certificate that the origin server presented. + 526: 'Invalid SSL Certificate', + '526_NAME': 'INVALID_SSL_CERTIFICATE', + '526_MESSAGE': 'Cloudflare could not validate the SSL/TLS certificate that the origin server presented.', + '526_CLASS': classes.SERVER_ERROR, + INVALID_SSL_CERTIFICATE: 526, + // 527 - Error 527 indicates that the request timed out or failed after the WAN connection had been established. + 527: 'Railgun Error', + '527_NAME': 'RAILGUN_ERROR', + '527_MESSAGE': 'Error 527 indicates that the request timed out or failed after the WAN connection had been established.', + '527_CLASS': classes.SERVER_ERROR, + RAILGUN_ERROR: 527 + } + } +}; diff --git a/node_modules/http-status/lib/nginx.js b/node_modules/http-status/lib/nginx.js new file mode 100644 index 0000000..172d320 --- /dev/null +++ b/node_modules/http-status/lib/nginx.js @@ -0,0 +1,23 @@ +// Generated by CoffeeScript 2.5.1 +// # NGINX extra status codes + +// The NGINX web server software expands the 4xx error class to signal issues with the client's request. +var k, ref, status, v; + +status = require('.'); + +// Import default status codes. +for (k in status) { + v = status[k]; + if (k === 'extra') { + continue; + } + module.exports[k] = v; +} + +ref = status.extra.nginx; +// Merge default status codes with NGINX status codes. +for (k in ref) { + v = ref[k]; + module.exports[k] = v; +} diff --git a/node_modules/http-status/lib/unofficial.js b/node_modules/http-status/lib/unofficial.js new file mode 100644 index 0000000..ad5e236 --- /dev/null +++ b/node_modules/http-status/lib/unofficial.js @@ -0,0 +1,23 @@ +// Generated by CoffeeScript 2.5.1 +// # Unofficial extra status codes + +// This represent a list of codes which are not specified by any standard. +var k, ref, status, v; + +status = require('.'); + +// Import default status codes. +for (k in status) { + v = status[k]; + if (k === 'extra') { + continue; + } + module.exports[k] = v; +} + +ref = status.extra.unofficial; +// Merge default status codes with unofficial status codes. +for (k in ref) { + v = ref[k]; + module.exports[k] = v; +} diff --git a/node_modules/http-status/package.json b/node_modules/http-status/package.json new file mode 100644 index 0000000..0b388a4 --- /dev/null +++ b/node_modules/http-status/package.json @@ -0,0 +1,82 @@ +{ + "name": "http-status", + "version": "1.5.0", + "description": "Interact with HTTP status code", + "homepage": "https://github.com/adaltas/node-http-status", + "author": "David Worms (https://www.adaltas.com)", + "keywords": [ + "http", + "express", + "connect" + ], + "license": "BSD-3-Clause", + "repository": { + "type": "git", + "url": "https://github.com/adaltas/node-http-status" + }, + "bugs": { + "email": "open@adaltas.com", + "url": "http://github.com/adaltas/node-http-status/issues" + }, + "devDependencies": { + "@types/mocha": "^8.0.4", + "@types/node": "^14.14.7", + "@types/should": "^13.0.0", + "coffeescript": "2.5.1", + "mocha": "8.2.1", + "should": "13.2.3", + "ts-node": "^9.0.0", + "typescript": "^4.0.5" + }, + "coffeelintConfig": { + "indentation": { + "level": "error", + "value": 2 + }, + "line_endings": { + "level": "error", + "value": "unix" + }, + "max_line_length": { + "level": "ignore" + } + }, + "contributors": [ + { + "name": "David Worms", + "email": "david@adaltas.com" + }, + { + "name": "Daniel Gasienica", + "email": "daniel@gasienica.ch" + } + ], + "mocha": { + "throw-deprecation": true, + "require": [ + "should", + "coffeescript/register", + "ts-node/register" + ], + "inline-diffs": true, + "timeout": 40000, + "reporter": "spec", + "recursive": true + }, + "main": "lib/index.js", + "types": "lib/index.d.ts", + "engines": { + "node": ">= 0.4.0" + }, + "scripts": { + "preversion": "grep '## Trunk' CHANGELOG.md && npm test", + "version": "version=`grep '^ \"version\": ' package.json | sed 's/.*\"\\([0-9\\.]*\\)\".*/\\1/'` && sed -i \"s/## Trunk/## Version $version/\" CHANGELOG.md && git add CHANGELOG.md", + "postversion": "git push origin master && git push origin master --tags && npm publish", + "patch": "npm version patch -m 'Bump to version %s'", + "minor": "npm version minor -m 'Bump to version %s'", + "major": "npm version major -m 'Bump to version %s'", + "coffee": "coffee -b -o lib src", + "pretest": "coffee -b -o lib src && cp src/index.d.ts lib", + "test": "mocha \"test/**/*.{coffee,ts}\"" + } +} diff --git a/node_modules/http-status/tsconfig.json b/node_modules/http-status/tsconfig.json new file mode 100644 index 0000000..9f40782 --- /dev/null +++ b/node_modules/http-status/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "target": "es6", + "moduleResolution": "node", + "strict": true, + } +} diff --git a/node_modules/https-proxy-agent/README.md b/node_modules/https-proxy-agent/README.md new file mode 100644 index 0000000..328656a --- /dev/null +++ b/node_modules/https-proxy-agent/README.md @@ -0,0 +1,137 @@ +https-proxy-agent +================ +### An HTTP(s) proxy `http.Agent` implementation for HTTPS +[![Build Status](https://github.com/TooTallNate/node-https-proxy-agent/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-https-proxy-agent/actions?workflow=Node+CI) + +This module provides an `http.Agent` implementation that connects to a specified +HTTP or HTTPS proxy server, and can be used with the built-in `https` module. + +Specifically, this `Agent` implementation connects to an intermediary "proxy" +server and issues the [CONNECT HTTP method][CONNECT], which tells the proxy to +open a direct TCP connection to the destination server. + +Since this agent implements the CONNECT HTTP method, it also works with other +protocols that use this method when connecting over proxies (i.e. WebSockets). +See the "Examples" section below for more. + + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install https-proxy-agent +``` + + +Examples +-------- + +#### `https` module example + +``` js +var url = require('url'); +var https = require('https'); +var HttpsProxyAgent = require('https-proxy-agent'); + +// HTTP/HTTPS proxy to connect to +var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; +console.log('using proxy server %j', proxy); + +// HTTPS endpoint for the proxy to connect to +var endpoint = process.argv[2] || 'https://graph.facebook.com/tootallnate'; +console.log('attempting to GET %j', endpoint); +var options = url.parse(endpoint); + +// create an instance of the `HttpsProxyAgent` class with the proxy server information +var agent = new HttpsProxyAgent(proxy); +options.agent = agent; + +https.get(options, function (res) { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +#### `ws` WebSocket connection example + +``` js +var url = require('url'); +var WebSocket = require('ws'); +var HttpsProxyAgent = require('https-proxy-agent'); + +// HTTP/HTTPS proxy to connect to +var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; +console.log('using proxy server %j', proxy); + +// WebSocket endpoint for the proxy to connect to +var endpoint = process.argv[2] || 'ws://echo.websocket.org'; +var parsed = url.parse(endpoint); +console.log('attempting to connect to WebSocket %j', endpoint); + +// create an instance of the `HttpsProxyAgent` class with the proxy server information +var options = url.parse(proxy); + +var agent = new HttpsProxyAgent(options); + +// finally, initiate the WebSocket connection +var socket = new WebSocket(endpoint, { agent: agent }); + +socket.on('open', function () { + console.log('"open" event!'); + socket.send('hello world'); +}); + +socket.on('message', function (data, flags) { + console.log('"message" event! %j %j', data, flags); + socket.close(); +}); +``` + +API +--- + +### new HttpsProxyAgent(Object options) + +The `HttpsProxyAgent` class implements an `http.Agent` subclass that connects +to the specified "HTTP(s) proxy server" in order to proxy HTTPS and/or WebSocket +requests. This is achieved by using the [HTTP `CONNECT` method][CONNECT]. + +The `options` argument may either be a string URI of the proxy server to use, or an +"options" object with more specific properties: + + * `host` - String - Proxy host to connect to (may use `hostname` as well). Required. + * `port` - Number - Proxy port to connect to. Required. + * `protocol` - String - If `https:`, then use TLS to connect to the proxy. + * `headers` - Object - Additional HTTP headers to be sent on the HTTP CONNECT method. + * Any other options given are passed to the `net.connect()`/`tls.connect()` functions. + + +License +------- + +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net> + +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. + +[CONNECT]: http://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_Tunneling diff --git a/node_modules/https-proxy-agent/dist/agent.d.ts b/node_modules/https-proxy-agent/dist/agent.d.ts new file mode 100644 index 0000000..4f1c636 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/agent.d.ts @@ -0,0 +1,30 @@ +/// +import net from 'net'; +import { Agent, ClientRequest, RequestOptions } from 'agent-base'; +import { HttpsProxyAgentOptions } from '.'; +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +export default class HttpsProxyAgent extends Agent { + private secureProxy; + private proxy; + constructor(_opts: string | HttpsProxyAgentOptions); + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req: ClientRequest, opts: RequestOptions): Promise; +} diff --git a/node_modules/https-proxy-agent/dist/agent.js b/node_modules/https-proxy-agent/dist/agent.js new file mode 100644 index 0000000..d666525 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/agent.js @@ -0,0 +1,180 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const net_1 = __importDefault(require("net")); +const tls_1 = __importDefault(require("tls")); +const url_1 = __importDefault(require("url")); +const assert_1 = __importDefault(require("assert")); +const debug_1 = __importDefault(require("debug")); +const agent_base_1 = require("agent-base"); +const parse_proxy_response_1 = __importDefault(require("./parse-proxy-response")); +const debug = debug_1.default('https-proxy-agent:agent'); +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); + } + else { + opts = _opts; + } + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + } + debug('creating new HttpsProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + // ALPN is supported by Node.js >= v5. + // attempt to negotiate http/1.1 for proxy servers that support http/2 + if (this.secureProxy && !('ALPNProtocols' in proxy)) { + proxy.ALPNProtocols = ['http 1.1']; + } + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); + } + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); + } + const headers = Object.assign({}, proxy.headers); + const hostname = `${opts.host}:${opts.port}`; + let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; + } + // The `Host` header should only include the port + // number when it is not the default port. + let { host, port, secureEndpoint } = opts; + if (!isDefaultPort(port, secureEndpoint)) { + host += `:${port}`; + } + headers.Host = host; + headers.Connection = 'close'; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = parse_proxy_response_1.default(socket); + socket.write(`${payload}\r\n`); + const { statusCode, buffered } = yield proxyResponsePromise; + if (statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + const servername = opts.servername || opts.host; + if (!servername) { + throw new Error('Could not determine "servername"'); + } + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, + servername })); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net_1.default.Socket(); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('replaying proxy buffer for failed request'); + assert_1.default(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + }); + } +} +exports.default = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function isDefaultPort(port, secure) { + return Boolean((!secure && port === 80) || (secure && port === 443)); +} +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=agent.js.map \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/agent.js.map b/node_modules/https-proxy-agent/dist/agent.js.map new file mode 100644 index 0000000..d1307cd --- /dev/null +++ b/node_modules/https-proxy-agent/dist/agent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8CAAsB;AACtB,8CAAsB;AACtB,8CAAsB;AACtB,oDAA4B;AAC5B,kDAAgC;AAEhC,2CAAkE;AAElE,kFAAwD;AAExD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AO,GAAG,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/index.d.ts b/node_modules/https-proxy-agent/dist/index.d.ts new file mode 100644 index 0000000..0d60062 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/index.d.ts @@ -0,0 +1,23 @@ +/// +import net from 'net'; +import tls from 'tls'; +import { Url } from 'url'; +import { AgentOptions } from 'agent-base'; +import { OutgoingHttpHeaders } from 'http'; +import _HttpsProxyAgent from './agent'; +declare function createHttpsProxyAgent(opts: string | createHttpsProxyAgent.HttpsProxyAgentOptions): _HttpsProxyAgent; +declare namespace createHttpsProxyAgent { + interface BaseHttpsProxyAgentOptions { + headers?: OutgoingHttpHeaders; + secureProxy?: boolean; + host?: string | null; + path?: string | null; + port?: string | number | null; + } + export interface HttpsProxyAgentOptions extends AgentOptions, BaseHttpsProxyAgentOptions, Partial> { + } + export type HttpsProxyAgent = _HttpsProxyAgent; + export const HttpsProxyAgent: typeof _HttpsProxyAgent; + export {}; +} +export = createHttpsProxyAgent; diff --git a/node_modules/https-proxy-agent/dist/index.js b/node_modules/https-proxy-agent/dist/index.js new file mode 100644 index 0000000..b03e763 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/index.js @@ -0,0 +1,14 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(require("./agent")); +function createHttpsProxyAgent(opts) { + return new agent_1.default(opts); +} +(function (createHttpsProxyAgent) { + createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; + createHttpsProxyAgent.prototype = agent_1.default.prototype; +})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); +module.exports = createHttpsProxyAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/index.js.map b/node_modules/https-proxy-agent/dist/index.js.map new file mode 100644 index 0000000..f3ce559 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAKA,oDAAuC;AAEvC,SAAS,qBAAqB,CAC7B,IAA2D;IAE3D,OAAO,IAAI,eAAgB,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC;AAED,WAAU,qBAAqB;IAoBjB,qCAAe,GAAG,eAAgB,CAAC;IAEhD,qBAAqB,CAAC,SAAS,GAAG,eAAgB,CAAC,SAAS,CAAC;AAC9D,CAAC,EAvBS,qBAAqB,KAArB,qBAAqB,QAuB9B;AAED,iBAAS,qBAAqB,CAAC"} \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts b/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts new file mode 100644 index 0000000..7565674 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts @@ -0,0 +1,7 @@ +/// +import { Readable } from 'stream'; +export interface ProxyResponse { + statusCode: number; + buffered: Buffer; +} +export default function parseProxyResponse(socket: Readable): Promise; diff --git a/node_modules/https-proxy-agent/dist/parse-proxy-response.js b/node_modules/https-proxy-agent/dist/parse-proxy-response.js new file mode 100644 index 0000000..aa5ce3c --- /dev/null +++ b/node_modules/https-proxy-agent/dist/parse-proxy-response.js @@ -0,0 +1,66 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const debug_1 = __importDefault(require("debug")); +const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('close', onclose); + socket.removeListener('readable', read); + } + function onclose(err) { + debug('onclose had error %o', err); + } + function onend() { + debug('onend'); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); + const statusCode = +firstLine.split(' ')[1]; + debug('got proxy server response: %o', firstLine); + resolve({ + statusCode, + buffered + }); + } + socket.on('error', onerror); + socket.on('close', onclose); + socket.on('end', onend); + read(); + }); +} +exports.default = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map b/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map new file mode 100644 index 0000000..bacdb84 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-proxy-response.js","sourceRoot":"","sources":["../src/parse-proxy-response.ts"],"names":[],"mappings":";;;;;AAAA,kDAAgC;AAGhC,MAAM,KAAK,GAAG,eAAW,CAAC,wCAAwC,CAAC,CAAC;AAOpE,SAAwB,kBAAkB,CACzC,MAAgB;IAEhB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,+EAA+E;QAC/E,gFAAgF;QAChF,8EAA8E;QAC9E,8BAA8B;QAC9B,IAAI,aAAa,GAAG,CAAC,CAAC;QACtB,MAAM,OAAO,GAAa,EAAE,CAAC;QAE7B,SAAS,IAAI;YACZ,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;YACxB,IAAI,CAAC;gBAAE,MAAM,CAAC,CAAC,CAAC,CAAC;;gBACZ,MA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C,CAAC,CAAC,CAAC;YAC5C,KAAK,CAAC,+BAA+B,EAAE,SAAS,CAAC,CAAC;YAClD,OAAO,CAAC;gBACP,UAAU;gBACV,QAAQ;aACR,CAAC,CAAC;QACJ,CAAC;QAED,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5B,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5B,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QAExB,IAAI,EAAE,CAAC;IACR,CAAC,CAAC,CAAC;AACJ,CAAC;AAvED,qCAuEC"} \ No newline at end of file diff --git a/node_modules/https-proxy-agent/node_modules/debug/LICENSE b/node_modules/https-proxy-agent/node_modules/debug/LICENSE new file mode 100644 index 0000000..1a9820e --- /dev/null +++ b/node_modules/https-proxy-agent/node_modules/debug/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/https-proxy-agent/node_modules/debug/README.md b/node_modules/https-proxy-agent/node_modules/debug/README.md new file mode 100644 index 0000000..5ea4cd2 --- /dev/null +++ b/node_modules/https-proxy-agent/node_modules/debug/README.md @@ -0,0 +1,478 @@ +# debug +[![Build Status](https://travis-ci.org/debug-js/debug.svg?branch=master)](https://travis-ci.org/debug-js/debug) [![Coverage Status](https://coveralls.io/repos/github/debug-js/debug/badge.svg?branch=master)](https://coveralls.io/github/debug-js/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny JavaScript debugging utility modelled after Node.js core's debugging +technique. Works in Node.js and web browsers. + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example [_app.js_](./examples/node/app.js): + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %o', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example [_worker.js_](./examples/node/worker.js): + +```js +var a = require('debug')('worker:a') + , b = require('debug')('worker:b'); + +function work() { + a('doing lots of uninteresting work'); + setTimeout(work, Math.random() * 1000); +} + +work(); + +function workb() { + b('doing some work'); + setTimeout(workb, Math.random() * 2000); +} + +workb(); +``` + +The `DEBUG` environment variable is then used to enable these based on space or +comma-delimited names. + +Here are some examples: + +screen shot 2017-08-08 at 12 53 04 pm +screen shot 2017-08-08 at 12 53 38 pm +screen shot 2017-08-08 at 12 53 25 pm + +#### Windows command prompt notes + +##### CMD + +On Windows the environment variable is set using the `set` command. + +```cmd +set DEBUG=*,-not_this +``` + +Example: + +```cmd +set DEBUG=* & node app.js +``` + +##### PowerShell (VS Code default) + +PowerShell uses different syntax to set environment variables. + +```cmd +$env:DEBUG = "*,-not_this" +``` + +Example: + +```cmd +$env:DEBUG='app';node app.js +``` + +Then, run the program to be debugged as usual. + +npm script example: +```js + "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", +``` + +## Namespace Colors + +Every debug instance has a color generated for it based on its namespace name. +This helps when visually parsing the debug output to identify which debug instance +a debug line belongs to. + +#### Node.js + +In Node.js, colors are enabled when stderr is a TTY. You also _should_ install +the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, +otherwise debug will only use a small handful of basic colors. + + + +#### Web Browser + +Colors are also enabled on "Web Inspectors" that understand the `%c` formatting +option. These are WebKit web inspectors, Firefox ([since version +31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) +and the Firebug plugin for Firefox (any version). + + + + +## Millisecond diff + +When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + + +When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: + + + + +## Conventions + +If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. + +## Wildcards + +The `*` character may be used as a wildcard. Suppose for example your library has +debuggers named "connect:bodyParser", "connect:compress", "connect:session", +instead of listing all three with +`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do +`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + +You can also exclude specific debuggers by prefixing them with a "-" character. +For example, `DEBUG=*,-connect:*` would include all debuggers except those +starting with "connect:". + +## Environment Variables + +When running through Node.js, you can set a few environment variables that will +change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + +__Note:__ The environment variables beginning with `DEBUG_` end up being +converted into an Options object that gets used with `%o`/`%O` formatters. +See the Node.js documentation for +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +## Formatters + +Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. +Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + + +### Custom formatters + +You can add custom formatters by extending the `debug.formatters` object. +For example, if you wanted to add support for rendering a Buffer as hex with +`%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + + +## Browser Support + +You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), +or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), +if you don't want to build it yourself. + +Debug's enable state is currently persisted by `localStorage`. +Consider the situation shown below where you have `worker:a` and `worker:b`, +and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example [_stdout.js_](./examples/node/stdout.js): + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + +## Extend +You can simply extend debugger +```js +const log = require('debug')('auth'); + +//creates new debug instance with extended namespace +const logSign = log.extend('sign'); +const logLogin = log.extend('login'); + +log('hello'); // auth hello +logSign('hello'); //auth:sign hello +logLogin('hello'); //auth:login hello +``` + +## Set dynamically + +You can also enable debug dynamically by calling the `enable()` method : + +```js +let debug = require('debug'); + +console.log(1, debug.enabled('test')); + +debug.enable('test'); +console.log(2, debug.enabled('test')); + +debug.disable(); +console.log(3, debug.enabled('test')); + +``` + +print : +``` +1 false +2 true +3 false +``` + +Usage : +`enable(namespaces)` +`namespaces` can include modes separated by a colon and wildcards. + +Note that calling `enable()` completely overrides previously set DEBUG variable : + +``` +$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' +=> false +``` + +`disable()` + +Will disable all namespaces. The functions returns the namespaces currently +enabled (and skipped). This can be useful if you want to disable debugging +temporarily without knowing what was enabled to begin with. + +For example: + +```js +let debug = require('debug'); +debug.enable('foo:*,-foo:bar'); +let namespaces = debug.disable(); +debug.enable(namespaces); +``` + +Note: There is no guarantee that the string will be identical to the initial +enable string, but semantically they will be identical. + +## Checking whether a debug target is enabled + +After you've created a debug instance, you can determine whether or not it is +enabled by checking the `enabled` property: + +```javascript +const debug = require('debug')('http'); + +if (debug.enabled) { + // do stuff... +} +``` + +You can also manually toggle this property to force the debug instance to be +enabled or disabled. + +## Usage in child processes + +Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process. +For example: + +```javascript +worker = fork(WORKER_WRAP_PATH, [workerPath], { + stdio: [ + /* stdin: */ 0, + /* stdout: */ 'pipe', + /* stderr: */ 'pipe', + 'ipc', + ], + env: Object.assign({}, process.env, { + DEBUG_COLORS: 1 // without this settings, colors won't be shown + }), +}); + +worker.stderr.pipe(process.stderr, { end: false }); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + - Josh Junon + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> +Copyright (c) 2018-2021 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/https-proxy-agent/node_modules/debug/package.json b/node_modules/https-proxy-agent/node_modules/debug/package.json new file mode 100644 index 0000000..cb7efa8 --- /dev/null +++ b/node_modules/https-proxy-agent/node_modules/debug/package.json @@ -0,0 +1,59 @@ +{ + "name": "debug", + "version": "4.3.3", + "repository": { + "type": "git", + "url": "git://github.com/debug-js/debug.git" + }, + "description": "Lightweight debugging utility for Node.js and the browser", + "keywords": [ + "debug", + "log", + "debugger" + ], + "files": [ + "src", + "LICENSE", + "README.md" + ], + "author": "Josh Junon ", + "contributors": [ + "TJ Holowaychuk ", + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "scripts": { + "lint": "xo", + "test": "npm run test:node && npm run test:browser && npm run lint", + "test:node": "istanbul cover _mocha -- test.js", + "test:browser": "karma start --single-run", + "test:coverage": "cat ./coverage/lcov.info | coveralls" + }, + "dependencies": { + "ms": "2.1.2" + }, + "devDependencies": { + "brfs": "^2.0.1", + "browserify": "^16.2.3", + "coveralls": "^3.0.2", + "istanbul": "^0.4.5", + "karma": "^3.1.4", + "karma-browserify": "^6.0.0", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "mocha": "^5.2.0", + "mocha-lcov-reporter": "^1.2.0", + "xo": "^0.23.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "engines": { + "node": ">=6.0" + } +} diff --git a/node_modules/https-proxy-agent/node_modules/debug/src/browser.js b/node_modules/https-proxy-agent/node_modules/debug/src/browser.js new file mode 100644 index 0000000..cd0fc35 --- /dev/null +++ b/node_modules/https-proxy-agent/node_modules/debug/src/browser.js @@ -0,0 +1,269 @@ +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; diff --git a/node_modules/https-proxy-agent/node_modules/debug/src/common.js b/node_modules/https-proxy-agent/node_modules/debug/src/common.js new file mode 100644 index 0000000..6d571d2 --- /dev/null +++ b/node_modules/https-proxy-agent/node_modules/debug/src/common.js @@ -0,0 +1,274 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; diff --git a/node_modules/https-proxy-agent/node_modules/debug/src/index.js b/node_modules/https-proxy-agent/node_modules/debug/src/index.js new file mode 100644 index 0000000..bf4c57f --- /dev/null +++ b/node_modules/https-proxy-agent/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/https-proxy-agent/node_modules/debug/src/node.js b/node_modules/https-proxy-agent/node_modules/debug/src/node.js new file mode 100644 index 0000000..79bc085 --- /dev/null +++ b/node_modules/https-proxy-agent/node_modules/debug/src/node.js @@ -0,0 +1,263 @@ +/** + * Module dependencies. + */ + +const tty = require('tty'); +const util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; diff --git a/node_modules/https-proxy-agent/node_modules/ms/index.js b/node_modules/https-proxy-agent/node_modules/ms/index.js new file mode 100644 index 0000000..c4498bc --- /dev/null +++ b/node_modules/https-proxy-agent/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/https-proxy-agent/node_modules/ms/license.md b/node_modules/https-proxy-agent/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/https-proxy-agent/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/https-proxy-agent/node_modules/ms/package.json b/node_modules/https-proxy-agent/node_modules/ms/package.json new file mode 100644 index 0000000..eea666e --- /dev/null +++ b/node_modules/https-proxy-agent/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.1.2", + "description": "Tiny millisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.12.1", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1" + } +} diff --git a/node_modules/https-proxy-agent/node_modules/ms/readme.md b/node_modules/https-proxy-agent/node_modules/ms/readme.md new file mode 100644 index 0000000..9a1996b --- /dev/null +++ b/node_modules/https-proxy-agent/node_modules/ms/readme.md @@ -0,0 +1,60 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/https-proxy-agent/package.json b/node_modules/https-proxy-agent/package.json new file mode 100644 index 0000000..7872bdf --- /dev/null +++ b/node_modules/https-proxy-agent/package.json @@ -0,0 +1,56 @@ +{ + "name": "https-proxy-agent", + "version": "5.0.0", + "description": "An HTTP(s) proxy `http.Agent` implementation for HTTPS", + "main": "dist/index", + "types": "dist/index", + "files": [ + "dist" + ], + "scripts": { + "prebuild": "rimraf dist", + "build": "tsc", + "test": "mocha --reporter spec", + "test-lint": "eslint src --ext .js,.ts", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/node-https-proxy-agent.git" + }, + "keywords": [ + "https", + "proxy", + "endpoint", + "agent" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/node-https-proxy-agent/issues" + }, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "devDependencies": { + "@types/debug": "4", + "@types/node": "^12.12.11", + "@typescript-eslint/eslint-plugin": "1.6.0", + "@typescript-eslint/parser": "1.1.0", + "eslint": "5.16.0", + "eslint-config-airbnb": "17.1.0", + "eslint-config-prettier": "4.1.0", + "eslint-import-resolver-typescript": "1.1.1", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-jsx-a11y": "6.2.1", + "eslint-plugin-react": "7.12.4", + "mocha": "^6.2.2", + "proxy": "1", + "rimraf": "^3.0.0", + "typescript": "^3.5.3" + }, + "engines": { + "node": ">= 6" + } +} diff --git a/node_modules/iconv-lite/Changelog.md b/node_modules/iconv-lite/Changelog.md new file mode 100644 index 0000000..f252313 --- /dev/null +++ b/node_modules/iconv-lite/Changelog.md @@ -0,0 +1,162 @@ +# 0.4.24 / 2018-08-22 + + * Added MIK encoding (#196, by @Ivan-Kalatchev) + + +# 0.4.23 / 2018-05-07 + + * Fix deprecation warning in Node v10 due to the last usage of `new Buffer` (#185, by @felixbuenemann) + * Switched from NodeBuffer to Buffer in typings (#155 by @felixfbecker, #186 by @larssn) + + +# 0.4.22 / 2018-05-05 + + * Use older semver style for dependencies to be compatible with Node version 0.10 (#182, by @dougwilson) + * Fix tests to accomodate fixes in Node v10 (#182, by @dougwilson) + + +# 0.4.21 / 2018-04-06 + + * Fix encoding canonicalization (#156) + * Fix the paths in the "browser" field in package.json (#174 by @LMLB) + * Removed "contributors" section in package.json - see Git history instead. + + +# 0.4.20 / 2018-04-06 + + * Updated `new Buffer()` usages with recommended replacements as it's being deprecated in Node v10 (#176, #178 by @ChALkeR) + + +# 0.4.19 / 2017-09-09 + + * Fixed iso8859-1 codec regression in handling untranslatable characters (#162, caused by #147) + * Re-generated windows1255 codec, because it was updated in iconv project + * Fixed grammar in error message when iconv-lite is loaded with encoding other than utf8 + + +# 0.4.18 / 2017-06-13 + + * Fixed CESU-8 regression in Node v8. + + +# 0.4.17 / 2017-04-22 + + * Updated typescript definition file to support Angular 2 AoT mode (#153 by @larssn) + + +# 0.4.16 / 2017-04-22 + + * Added support for React Native (#150) + * Changed iso8859-1 encoding to usine internal 'binary' encoding, as it's the same thing (#147 by @mscdex) + * Fixed typo in Readme (#138 by @jiangzhuo) + * Fixed build for Node v6.10+ by making correct version comparison + * Added a warning if iconv-lite is loaded not as utf-8 (see #142) + + +# 0.4.15 / 2016-11-21 + + * Fixed typescript type definition (#137) + + +# 0.4.14 / 2016-11-20 + + * Preparation for v1.0 + * Added Node v6 and latest Node versions to Travis CI test rig + * Deprecated Node v0.8 support + * Typescript typings (@larssn) + * Fix encoding of Euro character in GB 18030 (inspired by @lygstate) + * Add ms prefix to dbcs windows encodings (@rokoroku) + + +# 0.4.13 / 2015-10-01 + + * Fix silly mistake in deprecation notice. + + +# 0.4.12 / 2015-09-26 + + * Node v4 support: + * Added CESU-8 decoding (#106) + * Added deprecation notice for `extendNodeEncodings` + * Added Travis tests for Node v4 and io.js latest (#105 by @Mithgol) + + +# 0.4.11 / 2015-07-03 + + * Added CESU-8 encoding. + + +# 0.4.10 / 2015-05-26 + + * Changed UTF-16 endianness heuristic to take into account any ASCII chars, not + just spaces. This should minimize the importance of "default" endianness. + + +# 0.4.9 / 2015-05-24 + + * Streamlined BOM handling: strip BOM by default, add BOM when encoding if + addBOM: true. Added docs to Readme. + * UTF16 now uses UTF16-LE by default. + * Fixed minor issue with big5 encoding. + * Added io.js testing on Travis; updated node-iconv version to test against. + Now we just skip testing SBCS encodings that node-iconv doesn't support. + * (internal refactoring) Updated codec interface to use classes. + * Use strict mode in all files. + + +# 0.4.8 / 2015-04-14 + + * added alias UNICODE-1-1-UTF-7 for UTF-7 encoding (#94) + + +# 0.4.7 / 2015-02-05 + + * stop official support of Node.js v0.8. Should still work, but no guarantees. + reason: Packages needed for testing are hard to get on Travis CI. + * work in environment where Object.prototype is monkey patched with enumerable + props (#89). + + +# 0.4.6 / 2015-01-12 + + * fix rare aliases of single-byte encodings (thanks @mscdex) + * double the timeout for dbcs tests to make them less flaky on travis + + +# 0.4.5 / 2014-11-20 + + * fix windows-31j and x-sjis encoding support (@nleush) + * minor fix: undefined variable reference when internal error happens + + +# 0.4.4 / 2014-07-16 + + * added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3) + * fixed streaming base64 encoding + + +# 0.4.3 / 2014-06-14 + + * added encodings UTF-16BE and UTF-16 with BOM + + +# 0.4.2 / 2014-06-12 + + * don't throw exception if `extendNodeEncodings()` is called more than once + + +# 0.4.1 / 2014-06-11 + + * codepage 808 added + + +# 0.4.0 / 2014-06-10 + + * code is rewritten from scratch + * all widespread encodings are supported + * streaming interface added + * browserify compatibility added + * (optional) extend core primitive encodings to make usage even simpler + * moved from vows to mocha as the testing framework + + diff --git a/node_modules/iconv-lite/LICENSE b/node_modules/iconv-lite/LICENSE new file mode 100644 index 0000000..d518d83 --- /dev/null +++ b/node_modules/iconv-lite/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011 Alexander Shtuchkin + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +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/iconv-lite/README.md b/node_modules/iconv-lite/README.md new file mode 100644 index 0000000..c981c37 --- /dev/null +++ b/node_modules/iconv-lite/README.md @@ -0,0 +1,156 @@ +## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite) + + * Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io). + * Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), + [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. + * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). + * Intuitive encode/decode API + * Streaming support for Node v0.10+ + * [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings. + * In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included). + * Typescript [type definition file](https://github.com/ashtuchkin/iconv-lite/blob/master/lib/index.d.ts) included. + * React Native is supported (need to explicitly `npm install` two more modules: `buffer` and `stream`). + * License: MIT. + +[![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true&downloadRank=true)](https://npmjs.org/packages/iconv-lite/) + +## Usage +### Basic API +```javascript +var iconv = require('iconv-lite'); + +// Convert from an encoded buffer to js string. +str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); + +// Convert from js string to an encoded buffer. +buf = iconv.encode("Sample input string", 'win1251'); + +// Check if encoding is supported +iconv.encodingExists("us-ascii") +``` + +### Streaming API (Node v0.10+) +```javascript + +// Decode stream (from binary stream to js strings) +http.createServer(function(req, res) { + var converterStream = iconv.decodeStream('win1251'); + req.pipe(converterStream); + + converterStream.on('data', function(str) { + console.log(str); // Do something with decoded strings, chunk-by-chunk. + }); +}); + +// Convert encoding streaming example +fs.createReadStream('file-in-win1251.txt') + .pipe(iconv.decodeStream('win1251')) + .pipe(iconv.encodeStream('ucs2')) + .pipe(fs.createWriteStream('file-in-ucs2.txt')); + +// Sugar: all encode/decode streams have .collect(cb) method to accumulate data. +http.createServer(function(req, res) { + req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { + assert(typeof body == 'string'); + console.log(body); // full request body string + }); +}); +``` + +### [Deprecated] Extend Node.js own encodings +> NOTE: This doesn't work on latest Node versions. See [details](https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility). + +```javascript +// After this call all Node basic primitives will understand iconv-lite encodings. +iconv.extendNodeEncodings(); + +// Examples: +buf = new Buffer(str, 'win1251'); +buf.write(str, 'gbk'); +str = buf.toString('latin1'); +assert(Buffer.isEncoding('iso-8859-15')); +Buffer.byteLength(str, 'us-ascii'); + +http.createServer(function(req, res) { + req.setEncoding('big5'); + req.collect(function(err, body) { + console.log(body); + }); +}); + +fs.createReadStream("file.txt", "shift_jis"); + +// External modules are also supported (if they use Node primitives, which they probably do). +request = require('request'); +request({ + url: "http://github.com/", + encoding: "cp932" +}); + +// To remove extensions +iconv.undoExtendNodeEncodings(); +``` + +## Supported encodings + + * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. + * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap. + * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, + IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. + Aliases like 'latin1', 'us-ascii' also supported. + * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP. + +See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). + +Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! + +Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! + + +## Encoding/decoding speed + +Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). +Note: your results may vary, so please always check on your hardware. + + operation iconv@2.1.4 iconv-lite@0.4.7 + ---------------------------------------------------------- + encode('win1251') ~96 Mb/s ~320 Mb/s + decode('win1251') ~95 Mb/s ~246 Mb/s + +## BOM handling + + * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options + (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). + A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. + * If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module. + * Encoding: No BOM added, unless overridden by `addBOM: true` option. + +## UTF-16 Encodings + +This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be +smart about endianness in the following ways: + * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be + overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. + * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. + +## Other notes + +When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). +Untranslatable characters are set to � or ?. No transliteration is currently supported. +Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77). + +## Testing + +```bash +$ git clone git@github.com:ashtuchkin/iconv-lite.git +$ cd iconv-lite +$ npm install +$ npm test + +$ # To view performance: +$ node test/performance.js + +$ # To view test coverage: +$ npm run coverage +$ open coverage/lcov-report/index.html +``` diff --git a/node_modules/iconv-lite/encodings/dbcs-codec.js b/node_modules/iconv-lite/encodings/dbcs-codec.js new file mode 100644 index 0000000..1fe3e16 --- /dev/null +++ b/node_modules/iconv-lite/encodings/dbcs-codec.js @@ -0,0 +1,555 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. + +exports._dbcs = DBCSCodec; + +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; + +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; + + +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); + + // Load tables. + var mappingTable = codecOptions.table(); + + + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; + + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); + + this.defaultCharUnicode = iconv.defaultCharUnicode; + + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); + + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + } + + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); + + + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } +} + +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; + +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); + + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; + + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} + + +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); + + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; + + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} + +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} + +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} + +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } + + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } + } + + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} + +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; + + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +} + + + +// == Encoder ================================================================== + +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; +} + +DBCSEncoder.prototype.write = function(str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; + + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } + + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } + + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; + + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; + + } else if (resCode == undefined) { // Current character is not part of the sequence. + + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. + + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } + + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } + + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } + + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} + +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. + + var newBuf = Buffer.alloc(10), j = 0; + + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined; + } + + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); +} + +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; + + +// == Decoder ================================================================== + +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = Buffer.alloc(0); + + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} + +DBCSDecoder.prototype.write = function(buf) { + var newBuf = Buffer.alloc(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; + + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) { + // Normal character, just use it. + } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); + } + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 + uCode % 0x400; + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } + + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} + +DBCSDecoder.prototype.end = function() { + var ret = ''; + + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); + + // Parse remaining as usual. + this.prevBuf = Buffer.alloc(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); + } + + this.nodeIdx = 0; + return ret; +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; + + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; + } + return l; +} + diff --git a/node_modules/iconv-lite/encodings/dbcs-data.js b/node_modules/iconv-lite/encodings/dbcs-data.js new file mode 100644 index 0000000..4b61914 --- /dev/null +++ b/node_modules/iconv-lite/encodings/dbcs-data.js @@ -0,0 +1,176 @@ +"use strict"; + +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. + +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + + 'shiftjis': { + type: '_dbcs', + table: function() { return require('./tables/shiftjis.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'ms31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + 'ms932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', + + 'eucjp': { + type: '_dbcs', + table: function() { return require('./tables/eucjp.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, + + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + + + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json') }, + }, + + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', + + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + 'gb18030': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + gb18030: function() { return require('./tables/gb18030-ranges.json') }, + encodeSkipVals: [0x80], + encodeAdd: {'€': 0xA2E3}, + }, + + 'chinese': 'gb18030', + + + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + 'ms949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return require('./tables/cp949.json') }, + }, + + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', + + + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json') }, + }, + + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) }, + encodeSkipVals: [0xa2cc], + }, + + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', +}; diff --git a/node_modules/iconv-lite/encodings/index.js b/node_modules/iconv-lite/encodings/index.js new file mode 100644 index 0000000..e304003 --- /dev/null +++ b/node_modules/iconv-lite/encodings/index.js @@ -0,0 +1,22 @@ +"use strict"; + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + require("./internal"), + require("./utf16"), + require("./utf7"), + require("./sbcs-codec"), + require("./sbcs-data"), + require("./sbcs-data-generated"), + require("./dbcs-codec"), + require("./dbcs-data"), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; +} diff --git a/node_modules/iconv-lite/encodings/internal.js b/node_modules/iconv-lite/encodings/internal.js new file mode 100644 index 0000000..05ce38b --- /dev/null +++ b/node_modules/iconv-lite/encodings/internal.js @@ -0,0 +1,188 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Export Node.js internal encodings. + +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", + + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", + + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, + + // Codec. + _internal: InternalCodec, +}; + +//------------------------------------------------------------------------------ + +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; + + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } + } +} + +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; + +//------------------------------------------------------------------------------ + +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = require('string_decoder').StringDecoder; + +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; + + +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); +} + +InternalDecoder.prototype = StringDecoder.prototype; + + +//------------------------------------------------------------------------------ +// Encoder is mostly trivial + +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} + +InternalEncoder.prototype.write = function(str) { + return Buffer.from(str, this.enc); +} + +InternalEncoder.prototype.end = function() { +} + + +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. + +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} + +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + + return Buffer.from(str, "base64"); +} + +InternalEncoderBase64.prototype.end = function() { + return Buffer.from(this.prevStr, "base64"); +} + + +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. + +function InternalEncoderCesu8(options, codec) { +} + +InternalEncoderCesu8.prototype.write = function(str) { + var buf = Buffer.alloc(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + } + return buf.slice(0, bufIdx); +} + +InternalEncoderCesu8.prototype.end = function() { +} + +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ + +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} + +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; + } + + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; + } + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); + } + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; + } + } + } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; +} + +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; +} diff --git a/node_modules/iconv-lite/encodings/sbcs-codec.js b/node_modules/iconv-lite/encodings/sbcs-codec.js new file mode 100644 index 0000000..abac5ff --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-codec.js @@ -0,0 +1,72 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). + +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; + } + + this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + + this.encodeBuf = encodeBuf; +} + +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; + + +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} + +SBCSEncoder.prototype.write = function(str) { + var buf = Buffer.alloc(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; +} + +SBCSEncoder.prototype.end = function() { +} + + +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} + +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = Buffer.alloc(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; + } + return newBuf.toString('ucs2'); +} + +SBCSDecoder.prototype.end = function() { +} diff --git a/node_modules/iconv-lite/encodings/sbcs-data-generated.js b/node_modules/iconv-lite/encodings/sbcs-data-generated.js new file mode 100644 index 0000000..9b48236 --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-data-generated.js @@ -0,0 +1,451 @@ +"use strict"; + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } +} \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/sbcs-data.js b/node_modules/iconv-lite/encodings/sbcs-data.js new file mode 100644 index 0000000..fdb81a3 --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-data.js @@ -0,0 +1,174 @@ +"use strict"; + +// Manually added data to be used by sbcs codec in addition to generated one. + +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, + + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, + + "mik": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", + + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", + + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", + + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", + + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", + + "cp819": "iso88591", + "ibm819": "iso88591", + + "cyrillic": "iso88595", + + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", + + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", + + "hebrew": "iso88598", + "hebrew8": "iso88598", + + "turkish": "iso88599", + "turkish8": "iso88599", + + "thai": "iso885911", + "thai8": "iso885911", + + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", + + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", + + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", + + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", + + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + + "strk10482002": "rk1048", + + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + + "gb198880": "iso646cn", + "cn": "iso646cn", + + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", +}; + diff --git a/node_modules/iconv-lite/encodings/tables/big5-added.json b/node_modules/iconv-lite/encodings/tables/big5-added.json new file mode 100644 index 0000000..3c3d3c2 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/big5-added.json @@ -0,0 +1,122 @@ +[ +["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"], +["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"], +["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"], +["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"], +["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"], +["8940","𪎩𡅅"], +["8943","攊"], +["8946","丽滝鵎釟"], +["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"], +["89a1","琑糼緍楆竉刧"], +["89ab","醌碸酞肼"], +["89b0","贋胶𠧧"], +["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"], +["89c1","溚舾甙"], +["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"], +["8a40","𧶄唥"], +["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"], +["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], +["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"], +["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"], +["8aac","䠋𠆩㿺塳𢶍"], +["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], +["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"], +["8ac9","𪘁𠸉𢫏𢳉"], +["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], +["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"], +["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"], +["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"], +["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"], +["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"], +["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"], +["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"], +["8ca1","𣏹椙橃𣱣泿"], +["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"], +["8cc9","顨杫䉶圽"], +["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], +["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"], +["8d40","𠮟"], +["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"], +["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"], +["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], +["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"], +["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], +["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"], +["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"], +["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"], +["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], +["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"], +["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"], +["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], +["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"], +["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], +["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], +["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"], +["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"], +["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"], +["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"], +["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], +["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"], +["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"], +["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"], +["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"], +["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"], +["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"], +["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"], +["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"], +["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], +["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"], +["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"], +["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"], +["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"], +["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"], +["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"], +["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"], +["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"], +["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"], +["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"], +["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"], +["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"], +["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"], +["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"], +["9fae","酙隁酜"], +["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"], +["9fc1","𤤙盖鮝个𠳔莾衂"], +["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"], +["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], +["9fe7","毺蠘罸"], +["9feb","嘠𪙊蹷齓"], +["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"], +["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"], +["a055","𡠻𦸅"], +["a058","詾𢔛"], +["a05b","惽癧髗鵄鍮鮏蟵"], +["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"], +["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"], +["a0a1","嵗𨯂迚𨸹"], +["a0a6","僙𡵆礆匲阸𠼻䁥"], +["a0ae","矾"], +["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], +["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"], +["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"], +["a3c0","␀",31,"␡"], +["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23], +["c740","す",58,"ァアィイ"], +["c7a1","ゥ",81,"А",5,"ЁЖ",4], +["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"], +["c8a1","龰冈龱𧘇"], +["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"], +["c8f5","ʃɐɛɔɵœøŋʊɪ"], +["f9fe","■"], +["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"], +["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"], +["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"], +["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"], +["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"], +["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"], +["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], +["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"], +["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"], +["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp936.json b/node_modules/iconv-lite/encodings/tables/cp936.json new file mode 100644 index 0000000..49ddb9a --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp936.json @@ -0,0 +1,264 @@ +[ +["0","\u0000",127,"€"], +["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], +["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"], +["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], +["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], +["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], +["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5], +["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"], +["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"], +["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"], +["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"], +["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"], +["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], +["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4], +["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6], +["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"], +["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7], +["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"], +["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"], +["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"], +["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5], +["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], +["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6], +["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"], +["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4], +["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4], +["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], +["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"], +["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6], +["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"], +["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], +["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"], +["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6], +["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"], +["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"], +["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"], +["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"], +["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"], +["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"], +["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8], +["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"], +["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"], +["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"], +["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"], +["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5], +["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], +["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"], +["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], +["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"], +["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5], +["9980","檧檨檪檭",114,"欥欦欨",6], +["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], +["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"], +["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"], +["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"], +["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], +["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5], +["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"], +["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"], +["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6], +["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], +["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"], +["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4], +["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], +["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"], +["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"], +["a2a1","ⅰ",9], +["a2b1","⒈",19,"⑴",19,"①",9], +["a2e5","㈠",9], +["a2f1","Ⅰ",11], +["a3a1","!"#¥%",88," ̄"], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"], +["a6ee","︻︼︷︸︱"], +["a6f4","︳︴"], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6], +["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"], +["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"], +["a8bd","ńň"], +["a8c0","ɡ"], +["a8c5","ㄅ",36], +["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"], +["a959","℡㈱"], +["a95c","‐"], +["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8], +["a980","﹢",4,"﹨﹩﹪﹫"], +["a996","〇"], +["a9a4","─",75], +["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8], +["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"], +["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4], +["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4], +["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11], +["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"], +["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12], +["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"], +["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"], +["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"], +["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], +["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"], +["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"], +["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"], +["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"], +["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], +["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], +["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"], +["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"], +["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"], +["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9], +["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"], +["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], +["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"], +["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"], +["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"], +["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16], +["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"], +["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"], +["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"], +["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"], +["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"], +["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"], +["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"], +["bb40","籃",9,"籎",36,"籵",5,"籾",9], +["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"], +["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5], +["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"], +["bd40","紷",54,"絯",7], +["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"], +["be40","継",12,"綧",6,"綯",42], +["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"], +["bf40","緻",62], +["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"], +["c040","繞",35,"纃",23,"纜纝纞"], +["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"], +["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"], +["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"], +["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"], +["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"], +["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"], +["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"], +["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"], +["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"], +["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"], +["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"], +["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"], +["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"], +["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"], +["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"], +["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"], +["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"], +["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"], +["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"], +["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10], +["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"], +["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"], +["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"], +["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], +["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"], +["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"], +["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"], +["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"], +["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"], +["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9], +["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"], +["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], +["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"], +["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5], +["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"], +["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], +["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"], +["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6], +["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"], +["d440","訞",31,"訿",8,"詉",21], +["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"], +["d540","誁",7,"誋",7,"誔",46], +["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"], +["d640","諤",34,"謈",27], +["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"], +["d740","譆",31,"譧",4,"譭",25], +["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"], +["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], +["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"], +["d940","貮",62], +["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], +["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"], +["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"], +["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], +["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"], +["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7], +["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"], +["dd40","軥",62], +["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"], +["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"], +["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"], +["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"], +["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"], +["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"], +["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"], +["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], +["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"], +["e240","釦",62], +["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"], +["e340","鉆",45,"鉵",16], +["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], +["e440","銨",5,"銯",24,"鋉",31], +["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"], +["e540","錊",51,"錿",10], +["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"], +["e640","鍬",34,"鎐",27], +["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"], +["e740","鏎",7,"鏗",54], +["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"], +["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"], +["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"], +["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42], +["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"], +["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"], +["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"], +["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"], +["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"], +["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7], +["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"], +["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], +["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"], +["ee40","頏",62], +["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], +["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4], +["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], +["f040","餈",4,"餎餏餑",28,"餯",26], +["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"], +["f140","馌馎馚",10,"馦馧馩",47], +["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"], +["f240","駺",62], +["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"], +["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"], +["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"], +["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5], +["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"], +["f540","魼",62], +["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"], +["f640","鯜",62], +["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], +["f740","鰼",62], +["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"], +["f840","鳣",62], +["f880","鴢",32], +["f940","鵃",62], +["f980","鶂",32], +["fa40","鶣",62], +["fa80","鷢",32], +["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"], +["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], +["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], +["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], +["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38], +["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"], +["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp949.json b/node_modules/iconv-lite/encodings/tables/cp949.json new file mode 100644 index 0000000..2022a00 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp949.json @@ -0,0 +1,273 @@ +[ +["0","\u0000",127], +["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], +["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], +["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], +["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], +["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], +["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], +["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], +["8361","긝",18,"긲긳긵긶긹긻긼"], +["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], +["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], +["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], +["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], +["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], +["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], +["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], +["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], +["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], +["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], +["8741","놞",9,"놩",15], +["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], +["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], +["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], +["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], +["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], +["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], +["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], +["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], +["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], +["8a61","둧",4,"둭",18,"뒁뒂"], +["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], +["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], +["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], +["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], +["8c41","똀",15,"똒똓똕똖똗똙",4], +["8c61","똞",6,"똦",5,"똭",6,"똵",5], +["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], +["8d41","뛃",16,"뛕",8], +["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], +["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], +["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], +["8e61","럂",4,"럈럊",19], +["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], +["8f41","뢅",7,"뢎",17], +["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], +["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], +["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], +["9061","륾",5,"릆릈릋릌릏",15], +["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], +["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], +["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], +["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], +["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], +["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], +["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], +["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], +["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], +["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], +["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], +["9461","봞",5,"봥",6,"봭",12], +["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], +["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], +["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], +["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], +["9641","뺸",23,"뻒뻓"], +["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], +["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], +["9741","뾃",16,"뾕",8], +["9761","뾞",17,"뾱",7], +["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], +["9841","쁀",16,"쁒",5,"쁙쁚쁛"], +["9861","쁝쁞쁟쁡",6,"쁪",15], +["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], +["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], +["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], +["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], +["9a41","숤숥숦숧숪숬숮숰숳숵",16], +["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], +["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], +["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], +["9b61","쌳",17,"썆",7], +["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], +["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], +["9c61","쏿",8,"쐉",6,"쐑",9], +["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], +["9d41","쒪",13,"쒹쒺쒻쒽",8], +["9d61","쓆",25], +["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], +["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], +["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], +["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], +["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], +["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], +["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], +["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], +["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], +["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], +["a141","좥좦좧좩",18,"좾좿죀죁"], +["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], +["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], +["a241","줐줒",5,"줙",18], +["a261","줭",6,"줵",18], +["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], +["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], +["a361","즑",6,"즚즜즞",16], +["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], +["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], +["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], +["a481","쨦쨧쨨쨪",28,"ㄱ",93], +["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], +["a561","쩫",17,"쩾",5,"쪅쪆"], +["a581","쪇",16,"쪙",14,"ⅰ",9], +["a5b0","Ⅰ",9], +["a5c1","Α",16,"Σ",6], +["a5e1","α",16,"σ",6], +["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], +["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], +["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], +["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], +["a761","쬪",22,"쭂쭃쭄"], +["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], +["a841","쭭",10,"쭺",14], +["a861","쮉",18,"쮝",6], +["a881","쮤",19,"쮹",11,"ÆЪĦ"], +["a8a6","IJ"], +["a8a8","ĿŁØŒºÞŦŊ"], +["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], +["a941","쯅",14,"쯕",10], +["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], +["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], +["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], +["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], +["aa81","챳챴챶",29,"ぁ",82], +["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], +["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], +["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], +["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], +["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], +["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], +["acd1","а",5,"ёж",25], +["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], +["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], +["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], +["ae41","췆",5,"췍췎췏췑",16], +["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], +["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], +["af41","츬츭츮츯츲츴츶",19], +["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], +["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], +["b041","캚",5,"캢캦",5,"캮",12], +["b061","캻",5,"컂",19], +["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], +["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], +["b161","켥",6,"켮켲",5,"켹",11], +["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], +["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], +["b261","쾎",18,"쾢",5,"쾩"], +["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], +["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], +["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], +["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], +["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], +["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], +["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], +["b541","킕",14,"킦킧킩킪킫킭",5], +["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], +["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], +["b641","턅",7,"턎",17], +["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], +["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], +["b741","텮",13,"텽",6,"톅톆톇톉톊"], +["b761","톋",20,"톢톣톥톦톧"], +["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], +["b841","퇐",7,"퇙",17], +["b861","퇫",8,"퇵퇶퇷퇹",13], +["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], +["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], +["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], +["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], +["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], +["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], +["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], +["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], +["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], +["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], +["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], +["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], +["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], +["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], +["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], +["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], +["be41","퐸",7,"푁푂푃푅",14], +["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], +["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], +["bf41","풞",10,"풪",14], +["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], +["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], +["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], +["c061","픞",25], +["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], +["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], +["c161","햌햍햎햏햑",19,"햦햧"], +["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], +["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], +["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], +["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], +["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], +["c361","홢",4,"홨홪",5,"홲홳홵",11], +["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], +["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], +["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], +["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], +["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], +["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], +["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], +["c641","힍힎힏힑",6,"힚힜힞",5], +["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], +["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], +["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], +["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], +["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], +["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], +["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], +["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], +["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], +["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], +["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], +["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], +["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], +["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], +["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], +["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], +["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], +["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], +["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], +["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], +["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], +["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], +["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], +["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], +["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], +["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], +["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], +["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], +["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], +["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], +["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], +["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], +["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], +["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], +["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], +["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], +["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], +["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], +["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], +["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], +["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], +["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], +["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], +["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], +["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], +["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], +["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], +["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], +["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], +["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], +["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], +["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], +["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], +["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], +["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp950.json b/node_modules/iconv-lite/encodings/tables/cp950.json new file mode 100644 index 0000000..d8bc871 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp950.json @@ -0,0 +1,177 @@ +[ +["0","\u0000",127], +["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"], +["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"], +["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"], +["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21], +["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10], +["a3a1","ㄐ",25,"˙ˉˊˇˋ"], +["a3e1","€"], +["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"], +["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"], +["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"], +["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"], +["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"], +["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"], +["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"], +["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"], +["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"], +["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"], +["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], +["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"], +["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"], +["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"], +["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"], +["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"], +["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"], +["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"], +["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"], +["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"], +["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"], +["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"], +["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"], +["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"], +["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"], +["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"], +["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"], +["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"], +["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"], +["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"], +["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"], +["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"], +["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"], +["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"], +["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"], +["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"], +["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"], +["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"], +["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"], +["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"], +["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"], +["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], +["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"], +["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"], +["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"], +["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], +["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"], +["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], +["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"], +["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"], +["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"], +["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"], +["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], +["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], +["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"], +["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"], +["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"], +["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"], +["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"], +["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"], +["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"], +["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"], +["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"], +["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"], +["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"], +["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"], +["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"], +["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"], +["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], +["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"], +["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"], +["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"], +["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"], +["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"], +["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"], +["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], +["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"], +["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], +["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"], +["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"], +["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"], +["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"], +["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"], +["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"], +["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"], +["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"], +["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"], +["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"], +["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"], +["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"], +["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"], +["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"], +["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"], +["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"], +["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"], +["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"], +["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"], +["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"], +["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], +["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"], +["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"], +["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"], +["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"], +["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"], +["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"], +["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"], +["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"], +["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"], +["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"], +["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"], +["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"], +["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"], +["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], +["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], +["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"], +["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"], +["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"], +["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"], +["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"], +["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], +["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"], +["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], +["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], +["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"], +["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"], +["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"], +["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"], +["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"], +["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"], +["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], +["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"], +["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"], +["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"], +["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"], +["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"], +["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"], +["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"], +["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], +["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"], +["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"], +["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"], +["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], +["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"], +["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"], +["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"], +["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"], +["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"], +["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"], +["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], +["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"], +["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"], +["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"], +["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"], +["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"], +["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"], +["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"], +["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"], +["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"], +["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"], +["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"], +["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], +["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"], +["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"], +["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"], +["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"], +["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"], +["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"] +] diff --git a/node_modules/iconv-lite/encodings/tables/eucjp.json b/node_modules/iconv-lite/encodings/tables/eucjp.json new file mode 100644 index 0000000..4fa61ca --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/eucjp.json @@ -0,0 +1,182 @@ +[ +["0","\u0000",127], +["8ea1","。",62], +["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"], +["a2a1","◆□■△▲▽▼※〒→←↑↓〓"], +["a2ba","∈∋⊆⊇⊂⊃∪∩"], +["a2ca","∧∨¬⇒⇔∀∃"], +["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["a2f2","ʼn♯♭♪†‡¶"], +["a2fe","◯"], +["a3b0","0",9], +["a3c1","A",25], +["a3e1","a",25], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["ada1","①",19,"Ⅰ",9], +["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"], +["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"], +["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"], +["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"], +["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"], +["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"], +["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"], +["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"], +["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"], +["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"], +["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"], +["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"], +["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"], +["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"], +["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"], +["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"], +["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"], +["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"], +["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"], +["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"], +["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"], +["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"], +["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], +["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"], +["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"], +["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"], +["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"], +["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"], +["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"], +["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"], +["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"], +["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"], +["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], +["f4a1","堯槇遙瑤凜熙"], +["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"], +["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"], +["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["fcf1","ⅰ",9,"¬¦'""], +["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"], +["8fa2c2","¡¦¿"], +["8fa2eb","ºª©®™¤№"], +["8fa6e1","ΆΈΉΊΪ"], +["8fa6e7","Ό"], +["8fa6e9","ΎΫ"], +["8fa6ec","Ώ"], +["8fa6f1","άέήίϊΐόςύϋΰώ"], +["8fa7c2","Ђ",10,"ЎЏ"], +["8fa7f2","ђ",10,"ўџ"], +["8fa9a1","ÆĐ"], +["8fa9a4","Ħ"], +["8fa9a6","IJ"], +["8fa9a8","ŁĿ"], +["8fa9ab","ŊØŒ"], +["8fa9af","ŦÞ"], +["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], +["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], +["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"], +["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"], +["8fabbd","ġĥíìïîǐ"], +["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], +["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"], +["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"], +["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"], +["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], +["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"], +["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"], +["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"], +["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"], +["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"], +["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], +["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], +["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"], +["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"], +["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"], +["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"], +["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"], +["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"], +["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"], +["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"], +["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"], +["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"], +["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"], +["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"], +["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"], +["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], +["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"], +["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"], +["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"], +["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], +["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"], +["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"], +["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"], +["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"], +["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], +["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5], +["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"], +["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"], +["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"], +["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"], +["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"], +["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"], +["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], +["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"], +["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], +["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"], +["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"], +["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"], +["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"], +["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"], +["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], +["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], +["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"], +["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"], +["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], +["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"], +["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"], +["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"], +["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], +["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"], +["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], +["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], +["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"] +] diff --git a/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json b/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json new file mode 100644 index 0000000..85c6934 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json @@ -0,0 +1 @@ +{"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]} \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/tables/gbk-added.json b/node_modules/iconv-lite/encodings/tables/gbk-added.json new file mode 100644 index 0000000..8abfa9f --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/gbk-added.json @@ -0,0 +1,55 @@ +[ +["a140","",62], +["a180","",32], +["a240","",62], +["a280","",32], +["a2ab","",5], +["a2e3","€"], +["a2ef",""], +["a2fd",""], +["a340","",62], +["a380","",31," "], +["a440","",62], +["a480","",32], +["a4f4","",10], +["a540","",62], +["a580","",32], +["a5f7","",7], +["a640","",62], +["a680","",32], +["a6b9","",7], +["a6d9","",6], +["a6ec",""], +["a6f3",""], +["a6f6","",8], +["a740","",62], +["a780","",32], +["a7c2","",14], +["a7f2","",12], +["a896","",10], +["a8bc",""], +["a8bf","ǹ"], +["a8c1",""], +["a8ea","",20], +["a958",""], +["a95b",""], +["a95d",""], +["a989","〾⿰",11], +["a997","",12], +["a9f0","",14], +["aaa1","",93], +["aba1","",93], +["aca1","",93], +["ada1","",93], +["aea1","",93], +["afa1","",93], +["d7fa","",4], +["f8a1","",93], +["f9a1","",93], +["faa1","",93], +["fba1","",93], +["fca1","",93], +["fda1","",93], +["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"], +["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93] +] diff --git a/node_modules/iconv-lite/encodings/tables/shiftjis.json b/node_modules/iconv-lite/encodings/tables/shiftjis.json new file mode 100644 index 0000000..5a3a43c --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/shiftjis.json @@ -0,0 +1,125 @@ +[ +["0","\u0000",128], +["a1","。",62], +["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"], +["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"], +["81b8","∈∋⊆⊇⊂⊃∪∩"], +["81c8","∧∨¬⇒⇔∀∃"], +["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["81f0","ʼn♯♭♪†‡¶"], +["81fc","◯"], +["824f","0",9], +["8260","A",25], +["8281","a",25], +["829f","ぁ",82], +["8340","ァ",62], +["8380","ム",22], +["839f","Α",16,"Σ",6], +["83bf","α",16,"σ",6], +["8440","А",5,"ЁЖ",25], +["8470","а",5,"ёж",7], +["8480","о",17], +["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["8740","①",19,"Ⅰ",9], +["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["877e","㍻"], +["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"], +["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"], +["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"], +["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"], +["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"], +["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"], +["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"], +["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"], +["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"], +["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"], +["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"], +["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"], +["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"], +["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"], +["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"], +["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], +["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"], +["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"], +["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"], +["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"], +["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"], +["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], +["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"], +["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"], +["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"], +["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], +["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"], +["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], +["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"], +["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], +["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"], +["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"], +["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"], +["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"], +["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"], +["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"], +["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["eeef","ⅰ",9,"¬¦'""], +["f040","",62], +["f080","",124], +["f140","",62], +["f180","",124], +["f240","",62], +["f280","",124], +["f340","",62], +["f380","",124], +["f440","",62], +["f480","",124], +["f540","",62], +["f580","",124], +["f640","",62], +["f680","",124], +["f740","",62], +["f780","",124], +["f840","",62], +["f880","",124], +["f940",""], +["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"], +["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], +["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"], +["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"], +["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"] +] diff --git a/node_modules/iconv-lite/encodings/utf16.js b/node_modules/iconv-lite/encodings/utf16.js new file mode 100644 index 0000000..54765ae --- /dev/null +++ b/node_modules/iconv-lite/encodings/utf16.js @@ -0,0 +1,177 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { +} + +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf16BEEncoder() { +} + +Utf16BEEncoder.prototype.write = function(str) { + var buf = Buffer.from(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; + } + return buf; +} + +Utf16BEEncoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf16BEDecoder() { + this.overflowByte = -1; +} + +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; + + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, j = 0; + + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; + } + + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); +} + +Utf16BEDecoder.prototype.end = function() { +} + + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} + +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; + + +// -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); +} + +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} + +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} + + +// -- Decoding + +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; + + this.options = options || {}; + this.iconv = codec.iconv; +} + +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + + if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + this.initialBytes.length = this.initialBytesLen = 0; + } + + return this.decoder.write(buf); +} + +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var res = this.decoder.write(buf), + trail = this.decoder.end(); + + return trail ? (res + trail) : res; + } + return this.decoder.end(); +} + +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; + + if (buf.length >= 2) { + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM + enc = 'utf-16be'; + else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM + enc = 'utf-16le'; + else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions + _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + + for (var i = 0; i < _len; i += 2) { + if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; + if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; + } + + if (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; + } + } + + return enc; +} + + diff --git a/node_modules/iconv-lite/encodings/utf7.js b/node_modules/iconv-lite/encodings/utf7.js new file mode 100644 index 0000000..b7631c2 --- /dev/null +++ b/node_modules/iconv-lite/encodings/utf7.js @@ -0,0 +1,290 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; + + +// -- Encoding + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} + +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return Buffer.from(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} + +Utf7Encoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + + +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = Buffer.alloc(6); + this.base64AccumIdx = 0; +} + +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } + } + } + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); +} + +Utf7IMAPEncoder.prototype.end = function() { + var buf = Buffer.alloc(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; + } + + return buf.slice(0, bufIdx); +} + + +// -- Decoding + +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; + +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + diff --git a/node_modules/iconv-lite/lib/bom-handling.js b/node_modules/iconv-lite/lib/bom-handling.js new file mode 100644 index 0000000..1050872 --- /dev/null +++ b/node_modules/iconv-lite/lib/bom-handling.js @@ -0,0 +1,52 @@ +"use strict"; + +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; +} + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; + } + + return this.encoder.write(str); +} + +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); +} + + +//------------------------------------------------------------------------------ + +exports.StripBOM = StripBOMWrapper; +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; +} + +StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) + return res; + + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') + this.options.stripBOM(); + } + + this.pass = true; + return res; +} + +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} + diff --git a/node_modules/iconv-lite/lib/extend-node.js b/node_modules/iconv-lite/lib/extend-node.js new file mode 100644 index 0000000..87f5394 --- /dev/null +++ b/node_modules/iconv-lite/lib/extend-node.js @@ -0,0 +1,217 @@ +"use strict"; +var Buffer = require("buffer").Buffer; +// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer + +// == Extend Node primitives to use iconv-lite ================================= + +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + + // Node authors rewrote Buffer internals to make it compatible with + // Uint8Array and we cannot patch key functions since then. + // Note: this does use older Buffer API on a purpose + iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); + + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; + + if (!iconv.supportsNodeEncodingsExtension) { + console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); + console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); + return; + } + + var nodeNativeEncodings = { + 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, + 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, + }; + + Buffer.isNativeEncoding = function(enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; + } + + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = require('buffer').SlowBuffer; + + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.SlowBufferWrite = SlowBuffer.prototype.write; + SlowBuffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + } + + // -- Buffer --------------------------------------------------------------- + + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); + } + + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); + + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; + } + + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.BufferWrite = Buffer.prototype.write; + Buffer.prototype.write = function(string, offset, length, encoding) { + var _offset = offset, _length = length, _encoding = encoding; + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + + // TODO: Set _charsWritten. + } + + + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + original.ReadableSetEncoding = Readable.prototype.setEncoding; + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Use our own decoder, it has the same interface. + // We cannot use original function as it doesn't handle BOM-s. + this._readableState.decoder = iconv.getDecoder(enc, options); + this._readableState.encoding = enc; + } + + Readable.prototype.collect = iconv._collect; + } + } + + // Remove iconv-lite Node primitive extensions. + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!iconv.supportsNodeEncodingsExtension) + return; + if (!original) + throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + + delete Buffer.isNativeEncoding; + + var SlowBuffer = require('buffer').SlowBuffer; + + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; + + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; + } +} diff --git a/node_modules/iconv-lite/lib/index.d.ts b/node_modules/iconv-lite/lib/index.d.ts new file mode 100644 index 0000000..0547eb3 --- /dev/null +++ b/node_modules/iconv-lite/lib/index.d.ts @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + * REQUIREMENT: This definition is dependent on the @types/node definition. + * Install with `npm install @types/node --save-dev` + *--------------------------------------------------------------------------------------------*/ + +declare module 'iconv-lite' { + export function decode(buffer: Buffer, encoding: string, options?: Options): string; + + export function encode(content: string, encoding: string, options?: Options): Buffer; + + export function encodingExists(encoding: string): boolean; + + export function decodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; + + export function encodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; +} + +export interface Options { + stripBOM?: boolean; + addBOM?: boolean; + defaultEncoding?: string; +} diff --git a/node_modules/iconv-lite/lib/index.js b/node_modules/iconv-lite/lib/index.js new file mode 100644 index 0000000..5391919 --- /dev/null +++ b/node_modules/iconv-lite/lib/index.js @@ -0,0 +1,153 @@ +"use strict"; + +// Some environments don't have global Buffer (e.g. React Native). +// Solution would be installing npm modules "buffer" and "stream" explicitly. +var Buffer = require("safer-buffer").Buffer; + +var bomHandling = require("./bom-handling"), + iconv = module.exports; + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; + +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; + +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getEncoder(encoding, options); + + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } + + buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. + } + + var decoder = iconv.getDecoder(encoding, options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return trail ? (res + trail) : res; +} + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; + } +} + +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = iconv._canonicalizeEncoding(encoding); + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; + + var codecDef = iconv.encodings[enc]; + + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) + codecOptions[key] = codecDef[key]; + + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; + + case "function": // Codec itself. + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codec = new codecDef(codecOptions, iconv); + + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); + } + } +} + +iconv._canonicalizeEncoding = function(encoding) { + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); +} + +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); + + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); + + return encoder; +} + +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); + + return decoder; +} + + +// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. +var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; +if (nodeVer) { + + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + require("./streams")(iconv); + } + + // Load Node primitive extensions. + require("./extend-node")(iconv); +} + +if ("Ā" != "\u0100") { + console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); +} diff --git a/node_modules/iconv-lite/lib/streams.js b/node_modules/iconv-lite/lib/streams.js new file mode 100644 index 0000000..4409552 --- /dev/null +++ b/node_modules/iconv-lite/lib/streams.js @@ -0,0 +1,121 @@ +"use strict"; + +var Buffer = require("buffer").Buffer, + Transform = require("stream").Transform; + + +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + } + + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + } + + iconv.supportsStreams = true; + + + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; + + +// == Encoder stream ======================================================= +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); +} + +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); + +IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; +} + + +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); +} + +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); + +IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; +} + diff --git a/node_modules/iconv-lite/package.json b/node_modules/iconv-lite/package.json new file mode 100644 index 0000000..a7c74fc --- /dev/null +++ b/node_modules/iconv-lite/package.json @@ -0,0 +1,46 @@ +{ + "name": "iconv-lite", + "description": "Convert character encodings in pure javascript.", + "version": "0.4.24", + "license": "MIT", + "keywords": [ + "iconv", + "convert", + "charset", + "icu" + ], + "author": "Alexander Shtuchkin ", + "main": "./lib/index.js", + "typings": "./lib/index.d.ts", + "homepage": "https://github.com/ashtuchkin/iconv-lite", + "bugs": "https://github.com/ashtuchkin/iconv-lite/issues", + "repository": { + "type": "git", + "url": "git://github.com/ashtuchkin/iconv-lite.git" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "coverage": "istanbul cover _mocha -- --grep .", + "coverage-open": "open coverage/lcov-report/index.html", + "test": "mocha --reporter spec --grep ." + }, + "browser": { + "./lib/extend-node": false, + "./lib/streams": false + }, + "devDependencies": { + "mocha": "^3.1.0", + "request": "~2.87.0", + "unorm": "*", + "errto": "*", + "async": "*", + "istanbul": "*", + "semver": "*", + "iconv": "*" + }, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + } +} diff --git a/node_modules/ieee754/LICENSE b/node_modules/ieee754/LICENSE new file mode 100644 index 0000000..5aac82c --- /dev/null +++ b/node_modules/ieee754/LICENSE @@ -0,0 +1,11 @@ +Copyright 2008 Fair Oaks Labs, Inc. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/ieee754/README.md b/node_modules/ieee754/README.md new file mode 100644 index 0000000..cb7527b --- /dev/null +++ b/node_modules/ieee754/README.md @@ -0,0 +1,51 @@ +# ieee754 [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/ieee754/master.svg +[travis-url]: https://travis-ci.org/feross/ieee754 +[npm-image]: https://img.shields.io/npm/v/ieee754.svg +[npm-url]: https://npmjs.org/package/ieee754 +[downloads-image]: https://img.shields.io/npm/dm/ieee754.svg +[downloads-url]: https://npmjs.org/package/ieee754 +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg +[saucelabs-url]: https://saucelabs.com/u/ieee754 + +### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object. + +## install + +``` +npm install ieee754 +``` + +## methods + +`var ieee754 = require('ieee754')` + +The `ieee754` object has the following functions: + +``` +ieee754.read = function (buffer, offset, isLE, mLen, nBytes) +ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) +``` + +The arguments mean the following: + +- buffer = the buffer +- offset = offset into the buffer +- value = value to set (only for `write`) +- isLe = is little endian? +- mLen = mantissa length +- nBytes = number of bytes + +## what is ieee754? + +The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point). + +## license + +BSD 3 Clause. Copyright (c) 2008, Fair Oaks Labs, Inc. diff --git a/node_modules/ieee754/index.d.ts b/node_modules/ieee754/index.d.ts new file mode 100644 index 0000000..f1e4354 --- /dev/null +++ b/node_modules/ieee754/index.d.ts @@ -0,0 +1,10 @@ +declare namespace ieee754 { + export function read( + buffer: Uint8Array, offset: number, isLE: boolean, mLen: number, + nBytes: number): number; + export function write( + buffer: Uint8Array, value: number, offset: number, isLE: boolean, + mLen: number, nBytes: number): void; + } + + export = ieee754; \ No newline at end of file diff --git a/node_modules/ieee754/index.js b/node_modules/ieee754/index.js new file mode 100644 index 0000000..81d26c3 --- /dev/null +++ b/node_modules/ieee754/index.js @@ -0,0 +1,85 @@ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} diff --git a/node_modules/ieee754/package.json b/node_modules/ieee754/package.json new file mode 100644 index 0000000..7b23851 --- /dev/null +++ b/node_modules/ieee754/package.json @@ -0,0 +1,52 @@ +{ + "name": "ieee754", + "description": "Read/write IEEE754 floating point numbers from/to a Buffer or array-like object", + "version": "1.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "contributors": [ + "Romain Beauxis " + ], + "devDependencies": { + "airtap": "^3.0.0", + "standard": "*", + "tape": "^5.0.1" + }, + "keywords": [ + "IEEE 754", + "buffer", + "convert", + "floating point", + "ieee754" + ], + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/ieee754.git" + }, + "scripts": { + "test": "standard && npm run test-node && npm run test-browser", + "test-browser": "airtap -- test/*.js", + "test-browser-local": "airtap --local -- test/*.js", + "test-node": "tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/inflight/LICENSE b/node_modules/inflight/LICENSE new file mode 100644 index 0000000..05eeeb8 --- /dev/null +++ b/node_modules/inflight/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +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/inflight/README.md b/node_modules/inflight/README.md new file mode 100644 index 0000000..6dc8929 --- /dev/null +++ b/node_modules/inflight/README.md @@ -0,0 +1,37 @@ +# inflight + +Add callbacks to requests in flight to avoid async duplication + +## USAGE + +```javascript +var inflight = require('inflight') + +// some request that does some stuff +function req(key, callback) { + // key is any random string. like a url or filename or whatever. + // + // will return either a falsey value, indicating that the + // request for this key is already in flight, or a new callback + // which when called will call all callbacks passed to inflightk + // with the same key + callback = inflight(key, callback) + + // If we got a falsey value back, then there's already a req going + if (!callback) return + + // this is where you'd fetch the url or whatever + // callback is also once()-ified, so it can safely be assigned + // to multiple events etc. First call wins. + setTimeout(function() { + callback(null, key) + }, 100) +} + +// only assigns a single setTimeout +// when it dings, all cbs get called +req('foo', cb1) +req('foo', cb2) +req('foo', cb3) +req('foo', cb4) +``` diff --git a/node_modules/inflight/inflight.js b/node_modules/inflight/inflight.js new file mode 100644 index 0000000..48202b3 --- /dev/null +++ b/node_modules/inflight/inflight.js @@ -0,0 +1,54 @@ +var wrappy = require('wrappy') +var reqs = Object.create(null) +var once = require('once') + +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } + } + }) +} + +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} diff --git a/node_modules/inflight/package.json b/node_modules/inflight/package.json new file mode 100644 index 0000000..6084d35 --- /dev/null +++ b/node_modules/inflight/package.json @@ -0,0 +1,29 @@ +{ + "name": "inflight", + "version": "1.0.6", + "description": "Add callbacks to requests in flight to avoid async duplication", + "main": "inflight.js", + "files": [ + "inflight.js" + ], + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + }, + "devDependencies": { + "tap": "^7.1.2" + }, + "scripts": { + "test": "tap test.js --100" + }, + "repository": { + "type": "git", + "url": "https://github.com/npm/inflight.git" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "bugs": { + "url": "https://github.com/isaacs/inflight/issues" + }, + "homepage": "https://github.com/isaacs/inflight", + "license": "ISC" +} diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +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/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 0000000..3b94763 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,7 @@ +try { + var util = require('util'); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 0000000..7cf62b9 --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,29 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.3", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": "git://github.com/isaacs/inherits", + "license": "ISC", + "scripts": { + "test": "node test" + }, + "devDependencies": { + "tap": "^7.1.0" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ] +} diff --git a/node_modules/ipaddr.js/LICENSE b/node_modules/ipaddr.js/LICENSE new file mode 100644 index 0000000..f6b37b5 --- /dev/null +++ b/node_modules/ipaddr.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011-2017 whitequark + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/ipaddr.js/README.md b/node_modules/ipaddr.js/README.md new file mode 100644 index 0000000..f57725b --- /dev/null +++ b/node_modules/ipaddr.js/README.md @@ -0,0 +1,233 @@ +# ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) + +ipaddr.js is a small (1.9K minified and gzipped) library for manipulating +IP addresses in JavaScript environments. It runs on both CommonJS runtimes +(e.g. [nodejs]) and in a web browser. + +ipaddr.js allows you to verify and parse string representation of an IP +address, match it against a CIDR range or range list, determine if it falls +into some reserved ranges (examples include loopback and private ranges), +and convert between IPv4 and IPv4-mapped IPv6 addresses. + +[nodejs]: http://nodejs.org + +## Installation + +`npm install ipaddr.js` + +or + +`bower install ipaddr.js` + +## API + +ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, +it is exported from the module: + +```js +var ipaddr = require('ipaddr.js'); +``` + +The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. + +### Global methods + +There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and +`ipaddr.process`. All of them receive a string as a single parameter. + +The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or +IPv6 address, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.parse` method returns an object representing the IP address, +or throws an `Error` if the passed string is not a valid representation of an +IP address. + +The `ipaddr.process` method works just like the `ipaddr.parse` one, but it +automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts +before returning. It is useful when you have a Node.js instance listening +on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its +equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 +connections on your IPv6-only socket, but the remote address will be mangled. +Use `ipaddr.process` method to automatically demangle it. + +### Object representation + +Parsing methods return an object which descends from `ipaddr.IPv6` or +`ipaddr.IPv4`. These objects share some properties, but most of them differ. + +#### Shared properties + +One can determine the type of address by calling `addr.kind()`. It will return +either `"ipv6"` or `"ipv4"`. + +An address can be converted back to its string representation with `addr.toString()`. +Note that this method: + * does not return the original string used to create the object (in fact, there is + no way of getting that string) + * returns a compact representation (when it is applicable) + +A `match(range, bits)` method can be used to check if the address falls into a +certain CIDR range. +Note that an address can be (obviously) matched only against an address of the same type. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); +var range = ipaddr.parse("2001:db8::"); + +addr.match(range, 32); // => true +``` + +Alternatively, `match` can also be called as `match([range, bits])`. In this way, +it can be used together with the `parseCIDR(string)` method, which parses an IP +address together with a CIDR range. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); + +addr.match(ipaddr.parseCIDR("2001:db8::/32")); // => true +``` + +A `range()` method returns one of predefined names for several special ranges defined +by IP protocols. The exact names (and their respective CIDR ranges) can be looked up +in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"` +(the default one) and `"reserved"`. + +You can match against your own range list by using +`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: + +```js +var rangeList = { + documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], + tunnelProviders: [ + [ ipaddr.parse('2001:470::'), 32 ], // he.net + [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 + ] +}; +ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders" +``` + +The addresses can be converted to their byte representation with `toByteArray()`. +(Actually, JavaScript mostly does not know about byte buffers. They are emulated with +arrays of numbers, each in range of 0..255.) + +```js +var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com +bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] +``` + +The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them +have the same interface for both protocols, and are similar to global methods. + +`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address +for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. + +`ipaddr.IPvX.isValid(string)` uses the same format for parsing as the POSIX `inet_ntoa` function, which accepts unusual formats like `0xc0.168.1.1` or `0x10000000`. The function `ipaddr.IPv4.isValidFourPartDecimal(string)` validates the IPv4 address and also ensures that it is written in four-part decimal format. + +[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 +[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 + +#### IPv6 properties + +Sometimes you will want to convert IPv6 not to a compact string representation (with +the `::` substitution); the `toNormalizedString()` method will return an address where +all zeroes are explicit. + +For example: + +```js +var addr = ipaddr.parse("2001:0db8::0001"); +addr.toString(); // => "2001:db8::1" +addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" +``` + +The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped +one, and `toIPv4Address()` will return an IPv4 object address. + +To access the underlying binary representation of the address, use `addr.parts`. + +```js +var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); +addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] +``` + +A IPv6 zone index can be accessed via `addr.zoneId`: + +```js +var addr = ipaddr.parse("2001:db8::%eth0"); +addr.zoneId // => 'eth0' +``` + +#### IPv4 properties + +`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. + +To access the underlying representation of the address, use `addr.octets`. + +```js +var addr = ipaddr.parse("192.168.1.1"); +addr.octets // => [192, 168, 1, 1] +``` + +`prefixLengthFromSubnetMask()` will return a CIDR prefix length for a valid IPv4 netmask or +null if the netmask is not valid. + +```js +ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28 +ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask() == null +``` + +`subnetMaskFromPrefixLength()` will return an IPv4 netmask for a valid CIDR prefix length. + +```js +ipaddr.IPv4.subnetMaskFromPrefixLength(24) == "255.255.255.0" +ipaddr.IPv4.subnetMaskFromPrefixLength(29) == "255.255.255.248" +``` + +`broadcastAddressFromCIDR()` will return the broadcast address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.broadcastAddressFromCIDR("172.0.0.1/24") == "172.0.0.255" +``` +`networkAddressFromCIDR()` will return the network address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.networkAddressFromCIDR("172.0.0.1/24") == "172.0.0.0" +``` + +#### Conversion + +IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays. + +The `fromByteArray()` method will take an array and create an appropriate IPv4 or IPv6 object +if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values, +while for IPv6 it has to be an array of sixteen 8-bit values. + +For example: +```js +var addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]); +addr.toString(); // => "127.0.0.1" +``` + +or + +```js +var addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) +addr.toString(); // => "2001:db8::1" +``` + +Both objects also offer a `toByteArray()` method, which returns an array in network byte order (MSB). + +For example: +```js +var addr = ipaddr.parse("127.0.0.1"); +addr.toByteArray(); // => [0x7f, 0, 0, 1] +``` + +or + +```js +var addr = ipaddr.parse("2001:db8::1"); +addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] +``` diff --git a/node_modules/ipaddr.js/ipaddr.min.js b/node_modules/ipaddr.js/ipaddr.min.js new file mode 100644 index 0000000..b54a7cc --- /dev/null +++ b/node_modules/ipaddr.js/ipaddr.min.js @@ -0,0 +1 @@ +(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;e>0;){if((o=n-e)<0&&(o=0),r[i]>>o!=t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(o in t)for(!(a=t[o])[0]||a[0]instanceof Array||(a=[a]),e=0,i=a.length;e=0;t=n+=-1){if(!((e=this.octets[t])in a))return null;if(o=a[e],i&&0!==o)return null;8!==o&&(i=!0),r+=o}return 32-r},r}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(a=[],r=0,e=(o=t.slice(1,6)).length;r4294967295||a<0)throw new Error("ipaddr: address outside defined range");return function(){var r,t;for(t=[],o=r=0;r<=24;o=r+=8)t.push(a>>o&255);return t}().reverse()}return null},t.IPv6=function(){function r(r,t){var n,e,i,o,a,s;if(16===r.length)for(this.parts=[],n=e=0;e<=14;n=e+=2)this.parts.push(r[n]<<8|r[n+1]);else{if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=r}for(i=0,o=(s=this.parts).length;it&&(r=n.index,t=n[0].length);return t<0?i:i.substring(0,r)+"::"+i.substring(r+t)},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],t=0,n=(i=this.parts).length;t>8),r.push(255&e);return r},r.prototype.toNormalizedString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r>8,255&r,n>>8,255&n])},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r=0,i=!1,t=n=7;n>=0;t=n+=-1){if(!((e=this.parts[t])in a))return null;if(o=a[e],i&&0!==o)return null;16!==o&&(i=!0),r+=o}return 128-r},r}(),i="(?:[0-9a-f]+::?)+",o={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"(%[0-9a-z]{1,})?$","i")},r=function(r,t){var n,e,i,a,s,p;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for((p=(r.match(o.zoneIndex)||[])[0])&&(p=p.substring(1),r=r.replace(/%.+$/,"")),n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(s=t-n,a=":";s--;)a+="0:";return":"===(r=r.replace("::",a))[0]&&(r=r.slice(1)),":"===r[r.length-1]&&(r=r.slice(0,-1)),t=function(){var t,n,e,o;for(o=[],t=0,n=(e=r.split(":")).length;t=0&&t<=32)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv4.subnetMaskFromPrefixLength=function(r){var t,n,e;if((r=parseInt(r))<0||r>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(e=[0,0,0,0],n=0,t=Math.floor(r/8);n=0&&t<=128)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},t.isValid=function(r){return t.IPv6.isValid(r)||t.IPv4.isValid(r)},t.parse=function(r){if(t.IPv6.isValid(r))return t.IPv6.parse(r);if(t.IPv4.isValid(r))return t.IPv4.parse(r);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},t.parseCIDR=function(r){try{return t.IPv6.parseCIDR(r)}catch(n){n;try{return t.IPv4.parseCIDR(r)}catch(r){throw r,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},t.fromByteArray=function(r){var n;if(4===(n=r.length))return new t.IPv4(r);if(16===n)return new t.IPv6(r);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},t.process=function(r){var t;return t=this.parse(r),"ipv6"===t.kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(this); \ No newline at end of file diff --git a/node_modules/ipaddr.js/lib/ipaddr.js b/node_modules/ipaddr.js/lib/ipaddr.js new file mode 100644 index 0000000..18bd93b --- /dev/null +++ b/node_modules/ipaddr.js/lib/ipaddr.js @@ -0,0 +1,673 @@ +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; + + ipaddr = {}; + + root = this; + + if ((typeof module !== "undefined" && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } + + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var k, len, rangeName, rangeSubnets, subnet; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (k = 0, len = rangeSubnets.length; k < len; k++) { + subnet = rangeSubnets[k]; + if (address.kind() === subnet[0].kind()) { + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + } + return defaultName; + }; + + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var k, len, octet; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + } + } + this.octets = octets; + } + + IPv4.prototype.kind = function() { + return 'ipv4'; + }; + + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; + + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + + IPv4.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv4') { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; + + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; + + IPv4.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, octet, stop, zeros, zerotable; + zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + cidr = 0; + stop = false; + for (i = k = 3; k >= 0; i = k += -1) { + octet = this.octets[i]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 8) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 32 - cidr; + }; + + return IPv4; + + })(); + + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; + + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var k, len, ref, results; + ref = match.slice(1, 6); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseIntAuto(part)); + } + return results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var k, results; + results = []; + for (shift = k = 0; k <= 24; shift = k += 8) { + results.push((value >> shift) & 0xff); + } + return results; + })()).reverse(); + } else { + return null; + } + }; + + ipaddr.IPv6 = (function() { + function IPv6(parts, zoneId) { + var i, k, l, len, part, ref; + if (parts.length === 16) { + this.parts = []; + for (i = k = 0; k <= 14; i = k += 2) { + this.parts.push((parts[i] << 8) | parts[i + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error("ipaddr: ipv6 part count should be 8 or 16"); + } + ref = this.parts; + for (l = 0, len = ref.length; l < len; l++) { + part = ref[l]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + } + } + if (zoneId) { + this.zoneId = zoneId; + } + } + + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); + }; + + IPv6.prototype.toRFC5952String = function() { + var bestMatchIndex, bestMatchLength, match, regex, string; + regex = /((^|:)(0(:|$)){2,})/g; + string = this.toNormalizedString(); + bestMatchIndex = 0; + bestMatchLength = -1; + while ((match = regex.exec(string))) { + if (match[0].length > bestMatchLength) { + bestMatchIndex = match.index; + bestMatchLength = match[0].length; + } + } + if (bestMatchLength < 0) { + return string; + } + return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); + }; + + IPv6.prototype.toByteArray = function() { + var bytes, k, len, part, ref; + bytes = []; + ref = this.parts; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; + + IPv6.prototype.toNormalizedString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16)); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; + + IPv6.prototype.toFixedLengthString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16).padStart(4, '0')); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; + + IPv6.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv6') { + throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; + + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; + + IPv6.prototype.toIPv4Address = function() { + var high, low, ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + ref = this.parts.slice(-2), high = ref[0], low = ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; + + IPv6.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, part, stop, zeros, zerotable; + zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + cidr = 0; + stop = false; + for (i = k = 7; k >= 0; i = k += -1) { + part = this.parts[i]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 16) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 128 - cidr; + }; + + return IPv6; + + })(); + + ipv6Part = "(?:[0-9a-f]+::?)+"; + + zoneIndex = "%[0-9a-z]{1,}"; + + ipv6Regexes = { + zoneIndex: new RegExp(zoneIndex, 'i'), + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') + }; + + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string = string.replace(/%.+$/, ''); + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + parts = (function() { + var k, len, ref, results; + ref = string.split(":"); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseInt(part, 16)); + } + return results; + })(); + return { + parts: parts, + zoneId: zoneId + }; + }; + + ipaddr.IPv6.parser = function(string) { + var addr, k, len, match, octet, octets, zoneId; + if (ipv6Regexes['native'].test(string)) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + zoneId = match[6] || ''; + addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); + if (addr.parts) { + octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + return null; + } + } + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } + } + return null; + }; + + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.isValidFourPartDecimal = function(string) { + if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; + } + }; + + ipaddr.IPv6.isValid = function(string) { + var addr, e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + addr = this.parser(string); + new this(addr.parts, addr.zoneId); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; + + ipaddr.IPv6.parse = function(string) { + var addr; + addr = this.parser(string); + if (addr.parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(addr.parts, addr.zoneId); + }; + + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + + ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { + var filledOctetCount, j, octets; + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 32) { + throw new Error('ipaddr: invalid IPv4 prefix length'); + } + octets = [0, 0, 0, 0]; + j = 0; + filledOctetCount = Math.floor(prefix / 8); + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + } + return new this(octets); + }; + + ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv4.networkAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + + ipaddr.parseCIDR = function(string) { + var e; + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (error1) { + e = error1; + try { + return ipaddr.IPv4.parseCIDR(string); + } catch (error1) { + e = error1; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + } + } + }; + + ipaddr.fromByteArray = function(bytes) { + var length; + length = bytes.length; + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); + } + }; + + ipaddr.process = function(string) { + var addr; + addr = this.parse(string); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + +}).call(this); diff --git a/node_modules/ipaddr.js/lib/ipaddr.js.d.ts b/node_modules/ipaddr.js/lib/ipaddr.js.d.ts new file mode 100644 index 0000000..52174b6 --- /dev/null +++ b/node_modules/ipaddr.js/lib/ipaddr.js.d.ts @@ -0,0 +1,68 @@ +declare module "ipaddr.js" { + type IPv4Range = 'unicast' | 'unspecified' | 'broadcast' | 'multicast' | 'linkLocal' | 'loopback' | 'carrierGradeNat' | 'private' | 'reserved'; + type IPv6Range = 'unicast' | 'unspecified' | 'linkLocal' | 'multicast' | 'loopback' | 'uniqueLocal' | 'ipv4Mapped' | 'rfc6145' | 'rfc6052' | '6to4' | 'teredo' | 'reserved'; + + interface RangeList { + [name: string]: [T, number] | [T, number][]; + } + + // Common methods/properties for IPv4 and IPv6 classes. + class IP { + prefixLengthFromSubnetMask(): number | null; + toByteArray(): number[]; + toNormalizedString(): string; + toString(): string; + } + + namespace Address { + export function isValid(addr: string): boolean; + export function fromByteArray(bytes: number[]): IPv4 | IPv6; + export function parse(addr: string): IPv4 | IPv6; + export function parseCIDR(mask: string): [IPv4 | IPv6, number]; + export function process(addr: string): IPv4 | IPv6; + export function subnetMatch(addr: IPv4, rangeList: RangeList, defaultName?: string): string; + export function subnetMatch(addr: IPv6, rangeList: RangeList, defaultName?: string): string; + + export class IPv4 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv4; + static isIPv4(addr: string): boolean; + static isValidFourPartDecimal(addr: string): boolean; + static isValid(addr: string): boolean; + static networkAddressFromCIDR(addr: string): IPv4; + static parse(addr: string): IPv4; + static parseCIDR(addr: string): [IPv4, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv4; + constructor(octets: number[]); + octets: number[] + + kind(): 'ipv4'; + match(addr: IPv4, bits: number): boolean; + match(mask: [IPv4, number]): boolean; + range(): IPv4Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4MappedAddress(): IPv6; + } + + export class IPv6 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv6; + static isIPv6(addr: string): boolean; + static isValid(addr: string): boolean; + static parse(addr: string): IPv6; + static parseCIDR(addr: string): [IPv6, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv6; + constructor(parts: number[]); + parts: number[] + zoneId?: string + + isIPv4MappedAddress(): boolean; + kind(): 'ipv6'; + match(addr: IPv6, bits: number): boolean; + match(mask: [IPv6, number]): boolean; + range(): IPv6Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4Address(): IPv4; + } + } + + export = Address; +} diff --git a/node_modules/ipaddr.js/package.json b/node_modules/ipaddr.js/package.json new file mode 100644 index 0000000..f4d3547 --- /dev/null +++ b/node_modules/ipaddr.js/package.json @@ -0,0 +1,35 @@ +{ + "name": "ipaddr.js", + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", + "version": "1.9.1", + "author": "whitequark ", + "directories": { + "lib": "./lib" + }, + "dependencies": {}, + "devDependencies": { + "coffee-script": "~1.12.6", + "nodeunit": "^0.11.3", + "uglify-js": "~3.0.19" + }, + "scripts": { + "test": "cake build test" + }, + "files": [ + "lib/", + "LICENSE", + "ipaddr.min.js" + ], + "keywords": [ + "ip", + "ipv4", + "ipv6" + ], + "repository": "git://github.com/whitequark/ipaddr.js", + "main": "./lib/ipaddr.js", + "engines": { + "node": ">= 0.10" + }, + "license": "MIT", + "types": "./lib/ipaddr.js.d.ts" +} diff --git a/node_modules/is-fullwidth-code-point/index.d.ts b/node_modules/is-fullwidth-code-point/index.d.ts new file mode 100644 index 0000000..729d202 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/index.d.ts @@ -0,0 +1,17 @@ +/** +Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms). + +@param codePoint - The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. + +@example +``` +import isFullwidthCodePoint from 'is-fullwidth-code-point'; + +isFullwidthCodePoint('谢'.codePointAt(0)); +//=> true + +isFullwidthCodePoint('a'.codePointAt(0)); +//=> false +``` +*/ +export default function isFullwidthCodePoint(codePoint: number): boolean; diff --git a/node_modules/is-fullwidth-code-point/index.js b/node_modules/is-fullwidth-code-point/index.js new file mode 100644 index 0000000..671f97f --- /dev/null +++ b/node_modules/is-fullwidth-code-point/index.js @@ -0,0 +1,50 @@ +/* eslint-disable yoda */ +'use strict'; + +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } + + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } + + return false; +}; + +module.exports = isFullwidthCodePoint; +module.exports.default = isFullwidthCodePoint; diff --git a/node_modules/is-fullwidth-code-point/license b/node_modules/is-fullwidth-code-point/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/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/is-fullwidth-code-point/package.json b/node_modules/is-fullwidth-code-point/package.json new file mode 100644 index 0000000..2137e88 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/package.json @@ -0,0 +1,42 @@ +{ + "name": "is-fullwidth-code-point", + "version": "3.0.0", + "description": "Check if the character represented by a given Unicode code point is fullwidth", + "license": "MIT", + "repository": "sindresorhus/is-fullwidth-code-point", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd-check" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "fullwidth", + "full-width", + "full", + "width", + "unicode", + "character", + "string", + "codepoint", + "code", + "point", + "is", + "detect", + "check" + ], + "devDependencies": { + "ava": "^1.3.1", + "tsd-check": "^0.5.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-fullwidth-code-point/readme.md b/node_modules/is-fullwidth-code-point/readme.md new file mode 100644 index 0000000..4236bba --- /dev/null +++ b/node_modules/is-fullwidth-code-point/readme.md @@ -0,0 +1,39 @@ +# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point) + +> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) + + +## Install + +``` +$ npm install is-fullwidth-code-point +``` + + +## Usage + +```js +const isFullwidthCodePoint = require('is-fullwidth-code-point'); + +isFullwidthCodePoint('谢'.codePointAt(0)); +//=> true + +isFullwidthCodePoint('a'.codePointAt(0)); +//=> false +``` + + +## API + +### isFullwidthCodePoint(codePoint) + +#### codePoint + +Type: `number` + +The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/jsonwebtoken/CHANGELOG.md b/node_modules/jsonwebtoken/CHANGELOG.md new file mode 100644 index 0000000..54364a2 --- /dev/null +++ b/node_modules/jsonwebtoken/CHANGELOG.md @@ -0,0 +1,476 @@ +# Change Log + + +All notable changes to this project will be documented in this file starting from version **v4.0.0**. +This project adheres to [Semantic Versioning](http://semver.org/). + +## 8.5.1 - 2019-03-18 + +### Bug fix + + - fix: ensure correct PS signing and verification (#585) ([e5874ae428ffc0465e6bd4e660f89f78b56a74a6](https://github.com/auth0/node-jsonwebtoken/commit/e5874ae428ffc0465e6bd4e660f89f78b56a74a6)), closes [#585](https://github.com/auth0/node-jsonwebtoken/issues/585) + +### Docs + + - README: fix markdown for algorithms table ([84e03ef70f9c44a3aef95a1dc122c8238854f683](https://github.com/auth0/node-jsonwebtoken/commit/84e03ef70f9c44a3aef95a1dc122c8238854f683)) + +## 8.5.0 - 2019-02-20 + +### New Functionality + + - feat: add PS JWA support for applicable node versions (#573) ([eefb9d9c6eec54718fa6e41306bda84788df7bec](https://github.com/auth0/node-jsonwebtoken/commit/eefb9d9c6eec54718fa6e41306bda84788df7bec)), closes [#573](https://github.com/auth0/node-jsonwebtoken/issues/573) + - Add complete option in jwt.verify (#522) ([8737789dd330cf9e7870f4df97fd52479adbac22](https://github.com/auth0/node-jsonwebtoken/commit/8737789dd330cf9e7870f4df97fd52479adbac22)), closes [#522](https://github.com/auth0/node-jsonwebtoken/issues/522) + + ### Test Improvements + + - Add tests for private claims in the payload (#555) ([5147852896755dc1291825e2e40556f964411fb2](https://github.com/auth0/node-jsonwebtoken/commit/5147852896755dc1291825e2e40556f964411fb2)), closes [#555](https://github.com/auth0/node-jsonwebtoken/issues/555) + - Force use_strict during testing (#577) ([7b60c127ceade36c33ff33be066e435802001c94](https://github.com/auth0/node-jsonwebtoken/commit/7b60c127ceade36c33ff33be066e435802001c94)), closes [#577](https://github.com/auth0/node-jsonwebtoken/issues/577) + - Refactor tests related to jti and jwtid (#544) ([7eebbc75ab89e01af5dacf2aae90fe05a13a1454](https://github.com/auth0/node-jsonwebtoken/commit/7eebbc75ab89e01af5dacf2aae90fe05a13a1454)), closes [#544](https://github.com/auth0/node-jsonwebtoken/issues/544) + - ci: remove nsp from tests (#569) ([da8f55c3c7b4dd0bfc07a2df228500fdd050242a](https://github.com/auth0/node-jsonwebtoken/commit/da8f55c3c7b4dd0bfc07a2df228500fdd050242a)), closes [#569](https://github.com/auth0/node-jsonwebtoken/issues/569) + +### Docs + +- Fix 'cert' token which isn't a cert (#554) ([0c24fe68cd2866cea6322016bf993cd897fefc98](https://github.com/auth0/node-jsonwebtoken/commit/0c24fe68cd2866cea6322016bf993cd897fefc98)), closes [#554](https://github.com/auth0/node-jsonwebtoken/issues/554) + + +## 8.4.0 - 2018-11-14 + +### New Functionality + + - Add verify option for nonce validation (#540) ([e7938f06fdf2ed3aa88745b72b8ae4ee66c2d0d0](https://github.com/auth0/node-jsonwebtoken/commit/e7938f06fdf2ed3aa88745b72b8ae4ee66c2d0d0)), closes [#540](https://github.com/auth0/node-jsonwebtoken/issues/540) + +### Bug Fixes + + - Updating Node version in Engines spec in package.json (#528) ([cfd1079305170a897dee6a5f55039783e6ee2711](https://github.com/auth0/node-jsonwebtoken/commit/cfd1079305170a897dee6a5f55039783e6ee2711)), closes [#528](https://github.com/auth0/node-jsonwebtoken/issues/528) [#509](https://github.com/auth0/node-jsonwebtoken/issues/509) + - Fixed error message when empty string passed as expiresIn or notBefore option (#531) ([7f9604ac98d4d0ff8d873c3d2b2ea64bd285cb76](https://github.com/auth0/node-jsonwebtoken/commit/7f9604ac98d4d0ff8d873c3d2b2ea64bd285cb76)), closes [#531](https://github.com/auth0/node-jsonwebtoken/issues/531) + +### Docs + + - Update README.md (#527) ([b76f2a80f5229ee5cde321dd2ff14aa5df16d283](https://github.com/auth0/node-jsonwebtoken/commit/b76f2a80f5229ee5cde321dd2ff14aa5df16d283)), closes [#527](https://github.com/auth0/node-jsonwebtoken/issues/527) + - Update README.md (#538) ([1956c4006472fd285b8a85074257cbdbe9131cbf](https://github.com/auth0/node-jsonwebtoken/commit/1956c4006472fd285b8a85074257cbdbe9131cbf)), closes [#538](https://github.com/auth0/node-jsonwebtoken/issues/538) + - Edited the README.md to make certain parts of the document for the api easier to read, emphasizing the examples. (#548) ([dc89a641293d42f72ecfc623ce2eabc33954cb9d](https://github.com/auth0/node-jsonwebtoken/commit/dc89a641293d42f72ecfc623ce2eabc33954cb9d)), closes [#548](https://github.com/auth0/node-jsonwebtoken/issues/548) + - Document NotBeforeError (#529) ([29cd654b956529e939ae8f8c30b9da7063aad501](https://github.com/auth0/node-jsonwebtoken/commit/29cd654b956529e939ae8f8c30b9da7063aad501)), closes [#529](https://github.com/auth0/node-jsonwebtoken/issues/529) + +### Test Improvements + + - Use lolex for faking date in tests (#491) ([677ead6d64482f2067b11437dda07309abe73cfa](https://github.com/auth0/node-jsonwebtoken/commit/677ead6d64482f2067b11437dda07309abe73cfa)), closes [#491](https://github.com/auth0/node-jsonwebtoken/issues/491) + - Update dependencies used for running tests (#518) ([5498bdc4865ffb2ba2fd44d889fad7e83873bb33](https://github.com/auth0/node-jsonwebtoken/commit/5498bdc4865ffb2ba2fd44d889fad7e83873bb33)), closes [#518](https://github.com/auth0/node-jsonwebtoken/issues/518) + - Minor test refactoring for recently added tests (#504) ([e2860a9d2a412627d79741a95bc7159971b923b9](https://github.com/auth0/node-jsonwebtoken/commit/e2860a9d2a412627d79741a95bc7159971b923b9)), closes [#504](https://github.com/auth0/node-jsonwebtoken/issues/504) + - Create and implement async/sync test helpers (#523) ([683d8a9b31ad6327948f84268bd2c8e4350779d1](https://github.com/auth0/node-jsonwebtoken/commit/683d8a9b31ad6327948f84268bd2c8e4350779d1)), closes [#523](https://github.com/auth0/node-jsonwebtoken/issues/523) + - Refactor tests related to audience and aud (#503) ([53d405e0223cce7c83cb51ecf290ca6bec1e9679](https://github.com/auth0/node-jsonwebtoken/commit/53d405e0223cce7c83cb51ecf290ca6bec1e9679)), closes [#503](https://github.com/auth0/node-jsonwebtoken/issues/503) + - Refactor tests related to expiresIn and exp (#501) ([72f0d9e5b11a99082250665d1200c58182903fa6](https://github.com/auth0/node-jsonwebtoken/commit/72f0d9e5b11a99082250665d1200c58182903fa6)), closes [#501](https://github.com/auth0/node-jsonwebtoken/issues/501) + - Refactor tests related to iat and maxAge (#507) ([877bd57ab2aca9b7d230805b21f921baed3da169](https://github.com/auth0/node-jsonwebtoken/commit/877bd57ab2aca9b7d230805b21f921baed3da169)), closes [#507](https://github.com/auth0/node-jsonwebtoken/issues/507) + - Refactor tests related to iss and issuer (#543) ([0906a3fa80f52f959ac1b6343d3024ce5c7e9dea](https://github.com/auth0/node-jsonwebtoken/commit/0906a3fa80f52f959ac1b6343d3024ce5c7e9dea)), closes [#543](https://github.com/auth0/node-jsonwebtoken/issues/543) + - Refactor tests related to kid and keyid (#545) ([88645427a0adb420bd3e149199a2a6bf1e17277e](https://github.com/auth0/node-jsonwebtoken/commit/88645427a0adb420bd3e149199a2a6bf1e17277e)), closes [#545](https://github.com/auth0/node-jsonwebtoken/issues/545) + - Refactor tests related to notBefore and nbf (#497) ([39adf87a6faef3df984140f88e6724ddd709fd89](https://github.com/auth0/node-jsonwebtoken/commit/39adf87a6faef3df984140f88e6724ddd709fd89)), closes [#497](https://github.com/auth0/node-jsonwebtoken/issues/497) + - Refactor tests related to subject and sub (#505) ([5a7fa23c0b4ac6c25304dab8767ef840b43a0eca](https://github.com/auth0/node-jsonwebtoken/commit/5a7fa23c0b4ac6c25304dab8767ef840b43a0eca)), closes [#505](https://github.com/auth0/node-jsonwebtoken/issues/505) + - Implement async/sync tests for exp claim (#536) ([9ae3f207ac64b7450ea0a3434418f5ca58d8125e](https://github.com/auth0/node-jsonwebtoken/commit/9ae3f207ac64b7450ea0a3434418f5ca58d8125e)), closes [#536](https://github.com/auth0/node-jsonwebtoken/issues/536) + - Implement async/sync tests for nbf claim (#537) ([88bc965061ed65299a395f42a100fb8f8c3c683e](https://github.com/auth0/node-jsonwebtoken/commit/88bc965061ed65299a395f42a100fb8f8c3c683e)), closes [#537](https://github.com/auth0/node-jsonwebtoken/issues/537) + - Implement async/sync tests for sub claim (#534) ([342b07bb105a35739eb91265ba5b9dd33c300fc6](https://github.com/auth0/node-jsonwebtoken/commit/342b07bb105a35739eb91265ba5b9dd33c300fc6)), closes [#534](https://github.com/auth0/node-jsonwebtoken/issues/534) + - Implement async/sync tests for the aud claim (#535) ([1c8ff5a68e6da73af2809c9d87faaf78602c99bb](https://github.com/auth0/node-jsonwebtoken/commit/1c8ff5a68e6da73af2809c9d87faaf78602c99bb)), closes [#535](https://github.com/auth0/node-jsonwebtoken/issues/535) + +### CI + + - Added Istanbul to check test-coverage (#468) ([9676a8306428a045e34c3987bd0680fb952b44e3](https://github.com/auth0/node-jsonwebtoken/commit/9676a8306428a045e34c3987bd0680fb952b44e3)), closes [#468](https://github.com/auth0/node-jsonwebtoken/issues/468) + - Complete ESLint conversion and cleanup (#490) ([cb1d2e1e40547f7ecf29fa6635041df6cbba7f40](https://github.com/auth0/node-jsonwebtoken/commit/cb1d2e1e40547f7ecf29fa6635041df6cbba7f40)), closes [#490](https://github.com/auth0/node-jsonwebtoken/issues/490) + - Make code-coverage mandatory when running tests (#495) ([fb0084a78535bfea8d0087c0870e7e3614a2cbe5](https://github.com/auth0/node-jsonwebtoken/commit/fb0084a78535bfea8d0087c0870e7e3614a2cbe5)), closes [#495](https://github.com/auth0/node-jsonwebtoken/issues/495) + + +## 8.3.0 - 2018-06-11 + + - docs: add some clarifications (#473) ([cd33cc81f06068b9df6c224d300dc6f70d8904ab](https://github.com/auth0/node-jsonwebtoken/commit/cd33cc81f06068b9df6c224d300dc6f70d8904ab)), closes [#473](https://github.com/auth0/node-jsonwebtoken/issues/473) + - ci: fix ci execution, remove not needed script (#472) ([c8ff7b2c3ffcd954a64a0273c20a7d1b22339aa5](https://github.com/auth0/node-jsonwebtoken/commit/c8ff7b2c3ffcd954a64a0273c20a7d1b22339aa5)), closes [#472](https://github.com/auth0/node-jsonwebtoken/issues/472) + - new feature: Secret callback revisited (#480) ([d01cc7bcbdeb606d997a580f967b3169fcc622ba](https://github.com/auth0/node-jsonwebtoken/commit/d01cc7bcbdeb606d997a580f967b3169fcc622ba)), closes [#480](https://github.com/auth0/node-jsonwebtoken/issues/480) + - docs:Update README.md (#461) ([f0e0954505f274da95a8d9603598e455b4d2c894](https://github.com/auth0/node-jsonwebtoken/commit/f0e0954505f274da95a8d9603598e455b4d2c894)), closes [#461](https://github.com/auth0/node-jsonwebtoken/issues/461) + + +## 8.2.2 - 2018-05-30 + + - security: deps: jws@3.1.5 (#477) ([ebde9b7cc75cb7ab5176de7ebc4a1d6a8f05bd51](https://github.com/auth0/node-jsonwebtoken/commit/ebde9b7cc75cb7ab5176de7ebc4a1d6a8f05bd51)), closes [#465](https://github.com/auth0/node-jsonwebtoken/issues/465) + - docs: add some clarifications (#473) ([cd33cc81f06068b9df6c224d300dc6f70d8904ab](https://github.com/auth0/node-jsonwebtoken/commit/cd33cc81f06068b9df6c224d300dc6f70d8904ab)), closes [#473](https://github.com/auth0/node-jsonwebtoken/issues/473) + - ci: fix ci execution, remove not needed script (#472) ([c8ff7b2c3ffcd954a64a0273c20a7d1b22339aa5](https://github.com/auth0/node-jsonwebtoken/commit/c8ff7b2c3ffcd954a64a0273c20a7d1b22339aa5)), closes [#472](https://github.com/auth0/node-jsonwebtoken/issues/472) + - docs: Update README.md (#461) ([f0e0954505f274da95a8d9603598e455b4d2c894](https://github.com/auth0/node-jsonwebtoken/commit/f0e0954505f274da95a8d9603598e455b4d2c894)), closes [#461](https://github.com/auth0/node-jsonwebtoken/issues/461) + + +## 8.2.1 - 2018-04-05 + + - bug fix: Check payload is not null when decoded. (#444) ([1232ae9352ce5fd1ca6c593291ce6ad0834a1ff5](https://github.com/auth0/node-jsonwebtoken/commit/1232ae9352ce5fd1ca6c593291ce6ad0834a1ff5)) + - docs: Clarify that buffer/string payloads must be JSON (#442) ([e8ac1be7565a3fd986d40cb5e31a9f6c4d9aed1b](https://github.com/auth0/node-jsonwebtoken/commit/e8ac1be7565a3fd986d40cb5e31a9f6c4d9aed1b)) + + +## 8.2.0 - 2018-03-02 + + - Add a new mutatePayload option (#446) ([d6d7c5e5103f05a92d3633ac190d3025a0455be0](https://github.com/auth0/node-jsonwebtoken/commit/d6d7c5e5103f05a92d3633ac190d3025a0455be0)) + + +## 8.1.1 - 2018-01-22 + + - ci: add newer node versions to build matrix (#428) ([83f3eee44e122da06f812d7da4ace1fa26c24d9d](https://github.com/auth0/node-jsonwebtoken/commit/83f3eee44e122da06f812d7da4ace1fa26c24d9d)) + - deps: Bump ms version to add support for negative numbers (#438) ([25e0e624545eaef76f3c324a134bf103bc394724](https://github.com/auth0/node-jsonwebtoken/commit/25e0e624545eaef76f3c324a134bf103bc394724)) + - docs: Minor typo (#424) ([dddcb73ac05de11b81feeb629f6cf78dd03d2047](https://github.com/auth0/node-jsonwebtoken/commit/dddcb73ac05de11b81feeb629f6cf78dd03d2047)) + - bug fix: Not Before (nbf) calculated based on iat/timestamp (#437) ([2764a64908d97c043d62eba0bf6c600674f9a6d6](https://github.com/auth0/node-jsonwebtoken/commit/2764a64908d97c043d62eba0bf6c600674f9a6d6)), closes [#435](https://github.com/auth0/node-jsonwebtoken/issues/435) + + +## 8.1.0 - 2017-10-09 + + - #402: Don't fail if captureStackTrace is not a function (#410) ([77ee965d9081faaf21650f266399f203f69533c5](https://github.com/auth0/node-jsonwebtoken/commit/77ee965d9081faaf21650f266399f203f69533c5)) + - #403: Clarify error wording for "Expected object" error. (#409) ([bb27eb346f0ff675a320b2de16b391a7cfeadc58](https://github.com/auth0/node-jsonwebtoken/commit/bb27eb346f0ff675a320b2de16b391a7cfeadc58)) + - Enhance audience check to verify against regular expressions (#398) ([81501a17da230af7b74a3f7535ab5cd3a19c8315](https://github.com/auth0/node-jsonwebtoken/commit/81501a17da230af7b74a3f7535ab5cd3a19c8315)) + + +## 8.0.1 - 2017-09-12 + + - Remove `lodash.isarray` dependency (#394) ([7508e8957cb1c778f72fa9a363a7b135b3c9c36d](https://github.com/auth0/node-jsonwebtoken/commit/7508e8957cb1c778f72fa9a363a7b135b3c9c36d)) + +## 8.0.0 - 2017-09-06 + + **Breaking changes: See [Migration notes from v7](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v7-to-v8)** + + - docs: readme, migration notes ([12cd8f7f47224f904f6b8f39d1dee73775de4f6f](https://github.com/auth0/node-jsonwebtoken/commit/12cd8f7f47224f904f6b8f39d1dee73775de4f6f)) + - verify: remove process.nextTick (#302) ([3305cf04e3f674b9fb7e27c9b14ddd159650ff82](https://github.com/auth0/node-jsonwebtoken/commit/3305cf04e3f674b9fb7e27c9b14ddd159650ff82)) + - Reduce size of NPM package (#347) ([0be5409ac6592eeaae373dce91ec992fa101bd8a](https://github.com/auth0/node-jsonwebtoken/commit/0be5409ac6592eeaae373dce91ec992fa101bd8a)) + - Remove joi to shrink module size (#348) ([2e7e68dbd59e845cdd940afae0a296f48438445f](https://github.com/auth0/node-jsonwebtoken/commit/2e7e68dbd59e845cdd940afae0a296f48438445f)) + - maxAge: Add validation to timespan result ([66a4f8b996c8357727ce62a84605a005b2f5eb18](https://github.com/auth0/node-jsonwebtoken/commit/66a4f8b996c8357727ce62a84605a005b2f5eb18)) + +## 7.4.3 - 2017-08-17 + + - Fix breaking change on 7.4.2 for empty secret + "none" algorithm (sync code style) ([PR 386](https://github.com/auth0/node-jsonwebtoken/pull/386)) + +## 7.4.2 - 2017-08-04 + + - bugfix: sign: add check to be sure secret has a value ([c584d1cbc34b788977b36f17cd57ab2212f1230e](https://github.com/auth0/node-jsonwebtoken/commit/c584d1cbc34b788977b36f17cd57ab2212f1230e)) + - docs: about refreshing tokens ([016fc10b847bfbb76b82171cb530f32d7da2001b](https://github.com/auth0/node-jsonwebtoken/commit/016fc10b847bfbb76b82171cb530f32d7da2001b)) + - docs: verifying with base64 encoded secrets ([c25e9906801f89605080cc71b3ee23a5e45a5811](https://github.com/auth0/node-jsonwebtoken/commit/c25e9906801f89605080cc71b3ee23a5e45a5811)) + - tests: Add tests for ES256 ([89900ea00735f76b04f437c9f542285b420fa9cb](https://github.com/auth0/node-jsonwebtoken/commit/89900ea00735f76b04f437c9f542285b420fa9cb)) + - docs: document keyid as option (#361) ([00086c2c006d7fc1a47bae02fa87d194d79aa558](https://github.com/auth0/node-jsonwebtoken/commit/00086c2c006d7fc1a47bae02fa87d194d79aa558)) + - docs: readme: Using private key with passpharase (#353) ([27a7f1d4f35b662426ff0270526d48658da4c8b7](https://github.com/auth0/node-jsonwebtoken/commit/27a7f1d4f35b662426ff0270526d48658da4c8b7)) + +## 7.4.1 - 2017-05-17 + + - bump ms to v2 due a ReDoS vulnerability (#352) ([adcfd6ae4088c838769d169f8cd9154265aa13e0](https://github.com/auth0/node-jsonwebtoken/commit/adcfd6ae4088c838769d169f8cd9154265aa13e0)) + +## 7.4.0 - 2017-04-24 + + - Add docs about numeric date fields ([659f73119900a4d837650d9b3f5af4e64a2f843b](https://github.com/auth0/node-jsonwebtoken/commit/659f73119900a4d837650d9b3f5af4e64a2f843b)) + - Make Options object optional for callback-ish sign ([e202c4fd00c35a24e9ab606eab89186ade13d0cc](https://github.com/auth0/node-jsonwebtoken/commit/e202c4fd00c35a24e9ab606eab89186ade13d0cc)) + +## 7.3.0 - 2017-02-13 + + - Add more information to `maxAge` option in README ([1b0592e99cc8def293eed177e2575fa7f1cf7aa5](https://github.com/auth0/node-jsonwebtoken/commit/1b0592e99cc8def293eed177e2575fa7f1cf7aa5)) + - Add `clockTimestamp` option to `verify()` you can set the current time in seconds with it (#274) ([8fdc1504f4325e7003894ffea078da9cba5208d9](https://github.com/auth0/node-jsonwebtoken/commit/8fdc1504f4325e7003894ffea078da9cba5208d9)) + - Fix handling non string tokens on `verify()` input (#305) ([1b6ec8d466504f58c5a6e2dae3360c828bad92fb](https://github.com/auth0/node-jsonwebtoken/commit/1b6ec8d466504f58c5a6e2dae3360c828bad92fb)), closes [#305](https://github.com/auth0/node-jsonwebtoken/issues/305) + - Fixed a simple typo in docs (#287) ([a54240384e24e18c00e75884295306db311d0cb7](https://github.com/auth0/node-jsonwebtoken/commit/a54240384e24e18c00e75884295306db311d0cb7)), closes [#287](https://github.com/auth0/node-jsonwebtoken/issues/287) + - Raise jws.decode error to avoid confusion with "invalid token" error (#294) ([7f68fe06c88d5c5653785bd66bc68c5b20e1bd8e](https://github.com/auth0/node-jsonwebtoken/commit/7f68fe06c88d5c5653785bd66bc68c5b20e1bd8e)) + - rauchg/ms.js changed to zeit/ms (#303) ([35d84152a6b716d757cb5b1dd3c79fe3a1bc0628](https://github.com/auth0/node-jsonwebtoken/commit/35d84152a6b716d757cb5b1dd3c79fe3a1bc0628)) + +## 7.2.1 - 2016-12-07 + + - add nsp check to find vulnerabilities on npm test ([4219c34b5346811c07f520f10516cc495bcc70dd](https://github.com/auth0/node-jsonwebtoken/commit/4219c34b5346811c07f520f10516cc495bcc70dd)) + - revert to joi@^6 to keep ES5 compatibility ([51d4796c07344bf817687f7ccfeef78f00bf5b4f](https://github.com/auth0/node-jsonwebtoken/commit/51d4796c07344bf817687f7ccfeef78f00bf5b4f)) + +## 7.2.0 - 2016-12-06 + + - improve the documentation for expiration ([771e0b5f9bed90771fb79140eb38e51a3ecac8f0](https://github.com/auth0/node-jsonwebtoken/commit/771e0b5f9bed90771fb79140eb38e51a3ecac8f0)) + - Restructured a sentence ([ccc7610187a862f7a50177eadc9152eef26cd065](https://github.com/auth0/node-jsonwebtoken/commit/ccc7610187a862f7a50177eadc9152eef26cd065)) + - Allow `keyid` on `sign`. ([b412be91b89acb3a742bb609d3b54e47e1dfc441](https://github.com/auth0/node-jsonwebtoken/commit/b412be91b89acb3a742bb609d3b54e47e1dfc441)) + - upgrade joi ([715e3d928023d414d45c6dc3f096a7c8448139ae](https://github.com/auth0/node-jsonwebtoken/commit/715e3d928023d414d45c6dc3f096a7c8448139ae)) + - upgrade to latest nodes and Travis infrastructure ([3febcc1dd23ecdec1abbf89313959941d15eb47a](https://github.com/auth0/node-jsonwebtoken/commit/3febcc1dd23ecdec1abbf89313959941d15eb47a)) + + +## 7.1.10 - 2016-12-06 + + - Bump node-jws version number ([07813dd7194630c9f452684279178af76464a759](https://github.com/auth0/node-jsonwebtoken/commit/07813dd7194630c9f452684279178af76464a759)) + - improve the documentation for expiration ([771e0b5f9bed90771fb79140eb38e51a3ecac8f0](https://github.com/auth0/node-jsonwebtoken/commit/771e0b5f9bed90771fb79140eb38e51a3ecac8f0)) + +## 7.1.9 - 2016-08-11 + + - Revert "Merge branch 'venatir-master'" ([d06359ef3b4e619680e043ee7c16adda16598f52](https://github.com/auth0/node-jsonwebtoken/commit/d06359ef3b4e619680e043ee7c16adda16598f52)) + + + +## 7.1.8 - 2016-08-10 + + - Fixed tests, however typ: 'JWT' should not be in the options at all, so please review other tests ([01903bcdc61b4ed429acbbd1fe0ffe0db364473b](https://github.com/auth0/node-jsonwebtoken/commit/01903bcdc61b4ed429acbbd1fe0ffe0db364473b)) + - Removing unnecessary extra decoding. jwtString is already verified as valid and signature checked ([55d5834f7b637011e1d8b927ff78a92a5fd521cf](https://github.com/auth0/node-jsonwebtoken/commit/55d5834f7b637011e1d8b927ff78a92a5fd521cf)) + - update changelog ([5117aacd0118a10331889a64e61d8186112d8a23](https://github.com/auth0/node-jsonwebtoken/commit/5117aacd0118a10331889a64e61d8186112d8a23)) + + +## 7.1.7 - 2016-07-29 + + - Use lodash.once instead of unlicensed/unmaintained cb ([3ac95ad93ef3068a64e03d8d14deff231b1ed529](https://github.com/auth0/node-jsonwebtoken/commit/3ac95ad93ef3068a64e03d8d14deff231b1ed529)) + +## 7.1.6 - 2016-07-15 + + - fix issue with buffer payload. closes #216 ([6b50ff324b4dfd2cb0e49b666f14a6672d015b22](https://github.com/auth0/node-jsonwebtoken/commit/6b50ff324b4dfd2cb0e49b666f14a6672d015b22)), closes [#216](https://github.com/auth0/node-jsonwebtoken/issues/216) + + +## 7.1.5 - 2016-07-15 + + - update jws in package.json ([b6260951eefc68aae5f4ede359210761f901ff7a](https://github.com/auth0/node-jsonwebtoken/commit/b6260951eefc68aae5f4ede359210761f901ff7a)) + + +## 7.1.4 - 2016-07-14 + + - add redundant test ([bece8816096f324511c3efcb8db0e64b75d757a1](https://github.com/auth0/node-jsonwebtoken/commit/bece8816096f324511c3efcb8db0e64b75d757a1)) + - fix an issue of double callback on error ([758ca5eeca2f1b06c32c9fce70642bf488b2e52b](https://github.com/auth0/node-jsonwebtoken/commit/758ca5eeca2f1b06c32c9fce70642bf488b2e52b)) + +## 7.1.2 - 2016-07-12 + + - do not stringify the payload when signing async - closes #224 ([084f537d3dfbcef2bea411cc0a1515899cc8aa21](https://github.com/auth0/node-jsonwebtoken/commit/084f537d3dfbcef2bea411cc0a1515899cc8aa21)), closes [#224](https://github.com/auth0/node-jsonwebtoken/issues/224) + +## 7.1.1 - 2016-07-12 + + - do not mutate options in jwt.verify, closes #227 ([63263a28a268624dab0927b9ad86fffa44a10f84](https://github.com/auth0/node-jsonwebtoken/commit/63263a28a268624dab0927b9ad86fffa44a10f84)), closes [#227](https://github.com/auth0/node-jsonwebtoken/issues/227) + - refactor into multiple files ([e11d505207fa33501298300c9accbfb809d8748d](https://github.com/auth0/node-jsonwebtoken/commit/e11d505207fa33501298300c9accbfb809d8748d)) + +## 7.1.0 - 2016-07-12 + + - Exp calculated based on iat. fix #217 ([757a16e0e35ad19f9e456820f55d5d9f3fc76aee](https://github.com/auth0/node-jsonwebtoken/commit/757a16e0e35ad19f9e456820f55d5d9f3fc76aee)), closes [#217](https://github.com/auth0/node-jsonwebtoken/issues/217) + +## 7.0.0 - 2016-05-19 + + - change jwt.sign to return errors on callback instead of throwing errors ([1e46c5a42aa3dab8478efa4081d8f8f5c5485d56](https://github.com/auth0/node-jsonwebtoken/commit/1e46c5a42aa3dab8478efa4081d8f8f5c5485d56)) + +## 6.2.0 - 2016-04-29 + + - add support for `options.clockTolerance` to `jwt.verify` ([65ddea934f226bf06bc9d6a55be9587515cfc38d](https://github.com/auth0/node-jsonwebtoken/commit/65ddea934f226bf06bc9d6a55be9587515cfc38d)) + +## 6.1.2 - 2016-04-29 + + - fix sign method for node.js 0.12. closes #193 ([9c38374142d3929be3c9314b5e9bc5d963c5955f](https://github.com/auth0/node-jsonwebtoken/commit/9c38374142d3929be3c9314b5e9bc5d963c5955f)), closes [#193](https://github.com/auth0/node-jsonwebtoken/issues/193) + - improve async test ([7b0981380ddc40a5f1208df520631785b5ffb85a](https://github.com/auth0/node-jsonwebtoken/commit/7b0981380ddc40a5f1208df520631785b5ffb85a)) + +## 6.1.0 - 2016-04-27 + + - verify unsigned tokens ([ec880791c10ed5ef7c8df7bf28ebb95c810479ed](https://github.com/auth0/node-jsonwebtoken/commit/ec880791c10ed5ef7c8df7bf28ebb95c810479ed)) + +## 6.0.1 - 2016-04-27 + +This was an immediate change after publishing 6.0.0. + + - throw error on invalid options when the payload is not an object ([304f1b33075f79ed66f784e27dc4f5307aa39e27](https://github.com/auth0/node-jsonwebtoken/commit/304f1b33075f79ed66f784e27dc4f5307aa39e27)) + +## 6.0.0 - 2016-04-27 + + - Change .sign to standard async callback ([50873c7d45d2733244d5da8afef3d1872e657a60](https://github.com/auth0/node-jsonwebtoken/commit/50873c7d45d2733244d5da8afef3d1872e657a60)) + - Improved the options for the `sign` method ([53c3987b3cc34e95eb396b26fc9b051276e2f6f9](https://github.com/auth0/node-jsonwebtoken/commit/53c3987b3cc34e95eb396b26fc9b051276e2f6f9)) + + - throw error on invalid options like `expiresIn` when the payload is not an object ([304f1b33075f79ed66f784e27dc4f5307aa39e27](https://github.com/auth0/node-jsonwebtoken/commit/304f1b33075f79ed66f784e27dc4f5307aa39e27)) + - `expiresInMinutes` and `expiresInSeconds` are deprecated and no longer supported. + - `notBeforeInMinutes` and `notBeforeInSeconds` are deprecated and no longer supported. + - `options` are strongly validated. + - `options.expiresIn`, `options.notBefore`, `options.audience`, `options.issuer`, `options.subject` and `options.jwtid` are mutually exclusive with `payload.exp`, `payload.nbf`, `payload.aud`, `payload.iss` + - `options.algorithm` is properly validated. + - `options.headers` is renamed to `options.header`. + + - update CHANGELOG to reflect most of the changes. closes #136 ([b87a1a8d2e2533fbfab518765a54f00077918eb7](https://github.com/auth0/node-jsonwebtoken/commit/b87a1a8d2e2533fbfab518765a54f00077918eb7)), closes [#136](https://github.com/auth0/node-jsonwebtoken/issues/136) + - update readme ([53a88ecf4494e30e1d62a1cf3cc354650349f486](https://github.com/auth0/node-jsonwebtoken/commit/53a88ecf4494e30e1d62a1cf3cc354650349f486)) + +## 5.7.0 - 2016-02-16 + + + - add support for validating multiples issuers. closes #163 ([39d9309ae05648dbd72e5fd1993df064ad0e8fa5](https://github.com/auth0/node-jsonwebtoken/commit/39d9309ae05648dbd72e5fd1993df064ad0e8fa5)), closes [#163](https://github.com/auth0/node-jsonwebtoken/issues/163) + + +## 5.6.1 - 2016-02-16 + + + - 5.6.1 ([06d8209d499dbc9a8dd978ab6cbb9c6818fde203](https://github.com/auth0/node-jsonwebtoken/commit/06d8209d499dbc9a8dd978ab6cbb9c6818fde203)) + - fix wrong error when setting expiration on non-object payload. closes #153 ([7f7d76edfd918d6afc7c7cead888caa42ccaceb4](https://github.com/auth0/node-jsonwebtoken/commit/7f7d76edfd918d6afc7c7cead888caa42ccaceb4)), closes [#153](https://github.com/auth0/node-jsonwebtoken/issues/153) + + + +## 5.6.0 - 2016-02-16 + + + - added missing validations of sub and jti ([a1affe960d0fc52e9042bcbdedb65734f8855580](https://github.com/auth0/node-jsonwebtoken/commit/a1affe960d0fc52e9042bcbdedb65734f8855580)) + - Fix tests in jwt.rs.tests.js which causes 4 to fail ([8aedf2b1f575b0d9575c1fc9f2ac7bc868f75ff1](https://github.com/auth0/node-jsonwebtoken/commit/8aedf2b1f575b0d9575c1fc9f2ac7bc868f75ff1)) + - Update README.md ([349b7cd00229789b138928ca060d3ef015aedaf9](https://github.com/auth0/node-jsonwebtoken/commit/349b7cd00229789b138928ca060d3ef015aedaf9)) + + + +## 5.5.4 - 2016-01-04 + + + - minor ([46552e7c45025c76e3f647680d7539a66bfac612](https://github.com/auth0/node-jsonwebtoken/commit/46552e7c45025c76e3f647680d7539a66bfac612)) + + + +## 5.5.3 - 2016-01-04 + + + - add a console.warn on invalid options for string payloads ([71200f14deba0533d3261266348338fac2d14661](https://github.com/auth0/node-jsonwebtoken/commit/71200f14deba0533d3261266348338fac2d14661)) + - minor ([65b1f580382dc58dd3da6f47a52713776fd7cdf2](https://github.com/auth0/node-jsonwebtoken/commit/65b1f580382dc58dd3da6f47a52713776fd7cdf2)) + + + +## 5.5.2 - 2016-01-04 + + + - fix signing method with sealed objects, do not modify the params object. closes #147 ([be9c09af83b09c9e72da8b2c6166fa51d92aeab6](https://github.com/auth0/node-jsonwebtoken/commit/be9c09af83b09c9e72da8b2c6166fa51d92aeab6)), closes [#147](https://github.com/auth0/node-jsonwebtoken/issues/147) + + + +## 5.5.1 - 2016-01-04 + + + - fix nbf verification. fix #152 ([786d37b299c67771b5e71a2ca476666ab0f97d98](https://github.com/auth0/node-jsonwebtoken/commit/786d37b299c67771b5e71a2ca476666ab0f97d98)), closes [#152](https://github.com/auth0/node-jsonwebtoken/issues/152) + + + +## 5.5.0 - 2015-12-28 + + + - improvements to nbf and jti claims ([46372e928f6d2e7398f9b88022ca617d2a3b0699](https://github.com/auth0/node-jsonwebtoken/commit/46372e928f6d2e7398f9b88022ca617d2a3b0699)) + - Remove duplicate payload line (fix bug in IE strict mode) ([8163d698e0c5ad8c44817a5dcd42a15d7e9c6bc8](https://github.com/auth0/node-jsonwebtoken/commit/8163d698e0c5ad8c44817a5dcd42a15d7e9c6bc8)) + - Remove duplicate require('ms') line ([7c00bcbcbf8f7503a1070b394a165eccd41de66f](https://github.com/auth0/node-jsonwebtoken/commit/7c00bcbcbf8f7503a1070b394a165eccd41de66f)) + - Update README to reflect addition of async sign ([d661d4b6f68eb417834c99b36769444723041ccf](https://github.com/auth0/node-jsonwebtoken/commit/d661d4b6f68eb417834c99b36769444723041ccf)) + + + +## 5.4.0 - 2015-10-02 + + + - deprecate expireInMinutes and expireInSeconds - in favor of expiresIn ([39ecc6f8f310f8462e082f1d53de0b4222b29b6f](https://github.com/auth0/node-jsonwebtoken/commit/39ecc6f8f310f8462e082f1d53de0b4222b29b6f)) + + +## 5.3.0 - 2015-10-02 + + + - 5.3.0 ([5d559ced3fbf10c1adae2e5792deda06ea89bcd3](https://github.com/auth0/node-jsonwebtoken/commit/5d559ced3fbf10c1adae2e5792deda06ea89bcd3)) + - minor ([6e81ff87a3799b0e56db09cbae42a97e784716c4](https://github.com/auth0/node-jsonwebtoken/commit/6e81ff87a3799b0e56db09cbae42a97e784716c4)) + + + +## 5.1.0 - 2015-10-02 + + + - added async signing ([9414fbcb15a1f9cf4fe147d070e9424c547dabba](https://github.com/auth0/node-jsonwebtoken/commit/9414fbcb15a1f9cf4fe147d070e9424c547dabba)) + - Update README.md ([40b2aaaa843442dfb8ee7b574f0a788177e7c904](https://github.com/auth0/node-jsonwebtoken/commit/40b2aaaa843442dfb8ee7b574f0a788177e7c904)) + + + +## 5.0.5 - 2015-08-19 + + + - add ms dep to package.json ([f13b3fb7f29dff787e7c91ebe2eb5adeeb05f251](https://github.com/auth0/node-jsonwebtoken/commit/f13b3fb7f29dff787e7c91ebe2eb5adeeb05f251)) + - add note to explain, related to #96 #101 #6 ([dd8969e0e6ed0bcb9cae905d2b1a96476bd85da3](https://github.com/auth0/node-jsonwebtoken/commit/dd8969e0e6ed0bcb9cae905d2b1a96476bd85da3)) + - add tests for options.headers ([7787dd74e705787c39a871ca29c75a2e0a3948ac](https://github.com/auth0/node-jsonwebtoken/commit/7787dd74e705787c39a871ca29c75a2e0a3948ac)) + - add tests for verify expires ([d7c5793d98c300603440ab460c11665f661ad3a0](https://github.com/auth0/node-jsonwebtoken/commit/d7c5793d98c300603440ab460c11665f661ad3a0)) + - add verify option maxAge (with tests) ([49d54e54f7e70b1c53a2e4ee67e116c907d75319](https://github.com/auth0/node-jsonwebtoken/commit/49d54e54f7e70b1c53a2e4ee67e116c907d75319)) + - fix spelling error in error message ([8078b11b224fa05ac9003ca5aa2c85e9f0128cfb](https://github.com/auth0/node-jsonwebtoken/commit/8078b11b224fa05ac9003ca5aa2c85e9f0128cfb)) + - Fix typo options.header is not a documented option + ([5feaa5b962ccbddeff054817a410f7b0c1e6ce7f](https://github.com/auth0/node-jsonwebtoken/commit/5feaa5b962ccbddeff054817a410f7b0c1e6ce7f)) + - update JWT spec link. closes #112 ([f5fa50f797456a12240589161835c7ea30807195](https://github.com/auth0/node-jsonwebtoken/commit/f5fa50f797456a12240589161835c7ea30807195)), closes [#112](https://github.com/auth0/node-jsonwebtoken/issues/112) + + +## 5.0.3 - 2015-07-15 + + - Added nbf support ([f26ba4e2fa197a20497632b63ffcd13ae93aacc4](https://github.com/auth0/node-jsonwebtoken/commit/f26ba4e2fa197a20497632b63ffcd13ae93aacc4)) + - Added support for subject and jwt id ([ab76ec5bc554e2d1e25376ddb7cea711d86af651](https://github.com/auth0/node-jsonwebtoken/commit/ab76ec5bc554e2d1e25376ddb7cea711d86af651)) + - Fix `this` referring to the global object instead of `module.exports` in `verify()` ([93f554312e37129027fcf4916f48cb8d1b53588c](https://github.com/auth0/node-jsonwebtoken/commit/93f554312e37129027fcf4916f48cb8d1b53588c)) + - Fix typo, line 139 README, complete option for .decode. ([59c110aeb8c7c1847ef2ffd77702d13627c89e10](https://github.com/auth0/node-jsonwebtoken/commit/59c110aeb8c7c1847ef2ffd77702d13627c89e10)) + - minor ([61ff1172272b582902313e958058ff22413494af](https://github.com/auth0/node-jsonwebtoken/commit/61ff1172272b582902313e958058ff22413494af)) + + + +## 5.0.2 - 2015-06-15 + + + - fix typo in docs . closes #86 ([3d3413221f36acef4dfd1cbed87f1f3565cd6f84](https://github.com/auth0/node-jsonwebtoken/commit/3d3413221f36acef4dfd1cbed87f1f3565cd6f84)), closes [#86](https://github.com/auth0/node-jsonwebtoken/issues/86) + + + +## 5.0.1 - 2015-05-15 + + + - Add option to return header and payload when decoding. ([7254e011b59f892d1947e6c11819281adac7069d](https://github.com/auth0/node-jsonwebtoken/commit/7254e011b59f892d1947e6c11819281adac7069d)) + - Avoid uncaught "SyntaxError: Unexpected token ͧ" error. ([0dc59cd6ee15d83a606acffa7909ee76176ae186](https://github.com/auth0/node-jsonwebtoken/commit/0dc59cd6ee15d83a606acffa7909ee76176ae186)) + - Document complete option in README. ([ec32b20241a74d9681ea26e1a7024b4642468c00](https://github.com/auth0/node-jsonwebtoken/commit/ec32b20241a74d9681ea26e1a7024b4642468c00)) + - Fix example in README, silence verbose logging. ([ba3174d10033c41e9c211a38f1cc67f74fbd7f69](https://github.com/auth0/node-jsonwebtoken/commit/ba3174d10033c41e9c211a38f1cc67f74fbd7f69)) + - Fix link to auth0.com in README ([1b3c5ff72c9bc25e9271646e679f3080f2a042a0](https://github.com/auth0/node-jsonwebtoken/commit/1b3c5ff72c9bc25e9271646e679f3080f2a042a0)) + - Immediate return if not decoded. ([851bda2b10168f3269c3da6e74d310742f31a193](https://github.com/auth0/node-jsonwebtoken/commit/851bda2b10168f3269c3da6e74d310742f31a193)) + - Prevent throw on undefined/null secret ([0fdf78d4dbf609455f3277d6169a987aef0384d4](https://github.com/auth0/node-jsonwebtoken/commit/0fdf78d4dbf609455f3277d6169a987aef0384d4)) + - Removed path from test ([d6240e24186732d368bffe21143becf44c38f0d6](https://github.com/auth0/node-jsonwebtoken/commit/d6240e24186732d368bffe21143becf44c38f0d6)) + - Simplified checking for missing key ([f1cffd033bffc44f20558eda4a797c3fa2f4ee05](https://github.com/auth0/node-jsonwebtoken/commit/f1cffd033bffc44f20558eda4a797c3fa2f4ee05)) + - Typo ([ffe68dbe0219bab535c1018448eb4c0b22f1f902](https://github.com/auth0/node-jsonwebtoken/commit/ffe68dbe0219bab535c1018448eb4c0b22f1f902)) + - Update CHANGELOG.md ([927cce0dad1bc9aad75aeef53e276cf4cfc0d776](https://github.com/auth0/node-jsonwebtoken/commit/927cce0dad1bc9aad75aeef53e276cf4cfc0d776)) + - Update CHANGELOG.md ([6879e0fdde222995c70a3a69a4af94993d9c667e](https://github.com/auth0/node-jsonwebtoken/commit/6879e0fdde222995c70a3a69a4af94993d9c667e)) + - Update CHANGELOG.md ([c5596c10e8705727fa13e0394184a606083078bc](https://github.com/auth0/node-jsonwebtoken/commit/c5596c10e8705727fa13e0394184a606083078bc)) + - Update CHANGELOG.md ([07541f0315f26d179e1cde92732b6124d6869b6f](https://github.com/auth0/node-jsonwebtoken/commit/07541f0315f26d179e1cde92732b6124d6869b6f)) + - Update CHANGELOG.md ([e6465d48ddd1dc2c3297229b28c78fd5490a2ba9](https://github.com/auth0/node-jsonwebtoken/commit/e6465d48ddd1dc2c3297229b28c78fd5490a2ba9)) + +## [5.0.0] - 2015-04-11 + +### Changed + + - [sign] Only set defautl `iat` if the user does not specify that argument. + + https://github.com/auth0/node-jsonwebtoken/commit/e900282a8d2dff1d4dec815f7e6aa7782e867d91 + https://github.com/auth0/node-jsonwebtoken/commit/35036b188b4ee6b42df553bbb93bc8a6b19eae9d + https://github.com/auth0/node-jsonwebtoken/commit/954bd7a312934f03036b6bb6f00edd41f29e54d9 + https://github.com/auth0/node-jsonwebtoken/commit/24a370080e0b75f11d4717cd2b11b2949d95fc2e + https://github.com/auth0/node-jsonwebtoken/commit/a77df6d49d4ec688dfd0a1cc723586bffe753516 + +### Security + + - [verify] Update to jws@^3.0.0 and renaming `header.alg` mismatch exception to `invalid algorithm` and adding more mismatch tests. + + As `jws@3.0.0` changed the verify method signature to be `jws.verify(signature, algorithm, secretOrKey)`, the token header must be decoded first in order to make sure that the `alg` field matches one of the allowed `options.algorithms`. After that, the now validated `header.alg` is passed to `jws.verify` + + As the order of steps has changed, the error that was thrown when the JWT was invalid is no longer the `jws` one: + ``` + { [Error: Invalid token: no header in signature 'a.b.c'] code: 'MISSING_HEADER', signature: 'a.b.c' } + ``` + + That old error (removed from jws) has been replaced by a `JsonWebTokenError` with message `invalid token`. + + > Important: versions >= 4.2.2 this library are safe to use but we decided to deprecate everything `< 5.0.0` to prevent security warnings from library `node-jws` when doing `npm install`. + + https://github.com/auth0/node-jsonwebtoken/commit/634b8ed0ff5267dc25da5c808634208af109824e + https://github.com/auth0/node-jsonwebtoken/commit/9f24ffd5791febb449d4d03ff58d7807da9b9b7e + https://github.com/auth0/node-jsonwebtoken/commit/19e6cc6a1f2fd90356f89b074223b9665f2aa8a2 + https://github.com/auth0/node-jsonwebtoken/commit/1e4623420159c6410616f02a44ed240f176287a9 + https://github.com/auth0/node-jsonwebtoken/commit/954bd7a312934f03036b6bb6f00edd41f29e54d9 + https://github.com/auth0/node-jsonwebtoken/commit/24a370080e0b75f11d4717cd2b11b2949d95fc2e + https://github.com/auth0/node-jsonwebtoken/commit/a77df6d49d4ec688dfd0a1cc723586bffe753516 + +## [4.2.2] - 2015-03-26 +### Fixed + + - [asymmetric-keys] Fix verify for RSAPublicKey formated keys (`jfromaniello - awlayton`) + https://github.com/auth0/node-jsonwebtoken/commit/402794663b9521bf602fcc6f2e811e7d3912f9dc + https://github.com/auth0/node-jsonwebtoken/commit/8df6aabbc7e1114c8fb3917931078254eb52c222 + +## [4.2.1] - 2015-03-17 +### Fixed + + - [asymmetric-keys] Fixed issue when public key starts with BEING PUBLIC KEY (https://github.com/auth0/node-jsonwebtoken/issues/70) (`jfromaniello`) + https://github.com/auth0/node-jsonwebtoken/commit/7017e74db9b194448ff488b3e16468ada60c4ee5 + +## [4.2.0] - 2015-03-16 +### Security + + - [asymmetric-keys] Making sure a token signed with an asymmetric key will be verified using a asymmetric key. + When the verification part was expecting a token digitally signed with an asymmetric key (RS/ES family) of algorithms an attacker could send a token signed with a symmetric algorithm (HS* family). + + The issue was caused because the same signature was used to verify both type of tokens (`verify` method parameter: `secretOrPublicKey`). + + This change adds a new parameter to the verify called `algorithms`. This can be used to specify a list of supported algorithms, but the default value depends on the secret used: if the secretOrPublicKey contains the string `BEGIN CERTIFICATE` the default is `[ 'RS256','RS384','RS512','ES256','ES384','ES512' ]` otherwise is `[ 'HS256','HS384','HS512' ]`. (`jfromaniello`) + https://github.com/auth0/node-jsonwebtoken/commit/c2bf7b2cd7e8daf66298c2d168a008690bc4bdd3 + https://github.com/auth0/node-jsonwebtoken/commit/1bb584bc382295eeb7ee8c4452a673a77a68b687 + +## [4.1.0] - 2015-03-10 +### Changed +- Assume the payload is JSON even when there is no `typ` property. [5290db1](https://github.com/auth0/node-jsonwebtoken/commit/5290db1bd74f74cd38c90b19e2355ef223a4d931) + +## [4.0.0] - 2015-03-06 +### Changed +- The default encoding is now utf8 instead of binary. [92d33bd](https://github.com/auth0/node-jsonwebtoken/commit/92d33bd99a3416e9e5a8897d9ad8ff7d70a00bfd) +- Add `encoding` as a new option to `sign`. [1fc385e](https://github.com/auth0/node-jsonwebtoken/commit/1fc385ee10bd0018cd1441552dce6c2e5a16375f) +- Add `ignoreExpiration` to `verify`. [8d4da27](https://github.com/auth0/node-jsonwebtoken/commit/8d4da279e1b351ac71ace276285c9255186d549f) +- Add `expiresInSeconds` to `sign`. [dd156cc](https://github.com/auth0/node-jsonwebtoken/commit/dd156cc30f17028744e60aec0502897e34609329) + +### Fixed +- Fix wrong error message when the audience doesn't match. [44e3c8d](https://github.com/auth0/node-jsonwebtoken/commit/44e3c8d757e6b4e2a57a69a035f26b4abec3e327) +- Fix wrong error message when the issuer doesn't match. [44e3c8d](https://github.com/auth0/node-jsonwebtoken/commit/44e3c8d757e6b4e2a57a69a035f26b4abec3e327) +- Fix wrong `iat` and `exp` values when signing with `noTimestamp`. [331b7bc](https://github.com/auth0/node-jsonwebtoken/commit/331b7bc9cc335561f8806f2c4558e105cb53e0a6) diff --git a/node_modules/jsonwebtoken/LICENSE b/node_modules/jsonwebtoken/LICENSE new file mode 100644 index 0000000..bcd1854 --- /dev/null +++ b/node_modules/jsonwebtoken/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Auth0, Inc. (http://auth0.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/jsonwebtoken/README.md b/node_modules/jsonwebtoken/README.md new file mode 100644 index 0000000..f966435 --- /dev/null +++ b/node_modules/jsonwebtoken/README.md @@ -0,0 +1,375 @@ +# jsonwebtoken + +| **Build** | **Dependency** | +|-----------|---------------| +| [![Build Status](https://secure.travis-ci.org/auth0/node-jsonwebtoken.svg?branch=master)](http://travis-ci.org/auth0/node-jsonwebtoken) | [![Dependency Status](https://david-dm.org/auth0/node-jsonwebtoken.svg)](https://david-dm.org/auth0/node-jsonwebtoken) | + + +An implementation of [JSON Web Tokens](https://tools.ietf.org/html/rfc7519). + +This was developed against `draft-ietf-oauth-json-web-token-08`. It makes use of [node-jws](https://github.com/brianloveswords/node-jws) + +# Install + +```bash +$ npm install jsonwebtoken +``` + +# Migration notes + +* [From v7 to v8](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v7-to-v8) + +# Usage + +### jwt.sign(payload, secretOrPrivateKey, [options, callback]) + +(Asynchronous) If a callback is supplied, the callback is called with the `err` or the JWT. + +(Synchronous) Returns the JsonWebToken as string + +`payload` could be an object literal, buffer or string representing valid JSON. +> **Please _note_ that** `exp` or any other claim is only set if the payload is an object literal. Buffer or string payloads are not checked for JSON validity. + +> If `payload` is not a buffer or a string, it will be coerced into a string using `JSON.stringify`. + +`secretOrPrivateKey` is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM +encoded private key for RSA and ECDSA. In case of a private key with passphrase an object `{ key, passphrase }` can be used (based on [crypto documentation](https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format)), in this case be sure you pass the `algorithm` option. + +`options`: + +* `algorithm` (default: `HS256`) +* `expiresIn`: expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms). + > Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`). +* `notBefore`: expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms). + > Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`). +* `audience` +* `issuer` +* `jwtid` +* `subject` +* `noTimestamp` +* `header` +* `keyid` +* `mutatePayload`: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token. + + + +> There are no default values for `expiresIn`, `notBefore`, `audience`, `subject`, `issuer`. These claims can also be provided in the payload directly with `exp`, `nbf`, `aud`, `sub` and `iss` respectively, but you **_can't_** include in both places. + +Remember that `exp`, `nbf` and `iat` are **NumericDate**, see related [Token Expiration (exp claim)](#token-expiration-exp-claim) + + +The header can be customized via the `options.header` object. + +Generated jwts will include an `iat` (issued at) claim by default unless `noTimestamp` is specified. If `iat` is inserted in the payload, it will be used instead of the real timestamp for calculating other things like `exp` given a timespan in `options.expiresIn`. + +Synchronous Sign with default (HMAC SHA256) + +```js +var jwt = require('jsonwebtoken'); +var token = jwt.sign({ foo: 'bar' }, 'shhhhh'); +``` + +Synchronous Sign with RSA SHA256 +```js +// sign with RSA SHA256 +var privateKey = fs.readFileSync('private.key'); +var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256'}); +``` + +Sign asynchronously +```js +jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }, function(err, token) { + console.log(token); +}); +``` + +Backdate a jwt 30 seconds +```js +var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh'); +``` + +#### Token Expiration (exp claim) + +The standard for JWT defines an `exp` claim for expiration. The expiration is represented as a **NumericDate**: + +> A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch", in which each day is accounted for by exactly 86400 seconds, other than that non-integer values can be represented. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular. + +This means that the `exp` field should contain the number of seconds since the epoch. + +Signing a token with 1 hour of expiration: + +```javascript +jwt.sign({ + exp: Math.floor(Date.now() / 1000) + (60 * 60), + data: 'foobar' +}, 'secret'); +``` + +Another way to generate a token like this with this library is: + +```javascript +jwt.sign({ + data: 'foobar' +}, 'secret', { expiresIn: 60 * 60 }); + +//or even better: + +jwt.sign({ + data: 'foobar' +}, 'secret', { expiresIn: '1h' }); +``` + +### jwt.verify(token, secretOrPublicKey, [options, callback]) + +(Asynchronous) If a callback is supplied, function acts asynchronously. The callback is called with the decoded payload if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will be called with the error. + +(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error. + +`token` is the JsonWebToken string + +`secretOrPublicKey` is a string or buffer containing either the secret for HMAC algorithms, or the PEM +encoded public key for RSA and ECDSA. +If `jwt.verify` is called asynchronous, `secretOrPublicKey` can be a function that should fetch the secret or public key. See below for a detailed example + +As mentioned in [this comment](https://github.com/auth0/node-jsonwebtoken/issues/208#issuecomment-231861138), there are other libraries that expect base64 encoded secrets (random bytes encoded using base64), if that is your case you can pass `Buffer.from(secret, 'base64')`, by doing this the secret will be decoded using base64 and the token verification will use the original random bytes. + +`options` + +* `algorithms`: List of strings with the names of the allowed algorithms. For instance, `["HS256", "HS384"]`. +* `audience`: if you want to check audience (`aud`), provide a value here. The audience can be checked against a string, a regular expression or a list of strings and/or regular expressions. + > Eg: `"urn:foo"`, `/urn:f[o]{2}/`, `[/urn:f[o]{2}/, "urn:bar"]` +* `complete`: return an object with the decoded `{ payload, header, signature }` instead of only the usual content of the payload. +* `issuer` (optional): string or array of strings of valid values for the `iss` field. +* `ignoreExpiration`: if `true` do not validate the expiration of the token. +* `ignoreNotBefore`... +* `subject`: if you want to check subject (`sub`), provide a value here +* `clockTolerance`: number of seconds to tolerate when checking the `nbf` and `exp` claims, to deal with small clock differences among different servers +* `maxAge`: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms). + > Eg: `1000`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`). +* `clockTimestamp`: the time in seconds that should be used as the current time for all necessary comparisons. +* `nonce`: if you want to check `nonce` claim, provide a string value here. It is used on Open ID for the ID Tokens. ([Open ID implementation notes](https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes)) + + +```js +// verify a token symmetric - synchronous +var decoded = jwt.verify(token, 'shhhhh'); +console.log(decoded.foo) // bar + +// verify a token symmetric +jwt.verify(token, 'shhhhh', function(err, decoded) { + console.log(decoded.foo) // bar +}); + +// invalid token - synchronous +try { + var decoded = jwt.verify(token, 'wrong-secret'); +} catch(err) { + // err +} + +// invalid token +jwt.verify(token, 'wrong-secret', function(err, decoded) { + // err + // decoded undefined +}); + +// verify a token asymmetric +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, function(err, decoded) { + console.log(decoded.foo) // bar +}); + +// verify audience +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) { + // if audience mismatch, err == invalid audience +}); + +// verify issuer +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) { + // if issuer mismatch, err == invalid issuer +}); + +// verify jwt id +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid' }, function(err, decoded) { + // if jwt id mismatch, err == invalid jwt id +}); + +// verify subject +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid', subject: 'subject' }, function(err, decoded) { + // if subject mismatch, err == invalid subject +}); + +// alg mismatch +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) { + // if token alg != RS256, err == invalid signature +}); + +// Verify using getKey callback +// Example uses https://github.com/auth0/node-jwks-rsa as a way to fetch the keys. +var jwksClient = require('jwks-rsa'); +var client = jwksClient({ + jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json' +}); +function getKey(header, callback){ + client.getSigningKey(header.kid, function(err, key) { + var signingKey = key.publicKey || key.rsaPublicKey; + callback(null, signingKey); + }); +} + +jwt.verify(token, getKey, options, function(err, decoded) { + console.log(decoded.foo) // bar +}); + +``` + +### jwt.decode(token [, options]) + +(Synchronous) Returns the decoded payload without verifying if the signature is valid. + +> __Warning:__ This will __not__ verify whether the signature is valid. You should __not__ use this for untrusted messages. You most likely want to use `jwt.verify` instead. + +`token` is the JsonWebToken string + +`options`: + +* `json`: force JSON.parse on the payload even if the header doesn't contain `"typ":"JWT"`. +* `complete`: return an object with the decoded payload and header. + +Example + +```js +// get the decoded payload ignoring signature, no secretOrPrivateKey needed +var decoded = jwt.decode(token); + +// get the decoded payload and header +var decoded = jwt.decode(token, {complete: true}); +console.log(decoded.header); +console.log(decoded.payload) +``` + +## Errors & Codes +Possible thrown errors during verification. +Error is the first argument of the verification callback. + +### TokenExpiredError + +Thrown error if the token is expired. + +Error object: + +* name: 'TokenExpiredError' +* message: 'jwt expired' +* expiredAt: [ExpDate] + +```js +jwt.verify(token, 'shhhhh', function(err, decoded) { + if (err) { + /* + err = { + name: 'TokenExpiredError', + message: 'jwt expired', + expiredAt: 1408621000 + } + */ + } +}); +``` + +### JsonWebTokenError +Error object: + +* name: 'JsonWebTokenError' +* message: + * 'jwt malformed' + * 'jwt signature is required' + * 'invalid signature' + * 'jwt audience invalid. expected: [OPTIONS AUDIENCE]' + * 'jwt issuer invalid. expected: [OPTIONS ISSUER]' + * 'jwt id invalid. expected: [OPTIONS JWT ID]' + * 'jwt subject invalid. expected: [OPTIONS SUBJECT]' + +```js +jwt.verify(token, 'shhhhh', function(err, decoded) { + if (err) { + /* + err = { + name: 'JsonWebTokenError', + message: 'jwt malformed' + } + */ + } +}); +``` + +### NotBeforeError +Thrown if current time is before the nbf claim. + +Error object: + +* name: 'NotBeforeError' +* message: 'jwt not active' +* date: 2018-10-04T16:10:44.000Z + +```js +jwt.verify(token, 'shhhhh', function(err, decoded) { + if (err) { + /* + err = { + name: 'NotBeforeError', + message: 'jwt not active', + date: 2018-10-04T16:10:44.000Z + } + */ + } +}); +``` + + +## Algorithms supported + +Array of supported algorithms. The following algorithms are currently supported. + +alg Parameter Value | Digital Signature or MAC Algorithm +----------------|---------------------------- +HS256 | HMAC using SHA-256 hash algorithm +HS384 | HMAC using SHA-384 hash algorithm +HS512 | HMAC using SHA-512 hash algorithm +RS256 | RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm +RS384 | RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm +RS512 | RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm +PS256 | RSASSA-PSS using SHA-256 hash algorithm (only node ^6.12.0 OR >=8.0.0) +PS384 | RSASSA-PSS using SHA-384 hash algorithm (only node ^6.12.0 OR >=8.0.0) +PS512 | RSASSA-PSS using SHA-512 hash algorithm (only node ^6.12.0 OR >=8.0.0) +ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm +ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm +ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm +none | No digital signature or MAC value included + +## Refreshing JWTs + +First of all, we recommend you to think carefully if auto-refreshing a JWT will not introduce any vulnerability in your system. + +We are not comfortable including this as part of the library, however, you can take a look at [this example](https://gist.github.com/ziluvatar/a3feb505c4c0ec37059054537b38fc48) to show how this could be accomplished. +Apart from that example there are [an issue](https://github.com/auth0/node-jsonwebtoken/issues/122) and [a pull request](https://github.com/auth0/node-jsonwebtoken/pull/172) to get more knowledge about this topic. + +# TODO + +* X.509 certificate chain is not checked + +## Issue Reporting + +If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues. + +## Author + +[Auth0](https://auth0.com) + +## License + +This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info. diff --git a/node_modules/jsonwebtoken/decode.js b/node_modules/jsonwebtoken/decode.js new file mode 100644 index 0000000..8fe1adc --- /dev/null +++ b/node_modules/jsonwebtoken/decode.js @@ -0,0 +1,30 @@ +var jws = require('jws'); + +module.exports = function (jwt, options) { + options = options || {}; + var decoded = jws.decode(jwt, options); + if (!decoded) { return null; } + var payload = decoded.payload; + + //try parse the payload + if(typeof payload === 'string') { + try { + var obj = JSON.parse(payload); + if(obj !== null && typeof obj === 'object') { + payload = obj; + } + } catch (e) { } + } + + //return header if `complete` option is enabled. header includes claims + //such as `kid` and `alg` used to select the key within a JWKS needed to + //verify the signature + if (options.complete === true) { + return { + header: decoded.header, + payload: payload, + signature: decoded.signature + }; + } + return payload; +}; diff --git a/node_modules/jsonwebtoken/index.js b/node_modules/jsonwebtoken/index.js new file mode 100644 index 0000000..161eb2d --- /dev/null +++ b/node_modules/jsonwebtoken/index.js @@ -0,0 +1,8 @@ +module.exports = { + decode: require('./decode'), + verify: require('./verify'), + sign: require('./sign'), + JsonWebTokenError: require('./lib/JsonWebTokenError'), + NotBeforeError: require('./lib/NotBeforeError'), + TokenExpiredError: require('./lib/TokenExpiredError'), +}; diff --git a/node_modules/jsonwebtoken/lib/JsonWebTokenError.js b/node_modules/jsonwebtoken/lib/JsonWebTokenError.js new file mode 100644 index 0000000..e068222 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/JsonWebTokenError.js @@ -0,0 +1,14 @@ +var JsonWebTokenError = function (message, error) { + Error.call(this, message); + if(Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = 'JsonWebTokenError'; + this.message = message; + if (error) this.inner = error; +}; + +JsonWebTokenError.prototype = Object.create(Error.prototype); +JsonWebTokenError.prototype.constructor = JsonWebTokenError; + +module.exports = JsonWebTokenError; diff --git a/node_modules/jsonwebtoken/lib/NotBeforeError.js b/node_modules/jsonwebtoken/lib/NotBeforeError.js new file mode 100644 index 0000000..7b30084 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/NotBeforeError.js @@ -0,0 +1,13 @@ +var JsonWebTokenError = require('./JsonWebTokenError'); + +var NotBeforeError = function (message, date) { + JsonWebTokenError.call(this, message); + this.name = 'NotBeforeError'; + this.date = date; +}; + +NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); + +NotBeforeError.prototype.constructor = NotBeforeError; + +module.exports = NotBeforeError; \ No newline at end of file diff --git a/node_modules/jsonwebtoken/lib/TokenExpiredError.js b/node_modules/jsonwebtoken/lib/TokenExpiredError.js new file mode 100644 index 0000000..abb704f --- /dev/null +++ b/node_modules/jsonwebtoken/lib/TokenExpiredError.js @@ -0,0 +1,13 @@ +var JsonWebTokenError = require('./JsonWebTokenError'); + +var TokenExpiredError = function (message, expiredAt) { + JsonWebTokenError.call(this, message); + this.name = 'TokenExpiredError'; + this.expiredAt = expiredAt; +}; + +TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); + +TokenExpiredError.prototype.constructor = TokenExpiredError; + +module.exports = TokenExpiredError; \ No newline at end of file diff --git a/node_modules/jsonwebtoken/lib/psSupported.js b/node_modules/jsonwebtoken/lib/psSupported.js new file mode 100644 index 0000000..8c04144 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/psSupported.js @@ -0,0 +1,3 @@ +var semver = require('semver'); + +module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0'); diff --git a/node_modules/jsonwebtoken/lib/timespan.js b/node_modules/jsonwebtoken/lib/timespan.js new file mode 100644 index 0000000..e509869 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/timespan.js @@ -0,0 +1,18 @@ +var ms = require('ms'); + +module.exports = function (time, iat) { + var timestamp = iat || Math.floor(Date.now() / 1000); + + if (typeof time === 'string') { + var milliseconds = ms(time); + if (typeof milliseconds === 'undefined') { + return; + } + return Math.floor(timestamp + milliseconds / 1000); + } else if (typeof time === 'number') { + return timestamp + time; + } else { + return; + } + +}; \ No newline at end of file diff --git a/node_modules/jsonwebtoken/node_modules/.bin/semver b/node_modules/jsonwebtoken/node_modules/.bin/semver new file mode 100644 index 0000000..86cee84 --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/.bin/semver @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../semver/bin/semver" "$@" +else + exec node "$basedir/../semver/bin/semver" "$@" +fi diff --git a/node_modules/jsonwebtoken/node_modules/.bin/semver.cmd b/node_modules/jsonwebtoken/node_modules/.bin/semver.cmd new file mode 100644 index 0000000..22d9286 --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/.bin/semver.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver" %* diff --git a/node_modules/jsonwebtoken/node_modules/.bin/semver.ps1 b/node_modules/jsonwebtoken/node_modules/.bin/semver.ps1 new file mode 100644 index 0000000..98c1b09 --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/.bin/semver.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../semver/bin/semver" $args + } else { + & "$basedir/node$exe" "$basedir/../semver/bin/semver" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../semver/bin/semver" $args + } else { + & "node$exe" "$basedir/../semver/bin/semver" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/jsonwebtoken/node_modules/ms/index.js b/node_modules/jsonwebtoken/node_modules/ms/index.js new file mode 100644 index 0000000..ea734fb --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/jsonwebtoken/node_modules/ms/license.md b/node_modules/jsonwebtoken/node_modules/ms/license.md new file mode 100644 index 0000000..fa5d39b --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jsonwebtoken/node_modules/ms/package.json b/node_modules/jsonwebtoken/node_modules/ms/package.json new file mode 100644 index 0000000..4997189 --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/node_modules/jsonwebtoken/node_modules/ms/readme.md b/node_modules/jsonwebtoken/node_modules/ms/readme.md new file mode 100644 index 0000000..0fc1abb --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/jsonwebtoken/node_modules/semver/CHANGELOG.md b/node_modules/jsonwebtoken/node_modules/semver/CHANGELOG.md new file mode 100644 index 0000000..66304fd --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/semver/CHANGELOG.md @@ -0,0 +1,39 @@ +# changes log + +## 5.7 + +* Add `minVersion` method + +## 5.6 + +* Move boolean `loose` param to an options object, with + backwards-compatibility protection. +* Add ability to opt out of special prerelease version handling with + the `includePrerelease` option flag. + +## 5.5 + +* Add version coercion capabilities + +## 5.4 + +* Add intersection checking + +## 5.3 + +* Add `minSatisfying` method + +## 5.2 + +* Add `prerelease(v)` that returns prerelease components + +## 5.1 + +* Add Backus-Naur for ranges +* Remove excessively cute inspection methods + +## 5.0 + +* Remove AMD/Browserified build artifacts +* Fix ltr and gtr when using the `*` range +* Fix for range `*` with a prerelease identifier diff --git a/node_modules/jsonwebtoken/node_modules/semver/LICENSE b/node_modules/jsonwebtoken/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/jsonwebtoken/node_modules/semver/README.md b/node_modules/jsonwebtoken/node_modules/semver/README.md new file mode 100644 index 0000000..f8dfa5a --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/semver/README.md @@ -0,0 +1,412 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install --save semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero digit in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). diff --git a/node_modules/jsonwebtoken/node_modules/semver/bin/semver b/node_modules/jsonwebtoken/node_modules/semver/bin/semver new file mode 100644 index 0000000..801e77f --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/semver/bin/semver @@ -0,0 +1,160 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + +var versions = [] + +var range = [] + +var inc = null + +var version = require('../package.json').version + +var loose = false + +var includePrerelease = false + +var coerce = false + +var identifier + +var semver = require('../semver') + +var reverse = false + +var options = {} + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + var options = { loose: loose, includePrerelease: includePrerelease } + + versions = versions.map(function (v) { + return coerce ? (semver.coerce(v) || { version: v }).version : v + }).filter(function (v) { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (var i = 0, l = range.length; i < l; i++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error('--inc can only be used on a single version with no range') + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? 'rcompare' : 'compare' + versions.sort(function (a, b) { + return semver[compare](a, b, options) + }).map(function (v) { + return semver.clean(v, options) + }).map(function (v) { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach(function (v, i, _) { console.log(v) }) +} + +function help () { + console.log(['SemVer ' + version, + '', + 'A JavaScript implementation of the https://semver.org/ specification', + 'Copyright Isaac Z. Schlueter', + '', + 'Usage: semver [options] [ [...]]', + 'Prints valid versions sorted by SemVer precedence', + '', + 'Options:', + '-r --range ', + ' Print versions that match the specified range.', + '', + '-i --increment []', + ' Increment a version by the specified level. Level can', + ' be one of: major, minor, patch, premajor, preminor,', + " prepatch, or prerelease. Default level is 'patch'.", + ' Only one version may be specified.', + '', + '--preid ', + ' Identifier to be used to prefix premajor, preminor,', + ' prepatch or prerelease version increments.', + '', + '-l --loose', + ' Interpret versions and ranges loosely', + '', + '-p --include-prerelease', + ' Always include prerelease versions in range matching', + '', + '-c --coerce', + ' Coerce a string into SemVer if possible', + ' (does not imply --loose)', + '', + 'Program exits successfully if any valid version satisfies', + 'all supplied ranges, and prints all satisfying versions.', + '', + 'If no satisfying versions are found, then exits failure.', + '', + 'Versions are printed in ascending order, so supplying', + 'multiple versions to the utility will just sort them.' + ].join('\n')) +} diff --git a/node_modules/jsonwebtoken/node_modules/semver/package.json b/node_modules/jsonwebtoken/node_modules/semver/package.json new file mode 100644 index 0000000..69d2db1 --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/semver/package.json @@ -0,0 +1,28 @@ +{ + "name": "semver", + "version": "5.7.1", + "description": "The semantic version parser used by npm.", + "main": "semver.js", + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "devDependencies": { + "tap": "^13.0.0-rc.18" + }, + "license": "ISC", + "repository": "https://github.com/npm/node-semver", + "bin": { + "semver": "./bin/semver" + }, + "files": [ + "bin", + "range.bnf", + "semver.js" + ], + "tap": { + "check-coverage": true + } +} diff --git a/node_modules/jsonwebtoken/node_modules/semver/range.bnf b/node_modules/jsonwebtoken/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/jsonwebtoken/node_modules/semver/semver.js b/node_modules/jsonwebtoken/node_modules/semver/semver.js new file mode 100644 index 0000000..d315d5d --- /dev/null +++ b/node_modules/jsonwebtoken/node_modules/semver/semver.js @@ -0,0 +1,1483 @@ +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var R = 0 + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' + +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' + +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' + +src[FULL] = '^' + FULLPLAIN + '$' + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?' + +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' + +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++ +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +var XRANGEIDENTIFIER = R++ +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' + +var XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++ +src[LONETILDE] = '(?:~>?)' + +var TILDETRIM = R++ +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') +var tildeTrimReplace = '$1~' + +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' + +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +var caretTrimReplace = '$1^' + +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++ +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' +var COMPARATOR = R++ +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++ +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++ +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$' + +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? re[LOOSE] : re[FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} + +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} + +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + this.operator = m[1] + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY) { + return true + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + var rangeTmp + + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options) + } + + if (!(this instanceof Range)) { + return new Range(range, options) + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } + + this.format() +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} + +Range.prototype.toString = function () { + return this.range +} + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) + + return set +} + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) +} + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} + +function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} + +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[CARETLOOSE] : re[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } + + debug('caret return', ret) + return ret + }) +} + +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} + +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + ret = gtlt + M + '.' + m + '.' + p + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], '') +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } + + return (from + ' ' + to).trim() +} + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} + +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} + +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} + +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} + +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} + +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + var high = null + var low = null + + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} + +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + var match = version.match(re[COERCE]) + + if (match == null) { + return null + } + + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) +} diff --git a/node_modules/jsonwebtoken/package.json b/node_modules/jsonwebtoken/package.json new file mode 100644 index 0000000..81d63da --- /dev/null +++ b/node_modules/jsonwebtoken/package.json @@ -0,0 +1,71 @@ +{ + "name": "jsonwebtoken", + "version": "8.5.1", + "description": "JSON Web Token implementation (symmetric and asymmetric)", + "main": "index.js", + "nyc": { + "check-coverage": true, + "lines": 95, + "statements": 95, + "functions": 100, + "branches": 95, + "exclude": [ + "./test/**" + ], + "reporter": [ + "json", + "lcov", + "text-summary" + ] + }, + "scripts": { + "lint": "eslint .", + "coverage": "nyc mocha --use_strict", + "test": "npm run lint && npm run coverage && cost-of-modules" + }, + "repository": { + "type": "git", + "url": "https://github.com/auth0/node-jsonwebtoken" + }, + "keywords": [ + "jwt" + ], + "author": "auth0", + "license": "MIT", + "bugs": { + "url": "https://github.com/auth0/node-jsonwebtoken/issues" + }, + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + }, + "devDependencies": { + "atob": "^2.1.2", + "chai": "^4.1.2", + "conventional-changelog": "~1.1.0", + "cost-of-modules": "^1.0.1", + "eslint": "^4.19.1", + "mocha": "^5.2.0", + "nsp": "^2.6.2", + "nyc": "^11.9.0", + "sinon": "^6.0.0" + }, + "engines": { + "npm": ">=1.4.28", + "node": ">=4" + }, + "files": [ + "lib", + "decode.js", + "sign.js", + "verify.js" + ] +} diff --git a/node_modules/jsonwebtoken/sign.js b/node_modules/jsonwebtoken/sign.js new file mode 100644 index 0000000..f649ce4 --- /dev/null +++ b/node_modules/jsonwebtoken/sign.js @@ -0,0 +1,206 @@ +var timespan = require('./lib/timespan'); +var PS_SUPPORTED = require('./lib/psSupported'); +var jws = require('jws'); +var includes = require('lodash.includes'); +var isBoolean = require('lodash.isboolean'); +var isInteger = require('lodash.isinteger'); +var isNumber = require('lodash.isnumber'); +var isPlainObject = require('lodash.isplainobject'); +var isString = require('lodash.isstring'); +var once = require('lodash.once'); + +var SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'] +if (PS_SUPPORTED) { + SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +} + +var sign_options_schema = { + expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' }, + notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' }, + audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' }, + algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, + header: { isValid: isPlainObject, message: '"header" must be an object' }, + encoding: { isValid: isString, message: '"encoding" must be a string' }, + issuer: { isValid: isString, message: '"issuer" must be a string' }, + subject: { isValid: isString, message: '"subject" must be a string' }, + jwtid: { isValid: isString, message: '"jwtid" must be a string' }, + noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, + keyid: { isValid: isString, message: '"keyid" must be a string' }, + mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' } +}; + +var registered_claims_schema = { + iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, + exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, + nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } +}; + +function validate(schema, allowUnknown, object, parameterName) { + if (!isPlainObject(object)) { + throw new Error('Expected "' + parameterName + '" to be a plain object.'); + } + Object.keys(object) + .forEach(function(key) { + var validator = schema[key]; + if (!validator) { + if (!allowUnknown) { + throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); + } + return; + } + if (!validator.isValid(object[key])) { + throw new Error(validator.message); + } + }); +} + +function validateOptions(options) { + return validate(sign_options_schema, false, options, 'options'); +} + +function validatePayload(payload) { + return validate(registered_claims_schema, true, payload, 'payload'); +} + +var options_to_payload = { + 'audience': 'aud', + 'issuer': 'iss', + 'subject': 'sub', + 'jwtid': 'jti' +}; + +var options_for_objects = [ + 'expiresIn', + 'notBefore', + 'noTimestamp', + 'audience', + 'issuer', + 'subject', + 'jwtid', +]; + +module.exports = function (payload, secretOrPrivateKey, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else { + options = options || {}; + } + + var isObjectPayload = typeof payload === 'object' && + !Buffer.isBuffer(payload); + + var header = Object.assign({ + alg: options.algorithm || 'HS256', + typ: isObjectPayload ? 'JWT' : undefined, + kid: options.keyid + }, options.header); + + function failure(err) { + if (callback) { + return callback(err); + } + throw err; + } + + if (!secretOrPrivateKey && options.algorithm !== 'none') { + return failure(new Error('secretOrPrivateKey must have a value')); + } + + if (typeof payload === 'undefined') { + return failure(new Error('payload is required')); + } else if (isObjectPayload) { + try { + validatePayload(payload); + } + catch (error) { + return failure(error); + } + if (!options.mutatePayload) { + payload = Object.assign({},payload); + } + } else { + var invalid_options = options_for_objects.filter(function (opt) { + return typeof options[opt] !== 'undefined'; + }); + + if (invalid_options.length > 0) { + return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload')); + } + } + + if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') { + return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); + } + + if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { + return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); + } + + try { + validateOptions(options); + } + catch (error) { + return failure(error); + } + + var timestamp = payload.iat || Math.floor(Date.now() / 1000); + + if (options.noTimestamp) { + delete payload.iat; + } else if (isObjectPayload) { + payload.iat = timestamp; + } + + if (typeof options.notBefore !== 'undefined') { + try { + payload.nbf = timespan(options.notBefore, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.nbf === 'undefined') { + return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } + + if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { + try { + payload.exp = timespan(options.expiresIn, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.exp === 'undefined') { + return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } + + Object.keys(options_to_payload).forEach(function (key) { + var claim = options_to_payload[key]; + if (typeof options[key] !== 'undefined') { + if (typeof payload[claim] !== 'undefined') { + return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); + } + payload[claim] = options[key]; + } + }); + + var encoding = options.encoding || 'utf8'; + + if (typeof callback === 'function') { + callback = callback && once(callback); + + jws.createSign({ + header: header, + privateKey: secretOrPrivateKey, + payload: payload, + encoding: encoding + }).once('error', callback) + .once('done', function (signature) { + callback(null, signature); + }); + } else { + return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding}); + } +}; diff --git a/node_modules/jsonwebtoken/verify.js b/node_modules/jsonwebtoken/verify.js new file mode 100644 index 0000000..1df99f8 --- /dev/null +++ b/node_modules/jsonwebtoken/verify.js @@ -0,0 +1,225 @@ +var JsonWebTokenError = require('./lib/JsonWebTokenError'); +var NotBeforeError = require('./lib/NotBeforeError'); +var TokenExpiredError = require('./lib/TokenExpiredError'); +var decode = require('./decode'); +var timespan = require('./lib/timespan'); +var PS_SUPPORTED = require('./lib/psSupported'); +var jws = require('jws'); + +var PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512']; +var RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512']; +var HS_ALGS = ['HS256', 'HS384', 'HS512']; + +if (PS_SUPPORTED) { + PUB_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); + RSA_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +} + +module.exports = function (jwtString, secretOrPublicKey, options, callback) { + if ((typeof options === 'function') && !callback) { + callback = options; + options = {}; + } + + if (!options) { + options = {}; + } + + //clone this object since we are going to mutate it. + options = Object.assign({}, options); + + var done; + + if (callback) { + done = callback; + } else { + done = function(err, data) { + if (err) throw err; + return data; + }; + } + + if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') { + return done(new JsonWebTokenError('clockTimestamp must be a number')); + } + + if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) { + return done(new JsonWebTokenError('nonce must be a non-empty string')); + } + + var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000); + + if (!jwtString){ + return done(new JsonWebTokenError('jwt must be provided')); + } + + if (typeof jwtString !== 'string') { + return done(new JsonWebTokenError('jwt must be a string')); + } + + var parts = jwtString.split('.'); + + if (parts.length !== 3){ + return done(new JsonWebTokenError('jwt malformed')); + } + + var decodedToken; + + try { + decodedToken = decode(jwtString, { complete: true }); + } catch(err) { + return done(err); + } + + if (!decodedToken) { + return done(new JsonWebTokenError('invalid token')); + } + + var header = decodedToken.header; + var getSecret; + + if(typeof secretOrPublicKey === 'function') { + if(!callback) { + return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback')); + } + + getSecret = secretOrPublicKey; + } + else { + getSecret = function(header, secretCallback) { + return secretCallback(null, secretOrPublicKey); + }; + } + + return getSecret(header, function(err, secretOrPublicKey) { + if(err) { + return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message)); + } + + var hasSignature = parts[2].trim() !== ''; + + if (!hasSignature && secretOrPublicKey){ + return done(new JsonWebTokenError('jwt signature is required')); + } + + if (hasSignature && !secretOrPublicKey) { + return done(new JsonWebTokenError('secret or public key must be provided')); + } + + if (!hasSignature && !options.algorithms) { + options.algorithms = ['none']; + } + + if (!options.algorithms) { + options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') || + ~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ? PUB_KEY_ALGS : + ~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ? RSA_KEY_ALGS : HS_ALGS; + + } + + if (!~options.algorithms.indexOf(decodedToken.header.alg)) { + return done(new JsonWebTokenError('invalid algorithm')); + } + + var valid; + + try { + valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey); + } catch (e) { + return done(e); + } + + if (!valid) { + return done(new JsonWebTokenError('invalid signature')); + } + + var payload = decodedToken.payload; + + if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) { + if (typeof payload.nbf !== 'number') { + return done(new JsonWebTokenError('invalid nbf value')); + } + if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) { + return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000))); + } + } + + if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) { + if (typeof payload.exp !== 'number') { + return done(new JsonWebTokenError('invalid exp value')); + } + if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000))); + } + } + + if (options.audience) { + var audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; + var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; + + var match = target.some(function (targetAudience) { + return audiences.some(function (audience) { + return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience; + }); + }); + + if (!match) { + return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or '))); + } + } + + if (options.issuer) { + var invalid_issuer = + (typeof options.issuer === 'string' && payload.iss !== options.issuer) || + (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1); + + if (invalid_issuer) { + return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer)); + } + } + + if (options.subject) { + if (payload.sub !== options.subject) { + return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject)); + } + } + + if (options.jwtid) { + if (payload.jti !== options.jwtid) { + return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid)); + } + } + + if (options.nonce) { + if (payload.nonce !== options.nonce) { + return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce)); + } + } + + if (options.maxAge) { + if (typeof payload.iat !== 'number') { + return done(new JsonWebTokenError('iat required when maxAge is specified')); + } + + var maxAgeTimestamp = timespan(options.maxAge, payload.iat); + if (typeof maxAgeTimestamp === 'undefined') { + return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000))); + } + } + + if (options.complete === true) { + var signature = decodedToken.signature; + + return done(null, { + header: header, + payload: payload, + signature: signature + }); + } + + return done(null, payload); + }); +}; diff --git a/node_modules/jwa/LICENSE b/node_modules/jwa/LICENSE new file mode 100644 index 0000000..caeb849 --- /dev/null +++ b/node_modules/jwa/LICENSE @@ -0,0 +1,17 @@ +Copyright (c) 2013 Brian J. Brennan + +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/jwa/README.md b/node_modules/jwa/README.md new file mode 100644 index 0000000..fb433e2 --- /dev/null +++ b/node_modules/jwa/README.md @@ -0,0 +1,150 @@ +# node-jwa [![Build Status](https://travis-ci.org/brianloveswords/node-jwa.svg?branch=master)](https://travis-ci.org/brianloveswords/node-jwa) + +A +[JSON Web Algorithms](http://tools.ietf.org/id/draft-ietf-jose-json-web-algorithms-08.html) +implementation focusing (exclusively, at this point) on the algorithms necessary for +[JSON Web Signatures](http://self-issued.info/docs/draft-ietf-jose-json-web-signature.html). + +This library supports all of the required, recommended and optional cryptographic algorithms for JWS: + +alg Parameter Value | Digital Signature or MAC Algorithm +----------------|---------------------------- +HS256 | HMAC using SHA-256 hash algorithm +HS384 | HMAC using SHA-384 hash algorithm +HS512 | HMAC using SHA-512 hash algorithm +RS256 | RSASSA using SHA-256 hash algorithm +RS384 | RSASSA using SHA-384 hash algorithm +RS512 | RSASSA using SHA-512 hash algorithm +PS256 | RSASSA-PSS using SHA-256 hash algorithm +PS384 | RSASSA-PSS using SHA-384 hash algorithm +PS512 | RSASSA-PSS using SHA-512 hash algorithm +ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm +ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm +ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm +none | No digital signature or MAC value included + +Please note that PS* only works on Node 6.12+ (excluding 7.x). + +# Requirements + +In order to run the tests, a recent version of OpenSSL is +required. **The version that comes with OS X (OpenSSL 0.9.8r 8 Feb +2011) is not recent enough**, as it does not fully support ECDSA +keys. You'll need to use a version > 1.0.0; I tested with OpenSSL 1.0.1c 10 May 2012. + +# Testing + +To run the tests, do + +```bash +$ npm test +``` + +This will generate a bunch of keypairs to use in testing. If you want to +generate new keypairs, do `make clean` before running `npm test` again. + +## Methodology + +I spawn `openssl dgst -sign` to test OpenSSL sign → JS verify and +`openssl dgst -verify` to test JS sign → OpenSSL verify for each of the +RSA and ECDSA algorithms. + +# Usage + +## jwa(algorithm) + +Creates a new `jwa` object with `sign` and `verify` methods for the +algorithm. Valid values for algorithm can be found in the table above +(`'HS256'`, `'HS384'`, etc) and are case-insensitive. Passing an invalid +algorithm value will throw a `TypeError`. + + +## jwa#sign(input, secretOrPrivateKey) + +Sign some input with either a secret for HMAC algorithms, or a private +key for RSA and ECDSA algorithms. + +If input is not already a string or buffer, `JSON.stringify` will be +called on it to attempt to coerce it. + +For the HMAC algorithm, `secretOrPrivateKey` should be a string or a +buffer. For ECDSA and RSA, the value should be a string representing a +PEM encoded **private** key. + +Output [base64url](http://en.wikipedia.org/wiki/Base64#URL_applications) +formatted. This is for convenience as JWS expects the signature in this +format. If your application needs the output in a different format, +[please open an issue](https://github.com/brianloveswords/node-jwa/issues). In +the meantime, you can use +[brianloveswords/base64url](https://github.com/brianloveswords/base64url) +to decode the signature. + +As of nodejs *v0.11.8*, SPKAC support was introduce. If your nodeJs +version satisfies, then you can pass an object `{ key: '..', passphrase: '...' }` + + +## jwa#verify(input, signature, secretOrPublicKey) + +Verify a signature. Returns `true` or `false`. + +`signature` should be a base64url encoded string. + +For the HMAC algorithm, `secretOrPublicKey` should be a string or a +buffer. For ECDSA and RSA, the value should be a string represented a +PEM encoded **public** key. + + +# Example + +HMAC +```js +const jwa = require('jwa'); + +const hmac = jwa('HS256'); +const input = 'super important stuff'; +const secret = 'shhhhhh'; + +const signature = hmac.sign(input, secret); +hmac.verify(input, signature, secret) // === true +hmac.verify(input, signature, 'trickery!') // === false +``` + +With keys +```js +const fs = require('fs'); +const jwa = require('jwa'); +const privateKey = fs.readFileSync(__dirname + '/ecdsa-p521-private.pem'); +const publicKey = fs.readFileSync(__dirname + '/ecdsa-p521-public.pem'); + +const ecdsa = jwa('ES512'); +const input = 'very important stuff'; + +const signature = ecdsa.sign(input, privateKey); +ecdsa.verify(input, signature, publicKey) // === true +``` +## License + +MIT + +``` +Copyright (c) 2013 Brian J. Brennan + +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/jwa/index.js b/node_modules/jwa/index.js new file mode 100644 index 0000000..e71e6d1 --- /dev/null +++ b/node_modules/jwa/index.js @@ -0,0 +1,252 @@ +var bufferEqual = require('buffer-equal-constant-time'); +var Buffer = require('safe-buffer').Buffer; +var crypto = require('crypto'); +var formatEcdsa = require('ecdsa-sig-formatter'); +var util = require('util'); + +var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' +var MSG_INVALID_SECRET = 'secret must be a string or buffer'; +var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; +var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; + +var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; +if (supportsKeyObjects) { + MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; + MSG_INVALID_SECRET += 'or a KeyObject'; +} + +function checkIsPublicKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.type !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.asymmetricKeyType !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } +}; + +function checkIsPrivateKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (typeof key === 'object') { + return; + } + + throw typeError(MSG_INVALID_SIGNER_KEY); +}; + +function checkIsSecretKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return key; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_SECRET); + } + + if (key.type !== 'secret') { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_SECRET); + } +} + +function fromBase64(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function toBase64(base64url) { + base64url = base64url.toString(); + + var padding = 4 - base64url.length % 4; + if (padding !== 4) { + for (var i = 0; i < padding; ++i) { + base64url += '='; + } + } + + return base64url + .replace(/\-/g, '+') + .replace(/_/g, '/'); +} + +function typeError(template) { + var args = [].slice.call(arguments, 1); + var errMsg = util.format.bind(util, template).apply(null, args); + return new TypeError(errMsg); +} + +function bufferOrString(obj) { + return Buffer.isBuffer(obj) || typeof obj === 'string'; +} + +function normalizeInput(thing) { + if (!bufferOrString(thing)) + thing = JSON.stringify(thing); + return thing; +} + +function createHmacSigner(bits) { + return function sign(thing, secret) { + checkIsSecretKey(secret); + thing = normalizeInput(thing); + var hmac = crypto.createHmac('sha' + bits, secret); + var sig = (hmac.update(thing), hmac.digest('base64')) + return fromBase64(sig); + } +} + +function createHmacVerifier(bits) { + return function verify(thing, signature, secret) { + var computedSig = createHmacSigner(bits)(thing, secret); + return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); + } +} + +function createKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + // Even though we are specifying "RSA" here, this works with ECDSA + // keys as well. + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); + return fromBase64(sig); + } +} + +function createKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify(publicKey, signature, 'base64'); + } +} + +function createPSSKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign({ + key: privateKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, 'base64')); + return fromBase64(sig); + } +} + +function createPSSKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify({ + key: publicKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, signature, 'base64'); + } +} + +function createECDSASigner(bits) { + var inner = createKeySigner(bits); + return function sign() { + var signature = inner.apply(null, arguments); + signature = formatEcdsa.derToJose(signature, 'ES' + bits); + return signature; + }; +} + +function createECDSAVerifer(bits) { + var inner = createKeyVerifier(bits); + return function verify(thing, signature, publicKey) { + signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); + var result = inner(thing, signature, publicKey); + return result; + }; +} + +function createNoneSigner() { + return function sign() { + return ''; + } +} + +function createNoneVerifier() { + return function verify(thing, signature) { + return signature === ''; + } +} + +module.exports = function jwa(algorithm) { + var signerFactories = { + hs: createHmacSigner, + rs: createKeySigner, + ps: createPSSKeySigner, + es: createECDSASigner, + none: createNoneSigner, + } + var verifierFactories = { + hs: createHmacVerifier, + rs: createKeyVerifier, + ps: createPSSKeyVerifier, + es: createECDSAVerifer, + none: createNoneVerifier, + } + var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i); + if (!match) + throw typeError(MSG_INVALID_ALGORITHM, algorithm); + var algo = (match[1] || match[3]).toLowerCase(); + var bits = match[2]; + + return { + sign: signerFactories[algo](bits), + verify: verifierFactories[algo](bits), + } +}; diff --git a/node_modules/jwa/package.json b/node_modules/jwa/package.json new file mode 100644 index 0000000..0777d53 --- /dev/null +++ b/node_modules/jwa/package.json @@ -0,0 +1,37 @@ +{ + "name": "jwa", + "version": "1.4.1", + "description": "JWA implementation (supports all JWS algorithms)", + "main": "index.js", + "directories": { + "test": "test" + }, + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + }, + "devDependencies": { + "base64url": "^2.0.0", + "jwk-to-pem": "^2.0.1", + "semver": "4.3.6", + "tap": "6.2.0" + }, + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/brianloveswords/node-jwa.git" + }, + "keywords": [ + "jwa", + "jws", + "jwt", + "rsa", + "ecdsa", + "hmac" + ], + "author": "Brian J. Brennan ", + "license": "MIT" +} diff --git a/node_modules/jws/CHANGELOG.md b/node_modules/jws/CHANGELOG.md new file mode 100644 index 0000000..af8fc28 --- /dev/null +++ b/node_modules/jws/CHANGELOG.md @@ -0,0 +1,34 @@ +# Change Log +All notable changes to this project will be documented in this file. + +## [3.0.0] +### Changed +- **BREAKING**: `jwt.verify` now requires an `algorithm` parameter, and + `jws.createVerify` requires an `algorithm` option. The `"alg"` field + signature headers is ignored. This mitigates a critical security flaw + in the library which would allow an attacker to generate signatures with + arbitrary contents that would be accepted by `jwt.verify`. See + https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/ + for details. + +## [2.0.0] - 2015-01-30 +### Changed +- **BREAKING**: Default payload encoding changed from `binary` to + `utf8`. `utf8` is a is a more sensible default than `binary` because + many payloads, as far as I can tell, will contain user-facing + strings that could be in any language. ([6b6de48]) + +- Code reorganization, thanks [@fearphage]! ([7880050]) + +### Added +- Option in all relevant methods for `encoding`. For those few users + that might be depending on a `binary` encoding of the messages, this + is for them. ([6b6de48]) + +[unreleased]: https://github.com/brianloveswords/node-jws/compare/v2.0.0...HEAD +[2.0.0]: https://github.com/brianloveswords/node-jws/compare/v1.0.1...v2.0.0 + +[7880050]: https://github.com/brianloveswords/node-jws/commit/7880050 +[6b6de48]: https://github.com/brianloveswords/node-jws/commit/6b6de48 + +[@fearphage]: https://github.com/fearphage diff --git a/node_modules/jws/LICENSE b/node_modules/jws/LICENSE new file mode 100644 index 0000000..caeb849 --- /dev/null +++ b/node_modules/jws/LICENSE @@ -0,0 +1,17 @@ +Copyright (c) 2013 Brian J. Brennan + +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/jws/index.js b/node_modules/jws/index.js new file mode 100644 index 0000000..8c8da93 --- /dev/null +++ b/node_modules/jws/index.js @@ -0,0 +1,22 @@ +/*global exports*/ +var SignStream = require('./lib/sign-stream'); +var VerifyStream = require('./lib/verify-stream'); + +var ALGORITHMS = [ + 'HS256', 'HS384', 'HS512', + 'RS256', 'RS384', 'RS512', + 'PS256', 'PS384', 'PS512', + 'ES256', 'ES384', 'ES512' +]; + +exports.ALGORITHMS = ALGORITHMS; +exports.sign = SignStream.sign; +exports.verify = VerifyStream.verify; +exports.decode = VerifyStream.decode; +exports.isValid = VerifyStream.isValid; +exports.createSign = function createSign(opts) { + return new SignStream(opts); +}; +exports.createVerify = function createVerify(opts) { + return new VerifyStream(opts); +}; diff --git a/node_modules/jws/lib/data-stream.js b/node_modules/jws/lib/data-stream.js new file mode 100644 index 0000000..3535d31 --- /dev/null +++ b/node_modules/jws/lib/data-stream.js @@ -0,0 +1,55 @@ +/*global module, process*/ +var Buffer = require('safe-buffer').Buffer; +var Stream = require('stream'); +var util = require('util'); + +function DataStream(data) { + this.buffer = null; + this.writable = true; + this.readable = true; + + // No input + if (!data) { + this.buffer = Buffer.alloc(0); + return this; + } + + // Stream + if (typeof data.pipe === 'function') { + this.buffer = Buffer.alloc(0); + data.pipe(this); + return this; + } + + // Buffer or String + // or Object (assumedly a passworded key) + if (data.length || typeof data === 'object') { + this.buffer = data; + this.writable = false; + process.nextTick(function () { + this.emit('end', data); + this.readable = false; + this.emit('close'); + }.bind(this)); + return this; + } + + throw new TypeError('Unexpected data type ('+ typeof data + ')'); +} +util.inherits(DataStream, Stream); + +DataStream.prototype.write = function write(data) { + this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); + this.emit('data', data); +}; + +DataStream.prototype.end = function end(data) { + if (data) + this.write(data); + this.emit('end', data); + this.emit('close'); + this.writable = false; + this.readable = false; +}; + +module.exports = DataStream; diff --git a/node_modules/jws/lib/sign-stream.js b/node_modules/jws/lib/sign-stream.js new file mode 100644 index 0000000..6a7ee42 --- /dev/null +++ b/node_modules/jws/lib/sign-stream.js @@ -0,0 +1,78 @@ +/*global module*/ +var Buffer = require('safe-buffer').Buffer; +var DataStream = require('./data-stream'); +var jwa = require('jwa'); +var Stream = require('stream'); +var toString = require('./tostring'); +var util = require('util'); + +function base64url(string, encoding) { + return Buffer + .from(string, encoding) + .toString('base64') + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function jwsSecuredInput(header, payload, encoding) { + encoding = encoding || 'utf8'; + var encodedHeader = base64url(toString(header), 'binary'); + var encodedPayload = base64url(toString(payload), encoding); + return util.format('%s.%s', encodedHeader, encodedPayload); +} + +function jwsSign(opts) { + var header = opts.header; + var payload = opts.payload; + var secretOrKey = opts.secret || opts.privateKey; + var encoding = opts.encoding; + var algo = jwa(header.alg); + var securedInput = jwsSecuredInput(header, payload, encoding); + var signature = algo.sign(securedInput, secretOrKey); + return util.format('%s.%s', securedInput, signature); +} + +function SignStream(opts) { + var secret = opts.secret||opts.privateKey||opts.key; + var secretStream = new DataStream(secret); + this.readable = true; + this.header = opts.header; + this.encoding = opts.encoding; + this.secret = this.privateKey = this.key = secretStream; + this.payload = new DataStream(opts.payload); + this.secret.once('close', function () { + if (!this.payload.writable && this.readable) + this.sign(); + }.bind(this)); + + this.payload.once('close', function () { + if (!this.secret.writable && this.readable) + this.sign(); + }.bind(this)); +} +util.inherits(SignStream, Stream); + +SignStream.prototype.sign = function sign() { + try { + var signature = jwsSign({ + header: this.header, + payload: this.payload.buffer, + secret: this.secret.buffer, + encoding: this.encoding + }); + this.emit('done', signature); + this.emit('data', signature); + this.emit('end'); + this.readable = false; + return signature; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +SignStream.sign = jwsSign; + +module.exports = SignStream; diff --git a/node_modules/jws/lib/tostring.js b/node_modules/jws/lib/tostring.js new file mode 100644 index 0000000..f5a49a3 --- /dev/null +++ b/node_modules/jws/lib/tostring.js @@ -0,0 +1,10 @@ +/*global module*/ +var Buffer = require('buffer').Buffer; + +module.exports = function toString(obj) { + if (typeof obj === 'string') + return obj; + if (typeof obj === 'number' || Buffer.isBuffer(obj)) + return obj.toString(); + return JSON.stringify(obj); +}; diff --git a/node_modules/jws/lib/verify-stream.js b/node_modules/jws/lib/verify-stream.js new file mode 100644 index 0000000..39f7c73 --- /dev/null +++ b/node_modules/jws/lib/verify-stream.js @@ -0,0 +1,120 @@ +/*global module*/ +var Buffer = require('safe-buffer').Buffer; +var DataStream = require('./data-stream'); +var jwa = require('jwa'); +var Stream = require('stream'); +var toString = require('./tostring'); +var util = require('util'); +var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; + +function isObject(thing) { + return Object.prototype.toString.call(thing) === '[object Object]'; +} + +function safeJsonParse(thing) { + if (isObject(thing)) + return thing; + try { return JSON.parse(thing); } + catch (e) { return undefined; } +} + +function headerFromJWS(jwsSig) { + var encodedHeader = jwsSig.split('.', 1)[0]; + return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); +} + +function securedInputFromJWS(jwsSig) { + return jwsSig.split('.', 2).join('.'); +} + +function signatureFromJWS(jwsSig) { + return jwsSig.split('.')[2]; +} + +function payloadFromJWS(jwsSig, encoding) { + encoding = encoding || 'utf8'; + var payload = jwsSig.split('.')[1]; + return Buffer.from(payload, 'base64').toString(encoding); +} + +function isValidJws(string) { + return JWS_REGEX.test(string) && !!headerFromJWS(string); +} + +function jwsVerify(jwsSig, algorithm, secretOrKey) { + if (!algorithm) { + var err = new Error("Missing algorithm parameter for jws.verify"); + err.code = "MISSING_ALGORITHM"; + throw err; + } + jwsSig = toString(jwsSig); + var signature = signatureFromJWS(jwsSig); + var securedInput = securedInputFromJWS(jwsSig); + var algo = jwa(algorithm); + return algo.verify(securedInput, signature, secretOrKey); +} + +function jwsDecode(jwsSig, opts) { + opts = opts || {}; + jwsSig = toString(jwsSig); + + if (!isValidJws(jwsSig)) + return null; + + var header = headerFromJWS(jwsSig); + + if (!header) + return null; + + var payload = payloadFromJWS(jwsSig); + if (header.typ === 'JWT' || opts.json) + payload = JSON.parse(payload, opts.encoding); + + return { + header: header, + payload: payload, + signature: signatureFromJWS(jwsSig) + }; +} + +function VerifyStream(opts) { + opts = opts || {}; + var secretOrKey = opts.secret||opts.publicKey||opts.key; + var secretStream = new DataStream(secretOrKey); + this.readable = true; + this.algorithm = opts.algorithm; + this.encoding = opts.encoding; + this.secret = this.publicKey = this.key = secretStream; + this.signature = new DataStream(opts.signature); + this.secret.once('close', function () { + if (!this.signature.writable && this.readable) + this.verify(); + }.bind(this)); + + this.signature.once('close', function () { + if (!this.secret.writable && this.readable) + this.verify(); + }.bind(this)); +} +util.inherits(VerifyStream, Stream); +VerifyStream.prototype.verify = function verify() { + try { + var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); + var obj = jwsDecode(this.signature.buffer, this.encoding); + this.emit('done', valid, obj); + this.emit('data', valid); + this.emit('end'); + this.readable = false; + return valid; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +VerifyStream.decode = jwsDecode; +VerifyStream.isValid = isValidJws; +VerifyStream.verify = jwsVerify; + +module.exports = VerifyStream; diff --git a/node_modules/jws/package.json b/node_modules/jws/package.json new file mode 100644 index 0000000..3fb2837 --- /dev/null +++ b/node_modules/jws/package.json @@ -0,0 +1,34 @@ +{ + "name": "jws", + "version": "3.2.2", + "description": "Implementation of JSON Web Signatures", + "main": "index.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/brianloveswords/node-jws.git" + }, + "keywords": [ + "jws", + "json", + "web", + "signatures" + ], + "author": "Brian J Brennan", + "license": "MIT", + "readmeFilename": "readme.md", + "gitHead": "c0f6b27bcea5a2ad2e304d91c2e842e4076a6b03", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + }, + "devDependencies": { + "semver": "^5.1.0", + "tape": "~2.14.0" + } +} diff --git a/node_modules/jws/readme.md b/node_modules/jws/readme.md new file mode 100644 index 0000000..1910c9a --- /dev/null +++ b/node_modules/jws/readme.md @@ -0,0 +1,255 @@ +# node-jws [![Build Status](https://secure.travis-ci.org/brianloveswords/node-jws.png)](http://travis-ci.org/brianloveswords/node-jws) + +An implementation of [JSON Web Signatures](http://self-issued.info/docs/draft-ietf-jose-json-web-signature.html). + +This was developed against `draft-ietf-jose-json-web-signature-08` and +implements the entire spec **except** X.509 Certificate Chain +signing/verifying (patches welcome). + +There are both synchronous (`jws.sign`, `jws.verify`) and streaming +(`jws.createSign`, `jws.createVerify`) APIs. + +# Install + +```bash +$ npm install jws +``` + +# Usage + +## jws.ALGORITHMS + +Array of supported algorithms. The following algorithms are currently supported. + +alg Parameter Value | Digital Signature or MAC Algorithm +----------------|---------------------------- +HS256 | HMAC using SHA-256 hash algorithm +HS384 | HMAC using SHA-384 hash algorithm +HS512 | HMAC using SHA-512 hash algorithm +RS256 | RSASSA using SHA-256 hash algorithm +RS384 | RSASSA using SHA-384 hash algorithm +RS512 | RSASSA using SHA-512 hash algorithm +PS256 | RSASSA-PSS using SHA-256 hash algorithm +PS384 | RSASSA-PSS using SHA-384 hash algorithm +PS512 | RSASSA-PSS using SHA-512 hash algorithm +ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm +ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm +ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm +none | No digital signature or MAC value included + +## jws.sign(options) + +(Synchronous) Return a JSON Web Signature for a header and a payload. + +Options: + +* `header` +* `payload` +* `secret` or `privateKey` +* `encoding` (Optional, defaults to 'utf8') + +`header` must be an object with an `alg` property. `header.alg` must be +one a value found in `jws.ALGORITHMS`. See above for a table of +supported algorithms. + +If `payload` is not a buffer or a string, it will be coerced into a string +using `JSON.stringify`. + +Example + +```js +const signature = jws.sign({ + header: { alg: 'HS256' }, + payload: 'h. jon benjamin', + secret: 'has a van', +}); +``` + +## jws.verify(signature, algorithm, secretOrKey) + +(Synchronous) Returns `true` or `false` for whether a signature matches a +secret or key. + +`signature` is a JWS Signature. `header.alg` must be a value found in `jws.ALGORITHMS`. +See above for a table of supported algorithms. `secretOrKey` is a string or +buffer containing either the secret for HMAC algorithms, or the PEM +encoded public key for RSA and ECDSA. + +Note that the `"alg"` value from the signature header is ignored. + + +## jws.decode(signature) + +(Synchronous) Returns the decoded header, decoded payload, and signature +parts of the JWS Signature. + +Returns an object with three properties, e.g. +```js +{ header: { alg: 'HS256' }, + payload: 'h. jon benjamin', + signature: 'YOWPewyGHKu4Y_0M_vtlEnNlqmFOclqp4Hy6hVHfFT4' +} +``` + +## jws.createSign(options) + +Returns a new SignStream object. + +Options: + +* `header` (required) +* `payload` +* `key` || `privateKey` || `secret` +* `encoding` (Optional, defaults to 'utf8') + +Other than `header`, all options expect a string or a buffer when the +value is known ahead of time, or a stream for convenience. +`key`/`privateKey`/`secret` may also be an object when using an encrypted +private key, see the [crypto documentation][encrypted-key-docs]. + +Example: + +```js + +// This... +jws.createSign({ + header: { alg: 'RS256' }, + privateKey: privateKeyStream, + payload: payloadStream, +}).on('done', function(signature) { + // ... +}); + +// is equivalent to this: +const signer = jws.createSign({ + header: { alg: 'RS256' }, +}); +privateKeyStream.pipe(signer.privateKey); +payloadStream.pipe(signer.payload); +signer.on('done', function(signature) { + // ... +}); +``` + +## jws.createVerify(options) + +Returns a new VerifyStream object. + +Options: + +* `signature` +* `algorithm` +* `key` || `publicKey` || `secret` +* `encoding` (Optional, defaults to 'utf8') + +All options expect a string or a buffer when the value is known ahead of +time, or a stream for convenience. + +Example: + +```js + +// This... +jws.createVerify({ + publicKey: pubKeyStream, + signature: sigStream, +}).on('done', function(verified, obj) { + // ... +}); + +// is equivilant to this: +const verifier = jws.createVerify(); +pubKeyStream.pipe(verifier.publicKey); +sigStream.pipe(verifier.signature); +verifier.on('done', function(verified, obj) { + // ... +}); +``` + +## Class: SignStream + +A `Readable Stream` that emits a single data event (the calculated +signature) when done. + +### Event: 'done' +`function (signature) { }` + +### signer.payload + +A `Writable Stream` that expects the JWS payload. Do *not* use if you +passed a `payload` option to the constructor. + +Example: + +```js +payloadStream.pipe(signer.payload); +``` + +### signer.secret
signer.key
signer.privateKey + +A `Writable Stream`. Expects the JWS secret for HMAC, or the privateKey +for ECDSA and RSA. Do *not* use if you passed a `secret` or `key` option +to the constructor. + +Example: + +```js +privateKeyStream.pipe(signer.privateKey); +``` + +## Class: VerifyStream + +This is a `Readable Stream` that emits a single data event, the result +of whether or not that signature was valid. + +### Event: 'done' +`function (valid, obj) { }` + +`valid` is a boolean for whether or not the signature is valid. + +### verifier.signature + +A `Writable Stream` that expects a JWS Signature. Do *not* use if you +passed a `signature` option to the constructor. + +### verifier.secret
verifier.key
verifier.publicKey + +A `Writable Stream` that expects a public key or secret. Do *not* use if you +passed a `key` or `secret` option to the constructor. + +# TODO + +* It feels like there should be some convenience options/APIs for + defining the algorithm rather than having to define a header object + with `{ alg: 'ES512' }` or whatever every time. + +* X.509 support, ugh + +# License + +MIT + +``` +Copyright (c) 2013-2015 Brian J. Brennan + +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. +``` + +[encrypted-key-docs]: https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format diff --git a/node_modules/kareem/.travis.yml b/node_modules/kareem/.travis.yml new file mode 100644 index 0000000..0a388b9 --- /dev/null +++ b/node_modules/kareem/.travis.yml @@ -0,0 +1,12 @@ +language: node_js +node_js: + - "12" + - "10" + - "9" + - "8" + - "7" + - "6" + - "5" + - "4" +script: "npm run-script test-travis" +after_script: "npm install coveralls@2.10.0 && cat ./coverage/lcov.info | coveralls" diff --git a/node_modules/kareem/CHANGELOG.md b/node_modules/kareem/CHANGELOG.md new file mode 100644 index 0000000..b0cbb52 --- /dev/null +++ b/node_modules/kareem/CHANGELOG.md @@ -0,0 +1,793 @@ +# Changelog + + +## 2.3.2 (2020-12-08) + +* fix: handle sync errors in pre hooks if there are multiple hooks + + +## 2.3.0 (2018-09-24) + +* chore(release): 2.2.3 ([c8f2695](https://github.com/vkarpov15/kareem/commit/c8f2695)) +* chore(release): 2.2.4 ([a377a4f](https://github.com/vkarpov15/kareem/commit/a377a4f)) +* chore(release): 2.2.5 ([5a495e3](https://github.com/vkarpov15/kareem/commit/5a495e3)) +* fix(filter): copy async pres correctly with `filter()` ([1b1ed8a](https://github.com/vkarpov15/kareem/commit/1b1ed8a)), closes [Automattic/mongoose#3054](https://github.com/Automattic/mongoose/issues/3054) +* feat: add filter() function ([1f641f4](https://github.com/vkarpov15/kareem/commit/1f641f4)) +* feat: support storing options on pre and post hooks ([59220b9](https://github.com/vkarpov15/kareem/commit/59220b9)) + + + + +## 2.2.3 (2018-09-10) + +* chore: release 2.2.3 ([af653a3](https://github.com/vkarpov15/kareem/commit/af653a3)) + + + + +## 2.2.2 (2018-09-10) + +* chore: release 2.2.2 ([3f0144d](https://github.com/vkarpov15/kareem/commit/3f0144d)) +* fix: allow merge() to not clone ([e628d65](https://github.com/vkarpov15/kareem/commit/e628d65)) + + + + +## 2.2.1 (2018-06-05) + +* chore: release 2.2.1 ([4625a64](https://github.com/vkarpov15/kareem/commit/4625a64)) +* chore: remove lockfile from git ([7f3e4e6](https://github.com/vkarpov15/kareem/commit/7f3e4e6)) +* fix: handle numAsync correctly when merging ([fef8e7e](https://github.com/vkarpov15/kareem/commit/fef8e7e)) +* test: repro issue with not copying numAsync ([952d9db](https://github.com/vkarpov15/kareem/commit/952d9db)) + + + + +## 2.2.0 (2018-06-05) + +* chore: release 2.2.0 ([ff9ad03](https://github.com/vkarpov15/kareem/commit/ff9ad03)) +* fix: use maps instead of objects for _pres and _posts so `toString()` doesn't get reported as having ([55df303](https://github.com/vkarpov15/kareem/commit/55df303)), closes [Automattic/mongoose#6538](https://github.com/Automattic/mongoose/issues/6538) + + + + +## 2.1.0 (2018-05-16) + +* chore: release 2.1.0 ([ba5f1bc](https://github.com/vkarpov15/kareem/commit/ba5f1bc)) +* feat: add option to check wrapped function return value for promises ([c9d7dd1](https://github.com/vkarpov15/kareem/commit/c9d7dd1)) +* refactor: use const in wrap() ([0fc21f9](https://github.com/vkarpov15/kareem/commit/0fc21f9)) + + + + +## 2.0.7 (2018-04-28) + +* chore: release 2.0.7 ([0bf91e6](https://github.com/vkarpov15/kareem/commit/0bf91e6)) +* feat: add `hasHooks()` ([225f18d](https://github.com/vkarpov15/kareem/commit/225f18d)), closes [Automattic/mongoose#6385](https://github.com/Automattic/mongoose/issues/6385) + + + + +## 2.0.6 (2018-03-22) + +* chore: release 2.0.6 ([f3d406b](https://github.com/vkarpov15/kareem/commit/f3d406b)) +* fix(wrap): ensure fast path still wraps function in `nextTick()` for chaining ([7000494](https://github.com/vkarpov15/kareem/commit/7000494)), closes [Automattic/mongoose#6250](https://github.com/Automattic/mongoose/issues/6250) [dsanel/mongoose-delete#36](https://github.com/dsanel/mongoose-delete/issues/36) + + + + +## 2.0.5 (2018-02-22) + +* chore: release 2.0.5 ([3286612](https://github.com/vkarpov15/kareem/commit/3286612)) +* perf(createWrapper): don't create wrapper if there are no hooks ([5afc5b9](https://github.com/vkarpov15/kareem/commit/5afc5b9)), closes [Automattic/mongoose#6126](https://github.com/Automattic/mongoose/issues/6126) + + + + +## 2.0.4 (2018-02-08) + +* chore: release 2.0.4 ([2ab0293](https://github.com/vkarpov15/kareem/commit/2ab0293)) + + + + +## 2.0.3 (2018-02-01) + +* chore: release 2.0.3 ([3c1abe5](https://github.com/vkarpov15/kareem/commit/3c1abe5)) +* fix: use process.nextTick() re: Automattic/mongoose#6074 ([e5bfe33](https://github.com/vkarpov15/kareem/commit/e5bfe33)), closes [Automattic/mongoose#6074](https://github.com/Automattic/mongoose/issues/6074) + + + + +## 2.0.2 (2018-01-24) + +* chore: fix license ([a9d755c](https://github.com/vkarpov15/kareem/commit/a9d755c)), closes [#10](https://github.com/vkarpov15/kareem/issues/10) +* chore: release 2.0.2 ([fe87ab6](https://github.com/vkarpov15/kareem/commit/fe87ab6)) + + + + +## 2.0.1 (2018-01-09) + +* chore: release 2.0.1 with lockfile bump ([09c44fb](https://github.com/vkarpov15/kareem/commit/09c44fb)) + + + + +## 2.0.0 (2018-01-09) + +* chore: bump marked re: security ([cc564a9](https://github.com/vkarpov15/kareem/commit/cc564a9)) +* chore: release 2.0.0 ([f511d1c](https://github.com/vkarpov15/kareem/commit/f511d1c)) + + + + +## 2.0.0-rc5 (2017-12-23) + +* chore: fix build on node 4+5 ([6dac5a4](https://github.com/vkarpov15/kareem/commit/6dac5a4)) +* chore: fix built on node 4 + 5 again ([434ef0a](https://github.com/vkarpov15/kareem/commit/434ef0a)) +* chore: release 2.0.0-rc5 ([25a32ee](https://github.com/vkarpov15/kareem/commit/25a32ee)) + + + + +## 2.0.0-rc4 (2017-12-22) + +* chore: release 2.0.0-rc4 ([49fc083](https://github.com/vkarpov15/kareem/commit/49fc083)) +* BREAKING CHANGE: deduplicate when merging hooks re: Automattic/mongoose#2945 ([d458573](https://github.com/vkarpov15/kareem/commit/d458573)), closes [Automattic/mongoose#2945](https://github.com/Automattic/mongoose/issues/2945) + + + + +## 2.0.0-rc3 (2017-12-22) + +* chore: release 2.0.0-rc3 ([adaaa00](https://github.com/vkarpov15/kareem/commit/adaaa00)) +* feat: support returning promises from middleware functions ([05b4480](https://github.com/vkarpov15/kareem/commit/05b4480)), closes [Automattic/mongoose#3779](https://github.com/Automattic/mongoose/issues/3779) + + + + +## 2.0.0-rc2 (2017-12-21) + +* chore: release 2.0.0-rc2 ([76325fa](https://github.com/vkarpov15/kareem/commit/76325fa)) +* fix: ensure next() and done() run in next tick ([6c20684](https://github.com/vkarpov15/kareem/commit/6c20684)) + + + + +## 2.0.0-rc1 (2017-12-21) + +* chore: improve test coverage re: Automattic/mongoose#3232 ([7b45cf0](https://github.com/vkarpov15/kareem/commit/7b45cf0)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) +* chore: release 2.0.0-rc1 ([9b83f52](https://github.com/vkarpov15/kareem/commit/9b83f52)) +* BREAKING CHANGE: report sync exceptions as errors, only allow calling next() and done() once ([674adcc](https://github.com/vkarpov15/kareem/commit/674adcc)), closes [Automattic/mongoose#3483](https://github.com/Automattic/mongoose/issues/3483) + + + + +## 2.0.0-rc0 (2017-12-17) + +* chore: release 2.0.0-rc0 ([16b44b5](https://github.com/vkarpov15/kareem/commit/16b44b5)) +* BREAKING CHANGE: drop support for node < 4 ([9cbb8c7](https://github.com/vkarpov15/kareem/commit/9cbb8c7)) +* BREAKING CHANGE: remove useLegacyPost and add several new features ([6dd8531](https://github.com/vkarpov15/kareem/commit/6dd8531)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) + + + + +## 1.5.0 (2017-07-20) + +* chore: release 1.5.0 ([9c491a0](https://github.com/vkarpov15/kareem/commit/9c491a0)) +* fix: improve post error handlers results ([9928dd5](https://github.com/vkarpov15/kareem/commit/9928dd5)), closes [Automattic/mongoose#5466](https://github.com/Automattic/mongoose/issues/5466) + + + + +## 1.4.2 (2017-07-06) + +* chore: release 1.4.2 ([8d14ac5](https://github.com/vkarpov15/kareem/commit/8d14ac5)) +* fix: correct args re: Automattic/mongoose#5405 ([3f28ae6](https://github.com/vkarpov15/kareem/commit/3f28ae6)), closes [Automattic/mongoose#5405](https://github.com/Automattic/mongoose/issues/5405) + + + + +## 1.4.1 (2017-04-25) + +* chore: release 1.4.1 ([5ecf0c2](https://github.com/vkarpov15/kareem/commit/5ecf0c2)) +* fix: handle numAsyncPres with clone() ([c72e857](https://github.com/vkarpov15/kareem/commit/c72e857)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) +* test: repro #8 ([9b4d6b2](https://github.com/vkarpov15/kareem/commit/9b4d6b2)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) + + + + +## 1.4.0 (2017-04-19) + +* chore: release 1.4.0 ([101c5f5](https://github.com/vkarpov15/kareem/commit/101c5f5)) +* feat: add merge() function ([285325e](https://github.com/vkarpov15/kareem/commit/285325e)) + + + + +## 1.3.0 (2017-03-26) + +* chore: release 1.3.0 ([f3a9e50](https://github.com/vkarpov15/kareem/commit/f3a9e50)) +* feat: pass function args to execPre ([4dd466d](https://github.com/vkarpov15/kareem/commit/4dd466d)) + + + + +## 1.2.1 (2017-02-03) + +* chore: release 1.2.1 ([d97081f](https://github.com/vkarpov15/kareem/commit/d97081f)) +* fix: filter out _kareemIgnored args for error handlers re: Automattic/mongoose#4925 ([ddc7aeb](https://github.com/vkarpov15/kareem/commit/ddc7aeb)), closes [Automattic/mongoose#4925](https://github.com/Automattic/mongoose/issues/4925) +* fix: make error handlers handle errors in pre hooks ([af38033](https://github.com/vkarpov15/kareem/commit/af38033)), closes [Automattic/mongoose#4927](https://github.com/Automattic/mongoose/issues/4927) + + + + +## 1.2.0 (2017-01-02) + +* chore: release 1.2.0 ([033225c](https://github.com/vkarpov15/kareem/commit/033225c)) +* chore: upgrade deps ([f9e9a09](https://github.com/vkarpov15/kareem/commit/f9e9a09)) +* feat: add _kareemIgnore re: Automattic/mongoose#4836 ([7957771](https://github.com/vkarpov15/kareem/commit/7957771)), closes [Automattic/mongoose#4836](https://github.com/Automattic/mongoose/issues/4836) + + + + +## 1.1.5 (2016-12-13) + +* chore: release 1.1.5 ([1a9f684](https://github.com/vkarpov15/kareem/commit/1a9f684)) +* fix: correct field name ([04a0e9d](https://github.com/vkarpov15/kareem/commit/04a0e9d)) + + + + +## 1.1.4 (2016-12-09) + +* chore: release 1.1.4 ([ece401c](https://github.com/vkarpov15/kareem/commit/ece401c)) +* chore: run tests on node 6 ([e0cb1cb](https://github.com/vkarpov15/kareem/commit/e0cb1cb)) +* fix: only copy own properties in clone() ([dfe28ce](https://github.com/vkarpov15/kareem/commit/dfe28ce)), closes [#7](https://github.com/vkarpov15/kareem/issues/7) + + + + +## 1.1.3 (2016-06-27) + +* chore: release 1.1.3 ([87171c8](https://github.com/vkarpov15/kareem/commit/87171c8)) +* fix: couple more issues with arg processing ([c65f523](https://github.com/vkarpov15/kareem/commit/c65f523)) + + + + +## 1.1.2 (2016-06-27) + +* chore: release 1.1.2 ([8e102b6](https://github.com/vkarpov15/kareem/commit/8e102b6)) +* fix: add early return ([4feda4e](https://github.com/vkarpov15/kareem/commit/4feda4e)) + + + + +## 1.1.1 (2016-06-27) + +* chore: release 1.1.1 ([8bb3050](https://github.com/vkarpov15/kareem/commit/8bb3050)) +* fix: skip error handlers if no error ([0eb3a44](https://github.com/vkarpov15/kareem/commit/0eb3a44)) + + + + +## 1.1.0 (2016-05-11) + +* chore: release 1.1.0 ([85332d9](https://github.com/vkarpov15/kareem/commit/85332d9)) +* chore: test on node 4 and node 5 ([1faefa1](https://github.com/vkarpov15/kareem/commit/1faefa1)) +* 100% coverage again ([c9aee4e](https://github.com/vkarpov15/kareem/commit/c9aee4e)) +* add support for error post hooks ([d378113](https://github.com/vkarpov15/kareem/commit/d378113)) +* basic setup for sync hooks #4 ([55aa081](https://github.com/vkarpov15/kareem/commit/55aa081)), closes [#4](https://github.com/vkarpov15/kareem/issues/4) +* proof of concept for error handlers ([e4a07d9](https://github.com/vkarpov15/kareem/commit/e4a07d9)) +* refactor out handleWrapError helper ([b19af38](https://github.com/vkarpov15/kareem/commit/b19af38)) + + + + +## 1.0.1 (2015-05-10) + +* Fix #1 ([de60dc6](https://github.com/vkarpov15/kareem/commit/de60dc6)), closes [#1](https://github.com/vkarpov15/kareem/issues/1) +* release 1.0.1 ([6971088](https://github.com/vkarpov15/kareem/commit/6971088)) +* Run tests on iojs in travis ([adcd201](https://github.com/vkarpov15/kareem/commit/adcd201)) +* support legacy post hook behavior in wrap() ([23fa74c](https://github.com/vkarpov15/kareem/commit/23fa74c)) +* Use node 0.12 in travis ([834689d](https://github.com/vkarpov15/kareem/commit/834689d)) + + + + +## 1.0.0 (2015-01-28) + +* Tag 1.0.0 ([4c5a35a](https://github.com/vkarpov15/kareem/commit/4c5a35a)) + + + + +## 0.0.8 (2015-01-27) + +* Add clone function ([688bba7](https://github.com/vkarpov15/kareem/commit/688bba7)) +* Add jscs for style checking ([5c93149](https://github.com/vkarpov15/kareem/commit/5c93149)) +* Bump 0.0.8 ([03c0d2f](https://github.com/vkarpov15/kareem/commit/03c0d2f)) +* Fix jscs config, add gulp rules ([9989abf](https://github.com/vkarpov15/kareem/commit/9989abf)) +* fix Makefile typo ([1f7e61a](https://github.com/vkarpov15/kareem/commit/1f7e61a)) + + + + +## 0.0.7 (2015-01-04) + +* Bump 0.0.7 ([98ef173](https://github.com/vkarpov15/kareem/commit/98ef173)) +* fix LearnBoost/mongoose#2553 - use null instead of undefined for err ([9157b48](https://github.com/vkarpov15/kareem/commit/9157b48)), closes [LearnBoost/mongoose#2553](https://github.com/LearnBoost/mongoose/issues/2553) +* Regenerate docs ([2331cdf](https://github.com/vkarpov15/kareem/commit/2331cdf)) + + + + +## 0.0.6 (2015-01-01) + +* Update docs and bump 0.0.6 ([92c12a7](https://github.com/vkarpov15/kareem/commit/92c12a7)) + + + + +## 0.0.5 (2015-01-01) + +* Add coverage rule to Makefile ([825a91c](https://github.com/vkarpov15/kareem/commit/825a91c)) +* Add coveralls to README ([fb52369](https://github.com/vkarpov15/kareem/commit/fb52369)) +* Add coveralls to travis ([93f6f15](https://github.com/vkarpov15/kareem/commit/93f6f15)) +* Add createWrapper() function ([ea77741](https://github.com/vkarpov15/kareem/commit/ea77741)) +* Add istanbul code coverage ([6eceeef](https://github.com/vkarpov15/kareem/commit/6eceeef)) +* Add some more comments for examples ([c5b0c6f](https://github.com/vkarpov15/kareem/commit/c5b0c6f)) +* Add travis ([e6dcb06](https://github.com/vkarpov15/kareem/commit/e6dcb06)) +* Add travis badge to docs ([ad8c9b3](https://github.com/vkarpov15/kareem/commit/ad8c9b3)) +* Add wrap() tests, 100% coverage ([6945be4](https://github.com/vkarpov15/kareem/commit/6945be4)) +* Better test coverage for execPost ([d9ad539](https://github.com/vkarpov15/kareem/commit/d9ad539)) +* Bump 0.0.5 ([69875b1](https://github.com/vkarpov15/kareem/commit/69875b1)) +* Docs fix ([15b7098](https://github.com/vkarpov15/kareem/commit/15b7098)) +* Fix silly mistake in docs generation ([50373eb](https://github.com/vkarpov15/kareem/commit/50373eb)) +* Fix typo in readme ([fec4925](https://github.com/vkarpov15/kareem/commit/fec4925)) +* Linkify travis badge ([92b25fe](https://github.com/vkarpov15/kareem/commit/92b25fe)) +* Make travis run coverage ([747157b](https://github.com/vkarpov15/kareem/commit/747157b)) +* Move travis status badge ([d52e89b](https://github.com/vkarpov15/kareem/commit/d52e89b)) +* Quick fix for coverage ([50bbddb](https://github.com/vkarpov15/kareem/commit/50bbddb)) +* Typo fix ([adea794](https://github.com/vkarpov15/kareem/commit/adea794)) + + + + +## 0.0.4 (2014-12-13) + +* Bump 0.0.4, run docs generation ([51a15fe](https://github.com/vkarpov15/kareem/commit/51a15fe)) +* Use correct post parameters in wrap() ([9bb5da3](https://github.com/vkarpov15/kareem/commit/9bb5da3)) + + + + +## 0.0.3 (2014-12-12) + +* Add npm test script, fix small bug with args not getting passed through post ([49e3e68](https://github.com/vkarpov15/kareem/commit/49e3e68)) +* Bump 0.0.3 ([65621d8](https://github.com/vkarpov15/kareem/commit/65621d8)) +* Update readme ([901388b](https://github.com/vkarpov15/kareem/commit/901388b)) + + + + +## 0.0.2 (2014-12-12) + +* Add github repo and bump 0.0.2 ([59db8be](https://github.com/vkarpov15/kareem/commit/59db8be)) + + + + +## 0.0.1 (2014-12-12) + +* Add basic docs ([ad29ea4](https://github.com/vkarpov15/kareem/commit/ad29ea4)) +* Add pre hooks ([2ffc356](https://github.com/vkarpov15/kareem/commit/2ffc356)) +* Add wrap function ([68c540c](https://github.com/vkarpov15/kareem/commit/68c540c)) +* Bump to version 0.0.1 ([a4bfd68](https://github.com/vkarpov15/kareem/commit/a4bfd68)) +* Initial commit ([4002458](https://github.com/vkarpov15/kareem/commit/4002458)) +* Initial deposit ([98fc489](https://github.com/vkarpov15/kareem/commit/98fc489)) +* Post hooks ([395b67c](https://github.com/vkarpov15/kareem/commit/395b67c)) +* Some basic setup work ([82df75e](https://github.com/vkarpov15/kareem/commit/82df75e)) +* Support sync pre hooks ([1cc1b9f](https://github.com/vkarpov15/kareem/commit/1cc1b9f)) +* Update package.json description ([978da18](https://github.com/vkarpov15/kareem/commit/978da18)) + + + + +## 2.2.5 (2018-09-24) + + + + + +## 2.2.4 (2018-09-24) + + + + + +## 2.2.3 (2018-09-24) + +* fix(filter): copy async pres correctly with `filter()` ([1b1ed8a](https://github.com/vkarpov15/kareem/commit/1b1ed8a)), closes [Automattic/mongoose#3054](https://github.com/Automattic/mongoose/issues/3054) +* feat: add filter() function ([1f641f4](https://github.com/vkarpov15/kareem/commit/1f641f4)) +* feat: support storing options on pre and post hooks ([59220b9](https://github.com/vkarpov15/kareem/commit/59220b9)) + + + + +## 2.2.3 (2018-09-10) + +* chore: release 2.2.3 ([af653a3](https://github.com/vkarpov15/kareem/commit/af653a3)) + + + + +## 2.2.2 (2018-09-10) + +* chore: release 2.2.2 ([3f0144d](https://github.com/vkarpov15/kareem/commit/3f0144d)) +* fix: allow merge() to not clone ([e628d65](https://github.com/vkarpov15/kareem/commit/e628d65)) + + + + +## 2.2.1 (2018-06-05) + +* chore: release 2.2.1 ([4625a64](https://github.com/vkarpov15/kareem/commit/4625a64)) +* chore: remove lockfile from git ([7f3e4e6](https://github.com/vkarpov15/kareem/commit/7f3e4e6)) +* fix: handle numAsync correctly when merging ([fef8e7e](https://github.com/vkarpov15/kareem/commit/fef8e7e)) +* test: repro issue with not copying numAsync ([952d9db](https://github.com/vkarpov15/kareem/commit/952d9db)) + + + + +## 2.2.0 (2018-06-05) + +* chore: release 2.2.0 ([ff9ad03](https://github.com/vkarpov15/kareem/commit/ff9ad03)) +* fix: use maps instead of objects for _pres and _posts so `toString()` doesn't get reported as having ([55df303](https://github.com/vkarpov15/kareem/commit/55df303)), closes [Automattic/mongoose#6538](https://github.com/Automattic/mongoose/issues/6538) + + + + +## 2.1.0 (2018-05-16) + +* chore: release 2.1.0 ([ba5f1bc](https://github.com/vkarpov15/kareem/commit/ba5f1bc)) +* feat: add option to check wrapped function return value for promises ([c9d7dd1](https://github.com/vkarpov15/kareem/commit/c9d7dd1)) +* refactor: use const in wrap() ([0fc21f9](https://github.com/vkarpov15/kareem/commit/0fc21f9)) + + + + +## 2.0.7 (2018-04-28) + +* chore: release 2.0.7 ([0bf91e6](https://github.com/vkarpov15/kareem/commit/0bf91e6)) +* feat: add `hasHooks()` ([225f18d](https://github.com/vkarpov15/kareem/commit/225f18d)), closes [Automattic/mongoose#6385](https://github.com/Automattic/mongoose/issues/6385) + + + + +## 2.0.6 (2018-03-22) + +* chore: release 2.0.6 ([f3d406b](https://github.com/vkarpov15/kareem/commit/f3d406b)) +* fix(wrap): ensure fast path still wraps function in `nextTick()` for chaining ([7000494](https://github.com/vkarpov15/kareem/commit/7000494)), closes [Automattic/mongoose#6250](https://github.com/Automattic/mongoose/issues/6250) [dsanel/mongoose-delete#36](https://github.com/dsanel/mongoose-delete/issues/36) + + + + +## 2.0.5 (2018-02-22) + +* chore: release 2.0.5 ([3286612](https://github.com/vkarpov15/kareem/commit/3286612)) +* perf(createWrapper): don't create wrapper if there are no hooks ([5afc5b9](https://github.com/vkarpov15/kareem/commit/5afc5b9)), closes [Automattic/mongoose#6126](https://github.com/Automattic/mongoose/issues/6126) + + + + +## 2.0.4 (2018-02-08) + +* chore: release 2.0.4 ([2ab0293](https://github.com/vkarpov15/kareem/commit/2ab0293)) + + + + +## 2.0.3 (2018-02-01) + +* chore: release 2.0.3 ([3c1abe5](https://github.com/vkarpov15/kareem/commit/3c1abe5)) +* fix: use process.nextTick() re: Automattic/mongoose#6074 ([e5bfe33](https://github.com/vkarpov15/kareem/commit/e5bfe33)), closes [Automattic/mongoose#6074](https://github.com/Automattic/mongoose/issues/6074) + + + + +## 2.0.2 (2018-01-24) + +* chore: fix license ([a9d755c](https://github.com/vkarpov15/kareem/commit/a9d755c)), closes [#10](https://github.com/vkarpov15/kareem/issues/10) +* chore: release 2.0.2 ([fe87ab6](https://github.com/vkarpov15/kareem/commit/fe87ab6)) + + + + +## 2.0.1 (2018-01-09) + +* chore: release 2.0.1 with lockfile bump ([09c44fb](https://github.com/vkarpov15/kareem/commit/09c44fb)) + + + + +## 2.0.0 (2018-01-09) + +* chore: bump marked re: security ([cc564a9](https://github.com/vkarpov15/kareem/commit/cc564a9)) +* chore: release 2.0.0 ([f511d1c](https://github.com/vkarpov15/kareem/commit/f511d1c)) + + + + +## 2.0.0-rc5 (2017-12-23) + +* chore: fix build on node 4+5 ([6dac5a4](https://github.com/vkarpov15/kareem/commit/6dac5a4)) +* chore: fix built on node 4 + 5 again ([434ef0a](https://github.com/vkarpov15/kareem/commit/434ef0a)) +* chore: release 2.0.0-rc5 ([25a32ee](https://github.com/vkarpov15/kareem/commit/25a32ee)) + + + + +## 2.0.0-rc4 (2017-12-22) + +* chore: release 2.0.0-rc4 ([49fc083](https://github.com/vkarpov15/kareem/commit/49fc083)) +* BREAKING CHANGE: deduplicate when merging hooks re: Automattic/mongoose#2945 ([d458573](https://github.com/vkarpov15/kareem/commit/d458573)), closes [Automattic/mongoose#2945](https://github.com/Automattic/mongoose/issues/2945) + + + + +## 2.0.0-rc3 (2017-12-22) + +* chore: release 2.0.0-rc3 ([adaaa00](https://github.com/vkarpov15/kareem/commit/adaaa00)) +* feat: support returning promises from middleware functions ([05b4480](https://github.com/vkarpov15/kareem/commit/05b4480)), closes [Automattic/mongoose#3779](https://github.com/Automattic/mongoose/issues/3779) + + + + +## 2.0.0-rc2 (2017-12-21) + +* chore: release 2.0.0-rc2 ([76325fa](https://github.com/vkarpov15/kareem/commit/76325fa)) +* fix: ensure next() and done() run in next tick ([6c20684](https://github.com/vkarpov15/kareem/commit/6c20684)) + + + + +## 2.0.0-rc1 (2017-12-21) + +* chore: improve test coverage re: Automattic/mongoose#3232 ([7b45cf0](https://github.com/vkarpov15/kareem/commit/7b45cf0)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) +* chore: release 2.0.0-rc1 ([9b83f52](https://github.com/vkarpov15/kareem/commit/9b83f52)) +* BREAKING CHANGE: report sync exceptions as errors, only allow calling next() and done() once ([674adcc](https://github.com/vkarpov15/kareem/commit/674adcc)), closes [Automattic/mongoose#3483](https://github.com/Automattic/mongoose/issues/3483) + + + + +## 2.0.0-rc0 (2017-12-17) + +* chore: release 2.0.0-rc0 ([16b44b5](https://github.com/vkarpov15/kareem/commit/16b44b5)) +* BREAKING CHANGE: drop support for node < 4 ([9cbb8c7](https://github.com/vkarpov15/kareem/commit/9cbb8c7)) +* BREAKING CHANGE: remove useLegacyPost and add several new features ([6dd8531](https://github.com/vkarpov15/kareem/commit/6dd8531)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) + + + + +## 1.5.0 (2017-07-20) + +* chore: release 1.5.0 ([9c491a0](https://github.com/vkarpov15/kareem/commit/9c491a0)) +* fix: improve post error handlers results ([9928dd5](https://github.com/vkarpov15/kareem/commit/9928dd5)), closes [Automattic/mongoose#5466](https://github.com/Automattic/mongoose/issues/5466) + + + + +## 1.4.2 (2017-07-06) + +* chore: release 1.4.2 ([8d14ac5](https://github.com/vkarpov15/kareem/commit/8d14ac5)) +* fix: correct args re: Automattic/mongoose#5405 ([3f28ae6](https://github.com/vkarpov15/kareem/commit/3f28ae6)), closes [Automattic/mongoose#5405](https://github.com/Automattic/mongoose/issues/5405) + + + + +## 1.4.1 (2017-04-25) + +* chore: release 1.4.1 ([5ecf0c2](https://github.com/vkarpov15/kareem/commit/5ecf0c2)) +* fix: handle numAsyncPres with clone() ([c72e857](https://github.com/vkarpov15/kareem/commit/c72e857)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) +* test: repro #8 ([9b4d6b2](https://github.com/vkarpov15/kareem/commit/9b4d6b2)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) + + + + +## 1.4.0 (2017-04-19) + +* chore: release 1.4.0 ([101c5f5](https://github.com/vkarpov15/kareem/commit/101c5f5)) +* feat: add merge() function ([285325e](https://github.com/vkarpov15/kareem/commit/285325e)) + + + + +## 1.3.0 (2017-03-26) + +* chore: release 1.3.0 ([f3a9e50](https://github.com/vkarpov15/kareem/commit/f3a9e50)) +* feat: pass function args to execPre ([4dd466d](https://github.com/vkarpov15/kareem/commit/4dd466d)) + + + + +## 1.2.1 (2017-02-03) + +* chore: release 1.2.1 ([d97081f](https://github.com/vkarpov15/kareem/commit/d97081f)) +* fix: filter out _kareemIgnored args for error handlers re: Automattic/mongoose#4925 ([ddc7aeb](https://github.com/vkarpov15/kareem/commit/ddc7aeb)), closes [Automattic/mongoose#4925](https://github.com/Automattic/mongoose/issues/4925) +* fix: make error handlers handle errors in pre hooks ([af38033](https://github.com/vkarpov15/kareem/commit/af38033)), closes [Automattic/mongoose#4927](https://github.com/Automattic/mongoose/issues/4927) + + + + +## 1.2.0 (2017-01-02) + +* chore: release 1.2.0 ([033225c](https://github.com/vkarpov15/kareem/commit/033225c)) +* chore: upgrade deps ([f9e9a09](https://github.com/vkarpov15/kareem/commit/f9e9a09)) +* feat: add _kareemIgnore re: Automattic/mongoose#4836 ([7957771](https://github.com/vkarpov15/kareem/commit/7957771)), closes [Automattic/mongoose#4836](https://github.com/Automattic/mongoose/issues/4836) + + + + +## 1.1.5 (2016-12-13) + +* chore: release 1.1.5 ([1a9f684](https://github.com/vkarpov15/kareem/commit/1a9f684)) +* fix: correct field name ([04a0e9d](https://github.com/vkarpov15/kareem/commit/04a0e9d)) + + + + +## 1.1.4 (2016-12-09) + +* chore: release 1.1.4 ([ece401c](https://github.com/vkarpov15/kareem/commit/ece401c)) +* chore: run tests on node 6 ([e0cb1cb](https://github.com/vkarpov15/kareem/commit/e0cb1cb)) +* fix: only copy own properties in clone() ([dfe28ce](https://github.com/vkarpov15/kareem/commit/dfe28ce)), closes [#7](https://github.com/vkarpov15/kareem/issues/7) + + + + +## 1.1.3 (2016-06-27) + +* chore: release 1.1.3 ([87171c8](https://github.com/vkarpov15/kareem/commit/87171c8)) +* fix: couple more issues with arg processing ([c65f523](https://github.com/vkarpov15/kareem/commit/c65f523)) + + + + +## 1.1.2 (2016-06-27) + +* chore: release 1.1.2 ([8e102b6](https://github.com/vkarpov15/kareem/commit/8e102b6)) +* fix: add early return ([4feda4e](https://github.com/vkarpov15/kareem/commit/4feda4e)) + + + + +## 1.1.1 (2016-06-27) + +* chore: release 1.1.1 ([8bb3050](https://github.com/vkarpov15/kareem/commit/8bb3050)) +* fix: skip error handlers if no error ([0eb3a44](https://github.com/vkarpov15/kareem/commit/0eb3a44)) + + + + +## 1.1.0 (2016-05-11) + +* chore: release 1.1.0 ([85332d9](https://github.com/vkarpov15/kareem/commit/85332d9)) +* chore: test on node 4 and node 5 ([1faefa1](https://github.com/vkarpov15/kareem/commit/1faefa1)) +* 100% coverage again ([c9aee4e](https://github.com/vkarpov15/kareem/commit/c9aee4e)) +* add support for error post hooks ([d378113](https://github.com/vkarpov15/kareem/commit/d378113)) +* basic setup for sync hooks #4 ([55aa081](https://github.com/vkarpov15/kareem/commit/55aa081)), closes [#4](https://github.com/vkarpov15/kareem/issues/4) +* proof of concept for error handlers ([e4a07d9](https://github.com/vkarpov15/kareem/commit/e4a07d9)) +* refactor out handleWrapError helper ([b19af38](https://github.com/vkarpov15/kareem/commit/b19af38)) + + + + +## 1.0.1 (2015-05-10) + +* Fix #1 ([de60dc6](https://github.com/vkarpov15/kareem/commit/de60dc6)), closes [#1](https://github.com/vkarpov15/kareem/issues/1) +* release 1.0.1 ([6971088](https://github.com/vkarpov15/kareem/commit/6971088)) +* Run tests on iojs in travis ([adcd201](https://github.com/vkarpov15/kareem/commit/adcd201)) +* support legacy post hook behavior in wrap() ([23fa74c](https://github.com/vkarpov15/kareem/commit/23fa74c)) +* Use node 0.12 in travis ([834689d](https://github.com/vkarpov15/kareem/commit/834689d)) + + + + +## 1.0.0 (2015-01-28) + +* Tag 1.0.0 ([4c5a35a](https://github.com/vkarpov15/kareem/commit/4c5a35a)) + + + + +## 0.0.8 (2015-01-27) + +* Add clone function ([688bba7](https://github.com/vkarpov15/kareem/commit/688bba7)) +* Add jscs for style checking ([5c93149](https://github.com/vkarpov15/kareem/commit/5c93149)) +* Bump 0.0.8 ([03c0d2f](https://github.com/vkarpov15/kareem/commit/03c0d2f)) +* Fix jscs config, add gulp rules ([9989abf](https://github.com/vkarpov15/kareem/commit/9989abf)) +* fix Makefile typo ([1f7e61a](https://github.com/vkarpov15/kareem/commit/1f7e61a)) + + + + +## 0.0.7 (2015-01-04) + +* Bump 0.0.7 ([98ef173](https://github.com/vkarpov15/kareem/commit/98ef173)) +* fix LearnBoost/mongoose#2553 - use null instead of undefined for err ([9157b48](https://github.com/vkarpov15/kareem/commit/9157b48)), closes [LearnBoost/mongoose#2553](https://github.com/LearnBoost/mongoose/issues/2553) +* Regenerate docs ([2331cdf](https://github.com/vkarpov15/kareem/commit/2331cdf)) + + + + +## 0.0.6 (2015-01-01) + +* Update docs and bump 0.0.6 ([92c12a7](https://github.com/vkarpov15/kareem/commit/92c12a7)) + + + + +## 0.0.5 (2015-01-01) + +* Add coverage rule to Makefile ([825a91c](https://github.com/vkarpov15/kareem/commit/825a91c)) +* Add coveralls to README ([fb52369](https://github.com/vkarpov15/kareem/commit/fb52369)) +* Add coveralls to travis ([93f6f15](https://github.com/vkarpov15/kareem/commit/93f6f15)) +* Add createWrapper() function ([ea77741](https://github.com/vkarpov15/kareem/commit/ea77741)) +* Add istanbul code coverage ([6eceeef](https://github.com/vkarpov15/kareem/commit/6eceeef)) +* Add some more comments for examples ([c5b0c6f](https://github.com/vkarpov15/kareem/commit/c5b0c6f)) +* Add travis ([e6dcb06](https://github.com/vkarpov15/kareem/commit/e6dcb06)) +* Add travis badge to docs ([ad8c9b3](https://github.com/vkarpov15/kareem/commit/ad8c9b3)) +* Add wrap() tests, 100% coverage ([6945be4](https://github.com/vkarpov15/kareem/commit/6945be4)) +* Better test coverage for execPost ([d9ad539](https://github.com/vkarpov15/kareem/commit/d9ad539)) +* Bump 0.0.5 ([69875b1](https://github.com/vkarpov15/kareem/commit/69875b1)) +* Docs fix ([15b7098](https://github.com/vkarpov15/kareem/commit/15b7098)) +* Fix silly mistake in docs generation ([50373eb](https://github.com/vkarpov15/kareem/commit/50373eb)) +* Fix typo in readme ([fec4925](https://github.com/vkarpov15/kareem/commit/fec4925)) +* Linkify travis badge ([92b25fe](https://github.com/vkarpov15/kareem/commit/92b25fe)) +* Make travis run coverage ([747157b](https://github.com/vkarpov15/kareem/commit/747157b)) +* Move travis status badge ([d52e89b](https://github.com/vkarpov15/kareem/commit/d52e89b)) +* Quick fix for coverage ([50bbddb](https://github.com/vkarpov15/kareem/commit/50bbddb)) +* Typo fix ([adea794](https://github.com/vkarpov15/kareem/commit/adea794)) + + + + +## 0.0.4 (2014-12-13) + +* Bump 0.0.4, run docs generation ([51a15fe](https://github.com/vkarpov15/kareem/commit/51a15fe)) +* Use correct post parameters in wrap() ([9bb5da3](https://github.com/vkarpov15/kareem/commit/9bb5da3)) + + + + +## 0.0.3 (2014-12-12) + +* Add npm test script, fix small bug with args not getting passed through post ([49e3e68](https://github.com/vkarpov15/kareem/commit/49e3e68)) +* Bump 0.0.3 ([65621d8](https://github.com/vkarpov15/kareem/commit/65621d8)) +* Update readme ([901388b](https://github.com/vkarpov15/kareem/commit/901388b)) + + + + +## 0.0.2 (2014-12-12) + +* Add github repo and bump 0.0.2 ([59db8be](https://github.com/vkarpov15/kareem/commit/59db8be)) + + + + +## 0.0.1 (2014-12-12) + +* Add basic docs ([ad29ea4](https://github.com/vkarpov15/kareem/commit/ad29ea4)) +* Add pre hooks ([2ffc356](https://github.com/vkarpov15/kareem/commit/2ffc356)) +* Add wrap function ([68c540c](https://github.com/vkarpov15/kareem/commit/68c540c)) +* Bump to version 0.0.1 ([a4bfd68](https://github.com/vkarpov15/kareem/commit/a4bfd68)) +* Initial commit ([4002458](https://github.com/vkarpov15/kareem/commit/4002458)) +* Initial deposit ([98fc489](https://github.com/vkarpov15/kareem/commit/98fc489)) +* Post hooks ([395b67c](https://github.com/vkarpov15/kareem/commit/395b67c)) +* Some basic setup work ([82df75e](https://github.com/vkarpov15/kareem/commit/82df75e)) +* Support sync pre hooks ([1cc1b9f](https://github.com/vkarpov15/kareem/commit/1cc1b9f)) +* Update package.json description ([978da18](https://github.com/vkarpov15/kareem/commit/978da18)) diff --git a/node_modules/kareem/LICENSE b/node_modules/kareem/LICENSE new file mode 100644 index 0000000..e06d208 --- /dev/null +++ b/node_modules/kareem/LICENSE @@ -0,0 +1,202 @@ +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/kareem/Makefile b/node_modules/kareem/Makefile new file mode 100644 index 0000000..f71ba90 --- /dev/null +++ b/node_modules/kareem/Makefile @@ -0,0 +1,5 @@ +docs: + node ./docs.js + +coverage: + ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/* diff --git a/node_modules/kareem/README.md b/node_modules/kareem/README.md new file mode 100644 index 0000000..aaf8471 --- /dev/null +++ b/node_modules/kareem/README.md @@ -0,0 +1,420 @@ +# kareem + + [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem) + [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem) + +Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, meant to offer additional flexibility in allowing you to execute hooks whenever necessary, as opposed to simply wrapping a single function. + +Named for the NBA's all-time leading scorer Kareem Abdul-Jabbar, known for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook) + + + +# API + +## pre hooks + +Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define +pre and post hooks: pre hooks are called before a given function executes. +Unlike hooks, kareem stores hooks and other internal state in a separate +object, rather than relying on inheritance. Furthermore, kareem exposes +an `execPre()` function that allows you to execute your pre hooks when +appropriate, giving you more fine-grained control over your function hooks. + + +#### It runs without any hooks specified + +```javascript +hooks.execPre('cook', null, function() { + // ... +}); +``` + +#### It runs basic serial pre hooks + +pre hook functions take one parameter, a "done" function that you execute +when your pre hook is finished. + + +```javascript +var count = 0; + +hooks.pre('cook', function(done) { + ++count; + done(); +}); + +hooks.execPre('cook', null, function() { + assert.equal(1, count); +}); +``` + +#### It can run multipe pre hooks + +```javascript +var count1 = 0; +var count2 = 0; + +hooks.pre('cook', function(done) { + ++count1; + done(); +}); + +hooks.pre('cook', function(done) { + ++count2; + done(); +}); + +hooks.execPre('cook', null, function() { + assert.equal(1, count1); + assert.equal(1, count2); +}); +``` + +#### It can run fully synchronous pre hooks + +If your pre hook function takes no parameters, its assumed to be +fully synchronous. + + +```javascript +var count1 = 0; +var count2 = 0; + +hooks.pre('cook', function() { + ++count1; +}); + +hooks.pre('cook', function() { + ++count2; +}); + +hooks.execPre('cook', null, function(error) { + assert.equal(null, error); + assert.equal(1, count1); + assert.equal(1, count2); +}); +``` + +#### It properly attaches context to pre hooks + +Pre save hook functions are bound to the second parameter to `execPre()` + + +```javascript +hooks.pre('cook', function(done) { + this.bacon = 3; + done(); +}); + +hooks.pre('cook', function(done) { + this.eggs = 4; + done(); +}); + +var obj = { bacon: 0, eggs: 0 }; + +// In the pre hooks, `this` will refer to `obj` +hooks.execPre('cook', obj, function(error) { + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); +}); +``` + +#### It can execute parallel (async) pre hooks + +Like the hooks module, you can declare "async" pre hooks - these take two +parameters, the functions `next()` and `done()`. `next()` passes control to +the next pre hook, but the underlying function won't be called until all +async pre hooks have called `done()`. + + +```javascript +hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); +}); + +hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); +}); + +hooks.pre('cook', function(next) { + this.waffles = false; + next(); +}); + +var obj = { bacon: 0, eggs: 0 }; + +hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); +}); +``` + +#### It supports returning a promise + +You can also return a promise from your pre hooks instead of calling +`next()`. When the returned promise resolves, kareem will kick off the +next middleware. + + +```javascript +hooks.pre('cook', function() { + return new Promise(resolve => { + setTimeout(() => { + this.bacon = 3; + resolve(); + }, 100); + }); +}); + +var obj = { bacon: 0 }; + +hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); +}); +``` + +## post hooks + +acquit:ignore:end + +#### It runs without any hooks specified + +```javascript +hooks.execPost('cook', null, [1], function(error, eggs) { + assert.ifError(error); + assert.equal(1, eggs); + done(); +}); +``` + +#### It executes with parameters passed in + +```javascript +hooks.post('cook', function(eggs, bacon, callback) { + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); +}); + +hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(1, eggs); + assert.equal(2, bacon); +}); +``` + +#### It can use synchronous post hooks + +```javascript +var execed = {}; + +hooks.post('cook', function(eggs, bacon) { + execed.first = true; + assert.equal(1, eggs); + assert.equal(2, bacon); +}); + +hooks.post('cook', function(eggs, bacon, callback) { + execed.second = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); +}); + +hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.equal(1, eggs); + assert.equal(2, bacon); +}); +``` + +#### It supports returning a promise + +You can also return a promise from your post hooks instead of calling +`next()`. When the returned promise resolves, kareem will kick off the +next middleware. + + +```javascript +hooks.post('cook', function(bacon) { + return new Promise(resolve => { + setTimeout(() => { + this.bacon = 3; + resolve(); + }, 100); + }); +}); + +var obj = { bacon: 0 }; + +hooks.execPost('cook', obj, obj, function() { + assert.equal(obj.bacon, 3); +}); +``` + +## wrap() + +acquit:ignore:end + +#### It wraps pre and post calls into one call + +```javascript +hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); +}); + +hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); +}); + +hooks.pre('cook', function(next) { + this.waffles = false; + next(); +}); + +hooks.post('cook', function(obj) { + obj.tofu = 'no'; +}); + +var obj = { bacon: 0, eggs: 0 }; + +var args = [obj]; +args.push(function(error, result) { + assert.ifError(error); + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); +}); + +hooks.wrap( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj, + args); +``` + +## createWrapper() + +#### It wraps wrap() into a callable function + +```javascript +hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); +}); + +hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); +}); + +hooks.pre('cook', function(next) { + this.waffles = false; + next(); +}); + +hooks.post('cook', function(obj) { + obj.tofu = 'no'; +}); + +var obj = { bacon: 0, eggs: 0 }; + +var cook = hooks.createWrapper( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj); + +cook(obj, function(error, result) { + assert.ifError(error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); +}); +``` + +## clone() + +acquit:ignore:end + +#### It clones a Kareem object + +```javascript +var k1 = new Kareem(); +k1.pre('cook', function() {}); +k1.post('cook', function() {}); + +var k2 = k1.clone(); +assert.deepEqual(Array.from(k2._pres.keys()), ['cook']); +assert.deepEqual(Array.from(k2._posts.keys()), ['cook']); +``` + +## merge() + +#### It pulls hooks from another Kareem object + +```javascript +var k1 = new Kareem(); +var test1 = function() {}; +k1.pre('cook', test1); +k1.post('cook', function() {}); + +var k2 = new Kareem(); +var test2 = function() {}; +k2.pre('cook', test2); +var k3 = k2.merge(k1); +assert.equal(k3._pres.get('cook').length, 2); +assert.equal(k3._pres.get('cook')[0].fn, test2); +assert.equal(k3._pres.get('cook')[1].fn, test1); +assert.equal(k3._posts.get('cook').length, 1); +``` + diff --git a/node_modules/kareem/docs.js b/node_modules/kareem/docs.js new file mode 100644 index 0000000..85ae502 --- /dev/null +++ b/node_modules/kareem/docs.js @@ -0,0 +1,39 @@ +var acquit = require('acquit'); + +require('acquit-ignore')(); + +var content = require('fs').readFileSync('./test/examples.test.js').toString(); +var blocks = acquit.parse(content); + +var mdOutput = + '# kareem\n\n' + + ' [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem)\n' + + ' [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem)\n\n' + + 'Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, ' + + 'meant to offer additional flexibility in allowing you to execute hooks ' + + 'whenever necessary, as opposed to simply wrapping a single function.\n\n' + + 'Named for the NBA\'s all-time leading scorer Kareem Abdul-Jabbar, known ' + + 'for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook)\n\n' + + '\n\n' + + '# API\n\n'; + +for (var i = 0; i < blocks.length; ++i) { + var describe = blocks[i]; + mdOutput += '## ' + describe.contents + '\n\n'; + mdOutput += describe.comments[0] ? + acquit.trimEachLine(describe.comments[0]) + '\n\n' : + ''; + + for (var j = 0; j < describe.blocks.length; ++j) { + var it = describe.blocks[j]; + mdOutput += '#### It ' + it.contents + '\n\n'; + mdOutput += it.comments[0] ? + acquit.trimEachLine(it.comments[0]) + '\n\n' : + ''; + mdOutput += '```javascript\n'; + mdOutput += it.code + '\n'; + mdOutput += '```\n\n'; + } +} + +require('fs').writeFileSync('README.md', mdOutput); diff --git a/node_modules/kareem/gulpfile.js b/node_modules/kareem/gulpfile.js new file mode 100644 index 0000000..635bfc7 --- /dev/null +++ b/node_modules/kareem/gulpfile.js @@ -0,0 +1,18 @@ +var gulp = require('gulp'); +var mocha = require('gulp-mocha'); +var config = require('./package.json'); +var jscs = require('gulp-jscs'); + +gulp.task('mocha', function() { + return gulp.src('./test/*'). + pipe(mocha({ reporter: 'dot' })); +}); + +gulp.task('jscs', function() { + return gulp.src('./index.js'). + pipe(jscs(config.jscsConfig)); +}); + +gulp.task('watch', function() { + gulp.watch('./index.js', ['jscs', 'mocha']); +}); diff --git a/node_modules/kareem/index.js b/node_modules/kareem/index.js new file mode 100644 index 0000000..1484ecd --- /dev/null +++ b/node_modules/kareem/index.js @@ -0,0 +1,512 @@ +'use strict'; + +function Kareem() { + this._pres = new Map(); + this._posts = new Map(); +} + +Kareem.prototype.execPre = function(name, context, args, callback) { + if (arguments.length === 3) { + callback = args; + args = []; + } + var pres = get(this._pres, name, []); + var numPres = pres.length; + var numAsyncPres = pres.numAsync || 0; + var currentPre = 0; + var asyncPresLeft = numAsyncPres; + var done = false; + var $args = args; + + if (!numPres) { + return process.nextTick(function() { + callback(null); + }); + } + + var next = function() { + if (currentPre >= numPres) { + return; + } + var pre = pres[currentPre]; + + if (pre.isAsync) { + var args = [ + decorateNextFn(_next), + decorateNextFn(function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + if (--asyncPresLeft === 0 && currentPre >= numPres) { + return callback(null); + } + }) + ]; + + callMiddlewareFunction(pre.fn, context, args, args[0]); + } else if (pre.fn.length > 0) { + var args = [decorateNextFn(_next)]; + var _args = arguments.length >= 2 ? arguments : [null].concat($args); + for (var i = 1; i < _args.length; ++i) { + args.push(_args[i]); + } + + callMiddlewareFunction(pre.fn, context, args, args[0]); + } else { + let maybePromise = null; + try { + maybePromise = pre.fn.call(context); + } catch (err) { + if (err != null) { + return callback(err); + } + } + + if (isPromise(maybePromise)) { + maybePromise.then(() => _next(), err => _next(err)); + } else { + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; + } else { + return process.nextTick(function() { + callback(null); + }); + } + } + next(); + } + } + }; + + next.apply(null, [null].concat(args)); + + function _next(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; + } else { + return callback(null); + } + } + + next.apply(context, arguments); + } +}; + +Kareem.prototype.execPreSync = function(name, context, args) { + var pres = get(this._pres, name, []); + var numPres = pres.length; + + for (var i = 0; i < numPres; ++i) { + pres[i].fn.apply(context, args || []); + } +}; + +Kareem.prototype.execPost = function(name, context, args, options, callback) { + if (arguments.length < 5) { + callback = options; + options = null; + } + var posts = get(this._posts, name, []); + var numPosts = posts.length; + var currentPost = 0; + + var firstError = null; + if (options && options.error) { + firstError = options.error; + } + + if (!numPosts) { + return process.nextTick(function() { + callback.apply(null, [firstError].concat(args)); + }); + } + + var next = function() { + var post = posts[currentPost].fn; + var numArgs = 0; + var argLength = args.length; + var newArgs = []; + for (var i = 0; i < argLength; ++i) { + numArgs += args[i] && args[i]._kareemIgnore ? 0 : 1; + if (!args[i] || !args[i]._kareemIgnore) { + newArgs.push(args[i]); + } + } + + if (firstError) { + if (post.length === numArgs + 2) { + var _cb = decorateNextFn(function(error) { + if (error) { + firstError = error; + } + if (++currentPost >= numPosts) { + return callback.call(null, firstError); + } + next(); + }); + + callMiddlewareFunction(post, context, + [firstError].concat(newArgs).concat([_cb]), _cb); + } else { + if (++currentPost >= numPosts) { + return callback.call(null, firstError); + } + next(); + } + } else { + const _cb = decorateNextFn(function(error) { + if (error) { + firstError = error; + return next(); + } + + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + + next(); + }); + + if (post.length === numArgs + 2) { + // Skip error handlers if no error + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + return next(); + } + if (post.length === numArgs + 1) { + callMiddlewareFunction(post, context, newArgs.concat([_cb]), _cb); + } else { + let error; + let maybePromise; + try { + maybePromise = post.apply(context, newArgs); + } catch (err) { + error = err; + firstError = err; + } + + if (isPromise(maybePromise)) { + return maybePromise.then(() => _cb(), err => _cb(err)); + } + + if (++currentPost >= numPosts) { + return callback.apply(null, [error].concat(args)); + } + + next(error); + } + } + }; + + next(); +}; + +Kareem.prototype.execPostSync = function(name, context, args) { + const posts = get(this._posts, name, []); + const numPosts = posts.length; + + for (let i = 0; i < numPosts; ++i) { + posts[i].fn.apply(context, args || []); + } +}; + +Kareem.prototype.createWrapperSync = function(name, fn) { + var kareem = this; + return function syncWrapper() { + kareem.execPreSync(name, this, arguments); + + var toReturn = fn.apply(this, arguments); + + kareem.execPostSync(name, this, [toReturn]); + + return toReturn; + }; +} + +function _handleWrapError(instance, error, name, context, args, options, callback) { + if (options.useErrorHandlers) { + var _options = { error: error }; + return instance.execPost(name, context, args, _options, function(error) { + return typeof callback === 'function' && callback(error); + }); + } else { + return typeof callback === 'function' ? + callback(error) : + undefined; + } +} + +Kareem.prototype.wrap = function(name, fn, context, args, options) { + const lastArg = (args.length > 0 ? args[args.length - 1] : null); + const argsWithoutCb = typeof lastArg === 'function' ? + args.slice(0, args.length - 1) : + args; + const _this = this; + + options = options || {}; + const checkForPromise = options.checkForPromise; + + this.execPre(name, context, args, function(error) { + if (error) { + const numCallbackParams = options.numCallbackParams || 0; + const errorArgs = options.contextParameter ? [context] : []; + for (var i = errorArgs.length; i < numCallbackParams; ++i) { + errorArgs.push(null); + } + return _handleWrapError(_this, error, name, context, errorArgs, + options, lastArg); + } + + const end = (typeof lastArg === 'function' ? args.length - 1 : args.length); + const numParameters = fn.length; + const ret = fn.apply(context, args.slice(0, end).concat(_cb)); + + if (checkForPromise) { + if (ret != null && typeof ret.then === 'function') { + // Thenable, use it + return ret.then( + res => _cb(null, res), + err => _cb(err) + ); + } + + // If `fn()` doesn't have a callback argument and doesn't return a + // promise, assume it is sync + if (numParameters < end + 1) { + return _cb(null, ret); + } + } + + function _cb() { + const args = arguments; + const argsWithoutError = Array.prototype.slice.call(arguments, 1); + if (options.nullResultByDefault && argsWithoutError.length === 0) { + argsWithoutError.push(null); + } + if (arguments[0]) { + // Assume error + return _handleWrapError(_this, arguments[0], name, context, + argsWithoutError, options, lastArg); + } else { + _this.execPost(name, context, argsWithoutError, function() { + if (arguments[0]) { + return typeof lastArg === 'function' ? + lastArg(arguments[0]) : + undefined; + } + + return typeof lastArg === 'function' ? + lastArg.apply(context, arguments) : + undefined; + }); + } + } + }); +}; + +Kareem.prototype.filter = function(fn) { + const clone = this.clone(); + + const pres = Array.from(clone._pres.keys()); + for (const name of pres) { + const hooks = this._pres.get(name). + map(h => Object.assign({}, h, { name: name })). + filter(fn); + + if (hooks.length === 0) { + clone._pres.delete(name); + continue; + } + + hooks.numAsync = hooks.filter(h => h.isAsync).length; + + clone._pres.set(name, hooks); + } + + const posts = Array.from(clone._posts.keys()); + for (const name of posts) { + const hooks = this._posts.get(name). + map(h => Object.assign({}, h, { name: name })). + filter(fn); + + if (hooks.length === 0) { + clone._posts.delete(name); + continue; + } + + clone._posts.set(name, hooks); + } + + return clone; +}; + +Kareem.prototype.hasHooks = function(name) { + return this._pres.has(name) || this._posts.has(name); +}; + +Kareem.prototype.createWrapper = function(name, fn, context, options) { + var _this = this; + if (!this.hasHooks(name)) { + // Fast path: if there's no hooks for this function, just return the + // function wrapped in a nextTick() + return function() { + process.nextTick(() => fn.apply(this, arguments)); + }; + } + return function() { + var _context = context || this; + var args = Array.prototype.slice.call(arguments); + _this.wrap(name, fn, _context, args, options); + }; +}; + +Kareem.prototype.pre = function(name, isAsync, fn, error, unshift) { + let options = {}; + if (typeof isAsync === 'object' && isAsync != null) { + options = isAsync; + isAsync = options.isAsync; + } else if (typeof arguments[1] !== 'boolean') { + error = fn; + fn = isAsync; + isAsync = false; + } + + const pres = get(this._pres, name, []); + this._pres.set(name, pres); + + if (isAsync) { + pres.numAsync = pres.numAsync || 0; + ++pres.numAsync; + } + + if (typeof fn !== 'function') { + throw new Error('pre() requires a function, got "' + typeof fn + '"'); + } + + if (unshift) { + pres.unshift(Object.assign({}, options, { fn: fn, isAsync: isAsync })); + } else { + pres.push(Object.assign({}, options, { fn: fn, isAsync: isAsync })); + } + + return this; +}; + +Kareem.prototype.post = function(name, options, fn, unshift) { + const hooks = get(this._posts, name, []); + + if (typeof options === 'function') { + unshift = !!fn; + fn = options; + options = {}; + } + + if (typeof fn !== 'function') { + throw new Error('post() requires a function, got "' + typeof fn + '"'); + } + + if (unshift) { + hooks.unshift(Object.assign({}, options, { fn: fn })); + } else { + hooks.push(Object.assign({}, options, { fn: fn })); + } + this._posts.set(name, hooks); + return this; +}; + +Kareem.prototype.clone = function() { + const n = new Kareem(); + + for (let key of this._pres.keys()) { + const clone = this._pres.get(key).slice(); + clone.numAsync = this._pres.get(key).numAsync; + n._pres.set(key, clone); + } + for (let key of this._posts.keys()) { + n._posts.set(key, this._posts.get(key).slice()); + } + + return n; +}; + +Kareem.prototype.merge = function(other, clone) { + clone = arguments.length === 1 ? true : clone; + var ret = clone ? this.clone() : this; + + for (let key of other._pres.keys()) { + const sourcePres = get(ret._pres, key, []); + const deduplicated = other._pres.get(key). + // Deduplicate based on `fn` + filter(p => sourcePres.map(_p => _p.fn).indexOf(p.fn) === -1); + const combined = sourcePres.concat(deduplicated); + combined.numAsync = sourcePres.numAsync || 0; + combined.numAsync += deduplicated.filter(p => p.isAsync).length; + ret._pres.set(key, combined); + } + for (let key of other._posts.keys()) { + const sourcePosts = get(ret._posts, key, []); + const deduplicated = other._posts.get(key). + filter(p => sourcePosts.indexOf(p) === -1); + ret._posts.set(key, sourcePosts.concat(deduplicated)); + } + + return ret; +}; + +function get(map, key, def) { + if (map.has(key)) { + return map.get(key); + } + return def; +} + +function callMiddlewareFunction(fn, context, args, next) { + let maybePromise; + try { + maybePromise = fn.apply(context, args); + } catch (error) { + return next(error); + } + + if (isPromise(maybePromise)) { + maybePromise.then(() => next(), err => next(err)); + } +} + +function isPromise(v) { + return v != null && typeof v.then === 'function'; +} + +function decorateNextFn(fn) { + var called = false; + var _this = this; + return function() { + // Ensure this function can only be called once + if (called) { + return; + } + called = true; + // Make sure to clear the stack so try/catch doesn't catch errors + // in subsequent middleware + return process.nextTick(() => fn.apply(_this, arguments)); + }; +} + +module.exports = Kareem; diff --git a/node_modules/kareem/package.json b/node_modules/kareem/package.json new file mode 100644 index 0000000..81d6d63 --- /dev/null +++ b/node_modules/kareem/package.json @@ -0,0 +1,22 @@ +{ + "name": "kareem", + "version": "2.3.2", + "description": "Next-generation take on pre/post function hooks", + "main": "index.js", + "scripts": { + "test": "mocha ./test/*", + "test-travis": "nyc mocha ./test/*" + }, + "repository": { + "type": "git", + "url": "git://github.com/vkarpov15/kareem.git" + }, + "devDependencies": { + "acquit": "1.x", + "acquit-ignore": "0.1.x", + "nyc": "11.x", + "mocha": "5.x" + }, + "author": "Valeri Karpov ", + "license": "Apache-2.0" +} diff --git a/node_modules/kareem/test/examples.test.js b/node_modules/kareem/test/examples.test.js new file mode 100644 index 0000000..cbde984 --- /dev/null +++ b/node_modules/kareem/test/examples.test.js @@ -0,0 +1,426 @@ +var assert = require('assert'); +var Kareem = require('../'); + +/* Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define + * pre and post hooks: pre hooks are called before a given function executes. + * Unlike hooks, kareem stores hooks and other internal state in a separate + * object, rather than relying on inheritance. Furthermore, kareem exposes + * an `execPre()` function that allows you to execute your pre hooks when + * appropriate, giving you more fine-grained control over your function hooks. + */ +describe('pre hooks', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('runs without any hooks specified', function(done) { + hooks.execPre('cook', null, function() { + // ... + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + }); + + /* pre hook functions take one parameter, a "done" function that you execute + * when your pre hook is finished. + */ + it('runs basic serial pre hooks', function(done) { + var count = 0; + + hooks.pre('cook', function(done) { + ++count; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count); + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + }); + + it('can run multipe pre hooks', function(done) { + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function(done) { + ++count1; + done(); + }); + + hooks.pre('cook', function(done) { + ++count2; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count1); + assert.equal(1, count2); + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + }); + + /* If your pre hook function takes no parameters, its assumed to be + * fully synchronous. + */ + it('can run fully synchronous pre hooks', function(done) { + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function() { + ++count1; + }); + + hooks.pre('cook', function() { + ++count2; + }); + + hooks.execPre('cook', null, function(error) { + assert.equal(null, error); + assert.equal(1, count1); + assert.equal(1, count2); + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + }); + + /* Pre save hook functions are bound to the second parameter to `execPre()` + */ + it('properly attaches context to pre hooks', function(done) { + hooks.pre('cook', function(done) { + this.bacon = 3; + done(); + }); + + hooks.pre('cook', function(done) { + this.eggs = 4; + done(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + // In the pre hooks, `this` will refer to `obj` + hooks.execPre('cook', obj, function(error) { + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + }); + + /* Like the hooks module, you can declare "async" pre hooks - these take two + * parameters, the functions `next()` and `done()`. `next()` passes control to + * the next pre hook, but the underlying function won't be called until all + * async pre hooks have called `done()`. + */ + it('can execute parallel (async) pre hooks', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + }); + + /* You can also return a promise from your pre hooks instead of calling + * `next()`. When the returned promise resolves, kareem will kick off the + * next middleware. + */ + it('supports returning a promise', function(done) { + hooks.pre('cook', function() { + return new Promise(resolve => { + setTimeout(() => { + this.bacon = 3; + resolve(); + }, 100); + }); + }); + + var obj = { bacon: 0 }; + + hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + }); +}); + +describe('post hooks', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('runs without any hooks specified', function(done) { + hooks.execPost('cook', null, [1], function(error, eggs) { + assert.ifError(error); + assert.equal(1, eggs); + done(); + }); + }); + + it('executes with parameters passed in', function(done) { + hooks.post('cook', function(eggs, bacon, callback) { + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(1, eggs); + assert.equal(2, bacon); + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + }); + + it('can use synchronous post hooks', function(done) { + var execed = {}; + + hooks.post('cook', function(eggs, bacon) { + execed.first = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + }); + + hooks.post('cook', function(eggs, bacon, callback) { + execed.second = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.equal(1, eggs); + assert.equal(2, bacon); + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + }); + + /* You can also return a promise from your post hooks instead of calling + * `next()`. When the returned promise resolves, kareem will kick off the + * next middleware. + */ + it('supports returning a promise', function(done) { + hooks.post('cook', function(bacon) { + return new Promise(resolve => { + setTimeout(() => { + this.bacon = 3; + resolve(); + }, 100); + }); + }); + + var obj = { bacon: 0 }; + + hooks.execPost('cook', obj, obj, function() { + assert.equal(obj.bacon, 3); + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + }); +}); + +describe('wrap()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('wraps pre and post calls into one call', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.ifError(error); + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + + hooks.wrap( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj, + args); + }); +}); + +describe('createWrapper()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('wraps wrap() into a callable function', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var cook = hooks.createWrapper( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj); + + cook(obj, function(error, result) { + assert.ifError(error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + // acquit:ignore:start + done(); + // acquit:ignore:end + }); + }); +}); + +describe('clone()', function() { + it('clones a Kareem object', function() { + var k1 = new Kareem(); + k1.pre('cook', function() {}); + k1.post('cook', function() {}); + + var k2 = k1.clone(); + assert.deepEqual(Array.from(k2._pres.keys()), ['cook']); + assert.deepEqual(Array.from(k2._posts.keys()), ['cook']); + }); +}); + +describe('merge()', function() { + it('pulls hooks from another Kareem object', function() { + var k1 = new Kareem(); + var test1 = function() {}; + k1.pre('cook', test1); + k1.post('cook', function() {}); + + var k2 = new Kareem(); + var test2 = function() {}; + k2.pre('cook', test2); + var k3 = k2.merge(k1); + assert.equal(k3._pres.get('cook').length, 2); + assert.equal(k3._pres.get('cook')[0].fn, test2); + assert.equal(k3._pres.get('cook')[1].fn, test1); + assert.equal(k3._posts.get('cook').length, 1); + }); +}); diff --git a/node_modules/kareem/test/misc.test.js b/node_modules/kareem/test/misc.test.js new file mode 100644 index 0000000..531b1d4 --- /dev/null +++ b/node_modules/kareem/test/misc.test.js @@ -0,0 +1,71 @@ +'use strict'; + +const assert = require('assert'); +const Kareem = require('../'); + +describe('hasHooks', function() { + it('returns false for toString (Automattic/mongoose#6538)', function() { + const k = new Kareem(); + assert.ok(!k.hasHooks('toString')); + }); +}); + +describe('merge', function() { + it('handles async pres if source doesnt have them', function() { + const k1 = new Kareem(); + k1.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('error!'); + }, + 5); + + next(); + }); + + assert.equal(k1._pres.get('cook').numAsync, 1); + + const k2 = new Kareem(); + const k3 = k2.merge(k1); + assert.equal(k3._pres.get('cook').numAsync, 1); + }); +}); + +describe('filter', function() { + it('returns clone with only hooks that match `fn()`', function() { + const k1 = new Kareem(); + + k1.pre('update', { document: true }, f1); + k1.pre('update', { query: true }, f2); + k1.pre('remove', { document: true }, f3); + + k1.post('update', { document: true }, f1); + k1.post('update', { query: true }, f2); + k1.post('remove', { document: true }, f3); + + const k2 = k1.filter(hook => hook.document); + assert.equal(k2._pres.get('update').length, 1); + assert.equal(k2._pres.get('update')[0].fn, f1); + assert.equal(k2._pres.get('remove').length, 1); + assert.equal(k2._pres.get('remove')[0].fn, f3); + + assert.equal(k2._posts.get('update').length, 1); + assert.equal(k2._posts.get('update')[0].fn, f1); + assert.equal(k2._posts.get('remove').length, 1); + assert.equal(k2._posts.get('remove')[0].fn, f3); + + const k3 = k1.filter(hook => hook.query); + assert.equal(k3._pres.get('update').length, 1); + assert.equal(k3._pres.get('update')[0].fn, f2); + assert.ok(!k3._pres.has('remove')); + + assert.equal(k3._posts.get('update').length, 1); + assert.equal(k3._posts.get('update')[0].fn, f2); + assert.ok(!k3._posts.has('remove')); + + function f1() {} + function f2() {} + function f3() {} + }); +}); diff --git a/node_modules/kareem/test/post.test.js b/node_modules/kareem/test/post.test.js new file mode 100644 index 0000000..b9a776d --- /dev/null +++ b/node_modules/kareem/test/post.test.js @@ -0,0 +1,198 @@ +'use strict'; + +const assert = require('assert'); +const Kareem = require('../'); + +describe('execPost', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles errors', function(done) { + hooks.post('cook', function(eggs, callback) { + callback('error!'); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.equal('error!', error); + assert.ok(!eggs); + done(); + }); + }); + + it('unshift', function() { + var f1 = function() {}; + var f2 = function() {}; + hooks.post('cook', f1); + hooks.post('cook', f2, true); + assert.strictEqual(hooks._posts.get('cook')[0].fn, f2); + assert.strictEqual(hooks._posts.get('cook')[1].fn, f1); + }); + + it('arbitrary options', function() { + const f1 = function() {}; + const f2 = function() {}; + hooks.post('cook', { foo: 'bar' }, f1); + hooks.post('cook', { bar: 'baz' }, f2, true); + assert.equal(hooks._posts.get('cook')[1].foo, 'bar'); + assert.equal(hooks._posts.get('cook')[0].bar, 'baz'); + }); + + it('throws error if no function', function() { + assert.throws(() => hooks.post('test'), /got "undefined"/); + }); + + it('multiple posts', function(done) { + hooks.post('cook', function(eggs, callback) { + setTimeout( + function() { + callback(); + }, + 5); + }); + + hooks.post('cook', function(eggs, callback) { + setTimeout( + function() { + callback(); + }, + 5); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.ifError(error); + assert.equal(4, eggs); + done(); + }); + }); + + it('error posts', function(done) { + var called = {}; + hooks.post('cook', function(eggs, callback) { + called.first = true; + callback(); + }); + + hooks.post('cook', function(eggs, callback) { + called.second = true; + callback(new Error('fail')); + }); + + hooks.post('cook', function(eggs, callback) { + assert.ok(false); + }); + + hooks.post('cook', function(error, eggs, callback) { + called.fourth = true; + assert.equal(error.message, 'fail'); + callback(new Error('fourth')); + }); + + hooks.post('cook', function(error, eggs, callback) { + called.fifth = true; + assert.equal(error.message, 'fourth'); + callback(new Error('fifth')); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.ok(error); + assert.equal(error.message, 'fifth'); + assert.deepEqual(called, { + first: true, + second: true, + fourth: true, + fifth: true + }); + done(); + }); + }); + + it('error posts with initial error', function(done) { + var called = {}; + + hooks.post('cook', function(eggs, callback) { + assert.ok(false); + }); + + hooks.post('cook', function(error, eggs, callback) { + called.second = true; + assert.equal(error.message, 'fail'); + callback(new Error('second')); + }); + + hooks.post('cook', function(error, eggs, callback) { + called.third = true; + assert.equal(error.message, 'second'); + callback(new Error('third')); + }); + + hooks.post('cook', function(error, eggs, callback) { + called.fourth = true; + assert.equal(error.message, 'third'); + callback(); + }); + + var options = { error: new Error('fail') }; + hooks.execPost('cook', null, [4], options, function(error, eggs) { + assert.ok(error); + assert.equal(error.message, 'third'); + assert.deepEqual(called, { + second: true, + third: true, + fourth: true + }); + done(); + }); + }); + + it('supports returning a promise', function(done) { + var calledPost = 0; + + hooks.post('cook', function() { + return new Promise(resolve => { + setTimeout(() => { + ++calledPost; + resolve(); + }, 100); + }); + }); + + hooks.execPost('cook', null, [], {}, function(error) { + assert.ifError(error); + assert.equal(calledPost, 1); + done(); + }); + }); +}); + +describe('execPostSync', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('executes hooks synchronously', function() { + var execed = {}; + + hooks.post('cook', function() { + execed.first = true; + }); + + hooks.post('cook', function() { + execed.second = true; + }); + + hooks.execPostSync('cook', null); + assert.ok(execed.first); + assert.ok(execed.second); + }); + + it('works with no hooks specified', function() { + assert.doesNotThrow(function() { + hooks.execPostSync('cook', null); + }); + }); +}); diff --git a/node_modules/kareem/test/pre.test.js b/node_modules/kareem/test/pre.test.js new file mode 100644 index 0000000..ebf7bfb --- /dev/null +++ b/node_modules/kareem/test/pre.test.js @@ -0,0 +1,340 @@ +'use strict'; + +const assert = require('assert'); +const Kareem = require('../'); + +describe('execPre', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles errors with multiple pres', function(done) { + var execed = {}; + + hooks.pre('cook', function(done) { + execed.first = true; + done(); + }); + + hooks.pre('cook', function(done) { + execed.second = true; + done('error!'); + }); + + hooks.pre('cook', function(done) { + execed.third = true; + done(); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('sync errors', function(done) { + var called = 0; + + hooks.pre('cook', function(next) { + throw new Error('woops!'); + }); + + hooks.pre('cook', function(next) { + ++called; + next(); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal(err.message, 'woops!'); + assert.equal(called, 0); + done(); + }); + }); + + it('unshift', function() { + var f1 = function() {}; + var f2 = function() {}; + hooks.pre('cook', false, f1); + hooks.pre('cook', false, f2, null, true); + assert.strictEqual(hooks._pres.get('cook')[0].fn, f2); + assert.strictEqual(hooks._pres.get('cook')[1].fn, f1); + }); + + it('throws error if no function', function() { + assert.throws(() => hooks.pre('test'), /got "undefined"/); + }); + + it('arbitrary options', function() { + const f1 = function() {}; + const f2 = function() {}; + hooks.pre('cook', { foo: 'bar' }, f1); + hooks.pre('cook', { bar: 'baz' }, f2, null, true); + assert.equal(hooks._pres.get('cook')[1].foo, 'bar'); + assert.equal(hooks._pres.get('cook')[0].bar, 'baz'); + }); + + it('handles async errors', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + done('other error!'); + }, + 10); + + next(); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors in next()', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 15); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + next('error!'); + done('another error!'); + }, + 5); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors in next() when already done', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + next('error!'); + done('another error!'); + }, + 25); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('other error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('async pres with clone()', function(done) { + var execed = false; + + hooks.pre('cook', true, function(next, done) { + execed = true; + setTimeout( + function() { + done(); + }, + 5); + + next(); + }); + + hooks.clone().execPre('cook', null, function(err) { + assert.ifError(err); + assert.ok(execed); + done(); + }); + }); + + it('returns correct error when async pre errors', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', function(next) { + execed.second = true; + setTimeout( + function() { + next('error!'); + }, + 15); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('other error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('lets async pres run when fully sync pres are done', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done(); + }, + 5); + + next(); + }); + + hooks.pre('cook', function() { + execed.second = true; + }); + + hooks.execPre('cook', null, function(err) { + assert.ifError(err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('allows passing arguments to the next pre', function(done) { + var execed = {}; + + hooks.pre('cook', function(next) { + execed.first = true; + next(null, 'test'); + }); + + hooks.pre('cook', function(next, p) { + execed.second = true; + assert.equal(p, 'test'); + next(); + }); + + hooks.pre('cook', function(next, p) { + execed.third = true; + assert.ok(!p); + next(); + }); + + hooks.execPre('cook', null, function(err) { + assert.ifError(err); + assert.equal(3, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.ok(execed.third); + done(); + }); + }); + + it('handles sync errors in pre if there are more hooks', function(done) { + var execed = {}; + + hooks.pre('cook', function() { + execed.first = true; + throw new Error('Oops!'); + }); + + hooks.pre('cook', function() { + execed.second = true; + }); + + hooks.execPre('cook', null, function(err) { + assert.ok(err); + assert.ok(execed.first); + assert.equal(err.message, 'Oops!'); + done(); + }); + }); +}); + +describe('execPreSync', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('executes hooks synchronously', function() { + var execed = {}; + + hooks.pre('cook', function() { + execed.first = true; + }); + + hooks.pre('cook', function() { + execed.second = true; + }); + + hooks.execPreSync('cook', null); + assert.ok(execed.first); + assert.ok(execed.second); + }); + + it('works with no hooks specified', function() { + assert.doesNotThrow(function() { + hooks.execPreSync('cook', null); + }); + }); +}); diff --git a/node_modules/kareem/test/wrap.test.js b/node_modules/kareem/test/wrap.test.js new file mode 100644 index 0000000..dd9196e --- /dev/null +++ b/node_modules/kareem/test/wrap.test.js @@ -0,0 +1,342 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('wrap()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles pre errors', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal(undefined, obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + // Should never get called + assert.ok(false); + callback(null, o); + }, + obj, + args); + }); + + it('handles pre errors when no callback defined', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + + hooks.wrap( + 'cook', + function(o, callback) { + // Should never get called + assert.ok(false); + callback(null, o); + }, + obj, + args); + + setTimeout( + function() { + done(); + }, + 25); + }); + + it('handles errors in wrapped function', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal(undefined, obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + callback('error!'); + }, + obj, + args); + }); + + it('handles errors in post', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(obj, callback) { + obj.tofu = 'no'; + callback('error!'); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal('no', obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + callback(null, o); + }, + obj, + args); + }); + + it('defers errors to post hooks if enabled', function(done) { + hooks.pre('cook', function(done) { + done(new Error('fail')); + }); + + hooks.post('cook', function(error, res, callback) { + callback(new Error('another error occurred')); + }); + + var args = []; + args.push(function(error) { + assert.equal(error.message, 'another error occurred'); + done(); + }); + + hooks.wrap( + 'cook', + function(callback) { + assert.ok(false); + callback(); + }, + null, + args, + { useErrorHandlers: true, numCallbackParams: 1 }); + }); + + it('error handlers with no callback', function(done) { + hooks.pre('cook', function(done) { + done(new Error('fail')); + }); + + hooks.post('cook', function(error, callback) { + assert.equal(error.message, 'fail'); + done(); + }); + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + assert.ok(false); + callback(); + }, + null, + args, + { useErrorHandlers: true }); + }); + + it('error handlers with no error', function(done) { + hooks.post('cook', function(error, callback) { + callback(new Error('another error occurred')); + }); + + var args = []; + args.push(function(error) { + assert.ifError(error); + done(); + }); + + hooks.wrap( + 'cook', + function(callback) { + callback(); + }, + null, + args, + { useErrorHandlers: true }); + }); + + it('works with no args', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(null); + }, + obj, + args); + + setTimeout( + function() { + assert.equal('no', obj.tofu); + done(); + }, + 25); + }); + + it('handles pre errors with no args', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(null); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(undefined, obj.tofu); + done(); + }, + 25); + }); + + it('handles wrapped function errors with no args', function(done) { + hooks.pre('cook', function(done) { + obj.waffles = false; + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback('error!'); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + done(); + }, + 25); + }); + + it('handles post errors with no args', function(done) { + hooks.pre('cook', function(done) { + obj.waffles = false; + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback('error!'); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + done(); + }, + 25); + }); + + it('sync wrappers', function() { + var calledPre = 0; + var calledFn = 0; + var calledPost = 0; + hooks.pre('cook', function() { + ++calledPre; + }); + + hooks.post('cook', function() { + ++calledPost; + }); + + var wrapper = hooks.createWrapperSync('cook', function() { ++calledFn; }); + + wrapper(); + + assert.equal(calledPre, 1); + assert.equal(calledFn, 1); + assert.equal(calledPost, 1); + }); +}); diff --git a/node_modules/lodash.includes/LICENSE b/node_modules/lodash.includes/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.includes/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.includes/README.md b/node_modules/lodash.includes/README.md new file mode 100644 index 0000000..26e9377 --- /dev/null +++ b/node_modules/lodash.includes/README.md @@ -0,0 +1,18 @@ +# lodash.includes v4.3.0 + +The [lodash](https://lodash.com/) method `_.includes` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.includes +``` + +In Node.js: +```js +var includes = require('lodash.includes'); +``` + +See the [documentation](https://lodash.com/docs#includes) or [package source](https://github.com/lodash/lodash/blob/4.3.0-npm-packages/lodash.includes) for more details. diff --git a/node_modules/lodash.includes/index.js b/node_modules/lodash.includes/index.js new file mode 100644 index 0000000..e88d533 --- /dev/null +++ b/node_modules/lodash.includes/index.js @@ -0,0 +1,745 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); + } + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ +function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ +function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +/** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ +function values(object) { + return object ? baseValues(object, keys(object)) : []; +} + +module.exports = includes; diff --git a/node_modules/lodash.includes/package.json b/node_modules/lodash.includes/package.json new file mode 100644 index 0000000..a02e645 --- /dev/null +++ b/node_modules/lodash.includes/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.includes", + "version": "4.3.0", + "description": "The lodash method `_.includes` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, includes", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isboolean/LICENSE b/node_modules/lodash.isboolean/LICENSE new file mode 100644 index 0000000..b054ca5 --- /dev/null +++ b/node_modules/lodash.isboolean/LICENSE @@ -0,0 +1,22 @@ +Copyright 2012-2016 The Dojo Foundation +Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +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/lodash.isboolean/README.md b/node_modules/lodash.isboolean/README.md new file mode 100644 index 0000000..b3c476b --- /dev/null +++ b/node_modules/lodash.isboolean/README.md @@ -0,0 +1,18 @@ +# lodash.isboolean v3.0.3 + +The [lodash](https://lodash.com/) method `_.isBoolean` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isboolean +``` + +In Node.js: +```js +var isBoolean = require('lodash.isboolean'); +``` + +See the [documentation](https://lodash.com/docs#isBoolean) or [package source](https://github.com/lodash/lodash/blob/3.0.3-npm-packages/lodash.isboolean) for more details. diff --git a/node_modules/lodash.isboolean/index.js b/node_modules/lodash.isboolean/index.js new file mode 100644 index 0000000..23bbabd --- /dev/null +++ b/node_modules/lodash.isboolean/index.js @@ -0,0 +1,70 @@ +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && objectToString.call(value) == boolTag); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +module.exports = isBoolean; diff --git a/node_modules/lodash.isboolean/package.json b/node_modules/lodash.isboolean/package.json new file mode 100644 index 0000000..01d6e8b --- /dev/null +++ b/node_modules/lodash.isboolean/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isboolean", + "version": "3.0.3", + "description": "The lodash method `_.isBoolean` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isboolean", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isinteger/LICENSE b/node_modules/lodash.isinteger/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.isinteger/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.isinteger/README.md b/node_modules/lodash.isinteger/README.md new file mode 100644 index 0000000..3a78567 --- /dev/null +++ b/node_modules/lodash.isinteger/README.md @@ -0,0 +1,18 @@ +# lodash.isinteger v4.0.4 + +The [lodash](https://lodash.com/) method `_.isInteger` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isinteger +``` + +In Node.js: +```js +var isInteger = require('lodash.isinteger'); +``` + +See the [documentation](https://lodash.com/docs#isInteger) or [package source](https://github.com/lodash/lodash/blob/4.0.4-npm-packages/lodash.isinteger) for more details. diff --git a/node_modules/lodash.isinteger/index.js b/node_modules/lodash.isinteger/index.js new file mode 100644 index 0000000..3bf06f0 --- /dev/null +++ b/node_modules/lodash.isinteger/index.js @@ -0,0 +1,265 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ +function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = isInteger; diff --git a/node_modules/lodash.isinteger/package.json b/node_modules/lodash.isinteger/package.json new file mode 100644 index 0000000..92db256 --- /dev/null +++ b/node_modules/lodash.isinteger/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isinteger", + "version": "4.0.4", + "description": "The lodash method `_.isInteger` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isinteger", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isnumber/LICENSE b/node_modules/lodash.isnumber/LICENSE new file mode 100644 index 0000000..b054ca5 --- /dev/null +++ b/node_modules/lodash.isnumber/LICENSE @@ -0,0 +1,22 @@ +Copyright 2012-2016 The Dojo Foundation +Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +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/lodash.isnumber/README.md b/node_modules/lodash.isnumber/README.md new file mode 100644 index 0000000..a1d434d --- /dev/null +++ b/node_modules/lodash.isnumber/README.md @@ -0,0 +1,18 @@ +# lodash.isnumber v3.0.3 + +The [lodash](https://lodash.com/) method `_.isNumber` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isnumber +``` + +In Node.js: +```js +var isNumber = require('lodash.isnumber'); +``` + +See the [documentation](https://lodash.com/docs#isNumber) or [package source](https://github.com/lodash/lodash/blob/3.0.3-npm-packages/lodash.isnumber) for more details. diff --git a/node_modules/lodash.isnumber/index.js b/node_modules/lodash.isnumber/index.js new file mode 100644 index 0000000..35a8573 --- /dev/null +++ b/node_modules/lodash.isnumber/index.js @@ -0,0 +1,79 @@ +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** `Object#toString` result references. */ +var numberTag = '[object Number]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified + * as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && objectToString.call(value) == numberTag); +} + +module.exports = isNumber; diff --git a/node_modules/lodash.isnumber/package.json b/node_modules/lodash.isnumber/package.json new file mode 100644 index 0000000..4c33c2a --- /dev/null +++ b/node_modules/lodash.isnumber/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isnumber", + "version": "3.0.3", + "description": "The lodash method `_.isNumber` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isnumber", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isplainobject/LICENSE b/node_modules/lodash.isplainobject/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.isplainobject/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.isplainobject/README.md b/node_modules/lodash.isplainobject/README.md new file mode 100644 index 0000000..aeefd74 --- /dev/null +++ b/node_modules/lodash.isplainobject/README.md @@ -0,0 +1,18 @@ +# lodash.isplainobject v4.0.6 + +The [lodash](https://lodash.com/) method `_.isPlainObject` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isplainobject +``` + +In Node.js: +```js +var isPlainObject = require('lodash.isplainobject'); +``` + +See the [documentation](https://lodash.com/docs#isPlainObject) or [package source](https://github.com/lodash/lodash/blob/4.0.6-npm-packages/lodash.isplainobject) for more details. diff --git a/node_modules/lodash.isplainobject/index.js b/node_modules/lodash.isplainobject/index.js new file mode 100644 index 0000000..0f820ee --- /dev/null +++ b/node_modules/lodash.isplainobject/index.js @@ -0,0 +1,139 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; + +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || + objectToString.call(value) != objectTag || isHostObject(value)) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); +} + +module.exports = isPlainObject; diff --git a/node_modules/lodash.isplainobject/package.json b/node_modules/lodash.isplainobject/package.json new file mode 100644 index 0000000..86f6a07 --- /dev/null +++ b/node_modules/lodash.isplainobject/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isplainobject", + "version": "4.0.6", + "description": "The lodash method `_.isPlainObject` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isplainobject", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isstring/LICENSE b/node_modules/lodash.isstring/LICENSE new file mode 100644 index 0000000..b054ca5 --- /dev/null +++ b/node_modules/lodash.isstring/LICENSE @@ -0,0 +1,22 @@ +Copyright 2012-2016 The Dojo Foundation +Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +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/lodash.isstring/README.md b/node_modules/lodash.isstring/README.md new file mode 100644 index 0000000..f184029 --- /dev/null +++ b/node_modules/lodash.isstring/README.md @@ -0,0 +1,18 @@ +# lodash.isstring v4.0.1 + +The [lodash](https://lodash.com/) method `_.isString` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isstring +``` + +In Node.js: +```js +var isString = require('lodash.isstring'); +``` + +See the [documentation](https://lodash.com/docs#isString) or [package source](https://github.com/lodash/lodash/blob/4.0.1-npm-packages/lodash.isstring) for more details. diff --git a/node_modules/lodash.isstring/index.js b/node_modules/lodash.isstring/index.js new file mode 100644 index 0000000..408225c --- /dev/null +++ b/node_modules/lodash.isstring/index.js @@ -0,0 +1,95 @@ +/** + * lodash 4.0.1 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** `Object#toString` result references. */ +var stringTag = '[object String]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @type Function + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} + +module.exports = isString; diff --git a/node_modules/lodash.isstring/package.json b/node_modules/lodash.isstring/package.json new file mode 100644 index 0000000..1331535 --- /dev/null +++ b/node_modules/lodash.isstring/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isstring", + "version": "4.0.1", + "description": "The lodash method `_.isString` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isstring", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.once/LICENSE b/node_modules/lodash.once/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.once/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.once/README.md b/node_modules/lodash.once/README.md new file mode 100644 index 0000000..c4a2f16 --- /dev/null +++ b/node_modules/lodash.once/README.md @@ -0,0 +1,18 @@ +# lodash.once v4.1.1 + +The [lodash](https://lodash.com/) method `_.once` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.once +``` + +In Node.js: +```js +var once = require('lodash.once'); +``` + +See the [documentation](https://lodash.com/docs#once) or [package source](https://github.com/lodash/lodash/blob/4.1.1-npm-packages/lodash.once) for more details. diff --git a/node_modules/lodash.once/index.js b/node_modules/lodash.once/index.js new file mode 100644 index 0000000..414ceb3 --- /dev/null +++ b/node_modules/lodash.once/index.js @@ -0,0 +1,294 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ +function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; +} + +/** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ +function once(func) { + return before(2, func); +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = once; diff --git a/node_modules/lodash.once/package.json b/node_modules/lodash.once/package.json new file mode 100644 index 0000000..fae782c --- /dev/null +++ b/node_modules/lodash.once/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.once", + "version": "4.1.1", + "description": "The lodash method `_.once` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, once", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lru-cache/LICENSE b/node_modules/lru-cache/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/lru-cache/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/lru-cache/README.md b/node_modules/lru-cache/README.md new file mode 100644 index 0000000..435dfeb --- /dev/null +++ b/node_modules/lru-cache/README.md @@ -0,0 +1,166 @@ +# lru cache + +A cache object that deletes the least-recently-used items. + +[![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) + +## Installation: + +```javascript +npm install lru-cache --save +``` + +## Usage: + +```javascript +var LRU = require("lru-cache") + , options = { max: 500 + , length: function (n, key) { return n * 2 + key.length } + , dispose: function (key, n) { n.close() } + , maxAge: 1000 * 60 * 60 } + , cache = new LRU(options) + , otherCache = new LRU(50) // sets just the max size + +cache.set("key", "value") +cache.get("key") // "value" + +// non-string keys ARE fully supported +// but note that it must be THE SAME object, not +// just a JSON-equivalent object. +var someObject = { a: 1 } +cache.set(someObject, 'a value') +// Object keys are not toString()-ed +cache.set('[object Object]', 'a different value') +assert.equal(cache.get(someObject), 'a value') +// A similar object with same keys/values won't work, +// because it's a different object identity +assert.equal(cache.get({ a: 1 }), undefined) + +cache.reset() // empty the cache +``` + +If you put more stuff in it, then items will fall out. + +If you try to put an oversized thing in it, then it'll fall out right +away. + +## Options + +* `max` The maximum size of the cache, checked by applying the length + function to all values in the cache. Not setting this is kind of + silly, since that's the whole purpose of this lib, but it defaults + to `Infinity`. Setting it to a non-number or negative number will + throw a `TypeError`. Setting it to 0 makes it be `Infinity`. +* `maxAge` Maximum age in ms. Items are not pro-actively pruned out + as they age, but if you try to get an item that is too old, it'll + drop it and return undefined instead of giving it to you. + Setting this to a negative value will make everything seem old! + Setting it to a non-number will throw a `TypeError`. +* `length` Function that is used to calculate the length of stored + items. If you're storing strings or buffers, then you probably want + to do something like `function(n, key){return n.length}`. The default is + `function(){return 1}`, which is fine if you want to store `max` + like-sized things. The item is passed as the first argument, and + the key is passed as the second argumnet. +* `dispose` Function that is called on items when they are dropped + from the cache. This can be handy if you want to close file + descriptors or do other cleanup tasks when items are no longer + accessible. Called with `key, value`. It's called *before* + actually removing the item from the internal cache, so if you want + to immediately put it back in, you'll have to do that in a + `nextTick` or `setTimeout` callback or it won't do anything. +* `stale` By default, if you set a `maxAge`, it'll only actually pull + stale items out of the cache when you `get(key)`. (That is, it's + not pre-emptively doing a `setTimeout` or anything.) If you set + `stale:true`, it'll return the stale value before deleting it. If + you don't set this, then it'll return `undefined` when you try to + get a stale entry, as if it had already been deleted. +* `noDisposeOnSet` By default, if you set a `dispose()` method, then + it'll be called whenever a `set()` operation overwrites an existing + key. If you set this option, `dispose()` will only be called when a + key falls out of the cache, not when it is overwritten. +* `updateAgeOnGet` When using time-expiring entries with `maxAge`, + setting this to `true` will make each item's effective time update + to the current time whenever it is retrieved from cache, causing it + to not expire. (It can still fall out of cache based on recency of + use, of course.) + +## API + +* `set(key, value, maxAge)` +* `get(key) => value` + + Both of these will update the "recently used"-ness of the key. + They do what you think. `maxAge` is optional and overrides the + cache `maxAge` option if provided. + + If the key is not found, `get()` will return `undefined`. + + The key and val can be any value. + +* `peek(key)` + + Returns the key value (or `undefined` if not found) without + updating the "recently used"-ness of the key. + + (If you find yourself using this a lot, you *might* be using the + wrong sort of data structure, but there are some use cases where + it's handy.) + +* `del(key)` + + Deletes a key out of the cache. + +* `reset()` + + Clear the cache entirely, throwing away all values. + +* `has(key)` + + Check if a key is in the cache, without updating the recent-ness + or deleting it for being stale. + +* `forEach(function(value,key,cache), [thisp])` + + Just like `Array.prototype.forEach`. Iterates over all the keys + in the cache, in order of recent-ness. (Ie, more recently used + items are iterated over first.) + +* `rforEach(function(value,key,cache), [thisp])` + + The same as `cache.forEach(...)` but items are iterated over in + reverse order. (ie, less recently used items are iterated over + first.) + +* `keys()` + + Return an array of the keys in the cache. + +* `values()` + + Return an array of the values in the cache. + +* `length` + + Return total length of objects in cache taking into account + `length` options function. + +* `itemCount` + + Return total quantity of objects currently in cache. Note, that + `stale` (see options) items are returned as part of this item + count. + +* `dump()` + + Return an array of the cache entries ready for serialization and usage + with 'destinationCache.load(arr)`. + +* `load(cacheEntriesArray)` + + Loads another cache entries array, obtained with `sourceCache.dump()`, + into the cache. The destination cache is reset before loading new entries + +* `prune()` + + Manually iterates over the entire cache proactively pruning old entries diff --git a/node_modules/lru-cache/index.js b/node_modules/lru-cache/index.js new file mode 100644 index 0000000..573b6b8 --- /dev/null +++ b/node_modules/lru-cache/index.js @@ -0,0 +1,334 @@ +'use strict' + +// A linked list to keep track of recently-used-ness +const Yallist = require('yallist') + +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') + +const naiveLength = () => 1 + +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } + + if (!options) + options = {} + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity + + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) + } + trim(this) + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev + } + } + + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) + } + + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } + + const node = this[CACHE].get(key) + const item = node.value + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } + + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } + + const hit = new Entry(key, value, len, now, maxAge) + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) + + return false + } + + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } + + get (key) { + return get(this, key, true) + } + + peek (key) { + return get(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null + + del(this, node) + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)) + } + + load (arr) { + // reset the cache + this.reset() + + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } +} + +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } + } + return hit.value + } +} + +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) +} + +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev + } + } +} + +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) + + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) + } +} + +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 + } +} + +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) +} + +module.exports = LRUCache diff --git a/node_modules/lru-cache/package.json b/node_modules/lru-cache/package.json new file mode 100644 index 0000000..43b7502 --- /dev/null +++ b/node_modules/lru-cache/package.json @@ -0,0 +1,34 @@ +{ + "name": "lru-cache", + "description": "A cache object that deletes the least-recently-used items.", + "version": "6.0.0", + "author": "Isaac Z. Schlueter ", + "keywords": [ + "mru", + "lru", + "cache" + ], + "scripts": { + "test": "tap", + "snap": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags" + }, + "main": "index.js", + "repository": "git://github.com/isaacs/node-lru-cache.git", + "devDependencies": { + "benchmark": "^2.1.4", + "tap": "^14.10.7" + }, + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "files": [ + "index.js" + ], + "engines": { + "node": ">=10" + } +} diff --git a/node_modules/make-dir/index.d.ts b/node_modules/make-dir/index.d.ts new file mode 100644 index 0000000..3a78251 --- /dev/null +++ b/node_modules/make-dir/index.d.ts @@ -0,0 +1,66 @@ +/// +import * as fs from 'fs'; + +declare namespace makeDir { + interface Options { + /** + Directory [permissions](https://x-team.com/blog/file-system-permissions-umask-node-js/). + + @default 0o777 + */ + readonly mode?: number; + + /** + Use a custom `fs` implementation. For example [`graceful-fs`](https://github.com/isaacs/node-graceful-fs). + + Using a custom `fs` implementation will block the use of the native `recursive` option if `fs.mkdir` or `fs.mkdirSync` is not the native function. + + @default require('fs') + */ + readonly fs?: typeof fs; + } +} + +declare const makeDir: { + /** + Make a directory and its parents if needed - Think `mkdir -p`. + + @param path - Directory to create. + @returns The path to the created directory. + + @example + ``` + import makeDir = require('make-dir'); + + (async () => { + const path = await makeDir('unicorn/rainbow/cake'); + + console.log(path); + //=> '/Users/sindresorhus/fun/unicorn/rainbow/cake' + + // Multiple directories: + const paths = await Promise.all([ + makeDir('unicorn/rainbow'), + makeDir('foo/bar') + ]); + + console.log(paths); + // [ + // '/Users/sindresorhus/fun/unicorn/rainbow', + // '/Users/sindresorhus/fun/foo/bar' + // ] + })(); + ``` + */ + (path: string, options?: makeDir.Options): Promise; + + /** + Synchronously make a directory and its parents if needed - Think `mkdir -p`. + + @param path - Directory to create. + @returns The path to the created directory. + */ + sync(path: string, options?: makeDir.Options): string; +}; + +export = makeDir; diff --git a/node_modules/make-dir/index.js b/node_modules/make-dir/index.js new file mode 100644 index 0000000..75889d8 --- /dev/null +++ b/node_modules/make-dir/index.js @@ -0,0 +1,156 @@ +'use strict'; +const fs = require('fs'); +const path = require('path'); +const {promisify} = require('util'); +const semver = require('semver'); + +const useNativeRecursiveOption = semver.satisfies(process.version, '>=10.12.0'); + +// https://github.com/nodejs/node/issues/8987 +// https://github.com/libuv/libuv/pull/1088 +const checkPath = pth => { + if (process.platform === 'win32') { + const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')); + + if (pathHasInvalidWinCharacters) { + const error = new Error(`Path contains invalid characters: ${pth}`); + error.code = 'EINVAL'; + throw error; + } + } +}; + +const processOptions = options => { + // https://github.com/sindresorhus/make-dir/issues/18 + const defaults = { + mode: 0o777, + fs + }; + + return { + ...defaults, + ...options + }; +}; + +const permissionError = pth => { + // This replicates the exception of `fs.mkdir` with native the + // `recusive` option when run on an invalid drive under Windows. + const error = new Error(`operation not permitted, mkdir '${pth}'`); + error.code = 'EPERM'; + error.errno = -4048; + error.path = pth; + error.syscall = 'mkdir'; + return error; +}; + +const makeDir = async (input, options) => { + checkPath(input); + options = processOptions(options); + + const mkdir = promisify(options.fs.mkdir); + const stat = promisify(options.fs.stat); + + if (useNativeRecursiveOption && options.fs.mkdir === fs.mkdir) { + const pth = path.resolve(input); + + await mkdir(pth, { + mode: options.mode, + recursive: true + }); + + return pth; + } + + const make = async pth => { + try { + await mkdir(pth, options.mode); + + return pth; + } catch (error) { + if (error.code === 'EPERM') { + throw error; + } + + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth); + } + + if (error.message.includes('null bytes')) { + throw error; + } + + await make(path.dirname(pth)); + + return make(pth); + } + + try { + const stats = await stat(pth); + if (!stats.isDirectory()) { + throw new Error('The path is not a directory'); + } + } catch (_) { + throw error; + } + + return pth; + } + }; + + return make(path.resolve(input)); +}; + +module.exports = makeDir; + +module.exports.sync = (input, options) => { + checkPath(input); + options = processOptions(options); + + if (useNativeRecursiveOption && options.fs.mkdirSync === fs.mkdirSync) { + const pth = path.resolve(input); + + fs.mkdirSync(pth, { + mode: options.mode, + recursive: true + }); + + return pth; + } + + const make = pth => { + try { + options.fs.mkdirSync(pth, options.mode); + } catch (error) { + if (error.code === 'EPERM') { + throw error; + } + + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth); + } + + if (error.message.includes('null bytes')) { + throw error; + } + + make(path.dirname(pth)); + return make(pth); + } + + try { + if (!options.fs.statSync(pth).isDirectory()) { + throw new Error('The path is not a directory'); + } + } catch (_) { + throw error; + } + } + + return pth; + }; + + return make(path.resolve(input)); +}; diff --git a/node_modules/make-dir/license b/node_modules/make-dir/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/make-dir/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/make-dir/node_modules/.bin/semver b/node_modules/make-dir/node_modules/.bin/semver new file mode 100644 index 0000000..77443e7 --- /dev/null +++ b/node_modules/make-dir/node_modules/.bin/semver @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../semver/bin/semver.js" "$@" +else + exec node "$basedir/../semver/bin/semver.js" "$@" +fi diff --git a/node_modules/make-dir/node_modules/.bin/semver.cmd b/node_modules/make-dir/node_modules/.bin/semver.cmd new file mode 100644 index 0000000..9913fa9 --- /dev/null +++ b/node_modules/make-dir/node_modules/.bin/semver.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %* diff --git a/node_modules/make-dir/node_modules/.bin/semver.ps1 b/node_modules/make-dir/node_modules/.bin/semver.ps1 new file mode 100644 index 0000000..314717a --- /dev/null +++ b/node_modules/make-dir/node_modules/.bin/semver.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args + } else { + & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../semver/bin/semver.js" $args + } else { + & "node$exe" "$basedir/../semver/bin/semver.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/make-dir/node_modules/semver/CHANGELOG.md b/node_modules/make-dir/node_modules/semver/CHANGELOG.md new file mode 100644 index 0000000..f567dd3 --- /dev/null +++ b/node_modules/make-dir/node_modules/semver/CHANGELOG.md @@ -0,0 +1,70 @@ +# changes log + +## 6.2.0 + +* Coerce numbers to strings when passed to semver.coerce() +* Add `rtl` option to coerce from right to left + +## 6.1.3 + +* Handle X-ranges properly in includePrerelease mode + +## 6.1.2 + +* Do not throw when testing invalid version strings + +## 6.1.1 + +* Add options support for semver.coerce() +* Handle undefined version passed to Range.test + +## 6.1.0 + +* Add semver.compareBuild function +* Support `*` in semver.intersects + +## 6.0 + +* Fix `intersects` logic. + + This is technically a bug fix, but since it is also a change to behavior + that may require users updating their code, it is marked as a major + version increment. + +## 5.7 + +* Add `minVersion` method + +## 5.6 + +* Move boolean `loose` param to an options object, with + backwards-compatibility protection. +* Add ability to opt out of special prerelease version handling with + the `includePrerelease` option flag. + +## 5.5 + +* Add version coercion capabilities + +## 5.4 + +* Add intersection checking + +## 5.3 + +* Add `minSatisfying` method + +## 5.2 + +* Add `prerelease(v)` that returns prerelease components + +## 5.1 + +* Add Backus-Naur for ranges +* Remove excessively cute inspection methods + +## 5.0 + +* Remove AMD/Browserified build artifacts +* Fix ltr and gtr when using the `*` range +* Fix for range `*` with a prerelease identifier diff --git a/node_modules/make-dir/node_modules/semver/LICENSE b/node_modules/make-dir/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/make-dir/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/make-dir/node_modules/semver/README.md b/node_modules/make-dir/node_modules/semver/README.md new file mode 100644 index 0000000..2293a14 --- /dev/null +++ b/node_modules/make-dir/node_modules/semver/README.md @@ -0,0 +1,443 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `2.1.5` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` diff --git a/node_modules/make-dir/node_modules/semver/bin/semver.js b/node_modules/make-dir/node_modules/semver/bin/semver.js new file mode 100644 index 0000000..666034a --- /dev/null +++ b/node_modules/make-dir/node_modules/semver/bin/semver.js @@ -0,0 +1,174 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + +var versions = [] + +var range = [] + +var inc = null + +var version = require('../package.json').version + +var loose = false + +var includePrerelease = false + +var coerce = false + +var rtl = false + +var identifier + +var semver = require('../semver') + +var reverse = false + +var options = {} + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + var options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl } + + versions = versions.map(function (v) { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter(function (v) { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (var i = 0, l = range.length; i < l; i++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error('--inc can only be used on a single version with no range') + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? 'rcompare' : 'compare' + versions.sort(function (a, b) { + return semver[compare](a, b, options) + }).map(function (v) { + return semver.clean(v, options) + }).map(function (v) { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach(function (v, i, _) { console.log(v) }) +} + +function help () { + console.log(['SemVer ' + version, + '', + 'A JavaScript implementation of the https://semver.org/ specification', + 'Copyright Isaac Z. Schlueter', + '', + 'Usage: semver [options] [ [...]]', + 'Prints valid versions sorted by SemVer precedence', + '', + 'Options:', + '-r --range ', + ' Print versions that match the specified range.', + '', + '-i --increment []', + ' Increment a version by the specified level. Level can', + ' be one of: major, minor, patch, premajor, preminor,', + " prepatch, or prerelease. Default level is 'patch'.", + ' Only one version may be specified.', + '', + '--preid ', + ' Identifier to be used to prefix premajor, preminor,', + ' prepatch or prerelease version increments.', + '', + '-l --loose', + ' Interpret versions and ranges loosely', + '', + '-p --include-prerelease', + ' Always include prerelease versions in range matching', + '', + '-c --coerce', + ' Coerce a string into SemVer if possible', + ' (does not imply --loose)', + '', + '--rtl', + ' Coerce version strings right to left', + '', + '--ltr', + ' Coerce version strings left to right (default)', + '', + 'Program exits successfully if any valid version satisfies', + 'all supplied ranges, and prints all satisfying versions.', + '', + 'If no satisfying versions are found, then exits failure.', + '', + 'Versions are printed in ascending order, so supplying', + 'multiple versions to the utility will just sort them.' + ].join('\n')) +} diff --git a/node_modules/make-dir/node_modules/semver/package.json b/node_modules/make-dir/node_modules/semver/package.json new file mode 100644 index 0000000..bdd442f --- /dev/null +++ b/node_modules/make-dir/node_modules/semver/package.json @@ -0,0 +1,28 @@ +{ + "name": "semver", + "version": "6.3.0", + "description": "The semantic version parser used by npm.", + "main": "semver.js", + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --follow-tags" + }, + "devDependencies": { + "tap": "^14.3.1" + }, + "license": "ISC", + "repository": "https://github.com/npm/node-semver", + "bin": { + "semver": "./bin/semver.js" + }, + "files": [ + "bin", + "range.bnf", + "semver.js" + ], + "tap": { + "check-coverage": true + } +} diff --git a/node_modules/make-dir/node_modules/semver/range.bnf b/node_modules/make-dir/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/make-dir/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/make-dir/node_modules/semver/semver.js b/node_modules/make-dir/node_modules/semver/semver.js new file mode 100644 index 0000000..636fa43 --- /dev/null +++ b/node_modules/make-dir/node_modules/semver/semver.js @@ -0,0 +1,1596 @@ +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var t = exports.tokens = {} +var R = 0 + +function tok (n) { + t[n] = R++ +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +tok('NUMERICIDENTIFIER') +src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' +tok('NUMERICIDENTIFIERLOOSE') +src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +tok('NONNUMERICIDENTIFIER') +src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +tok('MAINVERSION') +src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')' + +tok('MAINVERSIONLOOSE') +src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +tok('PRERELEASEIDENTIFIER') +src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +tok('PRERELEASEIDENTIFIERLOOSE') +src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +tok('PRERELEASE') +src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' + +tok('PRERELEASELOOSE') +src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +tok('BUILDIDENTIFIER') +src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +tok('BUILD') +src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +tok('FULL') +tok('FULLPLAIN') +src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + + src[t.PRERELEASE] + '?' + + src[t.BUILD] + '?' + +src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +tok('LOOSEPLAIN') +src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + + src[t.PRERELEASELOOSE] + '?' + + src[t.BUILD] + '?' + +tok('LOOSE') +src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' + +tok('GTLT') +src[t.GTLT] = '((?:<|>)?=?)' + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +tok('XRANGEIDENTIFIERLOOSE') +src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +tok('XRANGEIDENTIFIER') +src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' + +tok('XRANGEPLAIN') +src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:' + src[t.PRERELEASE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' + +tok('XRANGEPLAINLOOSE') +src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[t.PRERELEASELOOSE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' + +tok('XRANGE') +src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' +tok('XRANGELOOSE') +src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +tok('COERCE') +src[t.COERCE] = '(^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' +tok('COERCERTL') +re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +tok('LONETILDE') +src[t.LONETILDE] = '(?:~>?)' + +tok('TILDETRIM') +src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' +re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') +var tildeTrimReplace = '$1~' + +tok('TILDE') +src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' +tok('TILDELOOSE') +src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +tok('LONECARET') +src[t.LONECARET] = '(?:\\^)' + +tok('CARETTRIM') +src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' +re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') +var caretTrimReplace = '$1^' + +tok('CARET') +src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' +tok('CARETLOOSE') +src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +tok('COMPARATORLOOSE') +src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' +tok('COMPARATOR') +src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +tok('COMPARATORTRIM') +src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +tok('HYPHENRANGE') +src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAIN] + ')' + + '\\s*$' + +tok('HYPHENRANGELOOSE') +src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +tok('STAR') +src[t.STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? re[t.LOOSE] : re[t.FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +SemVer.prototype.compareBuild = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + var i = 0 + do { + var a = this.build[i] + var b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} + +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} + +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.compareBuild = compareBuild +function compareBuild (a, b, loose) { + var versionA = new SemVer(a, loose) + var versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(b, a, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + var rangeTmp + + if (this.operator === '') { + if (this.value === '') { + return true + } + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options) + } + + if (!(this instanceof Range)) { + return new Range(range, options) + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } + + this.format() +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} + +Range.prototype.toString = function () { + return this.range +} + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[t.COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) + + return set +} + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return ( + isSatisfiable(thisComparators, options) && + range.set.some(function (rangeComparators) { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every(function (thisComparator) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) +} + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +function isSatisfiable (comparators, options) { + var result = true + var remainingComparators = comparators.slice() + var testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every(function (otherComparator) { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} + +function replaceTilde (comp, options) { + var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} + +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } + + debug('caret return', ret) + return ret + }) +} + +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} + +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + ret = gtlt + M + '.' + m + '.' + p + pr + } else if (xm) { + ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr + } else if (xp) { + ret = '>=' + M + '.' + m + '.0' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + pr + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[t.STAR], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } + + return (from + ' ' + to).trim() +} + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} + +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} + +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} + +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} + +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} + +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + var high = null + var low = null + + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} + +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version, options) { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + var match = null + if (!options.rtl) { + match = version.match(re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + var next + while ((next = re[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + re[t.COERCERTL].lastIndex = -1 + } + + if (match === null) { + return null + } + + return parse(match[2] + + '.' + (match[3] || '0') + + '.' + (match[4] || '0'), options) +} diff --git a/node_modules/make-dir/package.json b/node_modules/make-dir/package.json new file mode 100644 index 0000000..98403ea --- /dev/null +++ b/node_modules/make-dir/package.json @@ -0,0 +1,59 @@ +{ + "name": "make-dir", + "version": "3.1.0", + "description": "Make a directory and its parents if needed - Think `mkdir -p`", + "license": "MIT", + "repository": "sindresorhus/make-dir", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && nyc ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "mkdir", + "mkdirp", + "make", + "directories", + "dir", + "dirs", + "folders", + "directory", + "folder", + "path", + "parent", + "parents", + "intermediate", + "recursively", + "recursive", + "create", + "fs", + "filesystem", + "file-system" + ], + "dependencies": { + "semver": "^6.0.0" + }, + "devDependencies": { + "@types/graceful-fs": "^4.1.3", + "@types/node": "^13.7.1", + "ava": "^1.4.0", + "codecov": "^3.2.0", + "graceful-fs": "^4.1.15", + "nyc": "^15.0.0", + "path-type": "^4.0.0", + "tempy": "^0.2.1", + "tsd": "^0.11.0", + "xo": "^0.25.4" + } +} diff --git a/node_modules/make-dir/readme.md b/node_modules/make-dir/readme.md new file mode 100644 index 0000000..a10a1a4 --- /dev/null +++ b/node_modules/make-dir/readme.md @@ -0,0 +1,125 @@ +# make-dir [![Build Status](https://travis-ci.org/sindresorhus/make-dir.svg?branch=master)](https://travis-ci.org/sindresorhus/make-dir) [![codecov](https://codecov.io/gh/sindresorhus/make-dir/branch/master/graph/badge.svg)](https://codecov.io/gh/sindresorhus/make-dir) + +> Make a directory and its parents if needed - Think `mkdir -p` + +## Advantages over [`mkdirp`](https://github.com/substack/node-mkdirp) + +- Promise API *(Async/await ready!)* +- Fixes many `mkdirp` issues: [#96](https://github.com/substack/node-mkdirp/pull/96) [#70](https://github.com/substack/node-mkdirp/issues/70) [#66](https://github.com/substack/node-mkdirp/issues/66) +- 100% test coverage +- CI-tested on macOS, Linux, and Windows +- Actively maintained +- Doesn't bundle a CLI +- Uses the native `fs.mkdir/mkdirSync` [`recursive` option](https://nodejs.org/dist/latest/docs/api/fs.html#fs_fs_mkdir_path_options_callback) in Node.js >=10.12.0 unless [overridden](#fs) + +## Install + +``` +$ npm install make-dir +``` + +## Usage + +``` +$ pwd +/Users/sindresorhus/fun +$ tree +. +``` + +```js +const makeDir = require('make-dir'); + +(async () => { + const path = await makeDir('unicorn/rainbow/cake'); + + console.log(path); + //=> '/Users/sindresorhus/fun/unicorn/rainbow/cake' +})(); +``` + +``` +$ tree +. +└── unicorn + └── rainbow + └── cake +``` + +Multiple directories: + +```js +const makeDir = require('make-dir'); + +(async () => { + const paths = await Promise.all([ + makeDir('unicorn/rainbow'), + makeDir('foo/bar') + ]); + + console.log(paths); + /* + [ + '/Users/sindresorhus/fun/unicorn/rainbow', + '/Users/sindresorhus/fun/foo/bar' + ] + */ +})(); +``` + +## API + +### makeDir(path, options?) + +Returns a `Promise` for the path to the created directory. + +### makeDir.sync(path, options?) + +Returns the path to the created directory. + +#### path + +Type: `string` + +Directory to create. + +#### options + +Type: `object` + +##### mode + +Type: `integer`\ +Default: `0o777` + +Directory [permissions](https://x-team.com/blog/file-system-permissions-umask-node-js/). + +##### fs + +Type: `object`\ +Default: `require('fs')` + +Use a custom `fs` implementation. For example [`graceful-fs`](https://github.com/isaacs/node-graceful-fs). + +Using a custom `fs` implementation will block the use of the native `recursive` option if `fs.mkdir` or `fs.mkdirSync` is not the native function. + +## Related + +- [make-dir-cli](https://github.com/sindresorhus/make-dir-cli) - CLI for this module +- [del](https://github.com/sindresorhus/del) - Delete files and directories +- [globby](https://github.com/sindresorhus/globby) - User-friendly glob matching +- [cpy](https://github.com/sindresorhus/cpy) - Copy files +- [cpy-cli](https://github.com/sindresorhus/cpy-cli) - Copy files on the command-line +- [move-file](https://github.com/sindresorhus/move-file) - Move a file + +--- + +
+ + 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/media-typer/HISTORY.md b/node_modules/media-typer/HISTORY.md new file mode 100644 index 0000000..62c2003 --- /dev/null +++ b/node_modules/media-typer/HISTORY.md @@ -0,0 +1,22 @@ +0.3.0 / 2014-09-07 +================== + + * Support Node.js 0.6 + * Throw error when parameter format invalid on parse + +0.2.0 / 2014-06-18 +================== + + * Add `typer.format()` to format media types + +0.1.0 / 2014-06-17 +================== + + * Accept `req` as argument to `parse` + * Accept `res` as argument to `parse` + * Parse media type with extra LWS between type and first parameter + +0.0.0 / 2014-06-13 +================== + + * Initial implementation diff --git a/node_modules/media-typer/LICENSE b/node_modules/media-typer/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +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/media-typer/README.md b/node_modules/media-typer/README.md new file mode 100644 index 0000000..d8df623 --- /dev/null +++ b/node_modules/media-typer/README.md @@ -0,0 +1,81 @@ +# media-typer + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Simple RFC 6838 media type parser + +## Installation + +```sh +$ npm install media-typer +``` + +## API + +```js +var typer = require('media-typer') +``` + +### typer.parse(string) + +```js +var obj = typer.parse('image/svg+xml; charset=utf-8') +``` + +Parse a media type string. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The type of the media type (always lower case). Example: `'image'` + + - `subtype`: The subtype of the media type (always lower case). Example: `'svg'` + + - `suffix`: The suffix of the media type (always lower case). Example: `'xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter always lower case). Example: `{charset: 'utf-8'}` + +### typer.parse(req) + +```js +var obj = typer.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`typer.parse(req.headers['content-type'])`. + +### typer.parse(res) + +```js +var obj = typer.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`typer.parse(res.getHeader('content-type'))`. + +### typer.format(obj) + +```js +var obj = typer.format({type: 'image', subtype: 'svg', suffix: 'xml'}) +``` + +Format an object into a media type string. This will return a string of the +mime type for the given object. For the properties of the object, see the +documentation for `typer.parse(string)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/media-typer.svg?style=flat +[npm-url]: https://npmjs.org/package/media-typer +[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/media-typer.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/media-typer +[coveralls-image]: https://img.shields.io/coveralls/jshttp/media-typer.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/media-typer +[downloads-image]: https://img.shields.io/npm/dm/media-typer.svg?style=flat +[downloads-url]: https://npmjs.org/package/media-typer diff --git a/node_modules/media-typer/index.js b/node_modules/media-typer/index.js new file mode 100644 index 0000000..07f7295 --- /dev/null +++ b/node_modules/media-typer/index.js @@ -0,0 +1,270 @@ +/*! + * media-typer + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7 + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * SHT = + * CTL = + * OCTET = + */ +var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; +var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ + +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + */ +var qescRegExp = /\\([\u0000-\u007f])/g; + +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + */ +var quoteRegExp = /([\\"])/g; + +/** + * RegExp to match type in RFC 6838 + * + * type-name = restricted-name + * subtype-name = restricted-name + * restricted-name = restricted-name-first *126restricted-name-chars + * restricted-name-first = ALPHA / DIGIT + * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / + * "$" / "&" / "-" / "^" / "_" + * restricted-name-chars =/ "." ; Characters before first dot always + * ; specify a facet name + * restricted-name-chars =/ "+" ; Characters after last plus always + * ; specify a structured syntax suffix + * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z + * DIGIT = %x30-39 ; 0-9 + */ +var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ +var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ +var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; + +/** + * Module exports. + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @api public + */ + +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var subtype = obj.subtype + var suffix = obj.suffix + var type = obj.type + + if (!type || !typeNameRegExp.test(type)) { + throw new TypeError('invalid type') + } + + if (!subtype || !subtypeNameRegExp.test(subtype)) { + throw new TypeError('invalid subtype') + } + + // format as type/subtype + var string = type + '/' + subtype + + // append +suffix + if (suffix) { + if (!typeNameRegExp.test(suffix)) { + throw new TypeError('invalid suffix') + } + + string += '+' + suffix + } + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + if (!tokenRegExp.test(param)) { + throw new TypeError('invalid parameter name') + } + + string += '; ' + param + '=' + qstring(parameters[param]) + } + } + + return string +} + +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @api public + */ + +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } + + // support req/res-like objects as argument + if (typeof string === 'object') { + string = getcontenttype(string) + } + + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = string.indexOf(';') + var type = index !== -1 + ? string.substr(0, index) + : string + + var key + var match + var obj = splitType(type) + var params = {} + var value + + paramRegExp.lastIndex = index + + while (match = paramRegExp.exec(string)) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(qescRegExp, '$1') + } + + params[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + obj.parameters = params + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @api private + */ + +function getcontenttype(obj) { + if (typeof obj.getHeader === 'function') { + // res-like + return obj.getHeader('content-type') + } + + if (typeof obj.headers === 'object') { + // req-like + return obj.headers && obj.headers['content-type'] + } +} + +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @api private + */ + +function qstring(val) { + var str = String(val) + + // no need to quote tokens + if (tokenRegExp.test(str)) { + return str + } + + if (str.length > 0 && !textRegExp.test(str)) { + throw new TypeError('invalid parameter value') + } + + return '"' + str.replace(quoteRegExp, '\\$1') + '"' +} + +/** + * Simply "type/subtype+siffx" into parts. + * + * @param {string} string + * @return {Object} + * @api private + */ + +function splitType(string) { + var match = typeRegExp.exec(string.toLowerCase()) + + if (!match) { + throw new TypeError('invalid media type') + } + + var type = match[1] + var subtype = match[2] + var suffix + + // suffix after last + + var index = subtype.lastIndexOf('+') + if (index !== -1) { + suffix = subtype.substr(index + 1) + subtype = subtype.substr(0, index) + } + + var obj = { + type: type, + subtype: subtype, + suffix: suffix + } + + return obj +} diff --git a/node_modules/media-typer/package.json b/node_modules/media-typer/package.json new file mode 100644 index 0000000..8cf3ebc --- /dev/null +++ b/node_modules/media-typer/package.json @@ -0,0 +1,26 @@ +{ + "name": "media-typer", + "description": "Simple RFC 6838 media type parser and formatter", + "version": "0.3.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "jshttp/media-typer", + "devDependencies": { + "istanbul": "0.3.2", + "mocha": "~1.21.4", + "should": "~4.0.4" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/memory-pager/.travis.yml b/node_modules/memory-pager/.travis.yml new file mode 100644 index 0000000..1c4ab31 --- /dev/null +++ b/node_modules/memory-pager/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - '4' + - '6' diff --git a/node_modules/memory-pager/LICENSE b/node_modules/memory-pager/LICENSE new file mode 100644 index 0000000..56fce08 --- /dev/null +++ b/node_modules/memory-pager/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/memory-pager/README.md b/node_modules/memory-pager/README.md new file mode 100644 index 0000000..aed1761 --- /dev/null +++ b/node_modules/memory-pager/README.md @@ -0,0 +1,65 @@ +# memory-pager + +Access memory using small fixed sized buffers instead of allocating a huge buffer. +Useful if you are implementing sparse data structures (such as large bitfield). + +![travis](https://travis-ci.org/mafintosh/memory-pager.svg?branch=master) + +``` +npm install memory-pager +``` + +## Usage + +``` js +var pager = require('paged-memory') + +var pages = pager(1024) // use 1kb per page + +var page = pages.get(10) // get page #10 + +console.log(page.offset) // 10240 +console.log(page.buffer) // a blank 1kb buffer +``` + +## API + +#### `var pages = pager(pageSize)` + +Create a new pager. `pageSize` defaults to `1024`. + +#### `var page = pages.get(pageNumber, [noAllocate])` + +Get a page. The page will be allocated at first access. + +Optionally you can set the `noAllocate` flag which will make the +method return undefined if no page has been allocated already + +A page looks like this + +``` js +{ + offset: byteOffset, + buffer: bufferWithPageSize +} +``` + +#### `pages.set(pageNumber, buffer)` + +Explicitly set the buffer for a page. + +#### `pages.updated(page)` + +Mark a page as updated. + +#### `pages.lastUpdate()` + +Get the last page that was updated. + +#### `var buf = pages.toBuffer()` + +Concat all pages allocated pages into a single buffer + +## License + +MIT diff --git a/node_modules/memory-pager/index.js b/node_modules/memory-pager/index.js new file mode 100644 index 0000000..687f346 --- /dev/null +++ b/node_modules/memory-pager/index.js @@ -0,0 +1,160 @@ +module.exports = Pager + +function Pager (pageSize, opts) { + if (!(this instanceof Pager)) return new Pager(pageSize, opts) + + this.length = 0 + this.updates = [] + this.path = new Uint16Array(4) + this.pages = new Array(32768) + this.maxPages = this.pages.length + this.level = 0 + this.pageSize = pageSize || 1024 + this.deduplicate = opts ? opts.deduplicate : null + this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null +} + +Pager.prototype.updated = function (page) { + while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { + page.deduplicate++ + if (page.deduplicate === this.deduplicate.length) { + page.deduplicate = 0 + if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate + break + } + } + if (page.updated || !this.updates) return + page.updated = true + this.updates.push(page) +} + +Pager.prototype.lastUpdate = function () { + if (!this.updates || !this.updates.length) return null + var page = this.updates.pop() + page.updated = false + return page +} + +Pager.prototype._array = function (i, noAllocate) { + if (i >= this.maxPages) { + if (noAllocate) return + grow(this, i) + } + + factor(i, this.path) + + var arr = this.pages + + for (var j = this.level; j > 0; j--) { + var p = this.path[j] + var next = arr[p] + + if (!next) { + if (noAllocate) return + next = arr[p] = new Array(32768) + } + + arr = next + } + + return arr +} + +Pager.prototype.get = function (i, noAllocate) { + var arr = this._array(i, noAllocate) + var first = this.path[0] + var page = arr && arr[first] + + if (!page && !noAllocate) { + page = arr[first] = new Page(i, alloc(this.pageSize)) + if (i >= this.length) this.length = i + 1 + } + + if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { + page.buffer = copy(page.buffer) + page.deduplicate = 0 + } + + return page +} + +Pager.prototype.set = function (i, buf) { + var arr = this._array(i, false) + var first = this.path[0] + + if (i >= this.length) this.length = i + 1 + + if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { + arr[first] = undefined + return + } + + if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { + buf = this.deduplicate + } + + var page = arr[first] + var b = truncate(buf, this.pageSize) + + if (page) page.buffer = b + else arr[first] = new Page(i, b) +} + +Pager.prototype.toBuffer = function () { + var list = new Array(this.length) + var empty = alloc(this.pageSize) + var ptr = 0 + + while (ptr < list.length) { + var arr = this._array(ptr, true) + for (var i = 0; i < 32768 && ptr < list.length; i++) { + list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty + } + } + + return Buffer.concat(list) +} + +function grow (pager, index) { + while (pager.maxPages < index) { + var old = pager.pages + pager.pages = new Array(32768) + pager.pages[0] = old + pager.level++ + pager.maxPages *= 32768 + } +} + +function truncate (buf, len) { + if (buf.length === len) return buf + if (buf.length > len) return buf.slice(0, len) + var cpy = alloc(len) + buf.copy(cpy) + return cpy +} + +function alloc (size) { + if (Buffer.alloc) return Buffer.alloc(size) + var buf = new Buffer(size) + buf.fill(0) + return buf +} + +function copy (buf) { + var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length) + buf.copy(cpy) + return cpy +} + +function Page (i, buf) { + this.offset = i * buf.length + this.buffer = buf + this.updated = false + this.deduplicate = 0 +} + +function factor (n, out) { + n = (n - (out[0] = (n & 32767))) / 32768 + n = (n - (out[1] = (n & 32767))) / 32768 + out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767 +} diff --git a/node_modules/memory-pager/package.json b/node_modules/memory-pager/package.json new file mode 100644 index 0000000..f4847e8 --- /dev/null +++ b/node_modules/memory-pager/package.json @@ -0,0 +1,24 @@ +{ + "name": "memory-pager", + "version": "1.5.0", + "description": "Access memory using small fixed sized buffers", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/memory-pager.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/memory-pager/issues" + }, + "homepage": "https://github.com/mafintosh/memory-pager" +} diff --git a/node_modules/memory-pager/test.js b/node_modules/memory-pager/test.js new file mode 100644 index 0000000..1638210 --- /dev/null +++ b/node_modules/memory-pager/test.js @@ -0,0 +1,80 @@ +var tape = require('tape') +var pager = require('./') + +tape('get page', function (t) { + var pages = pager(1024) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.end() +}) + +tape('get page twice', function (t) { + var pages = pager(1024) + t.same(pages.length, 0) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1) + + var other = pages.get(0) + + t.same(other, page) + t.end() +}) + +tape('get no mutable page', function (t) { + var pages = pager(1024) + + t.ok(!pages.get(141, true)) + t.ok(pages.get(141)) + t.ok(pages.get(141, true)) + + t.end() +}) + +tape('get far out page', function (t) { + var pages = pager(1024) + + var page = pages.get(1000000) + + t.same(page.offset, 1000000 * 1024) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + + var other = pages.get(1) + + t.same(other.offset, 1024) + t.same(other.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + t.ok(other !== page) + + t.end() +}) + +tape('updates', function (t) { + var pages = pager(1024) + + t.same(pages.lastUpdate(), null) + + var page = pages.get(10) + + page.buffer[42] = 1 + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + page.buffer[42] = 2 + pages.updated(page) + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + t.end() +}) diff --git a/node_modules/merge-descriptors/HISTORY.md b/node_modules/merge-descriptors/HISTORY.md new file mode 100644 index 0000000..486771f --- /dev/null +++ b/node_modules/merge-descriptors/HISTORY.md @@ -0,0 +1,21 @@ +1.0.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.0.0 / 2015-03-01 +================== + + * Add option to only add new descriptors + * Add simple argument validation + * Add jsdoc to source file + +0.0.2 / 2013-12-14 +================== + + * Move repository to `component` organization + +0.0.1 / 2013-10-29 +================== + + * Initial release diff --git a/node_modules/merge-descriptors/LICENSE b/node_modules/merge-descriptors/LICENSE new file mode 100644 index 0000000..274bfd8 --- /dev/null +++ b/node_modules/merge-descriptors/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +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/merge-descriptors/README.md b/node_modules/merge-descriptors/README.md new file mode 100644 index 0000000..d593c0e --- /dev/null +++ b/node_modules/merge-descriptors/README.md @@ -0,0 +1,48 @@ +# Merge Descriptors + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Merge objects using descriptors. + +```js +var thing = { + get name() { + return 'jon' + } +} + +var animal = { + +} + +merge(animal, thing) + +animal.name === 'jon' +``` + +## API + +### merge(destination, source) + +Redefines `destination`'s descriptors with `source`'s. + +### merge(destination, source, false) + +Defines `source`'s descriptors on `destination` if `destination` does not have +a descriptor by the same name. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/merge-descriptors.svg +[npm-url]: https://npmjs.org/package/merge-descriptors +[travis-image]: https://img.shields.io/travis/component/merge-descriptors/master.svg +[travis-url]: https://travis-ci.org/component/merge-descriptors +[coveralls-image]: https://img.shields.io/coveralls/component/merge-descriptors/master.svg +[coveralls-url]: https://coveralls.io/r/component/merge-descriptors?branch=master +[downloads-image]: https://img.shields.io/npm/dm/merge-descriptors.svg +[downloads-url]: https://npmjs.org/package/merge-descriptors diff --git a/node_modules/merge-descriptors/index.js b/node_modules/merge-descriptors/index.js new file mode 100644 index 0000000..573b132 --- /dev/null +++ b/node_modules/merge-descriptors/index.js @@ -0,0 +1,60 @@ +/*! + * merge-descriptors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = merge + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty + +/** + * Merge the property descriptors of `src` into `dest` + * + * @param {object} dest Object to add descriptors to + * @param {object} src Object to clone descriptors from + * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties + * @returns {object} Reference to dest + * @public + */ + +function merge(dest, src, redefine) { + if (!dest) { + throw new TypeError('argument dest is required') + } + + if (!src) { + throw new TypeError('argument src is required') + } + + if (redefine === undefined) { + // Default to true + redefine = true + } + + Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) { + if (!redefine && hasOwnProperty.call(dest, name)) { + // Skip desriptor + return + } + + // Copy descriptor + var descriptor = Object.getOwnPropertyDescriptor(src, name) + Object.defineProperty(dest, name, descriptor) + }) + + return dest +} diff --git a/node_modules/merge-descriptors/package.json b/node_modules/merge-descriptors/package.json new file mode 100644 index 0000000..514cdbd --- /dev/null +++ b/node_modules/merge-descriptors/package.json @@ -0,0 +1,32 @@ +{ + "name": "merge-descriptors", + "description": "Merge objects using descriptors", + "version": "1.0.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "contributors": [ + "Douglas Christopher Wilson ", + "Mike Grabowski " + ], + "license": "MIT", + "repository": "component/merge-descriptors", + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + } +} diff --git a/node_modules/methods/HISTORY.md b/node_modules/methods/HISTORY.md new file mode 100644 index 0000000..c0ecf07 --- /dev/null +++ b/node_modules/methods/HISTORY.md @@ -0,0 +1,29 @@ +1.1.2 / 2016-01-17 +================== + + * perf: enable strict mode + +1.1.1 / 2014-12-30 +================== + + * Improve `browserify` support + +1.1.0 / 2014-07-05 +================== + + * Add `CONNECT` method + +1.0.1 / 2014-06-02 +================== + + * Fix module to work with harmony transform + +1.0.0 / 2014-05-08 +================== + + * Add `PURGE` method + +0.1.0 / 2013-10-28 +================== + + * Add `http.METHODS` support diff --git a/node_modules/methods/LICENSE b/node_modules/methods/LICENSE new file mode 100644 index 0000000..220dc1a --- /dev/null +++ b/node_modules/methods/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2013-2014 TJ Holowaychuk +Copyright (c) 2015-2016 Douglas Christopher Wilson + +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/methods/README.md b/node_modules/methods/README.md new file mode 100644 index 0000000..672a32b --- /dev/null +++ b/node_modules/methods/README.md @@ -0,0 +1,51 @@ +# Methods + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP verbs that Node.js core's HTTP parser supports. + +This module provides an export that is just like `http.METHODS` from Node.js core, +with the following differences: + + * All method names are lower-cased. + * Contains a fallback list of methods for Node.js versions that do not have a + `http.METHODS` export (0.10 and lower). + * Provides the fallback list when using tools like `browserify` without pulling + in the `http` shim module. + +## Install + +```bash +$ npm install methods +``` + +## API + +```js +var methods = require('methods') +``` + +### methods + +This is an array of lower-cased method names that Node.js supports. If Node.js +provides the `http.METHODS` export, then this is the same array lower-cased, +otherwise it is a snapshot of the verbs from Node.js 0.10. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/methods.svg?style=flat +[npm-url]: https://npmjs.org/package/methods +[node-version-image]: https://img.shields.io/node/v/methods.svg?style=flat +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/methods.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/methods +[coveralls-image]: https://img.shields.io/coveralls/jshttp/methods.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/methods?branch=master +[downloads-image]: https://img.shields.io/npm/dm/methods.svg?style=flat +[downloads-url]: https://npmjs.org/package/methods diff --git a/node_modules/methods/index.js b/node_modules/methods/index.js new file mode 100644 index 0000000..667a50b --- /dev/null +++ b/node_modules/methods/index.js @@ -0,0 +1,69 @@ +/*! + * methods + * Copyright(c) 2013-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var http = require('http'); + +/** + * Module exports. + * @public + */ + +module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); + +/** + * Get the current Node.js methods. + * @private + */ + +function getCurrentNodeMethods() { + return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { + return method.toLowerCase(); + }); +} + +/** + * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * @private + */ + +function getBasicNodeMethods() { + return [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search', + 'connect' + ]; +} diff --git a/node_modules/methods/package.json b/node_modules/methods/package.json new file mode 100644 index 0000000..c4ce6f0 --- /dev/null +++ b/node_modules/methods/package.json @@ -0,0 +1,36 @@ +{ + "name": "methods", + "description": "HTTP methods that node supports", + "version": "1.1.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "TJ Holowaychuk (http://tjholowaychuk.com)" + ], + "license": "MIT", + "repository": "jshttp/methods", + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "index.js", + "HISTORY.md", + "LICENSE" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "browser": { + "http": false + }, + "keywords": [ + "http", + "methods" + ] +} diff --git a/node_modules/mime-db/HISTORY.md b/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..622adb9 --- /dev/null +++ b/node_modules/mime-db/HISTORY.md @@ -0,0 +1,492 @@ +1.50.0 / 2021-09-15 +=================== + + * Add deprecated iWorks mime types and extensions + * Add new upstream MIME types + +1.49.0 / 2021-07-26 +=================== + + * Add extension `.trig` to `application/trig` + * Add new upstream MIME types + +1.48.0 / 2021-05-30 +=================== + + * Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + * Add new upstream MIME types + * Mark `text/yaml` as compressible + +1.47.0 / 2021-04-01 +=================== + + * Add new upstream MIME types + * Remove ambigious extensions from IANA for `application/*+xml` types + * Update primary extension to `.es` for `application/ecmascript` + +1.46.0 / 2021-02-13 +=================== + + * Add extension `.amr` to `audio/amr` + * Add extension `.m4s` to `video/iso.segment` + * Add extension `.opus` to `audio/ogg` + * Add new upstream MIME types + +1.45.0 / 2020-09-22 +=================== + + * Add `application/ubjson` with extension `.ubj` + * Add `image/avif` with extension `.avif` + * Add `image/ktx2` with extension `.ktx2` + * Add extension `.dbf` to `application/vnd.dbf` + * Add extension `.rar` to `application/vnd.rar` + * Add extension `.td` to `application/urc-targetdesc+xml` + * Add new upstream MIME types + * Fix extension of `application/vnd.apple.keynote` to be `.key` + +1.44.0 / 2020-04-22 +=================== + + * Add charsets from IANA + * Add extension `.cjs` to `application/node` + * Add new upstream MIME types + +1.43.0 / 2020-01-05 +=================== + + * Add `application/x-keepass2` with extension `.kdbx` + * Add extension `.mxmf` to `audio/mobile-xmf` + * Add extensions from IANA for `application/*+xml` types + * Add new upstream MIME types + +1.42.0 / 2019-09-25 +=================== + + * Add `image/vnd.ms-dds` with extension `.dds` + * Add new upstream MIME types + * Remove compressible from `multipart/mixed` + +1.41.0 / 2019-08-30 +=================== + + * Add new upstream MIME types + * Add `application/toml` with extension `.toml` + * Mark `font/ttf` as compressible + +1.40.0 / 2019-04-20 +=================== + + * Add extensions from IANA for `model/*` types + * Add `text/mdx` with extension `.mdx` + +1.39.0 / 2019-04-04 +=================== + + * Add extensions `.siv` and `.sieve` to `application/sieve` + * Add new upstream MIME types + +1.38.0 / 2019-02-04 +=================== + + * Add extension `.nq` to `application/n-quads` + * Add extension `.nt` to `application/n-triples` + * Add new upstream MIME types + * Mark `text/less` as compressible + +1.37.0 / 2018-10-19 +=================== + + * Add extensions to HEIC image types + * Add new upstream MIME types + +1.36.0 / 2018-08-20 +=================== + + * Add Apple file extensions from IANA + * Add extensions from IANA for `image/*` types + * Add new upstream MIME types + +1.35.0 / 2018-07-15 +=================== + + * Add extension `.owl` to `application/rdf+xml` + * Add new upstream MIME types + - Removes extension `.woff` from `application/font-woff` + +1.34.0 / 2018-06-03 +=================== + + * Add extension `.csl` to `application/vnd.citationstyles.style+xml` + * Add extension `.es` to `application/ecmascript` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/turtle` + * Mark all XML-derived types as compressible + +1.33.0 / 2018-02-15 +=================== + + * Add extensions from IANA for `message/*` types + * Add new upstream MIME types + * Fix some incorrect OOXML types + * Remove `application/font-woff2` + +1.32.0 / 2017-11-29 +=================== + + * Add new upstream MIME types + * Update `text/hjson` to registered `application/hjson` + * Add `text/shex` with extension `.shex` + +1.31.0 / 2017-10-25 +=================== + + * Add `application/raml+yaml` with extension `.raml` + * Add `application/wasm` with extension `.wasm` + * Add new `font` type from IANA + * Add new upstream font extensions + * Add new upstream MIME types + * Add extensions for JPEG-2000 images + +1.30.0 / 2017-08-27 +=================== + + * Add `application/vnd.ms-outlook` + * Add `application/x-arj` + * Add extension `.mjs` to `application/javascript` + * Add glTF types and extensions + * Add new upstream MIME types + * Add `text/x-org` + * Add VirtualBox MIME types + * Fix `source` records for `video/*` types that are IANA + * Update `font/opentype` to registered `font/otf` + +1.29.0 / 2017-07-10 +=================== + + * Add `application/fido.trusted-apps+json` + * Add extension `.wadl` to `application/vnd.sun.wadl+xml` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/css` + +1.28.0 / 2017-05-14 +=================== + + * Add new upstream MIME types + * Add extension `.gz` to `application/gzip` + * Update extensions `.md` and `.markdown` to be `text/markdown` + +1.27.0 / 2017-03-16 +=================== + + * Add new upstream MIME types + * Add `image/apng` with extension `.apng` + +1.26.0 / 2017-01-14 +=================== + + * Add new upstream MIME types + * Add extension `.geojson` to `application/geo+json` + +1.25.0 / 2016-11-11 +=================== + + * Add new upstream MIME types + +1.24.0 / 2016-09-18 +=================== + + * Add `audio/mp3` + * Add new upstream MIME types + +1.23.0 / 2016-05-01 +=================== + + * Add new upstream MIME types + * Add extension `.3gpp` to `audio/3gpp` + +1.22.0 / 2016-02-15 +=================== + + * Add `text/slim` + * Add extension `.rng` to `application/xml` + * Add new upstream MIME types + * Fix extension of `application/dash+xml` to be `.mpd` + * Update primary extension to `.m4a` for `audio/mp4` + +1.21.0 / 2016-01-06 +=================== + + * Add Google document types + * Add new upstream MIME types + +1.20.0 / 2015-11-10 +=================== + + * Add `text/x-suse-ymp` + * Add new upstream MIME types + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.apple.pkpass` + * Add new upstream MIME types + +1.18.0 / 2015-09-03 +=================== + + * Add new upstream MIME types + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + +1.8.0 / 2015-03-13 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/node_modules/mime-db/LICENSE b/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.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/mime-db/README.md b/node_modules/mime-db/README.md new file mode 100644 index 0000000..41c696a --- /dev/null +++ b/node_modules/mime-db/README.md @@ -0,0 +1,100 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +It aggregates data from the following sources: + +- http://www.iana.org/assignments/media-types/media-types.xhtml +- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types + +## Installation + +```bash +npm install mime-db +``` + +### Database Download + +If you're crazy enough to use this in the browser, you can just grab the +JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to +replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) +as the JSON format may change in the future. + +``` +https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json +``` + +## Usage + +```js +var db = require('mime-db') + +// grab data on .js files +var data = db['application/javascript'] +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + If not set, it's probably a custom media type. + - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) +- `.extensions[]` - known extensions associated with this mime type. +- `.compressible` - whether a file of this type can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom-types.json` or +`src/custom-suffix.json`. + +The `src/custom-types.json` file is a JSON object with the MIME type as the +keys and the values being an object with the following keys: + +- `compressible` - leave out if you don't know, otherwise `true`/`false` to + indicate whether the data represented by the type is typically compressible. +- `extensions` - include an array of file extensions that are associated with + the type. +- `notes` - human-readable notes about the type, typically what the type is. +- `sources` - include an array of URLs of where the MIME type and the associated + extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); + links to type aggregating sites and Wikipedia are _not acceptable_. + +To update the build, run `npm run build`. + +### Adding Custom Media Types + +The best way to get new media types included in this library is to register +them with the IANA. The community registration procedure is outlined in +[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types +registered with the IANA are automatically pulled into this library. + +If that is not possible / feasible, they can be added directly here as a +"custom" type. To do this, it is required to have a primary source that +definitively lists the media type. If an extension is going to be listed as +associateed with this media type, the source must definitively link the +media type and extension as well. + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci +[ci-url]: https://github.com/jshttp/mime-db/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master +[node-image]: https://badgen.net/npm/node/mime-db +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-db +[npm-url]: https://npmjs.org/package/mime-db +[npm-version-image]: https://badgen.net/npm/v/mime-db diff --git a/node_modules/mime-db/db.json b/node_modules/mime-db/db.json new file mode 100644 index 0000000..29786a7 --- /dev/null +++ b/node_modules/mime-db/db.json @@ -0,0 +1,8453 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpphal+json": { + "source": "iana", + "compressible": true + }, + "application/3gpphalforms+json": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/ace+cbor": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamcontrol+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamparams+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/at+jwt": { + "source": "iana" + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomdeleted"] + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atsc-dwd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dwd"] + }, + "application/atsc-dynamic-event-message": { + "source": "iana" + }, + "application/atsc-held+xml": { + "source": "iana", + "compressible": true, + "extensions": ["held"] + }, + "application/atsc-rdt+json": { + "source": "iana", + "compressible": true + }, + "application/atsc-rsat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsat"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xcs"] + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/captive+json": { + "source": "iana", + "compressible": true + }, + "application/cbor": { + "source": "iana" + }, + "application/cbor-seq": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdfx"] + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/clr": { + "source": "iana" + }, + "application/clue+xml": { + "source": "iana", + "compressible": true + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana" + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/dns-message": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dots+cbor": { + "source": "iana" + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["es","ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/elm+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/elm+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.cap+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emotionml"] + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/expect-ct-report+json": { + "source": "iana", + "compressible": true + }, + "application/express": { + "source": "iana", + "extensions": ["exp"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fdt"] + }, + "application/fhir+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/flexfec": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true, + "extensions": ["its"] + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/jscalendar+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lgr"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lpf+zip": { + "source": "iana", + "compressible": false + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mipc": { + "source": "iana" + }, + "application/missing-blocks+cbor-seq": { + "source": "iana" + }, + "application/mmt-aei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["maei"] + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musd"] + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/multipart-core": { + "source": "iana" + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana", + "extensions": ["nq"] + }, + "application/n-triples": { + "source": "iana", + "extensions": ["nt"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-groupinfo": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana", + "extensions": ["cjs"] + }, + "application/nss": { + "source": "iana" + }, + "application/oauth-authz-req+jwt": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odm+xml": { + "source": "iana", + "compressible": true + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/opc-nodeset+xml": { + "source": "iana", + "compressible": true + }, + "application/oscore": { + "source": "iana" + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p21": { + "source": "iana" + }, + "application/p21+zip": { + "source": "iana", + "compressible": false + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true, + "extensions": ["relo"] + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pem-certificate-chain": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true, + "extensions": ["provx"] + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.cyn": { + "source": "iana", + "charset": "7-BIT" + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/pvd+json": { + "source": "iana", + "compressible": true + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rapd"] + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sls"] + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rusd"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sarif+json": { + "source": "iana", + "compressible": true + }, + "application/sarif-external-properties+json": { + "source": "iana", + "compressible": true + }, + "application/sbe": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["senmlx"] + }, + "application/senml-etch+cbor": { + "source": "iana" + }, + "application/senml-etch+json": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sensmlx"] + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana", + "extensions": ["siv","sieve"] + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/sipc": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/swid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["swidtag"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/td+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/tetra_isi": { + "source": "iana" + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/token-introspection+jwt": { + "source": "iana" + }, + "application/toml": { + "compressible": true, + "extensions": ["toml"] + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana", + "extensions": ["trig"] + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ttml"] + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/tzif": { + "source": "iana" + }, + "application/tzif-leap": { + "source": "iana" + }, + "application/ubjson": { + "compressible": false, + "extensions": ["ubj"] + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsheet"] + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["td"] + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true, + "extensions": ["1km"] + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gnas": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gtpc": { + "source": "iana" + }, + "application/vnd.3gpp.interworking-data": { + "source": "iana" + }, + "application/vnd.3gpp.lpp": { + "source": "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ngap": { + "source": "iana" + }, + "application/vnd.3gpp.pfcp": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.s1ap": { + "source": "iana" + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + "source": "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + "source": "iana" + }, + "application/vnd.afpc.foca-charset": { + "source": "iana" + }, + "application/vnd.afpc.foca-codedfont": { + "source": "iana" + }, + "application/vnd.afpc.foca-codepage": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.afpc.modca-cmtable": { + "source": "iana" + }, + "application/vnd.afpc.modca-formdef": { + "source": "iana" + }, + "application/vnd.afpc.modca-mediummap": { + "source": "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + "source": "iana" + }, + "application/vnd.afpc.modca-overlay": { + "source": "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.ota": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.arrow.file": { + "source": "iana" + }, + "application/vnd.apache.arrow.stream": { + "source": "iana" + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.aplextor.warrp+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["key"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.error": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.bpf": { + "source": "iana" + }, + "application/vnd.bpf3": { + "source": "iana" + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.ciedi": { + "source": "iana" + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.crypto-shade-file": { + "source": "iana" + }, + "application/vnd.cryptomator.encrypted": { + "source": "iana" + }, + "application/vnd.cryptomator.vault": { + "source": "iana" + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.cyclonedx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cyclonedx+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.d3m-dataset": { + "source": "iana" + }, + "application/vnd.d3m-problem": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dbf": { + "source": "iana", + "extensions": ["dbf"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.exstream-empower+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.exstream-package": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.ficlab.flb+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+cbor": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.gentics.grd+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.slides": { + "source": "iana" + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las": { + "source": "iana" + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.laszip": { + "source": "iana" + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.loom": { + "source": "iana" + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana", + "extensions": ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nebumind.line": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+cbor": { + "source": "iana" + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true, + "extensions": ["obgx"] + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osm"] + }, + "application/vnd.opentimestamps.ots": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.patientecommsdoc": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana", + "extensions": ["rar"] + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.resilient.logic": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sar": { + "source": "iana" + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.seis+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shade-save-file": { + "source": "iana" + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shopkick+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shp": { + "source": "iana" + }, + "application/vnd.shx": { + "source": "iana" + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.snesdev-page-table": { + "source": "iana" + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.sycle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.veritone.aion+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veryant.thin": { + "source": "iana" + }, + "application/vnd.ves.encrypted": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.dpp": { + "source": "iana" + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.youtube.yt": { + "source": "iana" + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "source": "iana", + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + "extensions": ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + "extensions": ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + "extensions": ["pages"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-keepass2": { + "extensions": ["kdbx"] + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-pki-message": { + "source": "iana" + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "iana", + "extensions": ["der","crt","pem"] + }, + "application/x-x509-ca-ra-cert": { + "source": "iana" + }, + "application/x-x509-next-ca-cert": { + "source": "iana" + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xav"] + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xca"] + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xel"] + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xns"] + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xlf"] + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsl","xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana", + "extensions": ["amr"] + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/flexfec": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/mhas": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana", + "extensions": ["mxmf"] + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx","opus"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/scip": { + "source": "iana" + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sofa": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tetra_acelp": { + "source": "iana" + }, + "audio/tetra_acelp_bb": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/tsvcis": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dts.uhd": { + "source": "iana" + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "compressible": true, + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana" + }, + "image/avcs": { + "source": "iana" + }, + "image/avif": { + "source": "iana", + "compressible": false, + "extensions": ["avif"] + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana", + "extensions": ["heic"] + }, + "image/heic-sequence": { + "source": "iana", + "extensions": ["heics"] + }, + "image/heif": { + "source": "iana", + "extensions": ["heif"] + }, + "image/heif-sequence": { + "source": "iana", + "extensions": ["heifs"] + }, + "image/hej2k": { + "source": "iana", + "extensions": ["hej2"] + }, + "image/hsj2": { + "source": "iana", + "extensions": ["hsj2"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jph": { + "source": "iana", + "extensions": ["jph"] + }, + "image/jphc": { + "source": "iana", + "extensions": ["jhc"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/jxr": { + "source": "iana", + "extensions": ["jxr"] + }, + "image/jxra": { + "source": "iana", + "extensions": ["jxra"] + }, + "image/jxrs": { + "source": "iana", + "extensions": ["jxrs"] + }, + "image/jxs": { + "source": "iana", + "extensions": ["jxs"] + }, + "image/jxsc": { + "source": "iana", + "extensions": ["jxsc"] + }, + "image/jxsi": { + "source": "iana", + "extensions": ["jxsi"] + }, + "image/jxss": { + "source": "iana", + "extensions": ["jxss"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/ktx2": { + "source": "iana", + "extensions": ["ktx2"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-dds": { + "extensions": ["dds"] + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.pco.b16": { + "source": "iana", + "extensions": ["b16"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana", + "extensions": ["3mf"] + }, + "model/e57": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/mtl": { + "source": "iana", + "extensions": ["mtl"] + }, + "model/obj": { + "source": "iana", + "extensions": ["obj"] + }, + "model/step": { + "source": "iana" + }, + "model/step+xml": { + "source": "iana", + "compressible": true, + "extensions": ["stpx"] + }, + "model/step+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpz"] + }, + "model/step-xml+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpxz"] + }, + "model/stl": { + "source": "iana", + "extensions": ["stl"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana", + "extensions": ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana", + "extensions": ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana", + "extensions": ["x_t"] + }, + "model/vnd.pytha.pyox": { + "source": "iana" + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.sap.vds": { + "source": "iana", + "extensions": ["vds"] + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false, + "extensions": ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana", + "extensions": ["bsp"] + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana", + "extensions": ["x3db"] + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana", + "extensions": ["x3dv"] + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana" + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/cql": { + "source": "iana" + }, + "text/cql-expression": { + "source": "iana" + }, + "text/cql-identifier": { + "source": "iana" + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fhirpath": { + "source": "iana" + }, + "text/flexfec": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/gff3": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "compressible": true, + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["markdown","md"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mdx": { + "compressible": true, + "extensions": ["mdx"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana", + "charset": "UTF-8" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana", + "charset": "UTF-8" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shaclc": { + "source": "iana" + }, + "text/shex": { + "source": "iana", + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/spdx": { + "source": "iana", + "extensions": ["spdx"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.ficlab.flt": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hans": { + "source": "iana" + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.senx.warpscript": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sosi": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "compressible": true, + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/av1": { + "source": "iana" + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/ffv1": { + "source": "iana" + }, + "video/flexfec": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana", + "extensions": ["m4s"] + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/jxsv": { + "source": "iana" + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/scip": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vc2": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "iana" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vnd.youtube.yt": { + "source": "iana" + }, + "video/vp8": { + "source": "iana" + }, + "video/vp9": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/node_modules/mime-db/index.js b/node_modules/mime-db/index.js new file mode 100644 index 0000000..551031f --- /dev/null +++ b/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/node_modules/mime-db/package.json b/node_modules/mime-db/package.json new file mode 100644 index 0000000..b53d3ce --- /dev/null +++ b/node_modules/mime-db/package.json @@ -0,0 +1,59 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.50.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "Robert Kieffer (http://github.com/broofa)" + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": "jshttp/mime-db", + "devDependencies": { + "bluebird": "3.7.2", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "4.16.3", + "eslint": "7.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.24.2", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.1.0", + "eslint-plugin-standard": "4.1.0", + "gnode": "0.1.2", + "mocha": "9.1.1", + "nyc": "15.1.0", + "raw-body": "2.4.1", + "stream-to-array": "2.3.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "fetch": "node scripts/fetch-apache && gnode scripts/fetch-iana && node scripts/fetch-nginx", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/mime-types/HISTORY.md b/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..d5545c1 --- /dev/null +++ b/node_modules/mime-types/HISTORY.md @@ -0,0 +1,385 @@ +2.1.33 / 2021-10-01 +=================== + + * deps: mime-db@1.50.0 + - Add deprecated iWorks mime types and extensions + - Add new upstream MIME types + +2.1.32 / 2021-07-27 +=================== + + * deps: mime-db@1.49.0 + - Add extension `.trig` to `application/trig` + - Add new upstream MIME types + +2.1.31 / 2021-06-01 +=================== + + * deps: mime-db@1.48.0 + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add new upstream MIME types + - Mark `text/yaml` as compressible + +2.1.30 / 2021-04-02 +=================== + + * deps: mime-db@1.47.0 + - Add extension `.amr` to `audio/amr` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +2.1.29 / 2021-02-17 +=================== + + * deps: mime-db@1.46.0 + - Add extension `.amr` to `audio/amr` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.opus` to `audio/ogg` + - Add new upstream MIME types + +2.1.28 / 2021-01-01 +=================== + + * deps: mime-db@1.45.0 + - Add `application/ubjson` with extension `.ubj` + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + +2.1.27 / 2020-04-23 +=================== + + * deps: mime-db@1.44.0 + - Add charsets from IANA + - Add extension `.cjs` to `application/node` + - Add new upstream MIME types + +2.1.26 / 2020-01-05 +=================== + + * deps: mime-db@1.43.0 + - Add `application/x-keepass2` with extension `.kdbx` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extensions from IANA for `application/*+xml` types + - Add new upstream MIME types + +2.1.25 / 2019-11-12 +=================== + + * deps: mime-db@1.42.0 + - Add new upstream MIME types + - Add `application/toml` with extension `.toml` + - Add `image/vnd.ms-dds` with extension `.dds` + +2.1.24 / 2019-04-20 +=================== + + * deps: mime-db@1.40.0 + - Add extensions from IANA for `model/*` types + - Add `text/mdx` with extension `.mdx` + +2.1.23 / 2019-04-17 +=================== + + * deps: mime-db@~1.39.0 + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add new upstream MIME types + +2.1.22 / 2019-02-14 +=================== + + * deps: mime-db@~1.38.0 + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add new upstream MIME types + - Mark `text/less` as compressible + +2.1.21 / 2018-10-19 +=================== + + * deps: mime-db@~1.37.0 + - Add extensions to HEIC image types + - Add new upstream MIME types + +2.1.20 / 2018-08-26 +=================== + + * deps: mime-db@~1.36.0 + - Add Apple file extensions from IANA + - Add extensions from IANA for `image/*` types + - Add new upstream MIME types + +2.1.19 / 2018-07-17 +=================== + + * deps: mime-db@~1.35.0 + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.owl` to `application/rdf+xml` + - Add new upstream MIME types + - Add UTF-8 as default charset for `text/turtle` + +2.1.18 / 2018-02-16 +=================== + + * deps: mime-db@~1.33.0 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add new upstream MIME types + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +2.1.17 / 2017-09-01 +=================== + + * deps: mime-db@~1.30.0 + - Add `application/vnd.ms-outlook` + - Add `application/x-arj` + - Add extension `.mjs` to `application/javascript` + - Add glTF types and extensions + - Add new upstream MIME types + - Add `text/x-org` + - Add VirtualBox MIME types + - Fix `source` records for `video/*` types that are IANA + - Update `font/opentype` to registered `font/otf` + +2.1.16 / 2017-07-24 +=================== + + * deps: mime-db@~1.29.0 + - Add `application/fido.trusted-apps+json` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add new upstream MIME types + - Update extensions `.md` and `.markdown` to be `text/markdown` + +2.1.15 / 2017-03-23 +=================== + + * deps: mime-db@~1.27.0 + - Add new mime types + - Add `image/apng` + +2.1.14 / 2017-01-14 +=================== + + * deps: mime-db@~1.26.0 + - Add new mime types + +2.1.13 / 2016-11-18 +=================== + + * deps: mime-db@~1.25.0 + - Add new mime types + +2.1.12 / 2016-09-18 +=================== + + * deps: mime-db@~1.24.0 + - Add new mime types + - Add `audio/mp3` + +2.1.11 / 2016-05-01 +=================== + + * deps: mime-db@~1.23.0 + - Add new mime types + +2.1.10 / 2016-02-15 +=================== + + * deps: mime-db@~1.22.0 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + +2.0.10 / 2015-03-13 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/node_modules/mime-types/LICENSE b/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +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/mime-types/README.md b/node_modules/mime-types/README.md new file mode 100644 index 0000000..c978ac2 --- /dev/null +++ b/node_modules/mime-types/README.md @@ -0,0 +1,113 @@ +# mime-types + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +The ultimate javascript content-type utility. + +Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, + `mime-types` simply returns `false`, so do + `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- No `.define()` functionality +- Bug fixes for `.lookup(path)` + +Otherwise, the API is compatible with `mime` 1.x. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. +When given an extension, `mime.lookup` is used to get the matching +content-type, otherwise the given content-type is used. Then if the +content-type does not already have a `charset` parameter, `mime.charset` +is used to get the default charset and add to the returned content-type. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' +mime.contentType('text/html') // 'text/html; charset=utf-8' +mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci +[ci-url]: https://github.com/jshttp/mime-types/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master +[node-version-image]: https://badgen.net/npm/node/mime-types +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-types +[npm-url]: https://npmjs.org/package/mime-types +[npm-version-image]: https://badgen.net/npm/v/mime-types diff --git a/node_modules/mime-types/index.js b/node_modules/mime-types/index.js new file mode 100644 index 0000000..b9f34d5 --- /dev/null +++ b/node_modules/mime-types/index.js @@ -0,0 +1,188 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var db = require('mime-db') +var extname = require('path').extname + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/node_modules/mime-types/package.json b/node_modules/mime-types/package.json new file mode 100644 index 0000000..17bddef --- /dev/null +++ b/node_modules/mime-types/package.json @@ -0,0 +1,44 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.33", + "contributors": [ + "Douglas Christopher Wilson ", + "Jeremiah Senkpiel (https://searchbeam.jit.su)", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": "jshttp/mime-types", + "dependencies": { + "mime-db": "1.50.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.24.2", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.1.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.1.2", + "nyc": "15.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec test/test.js", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/mime/.npmignore b/node_modules/mime/.npmignore new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mime/CHANGELOG.md b/node_modules/mime/CHANGELOG.md new file mode 100644 index 0000000..f127535 --- /dev/null +++ b/node_modules/mime/CHANGELOG.md @@ -0,0 +1,164 @@ +# Changelog + +## v1.6.0 (24/11/2017) +*No changelog for this release.* + +--- + +## v2.0.4 (24/11/2017) +- [**closed**] Switch to mime-score module for resolving extension contention issues. [#182](https://github.com/broofa/node-mime/issues/182) +- [**closed**] Update mime-db to 1.31.0 in v1.x branch [#181](https://github.com/broofa/node-mime/issues/181) + +--- + +## v1.5.0 (22/11/2017) +- [**closed**] need ES5 version ready in npm package [#179](https://github.com/broofa/node-mime/issues/179) +- [**closed**] mime-db no trace of iWork - pages / numbers / etc. [#178](https://github.com/broofa/node-mime/issues/178) +- [**closed**] How it works in brownser ? [#176](https://github.com/broofa/node-mime/issues/176) +- [**closed**] Missing `./Mime` [#175](https://github.com/broofa/node-mime/issues/175) +- [**closed**] Vulnerable Regular Expression [#167](https://github.com/broofa/node-mime/issues/167) + +--- + +## v2.0.3 (25/09/2017) +*No changelog for this release.* + +--- + +## v1.4.1 (25/09/2017) +- [**closed**] Issue when bundling with webpack [#172](https://github.com/broofa/node-mime/issues/172) + +--- + +## v2.0.2 (15/09/2017) +- [**V2**] fs.readFileSync is not a function [#165](https://github.com/broofa/node-mime/issues/165) +- [**closed**] The extension for video/quicktime should map to .mov, not .qt [#164](https://github.com/broofa/node-mime/issues/164) +- [**V2**] [v2 Feedback request] Mime class API [#163](https://github.com/broofa/node-mime/issues/163) +- [**V2**] [v2 Feedback request] Resolving conflicts over extensions [#162](https://github.com/broofa/node-mime/issues/162) +- [**V2**] Allow callers to load module with official, full, or no defined types. [#161](https://github.com/broofa/node-mime/issues/161) +- [**V2**] Use "facets" to resolve extension conflicts [#160](https://github.com/broofa/node-mime/issues/160) +- [**V2**] Remove fs and path dependencies [#152](https://github.com/broofa/node-mime/issues/152) +- [**V2**] Default content-type should not be application/octet-stream [#139](https://github.com/broofa/node-mime/issues/139) +- [**V2**] reset mime-types [#124](https://github.com/broofa/node-mime/issues/124) +- [**V2**] Extensionless paths should return null or false [#113](https://github.com/broofa/node-mime/issues/113) + +--- + +## v2.0.1 (14/09/2017) +- [**closed**] Changelog for v2.0 does not mention breaking changes [#171](https://github.com/broofa/node-mime/issues/171) +- [**closed**] MIME breaking with 'class' declaration as it is without 'use strict mode' [#170](https://github.com/broofa/node-mime/issues/170) + +--- + +## v2.0.0 (12/09/2017) +- [**closed**] woff and woff2 [#168](https://github.com/broofa/node-mime/issues/168) + +--- + +## v1.4.0 (28/08/2017) +- [**closed**] support for ac3 voc files [#159](https://github.com/broofa/node-mime/issues/159) +- [**closed**] Help understanding change from application/xml to text/xml [#158](https://github.com/broofa/node-mime/issues/158) +- [**closed**] no longer able to override mimetype [#157](https://github.com/broofa/node-mime/issues/157) +- [**closed**] application/vnd.adobe.photoshop [#147](https://github.com/broofa/node-mime/issues/147) +- [**closed**] Directories should appear as something other than application/octet-stream [#135](https://github.com/broofa/node-mime/issues/135) +- [**closed**] requested features [#131](https://github.com/broofa/node-mime/issues/131) +- [**closed**] Make types.json loading optional? [#129](https://github.com/broofa/node-mime/issues/129) +- [**closed**] Cannot find module './types.json' [#120](https://github.com/broofa/node-mime/issues/120) +- [**V2**] .wav files show up as "audio/x-wav" instead of "audio/x-wave" [#118](https://github.com/broofa/node-mime/issues/118) +- [**closed**] Don't be a pain in the ass for node community [#108](https://github.com/broofa/node-mime/issues/108) +- [**closed**] don't make default_type global [#78](https://github.com/broofa/node-mime/issues/78) +- [**closed**] mime.extension() fails if the content-type is parameterized [#74](https://github.com/broofa/node-mime/issues/74) + +--- + +## v1.3.6 (11/05/2017) +- [**closed**] .md should be text/markdown as of March 2016 [#154](https://github.com/broofa/node-mime/issues/154) +- [**closed**] Error while installing mime [#153](https://github.com/broofa/node-mime/issues/153) +- [**closed**] application/manifest+json [#149](https://github.com/broofa/node-mime/issues/149) +- [**closed**] Dynamic adaptive streaming over HTTP (DASH) file extension typo [#141](https://github.com/broofa/node-mime/issues/141) +- [**closed**] charsets image/png undefined [#140](https://github.com/broofa/node-mime/issues/140) +- [**closed**] Mime-db dependency out of date [#130](https://github.com/broofa/node-mime/issues/130) +- [**closed**] how to support plist? [#126](https://github.com/broofa/node-mime/issues/126) +- [**closed**] how does .types file format look like? [#123](https://github.com/broofa/node-mime/issues/123) +- [**closed**] Feature: support for expanding MIME patterns [#121](https://github.com/broofa/node-mime/issues/121) +- [**closed**] DEBUG_MIME doesn't work [#117](https://github.com/broofa/node-mime/issues/117) + +--- + +## v1.3.4 (06/02/2015) +*No changelog for this release.* + +--- + +## v1.3.3 (06/02/2015) +*No changelog for this release.* + +--- + +## v1.3.1 (05/02/2015) +- [**closed**] Consider adding support for Handlebars .hbs file ending [#111](https://github.com/broofa/node-mime/issues/111) +- [**closed**] Consider adding support for hjson. [#110](https://github.com/broofa/node-mime/issues/110) +- [**closed**] Add mime type for Opus audio files [#94](https://github.com/broofa/node-mime/issues/94) +- [**closed**] Consider making the `Requesting New Types` information more visible [#77](https://github.com/broofa/node-mime/issues/77) + +--- + +## v1.3.0 (05/02/2015) +- [**closed**] Add common name? [#114](https://github.com/broofa/node-mime/issues/114) +- [**closed**] application/x-yaml [#104](https://github.com/broofa/node-mime/issues/104) +- [**closed**] Add mime type for WOFF file format 2.0 [#102](https://github.com/broofa/node-mime/issues/102) +- [**closed**] application/x-msi for .msi [#99](https://github.com/broofa/node-mime/issues/99) +- [**closed**] Add mimetype for gettext translation files [#98](https://github.com/broofa/node-mime/issues/98) +- [**closed**] collaborators [#88](https://github.com/broofa/node-mime/issues/88) +- [**closed**] getting errot in installation of mime module...any1 can help? [#87](https://github.com/broofa/node-mime/issues/87) +- [**closed**] should application/json's charset be utf8? [#86](https://github.com/broofa/node-mime/issues/86) +- [**closed**] Add "license" and "licenses" to package.json [#81](https://github.com/broofa/node-mime/issues/81) +- [**closed**] lookup with extension-less file on Windows returns wrong type [#68](https://github.com/broofa/node-mime/issues/68) + +--- + +## v1.2.11 (15/08/2013) +- [**closed**] Update mime.types [#65](https://github.com/broofa/node-mime/issues/65) +- [**closed**] Publish a new version [#63](https://github.com/broofa/node-mime/issues/63) +- [**closed**] README should state upfront that "application/octet-stream" is default for unknown extension [#55](https://github.com/broofa/node-mime/issues/55) +- [**closed**] Suggested improvement to the charset API [#52](https://github.com/broofa/node-mime/issues/52) + +--- + +## v1.2.10 (25/07/2013) +- [**closed**] Mime type for woff files should be application/font-woff and not application/x-font-woff [#62](https://github.com/broofa/node-mime/issues/62) +- [**closed**] node.types in conflict with mime.types [#51](https://github.com/broofa/node-mime/issues/51) + +--- + +## v1.2.9 (17/01/2013) +- [**closed**] Please update "mime" NPM [#49](https://github.com/broofa/node-mime/issues/49) +- [**closed**] Please add semicolon [#46](https://github.com/broofa/node-mime/issues/46) +- [**closed**] parse full mime types [#43](https://github.com/broofa/node-mime/issues/43) + +--- + +## v1.2.8 (10/01/2013) +- [**closed**] /js directory mime is application/javascript. Is it correct? [#47](https://github.com/broofa/node-mime/issues/47) +- [**closed**] Add mime types for lua code. [#45](https://github.com/broofa/node-mime/issues/45) + +--- + +## v1.2.7 (19/10/2012) +- [**closed**] cannot install 1.2.7 via npm [#41](https://github.com/broofa/node-mime/issues/41) +- [**closed**] Transfer ownership to @broofa [#36](https://github.com/broofa/node-mime/issues/36) +- [**closed**] it's wrong to set charset to UTF-8 for text [#30](https://github.com/broofa/node-mime/issues/30) +- [**closed**] Allow multiple instances of MIME types container [#27](https://github.com/broofa/node-mime/issues/27) + +--- + +## v1.2.5 (16/02/2012) +- [**closed**] When looking up a types, check hasOwnProperty [#23](https://github.com/broofa/node-mime/issues/23) +- [**closed**] Bump version to 1.2.2 [#18](https://github.com/broofa/node-mime/issues/18) +- [**closed**] No license [#16](https://github.com/broofa/node-mime/issues/16) +- [**closed**] Some types missing that are used by html5/css3 [#13](https://github.com/broofa/node-mime/issues/13) +- [**closed**] npm install fails for 1.2.1 [#12](https://github.com/broofa/node-mime/issues/12) +- [**closed**] image/pjpeg + image/x-png [#10](https://github.com/broofa/node-mime/issues/10) +- [**closed**] symlink [#8](https://github.com/broofa/node-mime/issues/8) +- [**closed**] gzip [#2](https://github.com/broofa/node-mime/issues/2) +- [**closed**] ALL CAPS filenames return incorrect mime type [#1](https://github.com/broofa/node-mime/issues/1) diff --git a/node_modules/mime/LICENSE b/node_modules/mime/LICENSE new file mode 100644 index 0000000..d3f46f7 --- /dev/null +++ b/node_modules/mime/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +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/mime/README.md b/node_modules/mime/README.md new file mode 100644 index 0000000..506fbe5 --- /dev/null +++ b/node_modules/mime/README.md @@ -0,0 +1,90 @@ +# mime + +Comprehensive MIME type mapping API based on mime-db module. + +## Install + +Install with [npm](http://github.com/isaacs/npm): + + npm install mime + +## Contributing / Testing + + npm run test + +## Command Line + + mime [path_string] + +E.g. + + > mime scripts/jquery.js + application/javascript + +## API - Queries + +### mime.lookup(path) +Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. + +```js +var mime = require('mime'); + +mime.lookup('/path/to/file.txt'); // => 'text/plain' +mime.lookup('file.txt'); // => 'text/plain' +mime.lookup('.TXT'); // => 'text/plain' +mime.lookup('htm'); // => 'text/html' +``` + +### mime.default_type +Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) + +### mime.extension(type) +Get the default extension for `type` + +```js +mime.extension('text/html'); // => 'html' +mime.extension('application/octet-stream'); // => 'bin' +``` + +### mime.charsets.lookup() + +Map mime-type to charset + +```js +mime.charsets.lookup('text/plain'); // => 'UTF-8' +``` + +(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) + +## API - Defining Custom Types + +Custom type mappings can be added on a per-project basis via the following APIs. + +### mime.define() + +Add custom mime/extension mappings + +```js +mime.define({ + 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], + 'application/x-my-type': ['x-mt', 'x-mtt'], + // etc ... +}); + +mime.lookup('x-sft'); // => 'text/x-some-format' +``` + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + +```js +mime.extension('text/x-some-format'); // => 'x-sf' +``` + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + +```js +mime.load('./my_project.types'); +``` +The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/mime/cli.js b/node_modules/mime/cli.js new file mode 100644 index 0000000..20b1ffe --- /dev/null +++ b/node_modules/mime/cli.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node + +var mime = require('./mime.js'); +var file = process.argv[2]; +var type = mime.lookup(file); + +process.stdout.write(type + '\n'); + diff --git a/node_modules/mime/mime.js b/node_modules/mime/mime.js new file mode 100644 index 0000000..d7efbde --- /dev/null +++ b/node_modules/mime/mime.js @@ -0,0 +1,108 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts[i]]) { + console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts[i]] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Define built-in types +mime.define(require('./types.json')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/node_modules/mime/package.json b/node_modules/mime/package.json new file mode 100644 index 0000000..6bd24bc --- /dev/null +++ b/node_modules/mime/package.json @@ -0,0 +1,44 @@ +{ + "author": { + "name": "Robert Kieffer", + "url": "http://github.com/broofa", + "email": "robert@broofa.com" + }, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + }, + "contributors": [ + { + "name": "Benjamin Thomas", + "url": "http://github.com/bentomas", + "email": "benjamin@benjaminthomas.org" + } + ], + "description": "A comprehensive library for mime-type mapping", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "github-release-notes": "0.13.1", + "mime-db": "1.31.0", + "mime-score": "1.1.0" + }, + "scripts": { + "prepare": "node src/build.js", + "changelog": "gren changelog --tags=all --generate --override", + "test": "node src/test.js" + }, + "keywords": [ + "util", + "mime" + ], + "main": "mime.js", + "name": "mime", + "repository": { + "url": "https://github.com/broofa/node-mime", + "type": "git" + }, + "version": "1.6.0" +} diff --git a/node_modules/mime/src/build.js b/node_modules/mime/src/build.js new file mode 100644 index 0000000..4928e48 --- /dev/null +++ b/node_modules/mime/src/build.js @@ -0,0 +1,53 @@ +#!/usr/bin/env node + +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const mimeScore = require('mime-score'); + +let db = require('mime-db'); +let chalk = require('chalk'); + +const STANDARD_FACET_SCORE = 900; + +const byExtension = {}; + +// Clear out any conflict extensions in mime-db +for (let type in db) { + let entry = db[type]; + entry.type = type; + + if (!entry.extensions) continue; + + entry.extensions.forEach(ext => { + if (ext in byExtension) { + const e0 = entry; + const e1 = byExtension[ext]; + e0.pri = mimeScore(e0.type, e0.source); + e1.pri = mimeScore(e1.type, e1.source); + + let drop = e0.pri < e1.pri ? e0 : e1; + let keep = e0.pri >= e1.pri ? e0 : e1; + drop.extensions = drop.extensions.filter(e => e !== ext); + + console.log(`${ext}: Keeping ${chalk.green(keep.type)} (${keep.pri}), dropping ${chalk.red(drop.type)} (${drop.pri})`); + } + byExtension[ext] = entry; + }); +} + +function writeTypesFile(types, path) { + fs.writeFileSync(path, JSON.stringify(types)); +} + +// Segregate into standard and non-standard types based on facet per +// https://tools.ietf.org/html/rfc6838#section-3.1 +const types = {}; + +Object.keys(db).sort().forEach(k => { + const entry = db[k]; + types[entry.type] = entry.extensions; +}); + +writeTypesFile(types, path.join(__dirname, '..', 'types.json')); diff --git a/node_modules/mime/src/test.js b/node_modules/mime/src/test.js new file mode 100644 index 0000000..42958a2 --- /dev/null +++ b/node_modules/mime/src/test.js @@ -0,0 +1,60 @@ +/** + * Usage: node test.js + */ + +var mime = require('../mime'); +var assert = require('assert'); +var path = require('path'); + +// +// Test mime lookups +// + +assert.equal('text/plain', mime.lookup('text.txt')); // normal file +assert.equal('text/plain', mime.lookup('TEXT.TXT')); // uppercase +assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file +assert.equal('text/plain', mime.lookup('.text.txt')); // hidden file +assert.equal('text/plain', mime.lookup('.txt')); // nameless +assert.equal('text/plain', mime.lookup('txt')); // extension-only +assert.equal('text/plain', mime.lookup('/txt')); // extension-less () +assert.equal('text/plain', mime.lookup('\\txt')); // Windows, extension-less +assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized +assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default + +// +// Test extensions +// + +assert.equal('txt', mime.extension(mime.types.text)); +assert.equal('html', mime.extension(mime.types.htm)); +assert.equal('bin', mime.extension('application/octet-stream')); +assert.equal('bin', mime.extension('application/octet-stream ')); +assert.equal('html', mime.extension(' text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html; charset=UTF-8 ')); +assert.equal('html', mime.extension('text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html ; charset=UTF-8')); +assert.equal('html', mime.extension('text/html;charset=UTF-8')); +assert.equal('html', mime.extension('text/Html;charset=UTF-8')); +assert.equal(undefined, mime.extension('unrecognized')); + +// +// Test node.types lookups +// + +assert.equal('font/woff', mime.lookup('file.woff')); +assert.equal('application/octet-stream', mime.lookup('file.buffer')); +// TODO: Uncomment once #157 is resolved +// assert.equal('audio/mp4', mime.lookup('file.m4a')); +assert.equal('font/otf', mime.lookup('file.otf')); + +// +// Test charsets +// + +assert.equal('UTF-8', mime.charsets.lookup('text/plain')); +assert.equal('UTF-8', mime.charsets.lookup(mime.types.js)); +assert.equal('UTF-8', mime.charsets.lookup(mime.types.json)); +assert.equal(undefined, mime.charsets.lookup(mime.types.bin)); +assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +console.log('\nAll tests passed'); diff --git a/node_modules/mime/types.json b/node_modules/mime/types.json new file mode 100644 index 0000000..bec78ab --- /dev/null +++ b/node_modules/mime/types.json @@ -0,0 +1 @@ +{"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomsvc+xml":["atomsvc"],"application/bdoc":["bdoc"],"application/ccxml+xml":["ccxml"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/font-tdpfr":["pfr"],"application/font-woff":[],"application/font-woff2":[],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/prs.cww":["cww"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":[],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":[],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":[],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":[],"application/x-msdownload":["com","bat"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["wmf","emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":[],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"application/xaml+xml":["xaml"],"application/xcap-diff+xml":["xdf"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":[],"audio/adpcm":["adp"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mp3":[],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/wav":["wav"],"audio/wave":[],"audio/webm":["weba"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":[],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":[],"audio/x-wav":[],"audio/xm":["xm"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/apng":["apng"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/g3fax":["g3"],"image/gif":["gif"],"image/ief":["ief"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/ktx":["ktx"],"image/png":["png"],"image/prs.btif":["btif"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/tiff":["tiff","tif"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":[],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/webp":["webp"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":[],"image/x-pcx":["pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/rfc822":["eml","mime"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.vtu":["vtu"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["x3db","x3dbz"],"model/x3d+vrml":["x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/hjson":["hjson"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/prs.lines.tag":["dsc"],"text/richtext":["rtx"],"text/rtf":[],"text/sgml":["sgml","sgm"],"text/slim":["slim","slm"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/vtt":["vtt"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":[],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"text/xml":[],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/jpeg":["jpgv"],"video/jpm":["jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/webm":["webm"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]} \ No newline at end of file diff --git a/node_modules/minimatch/LICENSE b/node_modules/minimatch/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/minimatch/README.md b/node_modules/minimatch/README.md new file mode 100644 index 0000000..ad72b81 --- /dev/null +++ b/node_modules/minimatch/README.md @@ -0,0 +1,209 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. diff --git a/node_modules/minimatch/minimatch.js b/node_modules/minimatch/minimatch.js new file mode 100644 index 0000000..5b5f8cf --- /dev/null +++ b/node_modules/minimatch/minimatch.js @@ -0,0 +1,923 @@ +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = { sep: '/' } +try { + path = require('path') +} catch (er) {} + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = require('brace-expansion') + +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' + +// * => any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + // "" only matches "" + if (pattern.trim() === '') return p === '' + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } + + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] + + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) + + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} diff --git a/node_modules/minimatch/package.json b/node_modules/minimatch/package.json new file mode 100644 index 0000000..c4514c8 --- /dev/null +++ b/node_modules/minimatch/package.json @@ -0,0 +1,30 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me)", + "name": "minimatch", + "description": "a glob matcher in javascript", + "version": "3.0.4", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "test": "tap test/*.js --cov", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "engines": { + "node": "*" + }, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "devDependencies": { + "tap": "^10.3.2" + }, + "license": "ISC", + "files": [ + "minimatch.js" + ] +} diff --git a/node_modules/minipass/LICENSE b/node_modules/minipass/LICENSE new file mode 100644 index 0000000..20a4762 --- /dev/null +++ b/node_modules/minipass/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) npm, Inc. and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/minipass/README.md b/node_modules/minipass/README.md new file mode 100644 index 0000000..59fa629 --- /dev/null +++ b/node_modules/minipass/README.md @@ -0,0 +1,613 @@ +# minipass + +A _very_ minimal implementation of a [PassThrough +stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) + +[It's very +fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0) +for objects, strings, and buffers. + +Supports `pipe()`ing (including multi-`pipe()` and backpressure transmission), +buffering data until either a `data` event handler or `pipe()` is added (so +you don't lose the first chunk), and most other cases where PassThrough is +a good idea. + +There is a `read()` method, but it's much more efficient to consume data +from this stream via `'data'` events or by calling `pipe()` into some other +stream. Calling `read()` requires the buffer to be flattened in some +cases, which requires copying memory. + +There is also no `unpipe()` method. Once you start piping, there is no +stopping it! + +If you set `objectMode: true` in the options, then whatever is written will +be emitted. Otherwise, it'll do a minimal amount of Buffer copying to +ensure proper Streams semantics when `read(n)` is called. + +`objectMode` can also be set by doing `stream.objectMode = true`, or by +writing any non-string/non-buffer data. `objectMode` cannot be set to +false once it is set. + +This is not a `through` or `through2` stream. It doesn't transform the +data, it just passes it right through. If you want to transform the data, +extend the class, and override the `write()` method. Once you're done +transforming the data however you want, call `super.write()` with the +transform output. + +For some examples of streams that extend Minipass in various ways, check +out: + +- [minizlib](http://npm.im/minizlib) +- [fs-minipass](http://npm.im/fs-minipass) +- [tar](http://npm.im/tar) +- [minipass-collect](http://npm.im/minipass-collect) +- [minipass-flush](http://npm.im/minipass-flush) +- [minipass-pipeline](http://npm.im/minipass-pipeline) +- [tap](http://npm.im/tap) +- [tap-parser](http://npm.im/tap-parser) +- [treport](http://npm.im/treport) +- [minipass-fetch](http://npm.im/minipass-fetch) +- [pacote](http://npm.im/pacote) +- [make-fetch-happen](http://npm.im/make-fetch-happen) +- [cacache](http://npm.im/cacache) +- [ssri](http://npm.im/ssri) +- [npm-registry-fetch](http://npm.im/npm-registry-fetch) +- [minipass-json-stream](http://npm.im/minipass-json-stream) +- [minipass-sized](http://npm.im/minipass-sized) + +## Differences from Node.js Streams + +There are several things that make Minipass streams different from (and in +some ways superior to) Node.js core streams. + +Please read these caveats if you are familiar with node-core streams and +intend to use Minipass streams in your programs. + +### Timing + +Minipass streams are designed to support synchronous use-cases. Thus, data +is emitted as soon as it is available, always. It is buffered until read, +but no longer. Another way to look at it is that Minipass streams are +exactly as synchronous as the logic that writes into them. + +This can be surprising if your code relies on `PassThrough.write()` always +providing data on the next tick rather than the current one, or being able +to call `resume()` and not have the entire buffer disappear immediately. + +However, without this synchronicity guarantee, there would be no way for +Minipass to achieve the speeds it does, or support the synchronous use +cases that it does. Simply put, waiting takes time. + +This non-deferring approach makes Minipass streams much easier to reason +about, especially in the context of Promises and other flow-control +mechanisms. + +### No High/Low Water Marks + +Node.js core streams will optimistically fill up a buffer, returning `true` +on all writes until the limit is hit, even if the data has nowhere to go. +Then, they will not attempt to draw more data in until the buffer size dips +below a minimum value. + +Minipass streams are much simpler. The `write()` method will return `true` +if the data has somewhere to go (which is to say, given the timing +guarantees, that the data is already there by the time `write()` returns). + +If the data has nowhere to go, then `write()` returns false, and the data +sits in a buffer, to be drained out immediately as soon as anyone consumes +it. + +### Hazards of Buffering (or: Why Minipass Is So Fast) + +Since data written to a Minipass stream is immediately written all the way +through the pipeline, and `write()` always returns true/false based on +whether the data was fully flushed, backpressure is communicated +immediately to the upstream caller. This minimizes buffering. + +Consider this case: + +```js +const {PassThrough} = require('stream') +const p1 = new PassThrough({ highWaterMark: 1024 }) +const p2 = new PassThrough({ highWaterMark: 1024 }) +const p3 = new PassThrough({ highWaterMark: 1024 }) +const p4 = new PassThrough({ highWaterMark: 1024 }) + +p1.pipe(p2).pipe(p3).pipe(p4) +p4.on('data', () => console.log('made it through')) + +// this returns false and buffers, then writes to p2 on next tick (1) +// p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) +// p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) +// p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' +// on next tick (4) +// p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and +// 'drain' on next tick (5) +// p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) +// p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next +// tick (7) + +p1.write(Buffer.alloc(2048)) // returns false +``` + +Along the way, the data was buffered and deferred at each stage, and +multiple event deferrals happened, for an unblocked pipeline where it was +perfectly safe to write all the way through! + +Furthermore, setting a `highWaterMark` of `1024` might lead someone reading +the code to think an advisory maximum of 1KiB is being set for the +pipeline. However, the actual advisory buffering level is the _sum_ of +`highWaterMark` values, since each one has its own bucket. + +Consider the Minipass case: + +```js +const m1 = new Minipass() +const m2 = new Minipass() +const m3 = new Minipass() +const m4 = new Minipass() + +m1.pipe(m2).pipe(m3).pipe(m4) +m4.on('data', () => console.log('made it through')) + +// m1 is flowing, so it writes the data to m2 immediately +// m2 is flowing, so it writes the data to m3 immediately +// m3 is flowing, so it writes the data to m4 immediately +// m4 is flowing, so it fires the 'data' event immediately, returns true +// m4's write returned true, so m3 is still flowing, returns true +// m3's write returned true, so m2 is still flowing, returns true +// m2's write returned true, so m1 is still flowing, returns true +// No event deferrals or buffering along the way! + +m1.write(Buffer.alloc(2048)) // returns true +``` + +It is extremely unlikely that you _don't_ want to buffer any data written, +or _ever_ buffer data that can be flushed all the way through. Neither +node-core streams nor Minipass ever fail to buffer written data, but +node-core streams do a lot of unnecessary buffering and pausing. + +As always, the faster implementation is the one that does less stuff and +waits less time to do it. + +### Immediately emit `end` for empty streams (when not paused) + +If a stream is not paused, and `end()` is called before writing any data +into it, then it will emit `end` immediately. + +If you have logic that occurs on the `end` event which you don't want to +potentially happen immediately (for example, closing file descriptors, +moving on to the next entry in an archive parse stream, etc.) then be sure +to call `stream.pause()` on creation, and then `stream.resume()` once you +are ready to respond to the `end` event. + +### Emit `end` When Asked + +One hazard of immediately emitting `'end'` is that you may not yet have had +a chance to add a listener. In order to avoid this hazard, Minipass +streams safely re-emit the `'end'` event if a new listener is added after +`'end'` has been emitted. + +Ie, if you do `stream.on('end', someFunction)`, and the stream has already +emitted `end`, then it will call the handler right away. (You can think of +this somewhat like attaching a new `.then(fn)` to a previously-resolved +Promise.) + +To prevent calling handlers multiple times who would not expect multiple +ends to occur, all listeners are removed from the `'end'` event whenever it +is emitted. + +### Impact of "immediate flow" on Tee-streams + +A "tee stream" is a stream piping to multiple destinations: + +```js +const tee = new Minipass() +t.pipe(dest1) +t.pipe(dest2) +t.write('foo') // goes to both destinations +``` + +Since Minipass streams _immediately_ process any pending data through the +pipeline when a new pipe destination is added, this can have surprising +effects, especially when a stream comes in from some other function and may +or may not have data in its buffer. + +```js +// WARNING! WILL LOSE DATA! +const src = new Minipass() +src.write('foo') +src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone +src.pipe(dest2) // gets nothing! +``` + +The solution is to create a dedicated tee-stream junction that pipes to +both locations, and then pipe to _that_ instead. + +```js +// Safe example: tee to both places +const src = new Minipass() +src.write('foo') +const tee = new Minipass() +tee.pipe(dest1) +tee.pipe(dest2) +src.pipe(tee) // tee gets 'foo', pipes to both locations +``` + +The same caveat applies to `on('data')` event listeners. The first one +added will _immediately_ receive all of the data, leaving nothing for the +second: + +```js +// WARNING! WILL LOSE DATA! +const src = new Minipass() +src.write('foo') +src.on('data', handler1) // receives 'foo' right away +src.on('data', handler2) // nothing to see here! +``` + +Using a dedicated tee-stream can be used in this case as well: + +```js +// Safe example: tee to both data handlers +const src = new Minipass() +src.write('foo') +const tee = new Minipass() +tee.on('data', handler1) +tee.on('data', handler2) +src.pipe(tee) +``` + +## USAGE + +It's a stream! Use it like a stream and it'll most likely do what you +want. + +```js +const Minipass = require('minipass') +const mp = new Minipass(options) // optional: { encoding, objectMode } +mp.write('foo') +mp.pipe(someOtherStream) +mp.end('bar') +``` + +### OPTIONS + +* `encoding` How would you like the data coming _out_ of the stream to be + encoded? Accepts any values that can be passed to `Buffer.toString()`. +* `objectMode` Emit data exactly as it comes in. This will be flipped on + by default if you write() something other than a string or Buffer at any + point. Setting `objectMode: true` will prevent setting any encoding + value. + +### API + +Implements the user-facing portions of Node.js's `Readable` and `Writable` +streams. + +### Methods + +* `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the + base Minipass class, the same data will come out.) Returns `false` if + the stream will buffer the next write, or true if it's still in "flowing" + mode. +* `end([chunk, [encoding]], [callback])` - Signal that you have no more + data to write. This will queue an `end` event to be fired when all the + data has been consumed. +* `setEncoding(encoding)` - Set the encoding for data coming of the stream. + This can only be done once. +* `pause()` - No more data for a while, please. This also prevents `end` + from being emitted for empty streams until the stream is resumed. +* `resume()` - Resume the stream. If there's data in the buffer, it is all + discarded. Any buffered events are immediately emitted. +* `pipe(dest)` - Send all output to the stream provided. There is no way + to unpipe. When data is emitted, it is immediately written to any and + all pipe destinations. +* `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some + events are given special treatment, however. (See below under "events".) +* `promise()` - Returns a Promise that resolves when the stream emits + `end`, or rejects if the stream emits `error`. +* `collect()` - Return a Promise that resolves on `end` with an array + containing each chunk of data that was emitted, or rejects if the stream + emits `error`. Note that this consumes the stream data. +* `concat()` - Same as `collect()`, but concatenates the data into a single + Buffer object. Will reject the returned promise if the stream is in + objectMode, or if it goes into objectMode by the end of the data. +* `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not + provided, then consume all of it. If `n` bytes are not available, then + it returns null. **Note** consuming streams in this way is less + efficient, and can lead to unnecessary Buffer copying. +* `destroy([er])` - Destroy the stream. If an error is provided, then an + `'error'` event is emitted. If the stream has a `close()` method, and + has not emitted a `'close'` event yet, then `stream.close()` will be + called. Any Promises returned by `.promise()`, `.collect()` or + `.concat()` will be rejected. After being destroyed, writing to the + stream will emit an error. No more data will be emitted if the stream is + destroyed, even if it was previously buffered. + +### Properties + +* `bufferLength` Read-only. Total number of bytes buffered, or in the case + of objectMode, the total number of objects. +* `encoding` The encoding that has been set. (Setting this is equivalent + to calling `setEncoding(enc)` and has the same prohibition against + setting multiple times.) +* `flowing` Read-only. Boolean indicating whether a chunk written to the + stream will be immediately emitted. +* `emittedEnd` Read-only. Boolean indicating whether the end-ish events + (ie, `end`, `prefinish`, `finish`) have been emitted. Note that + listening on any end-ish event will immediateyl re-emit it if it has + already been emitted. +* `writable` Whether the stream is writable. Default `true`. Set to + `false` when `end()` +* `readable` Whether the stream is readable. Default `true`. +* `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written + to the stream that have not yet been emitted. (It's probably a bad idea + to mess with this.) +* `pipes` A [yallist](http://npm.im/yallist) linked list of streams that + this stream is piping into. (It's probably a bad idea to mess with + this.) +* `destroyed` A getter that indicates whether the stream was destroyed. +* `paused` True if the stream has been explicitly paused, otherwise false. +* `objectMode` Indicates whether the stream is in `objectMode`. Once set + to `true`, it cannot be set to `false`. + +### Events + +* `data` Emitted when there's data to read. Argument is the data to read. + This is never emitted while not flowing. If a listener is attached, that + will resume the stream. +* `end` Emitted when there's no more data to read. This will be emitted + immediately for empty streams when `end()` is called. If a listener is + attached, and `end` was already emitted, then it will be emitted again. + All listeners are removed when `end` is emitted. +* `prefinish` An end-ish event that follows the same logic as `end` and is + emitted in the same conditions where `end` is emitted. Emitted after + `'end'`. +* `finish` An end-ish event that follows the same logic as `end` and is + emitted in the same conditions where `end` is emitted. Emitted after + `'prefinish'`. +* `close` An indication that an underlying resource has been released. + Minipass does not emit this event, but will defer it until after `end` + has been emitted, since it throws off some stream libraries otherwise. +* `drain` Emitted when the internal buffer empties, and it is again + suitable to `write()` into the stream. +* `readable` Emitted when data is buffered and ready to be read by a + consumer. +* `resume` Emitted when stream changes state from buffering to flowing + mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event + listener is added.) + +### Static Methods + +* `Minipass.isStream(stream)` Returns `true` if the argument is a stream, + and false otherwise. To be considered a stream, the object must be + either an instance of Minipass, or an EventEmitter that has either a + `pipe()` method, or both `write()` and `end()` methods. (Pretty much any + stream in node-land will return `true` for this.) + +## EXAMPLES + +Here are some examples of things you can do with Minipass streams. + +### simple "are you done yet" promise + +```js +mp.promise().then(() => { + // stream is finished +}, er => { + // stream emitted an error +}) +``` + +### collecting + +```js +mp.collect().then(all => { + // all is an array of all the data emitted + // encoding is supported in this case, so + // so the result will be a collection of strings if + // an encoding is specified, or buffers/objects if not. + // + // In an async function, you may do + // const data = await stream.collect() +}) +``` + +### collecting into a single blob + +This is a bit slower because it concatenates the data into one chunk for +you, but if you're going to do it yourself anyway, it's convenient this +way: + +```js +mp.concat().then(onebigchunk => { + // onebigchunk is a string if the stream + // had an encoding set, or a buffer otherwise. +}) +``` + +### iteration + +You can iterate over streams synchronously or asynchronously in platforms +that support it. + +Synchronous iteration will end when the currently available data is +consumed, even if the `end` event has not been reached. In string and +buffer mode, the data is concatenated, so unless multiple writes are +occurring in the same tick as the `read()`, sync iteration loops will +generally only have a single iteration. + +To consume chunks in this way exactly as they have been written, with no +flattening, create the stream with the `{ objectMode: true }` option. + +```js +const mp = new Minipass({ objectMode: true }) +mp.write('a') +mp.write('b') +for (let letter of mp) { + console.log(letter) // a, b +} +mp.write('c') +mp.write('d') +for (let letter of mp) { + console.log(letter) // c, d +} +mp.write('e') +mp.end() +for (let letter of mp) { + console.log(letter) // e +} +for (let letter of mp) { + console.log(letter) // nothing +} +``` + +Asynchronous iteration will continue until the end event is reached, +consuming all of the data. + +```js +const mp = new Minipass({ encoding: 'utf8' }) + +// some source of some data +let i = 5 +const inter = setInterval(() => { + if (i-- > 0) + mp.write(Buffer.from('foo\n', 'utf8')) + else { + mp.end() + clearInterval(inter) + } +}, 100) + +// consume the data with asynchronous iteration +async function consume () { + for await (let chunk of mp) { + console.log(chunk) + } + return 'ok' +} + +consume().then(res => console.log(res)) +// logs `foo\n` 5 times, and then `ok` +``` + +### subclass that `console.log()`s everything written into it + +```js +class Logger extends Minipass { + write (chunk, encoding, callback) { + console.log('WRITE', chunk, encoding) + return super.write(chunk, encoding, callback) + } + end (chunk, encoding, callback) { + console.log('END', chunk, encoding) + return super.end(chunk, encoding, callback) + } +} + +someSource.pipe(new Logger()).pipe(someDest) +``` + +### same thing, but using an inline anonymous class + +```js +// js classes are fun +someSource + .pipe(new (class extends Minipass { + emit (ev, ...data) { + // let's also log events, because debugging some weird thing + console.log('EMIT', ev) + return super.emit(ev, ...data) + } + write (chunk, encoding, callback) { + console.log('WRITE', chunk, encoding) + return super.write(chunk, encoding, callback) + } + end (chunk, encoding, callback) { + console.log('END', chunk, encoding) + return super.end(chunk, encoding, callback) + } + })) + .pipe(someDest) +``` + +### subclass that defers 'end' for some reason + +```js +class SlowEnd extends Minipass { + emit (ev, ...args) { + if (ev === 'end') { + console.log('going to end, hold on a sec') + setTimeout(() => { + console.log('ok, ready to end now') + super.emit('end', ...args) + }, 100) + } else { + return super.emit(ev, ...args) + } + } +} +``` + +### transform that creates newline-delimited JSON + +```js +class NDJSONEncode extends Minipass { + write (obj, cb) { + try { + // JSON.stringify can throw, emit an error on that + return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) + } catch (er) { + this.emit('error', er) + } + } + end (obj, cb) { + if (typeof obj === 'function') { + cb = obj + obj = undefined + } + if (obj !== undefined) { + this.write(obj) + } + return super.end(cb) + } +} +``` + +### transform that parses newline-delimited JSON + +```js +class NDJSONDecode extends Minipass { + constructor (options) { + // always be in object mode, as far as Minipass is concerned + super({ objectMode: true }) + this._jsonBuffer = '' + } + write (chunk, encoding, cb) { + if (typeof chunk === 'string' && + typeof encoding === 'string' && + encoding !== 'utf8') { + chunk = Buffer.from(chunk, encoding).toString() + } else if (Buffer.isBuffer(chunk)) + chunk = chunk.toString() + } + if (typeof encoding === 'function') { + cb = encoding + } + const jsonData = (this._jsonBuffer + chunk).split('\n') + this._jsonBuffer = jsonData.pop() + for (let i = 0; i < jsonData.length; i++) { + try { + // JSON.parse can throw, emit an error on that + super.write(JSON.parse(jsonData[i])) + } catch (er) { + this.emit('error', er) + continue + } + } + if (cb) + cb() + } +} +``` diff --git a/node_modules/minipass/index.js b/node_modules/minipass/index.js new file mode 100644 index 0000000..1835dd9 --- /dev/null +++ b/node_modules/minipass/index.js @@ -0,0 +1,560 @@ +'use strict' +const proc = typeof process === 'object' && process ? process : { + stdout: null, + stderr: null, +} +const EE = require('events') +const Stream = require('stream') +const Yallist = require('yallist') +const SD = require('string_decoder').StringDecoder + +const EOF = Symbol('EOF') +const MAYBE_EMIT_END = Symbol('maybeEmitEnd') +const EMITTED_END = Symbol('emittedEnd') +const EMITTING_END = Symbol('emittingEnd') +const EMITTED_ERROR = Symbol('emittedError') +const CLOSED = Symbol('closed') +const READ = Symbol('read') +const FLUSH = Symbol('flush') +const FLUSHCHUNK = Symbol('flushChunk') +const ENCODING = Symbol('encoding') +const DECODER = Symbol('decoder') +const FLOWING = Symbol('flowing') +const PAUSED = Symbol('paused') +const RESUME = Symbol('resume') +const BUFFERLENGTH = Symbol('bufferLength') +const BUFFERPUSH = Symbol('bufferPush') +const BUFFERSHIFT = Symbol('bufferShift') +const OBJECTMODE = Symbol('objectMode') +const DESTROYED = Symbol('destroyed') + +// TODO remove when Node v8 support drops +const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' +const ASYNCITERATOR = doIter && Symbol.asyncIterator + || Symbol('asyncIterator not implemented') +const ITERATOR = doIter && Symbol.iterator + || Symbol('iterator not implemented') + +// events that mean 'the stream is over' +// these are treated specially, and re-emitted +// if they are listened for after emitting. +const isEndish = ev => + ev === 'end' || + ev === 'finish' || + ev === 'prefinish' + +const isArrayBuffer = b => b instanceof ArrayBuffer || + typeof b === 'object' && + b.constructor && + b.constructor.name === 'ArrayBuffer' && + b.byteLength >= 0 + +const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) + +module.exports = class Minipass extends Stream { + constructor (options) { + super() + this[FLOWING] = false + // whether we're explicitly paused + this[PAUSED] = false + this.pipes = new Yallist() + this.buffer = new Yallist() + this[OBJECTMODE] = options && options.objectMode || false + if (this[OBJECTMODE]) + this[ENCODING] = null + else + this[ENCODING] = options && options.encoding || null + if (this[ENCODING] === 'buffer') + this[ENCODING] = null + this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null + this[EOF] = false + this[EMITTED_END] = false + this[EMITTING_END] = false + this[CLOSED] = false + this[EMITTED_ERROR] = null + this.writable = true + this.readable = true + this[BUFFERLENGTH] = 0 + this[DESTROYED] = false + } + + get bufferLength () { return this[BUFFERLENGTH] } + + get encoding () { return this[ENCODING] } + set encoding (enc) { + if (this[OBJECTMODE]) + throw new Error('cannot set encoding in objectMode') + + if (this[ENCODING] && enc !== this[ENCODING] && + (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) + throw new Error('cannot change encoding') + + if (this[ENCODING] !== enc) { + this[DECODER] = enc ? new SD(enc) : null + if (this.buffer.length) + this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) + } + + this[ENCODING] = enc + } + + setEncoding (enc) { + this.encoding = enc + } + + get objectMode () { return this[OBJECTMODE] } + set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } + + write (chunk, encoding, cb) { + if (this[EOF]) + throw new Error('write after end') + + if (this[DESTROYED]) { + this.emit('error', Object.assign( + new Error('Cannot call write after a stream was destroyed'), + { code: 'ERR_STREAM_DESTROYED' } + )) + return true + } + + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' + + if (!encoding) + encoding = 'utf8' + + // convert array buffers and typed array views into buffers + // at some point in the future, we may want to do the opposite! + // leave strings and buffers as-is + // anything else switches us into object mode + if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { + if (isArrayBufferView(chunk)) + chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) + else if (isArrayBuffer(chunk)) + chunk = Buffer.from(chunk) + else if (typeof chunk !== 'string') + // use the setter so we throw if we have encoding set + this.objectMode = true + } + + // this ensures at this point that the chunk is a buffer or string + // don't buffer it up or send it to the decoder + if (!this.objectMode && !chunk.length) { + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') + if (cb) + cb() + return this.flowing + } + + // fast-path writing strings of same encoding to a stream with + // an empty buffer, skipping the buffer/decoder dance + if (typeof chunk === 'string' && !this[OBJECTMODE] && + // unless it is a string already ready for us to use + !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { + chunk = Buffer.from(chunk, encoding) + } + + if (Buffer.isBuffer(chunk) && this[ENCODING]) + chunk = this[DECODER].write(chunk) + + if (this.flowing) { + // if we somehow have something in the buffer, but we think we're + // flowing, then we need to flush all that out first, or we get + // chunks coming in out of order. Can't emit 'drain' here though, + // because we're mid-write, so that'd be bad. + if (this[BUFFERLENGTH] !== 0) + this[FLUSH](true) + + // if we are still flowing after flushing the buffer we can emit the + // chunk otherwise we have to buffer it. + this.flowing + ? this.emit('data', chunk) + : this[BUFFERPUSH](chunk) + } else + this[BUFFERPUSH](chunk) + + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') + + if (cb) + cb() + + return this.flowing + } + + read (n) { + if (this[DESTROYED]) + return null + + try { + if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) + return null + + if (this[OBJECTMODE]) + n = null + + if (this.buffer.length > 1 && !this[OBJECTMODE]) { + if (this.encoding) + this.buffer = new Yallist([ + Array.from(this.buffer).join('') + ]) + else + this.buffer = new Yallist([ + Buffer.concat(Array.from(this.buffer), this[BUFFERLENGTH]) + ]) + } + + return this[READ](n || null, this.buffer.head.value) + } finally { + this[MAYBE_EMIT_END]() + } + } + + [READ] (n, chunk) { + if (n === chunk.length || n === null) + this[BUFFERSHIFT]() + else { + this.buffer.head.value = chunk.slice(n) + chunk = chunk.slice(0, n) + this[BUFFERLENGTH] -= n + } + + this.emit('data', chunk) + + if (!this.buffer.length && !this[EOF]) + this.emit('drain') + + return chunk + } + + end (chunk, encoding, cb) { + if (typeof chunk === 'function') + cb = chunk, chunk = null + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' + if (chunk) + this.write(chunk, encoding) + if (cb) + this.once('end', cb) + this[EOF] = true + this.writable = false + + // if we haven't written anything, then go ahead and emit, + // even if we're not reading. + // we'll re-emit if a new 'end' listener is added anyway. + // This makes MP more suitable to write-only use cases. + if (this.flowing || !this[PAUSED]) + this[MAYBE_EMIT_END]() + return this + } + + // don't let the internal resume be overwritten + [RESUME] () { + if (this[DESTROYED]) + return + + this[PAUSED] = false + this[FLOWING] = true + this.emit('resume') + if (this.buffer.length) + this[FLUSH]() + else if (this[EOF]) + this[MAYBE_EMIT_END]() + else + this.emit('drain') + } + + resume () { + return this[RESUME]() + } + + pause () { + this[FLOWING] = false + this[PAUSED] = true + } + + get destroyed () { + return this[DESTROYED] + } + + get flowing () { + return this[FLOWING] + } + + get paused () { + return this[PAUSED] + } + + [BUFFERPUSH] (chunk) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] += 1 + else + this[BUFFERLENGTH] += chunk.length + return this.buffer.push(chunk) + } + + [BUFFERSHIFT] () { + if (this.buffer.length) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] -= 1 + else + this[BUFFERLENGTH] -= this.buffer.head.value.length + } + return this.buffer.shift() + } + + [FLUSH] (noDrain) { + do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) + + if (!noDrain && !this.buffer.length && !this[EOF]) + this.emit('drain') + } + + [FLUSHCHUNK] (chunk) { + return chunk ? (this.emit('data', chunk), this.flowing) : false + } + + pipe (dest, opts) { + if (this[DESTROYED]) + return + + const ended = this[EMITTED_END] + opts = opts || {} + if (dest === proc.stdout || dest === proc.stderr) + opts.end = false + else + opts.end = opts.end !== false + + const p = { dest: dest, opts: opts, ondrain: _ => this[RESUME]() } + this.pipes.push(p) + + dest.on('drain', p.ondrain) + this[RESUME]() + // piping an ended stream ends immediately + if (ended && p.opts.end) + p.dest.end() + return dest + } + + addListener (ev, fn) { + return this.on(ev, fn) + } + + on (ev, fn) { + try { + return super.on(ev, fn) + } finally { + if (ev === 'data' && !this.pipes.length && !this.flowing) + this[RESUME]() + else if (isEndish(ev) && this[EMITTED_END]) { + super.emit(ev) + this.removeAllListeners(ev) + } else if (ev === 'error' && this[EMITTED_ERROR]) { + fn.call(this, this[EMITTED_ERROR]) + } + } + } + + get emittedEnd () { + return this[EMITTED_END] + } + + [MAYBE_EMIT_END] () { + if (!this[EMITTING_END] && + !this[EMITTED_END] && + !this[DESTROYED] && + this.buffer.length === 0 && + this[EOF]) { + this[EMITTING_END] = true + this.emit('end') + this.emit('prefinish') + this.emit('finish') + if (this[CLOSED]) + this.emit('close') + this[EMITTING_END] = false + } + } + + emit (ev, data) { + // error and close are only events allowed after calling destroy() + if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) + return + else if (ev === 'data') { + if (!data) + return + + if (this.pipes.length) + this.pipes.forEach(p => + p.dest.write(data) === false && this.pause()) + } else if (ev === 'end') { + // only actual end gets this treatment + if (this[EMITTED_END] === true) + return + + this[EMITTED_END] = true + this.readable = false + + if (this[DECODER]) { + data = this[DECODER].end() + if (data) { + this.pipes.forEach(p => p.dest.write(data)) + super.emit('data', data) + } + } + + this.pipes.forEach(p => { + p.dest.removeListener('drain', p.ondrain) + if (p.opts.end) + p.dest.end() + }) + } else if (ev === 'close') { + this[CLOSED] = true + // don't emit close before 'end' and 'finish' + if (!this[EMITTED_END] && !this[DESTROYED]) + return + } else if (ev === 'error') { + this[EMITTED_ERROR] = data + } + + // TODO: replace with a spread operator when Node v4 support drops + const args = new Array(arguments.length) + args[0] = ev + args[1] = data + if (arguments.length > 2) { + for (let i = 2; i < arguments.length; i++) { + args[i] = arguments[i] + } + } + + try { + return super.emit.apply(this, args) + } finally { + if (!isEndish(ev)) + this[MAYBE_EMIT_END]() + else + this.removeAllListeners(ev) + } + } + + // const all = await stream.collect() + collect () { + const buf = [] + if (!this[OBJECTMODE]) + buf.dataLength = 0 + // set the promise first, in case an error is raised + // by triggering the flow here. + const p = this.promise() + this.on('data', c => { + buf.push(c) + if (!this[OBJECTMODE]) + buf.dataLength += c.length + }) + return p.then(() => buf) + } + + // const data = await stream.concat() + concat () { + return this[OBJECTMODE] + ? Promise.reject(new Error('cannot concat in objectMode')) + : this.collect().then(buf => + this[OBJECTMODE] + ? Promise.reject(new Error('cannot concat in objectMode')) + : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) + } + + // stream.promise().then(() => done, er => emitted error) + promise () { + return new Promise((resolve, reject) => { + this.on(DESTROYED, () => reject(new Error('stream destroyed'))) + this.on('error', er => reject(er)) + this.on('end', () => resolve()) + }) + } + + // for await (let chunk of stream) + [ASYNCITERATOR] () { + const next = () => { + const res = this.read() + if (res !== null) + return Promise.resolve({ done: false, value: res }) + + if (this[EOF]) + return Promise.resolve({ done: true }) + + let resolve = null + let reject = null + const onerr = er => { + this.removeListener('data', ondata) + this.removeListener('end', onend) + reject(er) + } + const ondata = value => { + this.removeListener('error', onerr) + this.removeListener('end', onend) + this.pause() + resolve({ value: value, done: !!this[EOF] }) + } + const onend = () => { + this.removeListener('error', onerr) + this.removeListener('data', ondata) + resolve({ done: true }) + } + const ondestroy = () => onerr(new Error('stream destroyed')) + return new Promise((res, rej) => { + reject = rej + resolve = res + this.once(DESTROYED, ondestroy) + this.once('error', onerr) + this.once('end', onend) + this.once('data', ondata) + }) + } + + return { next } + } + + // for (let chunk of stream) + [ITERATOR] () { + const next = () => { + const value = this.read() + const done = value === null + return { value, done } + } + return { next } + } + + destroy (er) { + if (this[DESTROYED]) { + if (er) + this.emit('error', er) + else + this.emit(DESTROYED) + return this + } + + this[DESTROYED] = true + + // throw away all buffered data, it's never coming out + this.buffer = new Yallist() + this[BUFFERLENGTH] = 0 + + if (typeof this.close === 'function' && !this[CLOSED]) + this.close() + + if (er) + this.emit('error', er) + else // if no error to emit, still reject pending promises + this.emit(DESTROYED) + + return this + } + + static isStream (s) { + return !!s && (s instanceof Minipass || s instanceof Stream || + s instanceof EE && ( + typeof s.pipe === 'function' || // readable + (typeof s.write === 'function' && typeof s.end === 'function') // writable + )) + } +} diff --git a/node_modules/minipass/package.json b/node_modules/minipass/package.json new file mode 100644 index 0000000..1728e51 --- /dev/null +++ b/node_modules/minipass/package.json @@ -0,0 +1,39 @@ +{ + "name": "minipass", + "version": "3.1.6", + "description": "minimal implementation of a PassThrough stream", + "main": "index.js", + "dependencies": { + "yallist": "^4.0.0" + }, + "devDependencies": { + "end-of-stream": "^1.4.0", + "tap": "^15.0.9", + "through2": "^2.0.3" + }, + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish --tag=next", + "postpublish": "git push origin --follow-tags" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/minipass.git" + }, + "keywords": [ + "passthrough", + "stream" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "files": [ + "index.js" + ], + "tap": { + "check-coverage": true + }, + "engines": { + "node": ">=8" + } +} diff --git a/node_modules/minizlib/LICENSE b/node_modules/minizlib/LICENSE new file mode 100644 index 0000000..ffce738 --- /dev/null +++ b/node_modules/minizlib/LICENSE @@ -0,0 +1,26 @@ +Minizlib was created by Isaac Z. Schlueter. +It is a derivative work of the Node.js project. + +""" +Copyright Isaac Z. Schlueter and Contributors +Copyright Node.js contributors. All rights reserved. +Copyright Joyent, Inc. and other Node 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. +""" diff --git a/node_modules/minizlib/README.md b/node_modules/minizlib/README.md new file mode 100644 index 0000000..80e067a --- /dev/null +++ b/node_modules/minizlib/README.md @@ -0,0 +1,60 @@ +# minizlib + +A fast zlib stream built on [minipass](http://npm.im/minipass) and +Node.js's zlib binding. + +This module was created to serve the needs of +[node-tar](http://npm.im/tar) and +[minipass-fetch](http://npm.im/minipass-fetch). + +Brotli is supported in versions of node with a Brotli binding. + +## How does this differ from the streams in `require('zlib')`? + +First, there are no convenience methods to compress or decompress a +buffer. If you want those, use the built-in `zlib` module. This is +only streams. That being said, Minipass streams to make it fairly easy to +use as one-liners: `new zlib.Deflate().end(data).read()` will return the +deflate compressed result. + +This module compresses and decompresses the data as fast as you feed +it in. It is synchronous, and runs on the main process thread. Zlib +and Brotli operations can be high CPU, but they're very fast, and doing it +this way means much less bookkeeping and artificial deferral. + +Node's built in zlib streams are built on top of `stream.Transform`. +They do the maximally safe thing with respect to consistent +asynchrony, buffering, and backpressure. + +See [Minipass](http://npm.im/minipass) for more on the differences between +Node.js core streams and Minipass streams, and the convenience methods +provided by that class. + +## Classes + +- Deflate +- Inflate +- Gzip +- Gunzip +- DeflateRaw +- InflateRaw +- Unzip +- BrotliCompress (Node v10 and higher) +- BrotliDecompress (Node v10 and higher) + +## USAGE + +```js +const zlib = require('minizlib') +const input = sourceOfCompressedData() +const decode = new zlib.BrotliDecompress() +const output = whereToWriteTheDecodedData() +input.pipe(decode).pipe(output) +``` + +## REPRODUCIBLE BUILDS + +To create reproducible gzip compressed files across different operating +systems, set `portable: true` in the options. This causes minizlib to set +the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for +'unknown'. diff --git a/node_modules/minizlib/constants.js b/node_modules/minizlib/constants.js new file mode 100644 index 0000000..641ebc7 --- /dev/null +++ b/node_modules/minizlib/constants.js @@ -0,0 +1,115 @@ +// Update with any zlib constants that are added or changed in the future. +// Node v6 didn't export this, so we just hard code the version and rely +// on all the other hard-coded values from zlib v4736. When node v6 +// support drops, we can just export the realZlibConstants object. +const realZlibConstants = require('zlib').constants || + /* istanbul ignore next */ { ZLIB_VERNUM: 4736 } + +module.exports = Object.freeze(Object.assign(Object.create(null), { + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + Z_VERSION_ERROR: -6, + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + DEFLATE: 1, + INFLATE: 2, + GZIP: 3, + GUNZIP: 4, + DEFLATERAW: 5, + INFLATERAW: 6, + UNZIP: 7, + BROTLI_DECODE: 8, + BROTLI_ENCODE: 9, + Z_MIN_WINDOWBITS: 8, + Z_MAX_WINDOWBITS: 15, + Z_DEFAULT_WINDOWBITS: 15, + Z_MIN_CHUNK: 64, + Z_MAX_CHUNK: Infinity, + Z_DEFAULT_CHUNK: 16384, + Z_MIN_MEMLEVEL: 1, + Z_MAX_MEMLEVEL: 9, + Z_DEFAULT_MEMLEVEL: 8, + Z_MIN_LEVEL: -1, + Z_MAX_LEVEL: 9, + Z_DEFAULT_LEVEL: -1, + BROTLI_OPERATION_PROCESS: 0, + BROTLI_OPERATION_FLUSH: 1, + BROTLI_OPERATION_FINISH: 2, + BROTLI_OPERATION_EMIT_METADATA: 3, + BROTLI_MODE_GENERIC: 0, + BROTLI_MODE_TEXT: 1, + BROTLI_MODE_FONT: 2, + BROTLI_DEFAULT_MODE: 0, + BROTLI_MIN_QUALITY: 0, + BROTLI_MAX_QUALITY: 11, + BROTLI_DEFAULT_QUALITY: 11, + BROTLI_MIN_WINDOW_BITS: 10, + BROTLI_MAX_WINDOW_BITS: 24, + BROTLI_LARGE_MAX_WINDOW_BITS: 30, + BROTLI_DEFAULT_WINDOW: 22, + BROTLI_MIN_INPUT_BLOCK_BITS: 16, + BROTLI_MAX_INPUT_BLOCK_BITS: 24, + BROTLI_PARAM_MODE: 0, + BROTLI_PARAM_QUALITY: 1, + BROTLI_PARAM_LGWIN: 2, + BROTLI_PARAM_LGBLOCK: 3, + BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, + BROTLI_PARAM_SIZE_HINT: 5, + BROTLI_PARAM_LARGE_WINDOW: 6, + BROTLI_PARAM_NPOSTFIX: 7, + BROTLI_PARAM_NDIRECT: 8, + BROTLI_DECODER_RESULT_ERROR: 0, + BROTLI_DECODER_RESULT_SUCCESS: 1, + BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, + BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, + BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, + BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, + BROTLI_DECODER_NO_ERROR: 0, + BROTLI_DECODER_SUCCESS: 1, + BROTLI_DECODER_NEEDS_MORE_INPUT: 2, + BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, + BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, + BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, + BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, + BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, + BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, + BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, + BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, + BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, + BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, + BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, + BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, + BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, + BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, + BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, + BROTLI_DECODER_ERROR_UNREACHABLE: -31, +}, realZlibConstants)) diff --git a/node_modules/minizlib/index.js b/node_modules/minizlib/index.js new file mode 100644 index 0000000..fbaf69e --- /dev/null +++ b/node_modules/minizlib/index.js @@ -0,0 +1,348 @@ +'use strict' + +const assert = require('assert') +const Buffer = require('buffer').Buffer +const realZlib = require('zlib') + +const constants = exports.constants = require('./constants.js') +const Minipass = require('minipass') + +const OriginalBufferConcat = Buffer.concat + +const _superWrite = Symbol('_superWrite') +class ZlibError extends Error { + constructor (err) { + super('zlib: ' + err.message) + this.code = err.code + this.errno = err.errno + /* istanbul ignore if */ + if (!this.code) + this.code = 'ZLIB_ERROR' + + this.message = 'zlib: ' + err.message + Error.captureStackTrace(this, this.constructor) + } + + get name () { + return 'ZlibError' + } +} + +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. +const _opts = Symbol('opts') +const _flushFlag = Symbol('flushFlag') +const _finishFlushFlag = Symbol('finishFlushFlag') +const _fullFlushFlag = Symbol('fullFlushFlag') +const _handle = Symbol('handle') +const _onError = Symbol('onError') +const _sawError = Symbol('sawError') +const _level = Symbol('level') +const _strategy = Symbol('strategy') +const _ended = Symbol('ended') +const _defaultFullFlush = Symbol('_defaultFullFlush') + +class ZlibBase extends Minipass { + constructor (opts, mode) { + if (!opts || typeof opts !== 'object') + throw new TypeError('invalid options for ZlibBase constructor') + + super(opts) + this[_sawError] = false + this[_ended] = false + this[_opts] = opts + + this[_flushFlag] = opts.flush + this[_finishFlushFlag] = opts.finishFlush + // this will throw if any options are invalid for the class selected + try { + this[_handle] = new realZlib[mode](opts) + } catch (er) { + // make sure that all errors get decorated properly + throw new ZlibError(er) + } + + this[_onError] = (err) => { + // no sense raising multiple errors, since we abort on the first one. + if (this[_sawError]) + return + + this[_sawError] = true + + // there is no way to cleanly recover. + // continuing only obscures problems. + this.close() + this.emit('error', err) + } + + this[_handle].on('error', er => this[_onError](new ZlibError(er))) + this.once('end', () => this.close) + } + + close () { + if (this[_handle]) { + this[_handle].close() + this[_handle] = null + this.emit('close') + } + } + + reset () { + if (!this[_sawError]) { + assert(this[_handle], 'zlib binding closed') + return this[_handle].reset() + } + } + + flush (flushFlag) { + if (this.ended) + return + + if (typeof flushFlag !== 'number') + flushFlag = this[_fullFlushFlag] + this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) + } + + end (chunk, encoding, cb) { + if (chunk) + this.write(chunk, encoding) + this.flush(this[_finishFlushFlag]) + this[_ended] = true + return super.end(null, null, cb) + } + + get ended () { + return this[_ended] + } + + write (chunk, encoding, cb) { + // process the chunk using the sync process + // then super.write() all the outputted chunks + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' + + if (typeof chunk === 'string') + chunk = Buffer.from(chunk, encoding) + + if (this[_sawError]) + return + assert(this[_handle], 'zlib binding closed') + + // _processChunk tries to .close() the native handle after it's done, so we + // intercept that by temporarily making it a no-op. + const nativeHandle = this[_handle]._handle + const originalNativeClose = nativeHandle.close + nativeHandle.close = () => {} + const originalClose = this[_handle].close + this[_handle].close = () => {} + // It also calls `Buffer.concat()` at the end, which may be convenient + // for some, but which we are not interested in as it slows us down. + Buffer.concat = (args) => args + let result + try { + const flushFlag = typeof chunk[_flushFlag] === 'number' + ? chunk[_flushFlag] : this[_flushFlag] + result = this[_handle]._processChunk(chunk, flushFlag) + // if we don't throw, reset it back how it was + Buffer.concat = OriginalBufferConcat + } catch (err) { + // or if we do, put Buffer.concat() back before we emit error + // Error events call into user code, which may call Buffer.concat() + Buffer.concat = OriginalBufferConcat + this[_onError](new ZlibError(err)) + } finally { + if (this[_handle]) { + // Core zlib resets `_handle` to null after attempting to close the + // native handle. Our no-op handler prevented actual closure, but we + // need to restore the `._handle` property. + this[_handle]._handle = nativeHandle + nativeHandle.close = originalNativeClose + this[_handle].close = originalClose + // `_processChunk()` adds an 'error' listener. If we don't remove it + // after each call, these handlers start piling up. + this[_handle].removeAllListeners('error') + // make sure OUR error listener is still attached tho + } + } + + if (this[_handle]) + this[_handle].on('error', er => this[_onError](new ZlibError(er))) + + let writeReturn + if (result) { + if (Array.isArray(result) && result.length > 0) { + // The first buffer is always `handle._outBuffer`, which would be + // re-used for later invocations; so, we always have to copy that one. + writeReturn = this[_superWrite](Buffer.from(result[0])) + for (let i = 1; i < result.length; i++) { + writeReturn = this[_superWrite](result[i]) + } + } else { + writeReturn = this[_superWrite](Buffer.from(result)) + } + } + + if (cb) + cb() + return writeReturn + } + + [_superWrite] (data) { + return super.write(data) + } +} + +class Zlib extends ZlibBase { + constructor (opts, mode) { + opts = opts || {} + + opts.flush = opts.flush || constants.Z_NO_FLUSH + opts.finishFlush = opts.finishFlush || constants.Z_FINISH + super(opts, mode) + + this[_fullFlushFlag] = constants.Z_FULL_FLUSH + this[_level] = opts.level + this[_strategy] = opts.strategy + } + + params (level, strategy) { + if (this[_sawError]) + return + + if (!this[_handle]) + throw new Error('cannot switch params when binding is closed') + + // no way to test this without also not supporting params at all + /* istanbul ignore if */ + if (!this[_handle].params) + throw new Error('not supported in this implementation') + + if (this[_level] !== level || this[_strategy] !== strategy) { + this.flush(constants.Z_SYNC_FLUSH) + assert(this[_handle], 'zlib binding closed') + // .params() calls .flush(), but the latter is always async in the + // core zlib. We override .flush() temporarily to intercept that and + // flush synchronously. + const origFlush = this[_handle].flush + this[_handle].flush = (flushFlag, cb) => { + this.flush(flushFlag) + cb() + } + try { + this[_handle].params(level, strategy) + } finally { + this[_handle].flush = origFlush + } + /* istanbul ignore else */ + if (this[_handle]) { + this[_level] = level + this[_strategy] = strategy + } + } + } +} + +// minimal 2-byte header +class Deflate extends Zlib { + constructor (opts) { + super(opts, 'Deflate') + } +} + +class Inflate extends Zlib { + constructor (opts) { + super(opts, 'Inflate') + } +} + +// gzip - bigger header, same deflate compression +const _portable = Symbol('_portable') +class Gzip extends Zlib { + constructor (opts) { + super(opts, 'Gzip') + this[_portable] = opts && !!opts.portable + } + + [_superWrite] (data) { + if (!this[_portable]) + return super[_superWrite](data) + + // we'll always get the header emitted in one first chunk + // overwrite the OS indicator byte with 0xFF + this[_portable] = false + data[9] = 255 + return super[_superWrite](data) + } +} + +class Gunzip extends Zlib { + constructor (opts) { + super(opts, 'Gunzip') + } +} + +// raw - no header +class DeflateRaw extends Zlib { + constructor (opts) { + super(opts, 'DeflateRaw') + } +} + +class InflateRaw extends Zlib { + constructor (opts) { + super(opts, 'InflateRaw') + } +} + +// auto-detect header. +class Unzip extends Zlib { + constructor (opts) { + super(opts, 'Unzip') + } +} + +class Brotli extends ZlibBase { + constructor (opts, mode) { + opts = opts || {} + + opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS + opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH + + super(opts, mode) + + this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH + } +} + +class BrotliCompress extends Brotli { + constructor (opts) { + super(opts, 'BrotliCompress') + } +} + +class BrotliDecompress extends Brotli { + constructor (opts) { + super(opts, 'BrotliDecompress') + } +} + +exports.Deflate = Deflate +exports.Inflate = Inflate +exports.Gzip = Gzip +exports.Gunzip = Gunzip +exports.DeflateRaw = DeflateRaw +exports.InflateRaw = InflateRaw +exports.Unzip = Unzip +/* istanbul ignore else */ +if (typeof realZlib.BrotliCompress === 'function') { + exports.BrotliCompress = BrotliCompress + exports.BrotliDecompress = BrotliDecompress +} else { + exports.BrotliCompress = exports.BrotliDecompress = class { + constructor () { + throw new Error('Brotli is not supported in this version of Node.js') + } + } +} diff --git a/node_modules/minizlib/package.json b/node_modules/minizlib/package.json new file mode 100644 index 0000000..98825a5 --- /dev/null +++ b/node_modules/minizlib/package.json @@ -0,0 +1,42 @@ +{ + "name": "minizlib", + "version": "2.1.2", + "description": "A small fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding.", + "main": "index.js", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "scripts": { + "test": "tap test/*.js --100 -J", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/minizlib.git" + }, + "keywords": [ + "zlib", + "gzip", + "gunzip", + "deflate", + "inflate", + "compression", + "zip", + "unzip" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "MIT", + "devDependencies": { + "tap": "^14.6.9" + }, + "files": [ + "index.js", + "constants.js" + ], + "engines": { + "node": ">= 8" + } +} diff --git a/node_modules/mkdirp/CHANGELOG.md b/node_modules/mkdirp/CHANGELOG.md new file mode 100644 index 0000000..8145838 --- /dev/null +++ b/node_modules/mkdirp/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changers Lorgs! + +## 1.0 + +Full rewrite. Essentially a brand new module. + +- Return a promise instead of taking a callback. +- Use native `fs.mkdir(path, { recursive: true })` when available. +- Drop support for outdated Node.js versions. (Technically still works on + Node.js v8, but only 10 and above are officially supported.) + +## 0.x + +Original and most widely used recursive directory creation implementation +in JavaScript, dating back to 2010. diff --git a/node_modules/mkdirp/LICENSE b/node_modules/mkdirp/LICENSE new file mode 100644 index 0000000..13fcd15 --- /dev/null +++ b/node_modules/mkdirp/LICENSE @@ -0,0 +1,21 @@ +Copyright James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me) + +This project is free software released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +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/mkdirp/bin/cmd.js b/node_modules/mkdirp/bin/cmd.js new file mode 100644 index 0000000..6e0aa8d --- /dev/null +++ b/node_modules/mkdirp/bin/cmd.js @@ -0,0 +1,68 @@ +#!/usr/bin/env node + +const usage = () => ` +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories + that don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m If a directory needs to be created, set the mode as an octal + --mode= permission string. + + -v --version Print the mkdirp version number + + -h --help Print this helpful banner + + -p --print Print the first directories created for each path provided + + --manual Use manual implementation, even if native is available +` + +const dirs = [] +const opts = {} +let print = false +let dashdash = false +let manual = false +for (const arg of process.argv.slice(2)) { + if (dashdash) + dirs.push(arg) + else if (arg === '--') + dashdash = true + else if (arg === '--manual') + manual = true + else if (/^-h/.test(arg) || /^--help/.test(arg)) { + console.log(usage()) + process.exit(0) + } else if (arg === '-v' || arg === '--version') { + console.log(require('../package.json').version) + process.exit(0) + } else if (arg === '-p' || arg === '--print') { + print = true + } else if (/^-m/.test(arg) || /^--mode=/.test(arg)) { + const mode = parseInt(arg.replace(/^(-m|--mode=)/, ''), 8) + if (isNaN(mode)) { + console.error(`invalid mode argument: ${arg}\nMust be an octal number.`) + process.exit(1) + } + opts.mode = mode + } else + dirs.push(arg) +} + +const mkdirp = require('../') +const impl = manual ? mkdirp.manual : mkdirp +if (dirs.length === 0) + console.error(usage()) + +Promise.all(dirs.map(dir => impl(dir, opts))) + .then(made => print ? made.forEach(m => m && console.log(m)) : null) + .catch(er => { + console.error(er.message) + if (er.code) + console.error(' code: ' + er.code) + process.exit(1) + }) diff --git a/node_modules/mkdirp/index.js b/node_modules/mkdirp/index.js new file mode 100644 index 0000000..ad7a16c --- /dev/null +++ b/node_modules/mkdirp/index.js @@ -0,0 +1,31 @@ +const optsArg = require('./lib/opts-arg.js') +const pathArg = require('./lib/path-arg.js') + +const {mkdirpNative, mkdirpNativeSync} = require('./lib/mkdirp-native.js') +const {mkdirpManual, mkdirpManualSync} = require('./lib/mkdirp-manual.js') +const {useNative, useNativeSync} = require('./lib/use-native.js') + + +const mkdirp = (path, opts) => { + path = pathArg(path) + opts = optsArg(opts) + return useNative(opts) + ? mkdirpNative(path, opts) + : mkdirpManual(path, opts) +} + +const mkdirpSync = (path, opts) => { + path = pathArg(path) + opts = optsArg(opts) + return useNativeSync(opts) + ? mkdirpNativeSync(path, opts) + : mkdirpManualSync(path, opts) +} + +mkdirp.sync = mkdirpSync +mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) +mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) +mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) +mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) + +module.exports = mkdirp diff --git a/node_modules/mkdirp/lib/find-made.js b/node_modules/mkdirp/lib/find-made.js new file mode 100644 index 0000000..022e492 --- /dev/null +++ b/node_modules/mkdirp/lib/find-made.js @@ -0,0 +1,29 @@ +const {dirname} = require('path') + +const findMade = (opts, parent, path = undefined) => { + // we never want the 'made' return value to be a root directory + if (path === parent) + return Promise.resolve() + + return opts.statAsync(parent).then( + st => st.isDirectory() ? path : undefined, // will fail later + er => er.code === 'ENOENT' + ? findMade(opts, dirname(parent), parent) + : undefined + ) +} + +const findMadeSync = (opts, parent, path = undefined) => { + if (path === parent) + return undefined + + try { + return opts.statSync(parent).isDirectory() ? path : undefined + } catch (er) { + return er.code === 'ENOENT' + ? findMadeSync(opts, dirname(parent), parent) + : undefined + } +} + +module.exports = {findMade, findMadeSync} diff --git a/node_modules/mkdirp/lib/mkdirp-manual.js b/node_modules/mkdirp/lib/mkdirp-manual.js new file mode 100644 index 0000000..2eb18cd --- /dev/null +++ b/node_modules/mkdirp/lib/mkdirp-manual.js @@ -0,0 +1,64 @@ +const {dirname} = require('path') + +const mkdirpManual = (path, opts, made) => { + opts.recursive = false + const parent = dirname(path) + if (parent === path) { + return opts.mkdirAsync(path, opts).catch(er => { + // swallowed by recursive implementation on posix systems + // any other error is a failure + if (er.code !== 'EISDIR') + throw er + }) + } + + return opts.mkdirAsync(path, opts).then(() => made || path, er => { + if (er.code === 'ENOENT') + return mkdirpManual(parent, opts) + .then(made => mkdirpManual(path, opts, made)) + if (er.code !== 'EEXIST' && er.code !== 'EROFS') + throw er + return opts.statAsync(path).then(st => { + if (st.isDirectory()) + return made + else + throw er + }, () => { throw er }) + }) +} + +const mkdirpManualSync = (path, opts, made) => { + const parent = dirname(path) + opts.recursive = false + + if (parent === path) { + try { + return opts.mkdirSync(path, opts) + } catch (er) { + // swallowed by recursive implementation on posix systems + // any other error is a failure + if (er.code !== 'EISDIR') + throw er + else + return + } + } + + try { + opts.mkdirSync(path, opts) + return made || path + } catch (er) { + if (er.code === 'ENOENT') + return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) + if (er.code !== 'EEXIST' && er.code !== 'EROFS') + throw er + try { + if (!opts.statSync(path).isDirectory()) + throw er + } catch (_) { + throw er + } + } +} + +module.exports = {mkdirpManual, mkdirpManualSync} diff --git a/node_modules/mkdirp/lib/mkdirp-native.js b/node_modules/mkdirp/lib/mkdirp-native.js new file mode 100644 index 0000000..c7a6b69 --- /dev/null +++ b/node_modules/mkdirp/lib/mkdirp-native.js @@ -0,0 +1,39 @@ +const {dirname} = require('path') +const {findMade, findMadeSync} = require('./find-made.js') +const {mkdirpManual, mkdirpManualSync} = require('./mkdirp-manual.js') + +const mkdirpNative = (path, opts) => { + opts.recursive = true + const parent = dirname(path) + if (parent === path) + return opts.mkdirAsync(path, opts) + + return findMade(opts, path).then(made => + opts.mkdirAsync(path, opts).then(() => made) + .catch(er => { + if (er.code === 'ENOENT') + return mkdirpManual(path, opts) + else + throw er + })) +} + +const mkdirpNativeSync = (path, opts) => { + opts.recursive = true + const parent = dirname(path) + if (parent === path) + return opts.mkdirSync(path, opts) + + const made = findMadeSync(opts, path) + try { + opts.mkdirSync(path, opts) + return made + } catch (er) { + if (er.code === 'ENOENT') + return mkdirpManualSync(path, opts) + else + throw er + } +} + +module.exports = {mkdirpNative, mkdirpNativeSync} diff --git a/node_modules/mkdirp/lib/opts-arg.js b/node_modules/mkdirp/lib/opts-arg.js new file mode 100644 index 0000000..2fa4833 --- /dev/null +++ b/node_modules/mkdirp/lib/opts-arg.js @@ -0,0 +1,23 @@ +const { promisify } = require('util') +const fs = require('fs') +const optsArg = opts => { + if (!opts) + opts = { mode: 0o777, fs } + else if (typeof opts === 'object') + opts = { mode: 0o777, fs, ...opts } + else if (typeof opts === 'number') + opts = { mode: opts, fs } + else if (typeof opts === 'string') + opts = { mode: parseInt(opts, 8), fs } + else + throw new TypeError('invalid options argument') + + opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir + opts.mkdirAsync = promisify(opts.mkdir) + opts.stat = opts.stat || opts.fs.stat || fs.stat + opts.statAsync = promisify(opts.stat) + opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync + opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync + return opts +} +module.exports = optsArg diff --git a/node_modules/mkdirp/lib/path-arg.js b/node_modules/mkdirp/lib/path-arg.js new file mode 100644 index 0000000..cc07de5 --- /dev/null +++ b/node_modules/mkdirp/lib/path-arg.js @@ -0,0 +1,29 @@ +const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform +const { resolve, parse } = require('path') +const pathArg = path => { + if (/\0/.test(path)) { + // simulate same failure that node raises + throw Object.assign( + new TypeError('path must be a string without null bytes'), + { + path, + code: 'ERR_INVALID_ARG_VALUE', + } + ) + } + + path = resolve(path) + if (platform === 'win32') { + const badWinChars = /[*|"<>?:]/ + const {root} = parse(path) + if (badWinChars.test(path.substr(root.length))) { + throw Object.assign(new Error('Illegal characters in path.'), { + path, + code: 'EINVAL', + }) + } + } + + return path +} +module.exports = pathArg diff --git a/node_modules/mkdirp/lib/use-native.js b/node_modules/mkdirp/lib/use-native.js new file mode 100644 index 0000000..079361d --- /dev/null +++ b/node_modules/mkdirp/lib/use-native.js @@ -0,0 +1,10 @@ +const fs = require('fs') + +const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version +const versArr = version.replace(/^v/, '').split('.') +const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 + +const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir +const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync + +module.exports = {useNative, useNativeSync} diff --git a/node_modules/mkdirp/package.json b/node_modules/mkdirp/package.json new file mode 100644 index 0000000..2913ed0 --- /dev/null +++ b/node_modules/mkdirp/package.json @@ -0,0 +1,44 @@ +{ + "name": "mkdirp", + "description": "Recursively mkdir, like `mkdir -p`", + "version": "1.0.4", + "main": "index.js", + "keywords": [ + "mkdir", + "directory", + "make dir", + "make", + "dir", + "recursive", + "native" + ], + "repository": { + "type": "git", + "url": "https://github.com/isaacs/node-mkdirp.git" + }, + "scripts": { + "test": "tap", + "snap": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --follow-tags" + }, + "tap": { + "check-coverage": true, + "coverage-map": "map.js" + }, + "devDependencies": { + "require-inject": "^1.4.4", + "tap": "^14.10.7" + }, + "bin": "bin/cmd.js", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "files": [ + "bin", + "lib", + "index.js" + ] +} diff --git a/node_modules/mkdirp/readme.markdown b/node_modules/mkdirp/readme.markdown new file mode 100644 index 0000000..827de59 --- /dev/null +++ b/node_modules/mkdirp/readme.markdown @@ -0,0 +1,266 @@ +# mkdirp + +Like `mkdir -p`, but in Node.js! + +Now with a modern API and no\* bugs! + +\* may contain some bugs + +# example + +## pow.js + +```js +const mkdirp = require('mkdirp') + +// return value is a Promise resolving to the first directory created +mkdirp('/tmp/foo/bar/baz').then(made => + console.log(`made directories, starting with ${made}`)) +``` + +Output (where `/tmp/foo` already exists) + +``` +made directories, starting with /tmp/foo/bar +``` + +Or, if you don't have time to wait around for promises: + +```js +const mkdirp = require('mkdirp') + +// return value is the first directory created +const made = mkdirp.sync('/tmp/foo/bar/baz') +console.log(`made directories, starting with ${made}`) +``` + +And now /tmp/foo/bar/baz exists, huzzah! + +# methods + +```js +const mkdirp = require('mkdirp') +``` + +## mkdirp(dir, [opts]) -> Promise + +Create a new directory and any necessary subdirectories at `dir` with octal +permission string `opts.mode`. If `opts` is a string or number, it will be +treated as the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0o777 & +(~process.umask())`. + +Promise resolves to first directory `made` that had to be created, or +`undefined` if everything already exists. Promise rejects if any errors +are encountered. Note that, in the case of promise rejection, some +directories _may_ have been created, as recursive directory creation is not +an atomic operation. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdir(path, opts, cb)` +and `opts.fs.stat(path, cb)`. + +You can also override just one or the other of `mkdir` and `stat` by +passing in `opts.stat` or `opts.mkdir`, or providing an `fs` option that +only overrides one of these. + +## mkdirp.sync(dir, opts) -> String|null + +Synchronously create a new directory and any necessary subdirectories at +`dir` with octal permission string `opts.mode`. If `opts` is a string or +number, it will be treated as the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0o777 & +(~process.umask())`. + +Returns the first directory that had to be created, or undefined if +everything already exists. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` +and `opts.fs.statSync(path)`. + +You can also override just one or the other of `mkdirSync` and `statSync` +by passing in `opts.statSync` or `opts.mkdirSync`, or providing an `fs` +option that only overrides one of these. + +## mkdirp.manual, mkdirp.manualSync + +Use the manual implementation (not the native one). This is the default +when the native implementation is not available or the stat/mkdir +implementation is overridden. + +## mkdirp.native, mkdirp.nativeSync + +Use the native implementation (not the manual one). This is the default +when the native implementation is available and stat/mkdir are not +overridden. + +# implementation + +On Node.js v10.12.0 and above, use the native `fs.mkdir(p, +{recursive:true})` option, unless `fs.mkdir`/`fs.mkdirSync` has been +overridden by an option. + +## native implementation + +- If the path is a root directory, then pass it to the underlying + implementation and return the result/error. (In this case, it'll either + succeed or fail, but we aren't actually creating any dirs.) +- Walk up the path statting each directory, to find the first path that + will be created, `made`. +- Call `fs.mkdir(path, { recursive: true })` (or `fs.mkdirSync`) +- If error, raise it to the caller. +- Return `made`. + +## manual implementation + +- Call underlying `fs.mkdir` implementation, with `recursive: false` +- If error: + - If path is a root directory, raise to the caller and do not handle it + - If ENOENT, mkdirp parent dir, store result as `made` + - stat(path) + - If error, raise original `mkdir` error + - If directory, return `made` + - Else, raise original `mkdir` error +- else + - return `undefined` if a root dir, or `made` if set, or `path` + +## windows vs unix caveat + +On Windows file systems, attempts to create a root directory (ie, a drive +letter or root UNC path) will fail. If the root directory exists, then it +will fail with `EPERM`. If the root directory does not exist, then it will +fail with `ENOENT`. + +On posix file systems, attempts to create a root directory (in recursive +mode) will succeed silently, as it is treated like just another directory +that already exists. (In non-recursive mode, of course, it fails with +`EEXIST`.) + +In order to preserve this system-specific behavior (and because it's not as +if we can create the parent of a root directory anyway), attempts to create +a root directory are passed directly to the `fs` implementation, and any +errors encountered are not handled. + +## native error caveat + +The native implementation (as of at least Node.js v13.4.0) does not provide +appropriate errors in some cases (see +[nodejs/node#31481](https://github.com/nodejs/node/issues/31481) and +[nodejs/node#28015](https://github.com/nodejs/node/issues/28015)). + +In order to work around this issue, the native implementation will fall +back to the manual implementation if an `ENOENT` error is encountered. + +# choosing a recursive mkdir implementation + +There are a few to choose from! Use the one that suits your needs best :D + +## use `fs.mkdir(path, {recursive: true}, cb)` if: + +- You wish to optimize performance even at the expense of other factors. +- You don't need to know the first dir created. +- You are ok with getting `ENOENT` as the error when some other problem is + the actual cause. +- You can limit your platforms to Node.js v10.12 and above. +- You're ok with using callbacks instead of promises. +- You don't need/want a CLI. +- You don't need to override the `fs` methods in use. + +## use this module (mkdirp 1.x) if: + +- You need to know the first directory that was created. +- You wish to use the native implementation if available, but fall back + when it's not. +- You prefer promise-returning APIs to callback-taking APIs. +- You want more useful error messages than the native recursive mkdir + provides (at least as of Node.js v13.4), and are ok with re-trying on + `ENOENT` to achieve this. +- You need (or at least, are ok with) a CLI. +- You need to override the `fs` methods in use. + +## use [`make-dir`](http://npm.im/make-dir) if: + +- You do not need to know the first dir created (and wish to save a few + `stat` calls when using the native implementation for this reason). +- You wish to use the native implementation if available, but fall back + when it's not. +- You prefer promise-returning APIs to callback-taking APIs. +- You are ok with occasionally getting `ENOENT` errors for failures that + are actually related to something other than a missing file system entry. +- You don't need/want a CLI. +- You need to override the `fs` methods in use. + +## use mkdirp 0.x if: + +- You need to know the first directory that was created. +- You need (or at least, are ok with) a CLI. +- You need to override the `fs` methods in use. +- You're ok with using callbacks instead of promises. +- You are not running on Windows, where the root-level ENOENT errors can + lead to infinite regress. +- You think vinyl just sounds warmer and richer for some weird reason. +- You are supporting truly ancient Node.js versions, before even the advent + of a `Promise` language primitive. (Please don't. You deserve better.) + +# cli + +This package also ships with a `mkdirp` command. + +``` +$ mkdirp -h + +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories + that don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m If a directory needs to be created, set the mode as an octal + --mode= permission string. + + -v --version Print the mkdirp version number + + -h --help Print this helpful banner + + -p --print Print the first directories created for each path provided + + --manual Use manual implementation, even if native is available +``` + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install mkdirp +``` + +to get the library locally, or + +``` +npm install -g mkdirp +``` + +to get the command everywhere, or + +``` +npx mkdirp ... +``` + +to run the command without installing it globally. + +# platform support + +This module works on node v8, but only v10 and above are officially +supported, as Node v8 reached its LTS end of life 2020-01-01, which is in +the past, as of this writing. + +# license + +MIT diff --git a/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs b/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs new file mode 100644 index 0000000..4cd3c04 --- /dev/null +++ b/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs @@ -0,0 +1,4 @@ +import mod from "./lib/index.js"; + +export default mod["default"]; +export const CommaAndColonSeparatedRecord = mod.CommaAndColonSeparatedRecord; diff --git a/node_modules/mongodb-connection-string-url/LICENSE b/node_modules/mongodb-connection-string-url/LICENSE new file mode 100644 index 0000000..d57f55f --- /dev/null +++ b/node_modules/mongodb-connection-string-url/LICENSE @@ -0,0 +1,192 @@ + + 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 + + Copyright 2020 MongoDB Inc. + + 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/mongodb-connection-string-url/README.md b/node_modules/mongodb-connection-string-url/README.md new file mode 100644 index 0000000..0eb65d0 --- /dev/null +++ b/node_modules/mongodb-connection-string-url/README.md @@ -0,0 +1,25 @@ +# mongodb-connection-string-url + +MongoDB connection strings, based on the WhatWG URL API + +```js +import ConnectionString from 'mongodb-connection-string-url'; + +const cs = new ConnectionString('mongodb://localhost'); +cs.searchParams.set('readPreference', 'secondary'); +console.log(cs.href); // 'mongodb://localhost/?readPreference=secondary' +``` + +## Deviations from the WhatWG URL package + +- URL parameters are case-insensitive +- The `.host`, `.hostname` and `.port` properties cannot be set, and reading + them does not return meaningful results (and are typed as `never`in TypeScript) +- The `.hosts` property contains a list of all hosts in the connection string +- The `.href` property cannot be set, only read +- There is an additional `.isSRV` property, set to `true` for `mongodb+srv://` +- There is an additional `.clone()` utility method on the prototype + +## LICENSE + +Apache-2.0 diff --git a/node_modules/mongodb-connection-string-url/lib/index.d.ts b/node_modules/mongodb-connection-string-url/lib/index.d.ts new file mode 100644 index 0000000..1020a12 --- /dev/null +++ b/node_modules/mongodb-connection-string-url/lib/index.d.ts @@ -0,0 +1,40 @@ +import { URL } from 'whatwg-url'; +declare class CaseInsensitiveMap extends Map { + delete(name: any): boolean; + get(name: any): string | undefined; + has(name: any): boolean; + set(name: any, value: any): this; + _normalizeKey(name: any): string; +} +declare abstract class URLWithoutHost extends URL { + abstract get host(): never; + abstract set host(value: never); + abstract get hostname(): never; + abstract set hostname(value: never); + abstract get port(): never; + abstract set port(value: never); + abstract get href(): string; + abstract set href(value: string); +} +export default class ConnectionString extends URLWithoutHost { + _hosts: string[]; + constructor(uri: string); + get host(): never; + set host(_ignored: never); + get hostname(): never; + set hostname(_ignored: never); + get port(): never; + set port(_ignored: never); + get href(): string; + set href(_ignored: string); + get isSRV(): boolean; + get hosts(): string[]; + set hosts(list: string[]); + toString(): string; + clone(): ConnectionString; +} +export declare class CommaAndColonSeparatedRecord extends CaseInsensitiveMap { + constructor(from?: string | null); + toString(): string; +} +export {}; diff --git a/node_modules/mongodb-connection-string-url/lib/index.js b/node_modules/mongodb-connection-string-url/lib/index.js new file mode 100644 index 0000000..82b4f98 --- /dev/null +++ b/node_modules/mongodb-connection-string-url/lib/index.js @@ -0,0 +1,161 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CommaAndColonSeparatedRecord = void 0; +const whatwg_url_1 = require("whatwg-url"); +const DUMMY_HOSTNAME = '__this_is_a_placeholder__'; +const HOSTS_REGEX = new RegExp(String.raw `(?mongodb(?:\+srv|)):\/\/(?:(?[^:]*)(?::(?[^@]*))?@)?(?(?!:)[^\/?@]+)(?.*)`); +class CaseInsensitiveMap extends Map { + delete(name) { + return super.delete(this._normalizeKey(name)); + } + get(name) { + return super.get(this._normalizeKey(name)); + } + has(name) { + return super.has(this._normalizeKey(name)); + } + set(name, value) { + return super.set(this._normalizeKey(name), value); + } + _normalizeKey(name) { + name = `${name}`; + for (const key of this.keys()) { + if (key.toLowerCase() === name.toLowerCase()) { + name = key; + break; + } + } + return name; + } +} +const caseInsenstiveURLSearchParams = (Ctor) => class CaseInsenstiveURLSearchParams extends Ctor { + append(name, value) { + return super.append(this._normalizeKey(name), value); + } + delete(name) { + return super.delete(this._normalizeKey(name)); + } + get(name) { + return super.get(this._normalizeKey(name)); + } + getAll(name) { + return super.getAll(this._normalizeKey(name)); + } + has(name) { + return super.has(this._normalizeKey(name)); + } + set(name, value) { + return super.set(this._normalizeKey(name), value); + } + _normalizeKey(name) { + return CaseInsensitiveMap.prototype._normalizeKey.call(this, name); + } +}; +class URLWithoutHost extends whatwg_url_1.URL { +} +class MongoParseError extends Error { + get name() { + return 'MongoParseError'; + } +} +class ConnectionString extends URLWithoutHost { + constructor(uri) { + var _a; + const match = uri.match(HOSTS_REGEX); + if (!match) { + throw new MongoParseError(`Invalid connection string "${uri}"`); + } + const { protocol, username, password, hosts, rest } = (_a = match.groups) !== null && _a !== void 0 ? _a : {}; + if (!protocol || !hosts) { + throw new MongoParseError(`Protocol and host list are required in "${uri}"`); + } + try { + decodeURIComponent(username !== null && username !== void 0 ? username : ''); + decodeURIComponent(password !== null && password !== void 0 ? password : ''); + } + catch (err) { + throw new MongoParseError(err.message); + } + const illegalCharacters = new RegExp(String.raw `[:/?#\[\]@]`, 'gi'); + if (username === null || username === void 0 ? void 0 : username.match(illegalCharacters)) { + throw new MongoParseError(`Username contains unescaped characters ${username}`); + } + if (!username || !password) { + const uriWithoutProtocol = uri.replace(`${protocol}://`, ''); + if (uriWithoutProtocol.startsWith('@') || uriWithoutProtocol.startsWith(':')) { + throw new MongoParseError('URI contained empty userinfo section'); + } + } + if (password === null || password === void 0 ? void 0 : password.match(illegalCharacters)) { + throw new MongoParseError('Password contains unescaped characters'); + } + let authString = ''; + if (typeof username === 'string') + authString += username; + if (typeof password === 'string') + authString += `:${password}`; + if (authString) + authString += '@'; + super(`${protocol.toLowerCase()}://${authString}${DUMMY_HOSTNAME}${rest}`); + this._hosts = hosts.split(','); + if (this.isSRV && this.hosts.length !== 1) { + throw new MongoParseError('mongodb+srv URI cannot have multiple service names'); + } + if (this.isSRV && this.hosts.some(host => host.includes(':'))) { + throw new MongoParseError('mongodb+srv URI cannot have port number'); + } + if (!this.pathname) { + this.pathname = '/'; + } + Object.setPrototypeOf(this.searchParams, caseInsenstiveURLSearchParams(this.searchParams.constructor).prototype); + } + get host() { return DUMMY_HOSTNAME; } + set host(_ignored) { throw new Error('No single host for connection string'); } + get hostname() { return DUMMY_HOSTNAME; } + set hostname(_ignored) { throw new Error('No single host for connection string'); } + get port() { return ''; } + set port(_ignored) { throw new Error('No single host for connection string'); } + get href() { return this.toString(); } + set href(_ignored) { throw new Error('Cannot set href for connection strings'); } + get isSRV() { + return this.protocol.includes('srv'); + } + get hosts() { + return this._hosts; + } + set hosts(list) { + this._hosts = list; + } + toString() { + return super.toString().replace(DUMMY_HOSTNAME, this.hosts.join(',')); + } + clone() { + return new ConnectionString(this.toString()); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + const { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash } = this; + return { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash }; + } +} +exports.default = ConnectionString; +class CommaAndColonSeparatedRecord extends CaseInsensitiveMap { + constructor(from) { + super(); + for (const entry of (from !== null && from !== void 0 ? from : '').split(',')) { + if (!entry) + continue; + const colonIndex = entry.indexOf(':'); + if (colonIndex === -1) { + this.set(entry, ''); + } + else { + this.set(entry.slice(0, colonIndex), entry.slice(colonIndex + 1)); + } + } + } + toString() { + return [...this].map(entry => entry.join(':')).join(','); + } +} +exports.CommaAndColonSeparatedRecord = CommaAndColonSeparatedRecord; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/mongodb-connection-string-url/lib/index.js.map b/node_modules/mongodb-connection-string-url/lib/index.js.map new file mode 100644 index 0000000..df059f0 --- /dev/null +++ b/node_modules/mongodb-connection-string-url/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,2CAAkD;AAElD,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAInD,MAAM,WAAW,GAAG,IAAI,MAAM,CAC5B,MAAM,CAAC,GAAG,CAAA,uHAAuH,CAClI,CAAC;AAEF,MAAM,kBAAmB,SAAQ,GAAmB;IAClD,MAAM,CAAC,IAAS;QACd,OAAO,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,GAAG,CAAC,IAAS;QACX,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;IAC7C,CAAC;IAED,GAAG,CAAC,IAAS;QACX,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;IAC7C,CAAC;IAED,GAAG,CAAC,IAAS,EAAE,KAAU;QACvB,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;IACpD,CAAC;IAED,aAAa,CAAC,IAAS;QACrB,IAAI,GAAG,GAAG,IAAI,EAAE,CAAC;QACjB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,EAAE;YAC7B,IAAI,GAAG,CAAC,WAAW,EAAE,KAAK,IAAI,CAAC,WAAW,EAAE,EAAE;gBAC5C,IAAI,GAAG,GAAG,CAAC;gBACX,MAAM;aACP;SACF;QACD,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAED,MAAM,6BAA6B,GAAG,CAAC,IAA4B,EA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AE,MAAM,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;IACrG,CAAC;CACF;AA/FD,mCA+FC;AAMD,MAAa,4BAA6B,SAAQ,kBAAkB;IAClE,YAAY,IAAoB;QAC9B,KAAK,EAAE,CAAC;QACR,KAAK,MAAM,KAAK,IAAI,CAAC,IAAI,aAAJ,IAAI,cAAJ,IAAI,GAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;YAC3C,IAAI,CAAC,KAAK;gBAAE,SAAS;YACrB,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YAEtC,IAAI,UAAU,KAAK,CAAC,CAAC,EAAE;gBACrB,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;aACrB;iBAAM;gBACL,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,UAAU,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;aACnE;SACF;IACH,CAAC;IAED,QAAQ;QACN,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC3D,CAAC;CACF;AAlBD,oEAkBC"} \ No newline at end of file diff --git a/node_modules/mongodb-connection-string-url/package.json b/node_modules/mongodb-connection-string-url/package.json new file mode 100644 index 0000000..5445bf8 --- /dev/null +++ b/node_modules/mongodb-connection-string-url/package.json @@ -0,0 +1,62 @@ +{ + "name": "mongodb-connection-string-url", + "version": "2.1.0", + "description": "MongoDB connection strings, based on the WhatWG URL API", + "keywords": [ + "password", + "prompt", + "tty" + ], + "homepage": "https://github.com/mongodb-js/mongodb-connection-string-url", + "repository": { + "type": "git", + "url": "https://github.com/mongodb-js/mongodb-connection-string-url.git" + }, + "bugs": { + "url": "https://github.com/mongodb-js/mongodb-connection-string-url/issues" + }, + "main": "lib/index.js", + "exports": { + "require": "./lib/index.js", + "import": "./.esm-wrapper.mjs" + }, + "files": [ + "LICENSE", + "lib", + "package.json", + "README.md", + ".esm-wrapper.mjs" + ], + "scripts": { + "lint": "eslint \"{src,test}/**/*.ts\"", + "test": "npm run lint && npm run build && nyc mocha --colors -r ts-node/register test/*.ts", + "build": "npm run compile-ts && gen-esm-wrapper . ./.esm-wrapper.mjs", + "prepack": "npm run build", + "compile-ts": "tsc -p tsconfig.json" + }, + "license": "Apache-2.0", + "devDependencies": { + "@types/chai": "^4.2.5", + "@types/mocha": "^8.0.3", + "@types/node": "^14.11.1", + "@typescript-eslint/eslint-plugin": "^4.2.0", + "@typescript-eslint/parser": "^4.2.0", + "chai": "^4.2.0", + "eslint": "^7.9.0", + "eslint-config-semistandard": "^15.0.1", + "eslint-config-standard": "^14.1.1", + "eslint-plugin-import": "^2.22.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^4.2.1", + "eslint-plugin-standard": "^4.0.1", + "gen-esm-wrapper": "^1.1.3", + "mocha": "^8.1.3", + "nyc": "^15.1.0", + "ts-node": "^9.0.0", + "typescript": "^4.0.3" + }, + "dependencies": { + "@types/whatwg-url": "^8.2.1", + "whatwg-url": "^9.1.0" + } +} diff --git a/node_modules/mongodb/LICENSE.md b/node_modules/mongodb/LICENSE.md new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/node_modules/mongodb/LICENSE.md @@ -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. \ No newline at end of file diff --git a/node_modules/mongodb/README.md b/node_modules/mongodb/README.md new file mode 100644 index 0000000..7100cce --- /dev/null +++ b/node_modules/mongodb/README.md @@ -0,0 +1,278 @@ +# MongoDB NodeJS Driver + +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. + +**Upgrading to version 4? Take a look at our [upgrade guide here](https://github.com/mongodb/node-mongodb-native/blob/4.1/docs/CHANGES_4.0.0.md)!** + +## Quick Links + +| what | where | +| ------------- | ------------------------------------------------------------------------------------------------------ | +| documentation | [docs.mongodb.com/drivers/node](https://docs.mongodb.com/drivers/node) | +| api-doc | [mongodb.github.io/node-mongodb-native/4.1/](https://mongodb.github.io/node-mongodb-native/4.1/) | +| npm package | [www.npmjs.com/package/mongodb](https://www.npmjs.com/package/mongodb) | +| source | [github.com/mongodb/node-mongodb-native](https://github.com/mongodb/node-mongodb-native) | +| mongodb | [www.mongodb.com](https://www.mongodb.com) | +| changelog | [HISTORY.md](https://github.com/mongodb/node-mongodb-native/blob/4.1/HISTORY.md) | +| upgrade to v4 | [docs/CHANGES_4.0.0.md](https://github.com/mongodb/node-mongodb-native/blob/4.1/docs/CHANGES_4.0.0.md) | + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a +case in our issue management tool, JIRA: + +- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). +- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Support / Feedback + +For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](https://docs.mongodb.com/manual/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [MongoDB Community Forums](https://community.mongodb.com/tags/c/drivers-odms-connectors/7/node-js-driver). + +### Change Log + +Change history can be found in [`HISTORY.md`](https://github.com/mongodb/node-mongodb-native/blob/4.1/HISTORY.md). + +### Compatibility + +For version compatibility matrices, please refer to the following links: + +- [MongoDB](https://docs.mongodb.com/drivers/node/compatibility#mongodb-compatibility) +- [NodeJS](https://docs.mongodb.com/drivers/node/compatibility#language-compatibility) + +#### Typescript Version + +We recommend using the latest version of typescript, however we do provide a [downleveled](https://github.com/sandersn/downlevel-dts#readme) version of the type definitions that we test compiling against `typescript@4.0.2`. +Since typescript [does not restrict breaking changes to major versions](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes) we consider this support best effort. +If you run into any unexpected compiler failures please let us know and we will do our best to correct it. + +## Installation + +The recommended way to get started using the Node.js 4.x driver is by using the `npm` (Node Package Manager) to install the dependency in your project. + +After you've created your own project using `npm init`, you can run: + +```bash +npm install mongodb +# or ... +yarn add mongodb +``` + +This will download the MongoDB driver and add a dependency entry in your `package.json` file. + +If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions: + +```sh +npm install -D @types/node +``` + +## Troubleshooting + +The MongoDB driver depends on several other packages. These are: + +- [bson](https://github.com/mongodb/js-bson) +- [bson-ext](https://github.com/mongodb-js/bson-ext) +- [kerberos](https://github.com/mongodb-js/kerberos) +- [mongodb-client-encryption](https://github.com/mongodb/libmongocrypt#readme) + +Some of these packages include native C++ extensions, consult the [trouble shooting guide here](https://github.com/mongodb/node-mongodb-native/blob/4.1/docs/native-extensions.md) if you run into issues. + +## Quick Start + +This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [official documentation](https://docs.mongodb.com/drivers/node/). + +### Create the `package.json` file + +First, create a directory where your application will live. + +```bash +mkdir myProject +cd myProject +``` + +Enter the following command and answer the questions to create the initial structure for your new project: + +```bash +npm init -y +``` + +Next, install the driver as a dependency. + +```bash +npm install mongodb +``` + +### Start a MongoDB Server + +For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). + +1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) +2. Create a database directory (in this case under **/data**). +3. Install and start a `mongod` process. + +```bash +mongod --dbpath=/data +``` + +You should see the **mongod** process start up and print some status information. + +### Connect to MongoDB + +Create a new **app.js** file and add the following code to try out some basic CRUD +operations using the MongoDB driver. + +Add code to connect to the server and the database **myProject**: + +> **NOTE:** All the examples below use async/await syntax. +> +> However, all async API calls support an optional callback as the final argument, +> if a callback is provided a Promise will not be returned. + +```js +const { MongoClient } = require('mongodb'); +// or as an es module: +// import { MongoClient } from 'mongodb' + +// Connection URL +const url = 'mongodb://localhost:27017'; +const client = new MongoClient(url); + +// Database Name +const dbName = 'myProject'; + +async function main() { + // Use connect method to connect to the server + await client.connect(); + console.log('Connected successfully to server'); + const db = client.db(dbName); + const collection = db.collection('documents'); + + // the following code examples can be pasted here... + + return 'done.'; +} + +main() + .then(console.log) + .catch(console.error) + .finally(() => client.close()); +``` + +Run your app from the command line with: + +```bash +node app.js +``` + +The application should print **Connected successfully to server** to the console. + +### Insert a Document + +Add to **app.js** the following function which uses the **insertMany** +method to add three documents to the **documents** collection. + +```js +const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]); +console.log('Inserted documents =>', insertResult); +``` + +The **insertMany** command returns an object with information about the insert operations. + +### Find All Documents + +Add a query that returns all the documents. + +```js +const findResult = await collection.find({}).toArray(); +console.log('Found documents =>', findResult); +``` + +This query returns all the documents in the **documents** collection. +If you add this below the insertMany example you'll see the document's you've inserted. + +### Find Documents with a Query Filter + +Add a query filter to find only documents which meet the query criteria. + +```js +const filteredDocs = await collection.find({ a: 3 }).toArray(); +console.log('Found documents filtered by { a: 3 } =>', filteredDocs); +``` + +Only the documents which match `'a' : 3` should be returned. + +### Update a document + +The following operation updates a document in the **documents** collection. + +```js +const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } }); +console.log('Updated documents =>', updateResult); +``` + +The method updates the first document where the field **a** is equal to **3** by adding a new field **b** to the document set to **1**. `updateResult` contains information about whether there was a matching document to update or not. + +### Remove a document + +Remove the document where the field **a** is equal to **3**. + +```js +const deleteResult = await collection.deleteMany({ a: 3 }); +console.log('Deleted documents =>', deleteResult); +``` + +### Index a Collection + +[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's +performance. The following function creates an index on the **a** field in the +**documents** collection. + +```js +const indexName = await collection.createIndex({ a: 1 }); +console.log('index name =', indexName); +``` + +For more detailed information, see the [indexing strategies page](https://docs.mongodb.com/manual/applications/indexes/). + +## Error Handling + +If you need to filter certain errors from our driver we have a helpful tree of errors described in [docs/errors.md](https://github.com/mongodb/node-mongodb-native/blob/4.1/docs/errors.md). + +It is our recommendation to use `instanceof` checks on errors and to avoid relying on parsing `error.message` and `error.name` strings in your code. +We guarantee `instanceof` checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors. + +Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release. +This means `instanceof` will always be able to accurately capture the errors that our driver throws (or returns in a callback). + +```typescript +const client = new MongoClient(url); +await client.connect(); +const collection = client.db().collection('collection'); + +try { + await collection.insertOne({ _id: 1 }); + await collection.insertOne({ _id: 1 }); // duplicate key error +} catch (error) { + if (error instanceof MongoServerError) { + console.log(`Error worth logging: ${error}`); // special case for some reason + } + throw error; // still want to crash +} +``` + +## Next Steps + +- [MongoDB Documentation](https://docs.mongodb.com/manual/) +- [MongoDB Node Driver Documentation](https://docs.mongodb.com/drivers/node/) +- [Read about Schemas](https://docs.mongodb.com/manual/core/data-modeling-introduction/) +- [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) + +## License + +[Apache 2.0](LICENSE.md) + +© 2009-2012 Christian Amor Kvalheim +© 2012-present MongoDB [Contributors](https://github.com/mongodb/node-mongodb-native/blob/4.1/CONTRIBUTORS.md) diff --git a/node_modules/mongodb/etc/prepare.js b/node_modules/mongodb/etc/prepare.js new file mode 100644 index 0000000..2039d0b --- /dev/null +++ b/node_modules/mongodb/etc/prepare.js @@ -0,0 +1,12 @@ +#! /usr/bin/env node +var cp = require('child_process'); +var fs = require('fs'); +var os = require('os'); + +if (fs.existsSync('src')) { + cp.spawn('npm', ['run', 'build:dts'], { stdio: 'inherit', shell: os.platform() === 'win32' }); +} else { + if (!fs.existsSync('lib')) { + console.warn('MongoDB: No compiled javascript present, the driver is not installed correctly.'); + } +} diff --git a/node_modules/mongodb/lib/admin.js b/node_modules/mongodb/lib/admin.js new file mode 100644 index 0000000..09a59be --- /dev/null +++ b/node_modules/mongodb/lib/admin.js @@ -0,0 +1,124 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Admin = void 0; +const add_user_1 = require("./operations/add_user"); +const remove_user_1 = require("./operations/remove_user"); +const validate_collection_1 = require("./operations/validate_collection"); +const list_databases_1 = require("./operations/list_databases"); +const execute_operation_1 = require("./operations/execute_operation"); +const run_command_1 = require("./operations/run_command"); +const utils_1 = require("./utils"); +/** + * The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Use the admin database for the operation + * const adminDb = client.db(dbName).admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * expect(err).to.not.exist; + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + * ``` + */ +class Admin { + /** + * Create a new Admin instance + * @internal + */ + constructor(db) { + this.s = { db }; + } + command(command, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = Object.assign({ dbName: 'admin' }, options); + return execute_operation_1.executeOperation(utils_1.getTopology(this.s.db), new run_command_1.RunCommandOperation(this.s.db, command, options), callback); + } + buildInfo(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ buildinfo: 1 }, options, callback); + } + serverInfo(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ buildinfo: 1 }, options, callback); + } + serverStatus(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ serverStatus: 1 }, options, callback); + } + ping(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ ping: 1 }, options, callback); + } + addUser(username, password, options, callback) { + if (typeof password === 'function') { + (callback = password), (password = undefined), (options = {}); + } + else if (typeof password !== 'string') { + if (typeof options === 'function') { + (callback = options), (options = password), (password = undefined); + } + else { + (options = password), (callback = undefined), (password = undefined); + } + } + else { + if (typeof options === 'function') + (callback = options), (options = {}); + } + options = Object.assign({ dbName: 'admin' }, options); + return execute_operation_1.executeOperation(utils_1.getTopology(this.s.db), new add_user_1.AddUserOperation(this.s.db, username, password, options), callback); + } + removeUser(username, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = Object.assign({ dbName: 'admin' }, options); + return execute_operation_1.executeOperation(utils_1.getTopology(this.s.db), new remove_user_1.RemoveUserOperation(this.s.db, username, options), callback); + } + validateCollection(collectionName, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return execute_operation_1.executeOperation(utils_1.getTopology(this.s.db), new validate_collection_1.ValidateCollectionOperation(this, collectionName, options), callback); + } + listDatabases(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return execute_operation_1.executeOperation(utils_1.getTopology(this.s.db), new list_databases_1.ListDatabasesOperation(this.s.db, options), callback); + } + replSetGetStatus(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ replSetGetStatus: 1 }, options, callback); + } +} +exports.Admin = Admin; +//# sourceMappingURL=admin.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/admin.js.map b/node_modules/mongodb/lib/admin.js.map new file mode 100644 index 0000000..c782035 --- /dev/null +++ b/node_modules/mongodb/lib/admin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"admin.js","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":";;;AAAA,oDAAyE;AACzE,0DAAkF;AAClF,0EAG0C;AAC1C,gEAIqC;AACrC,sEAAkE;AAClE,0DAAkF;AAClF,mCAAgD;AAUhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAa,KAAK;IAIhB;;;OAGG;IACH,YAAY,EAAM;QAChB,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC;IAClB,CAAC;IAaD,OAAO,CACL,OAAiB,EACjB,OAAgD,EAChD,QAA6B;QAE7B,IAAI,OAAO,OAAO,KAAK,UAAU;YAAE,CAAC,QAAQ,GAAG,OAAO,CAAC,EAAE,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;QACxE,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,OAAO,CAAC,CAAC;QAEtD,OAAO,oCAAgB,CACrB,mBAAW,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EACtB,IAAI,iCAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,EAAE,OAAO,CAAC,EACpD,QAAQ,CACT,CAAC;IACJ,CAAC;IAYD,SAAS,CACP,OAAsD,EACtD,QAA6B;QAE7B,IAAI,OAAO,OAAO,KAAK,UAAU;YAAE,CAAC,QAAQ,GAAG,OAAO,CAAC,EAAE,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;QACxE,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,G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OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,QAA8B,CAAC,CAAC;IACxF,CAAC;CACF;AApQD,sBAoQC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/bson.js b/node_modules/mongodb/lib/bson.js new file mode 100644 index 0000000..74385c8 --- /dev/null +++ b/node_modules/mongodb/lib/bson.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveBSONOptions = exports.pluckBSONSerializeOptions = exports.Map = exports.BSONSymbol = exports.BSONRegExp = exports.DBRef = exports.Double = exports.Int32 = exports.Decimal128 = exports.MaxKey = exports.MinKey = exports.Code = exports.Timestamp = exports.ObjectId = exports.Binary = exports.Long = exports.calculateObjectSize = exports.serialize = exports.deserialize = void 0; +// eslint-disable-next-line @typescript-eslint/no-var-requires +let BSON = require('bson'); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + BSON = require('bson-ext'); +} +catch { } // eslint-disable-line +/** @internal */ +exports.deserialize = BSON.deserialize; +/** @internal */ +exports.serialize = BSON.serialize; +/** @internal */ +exports.calculateObjectSize = BSON.calculateObjectSize; +var bson_1 = require("bson"); +Object.defineProperty(exports, "Long", { enumerable: true, get: function () { return bson_1.Long; } }); +Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return bson_1.Binary; } }); +Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function () { return bson_1.ObjectId; } }); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return bson_1.Timestamp; } }); +Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return bson_1.Code; } }); +Object.defineProperty(exports, "MinKey", { enumerable: true, get: function () { return bson_1.MinKey; } }); +Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function () { return bson_1.MaxKey; } }); +Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function () { return bson_1.Decimal128; } }); +Object.defineProperty(exports, "Int32", { enumerable: true, get: function () { return bson_1.Int32; } }); +Object.defineProperty(exports, "Double", { enumerable: true, get: function () { return bson_1.Double; } }); +Object.defineProperty(exports, "DBRef", { enumerable: true, get: function () { return bson_1.DBRef; } }); +Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function () { return bson_1.BSONRegExp; } }); +Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function () { return bson_1.BSONSymbol; } }); +Object.defineProperty(exports, "Map", { enumerable: true, get: function () { return bson_1.Map; } }); +function pluckBSONSerializeOptions(options) { + const { fieldsAsRaw, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw } = options; + return { + fieldsAsRaw, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw + }; +} +exports.pluckBSONSerializeOptions = pluckBSONSerializeOptions; +/** + * Merge the given BSONSerializeOptions, preferring options over the parent's options, and + * substituting defaults for values not set. + * + * @internal + */ +function resolveBSONOptions(options, parent) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; + const parentOptions = parent === null || parent === void 0 ? void 0 : parent.bsonOptions; + return { + raw: (_b = (_a = options === null || options === void 0 ? void 0 : options.raw) !== null && _a !== void 0 ? _a : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.raw) !== null && _b !== void 0 ? _b : false, + promoteLongs: (_d = (_c = options === null || options === void 0 ? void 0 : options.promoteLongs) !== null && _c !== void 0 ? _c : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.promoteLongs) !== null && _d !== void 0 ? _d : true, + promoteValues: (_f = (_e = options === null || options === void 0 ? void 0 : options.promoteValues) !== null && _e !== void 0 ? _e : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.promoteValues) !== null && _f !== void 0 ? _f : true, + promoteBuffers: (_h = (_g = options === null || options === void 0 ? void 0 : options.promoteBuffers) !== null && _g !== void 0 ? _g : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.promoteBuffers) !== null && _h !== void 0 ? _h : false, + ignoreUndefined: (_k = (_j = options === null || options === void 0 ? void 0 : options.ignoreUndefined) !== null && _j !== void 0 ? _j : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.ignoreUndefined) !== null && _k !== void 0 ? _k : false, + bsonRegExp: (_m = (_l = options === null || options === void 0 ? void 0 : options.bsonRegExp) !== null && _l !== void 0 ? _l : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.bsonRegExp) !== null && _m !== void 0 ? _m : false, + serializeFunctions: (_p = (_o = options === null || options === void 0 ? void 0 : options.serializeFunctions) !== null && _o !== void 0 ? _o : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.serializeFunctions) !== null && _p !== void 0 ? _p : false, + fieldsAsRaw: (_r = (_q = options === null || options === void 0 ? void 0 : options.fieldsAsRaw) !== null && _q !== void 0 ? _q : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.fieldsAsRaw) !== null && _r !== void 0 ? _r : {} + }; +} +exports.resolveBSONOptions = resolveBSONOptions; +//# sourceMappingURL=bson.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/bson.js.map b/node_modules/mongodb/lib/bson.js.map new file mode 100644 index 0000000..2f9bfd7 --- /dev/null +++ b/node_modules/mongodb/lib/bson.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.js","sourceRoot":"","sources":["../src/bson.ts"],"names":[],"mappings":";;;AAMA,8DAA8D;AAC9D,IAAI,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAC3B,IAAI;IACF,wEAAwE;IACxE,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAC5B;AAAC,MAAM,GAAE,CAAC,sBAAsB;AAEjC,gBAAgB;AACH,QAAA,WAAW,GAAG,IAAI,CAAC,WAAmC,CAAC;AACpE,gBAAgB;AACH,QAAA,SAAS,GAAG,IAAI,CAAC,SAA+B,CAAC;AAC9D,gBAAgB;AACH,QAAA,mBAAmB,GAAG,IAAI,CAAC,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CAAI,IAAI;QAC7E,cAAc,EAAE,MAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,cAAc,mCAAI,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,cAAc,mCAAI,KAAK;QACjF,eAAe,EAAE,MAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,eAAe,mCAAI,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,eAAe,mCAAI,KAAK;QACpF,UAAU,EAAE,MAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,mCAAI,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,UAAU,mCAAI,KAAK;QACrE,kBAAkB,EAAE,MAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,kBAAkB,mCAAI,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,kBAAkB,mCAAI,KAAK;QAC7F,WAAW,EAAE,MAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,WAAW,mCAAI,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,WAAW,mCAAI,EAAE;KACtE,CAAC;AACJ,CAAC;AAfD,gDAeC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/bulk/common.js b/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 0000000..1955041 --- /dev/null +++ b/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,941 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BulkOperationBase = exports.FindOperators = exports.MongoBulkWriteError = exports.WriteError = exports.WriteConcernError = exports.BulkWriteResult = exports.Batch = exports.BatchType = void 0; +const promise_provider_1 = require("../promise_provider"); +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const execute_operation_1 = require("../operations/execute_operation"); +const insert_1 = require("../operations/insert"); +const update_1 = require("../operations/update"); +const delete_1 = require("../operations/delete"); +const write_concern_1 = require("../write_concern"); +/** @internal */ +const kServerError = Symbol('serverError'); +/** @public */ +exports.BatchType = Object.freeze({ + INSERT: 1, + UPDATE: 2, + DELETE: 3 +}); +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +class Batch { + constructor(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; + } +} +exports.Batch = Batch; +/** + * @public + * The result of a bulk write. + */ +class BulkWriteResult { + /** + * Create a new BulkWriteResult instance + * @internal + */ + constructor(bulkResult) { + this.result = bulkResult; + } + /** Number of documents inserted. */ + get insertedCount() { + var _a; + return (_a = this.result.nInserted) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents matched for update. */ + get matchedCount() { + var _a; + return (_a = this.result.nMatched) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents modified. */ + get modifiedCount() { + var _a; + return (_a = this.result.nModified) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents deleted. */ + get deletedCount() { + var _a; + return (_a = this.result.nRemoved) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents upserted. */ + get upsertedCount() { + var _a; + return (_a = this.result.upserted.length) !== null && _a !== void 0 ? _a : 0; + } + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds() { + var _a; + const upserted = {}; + for (const doc of (_a = this.result.upserted) !== null && _a !== void 0 ? _a : []) { + upserted[doc.index] = doc._id; + } + return upserted; + } + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds() { + var _a; + const inserted = {}; + for (const doc of (_a = this.result.insertedIds) !== null && _a !== void 0 ? _a : []) { + inserted[doc.index] = doc._id; + } + return inserted; + } + /** Evaluates to true if the bulk operation correctly executes */ + get ok() { + return this.result.ok; + } + /** The number of inserted documents */ + get nInserted() { + return this.result.nInserted; + } + /** Number of upserted documents */ + get nUpserted() { + return this.result.nUpserted; + } + /** Number of matched documents */ + get nMatched() { + return this.result.nMatched; + } + /** Number of documents updated physically on disk */ + get nModified() { + return this.result.nModified; + } + /** Number of removed documents */ + get nRemoved() { + return this.result.nRemoved; + } + /** Returns an array of all inserted ids */ + getInsertedIds() { + return this.result.insertedIds; + } + /** Returns an array of all upserted ids */ + getUpsertedIds() { + return this.result.upserted; + } + /** Returns the upserted id at the given index */ + getUpsertedIdAt(index) { + return this.result.upserted[index]; + } + /** Returns raw internal result */ + getRawResponse() { + return this.result; + } + /** Returns true if the bulk operation contains a write error */ + hasWriteErrors() { + return this.result.writeErrors.length > 0; + } + /** Returns the number of write errors off the bulk operation */ + getWriteErrorCount() { + return this.result.writeErrors.length; + } + /** Returns a specific write error object */ + getWriteErrorAt(index) { + if (index < this.result.writeErrors.length) { + return this.result.writeErrors[index]; + } + } + /** Retrieve all write errors */ + getWriteErrors() { + return this.result.writeErrors; + } + /** Retrieve lastOp if available */ + getLastOp() { + return this.result.opTime; + } + /** Retrieve the write concern error if one exists */ + getWriteConcernError() { + if (this.result.writeConcernErrors.length === 0) { + return; + } + else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; + } + else { + // Combine the errors + let errmsg = ''; + for (let i = 0; i < this.result.writeConcernErrors.length; i++) { + const err = this.result.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + // TODO: Something better + if (i === 0) + errmsg = errmsg + ' and '; + } + return new WriteConcernError({ errmsg, code: error_1.MONGODB_ERROR_CODES.WriteConcernFailed }); + } + } + toJSON() { + return this.result; + } + toString() { + return `BulkWriteResult(${this.toJSON()})`; + } + isOk() { + return this.result.ok === 1; + } +} +exports.BulkWriteResult = BulkWriteResult; +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +class WriteConcernError { + constructor(error) { + this[kServerError] = error; + } + /** Write concern error code. */ + get code() { + return this[kServerError].code; + } + /** Write concern error message. */ + get errmsg() { + return this[kServerError].errmsg; + } + /** Write concern error info. */ + get errInfo() { + return this[kServerError].errInfo; + } + /** @deprecated The `err` prop that contained a MongoServerError has been deprecated. */ + get err() { + return this[kServerError]; + } + toJSON() { + return this[kServerError]; + } + toString() { + return `WriteConcernError(${this.errmsg})`; + } +} +exports.WriteConcernError = WriteConcernError; +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +class WriteError { + constructor(err) { + this.err = err; + } + /** WriteError code. */ + get code() { + return this.err.code; + } + /** WriteError original bulk operation index. */ + get index() { + return this.err.index; + } + /** WriteError message. */ + get errmsg() { + return this.err.errmsg; + } + /** WriteError details. */ + get errInfo() { + return this.err.errInfo; + } + /** Returns the underlying operation that caused the error */ + getOperation() { + return this.err.op; + } + toJSON() { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + toString() { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} +exports.WriteError = WriteError; +/** Merges results into shared data structure */ +function mergeBatchResults(batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if (err) { + result = err; + } + else if (result && result.result) { + result = result.result; + } + if (result == null) { + return; + } + // Do we have a top level error stop processing and return + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + errInfo: result.errInfo, + op: batch.operations[0] + }; + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } + else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + // Deal with opTime if available + if (result.opTime || result.lastOp) { + const opTime = result.lastOp || result.opTime; + let lastOpTS = null; + let lastOpT = null; + // We have a time stamp + if (opTime && opTime._bsontype === 'Timestamp') { + if (bulkResult.opTime == null) { + bulkResult.opTime = opTime; + } + else if (opTime.greaterThan(bulkResult.opTime)) { + bulkResult.opTime = opTime; + } + } + else { + // Existing TS + if (bulkResult.opTime) { + lastOpTS = + typeof bulkResult.opTime.ts === 'number' + ? bson_1.Long.fromNumber(bulkResult.opTime.ts) + : bulkResult.opTime.ts; + lastOpT = + typeof bulkResult.opTime.t === 'number' + ? bson_1.Long.fromNumber(bulkResult.opTime.t) + : bulkResult.opTime.t; + } + // Current OpTime TS + const opTimeTS = typeof opTime.ts === 'number' ? bson_1.Long.fromNumber(opTime.ts) : opTime.ts; + const opTimeT = typeof opTime.t === 'number' ? bson_1.Long.fromNumber(opTime.t) : opTime.t; + // Compare the opTime's + if (bulkResult.opTime == null) { + bulkResult.opTime = opTime; + } + else if (opTimeTS.greaterThan(lastOpTS)) { + bulkResult.opTime = opTime; + } + else if (opTimeTS.equals(lastOpTS)) { + if (opTimeT.greaterThan(lastOpT)) { + bulkResult.opTime = opTime; + } + } + } + } + // If we have an insert Batch type + if (isInsertBatch(batch) && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + // If we have an insert Batch type + if (isDeleteBatch(batch) && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + let nUpserted = 0; + // We have an array of upserted values, we need to rewrite the indexes + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + for (let i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex, + _id: result.upserted[i]._id + }); + } + } + else if (result.upserted) { + nUpserted = 1; + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + // If we have an update Batch type + if (isUpdateBatch(batch) && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + if (typeof nModified === 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } + else { + bulkResult.nModified = 0; + } + } + if (Array.isArray(result.writeErrors)) { + for (let i = 0; i < result.writeErrors.length; i++) { + const writeError = { + index: batch.originalIndexes[result.writeErrors[i].index], + code: result.writeErrors[i].code, + errmsg: result.writeErrors[i].errmsg, + errInfo: result.writeErrors[i].errInfo, + op: batch.operations[result.writeErrors[i].index] + }; + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} +function executeCommands(bulkOperation, options, callback) { + if (bulkOperation.s.batches.length === 0) { + return callback(undefined, new BulkWriteResult(bulkOperation.s.bulkResult)); + } + const batch = bulkOperation.s.batches.shift(); + function resultHandler(err, result) { + // Error is a driver related error not a bulk op error, return early + if (err && 'message' in err && !(err instanceof error_1.MongoWriteConcernError)) { + return callback(new MongoBulkWriteError(err, new BulkWriteResult(bulkOperation.s.bulkResult))); + } + if (err instanceof error_1.MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); + } + // Merge the results together + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + if (mergeResult != null) { + return callback(undefined, writeResult); + } + if (bulkOperation.handleWriteError(callback, writeResult)) + return; + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + const finalOptions = utils_1.resolveOptions(bulkOperation, { + ...options, + ordered: bulkOperation.isOrdered + }); + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + // Set an operationIf if provided + if (bulkOperation.operationId) { + resultHandler.operationId = bulkOperation.operationId; + } + // Is the bypassDocumentValidation options specific + if (bulkOperation.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + // Is the checkKeys option disabled + if (bulkOperation.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + if (finalOptions.retryWrites) { + if (isUpdateBatch(batch)) { + finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some(op => op.multi); + } + if (isDeleteBatch(batch)) { + finalOptions.retryWrites = + finalOptions.retryWrites && !batch.operations.some(op => op.limit === 0); + } + } + try { + if (isInsertBatch(batch)) { + execute_operation_1.executeOperation(bulkOperation.s.topology, new insert_1.InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler); + } + else if (isUpdateBatch(batch)) { + execute_operation_1.executeOperation(bulkOperation.s.topology, new update_1.UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler); + } + else if (isDeleteBatch(batch)) { + execute_operation_1.executeOperation(bulkOperation.s.topology, new delete_1.DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler); + } + } + catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, undefined); + callback(); + } +} +function handleMongoWriteConcernError(batch, bulkResult, err, callback) { + var _a, _b; + mergeBatchResults(batch, bulkResult, undefined, err.result); + callback(new MongoBulkWriteError({ + message: (_a = err.result) === null || _a === void 0 ? void 0 : _a.writeConcernError.errmsg, + code: (_b = err.result) === null || _b === void 0 ? void 0 : _b.writeConcernError.result + }, new BulkWriteResult(bulkResult))); +} +/** + * An error indicating an unsuccessful Bulk Write + * @public + * @category Error + */ +class MongoBulkWriteError extends error_1.MongoServerError { + /** Creates a new MongoBulkWriteError */ + constructor(error, result) { + var _a; + super(error); + this.writeErrors = []; + if (error instanceof WriteConcernError) + this.err = error; + else if (!(error instanceof Error)) { + this.message = error.message; + this.code = error.code; + this.writeErrors = (_a = error.writeErrors) !== null && _a !== void 0 ? _a : []; + } + this.result = result; + Object.assign(this, error); + } + get name() { + return 'MongoBulkWriteError'; + } + /** Number of documents inserted. */ + get insertedCount() { + return this.result.insertedCount; + } + /** Number of documents matched for update. */ + get matchedCount() { + return this.result.matchedCount; + } + /** Number of documents modified. */ + get modifiedCount() { + return this.result.modifiedCount; + } + /** Number of documents deleted. */ + get deletedCount() { + return this.result.deletedCount; + } + /** Number of documents upserted. */ + get upsertedCount() { + return this.result.upsertedCount; + } + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds() { + return this.result.insertedIds; + } + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds() { + return this.result.upsertedIds; + } +} +exports.MongoBulkWriteError = MongoBulkWriteError; +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +class FindOperators { + /** + * Creates a new FindOperators object. + * @internal + */ + constructor(bulkOperation) { + this.bulkOperation = bulkOperation; + } + /** Add a multiple update operation to the bulk operation */ + update(updateDocument) { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, update_1.makeUpdateStatement(currentOp.selector, updateDocument, { + ...currentOp, + multi: true + })); + } + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument) { + if (!utils_1.hasAtomicOperators(updateDocument)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, update_1.makeUpdateStatement(currentOp.selector, updateDocument, { ...currentOp, multi: false })); + } + /** Add a replace one operation to the bulk operation */ + replaceOne(replacement) { + if (utils_1.hasAtomicOperators(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, update_1.makeUpdateStatement(currentOp.selector, replacement, { ...currentOp, multi: false })); + } + /** Add a delete one operation to the bulk operation */ + deleteOne() { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, delete_1.makeDeleteStatement(currentOp.selector, { ...currentOp, limit: 1 })); + } + /** Add a delete many operation to the bulk operation */ + delete() { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, delete_1.makeDeleteStatement(currentOp.selector, { ...currentOp, limit: 0 })); + } + /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ + upsert() { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.upsert = true; + return this; + } + /** Specifies the collation for the query condition. */ + collation(collation) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.collation = collation; + return this; + } + /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ + arrayFilters(arrayFilters) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.arrayFilters = arrayFilters; + return this; + } +} +exports.FindOperators = FindOperators; +/** @public */ +class BulkOperationBase { + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance + * @internal + */ + constructor(collection, options, isOrdered) { + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + const topology = utils_1.getTopology(collection); + options = options == null ? {} : options; + // TODO Bring from driver information in isMaster + // Get the namespace for the write operations + const namespace = collection.s.namespace; + // Used to mark operation as executed + const executed = false; + // Current item + const currentOp = undefined; + // Set max byte size + const isMaster = topology.lastIsMaster(); + // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents + // over 2mb are still allowed + const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); + const maxBsonObjectSize = isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; + const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; + const maxWriteBatchSize = isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; + // Calculates the largest possible size of an Array key, represented as a BSON string + // element. This calculation: + // 1 byte for BSON type + // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) + // + 1 bytes for null terminator + const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; + // Final options for retryable writes + let finalOptions = Object.assign({}, options); + finalOptions = utils_1.applyRetryableWrites(finalOptions, collection.s.db); + // Final results + const bulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + // Internal state + this.s = { + // Final result + bulkResult, + // Current batch state + currentBatch: undefined, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: undefined, + currentUpdateBatch: undefined, + currentRemoveBatch: undefined, + batches: [], + // Write concern + writeConcern: write_concern_1.WriteConcern.fromOptions(options), + // Max batch size options + maxBsonObjectSize, + maxBatchSizeBytes, + maxWriteBatchSize, + maxKeySize, + // Namespace + namespace, + // Topology + topology, + // Options + options: finalOptions, + // BSON options + bsonOptions: bson_1.resolveBSONOptions(options), + // Current operation + currentOp, + // Executed + executed, + // Collection + collection, + // Fundamental error + err: undefined, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : false + }; + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + /** + * Add a single insert document to the bulk operation + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + * ``` + */ + insert(document) { + if (document._id == null && !shouldForceServerObjectId(this)) { + document._id = new bson_1.ObjectId(); + } + return this.addToOperationsList(exports.BatchType.INSERT, document); + } + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }}); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + * ``` + */ + find(selector) { + if (!selector) { + throw new error_1.MongoInvalidArgumentError('Bulk find operation must specify a selector'); + } + // Save a current selector + this.s.currentOp = { + selector: selector + }; + return new FindOperators(this); + } + /** Specifies a raw operation to perform in the bulk write. */ + raw(op) { + if ('insertOne' in op) { + const forceServerObjectId = shouldForceServerObjectId(this); + if (op.insertOne && op.insertOne.document == null) { + // NOTE: provided for legacy support, but this is a malformed operation + if (forceServerObjectId !== true && op.insertOne._id == null) { + op.insertOne._id = new bson_1.ObjectId(); + } + return this.addToOperationsList(exports.BatchType.INSERT, op.insertOne); + } + if (forceServerObjectId !== true && op.insertOne.document._id == null) { + op.insertOne.document._id = new bson_1.ObjectId(); + } + return this.addToOperationsList(exports.BatchType.INSERT, op.insertOne.document); + } + if ('replaceOne' in op || 'updateOne' in op || 'updateMany' in op) { + if ('replaceOne' in op) { + if ('q' in op.replaceOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = update_1.makeUpdateStatement(op.replaceOne.filter, op.replaceOne.replacement, { ...op.replaceOne, multi: false }); + if (utils_1.hasAtomicOperators(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + if ('updateOne' in op) { + if ('q' in op.updateOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = update_1.makeUpdateStatement(op.updateOne.filter, op.updateOne.update, { + ...op.updateOne, + multi: false + }); + if (!utils_1.hasAtomicOperators(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + if ('updateMany' in op) { + if ('q' in op.updateMany) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = update_1.makeUpdateStatement(op.updateMany.filter, op.updateMany.update, { + ...op.updateMany, + multi: true + }); + if (!utils_1.hasAtomicOperators(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + } + if ('deleteOne' in op) { + if ('q' in op.deleteOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList(exports.BatchType.DELETE, delete_1.makeDeleteStatement(op.deleteOne.filter, { ...op.deleteOne, limit: 1 })); + } + if ('deleteMany' in op) { + if ('q' in op.deleteMany) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList(exports.BatchType.DELETE, delete_1.makeDeleteStatement(op.deleteMany.filter, { ...op.deleteMany, limit: 0 })); + } + // otherwise an unknown operation was provided + throw new error_1.MongoInvalidArgumentError('bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany'); + } + get bsonOptions() { + return this.s.bsonOptions; + } + get writeConcern() { + return this.s.writeConcern; + } + get batches() { + const batches = [...this.s.batches]; + if (this.isOrdered) { + if (this.s.currentBatch) + batches.push(this.s.currentBatch); + } + else { + if (this.s.currentInsertBatch) + batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) + batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) + batches.push(this.s.currentRemoveBatch); + } + return batches; + } + /** An internal helper method. Do not invoke directly. Will be going away in the future */ + execute(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + if (this.s.executed) { + return handleEarlyError(new error_1.MongoBatchReExecutionError(), callback); + } + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (writeConcern) { + this.s.writeConcern = writeConcern; + } + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) + this.s.batches.push(this.s.currentBatch); + } + else { + if (this.s.currentInsertBatch) + this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) + this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) + this.s.batches.push(this.s.currentRemoveBatch); + } + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + const emptyBatchError = new error_1.MongoInvalidArgumentError('Invalid BulkOperation, Batch cannot be empty'); + return handleEarlyError(emptyBatchError, callback); + } + this.s.executed = true; + const finalOptions = { ...this.s.options, ...options }; + return utils_1.executeLegacyOperation(this.s.topology, executeCommands, [this, finalOptions, callback]); + } + /** + * Handles the write error before executing commands + * @internal + */ + handleWriteError(callback, writeResult) { + if (this.s.bulkResult.writeErrors.length > 0) { + const msg = this.s.bulkResult.writeErrors[0].errmsg + ? this.s.bulkResult.writeErrors[0].errmsg + : 'write operation failed'; + callback(new MongoBulkWriteError({ + message: msg, + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }, writeResult)); + return true; + } + const writeConcernError = writeResult.getWriteConcernError(); + if (writeConcernError) { + callback(new MongoBulkWriteError(writeConcernError, writeResult)); + return true; + } + } +} +exports.BulkOperationBase = BulkOperationBase; +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get() { + return this.s.currentIndex; + } +}); +/** helper function to assist with promiseOrCallback behavior */ +function handleEarlyError(err, callback) { + const Promise = promise_provider_1.PromiseProvider.get(); + if (typeof callback === 'function') { + callback(err); + return; + } + return Promise.reject(err); +} +function shouldForceServerObjectId(bulkOperation) { + var _a, _b; + if (typeof bulkOperation.s.options.forceServerObjectId === 'boolean') { + return bulkOperation.s.options.forceServerObjectId; + } + if (typeof ((_a = bulkOperation.s.collection.s.db.options) === null || _a === void 0 ? void 0 : _a.forceServerObjectId) === 'boolean') { + return (_b = bulkOperation.s.collection.s.db.options) === null || _b === void 0 ? void 0 : _b.forceServerObjectId; + } + return false; +} +function isInsertBatch(batch) { + return batch.batchType === exports.BatchType.INSERT; +} +function isUpdateBatch(batch) { + return batch.batchType === exports.BatchType.UPDATE; +} +function isDeleteBatch(batch) { + return batch.batchType === exports.BatchType.DELETE; +} +function buildCurrentOp(bulkOp) { + let { currentOp } = bulkOp.s; + bulkOp.s.currentOp = undefined; + if (!currentOp) + currentOp = {}; + return currentOp; +} +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/bulk/common.js.map b/node_modules/mongodb/lib/bulk/common.js.map new file mode 100644 index 0000000..3b9a767 --- /dev/null +++ b/node_modules/mongodb/lib/bulk/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/bulk/common.ts"],"names":[],"mappings":";;;AAAA,0DAAsD;AACtD,kCAA6F;AAC7F,oCAOkB;AAClB,oCAQkB;AAClB,uEAAmE;AACnE,iDAAuD;AACvD,iDAA6F;AAC7F,iDAA6F;AAC7F,oDAAgD;AAOhD,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAE3C,cAAc;AACD,QAAA,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC;IACrC,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,CAAC;CACD,CAAC,CAAC;AAqGZ;;;;;GAKG;AACH,MAAa,KAAK;IAShB,YAAY,SAAoB,EAAE,iBAAyB;QACzD,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC;QACtB,IAAI,CAAC,eAAe,GAAG,EAAE,CAAC;QAC1B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC;QACd,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC;IACrB,CAAC;CACF;AAlBD,sBAkBC;AAED;;;GAGG;AACH,MAAa,eAAe;IAG1B;;;O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QAAQ,CAAC,GAAG,CAAC,CAAC;QACd,OAAO;KACR;IAED,OAAO,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,yBAAyB,CAAC,aAAgC;;IACjE,IAAI,OAAO,aAAa,CAAC,CAAC,CAAC,OAAO,CAAC,mBAAmB,KAAK,SAAS,EAAE;QACpE,OAAO,aAAa,CAAC,CAAC,CAAC,OAAO,CAAC,mBAAmB,CAAC;KACpD;IAED,IAAI,OAAO,CAAA,MAAA,aAAa,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,0CAAE,mBAAmB,CAAA,KAAK,SAAS,EAAE;QACrF,OAAO,MAAA,aAAa,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,0CAAE,mBAAmB,CAAC;KACrE;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,aAAa,CAAC,KAAY;IACjC,OAAO,KAAK,CAAC,SAAS,KAAK,iBAAS,CAAC,MAAM,CAAC;AAC9C,CAAC;AAED,SAAS,aAAa,CAAC,KAAY;IACjC,OAAO,KAAK,CAAC,SAAS,KAAK,iBAAS,CAAC,MAAM,CAAC;AAC9C,CAAC;AAED,SAAS,aAAa,CAAC,KAAY;IACjC,OAAO,KAAK,CAAC,SAAS,KAAK,iBAAS,CAAC,MAAM,CAAC;AAC9C,CAAC;AAED,SAAS,cAAc,CAAC,MAAyB;IAC/C,IAAI,EAAE,SAAS,EAAE,GAAG,MAAM,CAAC,CAAC,CAAC;IAC7B,MAAM,CAAC,CAAC,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,IAAI,CAAC,SAAS;QAAE,SAAS,GAAG,EAAE,CAAC;IAC/B,OAAO,SAAS,CAAC;AACnB,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/bulk/ordered.js b/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 0000000..bf4b3f3 --- /dev/null +++ b/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,66 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OrderedBulkOperation = void 0; +const BSON = require("../bson"); +const common_1 = require("./common"); +const error_1 = require("../error"); +/** @public */ +class OrderedBulkOperation extends common_1.BulkOperationBase { + constructor(collection, options) { + super(collection, options, true); + } + addToOperationsList(batchType, document) { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) + // TODO(NODE-3483): Change this to MongoBSONError + throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + const maxKeySize = this.s.maxKeySize; + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatchSize > 0 && + this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + // Create a new batch + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + // Reset the current size trackers + this.s.currentBatchSize = 0; + this.s.currentBatchSizeBytes = 0; + } + if (batchType === common_1.BatchType.INSERT) { + this.s.bulkResult.insertedIds.push({ + index: this.s.currentIndex, + _id: document._id + }); + } + // We have an array of documents + if (Array.isArray(document)) { + throw new error_1.MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentBatch.operations.push(document); + this.s.currentBatchSize += 1; + this.s.currentBatchSizeBytes += maxKeySize + bsonSize; + this.s.currentIndex += 1; + return this; + } +} +exports.OrderedBulkOperation = OrderedBulkOperation; +//# sourceMappingURL=ordered.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/bulk/ordered.js.map b/node_modules/mongodb/lib/bulk/ordered.js.map new file mode 100644 index 0000000..2ad7c9d --- /dev/null +++ b/node_modules/mongodb/lib/bulk/ordered.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ordered.js","sourceRoot":"","sources":["../../src/bulk/ordered.ts"],"names":[],"mappings":";;;AAAA,gCAAgC;AAChC,qCAAiF;AAKjF,oCAAqD;AAErD,cAAc;AACd,MAAa,oBAAqB,SAAQ,0BAAiB;IACzD,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,mBAAmB,CACjB,SAAoB,EACpB,QAAsD;QAEtD,mBAAmB;QACnB,MAAM,QAAQ,GAAG,IAAI,CAAC,mBAAmB,CAAC,QAAQ,EAAE;YAClD,SAAS,EAAE,KAAK;YAChB,oEAAoE;YACpE,wEAAwE;YACxE,eAAe,EAAE,KAAK;SAChB,CAAC,CAAC;QAEV,0DAA0D;QAC1D,IAAI,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,iBAAiB;YACtC,iDAAiD;YACjD,MAAM,IAAI,iCAAyB,CACjC,4CAA4C,IAAI,CAAC,CAAC,CAAC,iBAAiB,EAAE,CACvE,CAAC;QAEJ,2DAA2D;QAC3D,IAAI,IAAI,CAAC,CAAC,CAAC,YAAY,IAAI,IAAI,EAAE;YAC/B,IAAI,CAAC,CAAC,CAAC,YAAY,GAAG,IAAI,cAAK,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;SACjE;QAED,MAAM,UAAU,GAAG,IAAI,CAAC,CAAC,CAAC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CAAC,YAAY,CAAC,CAAC;QAC9D,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC9C,IAAI,CAAC,CAAC,CAAC,gBAAgB,IAAI,CAAC,CAAC;QAC7B,IAAI,CAAC,CAAC,CAAC,qBAAqB,IAAI,UAAU,GAAG,QAAQ,CAAC;QACtD,IAAI,CAAC,CAAC,CAAC,YAAY,IAAI,CAAC,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAxED,oDAwEC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/bulk/unordered.js b/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 0000000..e65657c --- /dev/null +++ b/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,91 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnorderedBulkOperation = void 0; +const BSON = require("../bson"); +const common_1 = require("./common"); +const error_1 = require("../error"); +/** @public */ +class UnorderedBulkOperation extends common_1.BulkOperationBase { + constructor(collection, options) { + super(collection, options, false); + } + handleWriteError(callback, writeResult) { + if (this.s.batches.length) { + return false; + } + return super.handleWriteError(callback, writeResult); + } + addToOperationsList(batchType, document) { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) { + // TODO(NODE-3483): Change this to MongoBSONError + throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); + } + // Holds the current batch + this.s.currentBatch = undefined; + // Get the right type of batch + if (batchType === common_1.BatchType.INSERT) { + this.s.currentBatch = this.s.currentInsertBatch; + } + else if (batchType === common_1.BatchType.UPDATE) { + this.s.currentBatch = this.s.currentUpdateBatch; + } + else if (batchType === common_1.BatchType.DELETE) { + this.s.currentBatch = this.s.currentRemoveBatch; + } + const maxKeySize = this.s.maxKeySize; + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatch.size + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatch.size > 0 && + this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + // Create a new batch + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + // We have an array of documents + if (Array.isArray(document)) { + throw new error_1.MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + this.s.currentBatch.operations.push(document); + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentIndex = this.s.currentIndex + 1; + // Save back the current Batch to the right type + if (batchType === common_1.BatchType.INSERT) { + this.s.currentInsertBatch = this.s.currentBatch; + this.s.bulkResult.insertedIds.push({ + index: this.s.bulkResult.insertedIds.length, + _id: document._id + }); + } + else if (batchType === common_1.BatchType.UPDATE) { + this.s.currentUpdateBatch = this.s.currentBatch; + } + else if (batchType === common_1.BatchType.DELETE) { + this.s.currentRemoveBatch = this.s.currentBatch; + } + // Update current batch size + this.s.currentBatch.size += 1; + this.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + return this; + } +} +exports.UnorderedBulkOperation = UnorderedBulkOperation; +//# sourceMappingURL=unordered.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/bulk/unordered.js.map b/node_modules/mongodb/lib/bulk/unordered.js.map new file mode 100644 index 0000000..7e970f7 --- /dev/null +++ b/node_modules/mongodb/lib/bulk/unordered.js.map @@ -0,0 +1 @@ +{"version":3,"file":"unordered.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UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC9C,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;QAC9D,IAAI,CAAC,CAAC,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY,GAAG,CAAC,CAAC;QAE9C,gDAAgD;QAChD,IAAI,SAAS,KAAK,kBAAS,CAAC,MAAM,EAAE;YAClC,IAAI,CAAC,CAAC,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC;YAChD,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC;gBACjC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,WAAW,CAAC,MAAM;gBAC3C,GAAG,EAAG,QAAqB,CAAC,GAAG;aAChC,CAAC,CAAC;SACJ;aAAM,IAAI,SAAS,KAAK,kBAAS,CAAC,MAAM,EAAE;YACzC,IAAI,CAAC,CAAC,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC;SACjD;aAAM,IAAI,SAAS,KAAK,kBAAS,CAAC,MAAM,EAAE;YACzC,IAAI,CAAC,CAAC,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC;SACjD;QAED,4BAA4B;QAC5B,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,IAAI,CAAC,CAAC;QAC9B,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,SAAS,IAAI,UAAU,GAAG,QAAQ,CAAC;QAEvD,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAlGD,wDAkGC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/change_stream.js b/node_modules/mongodb/lib/change_stream.js new file mode 100644 index 0000000..1a84663 --- /dev/null +++ b/node_modules/mongodb/lib/change_stream.js @@ -0,0 +1,495 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChangeStreamCursor = exports.ChangeStream = void 0; +const Denque = require("denque"); +const error_1 = require("./error"); +const aggregate_1 = require("./operations/aggregate"); +const utils_1 = require("./utils"); +const mongo_client_1 = require("./mongo_client"); +const db_1 = require("./db"); +const collection_1 = require("./collection"); +const abstract_cursor_1 = require("./cursor/abstract_cursor"); +const execute_operation_1 = require("./operations/execute_operation"); +const mongo_types_1 = require("./mongo_types"); +/** @internal */ +const kResumeQueue = Symbol('resumeQueue'); +/** @internal */ +const kCursorStream = Symbol('cursorStream'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kMode = Symbol('mode'); +const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument']; +const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat(CHANGE_STREAM_OPTIONS); +const CHANGE_DOMAIN_TYPES = { + COLLECTION: Symbol('Collection'), + DATABASE: Symbol('Database'), + CLUSTER: Symbol('Cluster') +}; +const NO_RESUME_TOKEN_ERROR = 'A change stream document has been received that lacks a resume token (_id).'; +const NO_CURSOR_ERROR = 'ChangeStream has no cursor'; +const CHANGESTREAM_CLOSED_ERROR = 'ChangeStream is closed'; +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @public + */ +class ChangeStream extends mongo_types_1.TypedEventEmitter { + /** + * @internal + * + * @param parent - The parent object that created this change stream + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + */ + constructor(parent, pipeline = [], options = {}) { + super(); + this.pipeline = pipeline; + this.options = options; + if (parent instanceof collection_1.Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + } + else if (parent instanceof db_1.Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + } + else if (parent instanceof mongo_client_1.MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + } + else { + throw new error_1.MongoChangeStreamError('Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient'); + } + this.parent = parent; + this.namespace = parent.s.namespace; + if (!this.options.readPreference && parent.readPreference) { + this.options.readPreference = parent.readPreference; + } + this[kResumeQueue] = new Denque(); + // Create contained Change Stream cursor + this.cursor = createChangeStreamCursor(this, options); + this[kClosed] = false; + this[kMode] = false; + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + streamEvents(this, this.cursor); + } + }); + this.on('removeListener', eventName => { + var _a; + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + (_a = this[kCursorStream]) === null || _a === void 0 ? void 0 : _a.removeAllListeners('data'); + } + }); + } + /** @internal */ + get cursorStream() { + return this[kCursorStream]; + } + /** The cached resume token that is used to resume after the most recently returned change. */ + get resumeToken() { + var _a; + return (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.resumeToken; + } + /** Check if there is any document still available in the Change Stream */ + hasNext(callback) { + setIsIterator(this); + return utils_1.maybePromise(callback, cb => { + getCursor(this, (err, cursor) => { + if (err || !cursor) + return cb(err); // failed to resume, raise an error + cursor.hasNext(cb); + }); + }); + } + next(callback) { + setIsIterator(this); + return utils_1.maybePromise(callback, cb => { + getCursor(this, (err, cursor) => { + if (err || !cursor) + return cb(err); // failed to resume, raise an error + cursor.next((error, change) => { + if (error) { + this[kResumeQueue].push(() => this.next(cb)); + processError(this, error, cb); + return; + } + processNewChange(this, change, cb); + }); + }); + }); + } + /** Is the cursor closed */ + get closed() { + var _a, _b; + return this[kClosed] || ((_b = (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.closed) !== null && _b !== void 0 ? _b : false); + } + /** Close the Change Stream */ + close(callback) { + this[kClosed] = true; + return utils_1.maybePromise(callback, cb => { + if (!this.cursor) { + return cb(); + } + const cursor = this.cursor; + return cursor.close(err => { + endStream(this); + this.cursor = undefined; + return cb(err); + }); + }); + } + /** + * Return a modified Readable stream including a possible transform method. + * @throws MongoDriverError if this.cursor is undefined + */ + stream(options) { + this.streamOptions = options; + if (!this.cursor) + throw new error_1.MongoChangeStreamError(NO_CURSOR_ERROR); + return this.cursor.stream(options); + } + tryNext(callback) { + setIsIterator(this); + return utils_1.maybePromise(callback, cb => { + getCursor(this, (err, cursor) => { + if (err || !cursor) + return cb(err); // failed to resume, raise an error + return cursor.tryNext(cb); + }); + }); + } +} +exports.ChangeStream = ChangeStream; +/** @event */ +ChangeStream.RESPONSE = 'response'; +/** @event */ +ChangeStream.MORE = 'more'; +/** @event */ +ChangeStream.INIT = 'init'; +/** @event */ +ChangeStream.CLOSE = 'close'; +/** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * @event + */ +ChangeStream.CHANGE = 'change'; +/** @event */ +ChangeStream.END = 'end'; +/** @event */ +ChangeStream.ERROR = 'error'; +/** + * Emitted each time the change stream stores a new resume token. + * @event + */ +ChangeStream.RESUME_TOKEN_CHANGED = 'resumeTokenChanged'; +/** @internal */ +class ChangeStreamCursor extends abstract_cursor_1.AbstractCursor { + constructor(topology, namespace, pipeline = [], options = {}) { + super(topology, namespace, options); + this.pipeline = pipeline; + this.options = options; + this._resumeToken = null; + this.startAtOperationTime = options.startAtOperationTime; + if (options.startAfter) { + this.resumeToken = options.startAfter; + } + else if (options.resumeAfter) { + this.resumeToken = options.resumeAfter; + } + } + set resumeToken(token) { + this._resumeToken = token; + this.emit(ChangeStream.RESUME_TOKEN_CHANGED, token); + } + get resumeToken() { + return this._resumeToken; + } + get resumeOptions() { + const result = {}; + for (const optionName of CURSOR_OPTIONS) { + if (Reflect.has(this.options, optionName)) { + Reflect.set(result, optionName, Reflect.get(this.options, optionName)); + } + } + if (this.resumeToken || this.startAtOperationTime) { + ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => Reflect.deleteProperty(result, key)); + if (this.resumeToken) { + const resumeKey = this.options.startAfter && !this.hasReceived ? 'startAfter' : 'resumeAfter'; + Reflect.set(result, resumeKey, this.resumeToken); + } + else if (this.startAtOperationTime && utils_1.maxWireVersion(this.server) >= 7) { + result.startAtOperationTime = this.startAtOperationTime; + } + } + return result; + } + cacheResumeToken(resumeToken) { + if (this.bufferedCount() === 0 && this.postBatchResumeToken) { + this.resumeToken = this.postBatchResumeToken; + } + else { + this.resumeToken = resumeToken; + } + this.hasReceived = true; + } + _processBatch(batchName, response) { + const cursor = (response === null || response === void 0 ? void 0 : response.cursor) || {}; + if (cursor.postBatchResumeToken) { + this.postBatchResumeToken = cursor.postBatchResumeToken; + if (cursor[batchName].length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + } + clone() { + return new ChangeStreamCursor(this.topology, this.namespace, this.pipeline, { + ...this.cursorOptions + }); + } + _initialize(session, callback) { + const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this.pipeline, { + ...this.cursorOptions, + ...this.options, + session + }); + execute_operation_1.executeOperation(this.topology, aggregateOperation, (err, response) => { + if (err || response == null) { + return callback(err); + } + const server = aggregateOperation.server; + if (this.startAtOperationTime == null && + this.resumeAfter == null && + this.startAfter == null && + utils_1.maxWireVersion(server) >= 7) { + this.startAtOperationTime = response.operationTime; + } + this._processBatch('firstBatch', response); + this.emit(ChangeStream.INIT, response); + this.emit(ChangeStream.RESPONSE); + // TODO: NODE-2882 + callback(undefined, { server, session, response }); + }); + } + _getMore(batchSize, callback) { + super._getMore(batchSize, (err, response) => { + if (err) { + return callback(err); + } + this._processBatch('nextBatch', response); + this.emit(ChangeStream.MORE, response); + this.emit(ChangeStream.RESPONSE); + callback(err, response); + }); + } +} +exports.ChangeStreamCursor = ChangeStreamCursor; +const CHANGE_STREAM_EVENTS = [ + ChangeStream.RESUME_TOKEN_CHANGED, + ChangeStream.END, + ChangeStream.CLOSE +]; +function setIsEmitter(changeStream) { + if (changeStream[kMode] === 'iterator') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new error_1.MongoAPIError('ChangeStream cannot be used as an EventEmitter after being used as an iterator'); + } + changeStream[kMode] = 'emitter'; +} +function setIsIterator(changeStream) { + if (changeStream[kMode] === 'emitter') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new error_1.MongoAPIError('ChangeStream cannot be used as an iterator after being used as an EventEmitter'); + } + changeStream[kMode] = 'iterator'; +} +/** + * Create a new change stream cursor based on self's configuration + * @internal + */ +function createChangeStreamCursor(changeStream, options) { + const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' }; + applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS); + if (changeStream.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(changeStream.pipeline); + const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); + const changeStreamCursor = new ChangeStreamCursor(utils_1.getTopology(changeStream.parent), changeStream.namespace, pipeline, cursorOptions); + for (const event of CHANGE_STREAM_EVENTS) { + changeStreamCursor.on(event, e => changeStream.emit(event, e)); + } + if (changeStream.listenerCount(ChangeStream.CHANGE) > 0) { + streamEvents(changeStream, changeStreamCursor); + } + return changeStreamCursor; +} +function applyKnownOptions(target, source, optionNames) { + optionNames.forEach(name => { + if (source[name]) { + target[name] = source[name]; + } + }); + return target; +} +// This method performs a basic server selection loop, satisfying the requirements of +// ChangeStream resumability until the new SDAM layer can be used. +const SELECTION_TIMEOUT = 30000; +function waitForTopologyConnected(topology, options, callback) { + setTimeout(() => { + if (options && options.start == null) { + options.start = utils_1.now(); + } + const start = options.start || utils_1.now(); + const timeout = options.timeout || SELECTION_TIMEOUT; + if (topology.isConnected()) { + return callback(); + } + if (utils_1.calculateDurationInMs(start) > timeout) { + // TODO(NODE-3497): Replace with MongoNetworkTimeoutError + return callback(new error_1.MongoRuntimeError('Timed out waiting for connection')); + } + waitForTopologyConnected(topology, options, callback); + }, 500); // this is an arbitrary wait time to allow SDAM to transition +} +function closeWithError(changeStream, error, callback) { + if (!callback) { + changeStream.emit(ChangeStream.ERROR, error); + } + changeStream.close(() => callback && callback(error)); +} +function streamEvents(changeStream, cursor) { + setIsEmitter(changeStream); + const stream = changeStream[kCursorStream] || cursor.stream(); + changeStream[kCursorStream] = stream; + stream.on('data', change => processNewChange(changeStream, change)); + stream.on('error', error => processError(changeStream, error)); +} +function endStream(changeStream) { + const cursorStream = changeStream[kCursorStream]; + if (cursorStream) { + ['data', 'close', 'end', 'error'].forEach(event => cursorStream.removeAllListeners(event)); + cursorStream.destroy(); + } + changeStream[kCursorStream] = undefined; +} +function processNewChange(changeStream, change, callback) { + var _a; + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + if (callback) + callback(new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + return; + } + // a null change means the cursor has been notified, implicitly closing the change stream + if (change == null) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + return closeWithError(changeStream, new error_1.MongoRuntimeError(CHANGESTREAM_CLOSED_ERROR), callback); + } + if (change && !change._id) { + return closeWithError(changeStream, new error_1.MongoChangeStreamError(NO_RESUME_TOKEN_ERROR), callback); + } + // cache the resume token + (_a = changeStream.cursor) === null || _a === void 0 ? void 0 : _a.cacheResumeToken(change._id); + // wipe the startAtOperationTime if there was one so that there won't be a conflict + // between resumeToken and startAtOperationTime if we need to reconnect the cursor + changeStream.options.startAtOperationTime = undefined; + // Return the change + if (!callback) + return changeStream.emit(ChangeStream.CHANGE, change); + return callback(undefined, change); +} +function processError(changeStream, error, callback) { + const cursor = changeStream.cursor; + // If the change stream has been closed explicitly, do not process error. + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + if (callback) + callback(new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + return; + } + // if the resume succeeds, continue with the new cursor + function resumeWithCursor(newCursor) { + changeStream.cursor = newCursor; + processResumeQueue(changeStream); + } + // otherwise, raise an error and close the change stream + function unresumableError(err) { + if (!callback) { + changeStream.emit(ChangeStream.ERROR, err); + } + changeStream.close(() => processResumeQueue(changeStream, err)); + } + if (cursor && error_1.isResumableError(error, utils_1.maxWireVersion(cursor.server))) { + changeStream.cursor = undefined; + // stop listening to all events from old cursor + endStream(changeStream); + // close internal cursor, ignore errors + cursor.close(); + const topology = utils_1.getTopology(changeStream.parent); + waitForTopologyConnected(topology, { readPreference: cursor.readPreference }, err => { + // if the topology can't reconnect, close the stream + if (err) + return unresumableError(err); + // create a new cursor, preserving the old cursor's options + const newCursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); + // attempt to continue in emitter mode + if (!callback) + return resumeWithCursor(newCursor); + // attempt to continue in iterator mode + newCursor.hasNext(err => { + // if there's an error immediately after resuming, close the stream + if (err) + return unresumableError(err); + resumeWithCursor(newCursor); + }); + }); + return; + } + // if initial error wasn't resumable, raise an error and close the change stream + return closeWithError(changeStream, error, callback); +} +/** + * Safely provides a cursor across resume attempts + * + * @param changeStream - the parent ChangeStream + */ +function getCursor(changeStream, callback) { + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + callback(new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + return; + } + // if a cursor exists and it is open, return it + if (changeStream.cursor) { + callback(undefined, changeStream.cursor); + return; + } + // no cursor, queue callback until topology reconnects + changeStream[kResumeQueue].push(callback); +} +/** + * Drain the resume queue when a new has become available + * + * @param changeStream - the parent ChangeStream + * @param err - error getting a new cursor + */ +function processResumeQueue(changeStream, err) { + while (changeStream[kResumeQueue].length) { + const request = changeStream[kResumeQueue].pop(); + if (!request) + break; // Should never occur but TS can't use the length check in the while condition + if (!err) { + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + request(new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + return; + } + if (!changeStream.cursor) { + request(new error_1.MongoChangeStreamError(NO_CURSOR_ERROR)); + return; + } + } + request(err, changeStream.cursor); + } +} +//# sourceMappingURL=change_stream.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/change_stream.js.map b/node_modules/mongodb/lib/change_stream.js.map new file mode 100644 index 0000000..81449be --- /dev/null +++ b/node_modules/mongodb/lib/change_stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"change_stream.js","sourceRoot":"","sources":["../src/change_stream.ts"],"names":[],"mappings":";;;AAAA,iCAAkC;AAClC,mCAOiB;AACjB,sDAA8E;AAC9E,mCAQiB;AAKjB,iDAA6C;AAC7C,6BAA0B;AAC1B,6CAA0C;AAE1C,8DAKkC;AAElC,sEAAmF;AACnF,+CAAyE;AAEzE,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC;AAC7C,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;AAE7B,MAAM,qBAAqB,GAAG,CAAC,aAAa,EAAE,YAAY,EAAE,sBAAsB,EAAE,cAAc,CAAC,CAAC;AACpG,MAAM,cAAc,GAAG,CAAC,WAAW,EAAE,gBAAgB,EAAE,WAAW,EAAE,gBAAgB,CAAC,CAAC,MAAM,CAC1F,qBAAqB,CACtB,CAAC;AAEF,MAAM,mBAAmB,GAAG;IAC1B,UAAU,EAAE,MAAM,CAAC,YAAY,CAAC;IAChC,QAAQ,EAAE,MAAM,CAAC,UAAU,CAAC;IAC5B,OAAO,EAAE,MAAM,CAAC,SAAS,CAAC;CAC3B,CAAC;AAEF,MAAM,qBAAqB,GACzB,6EAA6E,CAAC;AAChF,MAAM,eAAe,GAAG,4BAA4B,CAAC;AACrD,MAAM,yBAAyB,GAAG,wBAAwB,CAAC;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AAC,MAAM,EAAE;gBACxB,OAAO,CAAC,IAAI,8BAAsB,CAAC,eAAe,CAAC,CAAC,CAAC;gBACrD,OAAO;aACR;SACF;QACD,OAAO,CAAC,GAAG,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;KACnC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/auth_provider.js b/node_modules/mongodb/lib/cmap/auth/auth_provider.js new file mode 100644 index 0000000..b9a840e --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/auth_provider.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AuthProvider = exports.AuthContext = void 0; +const error_1 = require("../../error"); +/** Context used during authentication */ +class AuthContext { + constructor(connection, credentials, options) { + this.connection = connection; + this.credentials = credentials; + this.options = options; + } +} +exports.AuthContext = AuthContext; +class AuthProvider { + /** + * Prepare the handshake document before the initial handshake. + * + * @param handshakeDoc - The document used for the initial handshake on a connection + * @param authContext - Context for authentication flow + */ + prepare(handshakeDoc, authContext, callback) { + callback(undefined, handshakeDoc); + } + /** + * Authenticate + * + * @param context - A shared context for authentication flow + * @param callback - The callback to return the result from the authentication + */ + auth(context, callback) { + // TODO(NODE-3483): Replace this with MongoMethodOverrideError + callback(new error_1.MongoRuntimeError('`auth` method must be overridden by subclass')); + } +} +exports.AuthProvider = AuthProvider; +//# sourceMappingURL=auth_provider.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map b/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map new file mode 100644 index 0000000..6bcee0e --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth_provider.js","sourceRoot":"","sources":["../../../src/cmap/auth/auth_provider.ts"],"names":[],"mappings":";;;AAKA,uCAAgD;AAIhD,yCAAyC;AACzC,MAAa,WAAW;IAatB,YACE,UAAsB,EACtB,WAAyC,EACzC,OAA2B;QAE3B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAtBD,kCAsBC;AAED,MAAa,YAAY;IACvB;;;;;OAKG;IACH,OAAO,CACL,YAA+B,EAC/B,WAAwB,EACxB,QAAqC;QAErC,QAAQ,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;IACpC,CAAC;IAED;;;;;OAKG;IACH,IAAI,CAAC,OAAoB,EAAE,QAAkB;QAC3C,8DAA8D;QAC9D,QAAQ,CAAC,IAAI,yBAAiB,CAAC,8CAA8C,CAAC,CAAC,CAAC;IAClF,CAAC;CACF;AAzBD,oCAyBC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/defaultAuthProviders.js b/node_modules/mongodb/lib/cmap/auth/defaultAuthProviders.js new file mode 100644 index 0000000..ad71c18 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/defaultAuthProviders.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AUTH_PROVIDERS = exports.AuthMechanism = void 0; +const mongocr_1 = require("./mongocr"); +const x509_1 = require("./x509"); +const plain_1 = require("./plain"); +const gssapi_1 = require("./gssapi"); +const scram_1 = require("./scram"); +const mongodb_aws_1 = require("./mongodb_aws"); +/** @public */ +exports.AuthMechanism = Object.freeze({ + MONGODB_AWS: 'MONGODB-AWS', + MONGODB_CR: 'MONGODB-CR', + MONGODB_DEFAULT: 'DEFAULT', + MONGODB_GSSAPI: 'GSSAPI', + MONGODB_PLAIN: 'PLAIN', + MONGODB_SCRAM_SHA1: 'SCRAM-SHA-1', + MONGODB_SCRAM_SHA256: 'SCRAM-SHA-256', + MONGODB_X509: 'MONGODB-X509' +}); +exports.AUTH_PROVIDERS = new Map([ + [exports.AuthMechanism.MONGODB_AWS, new mongodb_aws_1.MongoDBAWS()], + [exports.AuthMechanism.MONGODB_CR, new mongocr_1.MongoCR()], + [exports.AuthMechanism.MONGODB_GSSAPI, new gssapi_1.GSSAPI()], + [exports.AuthMechanism.MONGODB_PLAIN, new plain_1.Plain()], + [exports.AuthMechanism.MONGODB_SCRAM_SHA1, new scram_1.ScramSHA1()], + [exports.AuthMechanism.MONGODB_SCRAM_SHA256, new scram_1.ScramSHA256()], + [exports.AuthMechanism.MONGODB_X509, new x509_1.X509()] +]); +//# sourceMappingURL=defaultAuthProviders.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/defaultAuthProviders.js.map b/node_modules/mongodb/lib/cmap/auth/defaultAuthProviders.js.map new file mode 100644 index 0000000..924e4dc --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/defaultAuthProviders.js.map @@ -0,0 +1 @@ +{"version":3,"file":"defaultAuthProviders.js","sourceRoot":"","sources":["../../../src/cmap/auth/defaultAuthProviders.ts"],"names":[],"mappings":";;;AAAA,uCAAoC;AACpC,iCAA8B;AAC9B,mCAAgC;AAChC,qCAAkC;AAClC,mCAAiD;AACjD,+CAA2C;AAG3C,cAAc;AACD,QAAA,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC;IACzC,WAAW,EAAE,aAAa;IAC1B,UAAU,EAAE,YAAY;IACxB,eAAe,EAAE,SAAS;IAC1B,cAAc,EAAE,QAAQ;IACxB,aAAa,EAAE,OAAO;IACtB,kBAAkB,EAAE,aAAa;IACjC,oBAAoB,EAAE,eAAe;IACrC,YAAY,EAAE,cAAc;CACpB,CAAC,CAAC;AAKC,QAAA,cAAc,GAAG,IAAI,GAAG,CAAuC;IAC1E,CAAC,qBAAa,CAAC,WAAW,EAAE,IAAI,wBAAU,EAAE,CAAC;IAC7C,CAAC,qBAAa,CAAC,UAAU,EAAE,IAAI,iBAAO,EAAE,CAAC;IACzC,CAAC,qBAAa,CAAC,cAAc,EAAE,IAAI,eAAM,EAAE,CAAC;IAC5C,CAAC,qBAAa,CAAC,aAAa,EAAE,IAAI,aAAK,EAAE,CAAC;IAC1C,CAAC,qBAAa,CAAC,kBAAkB,EAAE,IAAI,iBAAS,EAAE,CAAC;IACnD,CAAC,qBAAa,CAAC,oBAAoB,EAAE,IAAI,mBAAW,EAAE,CAAC;IACvD,CAAC,qBAAa,CAAC,YAAY,EAAE,IAAI,WAAI,EAAE,CAAC;CACzC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/gssapi.js b/node_modules/mongodb/lib/cmap/auth/gssapi.js new file mode 100644 index 0000000..78d02c9 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/gssapi.js @@ -0,0 +1,148 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GSSAPI = void 0; +const auth_provider_1 = require("./auth_provider"); +const error_1 = require("../../error"); +const deps_1 = require("../../deps"); +const utils_1 = require("../../utils"); +const dns = require("dns"); +class GSSAPI extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (credentials == null) + return callback(new error_1.MongoMissingCredentialsError('Credentials required for GSSAPI authentication')); + const { username } = credentials; + function externalCommand(command, cb) { + return connection.command(utils_1.ns('$external.$cmd'), command, undefined, cb); + } + makeKerberosClient(authContext, (err, client) => { + if (err) + return callback(err); + if (client == null) + return callback(new error_1.MongoMissingDependencyError('GSSAPI client missing')); + client.step('', (err, payload) => { + if (err) + return callback(err); + externalCommand(saslStart(payload), (err, result) => { + if (err) + return callback(err); + if (result == null) + return callback(); + negotiate(client, 10, result.payload, (err, payload) => { + if (err) + return callback(err); + externalCommand(saslContinue(payload, result.conversationId), (err, result) => { + if (err) + return callback(err); + if (result == null) + return callback(); + finalize(client, username, result.payload, (err, payload) => { + if (err) + return callback(err); + externalCommand({ + saslContinue: 1, + conversationId: result.conversationId, + payload + }, (err, result) => { + if (err) + return callback(err); + callback(undefined, result); + }); + }); + }); + }); + }); + }); + }); + } +} +exports.GSSAPI = GSSAPI; +function makeKerberosClient(authContext, callback) { + var _a; + const { hostAddress } = authContext.options; + const { credentials } = authContext; + if (!hostAddress || typeof hostAddress.host !== 'string' || !credentials) { + return callback(new error_1.MongoInvalidArgumentError('Connection must have host and port and credentials defined.')); + } + if ('kModuleError' in deps_1.Kerberos) { + return callback(deps_1.Kerberos['kModuleError']); + } + const { initializeClient } = deps_1.Kerberos; + const { username, password } = credentials; + const mechanismProperties = credentials.mechanismProperties; + const serviceName = (_a = mechanismProperties.SERVICE_NAME) !== null && _a !== void 0 ? _a : 'mongodb'; + performGssapiCanonicalizeHostName(hostAddress.host, mechanismProperties, (err, host) => { + if (err) + return callback(err); + const initOptions = {}; + if (password != null) { + Object.assign(initOptions, { user: username, password: password }); + } + let spn = `${serviceName}${process.platform === 'win32' ? '/' : '@'}${host}`; + if ('SERVICE_REALM' in mechanismProperties) { + spn = `${spn}@${mechanismProperties.SERVICE_REALM}`; + } + initializeClient(spn, initOptions, (err, client) => { + // TODO(NODE-3483) + if (err) + return callback(new error_1.MongoRuntimeError(err)); + callback(undefined, client); + }); + }); +} +function saslStart(payload) { + return { + saslStart: 1, + mechanism: 'GSSAPI', + payload, + autoAuthorize: 1 + }; +} +function saslContinue(payload, conversationId) { + return { + saslContinue: 1, + conversationId, + payload + }; +} +function negotiate(client, retries, payload, callback) { + client.step(payload, (err, response) => { + // Retries exhausted, raise error + if (err && retries === 0) + return callback(err); + // Adjust number of retries and call step again + if (err) + return negotiate(client, retries - 1, payload, callback); + // Return the payload + callback(undefined, response || ''); + }); +} +function finalize(client, user, payload, callback) { + // GSS Client Unwrap + client.unwrap(payload, (err, response) => { + if (err) + return callback(err); + // Wrap the response + client.wrap(response || '', { user }, (err, wrapped) => { + if (err) + return callback(err); + // Return the payload + callback(undefined, wrapped); + }); + }); +} +function performGssapiCanonicalizeHostName(host, mechanismProperties, callback) { + if (!mechanismProperties.gssapiCanonicalizeHostName) + return callback(undefined, host); + // Attempt to resolve the host name + dns.resolveCname(host, (err, r) => { + if (err) + return callback(err); + // Get the first resolve host id + if (Array.isArray(r) && r.length > 0) { + return callback(undefined, r[0]); + } + callback(undefined, host); + }); +} +//# sourceMappingURL=gssapi.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/gssapi.js.map b/node_modules/mongodb/lib/cmap/auth/gssapi.js.map new file mode 100644 index 0000000..630b4bb --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/gssapi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gssapi.js","sourceRoot":"","sources":["../../../src/cmap/auth/gssapi.ts"],"names":[],"mappings":";;;AAAA,mDAA4D;AAC5D,uCAMqB;AACrB,qCAAsD;AACtD,uCAA2C;AAS3C,2BAA2B;AAE3B,MAAa,MAAO,SAAQ,4BAAY;IACtC,IAAI,CAAC,WAAwB,EAAE,QAAkB;QAC/C,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,GAAG,WAAW,CAAC;QAChD,IAAI,WAAW,IAAI,IAAI;YACrB,OAAO,QAAQ,CACb,IAAI,oCAA4B,CAAC,gDAAgD,CAAC,CACnF,CAAC;QACJ,MAAM,EAAE,QAAQ,EAAE,GAAG,WAAW,CAAC;QACjC,SAAS,eAAe,CACtB,OAAiB,EACjB,EAAsD;YAEtD,OAAO,UAAU,CAAC,OAAO,CAAC,UAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;QAC1E,CAAC;QACD,kBAAkB,CAAC,WAAW,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YAC9C,IAAI,GAAG;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9B,IAAI,MAAM,IAAI,IAAI;gBAAE,OAAO,QAAQ,CAAC,IAAI,mCAA2B,CAAC,uBAAuB,CAAC,CAAC,CAAC;YAC9F,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE;gBAC/B,IAAI,GAAG;oBAAE,OAAO,QAAQ,CAA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,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE;QACvC,IAAI,GAAG;YAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;QAE9B,oBAAoB;QACpB,MAAM,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE;YACrD,IAAI,GAAG;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAE9B,qBAAqB;YACrB,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC/B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,iCAAiC,CACxC,IAAY,EACZ,mBAAwC,EACxC,QAA0B;IAE1B,IAAI,CAAC,mBAAmB,CAAC,0BAA0B;QAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAEtF,mCAAmC;IACnC,GAAG,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE;QAChC,IAAI,GAAG;YAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;QAE9B,gCAAgC;QAChC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACpC,OAAO,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SAClC;QAED,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js b/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js new file mode 100644 index 0000000..1368227 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js @@ -0,0 +1,125 @@ +"use strict"; +// Resolves the default auth mechanism according to +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoCredentials = void 0; +const error_1 = require("../../error"); +const defaultAuthProviders_1 = require("./defaultAuthProviders"); +// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst +function getDefaultAuthMechanism(ismaster) { + if (ismaster) { + // If ismaster contains saslSupportedMechs, use scram-sha-256 + // if it is available, else scram-sha-1 + if (Array.isArray(ismaster.saslSupportedMechs)) { + return ismaster.saslSupportedMechs.includes(defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256) + ? defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256 + : defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA1; + } + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (ismaster.maxWireVersion >= 3) { + return defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA1; + } + } + // Default for wireprotocol < 3 + return defaultAuthProviders_1.AuthMechanism.MONGODB_CR; +} +/** + * A representation of the credentials used by MongoDB + * @public + */ +class MongoCredentials { + constructor(options) { + this.username = options.username; + this.password = options.password; + this.source = options.source; + if (!this.source && options.db) { + this.source = options.db; + } + this.mechanism = options.mechanism || defaultAuthProviders_1.AuthMechanism.MONGODB_DEFAULT; + this.mechanismProperties = options.mechanismProperties || {}; + if (this.mechanism.match(/MONGODB-AWS/i)) { + if (!this.username && process.env.AWS_ACCESS_KEY_ID) { + this.username = process.env.AWS_ACCESS_KEY_ID; + } + if (!this.password && process.env.AWS_SECRET_ACCESS_KEY) { + this.password = process.env.AWS_SECRET_ACCESS_KEY; + } + if (this.mechanismProperties.AWS_SESSION_TOKEN == null && + process.env.AWS_SESSION_TOKEN != null) { + this.mechanismProperties = { + ...this.mechanismProperties, + AWS_SESSION_TOKEN: process.env.AWS_SESSION_TOKEN + }; + } + } + Object.freeze(this.mechanismProperties); + Object.freeze(this); + } + /** Determines if two MongoCredentials objects are equivalent */ + equals(other) { + return (this.mechanism === other.mechanism && + this.username === other.username && + this.password === other.password && + this.source === other.source); + } + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param ismaster - An ismaster response from the server + */ + resolveAuthMechanism(ismaster) { + // If the mechanism is not "default", then it does not need to be resolved + if (this.mechanism.match(/DEFAULT/i)) { + return new MongoCredentials({ + username: this.username, + password: this.password, + source: this.source, + mechanism: getDefaultAuthMechanism(ismaster), + mechanismProperties: this.mechanismProperties + }); + } + return this; + } + validate() { + if ((this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_GSSAPI || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_CR || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_PLAIN || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA1 || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256) && + !this.username) { + throw new error_1.MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`); + } + if (this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_GSSAPI || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_AWS || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_X509) { + if (this.source != null && this.source !== '$external') { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError(`Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.`); + } + } + if (this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_PLAIN && this.source == null) { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError('PLAIN Authentication Mechanism needs an auth source'); + } + if (this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_X509 && this.password != null) { + if (this.password === '') { + Reflect.set(this, 'password', undefined); + return; + } + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError(`Password not allowed for mechanism MONGODB-X509`); + } + } + static merge(creds, options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + return new MongoCredentials({ + username: (_b = (_a = options.username) !== null && _a !== void 0 ? _a : creds === null || creds === void 0 ? void 0 : creds.username) !== null && _b !== void 0 ? _b : '', + password: (_d = (_c = options.password) !== null && _c !== void 0 ? _c : creds === null || creds === void 0 ? void 0 : creds.password) !== null && _d !== void 0 ? _d : '', + mechanism: (_f = (_e = options.mechanism) !== null && _e !== void 0 ? _e : creds === null || creds === void 0 ? void 0 : creds.mechanism) !== null && _f !== void 0 ? _f : defaultAuthProviders_1.AuthMechanism.MONGODB_DEFAULT, + mechanismProperties: (_h = (_g = options.mechanismProperties) !== null && _g !== void 0 ? _g : creds === null || creds === void 0 ? void 0 : creds.mechanismProperties) !== null && _h !== void 0 ? _h : {}, + source: (_l = (_k = (_j = options.source) !== null && _j !== void 0 ? _j : options.db) !== null && _k !== void 0 ? _k : creds === null || creds === void 0 ? void 0 : creds.source) !== null && _l !== void 0 ? _l : 'admin' + }); + } +} +exports.MongoCredentials = MongoCredentials; +//# sourceMappingURL=mongo_credentials.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map b/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map new file mode 100644 index 0000000..523fec2 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_credentials.js","sourceRoot":"","sources":["../../../src/cmap/auth/mongo_credentials.ts"],"names":[],"mappings":";AAAA,mDAAmD;;;AAGnD,uCAA0E;AAC1E,iEAAuD;AAEvD,6EAA6E;AAC7E,SAAS,uBAAuB,CAAC,QAAmB;IAClD,IAAI,QAAQ,EAAE;QACZ,6DAA6D;QAC7D,uCAAuC;QACvC,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE;YAC9C,OAAO,QAAQ,CAAC,kBAAkB,CAAC,QAAQ,CAAC,oCAAa,CAAC,oBAAoB,CAA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AAI,EAAE;YACnD,QAAQ,EAAE,MAAA,MAAA,OAAO,CAAC,QAAQ,mCAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,QAAQ,mCAAI,EAAE;YACnD,SAAS,EAAE,MAAA,MAAA,OAAO,CAAC,SAAS,mCAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,SAAS,mCAAI,oCAAa,CAAC,eAAe;YACjF,mBAAmB,EAAE,MAAA,MAAA,OAAO,CAAC,mBAAmB,mCAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,mBAAmB,mCAAI,EAAE;YACpF,MAAM,EAAE,MAAA,MAAA,MAAA,OAAO,CAAC,MAAM,mCAAI,OAAO,CAAC,EAAE,mCAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAAM,mCAAI,OAAO;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AAjID,4CAiIC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/mongocr.js b/node_modules/mongodb/lib/cmap/auth/mongocr.js new file mode 100644 index 0000000..6d6b256 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/mongocr.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoCR = void 0; +const crypto = require("crypto"); +const auth_provider_1 = require("./auth_provider"); +const utils_1 = require("../../utils"); +const error_1 = require("../../error"); +class MongoCR extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const username = credentials.username; + const password = credentials.password; + const source = credentials.source; + connection.command(utils_1.ns(`${source}.$cmd`), { getnonce: 1 }, undefined, (err, r) => { + let nonce = null; + let key = null; + // Get nonce + if (err == null) { + nonce = r.nonce; + // Use node md5 generator + let md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(`${username}:mongo:${password}`, 'utf8'); + const hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + const authenticateCommand = { + authenticate: 1, + user: username, + nonce, + key + }; + connection.command(utils_1.ns(`${source}.$cmd`), authenticateCommand, undefined, callback); + }); + } +} +exports.MongoCR = MongoCR; +//# sourceMappingURL=mongocr.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/mongocr.js.map b/node_modules/mongodb/lib/cmap/auth/mongocr.js.map new file mode 100644 index 0000000..d463397 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/mongocr.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongocr.js","sourceRoot":"","sources":["../../../src/cmap/auth/mongocr.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AACjC,mDAA4D;AAC5D,uCAA2C;AAC3C,uCAA2D;AAE3D,MAAa,OAAQ,SAAQ,4BAAY;IACvC,IAAI,CAAC,WAAwB,EAAE,QAAkB;QAC/C,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,GAAG,WAAW,CAAC;QAChD,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,QAAQ,CAAC,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC,CAAC;SAC5F;QACD,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;QACtC,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;QACtC,MAAM,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC;QAClC,UAAU,CAAC,OAAO,CAAC,UAAE,CAAC,GAAG,MAAM,OAAO,CAAC,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE;YAC9E,IAAI,KAAK,GAAG,IAAI,CAAC;YACjB,IAAI,GAAG,GAAG,IAAI,CAAC;YAEf,YAAY;YACZ,IAAI,GAAG,IAAI,IAAI,EAAE;gBACf,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC;gBAEhB,yBAAyB;gBACzB,IAAI,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;gBAEnC,wCAAwC;gBACxC,GAAG,CAAC,MAAM,CAAC,GAAG,QAAQ,UAAU,QAAQ,EAAE,EAAE,MAAM,CAAC,CAAC;gBACpD,MAAM,aAAa,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBAExC,YAAY;gBACZ,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;gBAC/B,GAAG,CAAC,MAAM,CAAC,KAAK,GAAG,QAAQ,GAAG,aAAa,EAAE,MAAM,CAAC,CAAC;gBACrD,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;aACzB;YAED,MAAM,mBAAmB,GAAG;gBAC1B,YAAY,EAAE,CAAC;gBACf,IAAI,EAAE,QAAQ;gBACd,KAAK;gBACL,GAAG;aACJ,CAAC;YAEF,UAAU,CAAC,OAAO,CAAC,UAAE,CAAC,GAAG,MAAM,OAAO,CAAC,EAAE,mBAAmB,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;QACrF,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAxCD,0BAwCC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js b/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js new file mode 100644 index 0000000..6ecf9fb --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js @@ -0,0 +1,201 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoDBAWS = void 0; +const http = require("http"); +const crypto = require("crypto"); +const url = require("url"); +const BSON = require("../../bson"); +const auth_provider_1 = require("./auth_provider"); +const mongo_credentials_1 = require("./mongo_credentials"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const deps_1 = require("../../deps"); +const defaultAuthProviders_1 = require("./defaultAuthProviders"); +const ASCII_N = 110; +const AWS_RELATIVE_URI = 'http://169.254.170.2'; +const AWS_EC2_URI = 'http://169.254.169.254'; +const AWS_EC2_PATH = '/latest/meta-data/iam/security-credentials'; +const bsonOptions = { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false +}; +class MongoDBAWS extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if ('kModuleError' in deps_1.aws4) { + return callback(deps_1.aws4['kModuleError']); + } + const { sign } = deps_1.aws4; + if (utils_1.maxWireVersion(connection) < 9) { + callback(new error_1.MongoCompatibilityError('MONGODB-AWS authentication requires MongoDB version 4.4 or later')); + return; + } + if (!credentials.username) { + makeTempCredentials(credentials, (err, tempCredentials) => { + if (err || !tempCredentials) + return callback(err); + authContext.credentials = tempCredentials; + this.auth(authContext, callback); + }); + return; + } + const accessKeyId = credentials.username; + const secretAccessKey = credentials.password; + const sessionToken = credentials.mechanismProperties.AWS_SESSION_TOKEN; + // If all three defined, include sessionToken, else include username and pass, else no credentials + const awsCredentials = accessKeyId && secretAccessKey && sessionToken + ? { accessKeyId, secretAccessKey, sessionToken } + : accessKeyId && secretAccessKey + ? { accessKeyId, secretAccessKey } + : undefined; + const db = credentials.source; + crypto.randomBytes(32, (err, nonce) => { + if (err) { + callback(err); + return; + } + const saslStart = { + saslStart: 1, + mechanism: 'MONGODB-AWS', + payload: BSON.serialize({ r: nonce, p: ASCII_N }, bsonOptions) + }; + connection.command(utils_1.ns(`${db}.$cmd`), saslStart, undefined, (err, res) => { + if (err) + return callback(err); + const serverResponse = BSON.deserialize(res.payload.buffer, bsonOptions); + const host = serverResponse.h; + const serverNonce = serverResponse.s.buffer; + if (serverNonce.length !== 64) { + callback( + // TODO(NODE-3483) + new error_1.MongoRuntimeError(`Invalid server nonce length ${serverNonce.length}, expected 64`)); + return; + } + if (serverNonce.compare(nonce, 0, nonce.length, 0, nonce.length) !== 0) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError('Server nonce does not begin with client nonce')); + return; + } + if (host.length < 1 || host.length > 255 || host.indexOf('..') !== -1) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError(`Server returned an invalid host: "${host}"`)); + return; + } + const body = 'Action=GetCallerIdentity&Version=2011-06-15'; + const options = sign({ + method: 'POST', + host, + region: deriveRegion(serverResponse.h), + service: 'sts', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Length': body.length, + 'X-MongoDB-Server-Nonce': serverNonce.toString('base64'), + 'X-MongoDB-GS2-CB-Flag': 'n' + }, + path: '/', + body + }, awsCredentials); + const payload = { + a: options.headers.Authorization, + d: options.headers['X-Amz-Date'] + }; + if (sessionToken) { + payload.t = sessionToken; + } + const saslContinue = { + saslContinue: 1, + conversationId: 1, + payload: BSON.serialize(payload, bsonOptions) + }; + connection.command(utils_1.ns(`${db}.$cmd`), saslContinue, undefined, callback); + }); + }); + } +} +exports.MongoDBAWS = MongoDBAWS; +function makeTempCredentials(credentials, callback) { + function done(creds) { + if (!creds.AccessKeyId || !creds.SecretAccessKey || !creds.Token) { + callback(new error_1.MongoMissingCredentialsError('Could not obtain temporary MONGODB-AWS credentials')); + return; + } + callback(undefined, new mongo_credentials_1.MongoCredentials({ + username: creds.AccessKeyId, + password: creds.SecretAccessKey, + source: credentials.source, + mechanism: defaultAuthProviders_1.AuthMechanism.MONGODB_AWS, + mechanismProperties: { + AWS_SESSION_TOKEN: creds.Token + } + })); + } + // If the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI + // is set then drivers MUST assume that it was set by an AWS ECS agent + if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) { + request(`${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`, undefined, (err, res) => { + if (err) + return callback(err); + done(res); + }); + return; + } + // Otherwise assume we are on an EC2 instance + // get a token + request(`${AWS_EC2_URI}/latest/api/token`, { method: 'PUT', json: false, headers: { 'X-aws-ec2-metadata-token-ttl-seconds': 30 } }, (err, token) => { + if (err) + return callback(err); + // get role name + request(`${AWS_EC2_URI}/${AWS_EC2_PATH}`, { json: false, headers: { 'X-aws-ec2-metadata-token': token } }, (err, roleName) => { + if (err) + return callback(err); + // get temp credentials + request(`${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, { headers: { 'X-aws-ec2-metadata-token': token } }, (err, creds) => { + if (err) + return callback(err); + done(creds); + }); + }); + }); +} +function deriveRegion(host) { + const parts = host.split('.'); + if (parts.length === 1 || parts[1] === 'amazonaws') { + return 'us-east-1'; + } + return parts[1]; +} +function request(uri, _options, callback) { + const options = Object.assign({ + method: 'GET', + timeout: 10000, + json: true + }, url.parse(uri), _options); + const req = http.request(options, res => { + res.setEncoding('utf8'); + let data = ''; + res.on('data', d => (data += d)); + res.on('end', () => { + if (options.json === false) { + callback(undefined, data); + return; + } + try { + const parsed = JSON.parse(data); + callback(undefined, parsed); + } + catch (err) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError(`Invalid JSON response: "${data}"`)); + } + }); + }); + req.on('error', err => callback(err)); + req.end(); +} +//# sourceMappingURL=mongodb_aws.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map b/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map new file mode 100644 index 0000000..2d12f9a --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongodb_aws.js","sourceRoot":"","sources":["../../../src/cmap/auth/mongodb_aws.ts"],"names":[],"mappings":";;;AAAA,6BAA6B;AAC7B,iCAAiC;AACjC,2BAA2B;AAC3B,mCAAmC;AACnC,mDAA4D;AAC5D,2DAAuD;AACvD,uCAIqB;AACrB,uCAA2D;AAG3D,qCAAkC;AAClC,iEAAuD;AAGvD,MAAM,OAAO,GAAG,GAAG,CAAC;AACpB,MAAM,g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IACpF,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAC3B;QACE,MAAM,EAAE,KAAK;QACb,OAAO,EAAE,KAAK;QACd,IAAI,EAAE,IAAI;KACX,EACD,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,EACd,QAAQ,CACT,CAAC;IAEF,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE;QACtC,GAAG,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QAExB,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;QACjC,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;YACjB,IAAI,OAAO,CAAC,IAAI,KAAK,KAAK,EAAE;gBAC1B,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;gBAC1B,OAAO;aACR;YAED,IAAI;gBACF,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;gBAChC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;aAC7B;YAAC,OAAO,GAAG,EAAE;gBACZ,kBAAkB;gBAClB,QAAQ,CAAC,IAAI,yBAAiB,CAAC,2BAA2B,IAAI,GAAG,CAAC,CAAC,CAAC;aACrE;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IACtC,GAAG,CAAC,GAAG,EAAE,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/plain.js b/node_modules/mongodb/lib/cmap/auth/plain.js new file mode 100644 index 0000000..a128b1b --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/plain.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Plain = void 0; +const bson_1 = require("../../bson"); +const auth_provider_1 = require("./auth_provider"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +class Plain extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const username = credentials.username; + const password = credentials.password; + const payload = new bson_1.Binary(Buffer.from(`\x00${username}\x00${password}`)); + const command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + connection.command(utils_1.ns('$external.$cmd'), command, undefined, callback); + } +} +exports.Plain = Plain; +//# sourceMappingURL=plain.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/plain.js.map b/node_modules/mongodb/lib/cmap/auth/plain.js.map new file mode 100644 index 0000000..aa85a39 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/plain.js.map @@ -0,0 +1 @@ +{"version":3,"file":"plain.js","sourceRoot":"","sources":["../../../src/cmap/auth/plain.ts"],"names":[],"mappings":";;;AAAA,qCAAoC;AACpC,mDAA4D;AAC5D,uCAA2D;AAC3D,uCAA2C;AAE3C,MAAa,KAAM,SAAQ,4BAAY;IACrC,IAAI,CAAC,WAAwB,EAAE,QAAkB;QAC/C,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,GAAG,WAAW,CAAC;QAChD,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,QAAQ,CAAC,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC,CAAC;SAC5F;QACD,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;QACtC,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;QAEtC,MAAM,OAAO,GAAG,IAAI,aAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,QAAQ,OAAO,QAAQ,EAAE,CAAC,CAAC,CAAC;QAC1E,MAAM,OAAO,GAAG;YACd,SAAS,EAAE,CAAC;YACZ,SAAS,EAAE,OAAO;YAClB,OAAO,EAAE,OAAO;YAChB,aAAa,EAAE,CAAC;SACjB,CAAC;QAEF,UAAU,CAAC,OAAO,CAAC,UAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;IACzE,CAAC;CACF;AAnBD,sBAmBC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/scram.js b/node_modules/mongodb/lib/cmap/auth/scram.js new file mode 100644 index 0000000..5e19104 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/scram.js @@ -0,0 +1,276 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ScramSHA256 = exports.ScramSHA1 = void 0; +const crypto = require("crypto"); +const bson_1 = require("../../bson"); +const error_1 = require("../../error"); +const auth_provider_1 = require("./auth_provider"); +const utils_1 = require("../../utils"); +const deps_1 = require("../../deps"); +const defaultAuthProviders_1 = require("./defaultAuthProviders"); +class ScramSHA extends auth_provider_1.AuthProvider { + constructor(cryptoMethod) { + super(); + this.cryptoMethod = cryptoMethod || 'sha1'; + } + prepare(handshakeDoc, authContext, callback) { + const cryptoMethod = this.cryptoMethod; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (cryptoMethod === 'sha256' && deps_1.saslprep == null) { + utils_1.emitWarning('Warning: no saslprep library specified. Passwords will not be sanitized'); + } + crypto.randomBytes(24, (err, nonce) => { + if (err) { + return callback(err); + } + // store the nonce for later use + Object.assign(authContext, { nonce }); + const request = Object.assign({}, handshakeDoc, { + speculativeAuthenticate: Object.assign(makeFirstMessage(cryptoMethod, credentials, nonce), { + db: credentials.source + }) + }); + callback(undefined, request); + }); + } + auth(authContext, callback) { + const response = authContext.response; + if (response && response.speculativeAuthenticate) { + continueScramConversation(this.cryptoMethod, response.speculativeAuthenticate, authContext, callback); + return; + } + executeScram(this.cryptoMethod, authContext, callback); + } +} +function cleanUsername(username) { + return username.replace('=', '=3D').replace(',', '=2C'); +} +function clientFirstMessageBare(username, nonce) { + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return Buffer.concat([ + Buffer.from('n=', 'utf8'), + Buffer.from(username, 'utf8'), + Buffer.from(',r=', 'utf8'), + Buffer.from(nonce.toString('base64'), 'utf8') + ]); +} +function makeFirstMessage(cryptoMethod, credentials, nonce) { + const username = cleanUsername(credentials.username); + const mechanism = cryptoMethod === 'sha1' ? defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA1 : defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256; + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return { + saslStart: 1, + mechanism, + payload: new bson_1.Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)])), + autoAuthorize: 1, + options: { skipEmptyExchange: true } + }; +} +function executeScram(cryptoMethod, authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (!authContext.nonce) { + return callback(new error_1.MongoInvalidArgumentError('AuthContext must contain a valid nonce property')); + } + const nonce = authContext.nonce; + const db = credentials.source; + const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce); + connection.command(utils_1.ns(`${db}.$cmd`), saslStartCmd, undefined, (_err, result) => { + const err = resolveError(_err, result); + if (err) { + return callback(err); + } + continueScramConversation(cryptoMethod, result, authContext, callback); + }); +} +function continueScramConversation(cryptoMethod, response, authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (!authContext.nonce) { + return callback(new error_1.MongoInvalidArgumentError('Unable to continue SCRAM without valid nonce')); + } + const nonce = authContext.nonce; + const db = credentials.source; + const username = cleanUsername(credentials.username); + const password = credentials.password; + let processedPassword; + if (cryptoMethod === 'sha256') { + processedPassword = 'kModuleError' in deps_1.saslprep ? password : deps_1.saslprep(password); + } + else { + try { + processedPassword = passwordDigest(username, password); + } + catch (e) { + return callback(e); + } + } + const payload = Buffer.isBuffer(response.payload) + ? new bson_1.Binary(response.payload) + : response.payload; + const dict = parsePayload(payload.value()); + const iterations = parseInt(dict.i, 10); + if (iterations && iterations < 4096) { + callback( + // TODO(NODE-3483) + new error_1.MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`), false); + return; + } + const salt = dict.s; + const rnonce = dict.r; + if (rnonce.startsWith('nonce')) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError(`Server returned an invalid nonce: ${rnonce}`), false); + return; + } + // Set up start of proof + const withoutProof = `c=biws,r=${rnonce}`; + const saltedPassword = HI(processedPassword, Buffer.from(salt, 'base64'), iterations, cryptoMethod); + const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); + const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key'); + const storedKey = H(cryptoMethod, clientKey); + const authMessage = [clientFirstMessageBare(username, nonce), payload.value(), withoutProof].join(','); + const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); + const clientProof = `p=${xor(clientKey, clientSignature)}`; + const clientFinal = [withoutProof, clientProof].join(','); + const serverSignature = HMAC(cryptoMethod, serverKey, authMessage); + const saslContinueCmd = { + saslContinue: 1, + conversationId: response.conversationId, + payload: new bson_1.Binary(Buffer.from(clientFinal)) + }; + connection.command(utils_1.ns(`${db}.$cmd`), saslContinueCmd, undefined, (_err, r) => { + const err = resolveError(_err, r); + if (err) { + return callback(err); + } + const parsedResponse = parsePayload(r.payload.value()); + if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) { + callback(new error_1.MongoRuntimeError('Server returned an invalid signature')); + return; + } + if (!r || r.done !== false) { + return callback(err, r); + } + const retrySaslContinueCmd = { + saslContinue: 1, + conversationId: r.conversationId, + payload: Buffer.alloc(0) + }; + connection.command(utils_1.ns(`${db}.$cmd`), retrySaslContinueCmd, undefined, callback); + }); +} +function parsePayload(payload) { + const dict = {}; + const parts = payload.split(','); + for (let i = 0; i < parts.length; i++) { + const valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + return dict; +} +function passwordDigest(username, password) { + if (typeof username !== 'string') { + throw new error_1.MongoInvalidArgumentError('Username must be a string'); + } + if (typeof password !== 'string') { + throw new error_1.MongoInvalidArgumentError('Password must be a string'); + } + if (password.length === 0) { + throw new error_1.MongoInvalidArgumentError('Password cannot be empty'); + } + const md5 = crypto.createHash('md5'); + md5.update(`${username}:mongo:${password}`, 'utf8'); + return md5.digest('hex'); +} +// XOR two buffers +function xor(a, b) { + if (!Buffer.isBuffer(a)) { + a = Buffer.from(a); + } + if (!Buffer.isBuffer(b)) { + b = Buffer.from(b); + } + const length = Math.max(a.length, b.length); + const res = []; + for (let i = 0; i < length; i += 1) { + res.push(a[i] ^ b[i]); + } + return Buffer.from(res).toString('base64'); +} +function H(method, text) { + return crypto.createHash(method).update(text).digest(); +} +function HMAC(method, key, text) { + return crypto.createHmac(method, key).update(text).digest(); +} +let _hiCache = {}; +let _hiCacheCount = 0; +function _hiCachePurge() { + _hiCache = {}; + _hiCacheCount = 0; +} +const hiLengthMap = { + sha256: 32, + sha1: 20 +}; +function HI(data, salt, iterations, cryptoMethod) { + // omit the work if already generated + const key = [data, salt.toString('base64'), iterations].join('_'); + if (_hiCache[key] != null) { + return _hiCache[key]; + } + // generate the salt + const saltedData = crypto.pbkdf2Sync(data, salt, iterations, hiLengthMap[cryptoMethod], cryptoMethod); + // cache a copy to speed up the next lookup, but prevent unbounded cache growth + if (_hiCacheCount >= 200) { + _hiCachePurge(); + } + _hiCache[key] = saltedData; + _hiCacheCount += 1; + return saltedData; +} +function compareDigest(lhs, rhs) { + if (lhs.length !== rhs.length) { + return false; + } + if (typeof crypto.timingSafeEqual === 'function') { + return crypto.timingSafeEqual(lhs, rhs); + } + let result = 0; + for (let i = 0; i < lhs.length; i++) { + result |= lhs[i] ^ rhs[i]; + } + return result === 0; +} +function resolveError(err, result) { + if (err) + return err; + if (result) { + if (result.$err || result.errmsg) + return new error_1.MongoServerError(result); + } +} +class ScramSHA1 extends ScramSHA { + constructor() { + super('sha1'); + } +} +exports.ScramSHA1 = ScramSHA1; +class ScramSHA256 extends ScramSHA { + constructor() { + super('sha256'); + } +} +exports.ScramSHA256 = ScramSHA256; +//# sourceMappingURL=scram.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/scram.js.map b/node_modules/mongodb/lib/cmap/auth/scram.js.map new file mode 100644 index 0000000..e77df0c --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/scram.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scram.js","sourceRoot":"","sources":["../../../src/cmap/auth/scram.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AACjC,qCAA8C;AAC9C,uCAMqB;AACrB,mDAA4D;AAC5D,uCAAwD;AAIxD,qCAAsC;AACtC,iEAAuD;AAIvD,MAAM,QAAS,SAAQ,4BAAY;IAEjC,YAAY,YAA0B;QACpC,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,YAAY,GAAG,YAAY,IAAI,MAAM,CAAC;IAC7C,CAAC;IAED,OAAO,CAAC,YAA+B,EAAE,WAAwB,EAAE,QAAkB;QACnF,MAAM,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC;QACvC,MAAM,WAAW,GAAG,WAAW,CAAC,WAAW,CAAC;QAC5C,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,QAAQ,CAAC,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC,CAAC;SAC5F;QACD,IAAI,YAAY,KAAK,QAAQ,IAAI,eAAQ,IAAI,IAAI,EAAE;YACjD,mBAAW,CAAC,yEAAyE,CAAC,CAAC;SAC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AAG,CAAC,MAAM,EAAE;QAC7B,OAAO,KAAK,CAAC;KACd;IAED,IAAI,OAAO,MAAM,CAAC,eAAe,KAAK,UAAU,EAAE;QAChD,OAAO,MAAM,CAAC,eAAe,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;KACzC;IAED,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;KAC3B;IAED,OAAO,MAAM,KAAK,CAAC,CAAC;AACtB,CAAC;AAED,SAAS,YAAY,CAAC,GAAc,EAAE,MAAiB;IACrD,IAAI,GAAG;QAAE,OAAO,GAAG,CAAC;IACpB,IAAI,MAAM,EAAE;QACV,IAAI,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,MAAM;YAAE,OAAO,IAAI,wBAAgB,CAAC,MAAM,CAAC,CAAC;KACvE;AACH,CAAC;AAED,MAAa,SAAU,SAAQ,QAAQ;IACrC;QACE,KAAK,CAAC,MAAM,CAAC,CAAC;IAChB,CAAC;CACF;AAJD,8BAIC;AAED,MAAa,WAAY,SAAQ,QAAQ;IACvC;QACE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAClB,CAAC;CACF;AAJD,kCAIC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/x509.js b/node_modules/mongodb/lib/cmap/auth/x509.js new file mode 100644 index 0000000..0c9897d --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/x509.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.X509 = void 0; +const auth_provider_1 = require("./auth_provider"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +class X509 extends auth_provider_1.AuthProvider { + prepare(handshakeDoc, authContext, callback) { + const { credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + Object.assign(handshakeDoc, { + speculativeAuthenticate: x509AuthenticateCommand(credentials) + }); + callback(undefined, handshakeDoc); + } + auth(authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const response = authContext.response; + if (response && response.speculativeAuthenticate) { + return callback(); + } + connection.command(utils_1.ns('$external.$cmd'), x509AuthenticateCommand(credentials), undefined, callback); + } +} +exports.X509 = X509; +function x509AuthenticateCommand(credentials) { + const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; + if (credentials.username) { + command.user = credentials.username; + } + return command; +} +//# sourceMappingURL=x509.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/auth/x509.js.map b/node_modules/mongodb/lib/cmap/auth/x509.js.map new file mode 100644 index 0000000..4a80bd3 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/auth/x509.js.map @@ -0,0 +1 @@ +{"version":3,"file":"x509.js","sourceRoot":"","sources":["../../../src/cmap/auth/x509.ts"],"names":[],"mappings":";;;AAAA,mDAA4D;AAC5D,uCAA2D;AAE3D,uCAA2C;AAI3C,MAAa,IAAK,SAAQ,4BAAY;IACpC,OAAO,CAAC,YAA+B,EAAE,WAAwB,EAAE,QAAkB;QACnF,MAAM,EAAE,WAAW,EAAE,GAAG,WAAW,CAAC;QACpC,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,QAAQ,CAAC,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC,CAAC;SAC5F;QACD,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE;YAC1B,uBAAuB,EAAE,uBAAuB,CAAC,WAAW,CAAC;SAC9D,CAAC,CAAC;QAEH,QAAQ,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;IACpC,CAAC;IAED,IAAI,CAAC,WAAwB,EAAE,QAAkB;QAC/C,MAAM,UAAU,GAAG,WAAW,CAAC,UAAU,CAAC;QAC1C,MAAM,WAAW,GAAG,WAAW,CAAC,WAAW,CAAC;QAC5C,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,QAAQ,CAAC,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC,CAAC;SAC5F;QACD,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;QAEtC,IAAI,QAAQ,IAAI,QAAQ,CAAC,uBAAuB,EAAE;YAChD,OAAO,QAAQ,EAAE,CAAC;SACnB;QAED,UAAU,CAAC,OAAO,CAChB,UAAE,CAAC,gBAAgB,CAAC,EACpB,uBAAuB,CAAC,WAAW,CAAC,EACpC,SAAS,EACT,QAAQ,CACT,CAAC;IACJ,CAAC;CACF;AAhCD,oBAgCC;AAED,SAAS,uBAAuB,CAAC,WAA6B;IAC5D,MAAM,OAAO,GAAa,EAAE,YAAY,EAAE,CAAC,EAAE,SAAS,EAAE,cAAc,EAAE,CAAC;IACzE,IAAI,WAAW,CAAC,QAAQ,EAAE;QACxB,OAAO,CAAC,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC;KACrC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/command_monitoring_events.js b/node_modules/mongodb/lib/cmap/command_monitoring_events.js new file mode 100644 index 0000000..a82b0f9 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/command_monitoring_events.js @@ -0,0 +1,272 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CommandFailedEvent = exports.CommandSucceededEvent = exports.CommandStartedEvent = void 0; +const commands_1 = require("./commands"); +const utils_1 = require("../utils"); +/** + * An event indicating the start of a given + * @public + * @category Event + */ +class CommandStartedEvent { + /** + * Create a started event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + */ + constructor(connection, command) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + // TODO: remove in major revision, this is not spec behavior + if (SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.databaseName = databaseName(command); + this.commandName = commandName; + this.command = maybeRedact(commandName, cmd, cmd); + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandStartedEvent = CommandStartedEvent; +/** + * An event indicating the success of a given command + * @public + * @category Event + */ +class CommandSucceededEvent { + /** + * Create a succeeded event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param reply - the reply for this command from the server + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(connection, command, reply, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = utils_1.calculateDurationInMs(started); + this.reply = maybeRedact(commandName, cmd, extractReply(command, reply)); + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandSucceededEvent = CommandSucceededEvent; +/** + * An event indicating the failure of a given command + * @public + * @category Event + */ +class CommandFailedEvent { + /** + * Create a failure event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param error - the generated error or a server error response + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(connection, command, error, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = utils_1.calculateDurationInMs(started); + this.failure = maybeRedact(commandName, cmd, error); + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandFailedEvent = CommandFailedEvent; +/** Commands that we want to redact because of the sensitive nature of their contents */ +const SENSITIVE_COMMANDS = new Set([ + 'authenticate', + 'saslStart', + 'saslContinue', + 'getnonce', + 'createUser', + 'updateUser', + 'copydbgetnonce', + 'copydbsaslstart', + 'copydb' +]); +const HELLO_COMMANDS = new Set(['hello', 'ismaster', 'isMaster']); +// helper methods +const extractCommandName = (commandDoc) => Object.keys(commandDoc)[0]; +const namespace = (command) => command.ns; +const databaseName = (command) => command.ns.split('.')[0]; +const collectionName = (command) => command.ns.split('.')[1]; +const maybeRedact = (commandName, commandDoc, result) => SENSITIVE_COMMANDS.has(commandName) || + (HELLO_COMMANDS.has(commandName) && commandDoc.speculativeAuthenticate) + ? {} + : result; +const LEGACY_FIND_QUERY_MAP = { + $query: 'filter', + $orderby: 'sort', + $hint: 'hint', + $comment: 'comment', + $maxScan: 'maxScan', + $max: 'max', + $min: 'min', + $returnKey: 'returnKey', + $showDiskLoc: 'showRecordId', + $maxTimeMS: 'maxTimeMS', + $snapshot: 'snapshot' +}; +const LEGACY_FIND_OPTIONS_MAP = { + numberToSkip: 'skip', + numberToReturn: 'batchSize', + returnFieldSelector: 'projection' +}; +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +]; +/** Extract the actual command from the query, possibly up-converting if it's a legacy format */ +function extractCommand(command) { + var _a; + if (command instanceof commands_1.GetMore) { + return { + getMore: utils_1.deepCopy(command.cursorId), + collection: collectionName(command), + batchSize: command.numberToReturn + }; + } + if (command instanceof commands_1.KillCursor) { + return { + killCursors: collectionName(command), + cursors: utils_1.deepCopy(command.cursorIds) + }; + } + if (command instanceof commands_1.Msg) { + return utils_1.deepCopy(command.command); + } + if ((_a = command.query) === null || _a === void 0 ? void 0 : _a.$query) { + let result; + if (command.ns === 'admin.$cmd') { + // up-convert legacy command + result = Object.assign({}, command.query.$query); + } + else { + // up-convert legacy find command + result = { find: collectionName(command) }; + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (command.query[key] != null) { + result[LEGACY_FIND_QUERY_MAP[key]] = utils_1.deepCopy(command.query[key]); + } + }); + } + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + const legacyKey = key; + if (command[legacyKey] != null) { + result[LEGACY_FIND_OPTIONS_MAP[legacyKey]] = utils_1.deepCopy(command[legacyKey]); + } + }); + OP_QUERY_KEYS.forEach(key => { + const opKey = key; + if (command[opKey]) { + result[opKey] = command[opKey]; + } + }); + if (command.pre32Limit != null) { + result.limit = command.pre32Limit; + } + if (command.query.$explain) { + return { explain: result }; + } + return result; + } + const clonedQuery = {}; + const clonedCommand = {}; + if (command.query) { + for (const k in command.query) { + clonedQuery[k] = utils_1.deepCopy(command.query[k]); + } + clonedCommand.query = clonedQuery; + } + for (const k in command) { + if (k === 'query') + continue; + clonedCommand[k] = utils_1.deepCopy(command[k]); + } + return command.query ? clonedQuery : clonedCommand; +} +function extractReply(command, reply) { + if (command instanceof commands_1.KillCursor) { + return { + ok: 1, + cursorsUnknown: command.cursorIds + }; + } + if (!reply) { + return reply; + } + if (command instanceof commands_1.GetMore) { + return { + ok: 1, + cursor: { + id: utils_1.deepCopy(reply.cursorId), + ns: namespace(command), + nextBatch: utils_1.deepCopy(reply.documents) + } + }; + } + if (command instanceof commands_1.Msg) { + return utils_1.deepCopy(reply.result ? reply.result : reply); + } + // is this a legacy find command? + if (command.query && command.query.$query != null) { + return { + ok: 1, + cursor: { + id: utils_1.deepCopy(reply.cursorId), + ns: namespace(command), + firstBatch: utils_1.deepCopy(reply.documents) + } + }; + } + return utils_1.deepCopy(reply.result ? reply.result : reply); +} +function extractConnectionDetails(connection) { + let connectionId; + if ('id' in connection) { + connectionId = connection.id; + } + return { + address: connection.address, + serviceId: connection.serviceId, + connectionId + }; +} +//# sourceMappingURL=command_monitoring_events.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map b/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map new file mode 100644 index 0000000..6b333f6 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"command_monitoring_events.js","sourceRoot":"","sources":["../../src/cmap/command_monitoring_events.ts"],"names":[],"mappings":";;;AAAA,yCAAgF;AAChF,oCAA2D;AAI3D;;;;GAIG;AACH,MAAa,mBAAmB;IAU9B;;;;;;OAMG;IACH,YAAY,UAAsB,EAAE,OAAiC;QACnE,MAAM,GAAG,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC;QACpC,MAAM,WAAW,GAAG,kBAAkB,CAAC,GAAG,CAAC,CAAC;QAC5C,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,GAAG,wBAAwB,CAAC,UAAU,CAAC,CAAC;QAElF,4DAA4D;QAC5D,IAAI,kBAAkB,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE;YACvC,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;YACrB,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC;SACrC;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;QAC1C,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC,WAAW,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;IACpD,CAAC;IAED,eAAe;IACf,IAAI,YAAY;QACd,OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC;IAC1B,CAAC;CACF;AAzCD,kDAyCC;AAED;;;;GAIG;AACH,MAAa,qBAAqB;IAShC;;;;;;;;OAQG;IACH,YACE,UAAsB,EACtB,OAAiC,EACjC,KAA2B,EAC3B,OAAe;QAEf,MAAM,GA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AC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;KACtD;IAED,iCAAiC;IACjC,IAAI,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,EAAE;QACjD,OAAO;YACL,EAAE,EAAE,CAAC;YACL,MAAM,EAAE;gBACN,EAAE,EAAE,gBAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAC5B,EAAE,EAAE,SAAS,CAAC,OAAO,CAAC;gBACtB,UAAU,EAAE,gBAAQ,CAAC,KAAK,CAAC,SAAS,CAAC;aACtC;SACF,CAAC;KACH;IAED,OAAO,gBAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AACvD,CAAC;AAED,SAAS,wBAAwB,CAAC,UAAsB;IACtD,IAAI,YAAY,CAAC;IACjB,IAAI,IAAI,IAAI,UAAU,EAAE;QACtB,YAAY,GAAG,UAAU,CAAC,EAAE,CAAC;KAC9B;IACD,OAAO;QACL,OAAO,EAAE,UAAU,CAAC,OAAO;QAC3B,SAAS,EAAE,UAAU,CAAC,SAAS;QAC/B,YAAY;KACb,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/commands.js b/node_modules/mongodb/lib/cmap/commands.js new file mode 100644 index 0000000..869b91b --- /dev/null +++ b/node_modules/mongodb/lib/cmap/commands.js @@ -0,0 +1,623 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BinMsg = exports.Msg = exports.Response = exports.KillCursor = exports.GetMore = exports.Query = void 0; +const read_preference_1 = require("../read_preference"); +const BSON = require("../bson"); +const utils_1 = require("../utils"); +const constants_1 = require("./wire_protocol/constants"); +const error_1 = require("../error"); +// Incrementing request id +let _requestId = 0; +// Query flags +const OPTS_TAILABLE_CURSOR = 2; +const OPTS_SLAVE = 4; +const OPTS_OPLOG_REPLAY = 8; +const OPTS_NO_CURSOR_TIMEOUT = 16; +const OPTS_AWAIT_DATA = 32; +const OPTS_EXHAUST = 64; +const OPTS_PARTIAL = 128; +// Response flags +const CURSOR_NOT_FOUND = 1; +const QUERY_FAILURE = 2; +const SHARD_CONFIG_STALE = 4; +const AWAIT_CAPABLE = 8; +/************************************************************** + * QUERY + **************************************************************/ +/** @internal */ +class Query { + constructor(ns, query, options) { + // Basic options needed to be passed in + // TODO(NODE-3483): Replace with MongoCommandError + if (ns == null) + throw new error_1.MongoRuntimeError('Namespace must be specified for query'); + // TODO(NODE-3483): Replace with MongoCommandError + if (query == null) + throw new error_1.MongoRuntimeError('A query document must be specified for query'); + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoRuntimeError('Namespace cannot contain a null character'); + } + // Basic options + this.ns = ns; + this.query = query; + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || undefined; + this.requestId = Query.getRequestId(); + // special case for pre-3.2 find commands, delete ASAP + this.pre32Limit = options.pre32Limit; + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.batchSize = this.numberToReturn; + // Flags + this.tailable = false; + this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; + } + /** Assign next request Id. */ + incRequestId() { + this.requestId = _requestId++; + } + /** Peek next request Id. */ + nextRequestId() { + return _requestId + 1; + } + /** Increment then return next request Id. */ + static getRequestId() { + return ++_requestId; + } + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin() { + const buffers = []; + let projection = null; + // Set up the flags + let flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + if (this.slaveOk) { + flags |= OPTS_SLAVE; + } + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + if (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + if (this.exhaust) { + flags |= OPTS_EXHAUST; + } + if (this.partial) { + flags |= OPTS_PARTIAL; + } + // If batchSize is different to this.numberToReturn + if (this.batchSize !== this.numberToReturn) + this.numberToReturn = this.batchSize; + // Allocate write protocol header buffer + const header = Buffer.alloc(4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(this.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn + ); + // Add header to buffers + buffers.push(header); + // Serialize the query + const query = BSON.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add query document + buffers.push(query); + if (this.returnFieldSelector && Object.keys(this.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = BSON.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add projection document + buffers.push(projection); + } + // Total message size + const totalLength = header.length + query.length + (projection ? projection.length : 0); + // Set up the index + let index = 4; + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = totalLength & 0xff; + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = this.requestId & 0xff; + index = index + 4; + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = 0 & 0xff; + index = index + 4; + // Write header information OP_QUERY + header[index + 3] = (constants_1.OP_QUERY >> 24) & 0xff; + header[index + 2] = (constants_1.OP_QUERY >> 16) & 0xff; + header[index + 1] = (constants_1.OP_QUERY >> 8) & 0xff; + header[index] = constants_1.OP_QUERY & 0xff; + index = index + 4; + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = flags & 0xff; + index = index + 4; + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = this.numberToSkip & 0xff; + index = index + 4; + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = this.numberToReturn & 0xff; + index = index + 4; + // Return the buffers + return buffers; + } +} +exports.Query = Query; +/************************************************************** + * GETMORE + **************************************************************/ +/** @internal */ +class GetMore { + constructor(ns, cursorId, opts = {}) { + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.ns = ns; + this.cursorId = cursorId; + } + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin() { + const length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; + // Create command buffer + let index = 0; + // Allocate buffer + const _buffer = Buffer.alloc(length); + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (constants_1.OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (constants_1.OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (constants_1.OP_GETMORE >> 8) & 0xff; + _buffer[index] = constants_1.OP_GETMORE & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = this.numberToReturn & 0xff; + index = index + 4; + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getLowBits() & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getHighBits() & 0xff; + index = index + 4; + // Return buffer + return [_buffer]; + } +} +exports.GetMore = GetMore; +/************************************************************** + * KILLCURSOR + **************************************************************/ +/** @internal */ +class KillCursor { + constructor(ns, cursorIds) { + this.ns = ns; + this.requestId = _requestId++; + this.cursorIds = cursorIds; + } + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin() { + const length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; + // Create command buffer + let index = 0; + const _buffer = Buffer.alloc(length); + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (constants_1.OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (constants_1.OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (constants_1.OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = constants_1.OP_KILL_CURSORS & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = this.cursorIds.length & 0xff; + index = index + 4; + // Write all the cursor ids into the array + for (let i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; + index = index + 4; + } + // Return buffer + return [_buffer]; + } +} +exports.KillCursor = KillCursor; +/** @internal */ +class Response { + constructor(message, msgHeader, msgBody, opts) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts !== null && opts !== void 0 ? opts : { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + // Read the message body + this.responseFlags = msgBody.readInt32LE(0); + this.cursorId = new BSON.Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); + this.startingFrom = msgBody.readInt32LE(12); + this.numberReturned = msgBody.readInt32LE(16); + // Preallocate document array + this.documents = new Array(this.numberReturned); + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + } + isParsed() { + return this.parsed; + } + parse(options) { + var _a, _b, _c, _d; + // Don't parse again if not needed + if (this.parsed) + return; + options = options !== null && options !== void 0 ? options : {}; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = (_a = options.promoteLongs) !== null && _a !== void 0 ? _a : this.opts.promoteLongs; + const promoteValues = (_b = options.promoteValues) !== null && _b !== void 0 ? _b : this.opts.promoteValues; + const promoteBuffers = (_c = options.promoteBuffers) !== null && _c !== void 0 ? _c : this.opts.promoteBuffers; + const bsonRegExp = (_d = options.bsonRegExp) !== null && _d !== void 0 ? _d : this.opts.bsonRegExp; + let bsonSize; + // Set up the options + const _options = { + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp + }; + // Position within OP_REPLY at which documents start + // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) + this.index = 20; + // Parse Body + for (let i = 0; i < this.numberReturned; i++) { + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + // If we have raw results specified slice the return document + if (raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } + else { + this.documents[i] = BSON.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); + } + // Adjust the index + this.index = this.index + bsonSize; + } + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + const doc = BSON.deserialize(this.documents[0], _options); + this.documents = [doc]; + } + // Set parsed + this.parsed = true; + } +} +exports.Response = Response; +// Implementation of OP_MSG spec: +// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst +// +// struct Section { +// uint8 payloadType; +// union payload { +// document document; // payloadType == 0 +// struct sequence { // payloadType == 1 +// int32 size; +// cstring identifier; +// document* documents; +// }; +// }; +// }; +// struct OP_MSG { +// struct MsgHeader { +// int32 messageLength; +// int32 requestID; +// int32 responseTo; +// int32 opCode = 2013; +// }; +// uint32 flagBits; +// Section+ sections; +// [uint32 checksum;] +// }; +// Msg Flags +const OPTS_CHECKSUM_PRESENT = 1; +const OPTS_MORE_TO_COME = 2; +const OPTS_EXHAUST_ALLOWED = 1 << 16; +/** @internal */ +class Msg { + constructor(ns, command, options) { + // Basic options needed to be passed in + if (command == null) + throw new error_1.MongoInvalidArgumentError('Query document must be specified for query'); + // Basic options + this.ns = ns; + this.command = command; + this.command.$db = utils_1.databaseNamespace(ns); + if (options.readPreference && options.readPreference.mode !== read_preference_1.ReadPreference.PRIMARY) { + this.command.$readPreference = options.readPreference.toJSON(); + } + // Ensure empty options + this.options = options !== null && options !== void 0 ? options : {}; + // Additional options + this.requestId = options.requestId ? options.requestId : Msg.getRequestId(); + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + // flags + this.checksumPresent = false; + this.moreToCome = options.moreToCome || false; + this.exhaustAllowed = + typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false; + } + toBin() { + const buffers = []; + let flags = 0; + if (this.checksumPresent) { + flags |= OPTS_CHECKSUM_PRESENT; + } + if (this.moreToCome) { + flags |= OPTS_MORE_TO_COME; + } + if (this.exhaustAllowed) { + flags |= OPTS_EXHAUST_ALLOWED; + } + const header = Buffer.alloc(4 * 4 + // Header + 4 // Flags + ); + buffers.push(header); + let totalLength = header.length; + const command = this.command; + totalLength += this.makeDocumentSegment(buffers, command); + header.writeInt32LE(totalLength, 0); // messageLength + header.writeInt32LE(this.requestId, 4); // requestID + header.writeInt32LE(0, 8); // responseTo + header.writeInt32LE(constants_1.OP_MSG, 12); // opCode + header.writeUInt32LE(flags, 16); // flags + return buffers; + } + makeDocumentSegment(buffers, document) { + const payloadTypeBuffer = Buffer.alloc(1); + payloadTypeBuffer[0] = 0; + const documentBuffer = this.serializeBson(document); + buffers.push(payloadTypeBuffer); + buffers.push(documentBuffer); + return payloadTypeBuffer.length + documentBuffer.length; + } + serializeBson(document) { + return BSON.serialize(document, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + } + static getRequestId() { + _requestId = (_requestId + 1) & 0x7fffffff; + return _requestId; + } +} +exports.Msg = Msg; +/** @internal */ +class BinMsg { + constructor(message, msgHeader, msgBody, opts) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts !== null && opts !== void 0 ? opts : { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + // Read response flags + this.responseFlags = msgBody.readInt32LE(0); + this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; + this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; + this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + this.documents = []; + } + isParsed() { + return this.parsed; + } + parse(options) { + var _a, _b, _c, _d; + // Don't parse again if not needed + if (this.parsed) + return; + options = options !== null && options !== void 0 ? options : {}; + this.index = 4; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = (_a = options.promoteLongs) !== null && _a !== void 0 ? _a : this.opts.promoteLongs; + const promoteValues = (_b = options.promoteValues) !== null && _b !== void 0 ? _b : this.opts.promoteValues; + const promoteBuffers = (_c = options.promoteBuffers) !== null && _c !== void 0 ? _c : this.opts.promoteBuffers; + const bsonRegExp = (_d = options.bsonRegExp) !== null && _d !== void 0 ? _d : this.opts.bsonRegExp; + // Set up the options + const _options = { + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp + }; + while (this.index < this.data.length) { + const payloadType = this.data.readUInt8(this.index++); + if (payloadType === 0) { + const bsonSize = this.data.readUInt32LE(this.index); + const bin = this.data.slice(this.index, this.index + bsonSize); + this.documents.push(raw ? bin : BSON.deserialize(bin, _options)); + this.index += bsonSize; + } + else if (payloadType === 1) { + // It was decided that no driver makes use of payload type 1 + // TODO(NODE-3483): Replace with MongoDeprecationError + throw new error_1.MongoRuntimeError('OP_MSG Payload Type 1 detected unsupported protocol'); + } + } + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + const doc = BSON.deserialize(this.documents[0], _options); + this.documents = [doc]; + } + this.parsed = true; + } +} +exports.BinMsg = BinMsg; +//# sourceMappingURL=commands.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/commands.js.map b/node_modules/mongodb/lib/cmap/commands.js.map new file mode 100644 index 0000000..0dc3cd1 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/commands.js.map @@ -0,0 +1 @@ +{"version":3,"file":"commands.js","sourceRoot":"","sources":["../../src/cmap/commands.ts"],"names":[],"mappings":";;;AAAA,wDAAoD;AACpD,gCAAgC;AAChC,oCAA6C;AAC7C,yDAA0F;AAI1F,oCAAwE;AAExE,0BAA0B;AAC1B,IAAI,UAAU,GAAG,CAAC,CAAC;AAEnB,cAAc;AACd,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,UAAU,GAAG,CAAC,CAAC;AACrB,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAClC,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,MAAM,YAAY,GAAG,EAAE,CAAC;AACxB,MAAM,YAAY,GAAG,GAAG,CAAC;AAEzB,iBAAiB;AACjB,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,aAAa,GAAG,CAAC,CAAC;AA0BxB;;gEAEgE;AAChE,gBAAgB;AAChB,MAAa,KAAK;IAsBhB,YAAY,EAAU,EAAE,KAAe,EAAE,OAAuB;QAC9D,uCAAuC;QACvC,kDAAkD;QAClD,IAAI,EAAE,IAAI,IAAI;YAAE,MAAM,IAAI,yBAAiB,CAAC,uCAAuC,CAAC,CAAC;QACrF,kDAAkD;QAClD,IAAI,KAAK,IAAI,IAAI;YAAE,MAAM,IAAI,yBAAiB,CAAC,8CAA8C,CAAC,CAAC;QAE/F,+DAA+D;QAC/D,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE;YAC7B,oDAAoD;YACpD,MAAM,IAAI,yBAAiB,CAAC,2CAA2C,CAAC,CAAC;SAC1E;QAED,gBAAgB;QAChB,IAAI,CAAC,EAAE,GAA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AAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBACpD,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC,CAAC;gBAC/D,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC;gBAEjE,IAAI,CAAC,KAAK,IAAI,QAAQ,CAAC;aACxB;iBAAM,IAAI,WAAW,KAAK,CAAC,EAAE;gBAC5B,4DAA4D;gBAE5D,sDAAsD;gBACtD,MAAM,IAAI,yBAAiB,CAAC,qDAAqD,CAAC,CAAC;aACpF;SACF;QAED,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,IAAI,mBAAmB,IAAI,IAAI,IAAI,GAAG,EAAE;YACrE,MAAM,WAAW,GAAa,EAAE,CAAC;YACjC,WAAW,CAAC,mBAAmB,CAAC,GAAG,IAAI,CAAC;YACxC,QAAQ,CAAC,WAAW,GAAG,WAAW,CAAC;YAEnC,MAAM,GAAG,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAW,EAAE,QAAQ,CAAC,CAAC;YACpE,IAAI,CAAC,SAAS,GAAG,CAAC,GAAG,CAAC,CAAC;SACxB;QAED,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;IACrB,CAAC;CACF;AAhHD,wBAgHC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/connect.js b/node_modules/mongodb/lib/cmap/connect.js new file mode 100644 index 0000000..eaacbde --- /dev/null +++ b/node_modules/mongodb/lib/cmap/connect.js @@ -0,0 +1,304 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LEGAL_TCP_SOCKET_OPTIONS = exports.LEGAL_TLS_SOCKET_OPTIONS = exports.connect = void 0; +const net = require("net"); +const tls = require("tls"); +const connection_1 = require("./connection"); +const error_1 = require("../error"); +const defaultAuthProviders_1 = require("./auth/defaultAuthProviders"); +const auth_provider_1 = require("./auth/auth_provider"); +const utils_1 = require("../utils"); +const constants_1 = require("./wire_protocol/constants"); +const bson_1 = require("../bson"); +const FAKE_MONGODB_SERVICE_ID = typeof process.env.FAKE_MONGODB_SERVICE_ID === 'string' && + process.env.FAKE_MONGODB_SERVICE_ID.toLowerCase() === 'true'; +function connect(options, callback) { + makeConnection(options, (err, socket) => { + var _a; + if (err || !socket) { + return callback(err); + } + let ConnectionType = (_a = options.connectionType) !== null && _a !== void 0 ? _a : connection_1.Connection; + if (options.autoEncrypter) { + ConnectionType = connection_1.CryptoConnection; + } + performInitialHandshake(new ConnectionType(socket, options), options, callback); + }); +} +exports.connect = connect; +function checkSupportedServer(ismaster, options) { + var _a; + const serverVersionHighEnough = ismaster && + (typeof ismaster.maxWireVersion === 'number' || ismaster.maxWireVersion instanceof bson_1.Int32) && + ismaster.maxWireVersion >= constants_1.MIN_SUPPORTED_WIRE_VERSION; + const serverVersionLowEnough = ismaster && + (typeof ismaster.minWireVersion === 'number' || ismaster.minWireVersion instanceof bson_1.Int32) && + ismaster.minWireVersion <= constants_1.MAX_SUPPORTED_WIRE_VERSION; + if (serverVersionHighEnough) { + if (serverVersionLowEnough) { + return null; + } + const message = `Server at ${options.hostAddress} reports minimum wire version ${JSON.stringify(ismaster.minWireVersion)}, but this version of the Node.js Driver requires at most ${constants_1.MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_1.MAX_SUPPORTED_SERVER_VERSION})`; + return new error_1.MongoCompatibilityError(message); + } + const message = `Server at ${options.hostAddress} reports maximum wire version ${(_a = JSON.stringify(ismaster.maxWireVersion)) !== null && _a !== void 0 ? _a : 0}, but this version of the Node.js Driver requires at least ${constants_1.MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_1.MIN_SUPPORTED_SERVER_VERSION})`; + return new error_1.MongoCompatibilityError(message); +} +function performInitialHandshake(conn, options, _callback) { + const callback = function (err, ret) { + if (err && conn) { + conn.destroy(); + } + _callback(err, ret); + }; + const credentials = options.credentials; + if (credentials) { + if (!(credentials.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_DEFAULT) && + !defaultAuthProviders_1.AUTH_PROVIDERS.get(credentials.mechanism)) { + callback(new error_1.MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`)); + return; + } + } + const authContext = new auth_provider_1.AuthContext(conn, credentials, options); + prepareHandshakeDocument(authContext, (err, handshakeDoc) => { + if (err || !handshakeDoc) { + return callback(err); + } + const handshakeOptions = Object.assign({}, options); + if (typeof options.connectTimeoutMS === 'number') { + // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS + handshakeOptions.socketTimeoutMS = options.connectTimeoutMS; + } + const start = new Date().getTime(); + conn.command(utils_1.ns('admin.$cmd'), handshakeDoc, handshakeOptions, (err, response) => { + if (err) { + callback(err); + return; + } + if ((response === null || response === void 0 ? void 0 : response.ok) === 0) { + callback(new error_1.MongoServerError(response)); + return; + } + if ('isWritablePrimary' in response) { + // Provide pre-hello-style response document. + response.ismaster = response.isWritablePrimary; + } + if (response.helloOk) { + conn.helloOk = true; + } + const supportedServerErr = checkSupportedServer(response, options); + if (supportedServerErr) { + callback(supportedServerErr); + return; + } + if (options.loadBalanced) { + // TODO: Durran: Remove when server support exists. (NODE-3431) + if (FAKE_MONGODB_SERVICE_ID) { + response.serviceId = response.topologyVersion.processId; + } + if (!response.serviceId) { + return callback(new error_1.MongoCompatibilityError('Driver attempted to initialize in load balancing mode, ' + + 'but the server does not support this mode.')); + } + } + // NOTE: This is metadata attached to the connection while porting away from + // handshake being done in the `Server` class. Likely, it should be + // relocated, or at very least restructured. + conn.ismaster = response; + conn.lastIsMasterMS = new Date().getTime() - start; + if (!response.arbiterOnly && credentials) { + // store the response on auth context + authContext.response = response; + const resolvedCredentials = credentials.resolveAuthMechanism(response); + const provider = defaultAuthProviders_1.AUTH_PROVIDERS.get(resolvedCredentials.mechanism); + if (!provider) { + return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${resolvedCredentials.mechanism} defined.`)); + } + provider.auth(authContext, err => { + if (err) + return callback(err); + callback(undefined, conn); + }); + return; + } + callback(undefined, conn); + }); + }); +} +function prepareHandshakeDocument(authContext, callback) { + const options = authContext.options; + const compressors = options.compressors ? options.compressors : []; + const { serverApi } = authContext.connection; + const handshakeDoc = { + [(serverApi === null || serverApi === void 0 ? void 0 : serverApi.version) ? 'hello' : 'ismaster']: true, + helloOk: true, + client: options.metadata || utils_1.makeClientMetadata(options), + compression: compressors, + loadBalanced: options.loadBalanced + }; + const credentials = authContext.credentials; + if (credentials) { + if (credentials.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_DEFAULT && credentials.username) { + handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`; + const provider = defaultAuthProviders_1.AUTH_PROVIDERS.get(defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256); + if (!provider) { + // This auth mechanism is always present. + return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`)); + } + return provider.prepare(handshakeDoc, authContext, callback); + } + const provider = defaultAuthProviders_1.AUTH_PROVIDERS.get(credentials.mechanism); + if (!provider) { + return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`)); + } + return provider.prepare(handshakeDoc, authContext, callback); + } + callback(undefined, handshakeDoc); +} +/** @public */ +exports.LEGAL_TLS_SOCKET_OPTIONS = [ + 'ALPNProtocols', + 'ca', + 'cert', + 'checkServerIdentity', + 'ciphers', + 'crl', + 'ecdhCurve', + 'key', + 'minDHSize', + 'passphrase', + 'pfx', + 'rejectUnauthorized', + 'secureContext', + 'secureProtocol', + 'servername', + 'session' +]; +/** @public */ +exports.LEGAL_TCP_SOCKET_OPTIONS = [ + 'family', + 'hints', + 'localAddress', + 'localPort', + 'lookup' +]; +function parseConnectOptions(options) { + const hostAddress = options.hostAddress; + if (!hostAddress) + throw new error_1.MongoInvalidArgumentError('Option "hostAddress" is required'); + const result = {}; + for (const name of exports.LEGAL_TCP_SOCKET_OPTIONS) { + if (options[name] != null) { + result[name] = options[name]; + } + } + if (typeof hostAddress.socketPath === 'string') { + result.path = hostAddress.socketPath; + return result; + } + else if (typeof hostAddress.host === 'string') { + result.host = hostAddress.host; + result.port = hostAddress.port; + return result; + } + else { + // This should never happen since we set up HostAddresses + // But if we don't throw here the socket could hang until timeout + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(hostAddress)}`); + } +} +function parseSslOptions(options) { + const result = parseConnectOptions(options); + // Merge in valid SSL options + for (const name of exports.LEGAL_TLS_SOCKET_OPTIONS) { + if (options[name] != null) { + result[name] = options[name]; + } + } + // Set default sni servername to be the same as host + if (result.servername == null && result.host && !net.isIP(result.host)) { + result.servername = result.host; + } + return result; +} +const SOCKET_ERROR_EVENT_LIST = ['error', 'close', 'timeout', 'parseError']; +const SOCKET_ERROR_EVENTS = new Set(SOCKET_ERROR_EVENT_LIST); +function makeConnection(options, _callback) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + const useTLS = (_a = options.tls) !== null && _a !== void 0 ? _a : false; + const keepAlive = (_b = options.keepAlive) !== null && _b !== void 0 ? _b : true; + const socketTimeoutMS = (_d = (_c = options.socketTimeoutMS) !== null && _c !== void 0 ? _c : Reflect.get(options, 'socketTimeout')) !== null && _d !== void 0 ? _d : 0; + const noDelay = (_e = options.noDelay) !== null && _e !== void 0 ? _e : true; + const connectionTimeout = (_f = options.connectTimeoutMS) !== null && _f !== void 0 ? _f : 30000; + const rejectUnauthorized = (_g = options.rejectUnauthorized) !== null && _g !== void 0 ? _g : true; + const keepAliveInitialDelay = (_j = (((_h = options.keepAliveInitialDelay) !== null && _h !== void 0 ? _h : 120000) > socketTimeoutMS + ? Math.round(socketTimeoutMS / 2) + : options.keepAliveInitialDelay)) !== null && _j !== void 0 ? _j : 120000; + let socket; + const callback = function (err, ret) { + if (err && socket) { + socket.destroy(); + } + _callback(err, ret); + }; + if (useTLS) { + const tlsSocket = tls.connect(parseSslOptions(options)); + if (typeof tlsSocket.disableRenegotiation === 'function') { + tlsSocket.disableRenegotiation(); + } + socket = tlsSocket; + } + else { + socket = net.createConnection(parseConnectOptions(options)); + } + socket.setKeepAlive(keepAlive, keepAliveInitialDelay); + socket.setTimeout(connectionTimeout); + socket.setNoDelay(noDelay); + const connectEvent = useTLS ? 'secureConnect' : 'connect'; + let cancellationHandler; + function errorHandler(eventName) { + return (err) => { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler && options.cancellationToken) { + options.cancellationToken.removeListener('cancel', cancellationHandler); + } + socket.removeListener(connectEvent, connectHandler); + callback(connectionFailureError(eventName, err)); + }; + } + function connectHandler() { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler && options.cancellationToken) { + options.cancellationToken.removeListener('cancel', cancellationHandler); + } + if ('authorizationError' in socket) { + if (socket.authorizationError && rejectUnauthorized) { + return callback(socket.authorizationError); + } + } + socket.setTimeout(socketTimeoutMS); + callback(undefined, socket); + } + SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event))); + if (options.cancellationToken) { + cancellationHandler = errorHandler('cancel'); + options.cancellationToken.once('cancel', cancellationHandler); + } + socket.once(connectEvent, connectHandler); +} +function connectionFailureError(type, err) { + switch (type) { + case 'error': + return new error_1.MongoNetworkError(err); + case 'timeout': + return new error_1.MongoNetworkTimeoutError('connection timed out'); + case 'close': + return new error_1.MongoNetworkError('connection closed'); + case 'cancel': + return new error_1.MongoNetworkError('connection establishment was cancelled'); + default: + return new error_1.MongoNetworkError('unknown network error'); + } +} +//# sourceMappingURL=connect.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/connect.js.map b/node_modules/mongodb/lib/cmap/connect.js.map new file mode 100644 index 0000000..dbee3c2 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/connect.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connect.js","sourceRoot":"","sources":["../../src/cmap/connect.ts"],"names":[],"mappings":";;;AAAA,2BAA2B;AAC3B,2BAA2B;AAC3B,6CAA+E;AAC/E,oCAQkB;AAClB,sEAA4E;AAC5E,wDAAmD;AACnD,oCAA8F;AAC9F,yDAKmC;AAEnC,kCAAgC;AAKhC,MAAM,uBAAuB,GAC3B,OAAO,OAAO,CAAC,GAAG,CAAC,uBAAuB,KAAK,QAAQ;IACvD,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC;AAK/D,SAAgB,OAAO,CAAC,OAA0B,EAAE,QAA8B;IAChF,cAAc,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;;QACtC,IAAI,GAAG,IAAI,CAAC,MAAM,EAAE;YAClB,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;SACtB;QAED,IAAI,cAAc,GAAG,MAAA,OAAO,CAAC,cAAc,mCAAI,uBAAU,CAAC;QAC1D,IAAI,OAAO,CAAC,aAAa,EAAE;YACzB,cAAc,GAAG,6BAAgB,CAAC;SACnC;QACD,uBAAuB,CAAC,IAAI,cAAc,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAClF,CAAC,CAAC,CAAC;AACL,CAAC;AAZD,0BAYC;AAED,SAAS,oBAAoB,CAAC,QAAkB,EAAE,OAA0B;;IAC1E,MAAM,uBAAuB,GAC3B,QAAQ;QACR,CAAC,OAAO,QAAQ,CAAC,cAAc,KAAK,QAAQ,IAAI,QAAQ,CAAC,cAAc,YAAY,YAAK,CAAC;QACzF,QAAQ,CAAC,cAAc,IAAI,s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,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9E,IAAI,OAAO,CAAC,iBAAiB,EAAE;QAC7B,mBAAmB,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;QAC7C,OAAO,CAAC,iBAAiB,CAAC,IAAI,CAAC,QAAQ,EAAE,mBAAmB,CAAC,CAAC;KAC/D;IAED,MAAM,CAAC,IAAI,CAAC,YAAY,EAAE,cAAc,CAAC,CAAC;AAC5C,CAAC;AAED,SAAS,sBAAsB,CAAC,IAAY,EAAE,GAAU;IACtD,QAAQ,IAAI,EAAE;QACZ,KAAK,OAAO;YACV,OAAO,IAAI,yBAAiB,CAAC,GAAG,CAAC,CAAC;QACpC,KAAK,SAAS;YACZ,OAAO,IAAI,gCAAwB,CAAC,sBAAsB,CAAC,CAAC;QAC9D,KAAK,OAAO;YACV,OAAO,IAAI,yBAAiB,CAAC,mBAAmB,CAAC,CAAC;QACpD,KAAK,QAAQ;YACX,OAAO,IAAI,yBAAiB,CAAC,wCAAwC,CAAC,CAAC;QACzE;YACE,OAAO,IAAI,yBAAiB,CAAC,uBAAuB,CAAC,CAAC;KACzD;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/connection.js b/node_modules/mongodb/lib/cmap/connection.js new file mode 100644 index 0000000..bd4e0d9 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/connection.js @@ -0,0 +1,557 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasSessionSupport = exports.CryptoConnection = exports.APM_EVENTS = exports.Connection = void 0; +const message_stream_1 = require("./message_stream"); +const stream_description_1 = require("./stream_description"); +const command_monitoring_events_1 = require("./command_monitoring_events"); +const sessions_1 = require("../sessions"); +const utils_1 = require("../utils"); +const error_1 = require("../error"); +const commands_1 = require("./commands"); +const bson_1 = require("../bson"); +const shared_1 = require("./wire_protocol/shared"); +const read_preference_1 = require("../read_preference"); +const mongo_types_1 = require("../mongo_types"); +/** @internal */ +const kStream = Symbol('stream'); +/** @internal */ +const kQueue = Symbol('queue'); +/** @internal */ +const kMessageStream = Symbol('messageStream'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kLastUseTime = Symbol('lastUseTime'); +/** @internal */ +const kClusterTime = Symbol('clusterTime'); +/** @internal */ +const kDescription = Symbol('description'); +/** @internal */ +const kIsMaster = Symbol('ismaster'); +/** @internal */ +const kAutoEncrypter = Symbol('autoEncrypter'); +/** @internal */ +const kFullResult = Symbol('fullResult'); +/** @internal */ +class Connection extends mongo_types_1.TypedEventEmitter { + constructor(stream, options) { + var _a, _b; + super(); + this.id = options.id; + this.address = streamIdentifier(stream); + this.socketTimeoutMS = (_a = options.socketTimeoutMS) !== null && _a !== void 0 ? _a : 0; + this.monitorCommands = options.monitorCommands; + this.serverApi = options.serverApi; + this.closed = false; + this.destroyed = false; + this[kDescription] = new stream_description_1.StreamDescription(this.address, options); + this[kGeneration] = options.generation; + this[kLastUseTime] = utils_1.now(); + // setup parser stream and message handling + this[kQueue] = new Map(); + this[kMessageStream] = new message_stream_1.MessageStream({ + ...options, + maxBsonMessageSize: (_b = this.ismaster) === null || _b === void 0 ? void 0 : _b.maxBsonMessageSize + }); + this[kMessageStream].on('message', messageHandler(this)); + this[kStream] = stream; + stream.on('error', () => { + /* ignore errors, listen to `close` instead */ + }); + this[kMessageStream].on('error', error => this.handleIssue({ destroy: error })); + stream.on('close', () => this.handleIssue({ isClose: true })); + stream.on('timeout', () => this.handleIssue({ isTimeout: true, destroy: true })); + // hook the message stream up to the passed in stream + stream.pipe(this[kMessageStream]); + this[kMessageStream].pipe(stream); + } + get description() { + return this[kDescription]; + } + get ismaster() { + return this[kIsMaster]; + } + // the `connect` method stores the result of the handshake ismaster on the connection + set ismaster(response) { + this[kDescription].receiveResponse(response); + this[kDescription] = Object.freeze(this[kDescription]); + // TODO: remove this, and only use the `StreamDescription` in the future + this[kIsMaster] = response; + } + get serviceId() { + var _a; + return (_a = this.ismaster) === null || _a === void 0 ? void 0 : _a.serviceId; + } + get loadBalanced() { + return this.description.loadBalanced; + } + get generation() { + return this[kGeneration] || 0; + } + set generation(generation) { + this[kGeneration] = generation; + } + get idleTime() { + return utils_1.calculateDurationInMs(this[kLastUseTime]); + } + get clusterTime() { + return this[kClusterTime]; + } + get stream() { + return this[kStream]; + } + markAvailable() { + this[kLastUseTime] = utils_1.now(); + } + handleIssue(issue) { + if (this.closed) { + return; + } + if (issue.destroy) { + this[kStream].destroy(typeof issue.destroy === 'boolean' ? undefined : issue.destroy); + } + this.closed = true; + for (const [, op] of this[kQueue]) { + if (issue.isTimeout) { + op.cb(new error_1.MongoNetworkTimeoutError(`connection ${this.id} to ${this.address} timed out`, { + beforeHandshake: this.ismaster == null + })); + } + else if (issue.isClose) { + op.cb(new error_1.MongoNetworkError(`connection ${this.id} to ${this.address} closed`)); + } + else { + op.cb(typeof issue.destroy === 'boolean' ? undefined : issue.destroy); + } + } + this[kQueue].clear(); + this.emit(Connection.CLOSE); + } + destroy(options, callback) { + if (typeof options === 'function') { + callback = options; + options = { force: false }; + } + this.removeAllListeners(Connection.PINNED); + this.removeAllListeners(Connection.UNPINNED); + options = Object.assign({ force: false }, options); + if (this[kStream] == null || this.destroyed) { + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + return; + } + if (options.force) { + this[kStream].destroy(); + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + return; + } + this[kStream].end(() => { + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + }); + } + /** @internal */ + command(ns, cmd, options, callback) { + if (!(ns instanceof utils_1.MongoDBNamespace)) { + // TODO(NODE-3483): Replace this with a MongoCommandError + throw new error_1.MongoRuntimeError('Must provide a MongoDBNamespace instance'); + } + const readPreference = shared_1.getReadPreference(cmd, options); + const shouldUseOpMsg = supportsOpMsg(this); + const session = options === null || options === void 0 ? void 0 : options.session; + let clusterTime = this.clusterTime; + let finalCmd = Object.assign({}, cmd); + if (this.serverApi) { + const { version, strict, deprecationErrors } = this.serverApi; + finalCmd.apiVersion = version; + if (strict != null) + finalCmd.apiStrict = strict; + if (deprecationErrors != null) + finalCmd.apiDeprecationErrors = deprecationErrors; + } + if (hasSessionSupport(this) && session) { + if (session.clusterTime && + clusterTime && + session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)) { + clusterTime = session.clusterTime; + } + const err = sessions_1.applySession(session, finalCmd, options); + if (err) { + return callback(err); + } + } + // if we have a known cluster time, gossip it + if (clusterTime) { + finalCmd.$clusterTime = clusterTime; + } + if (shared_1.isSharded(this) && !shouldUseOpMsg && readPreference && readPreference.mode !== 'primary') { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; + } + const commandOptions = Object.assign({ + command: true, + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false, + // This value is not overridable + slaveOk: readPreference.slaveOk() + }, options); + const cmdNs = `${ns.db}.$cmd`; + const message = shouldUseOpMsg + ? new commands_1.Msg(cmdNs, finalCmd, commandOptions) + : new commands_1.Query(cmdNs, finalCmd, commandOptions); + try { + write(this, message, commandOptions, callback); + } + catch (err) { + callback(err); + } + } + /** @internal */ + query(ns, cmd, options, callback) { + var _a; + const isExplain = cmd.$explain != null; + const readPreference = (_a = options.readPreference) !== null && _a !== void 0 ? _a : read_preference_1.ReadPreference.primary; + const batchSize = options.batchSize || 0; + const limit = options.limit; + const numberToSkip = options.skip || 0; + let numberToReturn = 0; + if (limit && + (limit < 0 || (limit !== 0 && limit < batchSize) || (limit > 0 && batchSize === 0))) { + numberToReturn = limit; + } + else { + numberToReturn = batchSize; + } + if (isExplain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(limit || 0); + } + const queryOptions = { + numberToSkip, + numberToReturn, + pre32Limit: typeof limit === 'number' ? limit : undefined, + checkKeys: false, + slaveOk: readPreference.slaveOk() + }; + if (options.projection) { + queryOptions.returnFieldSelector = options.projection; + } + const query = new commands_1.Query(ns.toString(), cmd, queryOptions); + if (typeof options.tailable === 'boolean') { + query.tailable = options.tailable; + } + if (typeof options.oplogReplay === 'boolean') { + query.oplogReplay = options.oplogReplay; + } + if (typeof options.timeout === 'boolean') { + query.noCursorTimeout = !options.timeout; + } + else if (typeof options.noCursorTimeout === 'boolean') { + query.noCursorTimeout = options.noCursorTimeout; + } + if (typeof options.awaitData === 'boolean') { + query.awaitData = options.awaitData; + } + if (typeof options.partial === 'boolean') { + query.partial = options.partial; + } + write(this, query, { [kFullResult]: true, ...bson_1.pluckBSONSerializeOptions(options) }, (err, result) => { + if (err || !result) + return callback(err, result); + if (isExplain && result.documents && result.documents[0]) { + return callback(undefined, result.documents[0]); + } + callback(undefined, result); + }); + } + /** @internal */ + getMore(ns, cursorId, options, callback) { + const fullResult = !!options[kFullResult]; + const wireVersion = utils_1.maxWireVersion(this); + if (!cursorId) { + // TODO(NODE-3483): Replace this with a MongoCommandError + callback(new error_1.MongoRuntimeError('Invalid internal cursor state, no known cursor id')); + return; + } + if (wireVersion < 4) { + const getMoreOp = new commands_1.GetMore(ns.toString(), cursorId, { numberToReturn: options.batchSize }); + const queryOptions = shared_1.applyCommonQueryOptions({}, Object.assign(options, { ...bson_1.pluckBSONSerializeOptions(options) })); + queryOptions[kFullResult] = true; + queryOptions.command = true; + write(this, getMoreOp, queryOptions, (err, response) => { + if (fullResult) + return callback(err, response); + if (err) + return callback(err); + callback(undefined, { cursor: { id: response.cursorId, nextBatch: response.documents } }); + }); + return; + } + const getMoreCmd = { + getMore: cursorId, + collection: ns.collection + }; + if (typeof options.batchSize === 'number') { + getMoreCmd.batchSize = Math.abs(options.batchSize); + } + if (typeof options.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = options.maxAwaitTimeMS; + } + const commandOptions = Object.assign({ + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch' + }, options); + this.command(ns, getMoreCmd, commandOptions, callback); + } + /** @internal */ + killCursors(ns, cursorIds, options, callback) { + if (!cursorIds || !Array.isArray(cursorIds)) { + // TODO(NODE-3483): Replace this with a MongoCommandError + throw new error_1.MongoRuntimeError(`Invalid list of cursor ids provided: ${cursorIds}`); + } + if (utils_1.maxWireVersion(this) < 4) { + try { + write(this, new commands_1.KillCursor(ns.toString(), cursorIds), { noResponse: true, ...options }, callback); + } + catch (err) { + callback(err); + } + return; + } + this.command(ns, { killCursors: ns.collection, cursors: cursorIds }, { [kFullResult]: true, ...options }, (err, response) => { + if (err || !response) + return callback(err); + if (response.cursorNotFound) { + return callback(new error_1.MongoNetworkError('cursor killed or timed out'), null); + } + if (!Array.isArray(response.documents) || response.documents.length === 0) { + return callback( + // TODO(NODE-3483) + new error_1.MongoRuntimeError(`invalid killCursors result returned for cursor id ${cursorIds[0]}`)); + } + callback(undefined, response.documents[0]); + }); + } +} +exports.Connection = Connection; +/** @event */ +Connection.COMMAND_STARTED = 'commandStarted'; +/** @event */ +Connection.COMMAND_SUCCEEDED = 'commandSucceeded'; +/** @event */ +Connection.COMMAND_FAILED = 'commandFailed'; +/** @event */ +Connection.CLUSTER_TIME_RECEIVED = 'clusterTimeReceived'; +/** @event */ +Connection.CLOSE = 'close'; +/** @event */ +Connection.MESSAGE = 'message'; +/** @event */ +Connection.PINNED = 'pinned'; +/** @event */ +Connection.UNPINNED = 'unpinned'; +/** @public */ +exports.APM_EVENTS = [ + Connection.COMMAND_STARTED, + Connection.COMMAND_SUCCEEDED, + Connection.COMMAND_FAILED +]; +/** @internal */ +class CryptoConnection extends Connection { + constructor(stream, options) { + super(stream, options); + this[kAutoEncrypter] = options.autoEncrypter; + } + /** @internal @override */ + command(ns, cmd, options, callback) { + const autoEncrypter = this[kAutoEncrypter]; + if (!autoEncrypter) { + return callback(new error_1.MongoMissingDependencyError('No AutoEncrypter available for encryption')); + } + const serverWireVersion = utils_1.maxWireVersion(this); + if (serverWireVersion === 0) { + // This means the initial handshake hasn't happened yet + return super.command(ns, cmd, options, callback); + } + if (serverWireVersion < 8) { + callback(new error_1.MongoCompatibilityError('Auto-encryption requires a minimum MongoDB version of 4.2')); + return; + } + autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => { + if (err || encrypted == null) { + callback(err, null); + return; + } + super.command(ns, encrypted, options, (err, response) => { + if (err || response == null) { + callback(err, response); + return; + } + autoEncrypter.decrypt(response, options, callback); + }); + }); + } +} +exports.CryptoConnection = CryptoConnection; +/** @internal */ +function hasSessionSupport(conn) { + const description = conn.description; + return description.logicalSessionTimeoutMinutes != null || !!description.loadBalanced; +} +exports.hasSessionSupport = hasSessionSupport; +function supportsOpMsg(conn) { + const description = conn.description; + if (description == null) { + return false; + } + return utils_1.maxWireVersion(conn) >= 6 && !description.__nodejs_mock_server__; +} +function messageHandler(conn) { + return function messageHandler(message) { + // always emit the message, in case we are streaming + conn.emit('message', message); + const operationDescription = conn[kQueue].get(message.responseTo); + if (!operationDescription) { + return; + } + const callback = operationDescription.cb; + // SERVER-45775: For exhaust responses we should be able to use the same requestId to + // track response, however the server currently synthetically produces remote requests + // making the `responseTo` change on each response + conn[kQueue].delete(message.responseTo); + if ('moreToCome' in message && message.moreToCome) { + // requeue the callback for next synthetic request + conn[kQueue].set(message.requestId, operationDescription); + } + else if (operationDescription.socketTimeoutOverride) { + conn[kStream].setTimeout(conn.socketTimeoutMS); + } + try { + // Pass in the entire description because it has BSON parsing options + message.parse(operationDescription); + } + catch (err) { + // If this error is generated by our own code, it will already have the correct class applied + // if it is not, then it is coming from a catastrophic data parse failure or the BSON library + // in either case, it should not be wrapped + callback(err); + return; + } + if (message.documents[0]) { + const document = message.documents[0]; + const session = operationDescription.session; + if (session) { + sessions_1.updateSessionFromResponse(session, document); + } + if (document.$clusterTime) { + conn[kClusterTime] = document.$clusterTime; + conn.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime); + } + if (operationDescription.command) { + if (document.writeConcernError) { + callback(new error_1.MongoWriteConcernError(document.writeConcernError, document)); + return; + } + if (document.ok === 0 || document.$err || document.errmsg || document.code) { + callback(new error_1.MongoServerError(document)); + return; + } + } + else { + // Pre 3.2 support + if (document.ok === 0 || document.$err || document.errmsg) { + callback(new error_1.MongoServerError(document)); + return; + } + } + } + callback(undefined, operationDescription.fullResult ? message : message.documents[0]); + }; +} +function streamIdentifier(stream) { + if (typeof stream.address === 'function') { + return `${stream.remoteAddress}:${stream.remotePort}`; + } + return utils_1.uuidV4().toString('hex'); +} +function write(conn, command, options, callback) { + if (typeof options === 'function') { + callback = options; + } + options = options !== null && options !== void 0 ? options : {}; + const operationDescription = { + requestId: command.requestId, + cb: callback, + session: options.session, + fullResult: !!options[kFullResult], + noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false, + documentsReturnedIn: options.documentsReturnedIn, + command: !!options.command, + // for BSON parsing + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false, + raw: typeof options.raw === 'boolean' ? options.raw : false, + started: 0 + }; + if (conn[kDescription] && conn[kDescription].compressor) { + operationDescription.agreedCompressor = conn[kDescription].compressor; + if (conn[kDescription].zlibCompressionLevel) { + operationDescription.zlibCompressionLevel = conn[kDescription].zlibCompressionLevel; + } + } + if (typeof options.socketTimeoutMS === 'number') { + operationDescription.socketTimeoutOverride = true; + conn[kStream].setTimeout(options.socketTimeoutMS); + } + // if command monitoring is enabled we need to modify the callback here + if (conn.monitorCommands) { + conn.emit(Connection.COMMAND_STARTED, new command_monitoring_events_1.CommandStartedEvent(conn, command)); + operationDescription.started = utils_1.now(); + operationDescription.cb = (err, reply) => { + if (err) { + conn.emit(Connection.COMMAND_FAILED, new command_monitoring_events_1.CommandFailedEvent(conn, command, err, operationDescription.started)); + } + else { + if (reply && (reply.ok === 0 || reply.$err)) { + conn.emit(Connection.COMMAND_FAILED, new command_monitoring_events_1.CommandFailedEvent(conn, command, reply, operationDescription.started)); + } + else { + conn.emit(Connection.COMMAND_SUCCEEDED, new command_monitoring_events_1.CommandSucceededEvent(conn, command, reply, operationDescription.started)); + } + } + if (typeof callback === 'function') { + callback(err, reply); + } + }; + } + if (!operationDescription.noResponse) { + conn[kQueue].set(operationDescription.requestId, operationDescription); + } + try { + conn[kMessageStream].writeCommand(command, operationDescription); + } + catch (e) { + if (!operationDescription.noResponse) { + conn[kQueue].delete(operationDescription.requestId); + operationDescription.cb(e); + return; + } + } + if (operationDescription.noResponse) { + operationDescription.cb(); + } +} +//# sourceMappingURL=connection.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/connection.js.map b/node_modules/mongodb/lib/cmap/connection.js.map new file mode 100644 index 0000000..a8a214a --- /dev/null +++ b/node_modules/mongodb/lib/cmap/connection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection.js","sourceRoot":"","sources":["../../src/cmap/connection.ts"],"names":[],"mappings":";;;AAAA,qDAAuE;AACvE,6DAAmF;AACnF,2EAIqC;AACrC,0CAAqF;AACrF,oCASkB;AAClB,oCAQkB;AAClB,yCASoB;AACpB,kCAAoG;AAIpG,mDAA+F;AAC/F,wDAAwE;AAGxE,gDAAsE;AAEtE,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AAC/B,gBAAgB;AAChB,MAAM,cAAc,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;AAC/C,gBAAgB;AAChB,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AACzC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAA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BAAoB,CAAC,UAAU,EAAE;QACnC,oBAAoB,CAAC,EAAE,EAAE,CAAC;KAC3B;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/connection_pool.js b/node_modules/mongodb/lib/cmap/connection_pool.js new file mode 100644 index 0000000..85ffb9a --- /dev/null +++ b/node_modules/mongodb/lib/cmap/connection_pool.js @@ -0,0 +1,495 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CMAP_EVENTS = exports.ConnectionPool = void 0; +const Denque = require("denque"); +const connection_1 = require("./connection"); +const logger_1 = require("../logger"); +const metrics_1 = require("./metrics"); +const connect_1 = require("./connect"); +const utils_1 = require("../utils"); +const error_1 = require("../error"); +const errors_1 = require("./errors"); +const connection_pool_events_1 = require("./connection_pool_events"); +const mongo_types_1 = require("../mongo_types"); +/** @internal */ +const kLogger = Symbol('logger'); +/** @internal */ +const kConnections = Symbol('connections'); +/** @internal */ +const kPermits = Symbol('permits'); +/** @internal */ +const kMinPoolSizeTimer = Symbol('minPoolSizeTimer'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kServiceGenerations = Symbol('serviceGenerations'); +/** @internal */ +const kConnectionCounter = Symbol('connectionCounter'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kMetrics = Symbol('metrics'); +/** @internal */ +const kCheckedOut = Symbol('checkedOut'); +/** @internal */ +const kProcessingWaitQueue = Symbol('processingWaitQueue'); +/** + * A pool of connections which dynamically resizes, and emit events related to pool activity + * @internal + */ +class ConnectionPool extends mongo_types_1.TypedEventEmitter { + /** @internal */ + constructor(options) { + var _a, _b, _c, _d; + super(); + this.closed = false; + this.options = Object.freeze({ + ...options, + connectionType: connection_1.Connection, + maxPoolSize: (_a = options.maxPoolSize) !== null && _a !== void 0 ? _a : 100, + minPoolSize: (_b = options.minPoolSize) !== null && _b !== void 0 ? _b : 0, + maxIdleTimeMS: (_c = options.maxIdleTimeMS) !== null && _c !== void 0 ? _c : 0, + waitQueueTimeoutMS: (_d = options.waitQueueTimeoutMS) !== null && _d !== void 0 ? _d : 0, + autoEncrypter: options.autoEncrypter, + metadata: options.metadata + }); + if (this.options.minPoolSize > this.options.maxPoolSize) { + throw new error_1.MongoInvalidArgumentError('Connection pool minimum size must not be greater than maximum pool size'); + } + this[kLogger] = new logger_1.Logger('ConnectionPool'); + this[kConnections] = new Denque(); + this[kPermits] = this.options.maxPoolSize; + this[kMinPoolSizeTimer] = undefined; + this[kGeneration] = 0; + this[kServiceGenerations] = new Map(); + this[kConnectionCounter] = utils_1.makeCounter(1); + this[kCancellationToken] = new mongo_types_1.CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kWaitQueue] = new Denque(); + this[kMetrics] = new metrics_1.ConnectionPoolMetrics(); + this[kCheckedOut] = 0; + this[kProcessingWaitQueue] = false; + process.nextTick(() => { + this.emit(ConnectionPool.CONNECTION_POOL_CREATED, new connection_pool_events_1.ConnectionPoolCreatedEvent(this)); + ensureMinPoolSize(this); + }); + } + /** The address of the endpoint the pool is connected to */ + get address() { + return this.options.hostAddress.toString(); + } + /** An integer representing the SDAM generation of the pool */ + get generation() { + return this[kGeneration]; + } + /** An integer expressing how many total connections (active + in use) the pool currently has */ + get totalConnectionCount() { + return this[kConnections].length + (this.options.maxPoolSize - this[kPermits]); + } + /** An integer expressing how many connections are currently available in the pool. */ + get availableConnectionCount() { + return this[kConnections].length; + } + get waitQueueSize() { + return this[kWaitQueue].length; + } + get loadBalanced() { + return this.options.loadBalanced; + } + get serviceGenerations() { + return this[kServiceGenerations]; + } + get currentCheckedOutCount() { + return this[kCheckedOut]; + } + /** + * Get the metrics information for the pool when a wait queue timeout occurs. + */ + waitQueueErrorMetrics() { + return this[kMetrics].info(this.options.maxPoolSize); + } + /** + * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it + * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or + * explicitly destroyed by the new owner. + */ + checkOut(callback) { + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_STARTED, new connection_pool_events_1.ConnectionCheckOutStartedEvent(this)); + if (this.closed) { + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'poolClosed')); + callback(new errors_1.PoolClosedError(this)); + return; + } + const waitQueueMember = { callback }; + const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; + if (waitQueueTimeoutMS) { + waitQueueMember.timer = setTimeout(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'timeout')); + waitQueueMember.callback(new errors_1.WaitQueueTimeoutError(this.loadBalanced + ? this.waitQueueErrorMetrics() + : 'Timed out while checking out a connection from connection pool', this.address)); + }, waitQueueTimeoutMS); + } + this[kCheckedOut] = this[kCheckedOut] + 1; + this[kWaitQueue].push(waitQueueMember); + process.nextTick(processWaitQueue, this); + } + /** + * Check a connection into the pool. + * + * @param connection - The connection to check in + */ + checkIn(connection) { + const poolClosed = this.closed; + const stale = connectionIsStale(this, connection); + const willDestroy = !!(poolClosed || stale || connection.closed); + if (!willDestroy) { + connection.markAvailable(); + this[kConnections].unshift(connection); + } + this[kCheckedOut] = this[kCheckedOut] - 1; + this.emit(ConnectionPool.CONNECTION_CHECKED_IN, new connection_pool_events_1.ConnectionCheckedInEvent(this, connection)); + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + destroyConnection(this, connection, reason); + } + process.nextTick(processWaitQueue, this); + } + /** + * Clear the pool + * + * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a + * previous generation will eventually be pruned during subsequent checkouts. + */ + clear(serviceId) { + if (this.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + // Only need to worry if the generation exists, since it should + // always be there but typescript needs the check. + if (generation == null) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('Service generations are required in load balancer mode.'); + } + else { + // Increment the generation for the service id. + this.serviceGenerations.set(sid, generation + 1); + } + } + else { + this[kGeneration] += 1; + } + this.emit('connectionPoolCleared', new connection_pool_events_1.ConnectionPoolClearedEvent(this, serviceId)); + } + close(_options, _cb) { + let options = _options; + const callback = (_cb !== null && _cb !== void 0 ? _cb : _options); + if (typeof options === 'function') { + options = {}; + } + options = Object.assign({ force: false }, options); + if (this.closed) { + return callback(); + } + // immediately cancel any in-flight connections + this[kCancellationToken].emit('cancel'); + // drain the wait queue + while (this.waitQueueSize) { + const waitQueueMember = this[kWaitQueue].pop(); + if (waitQueueMember) { + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + if (!waitQueueMember[kCancelled]) { + // TODO(NODE-3483): Replace with MongoConnectionPoolClosedError + waitQueueMember.callback(new error_1.MongoRuntimeError('Connection pool closed')); + } + } + } + // clear the min pool size timer + const minPoolSizeTimer = this[kMinPoolSizeTimer]; + if (minPoolSizeTimer) { + clearTimeout(minPoolSizeTimer); + } + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(undefined); + } + // mark the pool as closed immediately + this.closed = true; + utils_1.eachAsync(this[kConnections].toArray(), (conn, cb) => { + this.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, conn, 'poolClosed')); + conn.destroy(options, cb); + }, err => { + this[kConnections].clear(); + this.emit(ConnectionPool.CONNECTION_POOL_CLOSED, new connection_pool_events_1.ConnectionPoolClosedEvent(this)); + callback(err); + }); + } + /** + * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda + * has completed by calling back. + * + * NOTE: please note the required signature of `fn` + * + * @remarks When in load balancer mode, connections can be pinned to cursors or transactions. + * In these cases we pass the connection in to this method to ensure it is used and a new + * connection is not checked out. + * + * @param conn - A pinned connection for use in load balancing mode. + * @param fn - A function which operates on a managed connection + * @param callback - The original callback + */ + withConnection(conn, fn, callback) { + if (conn) { + // use the provided connection, and do _not_ check it in after execution + fn(undefined, conn, (fnErr, result) => { + if (typeof callback === 'function') { + if (fnErr) { + callback(fnErr); + } + else { + callback(undefined, result); + } + } + }); + return; + } + this.checkOut((err, conn) => { + // don't callback with `err` here, we might want to act upon it inside `fn` + fn(err, conn, (fnErr, result) => { + if (typeof callback === 'function') { + if (fnErr) { + callback(fnErr); + } + else { + callback(undefined, result); + } + } + if (conn) { + this.checkIn(conn); + } + }); + }); + } +} +exports.ConnectionPool = ConnectionPool; +/** + * Emitted when the connection pool is created. + * @event + */ +ConnectionPool.CONNECTION_POOL_CREATED = 'connectionPoolCreated'; +/** + * Emitted once when the connection pool is closed + * @event + */ +ConnectionPool.CONNECTION_POOL_CLOSED = 'connectionPoolClosed'; +/** + * Emitted each time the connection pool is cleared and it's generation incremented + * @event + */ +ConnectionPool.CONNECTION_POOL_CLEARED = 'connectionPoolCleared'; +/** + * Emitted when a connection is created. + * @event + */ +ConnectionPool.CONNECTION_CREATED = 'connectionCreated'; +/** + * Emitted when a connection becomes established, and is ready to use + * @event + */ +ConnectionPool.CONNECTION_READY = 'connectionReady'; +/** + * Emitted when a connection is closed + * @event + */ +ConnectionPool.CONNECTION_CLOSED = 'connectionClosed'; +/** + * Emitted when an attempt to check out a connection begins + * @event + */ +ConnectionPool.CONNECTION_CHECK_OUT_STARTED = 'connectionCheckOutStarted'; +/** + * Emitted when an attempt to check out a connection fails + * @event + */ +ConnectionPool.CONNECTION_CHECK_OUT_FAILED = 'connectionCheckOutFailed'; +/** + * Emitted each time a connection is successfully checked out of the connection pool + * @event + */ +ConnectionPool.CONNECTION_CHECKED_OUT = 'connectionCheckedOut'; +/** + * Emitted each time a connection is successfully checked into the connection pool + * @event + */ +ConnectionPool.CONNECTION_CHECKED_IN = 'connectionCheckedIn'; +function ensureMinPoolSize(pool) { + if (pool.closed || pool.options.minPoolSize === 0) { + return; + } + const minPoolSize = pool.options.minPoolSize; + for (let i = pool.totalConnectionCount; i < minPoolSize; ++i) { + createConnection(pool); + } + pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 10); +} +function connectionIsStale(pool, connection) { + const serviceId = connection.serviceId; + if (pool.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = pool.serviceGenerations.get(sid); + return connection.generation !== generation; + } + return connection.generation !== pool[kGeneration]; +} +function connectionIsIdle(pool, connection) { + return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS); +} +function createConnection(pool, callback) { + const connectOptions = { + ...pool.options, + id: pool[kConnectionCounter].next().value, + generation: pool[kGeneration], + cancellationToken: pool[kCancellationToken] + }; + pool[kPermits]--; + connect_1.connect(connectOptions, (err, connection) => { + if (err || !connection) { + pool[kPermits]++; + pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`); + if (typeof callback === 'function') { + callback(err); + } + return; + } + // The pool might have closed since we started trying to create a connection + if (pool.closed) { + connection.destroy({ force: true }); + return; + } + // forward all events from the connection to the pool + for (const event of [...connection_1.APM_EVENTS, connection_1.Connection.CLUSTER_TIME_RECEIVED]) { + connection.on(event, (e) => pool.emit(event, e)); + } + pool.emit(ConnectionPool.CONNECTION_CREATED, new connection_pool_events_1.ConnectionCreatedEvent(pool, connection)); + if (pool.loadBalanced) { + connection.on(connection_1.Connection.PINNED, pinType => pool[kMetrics].markPinned(pinType)); + connection.on(connection_1.Connection.UNPINNED, pinType => pool[kMetrics].markUnpinned(pinType)); + const serviceId = connection.serviceId; + if (serviceId) { + let generation; + const sid = serviceId.toHexString(); + if ((generation = pool.serviceGenerations.get(sid))) { + connection.generation = generation; + } + else { + pool.serviceGenerations.set(sid, 0); + connection.generation = 0; + } + } + } + connection.markAvailable(); + pool.emit(ConnectionPool.CONNECTION_READY, new connection_pool_events_1.ConnectionReadyEvent(pool, connection)); + // if a callback has been provided, check out the connection immediately + if (typeof callback === 'function') { + callback(undefined, connection); + return; + } + // otherwise add it to the pool for later acquisition, and try to process the wait queue + pool[kConnections].push(connection); + process.nextTick(processWaitQueue, pool); + }); +} +function destroyConnection(pool, connection, reason) { + pool.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(pool, connection, reason)); + // allow more connections to be created + pool[kPermits]++; + // destroy the connection + process.nextTick(() => connection.destroy()); +} +function processWaitQueue(pool) { + if (pool.closed || pool[kProcessingWaitQueue]) { + return; + } + pool[kProcessingWaitQueue] = true; + while (pool.waitQueueSize) { + const waitQueueMember = pool[kWaitQueue].peekFront(); + if (!waitQueueMember) { + pool[kWaitQueue].shift(); + continue; + } + if (waitQueueMember[kCancelled]) { + pool[kWaitQueue].shift(); + continue; + } + if (!pool.availableConnectionCount) { + break; + } + const connection = pool[kConnections].shift(); + if (!connection) { + break; + } + const isStale = connectionIsStale(pool, connection); + const isIdle = connectionIsIdle(pool, connection); + if (!isStale && !isIdle && !connection.closed) { + pool.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(pool, connection)); + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + pool[kWaitQueue].shift(); + waitQueueMember.callback(undefined, connection); + } + else { + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + destroyConnection(pool, connection, reason); + } + } + const maxPoolSize = pool.options.maxPoolSize; + if (pool.waitQueueSize && (maxPoolSize <= 0 || pool.totalConnectionCount < maxPoolSize)) { + createConnection(pool, (err, connection) => { + const waitQueueMember = pool[kWaitQueue].shift(); + if (!waitQueueMember || waitQueueMember[kCancelled]) { + if (!err && connection) { + pool[kConnections].push(connection); + } + pool[kProcessingWaitQueue] = false; + return; + } + if (err) { + pool.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(pool, err)); + } + else if (connection) { + pool.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(pool, connection)); + } + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(err, connection); + pool[kProcessingWaitQueue] = false; + process.nextTick(() => processWaitQueue(pool)); + }); + } + else { + pool[kProcessingWaitQueue] = false; + } +} +exports.CMAP_EVENTS = [ + ConnectionPool.CONNECTION_POOL_CREATED, + ConnectionPool.CONNECTION_POOL_CLOSED, + ConnectionPool.CONNECTION_CREATED, + ConnectionPool.CONNECTION_READY, + ConnectionPool.CONNECTION_CLOSED, + ConnectionPool.CONNECTION_CHECK_OUT_STARTED, + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + ConnectionPool.CONNECTION_CHECKED_OUT, + ConnectionPool.CONNECTION_CHECKED_IN, + ConnectionPool.CONNECTION_POOL_CLEARED +]; +//# sourceMappingURL=connection_pool.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/connection_pool.js.map b/node_modules/mongodb/lib/cmap/connection_pool.js.map new file mode 100644 index 0000000..2042412 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/connection_pool.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_pool.js","sourceRoot":"","sources":["../../src/cmap/connection_pool.ts"],"names":[],"mappings":";;;AAAA,iCAAkC;AAClC,6CAA2F;AAE3F,sCAAmC;AACnC,uCAAkD;AAClD,uCAAoC;AACpC,oCAA4D;AAC5D,oCAAoF;AACpF,qCAAkE;AAClE,qEAWkC;AAClC,gDAAsE;AAEtE,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AACnC,gBAAgB;AAChB,MAAM,iBAAiB,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAC;AACrD,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,sBAAsB;IACrC,cAAc,CAAC,qBAAqB;IACpC,cAAc,CAAC,uBAAuB;CAC9B,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/connection_pool_events.js b/node_modules/mongodb/lib/cmap/connection_pool_events.js new file mode 100644 index 0000000..86aeaef --- /dev/null +++ b/node_modules/mongodb/lib/cmap/connection_pool_events.js @@ -0,0 +1,147 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectionPoolClearedEvent = exports.ConnectionCheckedInEvent = exports.ConnectionCheckedOutEvent = exports.ConnectionCheckOutFailedEvent = exports.ConnectionCheckOutStartedEvent = exports.ConnectionClosedEvent = exports.ConnectionReadyEvent = exports.ConnectionCreatedEvent = exports.ConnectionPoolClosedEvent = exports.ConnectionPoolCreatedEvent = exports.ConnectionPoolMonitoringEvent = void 0; +/** + * The base export class for all monitoring events published from the connection pool + * @public + * @category Event + */ +class ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + this.time = new Date(); + this.address = pool.address; + } +} +exports.ConnectionPoolMonitoringEvent = ConnectionPoolMonitoringEvent; +/** + * An event published when a connection pool is created + * @public + * @category Event + */ +class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + this.options = pool.options; + } +} +exports.ConnectionPoolCreatedEvent = ConnectionPoolCreatedEvent; +/** + * An event published when a connection pool is closed + * @public + * @category Event + */ +class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + } +} +exports.ConnectionPoolClosedEvent = ConnectionPoolClosedEvent; +/** + * An event published when a connection pool creates a new connection + * @public + * @category Event + */ +class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionCreatedEvent = ConnectionCreatedEvent; +/** + * An event published when a connection is ready for use + * @public + * @category Event + */ +class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionReadyEvent = ConnectionReadyEvent; +/** + * An event published when a connection is closed + * @public + * @category Event + */ +class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection, reason) { + super(pool); + this.connectionId = connection.id; + this.reason = reason || 'unknown'; + this.serviceId = connection.serviceId; + } +} +exports.ConnectionClosedEvent = ConnectionClosedEvent; +/** + * An event published when a request to check a connection out begins + * @public + * @category Event + */ +class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + } +} +exports.ConnectionCheckOutStartedEvent = ConnectionCheckOutStartedEvent; +/** + * An event published when a request to check a connection out fails + * @public + * @category Event + */ +class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, reason) { + super(pool); + this.reason = reason; + } +} +exports.ConnectionCheckOutFailedEvent = ConnectionCheckOutFailedEvent; +/** + * An event published when a connection is checked out of the connection pool + * @public + * @category Event + */ +class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionCheckedOutEvent = ConnectionCheckedOutEvent; +/** + * An event published when a connection is checked into the connection pool + * @public + * @category Event + */ +class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionCheckedInEvent = ConnectionCheckedInEvent; +/** + * An event published when a connection pool is cleared + * @public + * @category Event + */ +class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, serviceId) { + super(pool); + this.serviceId = serviceId; + } +} +exports.ConnectionPoolClearedEvent = ConnectionPoolClearedEvent; +//# sourceMappingURL=connection_pool_events.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/connection_pool_events.js.map b/node_modules/mongodb/lib/cmap/connection_pool_events.js.map new file mode 100644 index 0000000..a24be17 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/connection_pool_events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_pool_events.js","sourceRoot":"","sources":["../../src/cmap/connection_pool_events.ts"],"names":[],"mappings":";;;AAKA;;;;GAIG;AACH,MAAa,6BAA6B;IAMxC,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC9B,CAAC;CACF;AAXD,sEAWC;AAED;;;;GAIG;AACH,MAAa,0BAA2B,SAAQ,6BAA6B;IAI3E,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC9B,CAAC;CACF;AATD,gEASC;AAED;;;;GAIG;AACH,MAAa,yBAA0B,SAAQ,6BAA6B;IAC1E,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,KAAK,CAAC,IAAI,CAAC,CAAC;IACd,CAAC;CACF;AALD,8DAKC;AAED;;;;GAIG;AACH,MAAa,sBAAuB,SAAQ,6BAA6B;IAIvE,gBAAgB;IAChB,YAAY,IAAoB,EAAE,UAAsB;QACtD,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,YAAY,GAAG,UAAU,CAAC,EAAE,CAAC;IACpC,CAAC;CACF;AATD,wDASC;AAED;;;;GAIG;AACH,MAAa,oBAAqB,SAAQ,6BAA6B;IAIrE,gBAAgB;IAChB,YAAY,IAAoB,EAAE,UAAsB;QACtD,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,YAAY,GAAG,UAAU,CAAC,EAAE,CAAC;IACpC,CAAC;CACF;AATD,oDASC;AAED;;;;GAIG;AACH,MAA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QACZ,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF;AATD,gEASC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/errors.js b/node_modules/mongodb/lib/cmap/errors.js new file mode 100644 index 0000000..6311262 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/errors.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WaitQueueTimeoutError = exports.PoolClosedError = void 0; +const error_1 = require("../error"); +/** + * An error indicating a connection pool is closed + * @category Error + */ +class PoolClosedError extends error_1.MongoDriverError { + constructor(pool) { + super('Attempted to check out a connection from closed connection pool'); + this.address = pool.address; + } + get name() { + return 'MongoPoolClosedError'; + } +} +exports.PoolClosedError = PoolClosedError; +/** + * An error thrown when a request to check out a connection times out + * @category Error + */ +class WaitQueueTimeoutError extends error_1.MongoDriverError { + constructor(message, address) { + super(message); + this.address = address; + } + get name() { + return 'MongoWaitQueueTimeoutError'; + } +} +exports.WaitQueueTimeoutError = WaitQueueTimeoutError; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/errors.js.map b/node_modules/mongodb/lib/cmap/errors.js.map new file mode 100644 index 0000000..c1c0959 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/cmap/errors.ts"],"names":[],"mappings":";;;AAAA,oCAA4C;AAG5C;;;GAGG;AACH,MAAa,eAAgB,SAAQ,wBAAgB;IAInD,YAAY,IAAoB;QAC9B,KAAK,CAAC,iEAAiE,CAAC,CAAC;QACzE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC9B,CAAC;IAED,IAAI,IAAI;QACN,OAAO,sBAAsB,CAAC;IAChC,CAAC;CACF;AAZD,0CAYC;AAED;;;GAGG;AACH,MAAa,qBAAsB,SAAQ,wBAAgB;IAIzD,YAAY,OAAe,EAAE,OAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,IAAI,IAAI;QACN,OAAO,4BAA4B,CAAC;IACtC,CAAC;CACF;AAZD,sDAYC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/message_stream.js b/node_modules/mongodb/lib/cmap/message_stream.js new file mode 100644 index 0000000..08b188a --- /dev/null +++ b/node_modules/mongodb/lib/cmap/message_stream.js @@ -0,0 +1,142 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MessageStream = void 0; +const stream_1 = require("stream"); +const commands_1 = require("./commands"); +const error_1 = require("../error"); +const constants_1 = require("./wire_protocol/constants"); +const compression_1 = require("./wire_protocol/compression"); +const utils_1 = require("../utils"); +const MESSAGE_HEADER_SIZE = 16; +const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID +const kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4; +/** @internal */ +const kBuffer = Symbol('buffer'); +/** + * A duplex stream that is capable of reading and writing raw wire protocol messages, with + * support for optional compression + * @internal + */ +class MessageStream extends stream_1.Duplex { + constructor(options = {}) { + super(options); + this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize; + this[kBuffer] = new utils_1.BufferPool(); + } + _write(chunk, _, callback) { + this[kBuffer].append(chunk); + processIncomingData(this, callback); + } + _read( /* size */) { + // NOTE: This implementation is empty because we explicitly push data to be read + // when `writeMessage` is called. + return; + } + writeCommand(command, operationDescription) { + // TODO: agreed compressor should live in `StreamDescription` + const compressorName = operationDescription && operationDescription.agreedCompressor + ? operationDescription.agreedCompressor + : 'none'; + if (compressorName === 'none' || !canCompress(command)) { + const data = command.toBin(); + this.push(Array.isArray(data) ? Buffer.concat(data) : data); + return; + } + // otherwise, compress the message + const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin()); + const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + // Extract information needed for OP_COMPRESSED from the uncompressed message + const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + // Compress the message body + compression_1.compress({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => { + if (err || !compressedMessage) { + operationDescription.cb(err); + return; + } + // Create the msgHeader of OP_COMPRESSED + const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE(MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, 0); // messageLength + msgHeader.writeInt32LE(command.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(constants_1.OP_COMPRESSED, 12); // opCode + // Create the compression details of OP_COMPRESSED + const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(compression_1.Compressor[compressorName], 8); // compressorID + this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + }); + } +} +exports.MessageStream = MessageStream; +// Return whether a command contains an uncompressible command term +// Will return true if command contains no uncompressible command terms +function canCompress(command) { + const commandDoc = command instanceof commands_1.Msg ? command.command : command.query; + const commandName = Object.keys(commandDoc)[0]; + return !compression_1.uncompressibleCommands.has(commandName); +} +function processIncomingData(stream, callback) { + const buffer = stream[kBuffer]; + if (buffer.length < 4) { + callback(); + return; + } + const sizeOfMessage = buffer.peek(4).readInt32LE(); + if (sizeOfMessage < 0) { + callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}`)); + return; + } + if (sizeOfMessage > stream.maxBsonMessageSize) { + callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}`)); + return; + } + if (sizeOfMessage > buffer.length) { + callback(); + return; + } + const message = buffer.read(sizeOfMessage); + const messageHeader = { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; + let ResponseType = messageHeader.opCode === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response; + if (messageHeader.opCode !== constants_1.OP_COMPRESSED) { + const messageBody = message.slice(MESSAGE_HEADER_SIZE); + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + if (buffer.length >= 4) { + processIncomingData(stream, callback); + } + else { + callback(); + } + return; + } + messageHeader.fromCompressed = true; + messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE); + messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4); + const compressorID = message[MESSAGE_HEADER_SIZE + 8]; + const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9); + // recalculate based on wrapped opcode + ResponseType = messageHeader.opCode === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response; + compression_1.decompress(compressorID, compressedBuffer, (err, messageBody) => { + if (err || !messageBody) { + callback(err); + return; + } + if (messageBody.length !== messageHeader.length) { + callback(new error_1.MongoDecompressionError('Message body and message header must be the same length')); + return; + } + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + if (buffer.length >= 4) { + processIncomingData(stream, callback); + } + else { + callback(); + } + }); +} +//# sourceMappingURL=message_stream.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/message_stream.js.map b/node_modules/mongodb/lib/cmap/message_stream.js.map new file mode 100644 index 0000000..80370ce --- /dev/null +++ b/node_modules/mongodb/lib/cmap/message_stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"message_stream.js","sourceRoot":"","sources":["../../src/cmap/message_stream.ts"],"names":[],"mappings":";;;AAAA,mCAA+C;AAC/C,yCAAmG;AACnG,oCAAoE;AACpE,yDAAkE;AAClE,6DAMqC;AAErC,oCAAgD;AAGhD,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,wB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,CAAC,mBAAQ,CAAC;IACnE,wBAAU,CAAC,YAAY,EAAE,gBAAgB,EAAE,CAAC,GAAG,EAAE,WAAW,EAAE,EAAE;QAC9D,IAAI,GAAG,IAAI,CAAC,WAAW,EAAE;YACvB,QAAQ,CAAC,GAAG,CAAC,CAAC;YACd,OAAO;SACR;QAED,IAAI,WAAW,CAAC,MAAM,KAAK,aAAa,CAAC,MAAM,EAAE;YAC/C,QAAQ,CACN,IAAI,+BAAuB,CAAC,yDAAyD,CAAC,CACvF,CAAC;YAEF,OAAO;SACR;QAED,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,YAAY,CAAC,OAAO,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC,CAAC;QAE9E,IAAI,MAAM,CAAC,MAAM,IAAI,CAAC,EAAE;YACtB,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;SACvC;aAAM;YACL,QAAQ,EAAE,CAAC;SACZ;IACH,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/metrics.js b/node_modules/mongodb/lib/cmap/metrics.js new file mode 100644 index 0000000..89c2210 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/metrics.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectionPoolMetrics = void 0; +/** @internal */ +class ConnectionPoolMetrics { + constructor() { + this.txnConnections = 0; + this.cursorConnections = 0; + this.otherConnections = 0; + } + /** + * Mark a connection as pinned for a specific operation. + */ + markPinned(pinType) { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections += 1; + } + else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections += 1; + } + else { + this.otherConnections += 1; + } + } + /** + * Unmark a connection as pinned for an operation. + */ + markUnpinned(pinType) { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections -= 1; + } + else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections -= 1; + } + else { + this.otherConnections -= 1; + } + } + /** + * Return information about the cmap metrics as a string. + */ + info(maxPoolSize) { + return ('Timed out while checking out a connection from connection pool: ' + + `maxPoolSize: ${maxPoolSize}, ` + + `connections in use by cursors: ${this.cursorConnections}, ` + + `connections in use by transactions: ${this.txnConnections}, ` + + `connections in use by other operations: ${this.otherConnections}`); + } + /** + * Reset the metrics to the initial values. + */ + reset() { + this.txnConnections = 0; + this.cursorConnections = 0; + this.otherConnections = 0; + } +} +exports.ConnectionPoolMetrics = ConnectionPoolMetrics; +ConnectionPoolMetrics.TXN = 'txn'; +ConnectionPoolMetrics.CURSOR = 'cursor'; +ConnectionPoolMetrics.OTHER = 'other'; +//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/metrics.js.map b/node_modules/mongodb/lib/cmap/metrics.js.map new file mode 100644 index 0000000..270cefe --- /dev/null +++ b/node_modules/mongodb/lib/cmap/metrics.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../src/cmap/metrics.ts"],"names":[],"mappings":";;;AAAA,gBAAgB;AAChB,MAAa,qBAAqB;IAAlC;QAKE,mBAAc,GAAG,CAAC,CAAC;QACnB,sBAAiB,GAAG,CAAC,CAAC;QACtB,qBAAgB,GAAG,CAAC,CAAC;IAiDvB,CAAC;IA/CC;;OAEG;IACH,UAAU,CAAC,OAAe;QACxB,IAAI,OAAO,KAAK,qBAAqB,CAAC,GAAG,EAAE;YACzC,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;SAC1B;aAAM,IAAI,OAAO,KAAK,qBAAqB,CAAC,MAAM,EAAE;YACnD,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;SAC7B;aAAM;YACL,IAAI,CAAC,gBAAgB,IAAI,CAAC,CAAC;SAC5B;IACH,CAAC;IAED;;OAEG;IACH,YAAY,CAAC,OAAe;QAC1B,IAAI,OAAO,KAAK,qBAAqB,CAAC,GAAG,EAAE;YACzC,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;SAC1B;aAAM,IAAI,OAAO,KAAK,qBAAqB,CAAC,MAAM,EAAE;YACnD,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;SAC7B;aAAM;YACL,IAAI,CAAC,gBAAgB,IAAI,CAAC,CAAC;SAC5B;IACH,CAAC;IAED;;OAEG;IACH,IAAI,CAAC,WAAmB;QACtB,OAAO,CACL,kEAAkE;YAClE,gBAAgB,WAAW,IAAI;YAC/B,kCAAkC,IAAI,CAAC,iBAAiB,IAAI;YAC5D,uCAAuC,IAAI,CAAC,cAAc,IAAI;YAC9D,2CAA2C,IAAI,CAAC,gBAAgB,EAAE,CACnE,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,cAAc,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,gBAAgB,GAAG,CAAC,CAAC;IAC5B,CAAC;;AAvDH,sDAwDC;AAvDiB,yBAAG,GAAG,KAAc,CAAC;AACrB,4BAAM,GAAG,QAAiB,CAAC;AAC3B,2BAAK,GAAG,OAAgB,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/stream_description.js b/node_modules/mongodb/lib/cmap/stream_description.js new file mode 100644 index 0000000..b9b2d27 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/stream_description.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamDescription = void 0; +const server_description_1 = require("../sdam/server_description"); +const common_1 = require("../sdam/common"); +const RESPONSE_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'maxBsonObjectSize', + 'maxMessageSizeBytes', + 'maxWriteBatchSize', + 'logicalSessionTimeoutMinutes' +]; +/** @public */ +class StreamDescription { + constructor(address, options) { + this.address = address; + this.type = common_1.ServerType.Unknown; + this.minWireVersion = undefined; + this.maxWireVersion = undefined; + this.maxBsonObjectSize = 16777216; + this.maxMessageSizeBytes = 48000000; + this.maxWriteBatchSize = 100000; + this.logicalSessionTimeoutMinutes = options === null || options === void 0 ? void 0 : options.logicalSessionTimeoutMinutes; + this.loadBalanced = !!(options === null || options === void 0 ? void 0 : options.loadBalanced); + this.compressors = + options && options.compressors && Array.isArray(options.compressors) + ? options.compressors + : []; + } + receiveResponse(response) { + this.type = server_description_1.parseServerType(response); + RESPONSE_FIELDS.forEach(field => { + if (typeof response[field] != null) { + this[field] = response[field]; + } + // testing case + if ('__nodejs_mock_server__' in response) { + this.__nodejs_mock_server__ = response['__nodejs_mock_server__']; + } + }); + if (response.compression) { + this.compressor = this.compressors.filter(c => { var _a; return (_a = response.compression) === null || _a === void 0 ? void 0 : _a.includes(c); })[0]; + } + } +} +exports.StreamDescription = StreamDescription; +//# sourceMappingURL=stream_description.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/stream_description.js.map b/node_modules/mongodb/lib/cmap/stream_description.js.map new file mode 100644 index 0000000..1d281b2 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/stream_description.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stream_description.js","sourceRoot":"","sources":["../../src/cmap/stream_description.ts"],"names":[],"mappings":";;;AAAA,mEAA6D;AAG7D,2CAA4C;AAE5C,MAAM,eAAe,GAAG;IACtB,gBAAgB;IAChB,gBAAgB;IAChB,mBAAmB;IACnB,qBAAqB;IACrB,mBAAmB;IACnB,8BAA8B;CACtB,CAAC;AASX,cAAc;AACd,MAAa,iBAAiB;IAiB5B,YAAY,OAAe,EAAE,OAAkC;QAC7D,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,mBAAU,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,iBAAiB,GAAG,QAAQ,CAAC;QAClC,IAAI,CA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compression.js new file mode 100644 index 0000000..7994189 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/wire_protocol/compression.js @@ -0,0 +1,83 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decompress = exports.compress = exports.uncompressibleCommands = exports.Compressor = void 0; +const zlib = require("zlib"); +const deps_1 = require("../../deps"); +const error_1 = require("../../error"); +/** @public */ +exports.Compressor = Object.freeze({ + none: 0, + snappy: 1, + zlib: 2 +}); +exports.uncompressibleCommands = new Set([ + 'ismaster', + 'saslStart', + 'saslContinue', + 'getnonce', + 'authenticate', + 'createUser', + 'updateUser', + 'copydbSaslStart', + 'copydbgetnonce', + 'copydb' +]); +// Facilitate compressing a message using an agreed compressor +function compress(self, dataToBeCompressed, callback) { + const zlibOptions = {}; + switch (self.options.agreedCompressor) { + case 'snappy': { + if ('kModuleError' in deps_1.Snappy) { + return callback(deps_1.Snappy['kModuleError']); + } + if (deps_1.Snappy[deps_1.PKG_VERSION].major <= 6) { + deps_1.Snappy.compress(dataToBeCompressed, callback); + } + else { + deps_1.Snappy.compress(dataToBeCompressed) + .then(buffer => callback(undefined, buffer)) + .catch(error => callback(error)); + } + break; + } + case 'zlib': + // Determine zlibCompressionLevel + if (self.options.zlibCompressionLevel) { + zlibOptions.level = self.options.zlibCompressionLevel; + } + zlib.deflate(dataToBeCompressed, zlibOptions, callback); + break; + default: + throw new error_1.MongoInvalidArgumentError(`Unknown compressor ${self.options.agreedCompressor} failed to compress`); + } +} +exports.compress = compress; +// Decompress a message using the given compressor +function decompress(compressorID, compressedData, callback) { + if (compressorID < 0 || compressorID > Math.max(2)) { + throw new error_1.MongoDecompressionError(`Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})`); + } + switch (compressorID) { + case exports.Compressor.snappy: { + if ('kModuleError' in deps_1.Snappy) { + return callback(deps_1.Snappy['kModuleError']); + } + if (deps_1.Snappy[deps_1.PKG_VERSION].major <= 6) { + deps_1.Snappy.uncompress(compressedData, { asBuffer: true }, callback); + } + else { + deps_1.Snappy.uncompress(compressedData, { asBuffer: true }) + .then(buffer => callback(undefined, buffer)) + .catch(error => callback(error)); + } + break; + } + case exports.Compressor.zlib: + zlib.inflate(compressedData, callback); + break; + default: + callback(undefined, compressedData); + } +} +exports.decompress = decompress; +//# sourceMappingURL=compression.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map b/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map new file mode 100644 index 0000000..18a16c7 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map @@ -0,0 +1 @@ +{"version":3,"file":"compression.js","sourceRoot":"","sources":["../../../src/cmap/wire_protocol/compression.ts"],"names":[],"mappings":";;;AAAA,6BAA6B;AAI7B,qCAAiD;AACjD,uCAAiF;AAEjF,cAAc;AACD,QAAA,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;IACtC,IAAI,EAAE,CAAC;IACP,MAAM,EAAE,CAAC;IACT,IAAI,EAAE,CAAC;CACC,CAAC,CAAC;AAQC,QAAA,sBAAsB,GAAG,IAAI,GAAG,CAAC;IAC5C,UAAU;IACV,WAAW;IACX,cAAc;IACd,UAAU;IACV,cAAc;IACd,YAAY;IACZ,YAAY;IACZ,iBAAiB;IACjB,gBAAgB;IAChB,QAAQ;CACT,CAAC,CAAC;AAEH,8DAA8D;AAC9D,SAAgB,QAAQ,CACtB,IAA0D,EAC1D,kBAA0B,EAC1B,QAA0B;IAE1B,MAAM,WAAW,GAAG,EAAsB,CAAC;IAC3C,QAAQ,IAAI,CAAC,OAAO,CAAC,gBAAgB,EAAE;QACrC,KAAK,QAAQ,CAAC,CAAC;YACb,IAAI,cAAc,IAAI,aAAM,EAAE;gBAC5B,OAAO,QAAQ,CAAC,aAAM,CAAC,cAAc,CAAC,CAAC,CAAC;aACzC;YAED,IAAI,aAAM,CAAC,kBAAW,CAAC,CAAC,KAAK,IAAI,CAAC,EAAE;gBAClC,aAAM,CAAC,QAAQ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CAAC;aACjE;iBAAM;gBACL,aAAM,CAAC,UAAU,CAAC,cAAc,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;qBAClD,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;qBAC3C,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;aACpC;YACD,MAAM;SACP;QACD,KAAK,kBAAU,CAAC,IAAI;YAClB,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,QAAiC,CAAC,CAAC;YAChE,MAAM;QACR;YACE,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;KACvC;AACH,CAAC;AAhCD,gCAgCC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/wire_protocol/constants.js b/node_modules/mongodb/lib/cmap/wire_protocol/constants.js new file mode 100644 index 0000000..352d2e7 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/wire_protocol/constants.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OP_MSG = exports.OP_COMPRESSED = exports.OP_KILL_CURSORS = exports.OP_DELETE = exports.OP_GETMORE = exports.OP_QUERY = exports.OP_INSERT = exports.OP_UPDATE = exports.OP_REPLY = exports.MAX_SUPPORTED_WIRE_VERSION = exports.MIN_SUPPORTED_WIRE_VERSION = exports.MAX_SUPPORTED_SERVER_VERSION = exports.MIN_SUPPORTED_SERVER_VERSION = void 0; +exports.MIN_SUPPORTED_SERVER_VERSION = '2.6'; +exports.MAX_SUPPORTED_SERVER_VERSION = '5.0'; +exports.MIN_SUPPORTED_WIRE_VERSION = 2; +exports.MAX_SUPPORTED_WIRE_VERSION = 13; +exports.OP_REPLY = 1; +exports.OP_UPDATE = 2001; +exports.OP_INSERT = 2002; +exports.OP_QUERY = 2004; +exports.OP_GETMORE = 2005; +exports.OP_DELETE = 2006; +exports.OP_KILL_CURSORS = 2007; +exports.OP_COMPRESSED = 2012; +exports.OP_MSG = 2013; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map b/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map new file mode 100644 index 0000000..9dc053b --- /dev/null +++ b/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/cmap/wire_protocol/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,4BAA4B,GAAG,KAAK,CAAC;AACrC,QAAA,4BAA4B,GAAG,KAAK,CAAC;AACrC,QAAA,0BAA0B,GAAG,CAAC,CAAC;AAC/B,QAAA,0BAA0B,GAAG,EAAE,CAAC;AAChC,QAAA,QAAQ,GAAG,CAAC,CAAC;AACb,QAAA,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,QAAQ,GAAG,IAAI,CAAC;AAChB,QAAA,UAAU,GAAG,IAAI,CAAC;AAClB,QAAA,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,eAAe,GAAG,IAAI,CAAC;AACvB,QAAA,aAAa,GAAG,IAAI,CAAC;AACrB,QAAA,MAAM,GAAG,IAAI,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/wire_protocol/shared.js b/node_modules/mongodb/lib/cmap/wire_protocol/shared.js new file mode 100644 index 0000000..44fdf06 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/wire_protocol/shared.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isSharded = exports.applyCommonQueryOptions = exports.getReadPreference = void 0; +const common_1 = require("../../sdam/common"); +const topology_description_1 = require("../../sdam/topology_description"); +const error_1 = require("../../error"); +const read_preference_1 = require("../../read_preference"); +function getReadPreference(cmd, options) { + // Default to command version of the readPreference + let readPreference = cmd.readPreference || read_preference_1.ReadPreference.primary; + // If we have an option readPreference override the command one + if (options === null || options === void 0 ? void 0 : options.readPreference) { + readPreference = options.readPreference; + } + if (typeof readPreference === 'string') { + readPreference = read_preference_1.ReadPreference.fromString(readPreference); + } + if (!(readPreference instanceof read_preference_1.ReadPreference)) { + throw new error_1.MongoInvalidArgumentError('Option "readPreference" must be a ReadPreference instance'); + } + return readPreference; +} +exports.getReadPreference = getReadPreference; +function applyCommonQueryOptions(queryOptions, options) { + Object.assign(queryOptions, { + raw: typeof options.raw === 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false + }); + if (options.session) { + queryOptions.session = options.session; + } + return queryOptions; +} +exports.applyCommonQueryOptions = applyCommonQueryOptions; +function isSharded(topologyOrServer) { + if (topologyOrServer.description && topologyOrServer.description.type === common_1.ServerType.Mongos) { + return true; + } + // NOTE: This is incredibly inefficient, and should be removed once command construction + // happens based on `Server` not `Topology`. + if (topologyOrServer.description && topologyOrServer.description instanceof topology_description_1.TopologyDescription) { + const servers = Array.from(topologyOrServer.description.servers.values()); + return servers.some((server) => server.type === common_1.ServerType.Mongos); + } + return false; +} +exports.isSharded = isSharded; +//# sourceMappingURL=shared.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map b/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map new file mode 100644 index 0000000..b7f7ae1 --- /dev/null +++ b/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map @@ -0,0 +1 @@ +{"version":3,"file":"shared.js","sourceRoot":"","sources":["../../../src/cmap/wire_protocol/shared.ts"],"names":[],"mappings":";;;AAAA,8CAA+C;AAC/C,0EAAsE;AACtE,uCAAwD;AACxD,2DAAuD;AAcvD,SAAgB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C,OAAO,EAAE;QACnB,YAAY,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;KACxC;IAED,OAAO,YAAY,CAAC;AACtB,CAAC;AAjBD,0DAiBC;AAED,SAAgB,SAAS,CAAC,gBAAgD;IACxE,IAAI,gBAAgB,CAAC,WAAW,IAAI,gBAAgB,CAAC,WAAW,CAAC,IAAI,KAAK,mBAAU,CAAC,MAAM,EAAE;QAC3F,OAAO,IAAI,CAAC;KACb;IAED,wFAAwF;IACxF,kDAAkD;IAClD,IAAI,gBAAgB,CAAC,WAAW,IAAI,gBAAgB,CAAC,WAAW,YAAY,0CAAmB,EAAE;QAC/F,MAAM,OAAO,GAAwB,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC/F,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,MAAyB,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,mBAAU,CAAC,MAAM,CAAC,CAAC;KACvF;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAbD,8BAaC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/collection.js b/node_modules/mongodb/lib/collection.js new file mode 100644 index 0000000..e5aafeb --- /dev/null +++ b/node_modules/mongodb/lib/collection.js @@ -0,0 +1,491 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Collection = void 0; +const utils_1 = require("./utils"); +const read_preference_1 = require("./read_preference"); +const utils_2 = require("./utils"); +const bson_1 = require("./bson"); +const error_1 = require("./error"); +const unordered_1 = require("./bulk/unordered"); +const ordered_1 = require("./bulk/ordered"); +const change_stream_1 = require("./change_stream"); +const write_concern_1 = require("./write_concern"); +const read_concern_1 = require("./read_concern"); +const aggregation_cursor_1 = require("./cursor/aggregation_cursor"); +const bulk_write_1 = require("./operations/bulk_write"); +const count_documents_1 = require("./operations/count_documents"); +const indexes_1 = require("./operations/indexes"); +const distinct_1 = require("./operations/distinct"); +const drop_1 = require("./operations/drop"); +const estimated_document_count_1 = require("./operations/estimated_document_count"); +const find_and_modify_1 = require("./operations/find_and_modify"); +const insert_1 = require("./operations/insert"); +const update_1 = require("./operations/update"); +const delete_1 = require("./operations/delete"); +const is_capped_1 = require("./operations/is_capped"); +const map_reduce_1 = require("./operations/map_reduce"); +const options_operation_1 = require("./operations/options_operation"); +const rename_1 = require("./operations/rename"); +const stats_1 = require("./operations/stats"); +const execute_operation_1 = require("./operations/execute_operation"); +const find_cursor_1 = require("./cursor/find_cursor"); +/** + * The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * expect(err).to.not.exist; + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * ``` + */ +class Collection { + /** + * Create a new Collection instance + * @internal + */ + constructor(db, name, options) { + var _a, _b; + utils_2.checkCollectionName(name); + // Internal state + this.s = { + db, + options, + namespace: new utils_2.MongoDBNamespace(db.databaseName, name), + pkFactory: (_b = (_a = db.options) === null || _a === void 0 ? void 0 : _a.pkFactory) !== null && _b !== void 0 ? _b : utils_1.DEFAULT_PK_FACTORY, + readPreference: read_preference_1.ReadPreference.fromOptions(options), + bsonOptions: bson_1.resolveBSONOptions(options, db), + readConcern: read_concern_1.ReadConcern.fromOptions(options), + writeConcern: write_concern_1.WriteConcern.fromOptions(options), + slaveOk: options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk + }; + } + /** + * The name of the database this collection belongs to + */ + get dbName() { + return this.s.namespace.db; + } + /** + * The name of this collection + */ + get collectionName() { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return this.s.namespace.collection; + } + /** + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + */ + get namespace() { + return this.s.namespace.toString(); + } + /** + * The current readConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readConcern() { + if (this.s.readConcern == null) { + return this.s.db.readConcern; + } + return this.s.readConcern; + } + /** + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readPreference() { + if (this.s.readPreference == null) { + return this.s.db.readPreference; + } + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + /** + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get writeConcern() { + if (this.s.writeConcern == null) { + return this.s.db.writeConcern; + } + return this.s.writeConcern; + } + /** The current index hint for the collection */ + get hint() { + return this.s.collectionHint; + } + set hint(v) { + this.s.collectionHint = utils_2.normalizeHintField(v); + } + insertOne(doc, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + // CSFLE passes in { w: 'majority' } to ensure the lib works in both 3.x and 4.x + // we support that option style here only + if (options && Reflect.get(options, 'w')) { + options.writeConcern = write_concern_1.WriteConcern.fromOptions(Reflect.get(options, 'w')); + } + return execute_operation_1.executeOperation(utils_2.getTopology(this), new insert_1.InsertOneOperation(this, doc, utils_1.resolveOptions(this, options)), callback); + } + insertMany(docs, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options ? Object.assign({}, options) : { ordered: true }; + return execute_operation_1.executeOperation(utils_2.getTopology(this), new insert_1.InsertManyOperation(this, docs, utils_1.resolveOptions(this, options)), callback); + } + bulkWrite(operations, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options || { ordered: true }; + if (!Array.isArray(operations)) { + throw new error_1.MongoInvalidArgumentError('Argument "operations" must be an array of documents'); + } + return execute_operation_1.executeOperation(utils_2.getTopology(this), new bulk_write_1.BulkWriteOperation(this, operations, utils_1.resolveOptions(this, options)), callback); + } + updateOne(filter, update, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new update_1.UpdateOneOperation(this, filter, update, utils_1.resolveOptions(this, options)), callback); + } + replaceOne(filter, replacement, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new update_1.ReplaceOneOperation(this, filter, replacement, utils_1.resolveOptions(this, options)), callback); + } + updateMany(filter, update, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new update_1.UpdateManyOperation(this, filter, update, utils_1.resolveOptions(this, options)), callback); + } + deleteOne(filter, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new delete_1.DeleteOneOperation(this, filter, utils_1.resolveOptions(this, options)), callback); + } + deleteMany(filter, options, callback) { + if (filter == null) { + filter = {}; + options = {}; + callback = undefined; + } + else if (typeof filter === 'function') { + callback = filter; + filter = {}; + options = {}; + } + else if (typeof options === 'function') { + callback = options; + options = {}; + } + return execute_operation_1.executeOperation(utils_2.getTopology(this), new delete_1.DeleteManyOperation(this, filter, utils_1.resolveOptions(this, options)), callback); + } + rename(newName, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + // Intentionally, we do not inherit options from parent for this operation. + return execute_operation_1.executeOperation(utils_2.getTopology(this), new rename_1.RenameOperation(this, newName, { + ...options, + readPreference: read_preference_1.ReadPreference.PRIMARY + }), callback); + } + drop(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return execute_operation_1.executeOperation(utils_2.getTopology(this), new drop_1.DropCollectionOperation(this.s.db, this.collectionName, options), callback); + } + findOne(filter, options, callback) { + if (callback != null && typeof callback !== 'function') { + throw new error_1.MongoInvalidArgumentError('Third parameter to `findOne()` must be a callback or undefined'); + } + if (typeof filter === 'function') { + callback = filter; + filter = {}; + options = {}; + } + if (typeof options === 'function') { + callback = options; + options = {}; + } + const finalFilter = filter !== null && filter !== void 0 ? filter : {}; + const finalOptions = options !== null && options !== void 0 ? options : {}; + return this.find(finalFilter, finalOptions).limit(-1).batchSize(1).next(callback); + } + find(filter, options) { + if (arguments.length > 2) { + throw new error_1.MongoInvalidArgumentError('Method "collection.find()" accepts at most two arguments'); + } + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "options" must not be function'); + } + return new find_cursor_1.FindCursor(utils_2.getTopology(this), this.s.namespace, filter, utils_1.resolveOptions(this, options)); + } + options(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new options_operation_1.OptionsOperation(this, utils_1.resolveOptions(this, options)), callback); + } + isCapped(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new is_capped_1.IsCappedOperation(this, utils_1.resolveOptions(this, options)), callback); + } + createIndex(indexSpec, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new indexes_1.CreateIndexOperation(this, this.collectionName, indexSpec, utils_1.resolveOptions(this, options)), callback); + } + createIndexes(indexSpecs, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + if (typeof options.maxTimeMS !== 'number') + delete options.maxTimeMS; + return execute_operation_1.executeOperation(utils_2.getTopology(this), new indexes_1.CreateIndexesOperation(this, this.collectionName, indexSpecs, utils_1.resolveOptions(this, options)), callback); + } + dropIndex(indexName, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = utils_1.resolveOptions(this, options); + // Run only against primary + options.readPreference = read_preference_1.ReadPreference.primary; + return execute_operation_1.executeOperation(utils_2.getTopology(this), new indexes_1.DropIndexOperation(this, indexName, options), callback); + } + dropIndexes(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new indexes_1.DropIndexesOperation(this, utils_1.resolveOptions(this, options)), callback); + } + /** + * Get the list of all indexes information for the collection. + * + * @param options - Optional settings for the command + */ + listIndexes(options) { + return new indexes_1.ListIndexesCursor(this, utils_1.resolveOptions(this, options)); + } + indexExists(indexes, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new indexes_1.IndexExistsOperation(this, indexes, utils_1.resolveOptions(this, options)), callback); + } + indexInformation(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new indexes_1.IndexInformationOperation(this.s.db, this.collectionName, utils_1.resolveOptions(this, options)), callback); + } + estimatedDocumentCount(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new estimated_document_count_1.EstimatedDocumentCountOperation(this, utils_1.resolveOptions(this, options)), callback); + } + countDocuments(filter, options, callback) { + if (filter == null) { + (filter = {}), (options = {}), (callback = undefined); + } + else if (typeof filter === 'function') { + (callback = filter), (filter = {}), (options = {}); + } + else { + if (arguments.length === 2) { + if (typeof options === 'function') + (callback = options), (options = {}); + } + } + filter !== null && filter !== void 0 ? filter : (filter = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new count_documents_1.CountDocumentsOperation(this, filter, utils_1.resolveOptions(this, options)), callback); + } + // Implementation + distinct(key, filter, options, callback) { + if (typeof filter === 'function') { + (callback = filter), (filter = {}), (options = {}); + } + else { + if (arguments.length === 3 && typeof options === 'function') { + (callback = options), (options = {}); + } + } + filter !== null && filter !== void 0 ? filter : (filter = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new distinct_1.DistinctOperation(this, key, filter, utils_1.resolveOptions(this, options)), callback); + } + indexes(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new indexes_1.IndexesOperation(this, utils_1.resolveOptions(this, options)), callback); + } + stats(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return execute_operation_1.executeOperation(utils_2.getTopology(this), new stats_1.CollStatsOperation(this, options), callback); + } + findOneAndDelete(filter, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new find_and_modify_1.FindOneAndDeleteOperation(this, filter, utils_1.resolveOptions(this, options)), callback); + } + findOneAndReplace(filter, replacement, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new find_and_modify_1.FindOneAndReplaceOperation(this, filter, replacement, utils_1.resolveOptions(this, options)), callback); + } + findOneAndUpdate(filter, update, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new find_and_modify_1.FindOneAndUpdateOperation(this, filter, update, utils_1.resolveOptions(this, options)), callback); + } + /** + * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 + * + * @param pipeline - An array of aggregation pipelines to execute + * @param options - Optional settings for the command + */ + aggregate(pipeline = [], options) { + if (arguments.length > 2) { + throw new error_1.MongoInvalidArgumentError('Method "collection.aggregate()" accepts at most two arguments'); + } + if (!Array.isArray(pipeline)) { + throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages'); + } + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "options" must not be function'); + } + return new aggregation_cursor_1.AggregationCursor(utils_2.getTopology(this), this.s.namespace, pipeline, utils_1.resolveOptions(this, options)); + } + /** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * + * @since 3.0.0 + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + return new change_stream_1.ChangeStream(this, pipeline, utils_1.resolveOptions(this, options)); + } + mapReduce(map, reduce, options, callback) { + if ('function' === typeof options) + (callback = options), (options = {}); + // Out must always be defined (make sure we don't break weirdly on pre 1.8+ servers) + // TODO NODE-3339: Figure out if this is still necessary given we no longer officially support pre-1.8 + if ((options === null || options === void 0 ? void 0 : options.out) == null) { + throw new error_1.MongoInvalidArgumentError('Option "out" must be defined, see mongodb docs for possible values'); + } + if ('function' === typeof map) { + map = map.toString(); + } + if ('function' === typeof reduce) { + reduce = reduce.toString(); + } + if ('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + return execute_operation_1.executeOperation(utils_2.getTopology(this), new map_reduce_1.MapReduceOperation(this, map, reduce, utils_1.resolveOptions(this, options)), callback); + } + /** Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. */ + initializeUnorderedBulkOp(options) { + return new unordered_1.UnorderedBulkOperation(this, utils_1.resolveOptions(this, options)); + } + /** Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. */ + initializeOrderedBulkOp(options) { + return new ordered_1.OrderedBulkOperation(this, utils_1.resolveOptions(this, options)); + } + /** Get the db scoped logger */ + getLogger() { + return this.s.db.s.logger; + } + get logger() { + return this.s.db.s.logger; + } + /** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @deprecated Use insertOne, insertMany or bulkWrite instead. + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insert(docs, options, callback) { + utils_1.emitWarningOnce('collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); + if (typeof options === 'function') + (callback = options), (options = {}); + options = options || { ordered: false }; + docs = !Array.isArray(docs) ? [docs] : docs; + if (options.keepGoing === true) { + options.ordered = false; + } + return this.insertMany(docs, options, callback); + } + /** + * Updates documents. + * + * @deprecated use updateOne, updateMany or bulkWrite + * @param selector - The selector for the update operation. + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + update(selector, update, options, callback) { + utils_1.emitWarningOnce('collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.updateMany(selector, update, options, callback); + } + /** + * Remove documents. + * + * @deprecated use deleteOne, deleteMany or bulkWrite + * @param selector - The selector for the update operation. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + remove(selector, options, callback) { + utils_1.emitWarningOnce('collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.deleteMany(selector, options, callback); + } + count(filter, options, callback) { + if (typeof filter === 'function') { + (callback = filter), (filter = {}), (options = {}); + } + else { + if (typeof options === 'function') + (callback = options), (options = {}); + } + filter !== null && filter !== void 0 ? filter : (filter = {}); + return execute_operation_1.executeOperation(utils_2.getTopology(this), new count_documents_1.CountDocumentsOperation(this, filter, utils_1.resolveOptions(this, options)), callback); + } +} +exports.Collection = Collection; +//# sourceMappingURL=collection.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/collection.js.map b/node_modules/mongodb/lib/collection.js.map new file mode 100644 index 0000000..e18e767 --- /dev/null +++ b/node_modules/mongodb/lib/collection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"collection.js","sourceRoot":"","sources":["../src/collection.ts"],"names":[],"mappings":";;;AAAA,mCAA8E;AAC9E,uDAAuE;AACvE,mCAMiB;AACjB,iCAA4E;AAC5E,mCAAoD;AACpD,gDAA0D;AAC1D,4CAAsD;AACtD,mDAAoE;AACpE,mDAAoE;AACpE,i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,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IACtD,CAAC;IAyBD,KAAK,CACH,MAA0D,EAC1D,OAAyC,EACzC,QAA2B;QAE3B,IAAI,OAAO,MAAM,KAAK,UAAU,EAAE;YAChC,CAAC,QAAQ,GAAG,MAA0B,CAAC,EAAE,CAAC,MAAM,GAAG,EAAE,CAAC,EAAE,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;SACxE;aAAM;YACL,IAAI,OAAO,OAAO,KAAK,UAAU;gBAAE,CAAC,QAAQ,GAAG,OAAO,CAAC,EAAE,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;SACzE;QAED,MAAM,aAAN,MAAM,cAAN,MAAM,IAAN,MAAM,GAAK,EAAE,EAAC;QACd,OAAO,oCAAgB,CACrB,mBAAW,CAAC,IAAI,CAAC,EACjB,IAAI,yCAAuB,CAAC,IAAsB,EAAE,MAAM,EAAE,sBAAc,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,EAC1F,QAAQ,CACT,CAAC;IACJ,CAAC;CACF;AAh7CD,gCAg7CC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/connection_string.js b/node_modules/mongodb/lib/connection_string.js new file mode 100644 index 0000000..0e8ae2f --- /dev/null +++ b/node_modules/mongodb/lib/connection_string.js @@ -0,0 +1,996 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_OPTIONS = exports.OPTIONS = exports.parseOptions = exports.checkTLSOptions = exports.resolveSRVRecord = void 0; +const dns = require("dns"); +const fs = require("fs"); +const mongodb_connection_string_url_1 = require("mongodb-connection-string-url"); +const url_1 = require("url"); +const defaultAuthProviders_1 = require("./cmap/auth/defaultAuthProviders"); +const read_preference_1 = require("./read_preference"); +const read_concern_1 = require("./read_concern"); +const write_concern_1 = require("./write_concern"); +const error_1 = require("./error"); +const utils_1 = require("./utils"); +const mongo_client_1 = require("./mongo_client"); +const mongo_credentials_1 = require("./cmap/auth/mongo_credentials"); +const logger_1 = require("./logger"); +const promise_provider_1 = require("./promise_provider"); +const encrypter_1 = require("./encrypter"); +const compression_1 = require("./cmap/wire_protocol/compression"); +const VALID_TXT_RECORDS = ['authSource', 'replicaSet', 'loadBalanced']; +const LB_SINGLE_HOST_ERROR = 'loadBalanced option only supported with a single host in the URI'; +const LB_REPLICA_SET_ERROR = 'loadBalanced option not supported with a replicaSet option'; +const LB_DIRECT_CONNECTION_ERROR = 'loadBalanced option not supported when directConnection is provided'; +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param srvAddress - The address to check against a domain + * @param parentDomain - The domain to check the provided address against + * @returns Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} +/** + * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal + * connection string. + * + * @param uri - The connection string to parse + * @param options - Optional user provided connection string options + */ +function resolveSRVRecord(options, callback) { + if (typeof options.srvHost !== 'string') { + return callback(new error_1.MongoAPIError('Option "srvHost" must not be empty')); + } + if (options.srvHost.split('.').length < 3) { + // TODO(NODE-3484): Replace with MongoConnectionStringError + return callback(new error_1.MongoAPIError('URI must include hostname, domain name, and tld')); + } + // Resolve the SRV record and use the result as the list of hosts to connect to. + const lookupAddress = options.srvHost; + dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { + if (err) + return callback(err); + if (addresses.length === 0) { + return callback(new error_1.MongoAPIError('No addresses found at host')); + } + for (const { name } of addresses) { + if (!matchesParentDomain(name, lookupAddress)) { + return callback(new error_1.MongoAPIError('Server record does not share hostname with parent URI')); + } + } + const hostAddresses = addresses.map(r => { var _a; return utils_1.HostAddress.fromString(`${r.name}:${(_a = r.port) !== null && _a !== void 0 ? _a : 27017}`); }); + const lbError = validateLoadBalancedOptions(hostAddresses, options); + if (lbError) { + return callback(lbError); + } + // Resolve TXT record and add options from there if they exist. + dns.resolveTxt(lookupAddress, (err, record) => { + var _a, _b, _c; + if (err) { + if (err.code !== 'ENODATA' && err.code !== 'ENOTFOUND') { + return callback(err); + } + } + else { + if (record.length > 1) { + return callback(new error_1.MongoParseError('Multiple text records not allowed')); + } + const txtRecordOptions = new url_1.URLSearchParams(record[0].join('')); + const txtRecordOptionKeys = [...txtRecordOptions.keys()]; + if (txtRecordOptionKeys.some(key => !VALID_TXT_RECORDS.includes(key))) { + return callback(new error_1.MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`)); + } + const source = (_a = txtRecordOptions.get('authSource')) !== null && _a !== void 0 ? _a : undefined; + const replicaSet = (_b = txtRecordOptions.get('replicaSet')) !== null && _b !== void 0 ? _b : undefined; + const loadBalanced = (_c = txtRecordOptions.get('loadBalanced')) !== null && _c !== void 0 ? _c : undefined; + if (source === '' || replicaSet === '') { + return callback(new error_1.MongoParseError('Cannot have empty URI params in DNS TXT Record')); + } + if (!options.userSpecifiedAuthSource && source) { + options.credentials = mongo_credentials_1.MongoCredentials.merge(options.credentials, { source }); + } + if (!options.userSpecifiedReplicaSet && replicaSet) { + options.replicaSet = replicaSet; + } + if (loadBalanced === 'true') { + options.loadBalanced = true; + } + const lbError = validateLoadBalancedOptions(hostAddresses, options); + if (lbError) { + return callback(lbError); + } + } + callback(undefined, hostAddresses); + }); + }); +} +exports.resolveSRVRecord = resolveSRVRecord; +/** + * Checks if TLS options are valid + * + * @param options - The options used for options parsing + * @throws MongoParseError if TLS options are invalid + */ +function checkTLSOptions(options) { + if (!options) + return; + const check = (a, b) => { + if (Reflect.has(options, a) && Reflect.has(options, b)) { + throw new error_1.MongoParseError(`The '${a}' option cannot be used with '${b}'`); + } + }; + check('tlsInsecure', 'tlsAllowInvalidCertificates'); + check('tlsInsecure', 'tlsAllowInvalidHostnames'); + check('tlsInsecure', 'tlsDisableCertificateRevocationCheck'); + check('tlsInsecure', 'tlsDisableOCSPEndpointCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableCertificateRevocationCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableOCSPEndpointCheck'); + check('tlsDisableCertificateRevocationCheck', 'tlsDisableOCSPEndpointCheck'); +} +exports.checkTLSOptions = checkTLSOptions; +const TRUTHS = new Set(['true', 't', '1', 'y', 'yes']); +const FALSEHOODS = new Set(['false', 'f', '0', 'n', 'no', '-1']); +function getBoolean(name, value) { + if (typeof value === 'boolean') + return value; + const valueString = String(value).toLowerCase(); + if (TRUTHS.has(valueString)) + return true; + if (FALSEHOODS.has(valueString)) + return false; + throw new error_1.MongoParseError(`Expected ${name} to be stringified boolean value, got: ${value}`); +} +function getInt(name, value) { + if (typeof value === 'number') + return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + if (!Number.isNaN(parsedValue)) + return parsedValue; + throw new error_1.MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); +} +function getUint(name, value) { + const parsedValue = getInt(name, value); + if (parsedValue < 0) { + throw new error_1.MongoParseError(`${name} can only be a positive int value, got: ${value}`); + } + return parsedValue; +} +function toRecord(value) { + const record = Object.create(null); + const keyValuePairs = value.split(','); + for (const keyValue of keyValuePairs) { + const [key, value] = keyValue.split(':'); + if (value == null) { + throw new error_1.MongoParseError('Cannot have undefined values in key value pairs'); + } + try { + // try to get a boolean + record[key] = getBoolean('', value); + } + catch { + try { + // try to get a number + record[key] = getInt('', value); + } + catch { + // keep value as a string + record[key] = value; + } + } + } + return record; +} +class CaseInsensitiveMap extends Map { + constructor(entries = []) { + super(entries.map(([k, v]) => [k.toLowerCase(), v])); + } + has(k) { + return super.has(k.toLowerCase()); + } + get(k) { + return super.get(k.toLowerCase()); + } + set(k, v) { + return super.set(k.toLowerCase(), v); + } + delete(k) { + return super.delete(k.toLowerCase()); + } +} +function parseOptions(uri, mongoClient = undefined, options = {}) { + if (mongoClient != null && !(mongoClient instanceof mongo_client_1.MongoClient)) { + options = mongoClient; + mongoClient = undefined; + } + const url = new mongodb_connection_string_url_1.default(uri); + const { hosts, isSRV } = url; + const mongoOptions = Object.create(null); + mongoOptions.hosts = isSRV ? [] : hosts.map(utils_1.HostAddress.fromString); + if (isSRV) { + // SRV Record is resolved upon connecting + mongoOptions.srvHost = hosts[0]; + if (!url.searchParams.has('tls') && !url.searchParams.has('ssl')) { + options.tls = true; + } + } + const urlOptions = new CaseInsensitiveMap(); + if (url.pathname !== '/' && url.pathname !== '') { + const dbName = decodeURIComponent(url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname); + if (dbName) { + urlOptions.set('dbName', [dbName]); + } + } + if (url.username !== '') { + const auth = { + username: decodeURIComponent(url.username) + }; + if (typeof url.password === 'string') { + auth.password = decodeURIComponent(url.password); + } + urlOptions.set('auth', [auth]); + } + for (const key of url.searchParams.keys()) { + const values = [...url.searchParams.getAll(key)]; + if (values.includes('')) { + throw new error_1.MongoAPIError('URI cannot contain options with no value'); + } + if (key.toLowerCase() === 'serverapi') { + throw new error_1.MongoParseError('URI cannot contain `serverApi`, it can only be passed to the client'); + } + if (key.toLowerCase() === 'authsource' && urlOptions.has('authSource')) { + // If authSource is an explicit key in the urlOptions we need to remove the implicit dbName + urlOptions.delete('authSource'); + } + if (!urlOptions.has(key)) { + urlOptions.set(key, values); + } + } + const objectOptions = new CaseInsensitiveMap(Object.entries(options).filter(([, v]) => v != null)); + if (objectOptions.has('loadBalanced')) { + throw new error_1.MongoParseError('loadBalanced is only a valid option in the URI'); + } + const allOptions = new CaseInsensitiveMap(); + const allKeys = new Set([ + ...urlOptions.keys(), + ...objectOptions.keys(), + ...exports.DEFAULT_OPTIONS.keys() + ]); + for (const key of allKeys) { + const values = []; + if (objectOptions.has(key)) { + values.push(objectOptions.get(key)); + } + if (urlOptions.has(key)) { + values.push(...urlOptions.get(key)); + } + if (exports.DEFAULT_OPTIONS.has(key)) { + values.push(exports.DEFAULT_OPTIONS.get(key)); + } + allOptions.set(key, values); + } + if (allOptions.has('tlsCertificateKeyFile') && !allOptions.has('tlsCertificateFile')) { + allOptions.set('tlsCertificateFile', allOptions.get('tlsCertificateKeyFile')); + } + if (allOptions.has('tls') || allOptions.has('ssl')) { + const tlsAndSslOpts = (allOptions.get('tls') || []) + .concat(allOptions.get('ssl') || []) + .map(getBoolean.bind(null, 'tls/ssl')); + if (new Set(tlsAndSslOpts).size !== 1) { + throw new error_1.MongoParseError('All values of tls/ssl must be the same.'); + } + } + const unsupportedOptions = utils_1.setDifference(allKeys, Array.from(Object.keys(exports.OPTIONS)).map(s => s.toLowerCase())); + if (unsupportedOptions.size !== 0) { + const optionWord = unsupportedOptions.size > 1 ? 'options' : 'option'; + const isOrAre = unsupportedOptions.size > 1 ? 'are' : 'is'; + throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported`); + } + for (const [key, descriptor] of Object.entries(exports.OPTIONS)) { + const values = allOptions.get(key); + if (!values || values.length === 0) + continue; + setOption(mongoOptions, key, descriptor, values); + } + if (mongoOptions.credentials) { + const isGssapi = mongoOptions.credentials.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_GSSAPI; + const isX509 = mongoOptions.credentials.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_X509; + const isAws = mongoOptions.credentials.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_AWS; + if ((isGssapi || isX509) && + allOptions.has('authSource') && + mongoOptions.credentials.source !== '$external') { + // If authSource was explicitly given and its incorrect, we error + throw new error_1.MongoParseError(`${mongoOptions.credentials} can only have authSource set to '$external'`); + } + if (!(isGssapi || isX509 || isAws) && mongoOptions.dbName && !allOptions.has('authSource')) { + // inherit the dbName unless GSSAPI or X509, then silently ignore dbName + // and there was no specific authSource given + mongoOptions.credentials = mongo_credentials_1.MongoCredentials.merge(mongoOptions.credentials, { + source: mongoOptions.dbName + }); + } + mongoOptions.credentials.validate(); + } + if (!mongoOptions.dbName) { + // dbName default is applied here because of the credential validation above + mongoOptions.dbName = 'test'; + } + checkTLSOptions(mongoOptions); + if (options.promiseLibrary) + promise_provider_1.PromiseProvider.set(options.promiseLibrary); + if (mongoOptions.directConnection && typeof mongoOptions.srvHost === 'string') { + throw new error_1.MongoAPIError('SRV URI does not support directConnection'); + } + const lbError = validateLoadBalancedOptions(hosts, mongoOptions); + if (lbError) { + throw lbError; + } + // Potential SRV Overrides + mongoOptions.userSpecifiedAuthSource = + objectOptions.has('authSource') || urlOptions.has('authSource'); + mongoOptions.userSpecifiedReplicaSet = + objectOptions.has('replicaSet') || urlOptions.has('replicaSet'); + if (mongoClient && mongoOptions.autoEncryption) { + encrypter_1.Encrypter.checkForMongoCrypt(); + mongoOptions.encrypter = new encrypter_1.Encrypter(mongoClient, uri, options); + mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter; + } + return mongoOptions; +} +exports.parseOptions = parseOptions; +function validateLoadBalancedOptions(hosts, mongoOptions) { + if (mongoOptions.loadBalanced) { + if (hosts.length > 1) { + return new error_1.MongoParseError(LB_SINGLE_HOST_ERROR); + } + if (mongoOptions.replicaSet) { + return new error_1.MongoParseError(LB_REPLICA_SET_ERROR); + } + if (mongoOptions.directConnection) { + return new error_1.MongoParseError(LB_DIRECT_CONNECTION_ERROR); + } + } +} +function setOption(mongoOptions, key, descriptor, values) { + const { target, type, transform, deprecated } = descriptor; + const name = target !== null && target !== void 0 ? target : key; + if (deprecated) { + const deprecatedMsg = typeof deprecated === 'string' ? `: ${deprecated}` : ''; + utils_1.emitWarning(`${key} is a deprecated option${deprecatedMsg}`); + } + switch (type) { + case 'boolean': + mongoOptions[name] = getBoolean(name, values[0]); + break; + case 'int': + mongoOptions[name] = getInt(name, values[0]); + break; + case 'uint': + mongoOptions[name] = getUint(name, values[0]); + break; + case 'string': + if (values[0] == null) { + break; + } + mongoOptions[name] = String(values[0]); + break; + case 'record': + if (!utils_1.isRecord(values[0])) { + throw new error_1.MongoParseError(`${name} must be an object`); + } + mongoOptions[name] = values[0]; + break; + case 'any': + mongoOptions[name] = values[0]; + break; + default: { + if (!transform) { + throw new error_1.MongoParseError('Descriptors missing a type must define a transform'); + } + const transformValue = transform({ name, options: mongoOptions, values }); + mongoOptions[name] = transformValue; + break; + } + } +} +exports.OPTIONS = { + appName: { + target: 'metadata', + transform({ options, values: [value] }) { + return utils_1.makeClientMetadata({ ...options.driverInfo, appName: String(value) }); + } + }, + auth: { + target: 'credentials', + transform({ name, options, values: [value] }) { + if (!utils_1.isRecord(value, ['username', 'password'])) { + throw new error_1.MongoParseError(`${name} must be an object with 'username' and 'password' properties`); + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { + username: value.username, + password: value.password + }); + } + }, + authMechanism: { + target: 'credentials', + transform({ options, values: [value] }) { + var _a, _b; + const mechanisms = Object.values(defaultAuthProviders_1.AuthMechanism); + const [mechanism] = mechanisms.filter(m => m.match(RegExp(String.raw `\b${value}\b`, 'i'))); + if (!mechanism) { + throw new error_1.MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`); + } + let source = (_a = options.credentials) === null || _a === void 0 ? void 0 : _a.source; + if (mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_PLAIN || + mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_GSSAPI || + mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_AWS || + mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_X509) { + // some mechanisms have '$external' as the Auth Source + source = '$external'; + } + let password = (_b = options.credentials) === null || _b === void 0 ? void 0 : _b.password; + if (mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_X509 && password === '') { + password = undefined; + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { + mechanism, + source, + password + }); + } + }, + authMechanismProperties: { + target: 'credentials', + transform({ options, values: [value] }) { + if (typeof value === 'string') { + value = toRecord(value); + } + if (!utils_1.isRecord(value)) { + throw new error_1.MongoParseError('AuthMechanismProperties must be an object'); + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { mechanismProperties: value }); + } + }, + authSource: { + target: 'credentials', + transform({ options, values: [value] }) { + const source = String(value); + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { source }); + } + }, + autoEncryption: { + type: 'record' + }, + bsonRegExp: { + type: 'boolean' + }, + serverApi: { + target: 'serverApi', + transform({ values: [version] }) { + const serverApiToValidate = typeof version === 'string' ? { version } : version; + const versionToValidate = serverApiToValidate && serverApiToValidate.version; + if (!versionToValidate) { + throw new error_1.MongoParseError(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`); + } + if (!Object.values(mongo_client_1.ServerApiVersion).some(v => v === versionToValidate)) { + throw new error_1.MongoParseError(`Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`); + } + return serverApiToValidate; + } + }, + checkKeys: { + type: 'boolean' + }, + compressors: { + default: 'none', + target: 'compressors', + transform({ values }) { + const compressionList = new Set(); + for (const compVal of values) { + const compValArray = typeof compVal === 'string' ? compVal.split(',') : compVal; + if (!Array.isArray(compValArray)) { + throw new error_1.MongoInvalidArgumentError('compressors must be an array or a comma-delimited list of strings'); + } + for (const c of compValArray) { + if (Object.keys(compression_1.Compressor).includes(String(c))) { + compressionList.add(String(c)); + } + else { + throw new error_1.MongoInvalidArgumentError(`${c} is not a valid compression mechanism. Must be one of: ${Object.keys(compression_1.Compressor)}.`); + } + } + } + return [...compressionList]; + } + }, + connectTimeoutMS: { + default: 30000, + type: 'uint' + }, + dbName: { + type: 'string' + }, + directConnection: { + default: false, + type: 'boolean' + }, + driverInfo: { + target: 'metadata', + default: utils_1.makeClientMetadata(), + transform({ options, values: [value] }) { + var _a, _b; + if (!utils_1.isRecord(value)) + throw new error_1.MongoParseError('DriverInfo must be an object'); + return utils_1.makeClientMetadata({ + driverInfo: value, + appName: (_b = (_a = options.metadata) === null || _a === void 0 ? void 0 : _a.application) === null || _b === void 0 ? void 0 : _b.name + }); + } + }, + family: { + transform({ name, values: [value] }) { + const transformValue = getInt(name, value); + if (transformValue === 4 || transformValue === 6) { + return transformValue; + } + throw new error_1.MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`); + } + }, + fieldsAsRaw: { + type: 'record' + }, + forceServerObjectId: { + default: false, + type: 'boolean' + }, + fsync: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + fsync: getBoolean(name, value) + } + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from fsync=${value}`); + return wc; + } + }, + heartbeatFrequencyMS: { + default: 10000, + type: 'uint' + }, + ignoreUndefined: { + type: 'boolean' + }, + j: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + }, + journal: { + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + }, + keepAlive: { + default: true, + type: 'boolean' + }, + keepAliveInitialDelay: { + default: 120000, + type: 'uint' + }, + loadBalanced: { + default: false, + type: 'boolean' + }, + localThresholdMS: { + default: 15, + type: 'uint' + }, + logger: { + default: new logger_1.Logger('MongoClient'), + transform({ values: [value] }) { + if (value instanceof logger_1.Logger) { + return value; + } + utils_1.emitWarning('Alternative loggers might not be supported'); + // TODO: make Logger an interface that others can implement, make usage consistent in driver + // DRIVERS-1204 + } + }, + loggerLevel: { + target: 'logger', + transform({ values: [value] }) { + return new logger_1.Logger('MongoClient', { loggerLevel: value }); + } + }, + maxIdleTimeMS: { + default: 0, + type: 'uint' + }, + maxPoolSize: { + default: 100, + type: 'uint' + }, + maxStalenessSeconds: { + target: 'readPreference', + transform({ name, options, values: [value] }) { + const maxStalenessSeconds = getUint(name, value); + if (options.readPreference) { + return read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, maxStalenessSeconds } + }); + } + else { + return new read_preference_1.ReadPreference('secondary', undefined, { maxStalenessSeconds }); + } + } + }, + minInternalBufferSize: { + type: 'uint' + }, + minPoolSize: { + default: 0, + type: 'uint' + }, + minHeartbeatFrequencyMS: { + default: 500, + type: 'uint' + }, + monitorCommands: { + default: false, + type: 'boolean' + }, + name: { + target: 'driverInfo', + transform({ values: [value], options }) { + return { ...options.driverInfo, name: String(value) }; + } + }, + noDelay: { + default: true, + type: 'boolean' + }, + pkFactory: { + default: utils_1.DEFAULT_PK_FACTORY, + transform({ values: [value] }) { + if (utils_1.isRecord(value, ['createPk']) && typeof value.createPk === 'function') { + return value; + } + throw new error_1.MongoParseError(`Option pkFactory must be an object with a createPk function, got ${value}`); + } + }, + promiseLibrary: { + deprecated: true, + type: 'any' + }, + promoteBuffers: { + type: 'boolean' + }, + promoteLongs: { + type: 'boolean' + }, + promoteValues: { + type: 'boolean' + }, + raw: { + default: false, + type: 'boolean' + }, + readConcern: { + transform({ values: [value], options }) { + if (value instanceof read_concern_1.ReadConcern || utils_1.isRecord(value, ['level'])) { + return read_concern_1.ReadConcern.fromOptions({ ...options.readConcern, ...value }); + } + throw new error_1.MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`); + } + }, + readConcernLevel: { + target: 'readConcern', + transform({ values: [level], options }) { + return read_concern_1.ReadConcern.fromOptions({ + ...options.readConcern, + level: level + }); + } + }, + readPreference: { + default: read_preference_1.ReadPreference.primary, + transform({ values: [value], options }) { + var _a, _b, _c; + if (value instanceof read_preference_1.ReadPreference) { + return read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + }); + } + if (utils_1.isRecord(value, ['mode'])) { + const rp = read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + }); + if (rp) + return rp; + else + throw new error_1.MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`); + } + if (typeof value === 'string') { + const rpOpts = { + hedge: (_a = options.readPreference) === null || _a === void 0 ? void 0 : _a.hedge, + maxStalenessSeconds: (_b = options.readPreference) === null || _b === void 0 ? void 0 : _b.maxStalenessSeconds + }; + return new read_preference_1.ReadPreference(value, (_c = options.readPreference) === null || _c === void 0 ? void 0 : _c.tags, rpOpts); + } + } + }, + readPreferenceTags: { + target: 'readPreference', + transform({ values, options }) { + const readPreferenceTags = []; + for (const tag of values) { + const readPreferenceTag = Object.create(null); + if (typeof tag === 'string') { + for (const [k, v] of Object.entries(toRecord(tag))) { + readPreferenceTag[k] = v; + } + } + if (utils_1.isRecord(tag)) { + for (const [k, v] of Object.entries(tag)) { + readPreferenceTag[k] = v; + } + } + readPreferenceTags.push(readPreferenceTag); + } + return read_preference_1.ReadPreference.fromOptions({ + readPreference: options.readPreference, + readPreferenceTags + }); + } + }, + replicaSet: { + type: 'string' + }, + retryReads: { + default: true, + type: 'boolean' + }, + retryWrites: { + default: true, + type: 'boolean' + }, + serializeFunctions: { + type: 'boolean' + }, + serverSelectionTimeoutMS: { + default: 30000, + type: 'uint' + }, + servername: { + type: 'string' + }, + socketTimeoutMS: { + default: 0, + type: 'uint' + }, + ssl: { + target: 'tls', + type: 'boolean' + }, + sslCA: { + target: 'ca', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslCRL: { + target: 'crl', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslCert: { + target: 'cert', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslKey: { + target: 'key', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslPass: { + deprecated: true, + target: 'passphrase', + type: 'string' + }, + sslValidate: { + target: 'rejectUnauthorized', + type: 'boolean' + }, + tls: { + type: 'boolean' + }, + tlsAllowInvalidCertificates: { + target: 'rejectUnauthorized', + transform({ name, values: [value] }) { + // allowInvalidCertificates is the inverse of rejectUnauthorized + return !getBoolean(name, value); + } + }, + tlsAllowInvalidHostnames: { + target: 'checkServerIdentity', + transform({ name, values: [value] }) { + // tlsAllowInvalidHostnames means setting the checkServerIdentity function to a noop + return getBoolean(name, value) ? () => undefined : undefined; + } + }, + tlsCAFile: { + target: 'ca', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateFile: { + target: 'cert', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateKeyFile: { + target: 'key', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateKeyFilePassword: { + target: 'passphrase', + type: 'any' + }, + tlsInsecure: { + transform({ name, options, values: [value] }) { + const tlsInsecure = getBoolean(name, value); + if (tlsInsecure) { + options.checkServerIdentity = () => undefined; + options.rejectUnauthorized = false; + } + else { + options.checkServerIdentity = options.tlsAllowInvalidHostnames + ? () => undefined + : undefined; + options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true; + } + return tlsInsecure; + } + }, + w: { + target: 'writeConcern', + transform({ values: [value], options }) { + return write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value } }); + } + }, + waitQueueTimeoutMS: { + default: 0, + type: 'uint' + }, + writeConcern: { + target: 'writeConcern', + transform({ values: [value], options }) { + if (utils_1.isRecord(value) || value instanceof write_concern_1.WriteConcern) { + return write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + ...value + } + }); + } + else if (value === 'majority' || typeof value === 'number') { + return write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + w: value + } + }); + } + throw new error_1.MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`); + } + }, + wtimeout: { + deprecated: 'Please use wtimeoutMS instead', + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeout: getUint('wtimeout', value) + } + }); + if (wc) + return wc; + throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + }, + wtimeoutMS: { + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeoutMS: getUint('wtimeoutMS', value) + } + }); + if (wc) + return wc; + throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + }, + zlibCompressionLevel: { + default: 0, + type: 'int' + }, + // Custom types for modifying core behavior + connectionType: { type: 'any' }, + srvPoller: { type: 'any' }, + // Accepted NodeJS Options + minDHSize: { type: 'any' }, + pskCallback: { type: 'any' }, + secureContext: { type: 'any' }, + enableTrace: { type: 'any' }, + requestCert: { type: 'any' }, + rejectUnauthorized: { type: 'any' }, + checkServerIdentity: { type: 'any' }, + ALPNProtocols: { type: 'any' }, + SNICallback: { type: 'any' }, + session: { type: 'any' }, + requestOCSP: { type: 'any' }, + localAddress: { type: 'any' }, + localPort: { type: 'any' }, + hints: { type: 'any' }, + lookup: { type: 'any' }, + ca: { type: 'any' }, + cert: { type: 'any' }, + ciphers: { type: 'any' }, + crl: { type: 'any' }, + ecdhCurve: { type: 'any' }, + key: { type: 'any' }, + passphrase: { type: 'any' }, + pfx: { type: 'any' }, + secureProtocol: { type: 'any' }, + index: { type: 'any' }, + // Legacy Options, these are unused but left here to avoid errors with CSFLE lib + useNewUrlParser: { type: 'boolean' }, + useUnifiedTopology: { type: 'boolean' } +}; +exports.DEFAULT_OPTIONS = new CaseInsensitiveMap(Object.entries(exports.OPTIONS) + .filter(([, descriptor]) => descriptor.default != null) + .map(([k, d]) => [k, d.default])); +//# sourceMappingURL=connection_string.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/connection_string.js.map b/node_modules/mongodb/lib/connection_string.js.map new file mode 100644 index 0000000..866db75 --- /dev/null +++ b/node_modules/mongodb/lib/connection_string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_string.js","sourceRoot":"","sources":["../src/connection_string.ts"],"names":[],"mappings":";;;AAAA,2BAA2B;AAC3B,yBAAyB;AACzB,iFAA6D;AAC7D,6BAAsC;AACtC,2EAAiE;AACjE,uDAAuE;AACvE,iDAA+D;AAC/D,mDAAkD;AAClD,mCAAoF;AACpF,mCASiB;AAEjB,iDAQwB;AACxB,qEAAiE;AAEjE,qCAA+C;AAC/C,yDAAqD;AACrD,2CAAwC;AACxC,kEAA8E;AAE9E,MAAM,iBAAiB,GAAG,CAAC,YAAY,EAAE,YAAY,EAAE,cAAc,CAAC,CAAC;AAEvE,MAAM,oBAAoB,GAAG,kEAAkE,CAAC;AAChG,MAAM,oBAAoB,GAAG,4DAA4D,CAAC;AAC1F,MAAM,0BAA0B,GAC9B,qEAAqE,CAAC;AAExE;;;;;;;GAOG;AACH,SAAS,mBAAmB,CAAC,UAAkB,EAAE,YAAoB;IACnE,MAAM,KAAK,GAAG,QAAQ,CAAC;IACvB,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC;IAChD,MAAM,MAAM,GAAG,IAAI,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC;IACrD,OAAO,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAAC,OAAqB,EAAE,QAAiC;IACvF,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,EAAE;QACvC,OAAO,QAAQ,CAAC,IAAI,qBAAa,CAAC,oCAAoC,CAAC,CAAC,CAAC;KAC1E;IAED,IAAI,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG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ongodb/lib/constants.js b/node_modules/mongodb/lib/constants.js new file mode 100644 index 0000000..f7ee653 --- /dev/null +++ b/node_modules/mongodb/lib/constants.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SYSTEM_JS_COLLECTION = exports.SYSTEM_COMMAND_COLLECTION = exports.SYSTEM_USER_COLLECTION = exports.SYSTEM_PROFILE_COLLECTION = exports.SYSTEM_INDEX_COLLECTION = exports.SYSTEM_NAMESPACE_COLLECTION = void 0; +exports.SYSTEM_NAMESPACE_COLLECTION = 'system.namespaces'; +exports.SYSTEM_INDEX_COLLECTION = 'system.indexes'; +exports.SYSTEM_PROFILE_COLLECTION = 'system.profile'; +exports.SYSTEM_USER_COLLECTION = 'system.users'; +exports.SYSTEM_COMMAND_COLLECTION = '$cmd'; +exports.SYSTEM_JS_COLLECTION = 'system.js'; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/constants.js.map b/node_modules/mongodb/lib/constants.js.map new file mode 100644 index 0000000..67df39c --- /dev/null +++ b/node_modules/mongodb/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,2BAA2B,GAAG,mBAAmB,CAAC;AAClD,QAAA,uBAAuB,GAAG,gBAAgB,CAAC;AAC3C,QAAA,yBAAyB,GAAG,gBAAgB,CAAC;AAC7C,QAAA,sBAAsB,GAAG,cAAc,CAAC;AACxC,QAAA,yBAAyB,GAAG,MAAM,CAAC;AACnC,QAAA,oBAAoB,GAAG,WAAW,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cursor/abstract_cursor.js b/node_modules/mongodb/lib/cursor/abstract_cursor.js new file mode 100644 index 0000000..a63d178 --- /dev/null +++ b/node_modules/mongodb/lib/cursor/abstract_cursor.js @@ -0,0 +1,629 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assertUninitialized = exports.AbstractCursor = exports.CURSOR_FLAGS = void 0; +const utils_1 = require("../utils"); +const bson_1 = require("../bson"); +const sessions_1 = require("../sessions"); +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const stream_1 = require("stream"); +const read_concern_1 = require("../read_concern"); +const mongo_types_1 = require("../mongo_types"); +/** @internal */ +const kId = Symbol('id'); +/** @internal */ +const kDocuments = Symbol('documents'); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kNamespace = Symbol('namespace'); +/** @internal */ +const kTopology = Symbol('topology'); +/** @internal */ +const kSession = Symbol('session'); +/** @internal */ +const kOptions = Symbol('options'); +/** @internal */ +const kTransform = Symbol('transform'); +/** @internal */ +const kInitialized = Symbol('initialized'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kKilled = Symbol('killed'); +/** @public */ +exports.CURSOR_FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +]; +/** @public */ +class AbstractCursor extends mongo_types_1.TypedEventEmitter { + /** @internal */ + constructor(topology, namespace, options = {}) { + super(); + this[kTopology] = topology; + this[kNamespace] = namespace; + this[kDocuments] = []; // TODO: https://github.com/microsoft/TypeScript/issues/36230 + this[kInitialized] = false; + this[kClosed] = false; + this[kKilled] = false; + this[kOptions] = { + readPreference: options.readPreference && options.readPreference instanceof read_preference_1.ReadPreference + ? options.readPreference + : read_preference_1.ReadPreference.primary, + ...bson_1.pluckBSONSerializeOptions(options) + }; + const readConcern = read_concern_1.ReadConcern.fromOptions(options); + if (readConcern) { + this[kOptions].readConcern = readConcern; + } + if (typeof options.batchSize === 'number') { + this[kOptions].batchSize = options.batchSize; + } + if (options.comment != null) { + this[kOptions].comment = options.comment; + } + if (typeof options.maxTimeMS === 'number') { + this[kOptions].maxTimeMS = options.maxTimeMS; + } + if (options.session instanceof sessions_1.ClientSession) { + this[kSession] = options.session; + } + } + get id() { + return this[kId]; + } + /** @internal */ + get topology() { + return this[kTopology]; + } + /** @internal */ + get server() { + return this[kServer]; + } + get namespace() { + return this[kNamespace]; + } + get readPreference() { + return this[kOptions].readPreference; + } + get readConcern() { + return this[kOptions].readConcern; + } + /** @internal */ + get session() { + return this[kSession]; + } + set session(clientSession) { + this[kSession] = clientSession; + } + /** @internal */ + get cursorOptions() { + return this[kOptions]; + } + get closed() { + return this[kClosed]; + } + get killed() { + return this[kKilled]; + } + get loadBalanced() { + return this[kTopology].loadBalanced; + } + /** Returns current buffered documents length */ + bufferedCount() { + return this[kDocuments].length; + } + /** Returns current buffered documents */ + readBufferedDocuments(number) { + return this[kDocuments].splice(0, number !== null && number !== void 0 ? number : this[kDocuments].length); + } + [Symbol.asyncIterator]() { + return { + next: () => this.next().then(value => value != null ? { value, done: false } : { value: undefined, done: true }) + }; + } + stream(options) { + if (options === null || options === void 0 ? void 0 : options.transform) { + const transform = options.transform; + const readable = makeCursorStream(this); + return readable.pipe(new stream_1.Transform({ + objectMode: true, + highWaterMark: 1, + transform(chunk, _, callback) { + try { + const transformed = transform(chunk); + callback(undefined, transformed); + } + catch (err) { + callback(err); + } + } + })); + } + return makeCursorStream(this); + } + hasNext(callback) { + return utils_1.maybePromise(callback, done => { + if (this[kId] === bson_1.Long.ZERO) { + return done(undefined, false); + } + if (this[kDocuments].length) { + return done(undefined, true); + } + next(this, true, (err, doc) => { + if (err) + return done(err); + if (doc) { + this[kDocuments].unshift(doc); + done(undefined, true); + return; + } + done(undefined, false); + }); + }); + } + next(callback) { + return utils_1.maybePromise(callback, done => { + if (this[kId] === bson_1.Long.ZERO) { + return done(new error_1.MongoCursorExhaustedError()); + } + next(this, true, done); + }); + } + tryNext(callback) { + return utils_1.maybePromise(callback, done => { + if (this[kId] === bson_1.Long.ZERO) { + return done(new error_1.MongoCursorExhaustedError()); + } + next(this, false, done); + }); + } + forEach(iterator, callback) { + if (typeof iterator !== 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "iterator" must be a function'); + } + return utils_1.maybePromise(callback, done => { + const transform = this[kTransform]; + const fetchDocs = () => { + next(this, true, (err, doc) => { + if (err || doc == null) + return done(err); + let result; + // NOTE: no need to transform because `next` will do this automatically + try { + result = iterator(doc); // TODO(NODE-3283): Improve transform typing + } + catch (error) { + return done(error); + } + if (result === false) + return done(); + // these do need to be transformed since they are copying the rest of the batch + const internalDocs = this[kDocuments].splice(0, this[kDocuments].length); + for (let i = 0; i < internalDocs.length; ++i) { + try { + result = iterator((transform ? transform(internalDocs[i]) : internalDocs[i]) // TODO(NODE-3283): Improve transform typing + ); + } + catch (error) { + return done(error); + } + if (result === false) + return done(); + } + fetchDocs(); + }); + }; + fetchDocs(); + }); + } + close(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + const needsToEmitClosed = !this[kClosed]; + this[kClosed] = true; + return utils_1.maybePromise(callback, done => cleanupCursor(this, { needsToEmitClosed }, done)); + } + toArray(callback) { + return utils_1.maybePromise(callback, done => { + const docs = []; + const transform = this[kTransform]; + const fetchDocs = () => { + // NOTE: if we add a `nextBatch` then we should use it here + next(this, true, (err, doc) => { + if (err) + return done(err); + if (doc == null) + return done(undefined, docs); + // NOTE: no need to transform because `next` will do this automatically + docs.push(doc); + // these do need to be transformed since they are copying the rest of the batch + const internalDocs = (transform + ? this[kDocuments].splice(0, this[kDocuments].length).map(transform) + : this[kDocuments].splice(0, this[kDocuments].length)); // TODO(NODE-3283): Improve transform typing + if (internalDocs) { + docs.push(...internalDocs); + } + fetchDocs(); + }); + }; + fetchDocs(); + }); + } + /** + * Add a cursor flag to the cursor + * + * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. + * @param value - The flag boolean value. + */ + addCursorFlag(flag, value) { + assertUninitialized(this); + if (!exports.CURSOR_FLAGS.includes(flag)) { + throw new error_1.MongoInvalidArgumentError(`Flag ${flag} is not one of ${exports.CURSOR_FLAGS}`); + } + if (typeof value !== 'boolean') { + throw new error_1.MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`); + } + this[kOptions][flag] = value; + return this; + } + /** + * Map all documents using the provided function + * If there is a transform set on the cursor, that will be called first and the result passed to + * this function's transform. + * + * @remarks + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling map, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor = coll.find(); + * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); + * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] + * ``` + * @param transform - The mapping transformation method. + */ + map(transform) { + assertUninitialized(this); + const oldTransform = this[kTransform]; // TODO(NODE-3283): Improve transform typing + if (oldTransform) { + this[kTransform] = doc => { + return transform(oldTransform(doc)); + }; + } + else { + this[kTransform] = transform; + } + return this; + } + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadPreference(readPreference) { + assertUninitialized(this); + if (readPreference instanceof read_preference_1.ReadPreference) { + this[kOptions].readPreference = readPreference; + } + else if (typeof readPreference === 'string') { + this[kOptions].readPreference = read_preference_1.ReadPreference.fromString(readPreference); + } + else { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`); + } + return this; + } + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadConcern(readConcern) { + assertUninitialized(this); + const resolvedReadConcern = read_concern_1.ReadConcern.fromOptions({ readConcern }); + if (resolvedReadConcern) { + this[kOptions].readConcern = resolvedReadConcern; + } + return this; + } + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value) { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + this[kOptions].maxTimeMS = value; + return this; + } + /** + * Set the batch size for the cursor. + * + * @param value - The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + */ + batchSize(value) { + assertUninitialized(this); + if (this[kOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support batchSize'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "batchSize" requires an integer'); + } + this[kOptions].batchSize = value; + return this; + } + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind() { + if (!this[kInitialized]) { + return; + } + this[kId] = undefined; + this[kDocuments] = []; + this[kClosed] = false; + this[kKilled] = false; + this[kInitialized] = false; + const session = this[kSession]; + if (session) { + // We only want to end this session if we created it, and it hasn't ended yet + if (session.explicit === false && !session.hasEnded) { + session.endSession(); + } + this[kSession] = undefined; + } + } + /** @internal */ + _getMore(batchSize, callback) { + const cursorId = this[kId]; + const cursorNs = this[kNamespace]; + const server = this[kServer]; + if (cursorId == null) { + callback(new error_1.MongoRuntimeError('Unable to iterate cursor with no id')); + return; + } + if (server == null) { + callback(new error_1.MongoRuntimeError('Unable to iterate cursor without selected server')); + return; + } + server.getMore(cursorNs, cursorId, { + ...this[kOptions], + session: this[kSession], + batchSize + }, callback); + } +} +exports.AbstractCursor = AbstractCursor; +/** @event */ +AbstractCursor.CLOSE = 'close'; +function nextDocument(cursor) { + if (cursor[kDocuments] == null || !cursor[kDocuments].length) { + return null; + } + const doc = cursor[kDocuments].shift(); + if (doc) { + const transform = cursor[kTransform]; + if (transform) { + return transform(doc); + } + return doc; + } + return null; +} +function next(cursor, blocking, callback) { + const cursorId = cursor[kId]; + if (cursor.closed) { + return callback(undefined, null); + } + if (cursor[kDocuments] && cursor[kDocuments].length) { + callback(undefined, nextDocument(cursor)); + return; + } + if (cursorId == null) { + // All cursors must operate within a session, one must be made implicitly if not explicitly provided + if (cursor[kSession] == null && cursor[kTopology].hasSessionSupport()) { + cursor[kSession] = cursor[kTopology].startSession({ owner: cursor, explicit: false }); + } + cursor._initialize(cursor[kSession], (err, state) => { + if (state) { + const response = state.response; + cursor[kServer] = state.server; + cursor[kSession] = state.session; + if (response.cursor) { + cursor[kId] = + typeof response.cursor.id === 'number' + ? bson_1.Long.fromNumber(response.cursor.id) + : response.cursor.id; + if (response.cursor.ns) { + cursor[kNamespace] = utils_1.ns(response.cursor.ns); + } + cursor[kDocuments] = response.cursor.firstBatch; + } + else { + // NOTE: This is for support of older servers (<3.2) which do not use commands + cursor[kId] = + typeof response.cursorId === 'number' + ? bson_1.Long.fromNumber(response.cursorId) + : response.cursorId; + cursor[kDocuments] = response.documents; + } + // When server responses return without a cursor document, we close this cursor + // and return the raw server response. This is often the case for explain commands + // for example + if (cursor[kId] == null) { + cursor[kId] = bson_1.Long.ZERO; + // TODO(NODE-3286): ExecutionResult needs to accept a generic parameter + cursor[kDocuments] = [state.response]; + } + } + // the cursor is now initialized, even if an error occurred or it is dead + cursor[kInitialized] = true; + if (err || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error: err }, () => callback(err, nextDocument(cursor))); + } + next(cursor, blocking, callback); + }); + return; + } + if (cursorIsDead(cursor)) { + return cleanupCursor(cursor, undefined, () => callback(undefined, null)); + } + // otherwise need to call getMore + const batchSize = cursor[kOptions].batchSize || 1000; + cursor._getMore(batchSize, (err, response) => { + if (response) { + const cursorId = typeof response.cursor.id === 'number' + ? bson_1.Long.fromNumber(response.cursor.id) + : response.cursor.id; + cursor[kDocuments] = response.cursor.nextBatch; + cursor[kId] = cursorId; + } + if (err || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error: err }, () => callback(err, nextDocument(cursor))); + } + if (cursor[kDocuments].length === 0 && blocking === false) { + return callback(undefined, null); + } + next(cursor, blocking, callback); + }); +} +function cursorIsDead(cursor) { + const cursorId = cursor[kId]; + return !!cursorId && cursorId.isZero(); +} +function cleanupCursor(cursor, options, callback) { + var _a; + const cursorId = cursor[kId]; + const cursorNs = cursor[kNamespace]; + const server = cursor[kServer]; + const session = cursor[kSession]; + const error = options === null || options === void 0 ? void 0 : options.error; + const needsToEmitClosed = (_a = options === null || options === void 0 ? void 0 : options.needsToEmitClosed) !== null && _a !== void 0 ? _a : cursor[kDocuments].length === 0; + if (error) { + if (cursor.loadBalanced && error instanceof error_1.MongoNetworkError) { + return completeCleanup(); + } + } + if (cursorId == null || server == null || cursorId.isZero() || cursorNs == null) { + if (needsToEmitClosed) { + cursor[kClosed] = true; + cursor[kId] = bson_1.Long.ZERO; + cursor.emit(AbstractCursor.CLOSE); + } + if (session) { + if (session.owner === cursor) { + return session.endSession({ error }, callback); + } + if (!session.inTransaction()) { + sessions_1.maybeClearPinnedConnection(session, { error }); + } + } + return callback(); + } + function completeCleanup() { + if (session) { + if (session.owner === cursor) { + return session.endSession({ error }, () => { + cursor.emit(AbstractCursor.CLOSE); + callback(); + }); + } + if (!session.inTransaction()) { + sessions_1.maybeClearPinnedConnection(session, { error }); + } + } + cursor.emit(AbstractCursor.CLOSE); + return callback(); + } + cursor[kKilled] = true; + server.killCursors(cursorNs, [cursorId], { ...bson_1.pluckBSONSerializeOptions(cursor[kOptions]), session }, () => completeCleanup()); +} +/** @internal */ +function assertUninitialized(cursor) { + if (cursor[kInitialized]) { + throw new error_1.MongoCursorInUseError(); + } +} +exports.assertUninitialized = assertUninitialized; +function makeCursorStream(cursor) { + const readable = new stream_1.Readable({ + objectMode: true, + autoDestroy: false, + highWaterMark: 1 + }); + let initialized = false; + let reading = false; + let needToClose = true; // NOTE: we must close the cursor if we never read from it, use `_construct` in future node versions + readable._read = function () { + if (initialized === false) { + needToClose = false; + initialized = true; + } + if (!reading) { + reading = true; + readNext(); + } + }; + readable._destroy = function (error, cb) { + if (needToClose) { + cursor.close(err => process.nextTick(cb, err || error)); + } + else { + cb(error); + } + }; + function readNext() { + needToClose = false; + next(cursor, true, (err, result) => { + needToClose = err ? !cursor.closed : result != null; + if (err) { + // NOTE: This is questionable, but we have a test backing the behavior. It seems the + // desired behavior is that a stream ends cleanly when a user explicitly closes + // a client during iteration. Alternatively, we could do the "right" thing and + // propagate the error message by removing this special case. + if (err.message.match(/server is closed/)) { + cursor.close(); + return readable.push(null); + } + // NOTE: This is also perhaps questionable. The rationale here is that these errors tend + // to be "operation interrupted", where a cursor has been closed but there is an + // active getMore in-flight. This used to check if the cursor was killed but once + // that changed to happen in cleanup legitimate errors would not destroy the + // stream. There are change streams test specifically test these cases. + if (err.message.match(/interrupted/)) { + return readable.push(null); + } + return readable.destroy(err); + } + if (result == null) { + readable.push(null); + } + else if (readable.destroyed) { + cursor.close(); + } + else { + if (readable.push(result)) { + return readNext(); + } + reading = false; + } + }); + } + return readable; +} +//# sourceMappingURL=abstract_cursor.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cursor/abstract_cursor.js.map b/node_modules/mongodb/lib/cursor/abstract_cursor.js.map new file mode 100644 index 0000000..30b3074 --- /dev/null +++ b/node_modules/mongodb/lib/cursor/abstract_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract_cursor.js","sourceRoot":"","sources":["../../src/cursor/abstract_cursor.ts"],"names":[],"mappings":";;;AAAA,oCAAwE;AACxE,kCAA0F;AAC1F,0CAAwE;AACxE,oCAQkB;AAClB,wDAAwE;AAGxE,mCAA6C;AAE7C,kDAA+D;AAC/D,gDAAmE;AAEnE,gBAAgB;AAChB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;AACzB,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,SAAS,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;AACrC,gBAAgB;AAChB,MAAM,QA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C5B;gBAED,wFAAwF;gBACxF,sFAAsF;gBACtF,uFAAuF;gBACvF,kFAAkF;gBAClF,6EAA6E;gBAC7E,IAAI,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,aAAa,CAAC,EAAE;oBACpC,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;iBAC5B;gBAED,OAAO,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;aAC9B;YAED,IAAI,MAAM,IAAI,IAAI,EAAE;gBAClB,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;aACrB;iBAAM,IAAI,QAAQ,CAAC,SAAS,EAAE;gBAC7B,MAAM,CAAC,KAAK,EAAE,CAAC;aAChB;iBAAM;gBACL,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;oBACzB,OAAO,QAAQ,EAAE,CAAC;iBACnB;gBAED,OAAO,GAAG,KAAK,CAAC;aACjB;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cursor/aggregation_cursor.js b/node_modules/mongodb/lib/cursor/aggregation_cursor.js new file mode 100644 index 0000000..21ee2c0 --- /dev/null +++ b/node_modules/mongodb/lib/cursor/aggregation_cursor.js @@ -0,0 +1,172 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregationCursor = void 0; +const aggregate_1 = require("../operations/aggregate"); +const abstract_cursor_1 = require("./abstract_cursor"); +const execute_operation_1 = require("../operations/execute_operation"); +const utils_1 = require("../utils"); +/** @internal */ +const kPipeline = Symbol('pipeline'); +/** @internal */ +const kOptions = Symbol('options'); +/** + * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * @public + */ +class AggregationCursor extends abstract_cursor_1.AbstractCursor { + /** @internal */ + constructor(topology, namespace, pipeline = [], options = {}) { + super(topology, namespace, options); + this[kPipeline] = pipeline; + this[kOptions] = options; + } + get pipeline() { + return this[kPipeline]; + } + clone() { + const clonedOptions = utils_1.mergeOptions({}, this[kOptions]); + delete clonedOptions.session; + return new AggregationCursor(this.topology, this.namespace, this[kPipeline], { + ...clonedOptions + }); + } + map(transform) { + return super.map(transform); + } + /** @internal */ + _initialize(session, callback) { + const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + session + }); + execute_operation_1.executeOperation(this.topology, aggregateOperation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: NODE-2882 + callback(undefined, { server: aggregateOperation.server, session, response }); + }); + } + explain(verbosity, callback) { + if (typeof verbosity === 'function') + (callback = verbosity), (verbosity = true); + if (verbosity == null) + verbosity = true; + return execute_operation_1.executeOperation(this.topology, new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + explain: verbosity + }), callback); + } + group($group) { + abstract_cursor_1.assertUninitialized(this); + this[kPipeline].push({ $group }); + return this; + } + /** Add a limit stage to the aggregation pipeline */ + limit($limit) { + abstract_cursor_1.assertUninitialized(this); + this[kPipeline].push({ $limit }); + return this; + } + /** Add a match stage to the aggregation pipeline */ + match($match) { + abstract_cursor_1.assertUninitialized(this); + this[kPipeline].push({ $match }); + return this; + } + /** Add an out stage to the aggregation pipeline */ + out($out) { + abstract_cursor_1.assertUninitialized(this); + this[kPipeline].push({ $out }); + return this; + } + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.aggregate().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project($project) { + abstract_cursor_1.assertUninitialized(this); + this[kPipeline].push({ $project }); + return this; + } + /** Add a lookup stage to the aggregation pipeline */ + lookup($lookup) { + abstract_cursor_1.assertUninitialized(this); + this[kPipeline].push({ $lookup }); + return this; + } + /** Add a redact stage to the aggregation pipeline */ + redact($redact) { + abstract_cursor_1.assertUninitialized(this); + this[kPipeline].push({ $redact }); + return this; + } + /** Add a skip stage to the aggregation pipeline */ + skip($skip) { + abstract_cursor_1.assertUninitialized(this); + this[kPipeline].push({ $skip }); + return this; + } + /** Add a sort stage to the aggregation pipeline */ + sort($sort) { + abstract_cursor_1.assertUninitialized(this); + this[kPipeline].push({ $sort }); + return this; + } + /** Add a unwind stage to the aggregation pipeline */ + unwind($unwind) { + abstract_cursor_1.assertUninitialized(this); + this[kPipeline].push({ $unwind }); + return this; + } + // deprecated methods + /** @deprecated Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear) { + abstract_cursor_1.assertUninitialized(this); + this[kPipeline].push({ $geoNear }); + return this; + } +} +exports.AggregationCursor = AggregationCursor; +//# sourceMappingURL=aggregation_cursor.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map b/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map new file mode 100644 index 0000000..d21e89f --- /dev/null +++ b/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aggregation_cursor.js","sourceRoot":"","sources":["../../src/cursor/aggregation_cursor.ts"],"names":[],"mappings":";;;AAAA,uDAA+E;AAC/E,uDAAwE;AACxE,uEAAoF;AACpF,oCAAwC;AAYxC,gBAAgB;AAChB,MAAM,SAAS,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;AACrC,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AAEnC;;;;;;GAMG;AACH,MAAa,iBAAsC,SAAQ,gCAAuB;IAMhF,gBAAgB;IAChB,YACE,QAAkB,EAClB,SAA2B,EAC3B,WAAuB,EAAE,EACzB,UAA4B,EAAE;QAE9B,KAAK,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;QAEpC,IAAI,CAAC,SAAS,CAAC,GAAG,QAAQ,CAAC;QAC3B,IAAI,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC;IAC3B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC;IACzB,CAAC;IAED,KAAK;QACH,MAAM,aAAa,GAAG,oBAAY,CAAC,EAAE,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QACvD,OAAO,aAAa,CAAC,OAAO,CAAC;QAC7B,OAAO,IAAI,iBAAiB,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE;YAC3E,GAAG,aAAa;SACjB,CAAC,CAAC;IACL,CAAC;IAED,GAAG,CAAI,SAA8B;QACnC,OAAO,KAAK,CAAC,GAAG,CAAC,SAAS,CAAyB,CAAC;IACtD,CAAC;IAED,gBAAgB;IAChB,WAAW,CAAC,OAAkC,EAAE,QAAmC;QACjF,MAAM,kBAAkB,GAAG,IAAI,8BAAkB,CAAC,IAAI,CAAC,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,EAAE,KAAK,EAAE,CAAC,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,mDAAmD;IACnD,IAAI,CAAC,KAAW;QACd,qCAAmB,CAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,qDAAqD;IACrD,MAAM,CAAC,OAA0B;QAC/B,qCAAmB,CAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC;QAClC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,qBAAqB;IACrB,kEAAkE;IAClE,OAAO,CAAC,QAAkB;QACxB,qCAAmB,CAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;QACnC,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA/LD,8CA+LC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/cursor/find_cursor.js b/node_modules/mongodb/lib/cursor/find_cursor.js new file mode 100644 index 0000000..d56493b --- /dev/null +++ b/node_modules/mongodb/lib/cursor/find_cursor.js @@ -0,0 +1,376 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FindCursor = exports.FLAGS = void 0; +const error_1 = require("../error"); +const count_1 = require("../operations/count"); +const execute_operation_1 = require("../operations/execute_operation"); +const find_1 = require("../operations/find"); +const utils_1 = require("../utils"); +const sort_1 = require("../sort"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @internal */ +const kFilter = Symbol('filter'); +/** @internal */ +const kNumReturned = Symbol('numReturned'); +/** @internal */ +const kBuiltOptions = Symbol('builtOptions'); +/** @public Flags allowed for cursor */ +exports.FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +]; +/** @public */ +class FindCursor extends abstract_cursor_1.AbstractCursor { + /** @internal */ + constructor(topology, namespace, filter, options = {}) { + super(topology, namespace, options); + this[kFilter] = filter || {}; + this[kBuiltOptions] = options; + if (options.sort != null) { + this[kBuiltOptions].sort = sort_1.formatSort(options.sort); + } + } + clone() { + const clonedOptions = utils_1.mergeOptions({}, this[kBuiltOptions]); + delete clonedOptions.session; + return new FindCursor(this.topology, this.namespace, this[kFilter], { + ...clonedOptions + }); + } + map(transform) { + return super.map(transform); + } + /** @internal */ + _initialize(session, callback) { + const findOperation = new find_1.FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + session + }); + execute_operation_1.executeOperation(this.topology, findOperation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: We only need this for legacy queries that do not support `limit`, maybe + // the value should only be saved in those cases. + if (response.cursor) { + this[kNumReturned] = response.cursor.firstBatch.length; + } + else { + this[kNumReturned] = response.documents ? response.documents.length : 0; + } + // TODO: NODE-2882 + callback(undefined, { server: findOperation.server, session, response }); + }); + } + /** @internal */ + _getMore(batchSize, callback) { + // NOTE: this is to support client provided limits in pre-command servers + const numReturned = this[kNumReturned]; + if (numReturned) { + const limit = this[kBuiltOptions].limit; + batchSize = + limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize; + if (batchSize <= 0) { + return this.close(callback); + } + } + super._getMore(batchSize, (err, response) => { + if (err) + return callback(err); + // TODO: wrap this in some logic to prevent it from happening if we don't need this support + if (response) { + this[kNumReturned] = this[kNumReturned] + response.cursor.nextBatch.length; + } + callback(undefined, response); + }); + } + count(options, callback) { + if (typeof options === 'boolean') { + throw new error_1.MongoInvalidArgumentError('Invalid first parameter to count'); + } + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return execute_operation_1.executeOperation(this.topology, new count_1.CountOperation(this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + ...options + }), callback); + } + explain(verbosity, callback) { + if (typeof verbosity === 'function') + (callback = verbosity), (verbosity = true); + if (verbosity == null) + verbosity = true; + return execute_operation_1.executeOperation(this.topology, new find_1.FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + explain: verbosity + }), callback); + } + /** Set the cursor query */ + filter(filter) { + abstract_cursor_1.assertUninitialized(this); + this[kFilter] = filter; + return this; + } + /** + * Set the cursor hint + * + * @param hint - If specified, then the query system will only consider plans using the hinted index. + */ + hint(hint) { + abstract_cursor_1.assertUninitialized(this); + this[kBuiltOptions].hint = hint; + return this; + } + /** + * Set the cursor min + * + * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + */ + min(min) { + abstract_cursor_1.assertUninitialized(this); + this[kBuiltOptions].min = min; + return this; + } + /** + * Set the cursor max + * + * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + */ + max(max) { + abstract_cursor_1.assertUninitialized(this); + this[kBuiltOptions].max = max; + return this; + } + /** + * Set the cursor returnKey. + * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. + * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * + * @param value - the returnKey value. + */ + returnKey(value) { + abstract_cursor_1.assertUninitialized(this); + this[kBuiltOptions].returnKey = value; + return this; + } + /** + * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. + * + * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + */ + showRecordId(value) { + abstract_cursor_1.assertUninitialized(this); + this[kBuiltOptions].showRecordId = value; + return this; + } + /** + * Add a query modifier to the cursor query + * + * @param name - The query modifier (must start with $, such as $orderby etc) + * @param value - The modifier value. + */ + addQueryModifier(name, value) { + abstract_cursor_1.assertUninitialized(this); + if (name[0] !== '$') { + throw new error_1.MongoInvalidArgumentError(`${name} is not a valid query modifier`); + } + // Strip of the $ + const field = name.substr(1); + // NOTE: consider some TS magic for this + switch (field) { + case 'comment': + this[kBuiltOptions].comment = value; + break; + case 'explain': + this[kBuiltOptions].explain = value; + break; + case 'hint': + this[kBuiltOptions].hint = value; + break; + case 'max': + this[kBuiltOptions].max = value; + break; + case 'maxTimeMS': + this[kBuiltOptions].maxTimeMS = value; + break; + case 'min': + this[kBuiltOptions].min = value; + break; + case 'orderby': + this[kBuiltOptions].sort = sort_1.formatSort(value); + break; + case 'query': + this[kFilter] = value; + break; + case 'returnKey': + this[kBuiltOptions].returnKey = value; + break; + case 'showDiskLoc': + this[kBuiltOptions].showRecordId = value; + break; + default: + throw new error_1.MongoInvalidArgumentError(`Invalid query modifier: ${name}`); + } + return this; + } + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * + * @param value - The comment attached to this query. + */ + comment(value) { + abstract_cursor_1.assertUninitialized(this); + this[kBuiltOptions].comment = value; + return this; + } + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * + * @param value - Number of milliseconds to wait before aborting the tailed query. + */ + maxAwaitTimeMS(value) { + abstract_cursor_1.assertUninitialized(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxAwaitTimeMS must be a number'); + } + this[kBuiltOptions].maxAwaitTimeMS = value; + return this; + } + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value) { + abstract_cursor_1.assertUninitialized(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + this[kBuiltOptions].maxTimeMS = value; + return this; + } + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic + * {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: FindCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.find().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project(value) { + abstract_cursor_1.assertUninitialized(this); + this[kBuiltOptions].projection = value; + return this; + } + /** + * Sets the sort order of the cursor query. + * + * @param sort - The key or keys set for the sort. + * @param direction - The direction of the sorting (1 or -1). + */ + sort(sort, direction) { + abstract_cursor_1.assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support sorting'); + } + this[kBuiltOptions].sort = sort_1.formatSort(sort, direction); + return this; + } + /** + * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) + * + * @remarks + * {@link https://docs.mongodb.com/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} + */ + allowDiskUse() { + abstract_cursor_1.assertUninitialized(this); + if (!this[kBuiltOptions].sort) { + throw new error_1.MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification'); + } + this[kBuiltOptions].allowDiskUse = true; + return this; + } + /** + * Set the collation options for the cursor. + * + * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + */ + collation(value) { + abstract_cursor_1.assertUninitialized(this); + this[kBuiltOptions].collation = value; + return this; + } + /** + * Set the limit for the cursor. + * + * @param value - The limit for the cursor query. + */ + limit(value) { + abstract_cursor_1.assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support limit'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "limit" requires an integer'); + } + this[kBuiltOptions].limit = value; + return this; + } + /** + * Set the skip for the cursor. + * + * @param value - The skip for the cursor query. + */ + skip(value) { + abstract_cursor_1.assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support skip'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "skip" requires an integer'); + } + this[kBuiltOptions].skip = value; + return this; + } +} +exports.FindCursor = FindCursor; +//# sourceMappingURL=find_cursor.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/cursor/find_cursor.js.map b/node_modules/mongodb/lib/cursor/find_cursor.js.map new file mode 100644 index 0000000..66efed8 --- /dev/null +++ b/node_modules/mongodb/lib/cursor/find_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"find_cursor.js","sourceRoot":"","sources":["../../src/cursor/find_cursor.ts"],"names":[],"mappings":";;;AACA,oCAA+E;AAE/E,+CAAmE;AACnE,uEAAoF;AACpF,6CAAgE;AAChE,oCAAwC;AAKxC,kCAA0D;AAE1D,uDAAwE;AAExE,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC;AAE7C,uCAAuC;AAC1B,QAAA,KAAK,GAAG;IACnB,UAAU;IACV,aAAa;IACb,iBAAiB;IACjB,WAAW;IACX,SAAS;IACT,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\ No newline at end of file diff --git a/node_modules/mongodb/lib/db.js b/node_modules/mongodb/lib/db.js new file mode 100644 index 0000000..59acda4 --- /dev/null +++ b/node_modules/mongodb/lib/db.js @@ -0,0 +1,317 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Db = void 0; +const utils_1 = require("./utils"); +const aggregation_cursor_1 = require("./cursor/aggregation_cursor"); +const bson_1 = require("./bson"); +const read_preference_1 = require("./read_preference"); +const error_1 = require("./error"); +const collection_1 = require("./collection"); +const change_stream_1 = require("./change_stream"); +const CONSTANTS = require("./constants"); +const write_concern_1 = require("./write_concern"); +const read_concern_1 = require("./read_concern"); +const logger_1 = require("./logger"); +const add_user_1 = require("./operations/add_user"); +const collections_1 = require("./operations/collections"); +const stats_1 = require("./operations/stats"); +const run_command_1 = require("./operations/run_command"); +const create_collection_1 = require("./operations/create_collection"); +const indexes_1 = require("./operations/indexes"); +const drop_1 = require("./operations/drop"); +const list_collections_1 = require("./operations/list_collections"); +const profiling_level_1 = require("./operations/profiling_level"); +const remove_user_1 = require("./operations/remove_user"); +const rename_1 = require("./operations/rename"); +const set_profiling_level_1 = require("./operations/set_profiling_level"); +const execute_operation_1 = require("./operations/execute_operation"); +const admin_1 = require("./admin"); +// Allowed parameters +const DB_OPTIONS_ALLOW_LIST = [ + 'writeConcern', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'authSource', + 'ignoreUndefined', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'loggerLevel', + 'logger', + 'promoteBuffers', + 'promoteLongs', + 'bsonRegExp', + 'promoteValues', + 'compression', + 'retryWrites' +]; +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```js + * const { MongoClient } = require('mongodb'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); + * }); + * ``` + */ +class Db { + /** + * Creates a new Db instance + * + * @param client - The MongoClient for the database. + * @param databaseName - The name of the database this instance represents. + * @param options - Optional settings for Db construction + */ + constructor(client, databaseName, options) { + var _a; + options = options !== null && options !== void 0 ? options : {}; + // Filter the options + options = utils_1.filterOptions(options, DB_OPTIONS_ALLOW_LIST); + // Ensure we have a valid db name + validateDatabaseName(databaseName); + // Internal state of the db object + this.s = { + // Client + client, + // Options + options, + // Logger instance + logger: new logger_1.Logger('Db', options), + // Unpack read preference + readPreference: read_preference_1.ReadPreference.fromOptions(options), + // Merge bson options + bsonOptions: bson_1.resolveBSONOptions(options, client), + // Set up the primary key factory or fallback to ObjectId + pkFactory: (_a = options === null || options === void 0 ? void 0 : options.pkFactory) !== null && _a !== void 0 ? _a : utils_1.DEFAULT_PK_FACTORY, + // ReadConcern + readConcern: read_concern_1.ReadConcern.fromOptions(options), + writeConcern: write_concern_1.WriteConcern.fromOptions(options), + // Namespace + namespace: new utils_1.MongoDBNamespace(databaseName) + }; + } + get databaseName() { + return this.s.namespace.db; + } + // Options + get options() { + return this.s.options; + } + // slaveOk specified + get slaveOk() { + var _a; + return ((_a = this.s.readPreference) === null || _a === void 0 ? void 0 : _a.preference) !== 'primary' || false; + } + get readConcern() { + return this.s.readConcern; + } + /** + * The current readPreference of the Db. If not explicitly defined for + * this Db, will be inherited from the parent MongoClient + */ + get readPreference() { + if (this.s.readPreference == null) { + return this.s.client.readPreference; + } + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + // get the write Concern + get writeConcern() { + return this.s.writeConcern; + } + get namespace() { + return this.s.namespace.toString(); + } + createCollection(name, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_1.getTopology(this), new create_collection_1.CreateCollectionOperation(this, name, utils_1.resolveOptions(this, options)), callback); + } + command(command, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + // Intentionally, we do not inherit options from parent for this operation. + return execute_operation_1.executeOperation(utils_1.getTopology(this), new run_command_1.RunCommandOperation(this, command, options !== null && options !== void 0 ? options : {}), callback); + } + /** + * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6 + * + * @param pipeline - An array of aggregation stages to be executed + * @param options - Optional settings for the command + */ + aggregate(pipeline = [], options) { + if (arguments.length > 2) { + throw new error_1.MongoInvalidArgumentError('Method "db.aggregate()" accepts at most two arguments'); + } + if (typeof pipeline === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must not be function'); + } + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "options" must not be function'); + } + return new aggregation_cursor_1.AggregationCursor(utils_1.getTopology(this), this.s.namespace, pipeline, utils_1.resolveOptions(this, options)); + } + /** Return the Admin db instance */ + admin() { + return new admin_1.Admin(this); + } + /** + * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. + * + * @param name - the collection name we wish to access. + * @returns return the new Collection instance + */ + collection(name, options = {}) { + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('The callback form of this helper has been removed.'); + } + const finalOptions = utils_1.resolveOptions(this, options); + return new collection_1.Collection(this, name, finalOptions); + } + stats(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_1.getTopology(this), new stats_1.DbStatsOperation(this, utils_1.resolveOptions(this, options)), callback); + } + listCollections(filter = {}, options = {}) { + return new list_collections_1.ListCollectionsCursor(this, filter, utils_1.resolveOptions(this, options)); + } + renameCollection(fromCollection, toCollection, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + // Intentionally, we do not inherit options from parent for this operation. + options = { ...options, readPreference: read_preference_1.ReadPreference.PRIMARY }; + // Add return new collection + options.new_collection = true; + return execute_operation_1.executeOperation(utils_1.getTopology(this), new rename_1.RenameOperation(this.collection(fromCollection), toCollection, options), callback); + } + dropCollection(name, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_1.getTopology(this), new drop_1.DropCollectionOperation(this, name, utils_1.resolveOptions(this, options)), callback); + } + dropDatabase(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_1.getTopology(this), new drop_1.DropDatabaseOperation(this, utils_1.resolveOptions(this, options)), callback); + } + collections(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_1.getTopology(this), new collections_1.CollectionsOperation(this, utils_1.resolveOptions(this, options)), callback); + } + createIndex(name, indexSpec, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_1.getTopology(this), new indexes_1.CreateIndexOperation(this, name, indexSpec, utils_1.resolveOptions(this, options)), callback); + } + addUser(username, password, options, callback) { + if (typeof password === 'function') { + (callback = password), (password = undefined), (options = {}); + } + else if (typeof password !== 'string') { + if (typeof options === 'function') { + (callback = options), (options = password), (password = undefined); + } + else { + (options = password), (callback = undefined), (password = undefined); + } + } + else { + if (typeof options === 'function') + (callback = options), (options = {}); + } + return execute_operation_1.executeOperation(utils_1.getTopology(this), new add_user_1.AddUserOperation(this, username, password, utils_1.resolveOptions(this, options)), callback); + } + removeUser(username, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_1.getTopology(this), new remove_user_1.RemoveUserOperation(this, username, utils_1.resolveOptions(this, options)), callback); + } + setProfilingLevel(level, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_1.getTopology(this), new set_profiling_level_1.SetProfilingLevelOperation(this, level, utils_1.resolveOptions(this, options)), callback); + } + profilingLevel(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_1.getTopology(this), new profiling_level_1.ProfilingLevelOperation(this, utils_1.resolveOptions(this, options)), callback); + } + indexInformation(name, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return execute_operation_1.executeOperation(utils_1.getTopology(this), new indexes_1.IndexInformationOperation(this, name, utils_1.resolveOptions(this, options)), callback); + } + /** + * Unref all sockets + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref() { + utils_1.getTopology(this).unref(); + } + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this database. Will ignore all + * changes to system collections. + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + return new change_stream_1.ChangeStream(this, pipeline, utils_1.resolveOptions(this, options)); + } + /** Return the db logger */ + getLogger() { + return this.s.logger; + } + get logger() { + return this.s.logger; + } +} +exports.Db = Db; +Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; +Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; +Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; +Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; +Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; +Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; +// TODO(NODE-3484): Refactor into MongoDBNamespace +// Validate the database name +function validateDatabaseName(databaseName) { + if (typeof databaseName !== 'string') + throw new error_1.MongoInvalidArgumentError('Database name must be a string'); + if (databaseName.length === 0) + throw new error_1.MongoInvalidArgumentError('Database name cannot be the empty string'); + if (databaseName === '$external') + return; + const invalidChars = [' ', '.', '$', '/', '\\']; + for (let i = 0; i < invalidChars.length; i++) { + if (databaseName.indexOf(invalidChars[i]) !== -1) + throw new error_1.MongoAPIError(`database names cannot contain the character '${invalidChars[i]}'`); + } +} +//# sourceMappingURL=db.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/db.js.map b/node_modules/mongodb/lib/db.js.map new file mode 100644 index 0000000..5e08bdc --- /dev/null +++ b/node_modules/mongodb/lib/db.js.map @@ -0,0 +1 @@ +{"version":3,"file":"db.js","sourceRoot":"","sources":["../src/db.ts"],"names":[],"mappings":";;;AAAA,mCAOiB;AACjB,oEAAgE;AAChE,iCAA4E;AAC5E,uDAAuE;AACvE,mCAAmE;AACnE,6CAA6D;AAC7D,mDAAoE;AACpE,yCAAyC;AACzC,mDAAoE;AACpE,iDAA6C;AAC7C,qCAAiD;AAEjD,oDAAyE;AACzE,0DAAgE;AAChE,8CAAsE;AACtE,0DAAkF;AAClF,sEAAoG;AACpG,kDAK8B;AAC9B,4CAK2B;AAC3B,oEAIuC;AACvC,kEAA8F;AAC9F,0DAAkF;AAClF,gDAAqE;AACrE,0EAI0C;AAC1C,sEAAkE;AAGlE,mCAAgC;AAGhC,qBAAqB;AACrB,MAAM,qBAAqB,GAAG;IAC5B,cAAc;IACd,gBAAgB;IAChB,oBAAoB;IACpB,eAAe;IACf,qBAAqB;IACrB,WAAW;IACX,oBAAoB;IACpB,KAAK;IACL,YAAY;IACZ,iBAAiB;IACjB,aAAa;IACb,kBAAkB;IAClB,iBAAiB;IACjB,aAAa;IACb,QAAQ;IACR,gBAAgB;IAChB,cAAc;IACd,YAAY;IACZ,eAAe;IACf,aAAa;IACb,aAAa;CACd,CAAC;AA+BF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAa,EAAE;IAWb;;;;;;OAMG;IACH,YAAY,MAAmB,EAAE,YAAoB,EAAE,OAAmB;;QACxE,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAExB,qBAAqB;QACrB,OAAO,GAAG,qBAAa,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;QAExD,iCAAiC;QACjC,oBAAoB,CAAC,YAAY,CA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BAAsB,CAAC;AAC1D,4BAAyB,GAAG,SAAS,CAAC,yBAAyB,CAAC;AAChE,uBAAoB,GAAG,SAAS,CAAC,oBAAoB,CAAC;AA4lBtE,kDAAkD;AAClD,6BAA6B;AAC7B,SAAS,oBAAoB,CAAC,YAAoB;IAChD,IAAI,OAAO,YAAY,KAAK,QAAQ;QAClC,MAAM,IAAI,iCAAyB,CAAC,gCAAgC,CAAC,CAAC;IACxE,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC;QAC3B,MAAM,IAAI,iCAAyB,CAAC,0CAA0C,CAAC,CAAC;IAClF,IAAI,YAAY,KAAK,WAAW;QAAE,OAAO;IAEzC,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IAChD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAC5C,IAAI,YAAY,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;YAC9C,MAAM,IAAI,qBAAa,CAAC,gDAAgD,YAAY,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAC/F;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/deps.js b/node_modules/mongodb/lib/deps.js new file mode 100644 index 0000000..a98a783 --- /dev/null +++ b/node_modules/mongodb/lib/deps.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AutoEncryptionLoggerLevel = exports.aws4 = exports.saslprep = exports.Snappy = exports.Kerberos = exports.PKG_VERSION = void 0; +/* eslint-disable @typescript-eslint/no-var-requires */ +const error_1 = require("./error"); +const utils_1 = require("./utils"); +exports.PKG_VERSION = Symbol('kPkgVersion'); +function makeErrorModule(error) { + const props = error ? { kModuleError: error } : {}; + return new Proxy(props, { + get: (_, key) => { + if (key === 'kModuleError') { + return error; + } + throw error; + }, + set: () => { + throw error; + } + }); +} +exports.Kerberos = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `kerberos` not found. Please install it to enable kerberos authentication')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.Kerberos = require('kerberos'); +} +catch { } // eslint-disable-line +exports.Snappy = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `snappy` not found. Please install it to enable snappy compression')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.Snappy = require('snappy'); + try { + exports.Snappy[exports.PKG_VERSION] = utils_1.parsePackageVersion(require('snappy/package.json')); + } + catch { } // eslint-disable-line +} +catch { } // eslint-disable-line +exports.saslprep = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `saslprep` not found.' + + ' Please install it to enable Stringprep Profile for User Names and Passwords')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.saslprep = require('saslprep'); +} +catch { } // eslint-disable-line +exports.aws4 = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `aws4` not found. Please install it to enable AWS authentication')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.aws4 = require('aws4'); +} +catch { } // eslint-disable-line +/** @public */ +exports.AutoEncryptionLoggerLevel = Object.freeze({ + FatalError: 0, + Error: 1, + Warning: 2, + Info: 3, + Trace: 4 +}); +//# sourceMappingURL=deps.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/deps.js.map b/node_modules/mongodb/lib/deps.js.map new file mode 100644 index 0000000..6264183 --- /dev/null +++ b/node_modules/mongodb/lib/deps.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deps.js","sourceRoot":"","sources":["../src/deps.ts"],"names":[],"mappings":";;;AAAA,uDAAuD;AACvD,mCAAsD;AAGtD,mCAAwD;AAE3C,QAAA,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAEjD,SAAS,eAAe,CAAC,KAAU;IACjC,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,YAA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AAC,MAAM,CAAC,CAAC;CACxB;AAAC,MAAM,GAAE,CAAC,sBAAsB;AAEjC,cAAc;AACD,QAAA,yBAAyB,GAAG,MAAM,CAAC,MAAM,CAAC;IACrD,UAAU,EAAE,CAAC;IACb,KAAK,EAAE,CAAC;IACR,OAAO,EAAE,CAAC;IACV,IAAI,EAAE,CAAC;IACP,KAAK,EAAE,CAAC;CACA,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/encrypter.js b/node_modules/mongodb/lib/encrypter.js new file mode 100644 index 0000000..c00349c --- /dev/null +++ b/node_modules/mongodb/lib/encrypter.js @@ -0,0 +1,93 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Encrypter = void 0; +/* eslint-disable @typescript-eslint/no-var-requires */ +const mongo_client_1 = require("./mongo_client"); +const error_1 = require("./error"); +const bson_1 = require("./bson"); +const connect_1 = require("./operations/connect"); +let AutoEncrypterClass; +/** @internal */ +const kInternalClient = Symbol('internalClient'); +/** @internal */ +class Encrypter { + constructor(client, uri, options) { + if (typeof options.autoEncryption !== 'object') { + throw new error_1.MongoInvalidArgumentError('Option "autoEncryption" must be specified'); + } + this.bypassAutoEncryption = !!options.autoEncryption.bypassAutoEncryption; + this.needsConnecting = false; + if (options.maxPoolSize === 0 && options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = client; + } + else if (options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = this.getInternalClient(client, uri, options); + } + if (this.bypassAutoEncryption) { + options.autoEncryption.metadataClient = undefined; + } + else if (options.maxPoolSize === 0) { + options.autoEncryption.metadataClient = client; + } + else { + options.autoEncryption.metadataClient = this.getInternalClient(client, uri, options); + } + options.autoEncryption.bson = Object.create(null); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + options.autoEncryption.bson.serialize = bson_1.serialize; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + options.autoEncryption.bson.deserialize = bson_1.deserialize; + this.autoEncrypter = new AutoEncrypterClass(client, options.autoEncryption); + } + getInternalClient(client, uri, options) { + if (!this[kInternalClient]) { + const clonedOptions = {}; + for (const key of Object.keys(options)) { + if (['autoEncryption', 'minPoolSize', 'servers', 'caseTranslate', 'dbName'].includes(key)) + continue; + Reflect.set(clonedOptions, key, Reflect.get(options, key)); + } + clonedOptions.minPoolSize = 0; + this[kInternalClient] = new mongo_client_1.MongoClient(uri, clonedOptions); + for (const eventName of connect_1.MONGO_CLIENT_EVENTS) { + for (const listener of client.listeners(eventName)) { + this[kInternalClient].on(eventName, listener); + } + } + client.on('newListener', (eventName, listener) => { + this[kInternalClient].on(eventName, listener); + }); + this.needsConnecting = true; + } + return this[kInternalClient]; + } + connectInternalClient(callback) { + if (this.needsConnecting) { + this.needsConnecting = false; + return this[kInternalClient].connect(callback); + } + return callback(); + } + close(client, force, callback) { + this.autoEncrypter.teardown(!!force, e => { + if (this[kInternalClient] && client !== this[kInternalClient]) { + return this[kInternalClient].close(force, callback); + } + callback(e); + }); + } + static checkForMongoCrypt() { + let mongodbClientEncryption = undefined; + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + mongodbClientEncryption = require('mongodb-client-encryption'); + } + catch (err) { + throw new error_1.MongoMissingDependencyError('Auto-encryption requested, but the module is not installed. ' + + 'Please add `mongodb-client-encryption` as a dependency of your project'); + } + AutoEncrypterClass = mongodbClientEncryption.extension(require('../lib/index')).AutoEncrypter; + } +} +exports.Encrypter = Encrypter; +//# sourceMappingURL=encrypter.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/encrypter.js.map b/node_modules/mongodb/lib/encrypter.js.map new file mode 100644 index 0000000..a0dcc5d --- /dev/null +++ b/node_modules/mongodb/lib/encrypter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encrypter.js","sourceRoot":"","sources":["../src/encrypter.ts"],"names":[],"mappings":";;;AAAA,uDAAuD;AACvD,iDAAiE;AAEjE,mCAAiF;AACjF,iCAAgD;AAEhD,kDAA2D;AAE3D,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C7B;QACD,OAAO,IAAI,CAAC,eAAe,CAAC,CAAC;IAC/B,CAAC;IAED,qBAAqB,CAAC,QAAkB;QACtC,IAAI,IAAI,CAAC,eAAe,EAAE;YACxB,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;YAC7B,OAAO,IAAI,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;SAChD;QAED,OAAO,QAAQ,EAAE,CAAC;IACpB,CAAC;IAED,KAAK,CAAC,MAAmB,EAAE,KAAc,EAAE,QAAkB;QAC3D,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,EAAE;YACvC,IAAI,IAAI,CAAC,eAAe,CAAC,IAAI,MAAM,KAAK,IAAI,CAAC,eAAe,CAAC,EAAE;gBAC7D,OAAO,IAAI,CAAC,eAAe,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;aACrD;YACD,QAAQ,CAAC,CAAC,CAAC,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC;IAED,MAAM,CAAC,kBAAkB;QACvB,IAAI,uBAAuB,GAAG,SAAS,CAAC;QACxC,IAAI;YACF,wEAAwE;YACxE,uBAAuB,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;SAChE;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,mCAA2B,CACnC,8DAA8D;gBAC5D,wEAAwE,CAC3E,CAAC;SACH;QAED,kBAAkB,GAAG,uBAAuB,CAAC,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,aAAa,CAAC;IAChG,CAAC;CACF;AAlGD,8BAkGC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/error.js b/node_modules/mongodb/lib/error.js new file mode 100644 index 0000000..94d55fd --- /dev/null +++ b/node_modules/mongodb/lib/error.js @@ -0,0 +1,712 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isResumableError = exports.isNetworkTimeoutError = exports.isSDAMUnrecoverableError = exports.isNodeShuttingDownError = exports.isRetryableError = exports.isRetryableWriteError = exports.MongoWriteConcernError = exports.MongoServerSelectionError = exports.MongoSystemError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoCompatibilityError = exports.MongoInvalidArgumentError = exports.MongoParseError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.isNetworkErrorBeforeHandshake = exports.MongoTopologyClosedError = exports.MongoCursorExhaustedError = exports.MongoServerClosedError = exports.MongoCursorInUseError = exports.MongoGridFSChunkError = exports.MongoGridFSStreamError = exports.MongoTailableCursorError = exports.MongoChangeStreamError = exports.MongoKerberosError = exports.MongoExpiredSessionError = exports.MongoTransactionError = exports.MongoNotConnectedError = exports.MongoDecompressionError = exports.MongoBatchReExecutionError = exports.MongoRuntimeError = exports.MongoAPIError = exports.MongoDriverError = exports.MongoServerError = exports.MongoError = exports.GET_MORE_RESUMABLE_CODES = exports.MONGODB_ERROR_CODES = void 0; +/** @internal */ +const kErrorLabels = Symbol('errorLabels'); +/** @internal MongoDB Error Codes */ +exports.MONGODB_ERROR_CODES = Object.freeze({ + HostUnreachable: 6, + HostNotFound: 7, + NetworkTimeout: 89, + ShutdownInProgress: 91, + PrimarySteppedDown: 189, + ExceededTimeLimit: 262, + SocketException: 9001, + NotMaster: 10107, + InterruptedAtShutdown: 11600, + InterruptedDueToReplStateChange: 11602, + NotMasterNoSlaveOk: 13435, + NotMasterOrSecondary: 13436, + StaleShardVersion: 63, + StaleEpoch: 150, + StaleConfig: 13388, + RetryChangeStream: 234, + FailedToSatisfyReadPreference: 133, + CursorNotFound: 43, + LegacyNotPrimary: 10058, + WriteConcernFailed: 64, + NamespaceNotFound: 26, + IllegalOperation: 20, + MaxTimeMSExpired: 50, + UnknownReplWriteConcern: 79, + UnsatisfiableWriteConcern: 100 +}); +// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error +exports.GET_MORE_RESUMABLE_CODES = new Set([ + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.ExceededTimeLimit, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.NotMaster, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotMasterNoSlaveOk, + exports.MONGODB_ERROR_CODES.NotMasterOrSecondary, + exports.MONGODB_ERROR_CODES.StaleShardVersion, + exports.MONGODB_ERROR_CODES.StaleEpoch, + exports.MONGODB_ERROR_CODES.StaleConfig, + exports.MONGODB_ERROR_CODES.RetryChangeStream, + exports.MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, + exports.MONGODB_ERROR_CODES.CursorNotFound +]); +/** + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error, it uses the constructor with a string argument + */ +class MongoError extends Error { + constructor(message) { + if (message instanceof Error) { + super(message.message); + } + else { + super(message); + } + } + get name() { + return 'MongoError'; + } + /** Legacy name for server error responses */ + get errmsg() { + return this.message; + } + /** + * Checks the error to see if it has an error label + * + * @param label - The error label to check for + * @returns returns true if the error has the provided error label + */ + hasErrorLabel(label) { + if (this[kErrorLabels] == null) { + return false; + } + return this[kErrorLabels].has(label); + } + addErrorLabel(label) { + if (this[kErrorLabels] == null) { + this[kErrorLabels] = new Set(); + } + this[kErrorLabels].add(label); + } + get errorLabels() { + return this[kErrorLabels] ? Array.from(this[kErrorLabels]) : []; + } +} +exports.MongoError = MongoError; +/** + * An error coming from the mongo server + * + * @public + * @category Error + */ +class MongoServerError extends MongoError { + constructor(message) { + super(message.message || message.errmsg || message.$err || 'n/a'); + if (message.errorLabels) { + this[kErrorLabels] = new Set(message.errorLabels); + } + for (const name in message) { + if (name !== 'errorLabels' && name !== 'errmsg' && name !== 'message') + this[name] = message[name]; + } + } + get name() { + return 'MongoServerError'; + } +} +exports.MongoServerError = MongoServerError; +/** + * An error generated by the driver + * + * @public + * @category Error + */ +class MongoDriverError extends MongoError { + constructor(message) { + super(message); + } + get name() { + return 'MongoDriverError'; + } +} +exports.MongoDriverError = MongoDriverError; +/** + * An error generated when the driver API is used incorrectly + * + * @privateRemarks + * Should **never** be directly instantiated + * + * @public + * @category Error + */ +class MongoAPIError extends MongoDriverError { + constructor(message) { + super(message); + } + get name() { + return 'MongoAPIError'; + } +} +exports.MongoAPIError = MongoAPIError; +/** + * An error generated when the driver encounters unexpected input + * or reaches an unexpected/invalid internal state + * + * @privateRemarks + * Should **never** be directly instantiated. + * + * @public + * @category Error + */ +class MongoRuntimeError extends MongoDriverError { + constructor(message) { + super(message); + } + get name() { + return 'MongoRuntimeError'; + } +} +exports.MongoRuntimeError = MongoRuntimeError; +/** + * An error generated when a batch command is reexecuted after one of the commands in the batch + * has failed + * + * @public + * @category Error + */ +class MongoBatchReExecutionError extends MongoAPIError { + constructor(message = 'This batch has already been executed, create new batch to execute') { + super(message); + } + get name() { + return 'MongoBatchReExecutionError'; + } +} +exports.MongoBatchReExecutionError = MongoBatchReExecutionError; +/** + * An error generated when the driver fails to decompress + * data received from the server. + * + * @public + * @category Error + */ +class MongoDecompressionError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoDecompressionError'; + } +} +exports.MongoDecompressionError = MongoDecompressionError; +/** + * An error thrown when the user attempts to operate on a database or collection through a MongoClient + * that has not yet successfully called the "connect" method + * + * @public + * @category Error + */ +class MongoNotConnectedError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoNotConnectedError'; + } +} +exports.MongoNotConnectedError = MongoNotConnectedError; +/** + * An error generated when the user makes a mistake in the usage of transactions. + * (e.g. attempting to commit a transaction with a readPreference other than primary) + * + * @public + * @category Error + */ +class MongoTransactionError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoTransactionError'; + } +} +exports.MongoTransactionError = MongoTransactionError; +/** + * An error generated when the user attempts to operate + * on a session that has expired or has been closed. + * + * @public + * @category Error + */ +class MongoExpiredSessionError extends MongoAPIError { + constructor(message = 'Cannot use a session that has ended') { + super(message); + } + get name() { + return 'MongoExpiredSessionError'; + } +} +exports.MongoExpiredSessionError = MongoExpiredSessionError; +/** + * A error generated when the user attempts to authenticate + * via Kerberos, but fails to connect to the Kerberos client. + * + * @public + * @category Error + */ +class MongoKerberosError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoKerberosError'; + } +} +exports.MongoKerberosError = MongoKerberosError; +/** + * An error generated when a ChangeStream operation fails to execute. + * + * @public + * @category Error + */ +class MongoChangeStreamError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoChangeStreamError'; + } +} +exports.MongoChangeStreamError = MongoChangeStreamError; +/** + * An error thrown when the user calls a function or method not supported on a tailable cursor + * + * @public + * @category Error + */ +class MongoTailableCursorError extends MongoAPIError { + constructor(message = 'Tailable cursor does not support this operation') { + super(message); + } + get name() { + return 'MongoTailableCursorError'; + } +} +exports.MongoTailableCursorError = MongoTailableCursorError; +/** An error generated when a GridFSStream operation fails to execute. + * + * @public + * @category Error + */ +class MongoGridFSStreamError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoGridFSStreamError'; + } +} +exports.MongoGridFSStreamError = MongoGridFSStreamError; +/** + * An error generated when a malformed or invalid chunk is + * encountered when reading from a GridFSStream. + * + * @public + * @category Error + */ +class MongoGridFSChunkError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoGridFSChunkError'; + } +} +exports.MongoGridFSChunkError = MongoGridFSChunkError; +/** + * An error thrown when the user attempts to add options to a cursor that has already been + * initialized + * + * @public + * @category Error + */ +class MongoCursorInUseError extends MongoAPIError { + constructor(message = 'Cursor is already initialized') { + super(message); + } + get name() { + return 'MongoCursorInUseError'; + } +} +exports.MongoCursorInUseError = MongoCursorInUseError; +/** + * An error generated when an attempt is made to operate + * on a closed/closing server. + * + * @public + * @category Error + */ +class MongoServerClosedError extends MongoAPIError { + constructor(message = 'Server is closed') { + super(message); + } + get name() { + return 'MongoServerClosedError'; + } +} +exports.MongoServerClosedError = MongoServerClosedError; +/** + * An error thrown when an attempt is made to read from a cursor that has been exhausted + * + * @public + * @category Error + */ +class MongoCursorExhaustedError extends MongoAPIError { + constructor(message) { + super(message || 'Cursor is exhausted'); + } + get name() { + return 'MongoCursorExhaustedError'; + } +} +exports.MongoCursorExhaustedError = MongoCursorExhaustedError; +/** + * An error generated when an attempt is made to operate on a + * dropped, or otherwise unavailable, database. + * + * @public + * @category Error + */ +class MongoTopologyClosedError extends MongoAPIError { + constructor(message = 'Topology is closed') { + super(message); + } + get name() { + return 'MongoTopologyClosedError'; + } +} +exports.MongoTopologyClosedError = MongoTopologyClosedError; +/** @internal */ +const kBeforeHandshake = Symbol('beforeHandshake'); +function isNetworkErrorBeforeHandshake(err) { + return err[kBeforeHandshake] === true; +} +exports.isNetworkErrorBeforeHandshake = isNetworkErrorBeforeHandshake; +/** + * An error indicating an issue with the network, including TCP errors and timeouts. + * @public + * @category Error + */ +class MongoNetworkError extends MongoError { + constructor(message, options) { + super(message); + if (options && typeof options.beforeHandshake === 'boolean') { + this[kBeforeHandshake] = options.beforeHandshake; + } + } + get name() { + return 'MongoNetworkError'; + } +} +exports.MongoNetworkError = MongoNetworkError; +/** + * An error indicating a network timeout occurred + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error with an instanceof check + */ +class MongoNetworkTimeoutError extends MongoNetworkError { + constructor(message, options) { + super(message, options); + } + get name() { + return 'MongoNetworkTimeoutError'; + } +} +exports.MongoNetworkTimeoutError = MongoNetworkTimeoutError; +/** + * An error used when attempting to parse a value (like a connection string) + * @public + * @category Error + */ +class MongoParseError extends MongoDriverError { + constructor(message) { + super(message); + } + get name() { + return 'MongoParseError'; + } +} +exports.MongoParseError = MongoParseError; +/** + * An error generated when the user supplies malformed or unexpected arguments + * or when a required argument or field is not provided. + * + * + * @public + * @category Error + */ +class MongoInvalidArgumentError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoInvalidArgumentError'; + } +} +exports.MongoInvalidArgumentError = MongoInvalidArgumentError; +/** + * An error generated when a feature that is not enabled or allowed for the current server + * configuration is used + * + * + * @public + * @category Error + */ +class MongoCompatibilityError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoCompatibilityError'; + } +} +exports.MongoCompatibilityError = MongoCompatibilityError; +/** + * An error generated when the user fails to provide authentication credentials before attempting + * to connect to a mongo server instance. + * + * + * @public + * @category Error + */ +class MongoMissingCredentialsError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoMissingCredentialsError'; + } +} +exports.MongoMissingCredentialsError = MongoMissingCredentialsError; +/** + * An error generated when a required module or dependency is not present in the local environment + * + * @public + * @category Error + */ +class MongoMissingDependencyError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoMissingDependencyError'; + } +} +exports.MongoMissingDependencyError = MongoMissingDependencyError; +/** + * An error signifying a general system issue + * @public + * @category Error + */ +class MongoSystemError extends MongoError { + constructor(message, reason) { + if (reason && reason.error) { + super(reason.error.message || reason.error); + } + else { + super(message); + } + if (reason) { + this.reason = reason; + } + } + get name() { + return 'MongoSystemError'; + } +} +exports.MongoSystemError = MongoSystemError; +/** + * An error signifying a client-side server selection error + * @public + * @category Error + */ +class MongoServerSelectionError extends MongoSystemError { + constructor(message, reason) { + super(message, reason); + } + get name() { + return 'MongoServerSelectionError'; + } +} +exports.MongoServerSelectionError = MongoServerSelectionError; +function makeWriteConcernResultObject(input) { + const output = Object.assign({}, input); + if (output.ok === 0) { + output.ok = 1; + delete output.errmsg; + delete output.code; + delete output.codeName; + } + return output; +} +/** + * An error thrown when the server reports a writeConcernError + * @public + * @category Error + */ +class MongoWriteConcernError extends MongoServerError { + constructor(message, result) { + if (result && Array.isArray(result.errorLabels)) { + message.errorLabels = result.errorLabels; + } + super(message); + this.errInfo = message.errInfo; + if (result != null) { + this.result = makeWriteConcernResultObject(result); + } + } + get name() { + return 'MongoWriteConcernError'; + } +} +exports.MongoWriteConcernError = MongoWriteConcernError; +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.NotMaster, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotMasterNoSlaveOk, + exports.MONGODB_ERROR_CODES.NotMasterOrSecondary +]); +const RETRYABLE_WRITE_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotMaster, + exports.MONGODB_ERROR_CODES.NotMasterNoSlaveOk, + exports.MONGODB_ERROR_CODES.NotMasterOrSecondary, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.ExceededTimeLimit +]); +function isRetryableWriteError(error) { + var _a, _b, _c; + if (error instanceof MongoWriteConcernError) { + return RETRYABLE_WRITE_ERROR_CODES.has((_c = (_b = (_a = error.result) === null || _a === void 0 ? void 0 : _a.code) !== null && _b !== void 0 ? _b : error.code) !== null && _c !== void 0 ? _c : 0); + } + return typeof error.code === 'number' && RETRYABLE_WRITE_ERROR_CODES.has(error.code); +} +exports.isRetryableWriteError = isRetryableWriteError; +/** Determines whether an error is something the driver should attempt to retry */ +function isRetryableError(error) { + return ( + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + (typeof error.code === 'number' && RETRYABLE_ERROR_CODES.has(error.code)) || + error instanceof MongoNetworkError || + !!error.message.match(/not master/) || + !!error.message.match(/node is recovering/)); +} +exports.isRetryableError = isRetryableError; +const SDAM_RECOVERING_CODES = new Set([ + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotMasterOrSecondary +]); +const SDAM_NOTMASTER_CODES = new Set([ + exports.MONGODB_ERROR_CODES.NotMaster, + exports.MONGODB_ERROR_CODES.NotMasterNoSlaveOk, + exports.MONGODB_ERROR_CODES.LegacyNotPrimary +]); +const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.ShutdownInProgress +]); +function isRecoveringError(err) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_RECOVERING_CODES.has(err.code); + } + return /not master or secondary/.test(err.message) || /node is recovering/.test(err.message); +} +function isNotMasterError(err) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_NOTMASTER_CODES.has(err.code); + } + if (isRecoveringError(err)) { + return false; + } + return /not master/.test(err.message); +} +function isNodeShuttingDownError(err) { + return !!(typeof err.code === 'number' && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code)); +} +exports.isNodeShuttingDownError = isNodeShuttingDownError; +/** + * Determines whether SDAM can recover from a given error. If it cannot + * then the pool will be cleared, and server state will completely reset + * locally. + * + * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering + */ +function isSDAMUnrecoverableError(error) { + // NOTE: null check is here for a strictly pre-CMAP world, a timeout or + // close event are considered unrecoverable + if (error instanceof MongoParseError || error == null) { + return true; + } + return isRecoveringError(error) || isNotMasterError(error); +} +exports.isSDAMUnrecoverableError = isSDAMUnrecoverableError; +function isNetworkTimeoutError(err) { + return !!(err instanceof MongoNetworkError && err.message.match(/timed out/)); +} +exports.isNetworkTimeoutError = isNetworkTimeoutError; +// From spec@https://github.com/mongodb/specifications/blob/7a2e93d85935ee4b1046a8d2ad3514c657dc74fa/source/change-streams/change-streams.rst#resumable-error: +// +// An error is considered resumable if it meets any of the following criteria: +// - any error encountered which is not a server error (e.g. a timeout error or network error) +// - any server error response from a getMore command excluding those containing the error label +// NonRetryableChangeStreamError and those containing the following error codes: +// - Interrupted: 11601 +// - CappedPositionLost: 136 +// - CursorKilled: 237 +// +// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors. +function isResumableError(error, wireVersion) { + if (error instanceof MongoNetworkError) { + return true; + } + if (wireVersion != null && wireVersion >= 9) { + // DRIVERS-1308: For 4.4 drivers running against 4.4 servers, drivers will add a special case to treat the CursorNotFound error code as resumable + if (error && error instanceof MongoError && error.code === 43) { + return true; + } + return error instanceof MongoError && error.hasErrorLabel('ResumableChangeStreamError'); + } + if (error && typeof error.code === 'number') { + return exports.GET_MORE_RESUMABLE_CODES.has(error.code); + } + return false; +} +exports.isResumableError = isResumableError; +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/error.js.map b/node_modules/mongodb/lib/error.js.map new file mode 100644 index 0000000..477d8bc --- /dev/null +++ b/node_modules/mongodb/lib/error.js.map @@ -0,0 +1 @@ +{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gB,wBAAwB,CAAC,KAAiB;IACxD,uEAAuE;IACvE,iDAAiD;IACjD,IAAI,KAAK,YAAY,eAAe,IAAI,KAAK,IAAI,IAAI,EAAE;QACrD,OAAO,IAAI,CAAC;KACb;IAED,OAAO,iBAAiB,CAAC,KAAK,CAAC,IAAI,gBAAgB,CAAC,KAAK,CAAC,CAAC;AAC7D,CAAC;AARD,4DAQC;AAED,SAAgB,qBAAqB,CAAC,GAAe;IACnD,OAAO,CAAC,CAAC,CAAC,GAAG,YAAY,iBAAiB,IAAI,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC;AAChF,CAAC;AAFD,sDAEC;AAED,8JAA8J;AAC9J,EAAE;AACF,8EAA8E;AAC9E,8FAA8F;AAC9F,gGAAgG;AAChG,kFAAkF;AAClF,yBAAyB;AACzB,8BAA8B;AAC9B,wBAAwB;AACxB,EAAE;AACF,kIAAkI;AAElI,SAAgB,gBAAgB,CAAC,KAAkB,EAAE,WAAoB;IACvE,IAAI,KAAK,YAAY,iBAAiB,EAAE;QACtC,OAAO,IAAI,CAAC;KACb;IAED,IAAI,WAAW,IAAI,IAAI,IAAI,WAAW,IAAI,CAAC,EAAE;QAC3C,iJAAiJ;QACjJ,IAAI,KAAK,IAAI,KAAK,YAAY,UAAU,IAAI,KAAK,CAAC,IAAI,KAAK,EAAE,EAAE;YAC7D,OAAO,IAAI,CAAC;SACb;QACD,OAAO,KAAK,YAAY,UAAU,IAAI,KAAK,CAAC,aAAa,CAAC,4BAA4B,CAAC,CAAC;KACzF;IAED,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE;QAC3C,OAAO,gCAAwB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;KACjD;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAjBD,4CAiBC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/explain.js b/node_modules/mongodb/lib/explain.js new file mode 100644 index 0000000..bc55e1f --- /dev/null +++ b/node_modules/mongodb/lib/explain.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Explain = exports.ExplainVerbosity = void 0; +const error_1 = require("./error"); +/** @public */ +exports.ExplainVerbosity = Object.freeze({ + queryPlanner: 'queryPlanner', + queryPlannerExtended: 'queryPlannerExtended', + executionStats: 'executionStats', + allPlansExecution: 'allPlansExecution' +}); +/** @internal */ +class Explain { + constructor(verbosity) { + if (typeof verbosity === 'boolean') { + this.verbosity = verbosity + ? exports.ExplainVerbosity.allPlansExecution + : exports.ExplainVerbosity.queryPlanner; + } + else { + this.verbosity = verbosity; + } + } + static fromOptions(options) { + if ((options === null || options === void 0 ? void 0 : options.explain) == null) + return; + const explain = options.explain; + if (typeof explain === 'boolean' || typeof explain === 'string') { + return new Explain(explain); + } + throw new error_1.MongoInvalidArgumentError('Field "explain" must be a string or a boolean'); + } +} +exports.Explain = Explain; +//# sourceMappingURL=explain.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/explain.js.map b/node_modules/mongodb/lib/explain.js.map new file mode 100644 index 0000000..ae503b2 --- /dev/null +++ b/node_modules/mongodb/lib/explain.js.map @@ -0,0 +1 @@ +{"version":3,"file":"explain.js","sourceRoot":"","sources":["../src/explain.ts"],"names":[],"mappings":";;;AAAA,mCAAoD;AAEpD,cAAc;AACD,QAAA,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5C,YAAY,EAAE,cAAc;IAC5B,oBAAoB,EAAE,sBAAsB;IAC5C,cAAc,EAAE,gBAAgB;IAChC,iBAAiB,EAAE,mBAAmB;CAC9B,CAAC,CAAC;AAmBZ,gBAAgB;AAChB,MAAa,OAAO;IAGlB,YAAY,SAA+B;QACzC,IAAI,OAAO,SAAS,KAAK,SAAS,EAAE;YAClC,IAAI,CAAC,SAAS,GAAG,SAAS;gBACxB,CAAC,CAAC,wBAAgB,CAAC,iBAAiB;gBACpC,CAAC,CAAC,wBAAgB,CAAC,YAAY,CAAC;SACnC;aAAM;YACL,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;SAC5B;IACH,CAAC;IAED,MAAM,CAAC,WAAW,CAAC,OAAwB;QACzC,IAAI,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,KAAI,IAAI;YAAE,OAAO;QAErC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAChC,IAAI,OAAO,OAAO,KAAK,SAAS,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;YAC/D,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;SAC7B;QAED,MAAM,IAAI,iCAAyB,CAAC,+CAA+C,CAAC,CAAC;IACvF,CAAC;CACF;AAvBD,0BAuBC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/gridfs/download.js b/node_modules/mongodb/lib/gridfs/download.js new file mode 100644 index 0000000..1e9687b --- /dev/null +++ b/node_modules/mongodb/lib/gridfs/download.js @@ -0,0 +1,315 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GridFSBucketReadStream = void 0; +const stream_1 = require("stream"); +const error_1 = require("../error"); +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * @public + */ +class GridFSBucketReadStream extends stream_1.Readable { + /** @internal + * @param chunks - Handle for chunks collection + * @param files - Handle for files collection + * @param readPreference - The read preference to use + * @param filter - The filter to use to find the file document + */ + constructor(chunks, files, readPreference, filter, options) { + super(); + this.s = { + bytesToTrim: 0, + bytesToSkip: 0, + bytesRead: 0, + chunks, + expected: 0, + files, + filter, + init: false, + expectedEnd: 0, + options: { + start: 0, + end: 0, + ...options + }, + readPreference + }; + } + /** + * Reads from the cursor and pushes to the stream. + * Private Impl, do not call directly + * @internal + */ + _read() { + if (this.destroyed) + return; + waitForFile(this, () => doRead(this)); + } + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param start - 0-based offset in bytes to start streaming from + */ + start(start = 0) { + throwIfInitialized(this); + this.s.options.start = start; + return this; + } + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param end - Offset in bytes to stop reading at + */ + end(end = 0) { + throwIfInitialized(this); + this.s.options.end = end; + return this; + } + /** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @param callback - called when the cursor is successfully closed or an error occurred. + */ + abort(callback) { + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + this.s.cursor.close(error => { + this.emit(GridFSBucketReadStream.CLOSE); + callback && callback(error); + }); + } + else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + this.emit(GridFSBucketReadStream.CLOSE); + } + callback && callback(); + } + } +} +exports.GridFSBucketReadStream = GridFSBucketReadStream; +/** + * An error occurred + * @event + */ +GridFSBucketReadStream.ERROR = 'error'; +/** + * Fires when the stream loaded the file document corresponding to the provided id. + * @event + */ +GridFSBucketReadStream.FILE = 'file'; +/** + * Emitted when a chunk of data is available to be consumed. + * @event + */ +GridFSBucketReadStream.DATA = 'data'; +/** + * Fired when the stream is exhausted (no more data events). + * @event + */ +GridFSBucketReadStream.END = 'end'; +/** + * Fired when the stream is exhausted and the underlying cursor is killed + * @event + */ +GridFSBucketReadStream.CLOSE = 'close'; +function throwIfInitialized(stream) { + if (stream.s.init) { + throw new error_1.MongoGridFSStreamError('Options cannot be changed after the stream is initialized'); + } +} +function doRead(stream) { + if (stream.destroyed) + return; + if (!stream.s.cursor) + return; + if (!stream.s.file) + return; + stream.s.cursor.next((error, doc) => { + if (stream.destroyed) { + return; + } + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + if (!doc) { + stream.push(null); + process.nextTick(() => { + if (!stream.s.cursor) + return; + stream.s.cursor.close(error => { + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + stream.emit(GridFSBucketReadStream.CLOSE); + }); + }); + return; + } + if (!stream.s.file) + return; + const bytesRemaining = stream.s.file.length - stream.s.bytesRead; + const expectedN = stream.s.expected++; + const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining); + if (doc.n > expectedN) { + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}`)); + } + if (doc.n < expectedN) { + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`)); + } + let buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + if (buf.byteLength !== expectedLength) { + if (bytesRemaining <= 0) { + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}`)); + } + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}`)); + } + stream.s.bytesRead += buf.byteLength; + if (buf.byteLength === 0) { + return stream.push(null); + } + let sliceStart = null; + let sliceEnd = null; + if (stream.s.bytesToSkip != null) { + sliceStart = stream.s.bytesToSkip; + stream.s.bytesToSkip = 0; + } + const atEndOfStream = expectedN === stream.s.expectedEnd - 1; + const bytesLeftToRead = stream.s.options.end - stream.s.bytesToSkip; + if (atEndOfStream && stream.s.bytesToTrim != null) { + sliceEnd = stream.s.file.chunkSize - stream.s.bytesToTrim; + } + else if (stream.s.options.end && bytesLeftToRead < doc.data.byteLength) { + sliceEnd = bytesLeftToRead; + } + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.byteLength); + } + stream.push(buf); + }); +} +function init(stream) { + const findOneOptions = {}; + if (stream.s.readPreference) { + findOneOptions.readPreference = stream.s.readPreference; + } + if (stream.s.options && stream.s.options.sort) { + findOneOptions.sort = stream.s.options.sort; + } + if (stream.s.options && stream.s.options.skip) { + findOneOptions.skip = stream.s.options.skip; + } + stream.s.files.findOne(stream.s.filter, findOneOptions, (error, doc) => { + if (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + if (!doc) { + const identifier = stream.s.filter._id + ? stream.s.filter._id.toString() + : stream.s.filter.filename; + const errmsg = `FileNotFound: file ${identifier} was not found`; + // TODO(NODE-3483) + const err = new error_1.MongoRuntimeError(errmsg); + err.code = 'ENOENT'; // TODO: NODE-3338 set property as part of constructor + return stream.emit(GridFSBucketReadStream.ERROR, err); + } + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + stream.push(null); + return; + } + if (stream.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + stream.emit(GridFSBucketReadStream.CLOSE); + return; + } + try { + stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options); + } + catch (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + const filter = { files_id: doc._id }; + // Currently (MongoDB 3.4.4) skip function does not support the index, + // it needs to retrieve all the documents first and then skip them. (CS-25811) + // As work around we use $gte on the "n" field. + if (stream.s.options && stream.s.options.start != null) { + const skip = Math.floor(stream.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; + } + } + stream.s.cursor = stream.s.chunks.find(filter).sort({ n: 1 }); + if (stream.s.readPreference) { + stream.s.cursor.withReadPreference(stream.s.readPreference); + } + stream.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + stream.s.file = doc; + try { + stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options); + } + catch (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + stream.emit(GridFSBucketReadStream.FILE, doc); + }); +} +function waitForFile(stream, callback) { + if (stream.s.file) { + return callback(); + } + if (!stream.s.init) { + init(stream); + stream.s.init = true; + } + stream.once('file', () => { + callback(); + }); +} +function handleStartOption(stream, doc, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be more than the length of the file (${doc.length})`); + } + if (options.start < 0) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be negative`); + } + if (options.end != null && options.end < options.start) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be greater than stream end (${options.end})`); + } + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + return options.start - stream.s.bytesRead; + } + throw new error_1.MongoInvalidArgumentError('Start option must be defined'); +} +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be more than the length of the file (${doc.length})`); + } + if (options.start == null || options.start < 0) { + throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`); + } + const start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; + } + throw new error_1.MongoInvalidArgumentError('End option must be defined'); +} +//# sourceMappingURL=download.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/gridfs/download.js.map b/node_modules/mongodb/lib/gridfs/download.js.map new file mode 100644 index 0000000..9416e3b --- /dev/null +++ b/node_modules/mongodb/lib/gridfs/download.js.map @@ -0,0 +1 @@ +{"version":3,"file":"download.js","sourceRoot":"","sources":["../../src/gridfs/download.ts"],"names":[],"mappings":";;;AAAA,mCAAkC;AAClC,oCAKkB;AA+DlB;;;;;GAKG;AACH,MAAa,sBAAuB,SAAQ,iBAAQ;IA8BlD;;;;;OAKG;IACH,YACE,MAA+B,EAC/B,KAA6B,EAC7B,cAA0C,EAC1C,MA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B,CAAC,4BAA4B,CAAC,CAAC;AACpE,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/gridfs/index.js b/node_modules/mongodb/lib/gridfs/index.js new file mode 100644 index 0000000..4ed123f --- /dev/null +++ b/node_modules/mongodb/lib/gridfs/index.js @@ -0,0 +1,161 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GridFSBucket = void 0; +const error_1 = require("../error"); +const download_1 = require("./download"); +const upload_1 = require("./upload"); +const utils_1 = require("../utils"); +const write_concern_1 = require("../write_concern"); +const mongo_types_1 = require("../mongo_types"); +const DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; +/** + * Constructor for a streaming GridFS interface + * @public + */ +class GridFSBucket extends mongo_types_1.TypedEventEmitter { + constructor(db, options) { + super(); + this.setMaxListeners(0); + const privateOptions = { + ...DEFAULT_GRIDFS_BUCKET_OPTIONS, + ...options, + writeConcern: write_concern_1.WriteConcern.fromOptions(options) + }; + this.s = { + db, + options: privateOptions, + _chunksCollection: db.collection(privateOptions.bucketName + '.chunks'), + _filesCollection: db.collection(privateOptions.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false + }; + } + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + openUploadStream(filename, options) { + return new upload_1.GridFSBucketWriteStream(this, filename, options); + } + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + */ + openUploadStreamWithId(id, filename, options) { + return new upload_1.GridFSBucketWriteStream(this, filename, { ...options, id }); + } + /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ + openDownloadStream(id, options) { + return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { _id: id }, options); + } + delete(id, callback) { + return utils_1.executeLegacyOperation(utils_1.getTopology(this.s.db), _delete, [this, id, callback], { + skipSessions: true + }); + } + /** Convenience wrapper around find on the files collection */ + find(filter, options) { + filter !== null && filter !== void 0 ? filter : (filter = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.s._filesCollection.find(filter, options); + } + /** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + */ + openDownloadStreamByName(filename, options) { + let sort = { uploadDate: -1 }; + let skip = undefined; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } + else { + skip = -options.revision - 1; + } + } + return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { filename }, { ...options, sort, skip }); + } + rename(id, filename, callback) { + return utils_1.executeLegacyOperation(utils_1.getTopology(this.s.db), _rename, [this, id, filename, callback], { + skipSessions: true + }); + } + drop(callback) { + return utils_1.executeLegacyOperation(utils_1.getTopology(this.s.db), _drop, [this, callback], { + skipSessions: true + }); + } + /** Get the Db scoped logger. */ + getLogger() { + return this.s.db.s.logger; + } +} +exports.GridFSBucket = GridFSBucket; +/** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * @event + */ +GridFSBucket.INDEX = 'index'; +function _delete(bucket, id, callback) { + return bucket.s._filesCollection.deleteOne({ _id: id }, (error, res) => { + if (error) { + return callback(error); + } + return bucket.s._chunksCollection.deleteMany({ files_id: id }, error => { + if (error) { + return callback(error); + } + // Delete orphaned chunks before returning FileNotFound + if (!(res === null || res === void 0 ? void 0 : res.deletedCount)) { + // TODO(NODE-3483): Replace with more appropriate error + // Consider creating new error MongoGridFSFileNotFoundError + return callback(new error_1.MongoRuntimeError(`File not found for id ${id}`)); + } + return callback(); + }); + }); +} +function _rename(bucket, id, filename, callback) { + const filter = { _id: id }; + const update = { $set: { filename } }; + return bucket.s._filesCollection.updateOne(filter, update, (error, res) => { + if (error) { + return callback(error); + } + if (!(res === null || res === void 0 ? void 0 : res.matchedCount)) { + return callback(new error_1.MongoRuntimeError(`File with id ${id} not found`)); + } + return callback(); + }); +} +function _drop(bucket, callback) { + return bucket.s._filesCollection.drop((error) => { + if (error) { + return callback(error); + } + return bucket.s._chunksCollection.drop((error) => { + if (error) { + return callback(error); + } + return callback(); + }); + }); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/gridfs/index.js.map b/node_modules/mongodb/lib/gridfs/index.js.map new file mode 100644 index 0000000..c2b2e86 --- /dev/null +++ b/node_modules/mongodb/lib/gridfs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/gridfs/index.ts"],"names":[],"mappings":";;;AAAA,oCAA6C;AAC7C,yCAKoB;AACpB,qCAAgG;AAChG,oCAAyE;AACzE,oDAAqE;AASrE,gDAA2D;AAE3D,MAAM,6BAA6B,GAG/B;IACF,UAAU,EAAE,IAAI;IAChB,cAAc,EAAE,GAAG,GAAG,IAAI;CAC3B,CAAC;AAgCF;;;GAGG;AACH,MAAa,YAAa,SAAQ,+BAAqC;IAcrE,YAAY,EAAM,EAAE,OAA6B;QAC/C,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;QACxB,MAAM,cAAc,GAAG;YACrB,GAAG,6BAA6B;YAChC,GAAG,OAAO;YACV,YAAY,EAAE,4BAAY,CAAC,WAAW,CAAC,OAAO,CAAC;SAChD,CAAC;QACF,IAAI,CAAC,CAAC,GAAG;YACP,EAAE;YACF,OAAO,EAAE,cAAc;YACvB,iBAAiB,EAAE,EAAE,CAAC,UAAU,CAAc,cAAc,CAAC,UAAU,GAAG,SAAS,CAAC;YACpF,gBAAgB,EA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AAM,EAAE,GAAI,EAAE,EAAE;QAC1E,IAAI,KAAK,EAAE;YACT,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;SACxB;QAED,IAAI,CAAC,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,YAAY,CAAA,EAAE;YACtB,OAAO,QAAQ,CAAC,IAAI,yBAAiB,CAAC,gBAAgB,EAAE,YAAY,CAAC,CAAC,CAAC;SACxE;QAED,OAAO,QAAQ,EAAE,CAAC;IACpB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,KAAK,CAAC,MAAoB,EAAE,QAAwB;IAC3D,OAAO,MAAM,CAAC,CAAC,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,KAAa,EAAE,EAAE;QACtD,IAAI,KAAK,EAAE;YACT,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;SACxB;QACD,OAAO,MAAM,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,KAAa,EAAE,EAAE;YACvD,IAAI,KAAK,EAAE;gBACT,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;aACxB;YAED,OAAO,QAAQ,EAAE,CAAC;QACpB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/gridfs/upload.js b/node_modules/mongodb/lib/gridfs/upload.js new file mode 100644 index 0000000..19a7781 --- /dev/null +++ b/node_modules/mongodb/lib/gridfs/upload.js @@ -0,0 +1,375 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GridFSBucketWriteStream = void 0; +const stream_1 = require("stream"); +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const write_concern_1 = require("./../write_concern"); +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * @public + */ +class GridFSBucketWriteStream extends stream_1.Writable { + /** @internal + * @param bucket - Handle for this stream's corresponding bucket + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + constructor(bucket, filename, options) { + super(); + options = options !== null && options !== void 0 ? options : {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + this.writeConcern = write_concern_1.WriteConcern.fromOptions(options) || bucket.s.options.writeConcern; + // Signals the write is all done + this.done = false; + this.id = options.id ? options.id : new bson_1.ObjectId(); + // properly inherit the default chunksize from parent + this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false + }; + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + checkIndexes(this, () => { + this.bucket.s.checkedIndexes = true; + this.bucket.emit('index'); + }); + } + } + write(chunk, encodingOrCallback, callback) { + const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback; + callback = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback; + return waitForIndexes(this, () => doWrite(this, chunk, encoding, callback)); + } + abort(callback) { + return utils_1.maybePromise(callback, callback => { + if (this.state.streamEnd) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + return callback(new error_1.MongoAPIError('Cannot abort a stream that has already completed')); + } + if (this.state.aborted) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + return callback(new error_1.MongoAPIError('Cannot call abort() on a stream twice')); + } + this.state.aborted = true; + this.chunks.deleteMany({ files_id: this.id }, error => callback(error)); + }); + } + end(chunkOrCallback, encodingOrCallback, callback) { + const chunk = typeof chunkOrCallback === 'function' ? undefined : chunkOrCallback; + const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback; + callback = + typeof chunkOrCallback === 'function' + ? chunkOrCallback + : typeof encodingOrCallback === 'function' + ? encodingOrCallback + : callback; + if (checkAborted(this, callback)) + return; + this.state.streamEnd = true; + if (callback) { + this.once(GridFSBucketWriteStream.FINISH, (result) => { + if (callback) + callback(undefined, result); + }); + } + if (!chunk) { + waitForIndexes(this, () => !!writeRemnant(this)); + return; + } + this.write(chunk, encoding, () => { + writeRemnant(this); + }); + } +} +exports.GridFSBucketWriteStream = GridFSBucketWriteStream; +/** @event */ +GridFSBucketWriteStream.CLOSE = 'close'; +/** @event */ +GridFSBucketWriteStream.ERROR = 'error'; +/** + * `end()` was called and the write stream successfully wrote the file metadata and all the chunks to MongoDB. + * @event + */ +GridFSBucketWriteStream.FINISH = 'finish'; +function __handleError(stream, error, callback) { + if (stream.state.errored) { + return; + } + stream.state.errored = true; + if (callback) { + return callback(error); + } + stream.emit(GridFSBucketWriteStream.ERROR, error); +} +function createChunkDoc(filesId, n, data) { + return { + _id: new bson_1.ObjectId(), + files_id: filesId, + n, + data + }; +} +function checkChunksIndex(stream, callback) { + stream.chunks.listIndexes().toArray((error, indexes) => { + let index; + if (error) { + // Collection doesn't exist so create index + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + index = { files_id: 1, n: 1 }; + stream.chunks.createIndex(index, { background: false, unique: true }, error => { + if (error) { + return callback(error); + } + callback(); + }); + return; + } + return callback(error); + } + let hasChunksIndex = false; + if (indexes) { + indexes.forEach((index) => { + if (index.key) { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + } + if (hasChunksIndex) { + callback(); + } + else { + index = { files_id: 1, n: 1 }; + const writeConcernOptions = getWriteOptions(stream); + stream.chunks.createIndex(index, { + ...writeConcernOptions, + background: true, + unique: true + }, callback); + } + }); +} +function checkDone(stream, callback) { + if (stream.done) + return true; + if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) { + // Set done so we do not trigger duplicate createFilesDoc + stream.done = true; + // Create a new files doc + const filesDoc = createFilesDoc(stream.id, stream.length, stream.chunkSizeBytes, stream.filename, stream.options.contentType, stream.options.aliases, stream.options.metadata); + if (checkAborted(stream, callback)) { + return false; + } + stream.files.insertOne(filesDoc, getWriteOptions(stream), (error) => { + if (error) { + return __handleError(stream, error, callback); + } + stream.emit(GridFSBucketWriteStream.FINISH, filesDoc); + stream.emit(GridFSBucketWriteStream.CLOSE); + }); + return true; + } + return false; +} +function checkIndexes(stream, callback) { + stream.files.findOne({}, { projection: { _id: 1 } }, (error, doc) => { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + stream.files.listIndexes().toArray((error, indexes) => { + let index; + if (error) { + // Collection doesn't exist so create index + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + index = { filename: 1, uploadDate: 1 }; + stream.files.createIndex(index, { background: false }, (error) => { + if (error) { + return callback(error); + } + checkChunksIndex(stream, callback); + }); + return; + } + return callback(error); + } + let hasFileIndex = false; + if (indexes) { + indexes.forEach((index) => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + } + if (hasFileIndex) { + checkChunksIndex(stream, callback); + } + else { + index = { filename: 1, uploadDate: 1 }; + const writeConcernOptions = getWriteOptions(stream); + stream.files.createIndex(index, { + ...writeConcernOptions, + background: false + }, (error) => { + if (error) { + return callback(error); + } + checkChunksIndex(stream, callback); + }); + } + }); + }); +} +function createFilesDoc(_id, length, chunkSize, filename, contentType, aliases, metadata) { + const ret = { + _id, + length, + chunkSize, + uploadDate: new Date(), + filename + }; + if (contentType) { + ret.contentType = contentType; + } + if (aliases) { + ret.aliases = aliases; + } + if (metadata) { + ret.metadata = metadata; + } + return ret; +} +function doWrite(stream, chunk, encoding, callback) { + if (checkAborted(stream, callback)) { + return false; + } + const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + stream.length += inputBuf.length; + // Input is small enough to fit in our buffer + if (stream.pos + inputBuf.length < stream.chunkSizeBytes) { + inputBuf.copy(stream.bufToStore, stream.pos); + stream.pos += inputBuf.length; + callback && callback(); + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + let inputBufRemaining = inputBuf.length; + let spaceRemaining = stream.chunkSizeBytes - stream.pos; + let numToCopy = Math.min(spaceRemaining, inputBuf.length); + let outstandingRequests = 0; + while (inputBufRemaining > 0) { + const inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy); + stream.pos += numToCopy; + spaceRemaining -= numToCopy; + let doc; + if (spaceRemaining === 0) { + doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore)); + ++stream.state.outstandingRequests; + ++outstandingRequests; + if (checkAborted(stream, callback)) { + return false; + } + stream.chunks.insertOne(doc, getWriteOptions(stream), (error) => { + if (error) { + return __handleError(stream, error); + } + --stream.state.outstandingRequests; + --outstandingRequests; + if (!outstandingRequests) { + stream.emit('drain', doc); + callback && callback(); + checkDone(stream); + } + }); + spaceRemaining = stream.chunkSizeBytes; + stream.pos = 0; + ++stream.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} +function getWriteOptions(stream) { + const obj = {}; + if (stream.writeConcern) { + obj.writeConcern = { + w: stream.writeConcern.w, + wtimeout: stream.writeConcern.wtimeout, + j: stream.writeConcern.j + }; + } + return obj; +} +function waitForIndexes(stream, callback) { + if (stream.bucket.s.checkedIndexes) { + return callback(false); + } + stream.bucket.once('index', () => { + callback(true); + }); + return true; +} +function writeRemnant(stream, callback) { + // Buffer is empty, so don't bother to insert + if (stream.pos === 0) { + return checkDone(stream, callback); + } + ++stream.state.outstandingRequests; + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + const remnant = Buffer.alloc(stream.pos); + stream.bufToStore.copy(remnant, 0, 0, stream.pos); + const doc = createChunkDoc(stream.id, stream.n, remnant); + // If the stream was aborted, do not write remnant + if (checkAborted(stream, callback)) { + return false; + } + stream.chunks.insertOne(doc, getWriteOptions(stream), (error) => { + if (error) { + return __handleError(stream, error); + } + --stream.state.outstandingRequests; + checkDone(stream); + }); + return true; +} +function checkAborted(stream, callback) { + if (stream.state.aborted) { + if (typeof callback === 'function') { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosedError + callback(new error_1.MongoAPIError('Stream has been aborted')); + } + return true; + } + return false; +} +//# sourceMappingURL=upload.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/gridfs/upload.js.map b/node_modules/mongodb/lib/gridfs/upload.js.map new file mode 100644 index 0000000..41091d3 --- /dev/null +++ b/node_modules/mongodb/lib/gridfs/upload.js.map @@ -0,0 +1 @@ +{"version":3,"file":"upload.js","sourceRoot":"","sources":["../../src/gridfs/upload.ts"],"names":[],"mappings":";;;AAAA,mCAAkC;AAElC,kCAAmC;AAEnC,oCAAoF;AACpF,oCAAkD;AAElD,sDAAkD;AA0BlD;;;;;GAKG;AACH,MAAa,uBAAwB,SAAQ,iBAAQ;IA+BnD;;;;OAIG;IACH,YAAY,MAAoB,EAAE,QAAgB,EAAE,OAAwC;QAC1F,KAAK,EAAE,CAAC;QAER,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QACxB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,iBAAiB,CAAC;QACzC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,gBAAgB,CAAC;QACvC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,YAAY,GAAG,4BAAY,CAAC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AAG,CAAC,CAAC;IACzC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;IAClD,MAAM,GAAG,GAAG,cAAc,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;IAEzD,kDAAkD;IAClD,IAAI,YAAY,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE;QAClC,OAAO,KAAK,CAAC;KACd;IAED,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,EAAE,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,KAAgB,EAAE,EAAE;QACzE,IAAI,KAAK,EAAE;YACT,OAAO,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;SACrC;QACD,EAAE,MAAM,CAAC,KAAK,CAAC,mBAAmB,CAAC;QACnC,SAAS,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,YAAY,CAAC,MAA+B,EAAE,QAAyB;IAC9E,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE;QACxB,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;YAClC,6DAA6D;YAC7D,QAAQ,CAAC,IAAI,qBAAa,CAAC,yBAAyB,CAAC,CAAC,CAAC;SACxD;QACD,OAAO,IAAI,CAAC;KACb;IACD,OAAO,KAAK,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/index.js b/node_modules/mongodb/lib/index.js new file mode 100644 index 0000000..901b079 --- /dev/null +++ b/node_modules/mongodb/lib/index.js @@ -0,0 +1,149 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Logger = exports.Collection = exports.Db = exports.MongoClient = exports.Admin = exports.Promise = exports.MongoBulkWriteError = exports.MongoTopologyClosedError = exports.MongoServerClosedError = exports.MongoKerberosError = exports.MongoTransactionError = exports.MongoExpiredSessionError = exports.MongoNotConnectedError = exports.MongoCursorInUseError = exports.MongoCursorExhaustedError = exports.MongoBatchReExecutionError = exports.MongoDecompressionError = exports.MongoGridFSChunkError = exports.MongoGridFSStreamError = exports.MongoChangeStreamError = exports.MongoRuntimeError = exports.MongoWriteConcernError = exports.MongoParseError = exports.MongoServerSelectionError = exports.MongoSystemError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoInvalidArgumentError = exports.MongoCompatibilityError = exports.MongoAPIError = exports.MongoDriverError = exports.MongoServerError = exports.MongoError = exports.ObjectID = exports.Map = exports.BSONSymbol = exports.BSONRegExp = exports.Decimal128 = exports.Timestamp = exports.ObjectId = exports.MaxKey = exports.MinKey = exports.Long = exports.Int32 = exports.Double = exports.DBRef = exports.Code = exports.Binary = void 0; +exports.SrvPollingEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.TopologyClosedEvent = exports.ServerOpeningEvent = exports.ServerDescriptionChangedEvent = exports.ServerClosedEvent = exports.ServerHeartbeatFailedEvent = exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.ConnectionReadyEvent = exports.ConnectionPoolMonitoringEvent = exports.ConnectionPoolCreatedEvent = exports.ConnectionPoolClosedEvent = exports.ConnectionPoolClearedEvent = exports.ConnectionCreatedEvent = exports.ConnectionClosedEvent = exports.ConnectionCheckedOutEvent = exports.ConnectionCheckedInEvent = exports.ConnectionCheckOutStartedEvent = exports.ConnectionCheckOutFailedEvent = exports.CommandFailedEvent = exports.CommandSucceededEvent = exports.CommandStartedEvent = exports.ReadPreference = exports.ReadConcern = exports.WriteConcern = exports.BSONType = exports.ServerApiVersion = exports.ReadPreferenceMode = exports.ReadConcernLevel = exports.ExplainVerbosity = exports.ReturnDocument = exports.Compressor = exports.CURSOR_FLAGS = exports.AuthMechanism = exports.BatchType = exports.AutoEncryptionLoggerLevel = exports.LoggerLevel = exports.TopologyType = exports.ServerType = exports.ProfilingLevel = exports.CancellationToken = exports.GridFSBucket = exports.ListCollectionsCursor = exports.ListIndexesCursor = exports.FindCursor = exports.AggregationCursor = exports.AbstractCursor = void 0; +const abstract_cursor_1 = require("./cursor/abstract_cursor"); +Object.defineProperty(exports, "AbstractCursor", { enumerable: true, get: function () { return abstract_cursor_1.AbstractCursor; } }); +const aggregation_cursor_1 = require("./cursor/aggregation_cursor"); +Object.defineProperty(exports, "AggregationCursor", { enumerable: true, get: function () { return aggregation_cursor_1.AggregationCursor; } }); +const find_cursor_1 = require("./cursor/find_cursor"); +Object.defineProperty(exports, "FindCursor", { enumerable: true, get: function () { return find_cursor_1.FindCursor; } }); +const indexes_1 = require("./operations/indexes"); +Object.defineProperty(exports, "ListIndexesCursor", { enumerable: true, get: function () { return indexes_1.ListIndexesCursor; } }); +const list_collections_1 = require("./operations/list_collections"); +Object.defineProperty(exports, "ListCollectionsCursor", { enumerable: true, get: function () { return list_collections_1.ListCollectionsCursor; } }); +const promise_provider_1 = require("./promise_provider"); +Object.defineProperty(exports, "Promise", { enumerable: true, get: function () { return promise_provider_1.PromiseProvider; } }); +const admin_1 = require("./admin"); +Object.defineProperty(exports, "Admin", { enumerable: true, get: function () { return admin_1.Admin; } }); +const mongo_client_1 = require("./mongo_client"); +Object.defineProperty(exports, "MongoClient", { enumerable: true, get: function () { return mongo_client_1.MongoClient; } }); +const db_1 = require("./db"); +Object.defineProperty(exports, "Db", { enumerable: true, get: function () { return db_1.Db; } }); +const collection_1 = require("./collection"); +Object.defineProperty(exports, "Collection", { enumerable: true, get: function () { return collection_1.Collection; } }); +const logger_1 = require("./logger"); +Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return logger_1.Logger; } }); +const gridfs_1 = require("./gridfs"); +Object.defineProperty(exports, "GridFSBucket", { enumerable: true, get: function () { return gridfs_1.GridFSBucket; } }); +const mongo_types_1 = require("./mongo_types"); +Object.defineProperty(exports, "CancellationToken", { enumerable: true, get: function () { return mongo_types_1.CancellationToken; } }); +var bson_1 = require("./bson"); +Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return bson_1.Binary; } }); +Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return bson_1.Code; } }); +Object.defineProperty(exports, "DBRef", { enumerable: true, get: function () { return bson_1.DBRef; } }); +Object.defineProperty(exports, "Double", { enumerable: true, get: function () { return bson_1.Double; } }); +Object.defineProperty(exports, "Int32", { enumerable: true, get: function () { return bson_1.Int32; } }); +Object.defineProperty(exports, "Long", { enumerable: true, get: function () { return bson_1.Long; } }); +Object.defineProperty(exports, "MinKey", { enumerable: true, get: function () { return bson_1.MinKey; } }); +Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function () { return bson_1.MaxKey; } }); +Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function () { return bson_1.ObjectId; } }); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return bson_1.Timestamp; } }); +Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function () { return bson_1.Decimal128; } }); +Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function () { return bson_1.BSONRegExp; } }); +Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function () { return bson_1.BSONSymbol; } }); +Object.defineProperty(exports, "Map", { enumerable: true, get: function () { return bson_1.Map; } }); +const bson_2 = require("bson"); +/** + * @public + * @deprecated Please use `ObjectId` + */ +exports.ObjectID = bson_2.ObjectId; +var error_1 = require("./error"); +Object.defineProperty(exports, "MongoError", { enumerable: true, get: function () { return error_1.MongoError; } }); +Object.defineProperty(exports, "MongoServerError", { enumerable: true, get: function () { return error_1.MongoServerError; } }); +Object.defineProperty(exports, "MongoDriverError", { enumerable: true, get: function () { return error_1.MongoDriverError; } }); +Object.defineProperty(exports, "MongoAPIError", { enumerable: true, get: function () { return error_1.MongoAPIError; } }); +Object.defineProperty(exports, "MongoCompatibilityError", { enumerable: true, get: function () { return error_1.MongoCompatibilityError; } }); +Object.defineProperty(exports, "MongoInvalidArgumentError", { enumerable: true, get: function () { return error_1.MongoInvalidArgumentError; } }); +Object.defineProperty(exports, "MongoMissingCredentialsError", { enumerable: true, get: function () { return error_1.MongoMissingCredentialsError; } }); +Object.defineProperty(exports, "MongoMissingDependencyError", { enumerable: true, get: function () { return error_1.MongoMissingDependencyError; } }); +Object.defineProperty(exports, "MongoNetworkError", { enumerable: true, get: function () { return error_1.MongoNetworkError; } }); +Object.defineProperty(exports, "MongoNetworkTimeoutError", { enumerable: true, get: function () { return error_1.MongoNetworkTimeoutError; } }); +Object.defineProperty(exports, "MongoSystemError", { enumerable: true, get: function () { return error_1.MongoSystemError; } }); +Object.defineProperty(exports, "MongoServerSelectionError", { enumerable: true, get: function () { return error_1.MongoServerSelectionError; } }); +Object.defineProperty(exports, "MongoParseError", { enumerable: true, get: function () { return error_1.MongoParseError; } }); +Object.defineProperty(exports, "MongoWriteConcernError", { enumerable: true, get: function () { return error_1.MongoWriteConcernError; } }); +Object.defineProperty(exports, "MongoRuntimeError", { enumerable: true, get: function () { return error_1.MongoRuntimeError; } }); +Object.defineProperty(exports, "MongoChangeStreamError", { enumerable: true, get: function () { return error_1.MongoChangeStreamError; } }); +Object.defineProperty(exports, "MongoGridFSStreamError", { enumerable: true, get: function () { return error_1.MongoGridFSStreamError; } }); +Object.defineProperty(exports, "MongoGridFSChunkError", { enumerable: true, get: function () { return error_1.MongoGridFSChunkError; } }); +Object.defineProperty(exports, "MongoDecompressionError", { enumerable: true, get: function () { return error_1.MongoDecompressionError; } }); +Object.defineProperty(exports, "MongoBatchReExecutionError", { enumerable: true, get: function () { return error_1.MongoBatchReExecutionError; } }); +Object.defineProperty(exports, "MongoCursorExhaustedError", { enumerable: true, get: function () { return error_1.MongoCursorExhaustedError; } }); +Object.defineProperty(exports, "MongoCursorInUseError", { enumerable: true, get: function () { return error_1.MongoCursorInUseError; } }); +Object.defineProperty(exports, "MongoNotConnectedError", { enumerable: true, get: function () { return error_1.MongoNotConnectedError; } }); +Object.defineProperty(exports, "MongoExpiredSessionError", { enumerable: true, get: function () { return error_1.MongoExpiredSessionError; } }); +Object.defineProperty(exports, "MongoTransactionError", { enumerable: true, get: function () { return error_1.MongoTransactionError; } }); +Object.defineProperty(exports, "MongoKerberosError", { enumerable: true, get: function () { return error_1.MongoKerberosError; } }); +Object.defineProperty(exports, "MongoServerClosedError", { enumerable: true, get: function () { return error_1.MongoServerClosedError; } }); +Object.defineProperty(exports, "MongoTopologyClosedError", { enumerable: true, get: function () { return error_1.MongoTopologyClosedError; } }); +var common_1 = require("./bulk/common"); +Object.defineProperty(exports, "MongoBulkWriteError", { enumerable: true, get: function () { return common_1.MongoBulkWriteError; } }); +// enums +var set_profiling_level_1 = require("./operations/set_profiling_level"); +Object.defineProperty(exports, "ProfilingLevel", { enumerable: true, get: function () { return set_profiling_level_1.ProfilingLevel; } }); +var common_2 = require("./sdam/common"); +Object.defineProperty(exports, "ServerType", { enumerable: true, get: function () { return common_2.ServerType; } }); +Object.defineProperty(exports, "TopologyType", { enumerable: true, get: function () { return common_2.TopologyType; } }); +var logger_2 = require("./logger"); +Object.defineProperty(exports, "LoggerLevel", { enumerable: true, get: function () { return logger_2.LoggerLevel; } }); +var deps_1 = require("./deps"); +Object.defineProperty(exports, "AutoEncryptionLoggerLevel", { enumerable: true, get: function () { return deps_1.AutoEncryptionLoggerLevel; } }); +var common_3 = require("./bulk/common"); +Object.defineProperty(exports, "BatchType", { enumerable: true, get: function () { return common_3.BatchType; } }); +var defaultAuthProviders_1 = require("./cmap/auth/defaultAuthProviders"); +Object.defineProperty(exports, "AuthMechanism", { enumerable: true, get: function () { return defaultAuthProviders_1.AuthMechanism; } }); +var abstract_cursor_2 = require("./cursor/abstract_cursor"); +Object.defineProperty(exports, "CURSOR_FLAGS", { enumerable: true, get: function () { return abstract_cursor_2.CURSOR_FLAGS; } }); +var compression_1 = require("./cmap/wire_protocol/compression"); +Object.defineProperty(exports, "Compressor", { enumerable: true, get: function () { return compression_1.Compressor; } }); +var find_and_modify_1 = require("./operations/find_and_modify"); +Object.defineProperty(exports, "ReturnDocument", { enumerable: true, get: function () { return find_and_modify_1.ReturnDocument; } }); +var explain_1 = require("./explain"); +Object.defineProperty(exports, "ExplainVerbosity", { enumerable: true, get: function () { return explain_1.ExplainVerbosity; } }); +var read_concern_1 = require("./read_concern"); +Object.defineProperty(exports, "ReadConcernLevel", { enumerable: true, get: function () { return read_concern_1.ReadConcernLevel; } }); +var read_preference_1 = require("./read_preference"); +Object.defineProperty(exports, "ReadPreferenceMode", { enumerable: true, get: function () { return read_preference_1.ReadPreferenceMode; } }); +var mongo_client_2 = require("./mongo_client"); +Object.defineProperty(exports, "ServerApiVersion", { enumerable: true, get: function () { return mongo_client_2.ServerApiVersion; } }); +var mongo_types_2 = require("./mongo_types"); +Object.defineProperty(exports, "BSONType", { enumerable: true, get: function () { return mongo_types_2.BSONType; } }); +// Helper classes +var write_concern_1 = require("./write_concern"); +Object.defineProperty(exports, "WriteConcern", { enumerable: true, get: function () { return write_concern_1.WriteConcern; } }); +var read_concern_2 = require("./read_concern"); +Object.defineProperty(exports, "ReadConcern", { enumerable: true, get: function () { return read_concern_2.ReadConcern; } }); +var read_preference_2 = require("./read_preference"); +Object.defineProperty(exports, "ReadPreference", { enumerable: true, get: function () { return read_preference_2.ReadPreference; } }); +// events +var command_monitoring_events_1 = require("./cmap/command_monitoring_events"); +Object.defineProperty(exports, "CommandStartedEvent", { enumerable: true, get: function () { return command_monitoring_events_1.CommandStartedEvent; } }); +Object.defineProperty(exports, "CommandSucceededEvent", { enumerable: true, get: function () { return command_monitoring_events_1.CommandSucceededEvent; } }); +Object.defineProperty(exports, "CommandFailedEvent", { enumerable: true, get: function () { return command_monitoring_events_1.CommandFailedEvent; } }); +var connection_pool_events_1 = require("./cmap/connection_pool_events"); +Object.defineProperty(exports, "ConnectionCheckOutFailedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckOutFailedEvent; } }); +Object.defineProperty(exports, "ConnectionCheckOutStartedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckOutStartedEvent; } }); +Object.defineProperty(exports, "ConnectionCheckedInEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckedInEvent; } }); +Object.defineProperty(exports, "ConnectionCheckedOutEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckedOutEvent; } }); +Object.defineProperty(exports, "ConnectionClosedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionClosedEvent; } }); +Object.defineProperty(exports, "ConnectionCreatedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCreatedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolClearedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolClearedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolClosedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolClosedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolCreatedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolCreatedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolMonitoringEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolMonitoringEvent; } }); +Object.defineProperty(exports, "ConnectionReadyEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionReadyEvent; } }); +var events_1 = require("./sdam/events"); +Object.defineProperty(exports, "ServerHeartbeatStartedEvent", { enumerable: true, get: function () { return events_1.ServerHeartbeatStartedEvent; } }); +Object.defineProperty(exports, "ServerHeartbeatSucceededEvent", { enumerable: true, get: function () { return events_1.ServerHeartbeatSucceededEvent; } }); +Object.defineProperty(exports, "ServerHeartbeatFailedEvent", { enumerable: true, get: function () { return events_1.ServerHeartbeatFailedEvent; } }); +Object.defineProperty(exports, "ServerClosedEvent", { enumerable: true, get: function () { return events_1.ServerClosedEvent; } }); +Object.defineProperty(exports, "ServerDescriptionChangedEvent", { enumerable: true, get: function () { return events_1.ServerDescriptionChangedEvent; } }); +Object.defineProperty(exports, "ServerOpeningEvent", { enumerable: true, get: function () { return events_1.ServerOpeningEvent; } }); +Object.defineProperty(exports, "TopologyClosedEvent", { enumerable: true, get: function () { return events_1.TopologyClosedEvent; } }); +Object.defineProperty(exports, "TopologyDescriptionChangedEvent", { enumerable: true, get: function () { return events_1.TopologyDescriptionChangedEvent; } }); +Object.defineProperty(exports, "TopologyOpeningEvent", { enumerable: true, get: function () { return events_1.TopologyOpeningEvent; } }); +var srv_polling_1 = require("./sdam/srv_polling"); +Object.defineProperty(exports, "SrvPollingEvent", { enumerable: true, get: function () { return srv_polling_1.SrvPollingEvent; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/index.js.map b/node_modules/mongodb/lib/index.js.map new file mode 100644 index 0000000..67e42a5 --- /dev/null +++ b/node_modules/mongodb/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAAA,8DAA0D;AA8ExD,+FA9EO,gCAAc,OA8EP;AA7EhB,oEAAgE;AA8E9D,kGA9EO,sCAAiB,OA8EP;AA7EnB,sDAAkD;AA8EhD,2FA9EO,wBAAU,OA8EP;AA7EZ,kDAAyD;AA8EvD,kGA9EO,2BAAiB,OA8EP;AA7EnB,oEAAsE;AA8EpE,sGA9EO,wCAAqB,OA8EP;AA7EvB,yDAAqD;AAkEhC,wFAlEZ,kCAAe,OAkEI;AAjE5B,mCAAgC;AAmE9B,sFAnEO,aAAK,OAmEP;AAlEP,iDAA6C;AAmE3C,4FAnEO,0BAAW,OAmEP;AAlEb,6BAA0B;AAmExB,mFAnEO,OAAE,OAmEP;AAlEJ,6CAA0C;AAmExC,2FAnEO,uBAAU,OAmEP;AAlEZ,qCAAkC;AAmEhC,uFAnEO,eAAM,OAmEP;AAlER,qCAAwC;AAwEtC,6FAxEO,qBAAY,OAwEP;AAvEd,+CAAkD;AAwEhD,kGAxEO,+BAAiB,O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,wCAUuB;AATrB,qHAAA,2BAA2B,OAAA;AAC3B,uHAAA,6BAA6B,OAAA;AAC7B,oHAAA,0BAA0B,OAAA;AAC1B,2GAAA,iBAAiB,OAAA;AACjB,uHAAA,6BAA6B,OAAA;AAC7B,4GAAA,kBAAkB,OAAA;AAClB,6GAAA,mBAAmB,OAAA;AACnB,yHAAA,+BAA+B,OAAA;AAC/B,8GAAA,oBAAoB,OAAA;AAEtB,kDAAqD;AAA5C,8GAAA,eAAe,OAAA"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/logger.js b/node_modules/mongodb/lib/logger.js new file mode 100644 index 0000000..94496c4 --- /dev/null +++ b/node_modules/mongodb/lib/logger.js @@ -0,0 +1,217 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Logger = exports.LoggerLevel = void 0; +const util_1 = require("util"); +const utils_1 = require("./utils"); +const error_1 = require("./error"); +// Filters for classes +const classFilters = {}; +let filteredClasses = {}; +let level; +// Save the process id +const pid = process.pid; +// current logger +// eslint-disable-next-line no-console +let currentLogger = console.warn; +/** @public */ +exports.LoggerLevel = Object.freeze({ + ERROR: 'error', + WARN: 'warn', + INFO: 'info', + DEBUG: 'debug', + error: 'error', + warn: 'warn', + info: 'info', + debug: 'debug' +}); +/** + * @public + */ +class Logger { + /** + * Creates a new Logger instance + * + * @param className - The Class name associated with the logging instance + * @param options - Optional logging settings + */ + constructor(className, options) { + options = options !== null && options !== void 0 ? options : {}; + // Current reference + this.className = className; + // Current logger + if (!(options.logger instanceof Logger) && typeof options.logger === 'function') { + currentLogger = options.logger; + } + // Set level of logging, default is error + if (options.loggerLevel) { + level = options.loggerLevel || exports.LoggerLevel.ERROR; + } + // Add all class names + if (filteredClasses[this.className] == null) { + classFilters[this.className] = true; + } + } + /** + * Log a message at the debug level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + debug(message, object) { + if (this.isDebug() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = util_1.format('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.DEBUG, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** + * Log a message at the warn level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + warn(message, object) { + if (this.isWarn() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = util_1.format('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.WARN, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** + * Log a message at the info level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + info(message, object) { + if (this.isInfo() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = util_1.format('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.INFO, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** + * Log a message at the error level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + error(message, object) { + if (this.isError() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = util_1.format('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.ERROR, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** Is the logger set at info level */ + isInfo() { + return level === exports.LoggerLevel.INFO || level === exports.LoggerLevel.DEBUG; + } + /** Is the logger set at error level */ + isError() { + return level === exports.LoggerLevel.ERROR || level === exports.LoggerLevel.INFO || level === exports.LoggerLevel.DEBUG; + } + /** Is the logger set at error level */ + isWarn() { + return (level === exports.LoggerLevel.ERROR || + level === exports.LoggerLevel.WARN || + level === exports.LoggerLevel.INFO || + level === exports.LoggerLevel.DEBUG); + } + /** Is the logger set at debug level */ + isDebug() { + return level === exports.LoggerLevel.DEBUG; + } + /** Resets the logger to default settings, error and no filtered classes */ + static reset() { + level = exports.LoggerLevel.ERROR; + filteredClasses = {}; + } + /** Get the current logger function */ + static currentLogger() { + return currentLogger; + } + /** + * Set the current logger function + * + * @param logger - Custom logging function + */ + static setCurrentLogger(logger) { + if (typeof logger !== 'function') { + throw new error_1.MongoInvalidArgumentError('Current logger must be a function'); + } + currentLogger = logger; + } + /** + * Filter log messages for a particular class + * + * @param type - The type of filter (currently only class) + * @param values - The filters to apply + */ + static filter(type, values) { + if (type === 'class' && Array.isArray(values)) { + filteredClasses = {}; + values.forEach(x => (filteredClasses[x] = true)); + } + } + /** + * Set the current log level + * + * @param newLevel - Set current log level (debug, warn, info, error) + */ + static setLevel(newLevel) { + if (newLevel !== exports.LoggerLevel.INFO && + newLevel !== exports.LoggerLevel.ERROR && + newLevel !== exports.LoggerLevel.DEBUG && + newLevel !== exports.LoggerLevel.WARN) { + throw new error_1.MongoInvalidArgumentError(`Argument "newLevel" should be one of ${utils_1.enumToString(exports.LoggerLevel)}`); + } + level = newLevel; + } +} +exports.Logger = Logger; +//# sourceMappingURL=logger.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/logger.js.map b/node_modules/mongodb/lib/logger.js.map new file mode 100644 index 0000000..7aeb630 --- /dev/null +++ b/node_modules/mongodb/lib/logger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":";;;AAAA,+BAA8B;AAC9B,mCAAuC;AACvC,mCAAoD;AAEpD,sBAAsB;AACtB,MAA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_modules/mongodb/lib/mongo_client.js b/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 0000000..e5e8aad --- /dev/null +++ b/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,262 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoClient = exports.ServerApiVersion = void 0; +const db_1 = require("./db"); +const change_stream_1 = require("./change_stream"); +const error_1 = require("./error"); +const utils_1 = require("./utils"); +const connect_1 = require("./operations/connect"); +const promise_provider_1 = require("./promise_provider"); +const bson_1 = require("./bson"); +const connection_string_1 = require("./connection_string"); +const mongo_types_1 = require("./mongo_types"); +/** @public */ +exports.ServerApiVersion = Object.freeze({ + v1: '1' +}); +/** @internal */ +const kOptions = Symbol('options'); +/** + * The **MongoClient** class is a class that allows for making Connections to MongoDB. + * @public + * + * @remarks + * The programmatically provided options take precedent over the URI options. + * + * @example + * ```js + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + * + * @example + * ```js + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + */ +class MongoClient extends mongo_types_1.TypedEventEmitter { + constructor(url, options) { + super(); + this[kOptions] = connection_string_1.parseOptions(url, this, options); + // eslint-disable-next-line @typescript-eslint/no-this-alias + const client = this; + // The internal state + this.s = { + url, + sessions: new Set(), + bsonOptions: bson_1.resolveBSONOptions(this[kOptions]), + namespace: utils_1.ns('admin'), + get options() { + return client[kOptions]; + }, + get readConcern() { + return client[kOptions].readConcern; + }, + get writeConcern() { + return client[kOptions].writeConcern; + }, + get readPreference() { + return client[kOptions].readPreference; + }, + get logger() { + return client[kOptions].logger; + } + }; + } + get options() { + return Object.freeze({ ...this[kOptions] }); + } + get serverApi() { + return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi }); + } + /** + * Intended for APM use only + * @internal + */ + get monitorCommands() { + return this[kOptions].monitorCommands; + } + set monitorCommands(value) { + this[kOptions].monitorCommands = value; + } + get autoEncrypter() { + return this[kOptions].autoEncrypter; + } + get readConcern() { + return this.s.readConcern; + } + get writeConcern() { + return this.s.writeConcern; + } + get readPreference() { + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + get logger() { + return this.s.logger; + } + connect(callback) { + if (callback && typeof callback !== 'function') { + throw new error_1.MongoInvalidArgumentError('Method `connect` only accepts a callback'); + } + return utils_1.maybePromise(callback, cb => { + connect_1.connect(this, this[kOptions], err => { + if (err) + return cb(err); + cb(undefined, this); + }); + }); + } + close(forceOrCallback, callback) { + if (typeof forceOrCallback === 'function') { + callback = forceOrCallback; + } + const force = typeof forceOrCallback === 'boolean' ? forceOrCallback : false; + return utils_1.maybePromise(callback, callback => { + if (this.topology == null) { + return callback(); + } + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + topology.close({ force }, error => { + if (error) + return callback(error); + const { encrypter } = this[kOptions]; + if (encrypter) { + return encrypter.close(this, force, error => { + callback(error); + }); + } + callback(); + }); + }); + } + /** + * Create a new Db instance sharing the current socket connections. + * + * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. + * @param options - Optional settings for Db construction + */ + db(dbName, options) { + options = options !== null && options !== void 0 ? options : {}; + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.options.dbName; + } + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this[kOptions], options); + // Return the db object + const db = new db_1.Db(this, dbName, finalOptions); + // Return the database + return db; + } + static connect(url, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + try { + // Create client + const mongoClient = new MongoClient(url, options); + // Execute the connect method + if (callback) { + return mongoClient.connect(callback); + } + else { + return mongoClient.connect(); + } + } + catch (error) { + if (callback) + return callback(error); + else + return promise_provider_1.PromiseProvider.get().reject(error); + } + } + startSession(options) { + options = Object.assign({ explicit: true }, options); + if (!this.topology) { + throw new error_1.MongoNotConnectedError('MongoClient must be connected to start a session'); + } + return this.topology.startSession(options, this.s.options); + } + withSession(optionsOrOperation, callback) { + let options = optionsOrOperation; + if (typeof optionsOrOperation === 'function') { + callback = optionsOrOperation; + options = { owner: Symbol() }; + } + if (callback == null) { + throw new error_1.MongoInvalidArgumentError('Missing required callback parameter'); + } + const session = this.startSession(options); + const Promise = promise_provider_1.PromiseProvider.get(); + let cleanupHandler = ((err, result, opts) => { + // prevent multiple calls to cleanupHandler + cleanupHandler = () => { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('cleanupHandler was called too many times'); + }; + opts = Object.assign({ throw: true }, opts); + session.endSession(); + if (err) { + if (opts.throw) + throw err; + return Promise.reject(err); + } + }); + try { + const result = callback(session); + return Promise.resolve(result).then(result => cleanupHandler(undefined, result, undefined), err => cleanupHandler(err, null, { throw: true })); + } + catch (err) { + return cleanupHandler(err, null, { throw: false }); + } + } + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this cluster. Will ignore all + * changes to system collections, as well as the local, admin, and config databases. + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + return new change_stream_1.ChangeStream(this, pipeline, utils_1.resolveOptions(this, options)); + } + /** Return the mongo client logger */ + getLogger() { + return this.s.logger; + } +} +exports.MongoClient = MongoClient; +//# sourceMappingURL=mongo_client.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongo_client.js.map b/node_modules/mongodb/lib/mongo_client.js.map new file mode 100644 index 0000000..be823c4 --- /dev/null +++ b/node_modules/mongodb/lib/mongo_client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_client.js","sourceRoot":"","sources":["../src/mongo_client.ts"],"names":[],"mappings":";;;AAAA,6BAAqC;AACrC,mDAAoE;AAEpE,mCAKiB;AAEjB,mCAQiB;AACjB,kDAAoE;AACpE,yDAAqD;AAGrD,iCAA4E;AAO5E,2DAAmD;AAQnD,+CAAkD;AAElD,cAAc;AACD,QAAA,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5C,EAAE,EAAE,GAAG;CACC,CAAC,CAAC;AAiOZ,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AAEnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,MAAa,WAAY,SAAQ,+BAAoC;IAYnE,YAAY,GAAW,EAAE,OAA4B;QACnD,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,QAAQ,CAAC,GAAG,gCAAY,CAAC,GAAG,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAElD,4DAA4D;QAC5D,MAAM,MAAM,GAAG,IAAI,CAAC;QAEpB,qBAAqB;QACrB,IAAI,CAAC,CAAC,GAAG;YACP,GAAG;YACH,QAAQ,EAAE,IAAI,GAAG,EAAE;YACnB,WAAW,EAAE,yBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC/C,SAAS,EAAE,UAAE,CAAC,OAAO,CAAC;YAEtB,IAAI,OAAO;gBACT,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC1B,CAAC;YACD,IAAI,WAAW;gBACb,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,WAAW,CAAC;YACtC,CAAC;YACD,IAAI,YAAY;gBACd,OAAO,MAAM,C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AAE;gBACP,IAAI,IAAI,CAAC,KAAK;oBAAE,MAAM,GAAG,CAAC;gBAC1B,OAAO,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;aAC5B;QACH,CAAC,CAA2B,CAAC;QAE7B,IAAI;YACF,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC;YACjC,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CACjC,MAAM,CAAC,EAAE,CAAC,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,CAAC,EACtD,GAAG,CAAC,EAAE,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAClD,CAAC;SACH;QAAC,OAAO,GAAG,EAAE;YACZ,OAAO,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAkB,CAAC;SACrE;IACH,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CACH,WAAuB,EAAE,EACzB,UAA+B,EAAE;QAEjC,6CAA6C;QAC7C,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC5B,OAAO,GAAG,QAAQ,CAAC;YACnB,QAAQ,GAAG,EAAE,CAAC;SACf;QAED,OAAO,IAAI,4BAAY,CAAU,IAAI,EAAE,QAAQ,EAAE,sBAAc,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IAClF,CAAC;IAED,qCAAqC;IACrC,SAAS;QACP,OAAO,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;IACvB,CAAC;CACF;AA5SD,kCA4SC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongo_types.js b/node_modules/mongodb/lib/mongo_types.js new file mode 100644 index 0000000..7cd4048 --- /dev/null +++ b/node_modules/mongodb/lib/mongo_types.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CancellationToken = exports.TypedEventEmitter = exports.BSONType = void 0; +const events_1 = require("events"); +/** @public */ +exports.BSONType = Object.freeze({ + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: -1, + maxKey: 127 +}); +/** + * Typescript type safe event emitter + * @public + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class TypedEventEmitter extends events_1.EventEmitter { +} +exports.TypedEventEmitter = TypedEventEmitter; +/** @public */ +class CancellationToken extends TypedEventEmitter { +} +exports.CancellationToken = CancellationToken; +//# sourceMappingURL=mongo_types.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongo_types.js.map b/node_modules/mongodb/lib/mongo_types.js.map new file mode 100644 index 0000000..605f94e --- /dev/null +++ b/node_modules/mongodb/lib/mongo_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_types.js","sourceRoot":"","sources":["../src/mongo_types.ts"],"names":[],"mappings":";;;AAWA,mCAAsC;AAkItC,cAAc;AACD,QAAA,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC;IACpC,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,CAAC;IACT,KAAK,EAAE,CAAC;IACR,OAAO,EAAE,CAAC;IACV,SAAS,EAAE,CAAC;IACZ,QAAQ,EAAE,CAAC;IACX,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;IACT,SAAS,EAAE,EAAE;IACb,UAAU,EAAE,EAAE;IACd,MAAM,EAAE,EAAE;IACV,mBAAmB,EAAE,EAAE;IACvB,GAAG,EAAE,EAAE;IACP,SAAS,EAAE,EAAE;IACb,IAAI,EAAE,EAAE;IACR,OAAO,EAAE,EAAE;IACX,MAAM,EAAE,CAAC,CAAC;IACV,MAAM,EAAE,GAAG;CACH,CAAC,CAAC;AA8PZ;;;GAGG;AACH,6DAA6D;AAC7D,MAAa,iBAAoD,SAAQ,qBAAY;CAAG;AAAxF,8CAAwF;AAExF,cAAc;AACd,MAAa,iBAAkB,SAAQ,iBAAqC;CAAG;AAA/E,8CAA+E"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/add_user.js b/node_modules/mongodb/lib/operations/add_user.js new file mode 100644 index 0000000..cdac6ad --- /dev/null +++ b/node_modules/mongodb/lib/operations/add_user.js @@ -0,0 +1,65 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AddUserOperation = void 0; +const crypto = require("crypto"); +const operation_1 = require("./operation"); +const command_1 = require("./command"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +/** @internal */ +class AddUserOperation extends command_1.CommandOperation { + constructor(db, username, password, options) { + super(db, options); + this.db = db; + this.username = username; + this.password = password; + this.options = options !== null && options !== void 0 ? options : {}; + } + execute(server, session, callback) { + const db = this.db; + const username = this.username; + const password = this.password; + const options = this.options; + // Error out if digestPassword set + if (options.digestPassword != null) { + return callback(new error_1.MongoInvalidArgumentError('Option "digestPassword" not supported via addUser, use db.command(...) instead')); + } + let roles; + if (!options.roles || (Array.isArray(options.roles) && options.roles.length === 0)) { + utils_1.emitWarningOnce('Creating a user without roles is deprecated. Defaults to "root" if db is "admin" or "dbOwner" otherwise'); + if (db.databaseName.toLowerCase() === 'admin') { + roles = ['root']; + } + else { + roles = ['dbOwner']; + } + } + else { + roles = Array.isArray(options.roles) ? options.roles : [options.roles]; + } + const digestPassword = utils_1.getTopology(db).lastIsMaster().maxWireVersion >= 7; + let userPassword = password; + if (!digestPassword) { + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(`${username}:mongo:${password}`); + userPassword = md5.digest('hex'); + } + // Build the command to execute + const command = { + createUser: username, + customData: options.customData || {}, + roles: roles, + digestPassword + }; + // No password + if (typeof password === 'string') { + command.pwd = userPassword; + } + super.executeCommand(server, session, command, callback); + } +} +exports.AddUserOperation = AddUserOperation; +operation_1.defineAspects(AddUserOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=add_user.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/add_user.js.map b/node_modules/mongodb/lib/operations/add_user.js.map new file mode 100644 index 0000000..8d1e5d1 --- /dev/null +++ b/node_modules/mongodb/lib/operations/add_user.js.map @@ -0,0 +1 @@ +{"version":3,"file":"add_user.js","sourceRoot":"","sources":["../../src/operations/add_user.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AACjC,2CAAoD;AACpD,uCAAsE;AACtE,oCAAqD;AACrD,oCAAkE;AA2BlE,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,0BAA0B;IAM9D,YAAY,EAAM,EAAE,QAAgB,EAAE,QAA4B,EAAE,OAAwB;QAC1F,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAEnB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;IAC/B,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA4B;QAC1E,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;QACnB,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE7B,kCAAkC;QAClC,IAAI,OAAO,CAAC,cAAc,IAAI,IAAI,EAAE;YAClC,OAAO,QAAQ,CACb,IAAI,iCAAyB,CAC3B,gFAAgF,CACjF,CACF,CAAC;SAC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ED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC3D,CAAC;CACF;AAvED,4CAuEC;AAED,yBAAa,CAAC,gBAAgB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/aggregate.js b/node_modules/mongodb/lib/operations/aggregate.js new file mode 100644 index 0000000..f66116c --- /dev/null +++ b/node_modules/mongodb/lib/operations/aggregate.js @@ -0,0 +1,86 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregateOperation = exports.DB_AGGREGATE_COLLECTION = void 0; +const command_1 = require("./command"); +const read_preference_1 = require("../read_preference"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const operation_1 = require("./operation"); +/** @internal */ +exports.DB_AGGREGATE_COLLECTION = 1; +const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; +/** @internal */ +class AggregateOperation extends command_1.CommandOperation { + constructor(ns, pipeline, options) { + super(undefined, { ...options, dbName: ns.db }); + this.options = options !== null && options !== void 0 ? options : {}; + // Covers when ns.collection is null, undefined or the empty string, use DB_AGGREGATE_COLLECTION + this.target = ns.collection || exports.DB_AGGREGATE_COLLECTION; + this.pipeline = pipeline; + // determine if we have a write stage, override read preference if so + this.hasWriteStage = false; + if (typeof (options === null || options === void 0 ? void 0 : options.out) === 'string') { + this.pipeline = this.pipeline.concat({ $out: options.out }); + this.hasWriteStage = true; + } + else if (pipeline.length > 0) { + const finalStage = pipeline[pipeline.length - 1]; + if (finalStage.$out || finalStage.$merge) { + this.hasWriteStage = true; + } + } + if (this.hasWriteStage) { + this.readPreference = read_preference_1.ReadPreference.primary; + } + if (this.explain && this.writeConcern) { + throw new error_1.MongoInvalidArgumentError('Option "explain" cannot be used on an aggregate call with writeConcern'); + } + if ((options === null || options === void 0 ? void 0 : options.cursor) != null && typeof options.cursor !== 'object') { + throw new error_1.MongoInvalidArgumentError('Cursor options must be an object'); + } + } + get canRetryRead() { + return !this.hasWriteStage; + } + addToPipeline(stage) { + this.pipeline.push(stage); + } + execute(server, session, callback) { + const options = this.options; + const serverWireVersion = utils_1.maxWireVersion(server); + const command = { aggregate: this.target, pipeline: this.pipeline }; + if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { + this.readConcern = undefined; + } + if (serverWireVersion >= 5) { + if (this.hasWriteStage && this.writeConcern) { + Object.assign(command, { writeConcern: this.writeConcern }); + } + } + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + if (typeof options.allowDiskUse === 'boolean') { + command.allowDiskUse = options.allowDiskUse; + } + if (options.hint) { + command.hint = options.hint; + } + if (options.let) { + command.let = options.let; + } + command.cursor = options.cursor || {}; + if (options.batchSize && !this.hasWriteStage) { + command.cursor.batchSize = options.batchSize; + } + super.executeCommand(server, session, command, callback); + } +} +exports.AggregateOperation = AggregateOperation; +operation_1.defineAspects(AggregateOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=aggregate.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/aggregate.js.map b/node_modules/mongodb/lib/operations/aggregate.js.map new file mode 100644 index 0000000..cc1f24d --- /dev/null +++ b/node_modules/mongodb/lib/operations/aggregate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aggregate.js","sourceRoot":"","sources":["../../src/operations/aggregate.ts"],"names":[],"mappings":";;;AAAA,uCAAwF;AACxF,wDAAoD;AACpD,oCAAqD;AACrD,oCAA4D;AAC5D,2CAA0D;AAM1D,gBAAgB;AACH,QAAA,uBAAuB,GAAG,CAAU,CAAC;AAClD,MAAM,0CAA0C,GAAG,CAAU,CAAC;AAyB9D,gBAAgB;AAChB,MAAa,kBAAiC,SAAQ,0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AE;YACf,OAAO,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;SAC3B;QAED,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC;QACtC,IAAI,OAAO,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE;YAC5C,OAAO,CAAC,MAAM,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;SAC9C;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC3D,CAAC;CACF;AAzFD,gDAyFC;AAED,yBAAa,CAAC,kBAAkB,EAAE;IAChC,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/bulk_write.js b/node_modules/mongodb/lib/operations/bulk_write.js new file mode 100644 index 0000000..e02029a --- /dev/null +++ b/node_modules/mongodb/lib/operations/bulk_write.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BulkWriteOperation = void 0; +const operation_1 = require("./operation"); +/** @internal */ +class BulkWriteOperation extends operation_1.AbstractOperation { + constructor(collection, operations, options) { + super(options); + this.options = options; + this.collection = collection; + this.operations = operations; + } + execute(server, session, callback) { + const coll = this.collection; + const operations = this.operations; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + // Create the bulk operation + const bulk = options.ordered === false + ? coll.initializeUnorderedBulkOp(options) + : coll.initializeOrderedBulkOp(options); + // for each op go through and add to the bulk + try { + for (let i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); + } + } + catch (err) { + return callback(err); + } + // Execute the bulk + bulk.execute({ ...options, session }, (err, r) => { + // We have connection level error + if (!r && err) { + return callback(err); + } + // Return the results + callback(undefined, r); + }); + } +} +exports.BulkWriteOperation = BulkWriteOperation; +operation_1.defineAspects(BulkWriteOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=bulk_write.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/bulk_write.js.map b/node_modules/mongodb/lib/operations/bulk_write.js.map new file mode 100644 index 0000000..cf5a6e4 --- /dev/null +++ b/node_modules/mongodb/lib/operations/bulk_write.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bulk_write.js","sourceRoot":"","sources":["../../src/operations/bulk_write.ts"],"names":[],"mappings":";;;AAAA,2CAAuE;AAYvE,gBAAgB;AAChB,MAAa,kBAAmB,SAAQ,6BAAkC;IAKxE,YACE,UAAsB,EACtB,UAAmC,EACnC,OAAyB;QAEzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAAmC;QACjF,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAC7B,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;QACnC,MAAM,OAAO,GAAG,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC;QAE9F,4BAA4B;QAC5B,MAAM,IAAI,GACR,OAAO,CAAC,OAAO,KAAK,KAAK;YACvB,CAAC,CAAC,IAAI,CAAC,yBAAyB,CAAC,OAAO,CAAC;YACzC,CAAC,CAAC,IAAI,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC;QAE5C,6CAA6C;QAC7C,IAAI;YACF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gBAC1C,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;aACzB;SACF;QAAC,OAAO,GAAG,EAAE;YACZ,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;SACtB;QAED,mBAAmB;QACnB,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE;YAC/C,iCAAiC;YACjC,IAAI,CAAC,CAAC,IAAI,GAAG,EAAE;gBACb,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;aACtB;YAED,qBAAqB;YACrB,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;QACzB,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA/CD,gDA+CC;AAED,yBAAa,CAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/collections.js b/node_modules/mongodb/lib/operations/collections.js new file mode 100644 index 0000000..927b991 --- /dev/null +++ b/node_modules/mongodb/lib/operations/collections.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CollectionsOperation = void 0; +const operation_1 = require("./operation"); +const collection_1 = require("../collection"); +/** @internal */ +class CollectionsOperation extends operation_1.AbstractOperation { + constructor(db, options) { + super(options); + this.options = options; + this.db = db; + } + execute(server, session, callback) { + const db = this.db; + // Let's get the collection names + db.listCollections({}, { ...this.options, nameOnly: true, readPreference: this.readPreference, session }).toArray((err, documents) => { + if (err || !documents) + return callback(err); + // Filter collections removing any illegal ones + documents = documents.filter(doc => doc.name.indexOf('$') === -1); + // Return the collection objects + callback(undefined, documents.map(d => { + return new collection_1.Collection(db, d.name, db.s.options); + })); + }); + } +} +exports.CollectionsOperation = CollectionsOperation; +//# sourceMappingURL=collections.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/collections.js.map b/node_modules/mongodb/lib/operations/collections.js.map new file mode 100644 index 0000000..31af51a --- /dev/null +++ b/node_modules/mongodb/lib/operations/collections.js.map @@ -0,0 +1 @@ +{"version":3,"file":"collections.js","sourceRoot":"","sources":["../../src/operations/collections.ts"],"names":[],"mappings":";;;AAAA,2CAAkE;AAClE,8CAA2C;AAU3C,gBAAgB;AAChB,MAAa,oBAAqB,SAAQ,6BAA+B;IAIvE,YAAY,EAAM,EAAE,OAA2B;QAC7C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACf,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAAgC;QAC9E,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;QAEnB,iCAAiC;QACjC,EAAE,CAAC,eAAe,CAChB,EAAE,EACF,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CAClF,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,SAAS,EAAE,EAAE;YAC3B,IAAI,GAAG,IAAI,CAAC,SAAS;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC5C,+CAA+C;YAC/C,SAAS,GAAG,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAElE,gCAAgC;YAChC,QAAQ,CACN,SAAS,EACT,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE;gBAChB,OAAO,IAAI,uBAAU,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;YAClD,CAAC,CAAC,CACH,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA/BD,oDA+BC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/command.js b/node_modules/mongodb/lib/operations/command.js new file mode 100644 index 0000000..1c8b704 --- /dev/null +++ b/node_modules/mongodb/lib/operations/command.js @@ -0,0 +1,95 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CommandOperation = void 0; +const operation_1 = require("./operation"); +const read_concern_1 = require("../read_concern"); +const write_concern_1 = require("../write_concern"); +const utils_1 = require("../utils"); +const sessions_1 = require("../sessions"); +const error_1 = require("../error"); +const explain_1 = require("../explain"); +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; +/** @internal */ +class CommandOperation extends operation_1.AbstractOperation { + constructor(parent, options) { + super(options); + this.options = options !== null && options !== void 0 ? options : {}; + // NOTE: this was explicitly added for the add/remove user operations, it's likely + // something we'd want to reconsider. Perhaps those commands can use `Admin` + // as a parent? + const dbNameOverride = (options === null || options === void 0 ? void 0 : options.dbName) || (options === null || options === void 0 ? void 0 : options.authdb); + if (dbNameOverride) { + this.ns = new utils_1.MongoDBNamespace(dbNameOverride, '$cmd'); + } + else { + this.ns = parent + ? parent.s.namespace.withCollection('$cmd') + : new utils_1.MongoDBNamespace('admin', '$cmd'); + } + this.readConcern = read_concern_1.ReadConcern.fromOptions(options); + this.writeConcern = write_concern_1.WriteConcern.fromOptions(options); + // TODO(NODE-2056): make logger another "inheritable" property + if (parent && parent.logger) { + this.logger = parent.logger; + } + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + this.explain = explain_1.Explain.fromOptions(options); + } + else if ((options === null || options === void 0 ? void 0 : options.explain) != null) { + throw new error_1.MongoInvalidArgumentError(`Option "explain" is not supported on this command`); + } + } + get canRetryWrite() { + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + return this.explain == null; + } + return true; + } + executeCommand(server, session, cmd, callback) { + // TODO: consider making this a non-enumerable property + this.server = server; + const options = { + ...this.options, + ...this.bsonOptions, + readPreference: this.readPreference, + session + }; + const serverWireVersion = utils_1.maxWireVersion(server); + const inTransaction = this.session && this.session.inTransaction(); + if (this.readConcern && sessions_1.commandSupportsReadConcern(cmd) && !inTransaction) { + Object.assign(cmd, { readConcern: this.readConcern }); + } + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`)); + return; + } + if (this.writeConcern && this.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !inTransaction) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + if (options.collation && + typeof options.collation === 'object' && + !this.hasAspect(operation_1.Aspect.SKIP_COLLATION)) { + Object.assign(cmd, { collation: options.collation }); + } + } + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + if (typeof options.comment === 'string') { + cmd.comment = options.comment; + } + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE) && this.explain) { + if (serverWireVersion < 6 && cmd.aggregate) { + // Prior to 3.6, with aggregate, verbosity is ignored, and we must pass in "explain: true" + cmd.explain = true; + } + else { + cmd = utils_1.decorateWithExplain(cmd, this.explain); + } + } + server.command(this.ns, cmd, options, callback); + } +} +exports.CommandOperation = CommandOperation; +//# sourceMappingURL=command.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/command.js.map b/node_modules/mongodb/lib/operations/command.js.map new file mode 100644 index 0000000..1c74467 --- /dev/null +++ b/node_modules/mongodb/lib/operations/command.js.map @@ -0,0 +1 @@ +{"version":3,"file":"command.js","sourceRoot":"","sources":["../../src/operations/command.ts"],"names":[],"mappings":";;;AAAA,2CAA0E;AAC1E,kDAA8C;AAC9C,oDAAqE;AACrE,oCAA2F;AAE3F,0CAAwE;AACxE,oCAA8E;AAK9E,wCAAqD;AAErD,MAAM,oCAAoC,GAAG,CAAC,CAAC;AAgD/C,gBAAgB;AAChB,M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AAS;gBACjB,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ;gBACrC,CAAC,IAAI,CAAC,SAAS,CAAC,kBAAM,CAAC,cAAc,CAAC,EACtC;gBACA,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;aACtD;SACF;QAED,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YACzC,GAAG,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;SACnC;QAED,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,EAAE;YACvC,GAAG,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;SAC/B;QAED,IAAI,IAAI,CAAC,SAAS,CAAC,kBAAM,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE;YACtD,IAAI,iBAAiB,GAAG,CAAC,IAAI,GAAG,CAAC,SAAS,EAAE;gBAC1C,0FAA0F;gBAC1F,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC;aACpB;iBAAM;gBACL,GAAG,GAAG,2BAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;aAC9C;SACF;QAED,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAClD,CAAC;CACF;AA5GD,4CA4GC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/common_functions.js b/node_modules/mongodb/lib/operations/common_functions.js new file mode 100644 index 0000000..ac8c6b0 --- /dev/null +++ b/node_modules/mongodb/lib/operations/common_functions.js @@ -0,0 +1,64 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.prepareDocs = exports.indexInformation = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +function indexInformation(db, name, _optionsOrCallback, _callback) { + let options = _optionsOrCallback; + let callback = _callback; + if ('function' === typeof _optionsOrCallback) { + callback = _optionsOrCallback; + options = {}; + } + // If we specified full information + const full = options.full == null ? false : options.full; + // Did the user destroy the topology + if (utils_1.getTopology(db).isDestroyed()) + return callback(new error_1.MongoTopologyClosedError()); + // Process all the results from the index command and collection + function processResults(indexes) { + // Contains all the information + const info = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (const name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + return info; + } + // Get the list of indexes of the specified collection + db.collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) + return callback(err); + if (!Array.isArray(indexes)) + return callback(undefined, []); + if (full) + return callback(undefined, indexes); + callback(undefined, processResults(indexes)); + }); +} +exports.indexInformation = indexInformation; +function prepareDocs(coll, docs, options) { + var _a; + const forceServerObjectId = typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : (_a = coll.s.db.options) === null || _a === void 0 ? void 0 : _a.forceServerObjectId; + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docs; + } + return docs.map(doc => { + if (doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); + } + return doc; + }); +} +exports.prepareDocs = prepareDocs; +//# sourceMappingURL=common_functions.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/common_functions.js.map b/node_modules/mongodb/lib/operations/common_functions.js.map new file mode 100644 index 0000000..fa91975 --- /dev/null +++ b/node_modules/mongodb/lib/operations/common_functions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common_functions.js","sourceRoot":"","sources":["../../src/operations/common_functions.ts"],"names":[],"mappings":";;;AAAA,oCAAoD;AACpD,oCAAiD;AA0BjD,SAAgB,gBAAgB,CAC9B,EAAM,EACN,IAAY,EACZ,kBAAsD,EACtD,SAAoB;IAEpB,IAAI,OAAO,GAAG,kBAA6C,CAAC;IAC5D,IAAI,QAAQ,GAAG,SAAqB,CAAC;IACrC,IAAI,UAAU,KAAK,OAAO,kBAAk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,IAAI,IAAI;YAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC9C,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;IAC/C,CAAC,CAAC,CAAC;AACP,CAAC;AA3CD,4CA2CC;AAED,SAAgB,WAAW,CACzB,IAAgB,EAChB,IAAgB,EAChB,OAA0C;;IAE1C,MAAM,mBAAmB,GACvB,OAAO,OAAO,CAAC,mBAAmB,KAAK,SAAS;QAC9C,CAAC,CAAC,OAAO,CAAC,mBAAmB;QAC7B,CAAC,CAAC,MAAA,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,0CAAE,mBAAmB,CAAC;IAE7C,yDAAyD;IACzD,IAAI,mBAAmB,KAAK,IAAI,EAAE;QAChC,OAAO,IAAI,CAAC;KACb;IAED,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;QACpB,IAAI,GAAG,CAAC,GAAG,IAAI,IAAI,EAAE;YACnB,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;SACvC;QAED,OAAO,GAAG,CAAC;IACb,CAAC,CAAC,CAAC;AACL,CAAC;AAtBD,kCAsBC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/connect.js b/node_modules/mongodb/lib/operations/connect.js new file mode 100644 index 0000000..71c6957 --- /dev/null +++ b/node_modules/mongodb/lib/operations/connect.js @@ -0,0 +1,93 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.connect = exports.MONGO_CLIENT_EVENTS = void 0; +const error_1 = require("../error"); +const topology_1 = require("../sdam/topology"); +const connection_string_1 = require("../connection_string"); +const connection_pool_1 = require("../cmap/connection_pool"); +const connection_1 = require("../cmap/connection"); +const server_1 = require("../sdam/server"); +/** @public */ +exports.MONGO_CLIENT_EVENTS = [ + ...connection_pool_1.CMAP_EVENTS, + ...connection_1.APM_EVENTS, + ...topology_1.TOPOLOGY_EVENTS, + ...server_1.HEARTBEAT_EVENTS +]; +function connect(mongoClient, options, callback) { + if (!callback) { + throw new error_1.MongoInvalidArgumentError('Callback function must be provided'); + } + // If a connection already been established, we can terminate early + if (mongoClient.topology && mongoClient.topology.isConnected()) { + return callback(undefined, mongoClient); + } + const logger = mongoClient.logger; + const connectCallback = err => { + const warningMessage = 'seed list contains no mongos proxies, replicaset connections requires ' + + 'the parameter replicaSet to be supplied in the URI or options object, ' + + 'mongodb://server:port/db?replicaSet=name'; + if (err && err.message === 'no mongos proxies found in seed list') { + if (logger.isWarn()) { + logger.warn(warningMessage); + } + // Return a more specific error message for MongoClient.connect + // TODO(NODE-3483) + return callback(new error_1.MongoRuntimeError(warningMessage)); + } + callback(err, mongoClient); + }; + if (typeof options.srvHost === 'string') { + return connection_string_1.resolveSRVRecord(options, (err, hosts) => { + if (err || !hosts) + return callback(err); + for (const [index, host] of hosts.entries()) { + options.hosts[index] = host; + } + return createTopology(mongoClient, options, connectCallback); + }); + } + return createTopology(mongoClient, options, connectCallback); +} +exports.connect = connect; +function createTopology(mongoClient, options, callback) { + // Create the topology + const topology = new topology_1.Topology(options.hosts, options); + // Events can be emitted before initialization is complete so we have to + // save the reference to the topology on the client ASAP if the event handlers need to access it + mongoClient.topology = topology; + topology.once(topology_1.Topology.OPEN, () => mongoClient.emit('open', mongoClient)); + for (const event of exports.MONGO_CLIENT_EVENTS) { + topology.on(event, (...args) => mongoClient.emit(event, ...args)); + } + // initialize CSFLE if requested + if (mongoClient.autoEncrypter) { + mongoClient.autoEncrypter.init(err => { + if (err) { + return callback(err); + } + topology.connect(options, err => { + if (err) { + topology.close({ force: true }); + return callback(err); + } + options.encrypter.connectInternalClient(error => { + if (error) + return callback(error); + callback(undefined, topology); + }); + }); + }); + return; + } + // otherwise connect normally + topology.connect(options, err => { + if (err) { + topology.close({ force: true }); + return callback(err); + } + callback(undefined, topology); + return; + }); +} +//# sourceMappingURL=connect.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/connect.js.map b/node_modules/mongodb/lib/operations/connect.js.map new file mode 100644 index 0000000..1f127be --- /dev/null +++ b/node_modules/mongodb/lib/operations/connect.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connect.js","sourceRoot":"","sources":["../../src/operations/connect.ts"],"names":[],"mappings":";;;AAAA,oCAAwE;AACxE,+CAA6D;AAC7D,4DAAwD;AAGxD,6DAAsD;AACtD,mDAAgD;AAChD,2CAAkD;AAElD,cAAc;AACD,QAAA,mBAAmB,GAAG;IACjC,GAAG,6BAAW;IACd,GAAG,uBAAU;IACb,GAAG,0BAAe;IAClB,GAAG,yBAAgB;CACX,CAAC;AAEX,SAAgB,OAAO,CACrB,WAAwB,EACxB,OAAqB,EACrB,QAA+B;IAE/B,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,iCAAyB,CAAC,oCAAoC,CAAC,CAAC;KAC3E;IAED,mEAAmE;IACnE,IAAI,WAAW,CAAC,QAAQ,IAAI,WAAW,CAAC,QAAQ,CAAC,WAAW,EAAE,EAAE;QAC9D,OAAO,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;KACzC;IAED,MAAM,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC;IAClC,MAAM,eAAe,GAAa,GAAG,CAAC,EAAE;QACtC,MAAM,cAAc,GAClB,wEAAwE;YACxE,wEAAwE;YACxE,0CAA0C,CAAC;QAC7C,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,KAAK,sCAAsC,EAAE;YACjE,IAAI,MAAM,CAAC,MAAM,EAAE,EAAE;gBACnB,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;aAC7B;YAED,+DAA+D;YAC/D,kBAAkB;YAClB,OAAO,QAAQ,CAAC,IAAI,yBAAiB,CAAC,cAAc,CAAC,CAAC,CAAC;SACxD;QAED,QAAQ,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;IAC7B,CAAC,CAAC;IAEF,IA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IAAI,GAAG,EAAE;gBACP,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;aACtB;YAED,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE;gBAC9B,IAAI,GAAG,EAAE;oBACP,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChC,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;iBACtB;gBAED,OAAO,CAAC,SAAS,CAAC,qBAAqB,CAAC,KAAK,CAAC,EAAE;oBAC9C,IAAI,KAAK;wBAAE,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;oBAElC,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;gBAChC,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,OAAO;KACR;IAED,6BAA6B;IAC7B,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE;QAC9B,IAAI,GAAG,EAAE;YACP,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YAChC,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;SACtB;QAED,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QAC9B,OAAO;IACT,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/count.js b/node_modules/mongodb/lib/operations/count.js new file mode 100644 index 0000000..ba2a5b4 --- /dev/null +++ b/node_modules/mongodb/lib/operations/count.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CountOperation = void 0; +const operation_1 = require("./operation"); +const command_1 = require("./command"); +/** @internal */ +class CountOperation extends command_1.CommandOperation { + constructor(namespace, filter, options) { + super({ s: { namespace: namespace } }, options); + this.options = options; + this.collectionName = namespace.collection; + this.query = filter; + } + execute(server, session, callback) { + const options = this.options; + const cmd = { + count: this.collectionName, + query: this.query + }; + if (typeof options.limit === 'number') { + cmd.limit = options.limit; + } + if (typeof options.skip === 'number') { + cmd.skip = options.skip; + } + if (options.hint != null) { + cmd.hint = options.hint; + } + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + super.executeCommand(server, session, cmd, (err, result) => { + callback(err, result ? result.n : 0); + }); + } +} +exports.CountOperation = CountOperation; +operation_1.defineAspects(CountOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); +//# sourceMappingURL=count.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/count.js.map b/node_modules/mongodb/lib/operations/count.js.map new file mode 100644 index 0000000..6da1b43 --- /dev/null +++ b/node_modules/mongodb/lib/operations/count.js.map @@ -0,0 +1 @@ +{"version":3,"file":"count.js","sourceRoot":"","sources":["../../src/operations/count.ts"],"names":[],"mappings":";;;AAAA,2CAAoD;AACpD,uCAAsE;AAmBtE,gBAAgB;AAChB,MAAa,cAAe,SAAQ,0BAAwB;IAK1D,YAAY,SAA2B,EAAE,MAAgB,EAAE,OAAqB;QAC9E,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,EAA2B,EAAE,OAAO,CAAC,CAAC;QAEzE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC,UAAU,CAAC;QAC3C,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC;IACtB,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA0B;QACxE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC7B,MAAM,GAAG,GAAa;YACpB,KAAK,EAAE,IAAI,CAAC,cAAc;YAC1B,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC;QAEF,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;YACrC,GAAG,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;SAC3B;QAED,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;YACpC,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;SACzB;QAED,IAAI,OAAO,CAAC,IAAI,IAAI,IAAI,EAAE;YACxB,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;SACzB;QAED,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YACzC,GAAG,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;SACnC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YACzD,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACvC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAxCD,wCAwCC;AAED,yBAAa,CAAC,cAAc,EAAE,CAAC,kBAAM,CAAC,cAAc,EAAE,kBAAM,CAAC,SAAS,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/count_documents.js b/node_modules/mongodb/lib/operations/count_documents.js new file mode 100644 index 0000000..562c9c0 --- /dev/null +++ b/node_modules/mongodb/lib/operations/count_documents.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CountDocumentsOperation = void 0; +const aggregate_1 = require("./aggregate"); +/** @internal */ +class CountDocumentsOperation extends aggregate_1.AggregateOperation { + constructor(collection, query, options) { + const pipeline = []; + pipeline.push({ $match: query }); + if (typeof options.skip === 'number') { + pipeline.push({ $skip: options.skip }); + } + if (typeof options.limit === 'number') { + pipeline.push({ $limit: options.limit }); + } + pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); + super(collection.s.namespace, pipeline, options); + } + execute(server, session, callback) { + super.execute(server, session, (err, result) => { + if (err || !result) { + callback(err); + return; + } + // NOTE: We're avoiding creating a cursor here to reduce the callstack. + const response = result; + if (response.cursor == null || response.cursor.firstBatch == null) { + callback(undefined, 0); + return; + } + const docs = response.cursor.firstBatch; + callback(undefined, docs.length ? docs[0].n : 0); + }); + } +} +exports.CountDocumentsOperation = CountDocumentsOperation; +//# sourceMappingURL=count_documents.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/count_documents.js.map b/node_modules/mongodb/lib/operations/count_documents.js.map new file mode 100644 index 0000000..8faec0e --- /dev/null +++ b/node_modules/mongodb/lib/operations/count_documents.js.map @@ -0,0 +1 @@ +{"version":3,"file":"count_documents.js","sourceRoot":"","sources":["../../src/operations/count_documents.ts"],"names":[],"mappings":";;;AAAA,2CAAmE;AAenE,gBAAgB;AAChB,MAAa,uBAAwB,SAAQ,8BAA0B;IACrE,YAAY,UAAsB,EAAE,KAAe,EAAE,OAA8B;QACjF,MAAM,QAAQ,GAAG,EAAE,CAAC;QACpB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;QAEjC,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;YACpC,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;SACxC;QAED,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;YACrC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;SAC1C;QAED,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QAEtD,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IACnD,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA0B;QACxE,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YAC7C,IAAI,GAAG,IAAI,CAAC,MAAM,EAAE;gBAClB,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACd,OAAO;aACR;YAED,uEAAuE;YACvE,MAAM,QAAQ,GAAG,MAA6B,CAAC;YAC/C,IAAI,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,CAAC,UAAU,IAAI,IAAI,EAAE;gBACjE,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;gBACvB,OAAO;aACR;YAED,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC;YACxC,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACnD,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AApCD,0DAoCC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/create_collection.js b/node_modules/mongodb/lib/operations/create_collection.js new file mode 100644 index 0000000..3841a5a --- /dev/null +++ b/node_modules/mongodb/lib/operations/create_collection.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CreateCollectionOperation = void 0; +const command_1 = require("./command"); +const operation_1 = require("./operation"); +const collection_1 = require("../collection"); +const ILLEGAL_COMMAND_FIELDS = new Set([ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'pkFactory', + 'raw', + 'readPreference', + 'session', + 'readConcern', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined' +]); +/** @internal */ +class CreateCollectionOperation extends command_1.CommandOperation { + constructor(db, name, options = {}) { + super(db, options); + this.options = options; + this.db = db; + this.name = name; + } + execute(server, session, callback) { + const db = this.db; + const name = this.name; + const options = this.options; + const done = err => { + if (err) { + return callback(err); + } + callback(undefined, new collection_1.Collection(db, name, options)); + }; + const cmd = { create: name }; + for (const n in options) { + if (options[n] != null && + typeof options[n] !== 'function' && + !ILLEGAL_COMMAND_FIELDS.has(n)) { + cmd[n] = options[n]; + } + } + // otherwise just execute the command + super.executeCommand(server, session, cmd, done); + } +} +exports.CreateCollectionOperation = CreateCollectionOperation; +operation_1.defineAspects(CreateCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=create_collection.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/create_collection.js.map b/node_modules/mongodb/lib/operations/create_collection.js.map new file mode 100644 index 0000000..15f50e0 --- /dev/null +++ b/node_modules/mongodb/lib/operations/create_collection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"create_collection.js","sourceRoot":"","sources":["../../src/operations/create_collection.ts"],"names":[],"mappings":";;;AAAA,uCAAsE;AACtE,2CAAoD;AACpD,8CAA2C;AAQ3C,MAAM,sBAAsB,GAAG,IAAI,GAAG,CAAC;IACrC,GAAG;IACH,UAAU;IACV,GAAG;IACH,OAAO;IACP,aAAa;IACb,WAAW;IACX,KAAK;IACL,gBAAgB;IAChB,SAAS;IACT,aAAa;IACb,cAAc;IACd,KAAK;IACL,aAAa;IACb,cAAc;IACd,eAAe;IACf,gBAAgB;IAChB,YAAY;IACZ,oBAAoB;IACpB,iBAAiB;CAClB,CAAC,CAAC;AAgDH,gBAAgB;AAChB,MAAa,yBAA0B,SAAQ,0BAA4B;IAKzE,YAAY,EAAM,EAAE,IAAY,EAAE,UAAmC,EAAE;QACrE,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAEnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA8B;QAC5E,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;QACnB,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE7B,MAAM,IAAI,GAAa,GAAG,CAAC,EAAE;YAC3B,IAAI,GAAG,EAAE;gBACP,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;aACtB;YAED,QAAQ,CAAC,SAAS,EAAE,IAAI,uBAAU,CAAC,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;QACzD,CAAC,CAAC;QAEF,MAAM,GAAG,GAAa,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QACvC,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE;YACvB,IACG,OAAe,CAAC,CAAC,CAAC,IAAI,IAAI;gBAC3B,OAAQ,OAAe,CAAC,CAAC,CAAC,KAAK,UAAU;gBACzC,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC,CAAC,EAC9B;gBACA,GAAG,CAAC,CAAC,CAAC,GAAI,OAAe,CAAC,CAAC,CAAC,CAAC;aAC9B;SACF;QAED,qCAAqC;QACrC,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IACnD,CAAC;CACF;AAxCD,8DAwCC;AAED,yBAAa,CAAC,yBAAyB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/delete.js b/node_modules/mongodb/lib/operations/delete.js new file mode 100644 index 0000000..c43ba3f --- /dev/null +++ b/node_modules/mongodb/lib/operations/delete.js @@ -0,0 +1,133 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.makeDeleteStatement = exports.DeleteManyOperation = exports.DeleteOneOperation = exports.DeleteOperation = void 0; +const operation_1 = require("./operation"); +const command_1 = require("./command"); +const utils_1 = require("../utils"); +const error_1 = require("../error"); +/** @internal */ +class DeleteOperation extends command_1.CommandOperation { + constructor(ns, statements, options) { + super(undefined, options); + this.options = options; + this.ns = ns; + this.statements = statements; + } + get canRetryWrite() { + if (super.canRetryWrite === false) { + return false; + } + return this.statements.every(op => (op.limit != null ? op.limit > 0 : true)); + } + execute(server, session, callback) { + var _a; + const options = (_a = this.options) !== null && _a !== void 0 ? _a : {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + delete: this.ns.collection, + deletes: this.statements, + ordered + }; + if (options.let) { + command.let = options.let; + } + if (options.explain != null && utils_1.maxWireVersion(server) < 3) { + return callback + ? callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on delete`)) + : undefined; + } + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite || utils_1.maxWireVersion(server) < 5) { + if (this.statements.find((o) => o.hint)) { + callback(new error_1.MongoCompatibilityError(`Servers < 3.4 do not support hint on delete`)); + return; + } + } + const statementWithCollation = this.statements.find(statement => !!statement.collation); + if (statementWithCollation && utils_1.collationNotSupported(server, statementWithCollation)) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support collation`)); + return; + } + super.executeCommand(server, session, command, callback); + } +} +exports.DeleteOperation = DeleteOperation; +class DeleteOneOperation extends DeleteOperation { + constructor(collection, filter, options) { + super(collection.s.namespace, [makeDeleteStatement(filter, { ...options, limit: 1 })], options); + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || res == null) + return callback(err); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + if (this.explain) + return callback(undefined, res); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + deletedCount: res.n + }); + }); + } +} +exports.DeleteOneOperation = DeleteOneOperation; +class DeleteManyOperation extends DeleteOperation { + constructor(collection, filter, options) { + super(collection.s.namespace, [makeDeleteStatement(filter, options)], options); + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || res == null) + return callback(err); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + if (this.explain) + return callback(undefined, res); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + deletedCount: res.n + }); + }); + } +} +exports.DeleteManyOperation = DeleteManyOperation; +function makeDeleteStatement(filter, options) { + const op = { + q: filter, + limit: typeof options.limit === 'number' ? options.limit : 0 + }; + if (options.single === true) { + op.limit = 1; + } + if (options.collation) { + op.collation = options.collation; + } + if (options.hint) { + op.hint = options.hint; + } + if (options.comment) { + op.comment = options.comment; + } + return op; +} +exports.makeDeleteStatement = makeDeleteStatement; +operation_1.defineAspects(DeleteOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +operation_1.defineAspects(DeleteOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +operation_1.defineAspects(DeleteManyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +//# sourceMappingURL=delete.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/delete.js.map b/node_modules/mongodb/lib/operations/delete.js.map new file mode 100644 index 0000000..ee3b688 --- /dev/null +++ b/node_modules/mongodb/lib/operations/delete.js.map @@ -0,0 +1 @@ +{"version":3,"file":"delete.js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Aa,CAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC3E,yBAAa,CAAC,kBAAkB,EAAE;IAChC,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC;AACH,yBAAa,CAAC,mBAAmB,EAAE;IACjC,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/distinct.js b/node_modules/mongodb/lib/operations/distinct.js new file mode 100644 index 0000000..cfed938 --- /dev/null +++ b/node_modules/mongodb/lib/operations/distinct.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DistinctOperation = void 0; +const operation_1 = require("./operation"); +const command_1 = require("./command"); +const utils_1 = require("../utils"); +const error_1 = require("../error"); +/** + * Return a list of distinct values for the given key across a collection. + * @internal + */ +class DistinctOperation extends command_1.CommandOperation { + /** + * Construct a Distinct operation. + * + * @param collection - Collection instance. + * @param key - Field of the document to find distinct values for. + * @param query - The query for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings. See Collection.prototype.distinct for a list of options. + */ + constructor(collection, key, query, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collection = collection; + this.key = key; + this.query = query; + } + execute(server, session, callback) { + const coll = this.collection; + const key = this.key; + const query = this.query; + const options = this.options; + // Distinct command + const cmd = { + distinct: coll.collectionName, + key: key, + query: query + }; + // Add maxTimeMS if defined + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + // Do we have a readConcern specified + utils_1.decorateWithReadConcern(cmd, coll, options); + // Have we specified collation + try { + utils_1.decorateWithCollation(cmd, coll, options); + } + catch (err) { + return callback(err); + } + if (this.explain && utils_1.maxWireVersion(server) < 4) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on distinct`)); + return; + } + super.executeCommand(server, session, cmd, (err, result) => { + if (err) { + callback(err); + return; + } + callback(undefined, this.explain ? result : result.values); + }); + } +} +exports.DistinctOperation = DistinctOperation; +operation_1.defineAspects(DistinctOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.EXPLAINABLE]); +//# sourceMappingURL=distinct.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/distinct.js.map b/node_modules/mongodb/lib/operations/distinct.js.map new file mode 100644 index 0000000..ba4e678 --- /dev/null +++ b/node_modules/mongodb/lib/operations/distinct.js.map @@ -0,0 +1 @@ +{"version":3,"file":"distinct.js","sourceRoot":"","sources":["../../src/operations/distinct.ts"],"names":[],"mappings":";;;AAAA,2CAAoD;AACpD,uCAAsE;AACtE,oCAAoG;AAIpG,oCAAmD;AAMnD;;;GAGG;AACH,MAAa,iBAAkB,SAAQ,0BAAuB;IAQ5D;;;;;;;OAOG;IACH,YAAY,UAAsB,EAAE,GAAW,EAAE,KAAe,EAAE,OAAyB;QACzF,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAE3B,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAAyB;QACvE,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAC7B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QACrB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;QACzB,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE7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lib/operations/drop.js new file mode 100644 index 0000000..7bda797 --- /dev/null +++ b/node_modules/mongodb/lib/operations/drop.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DropDatabaseOperation = exports.DropCollectionOperation = void 0; +const operation_1 = require("./operation"); +const command_1 = require("./command"); +/** @internal */ +class DropCollectionOperation extends command_1.CommandOperation { + constructor(db, name, options) { + super(db, options); + this.options = options; + this.name = name; + } + execute(server, session, callback) { + super.executeCommand(server, session, { drop: this.name }, (err, result) => { + if (err) + return callback(err); + if (result.ok) + return callback(undefined, true); + callback(undefined, false); + }); + } +} +exports.DropCollectionOperation = DropCollectionOperation; +/** @internal */ +class DropDatabaseOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + execute(server, session, callback) { + super.executeCommand(server, session, { dropDatabase: 1 }, (err, result) => { + if (err) + return callback(err); + if (result.ok) + return callback(undefined, true); + callback(undefined, false); + }); + } +} +exports.DropDatabaseOperation = DropDatabaseOperation; +operation_1.defineAspects(DropCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]); +operation_1.defineAspects(DropDatabaseOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=drop.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/drop.js.map b/node_modules/mongodb/lib/operations/drop.js.map new file mode 100644 index 0000000..1517cad --- /dev/null +++ b/node_modules/mongodb/lib/operations/drop.js.map @@ -0,0 +1 @@ +{"version":3,"file":"drop.js","sourceRoot":"","sources":["../../src/operations/drop.ts"],"names":[],"mappings":";;;AAAA,2CAAoD;AACpD,uCAAsE;AAStE,gBAAgB;AAChB,MAAa,uBAAwB,SAAQ,0BAAyB;IAIpE,YAAY,EAAM,EAAE,IAAY,EAAE,OAA8B;QAC9D,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,I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AC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/estimated_document_count.js b/node_modules/mongodb/lib/operations/estimated_document_count.js new file mode 100644 index 0000000..4366d75 --- /dev/null +++ b/node_modules/mongodb/lib/operations/estimated_document_count.js @@ -0,0 +1,52 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EstimatedDocumentCountOperation = void 0; +const operation_1 = require("./operation"); +const command_1 = require("./command"); +const utils_1 = require("../utils"); +/** @internal */ +class EstimatedDocumentCountOperation extends command_1.CommandOperation { + constructor(collection, options = {}) { + super(collection, options); + this.options = options; + this.collectionName = collection.collectionName; + } + execute(server, session, callback) { + if (utils_1.maxWireVersion(server) < 12) { + return this.executeLegacy(server, session, callback); + } + const pipeline = [{ $collStats: { count: {} } }, { $group: { _id: 1, n: { $sum: '$count' } } }]; + const cmd = { aggregate: this.collectionName, pipeline, cursor: {} }; + if (typeof this.options.maxTimeMS === 'number') { + cmd.maxTimeMS = this.options.maxTimeMS; + } + super.executeCommand(server, session, cmd, (err, response) => { + var _a, _b; + if (err && err.code !== 26) { + callback(err); + return; + } + callback(undefined, ((_b = (_a = response === null || response === void 0 ? void 0 : response.cursor) === null || _a === void 0 ? void 0 : _a.firstBatch[0]) === null || _b === void 0 ? void 0 : _b.n) || 0); + }); + } + executeLegacy(server, session, callback) { + const cmd = { count: this.collectionName }; + if (typeof this.options.maxTimeMS === 'number') { + cmd.maxTimeMS = this.options.maxTimeMS; + } + super.executeCommand(server, session, cmd, (err, response) => { + if (err) { + callback(err); + return; + } + callback(undefined, response.n || 0); + }); + } +} +exports.EstimatedDocumentCountOperation = EstimatedDocumentCountOperation; +operation_1.defineAspects(EstimatedDocumentCountOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=estimated_document_count.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/estimated_document_count.js.map b/node_modules/mongodb/lib/operations/estimated_document_count.js.map new file mode 100644 index 0000000..f5f92a7 --- /dev/null +++ b/node_modules/mongodb/lib/operations/estimated_document_count.js.map @@ -0,0 +1 @@ +{"version":3,"file":"estimated_document_count.js","sourceRoot":"","sources":["../../src/operations/estimated_document_count.ts"],"names":[],"mappings":";;;AAAA,2CAAoD;AACpD,uCAAsE;AACtE,oCAAoD;AAiBpD,gBAAgB;AAChB,MAAa,+BAAgC,SAAQ,0BAAwB;IAI3E,YAAY,UAAsB,EAAE,UAAyC,EAAE;QAC7E,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,cAAc,CAAC;IAClD,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA0B;QACxE,IAAI,sBAAc,CAAC,MAAM,CAAC,GAAG,EAAE,EAAE;YAC/B,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;SACtD;QACD,MAAM,QAAQ,GAAG,CAAC,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC;QAEhG,MAAM,GAAG,GAAa,EAAE,SAAS,EAAE,IAAI,CAAC,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;QAE/E,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YAC9C,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;SACxC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE;;YAC3D,IAAI,GAAG,IAAK,GAAwB,CAAC,IAAI,KAAK,EAAE,EAAE;gBAChD,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACd,OAAO;aACR;YAED,QAAQ,CAAC,SAAS,EAAE,CAAA,MAAA,MAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,MAAM,0CAAE,UAAU,CAAC,CAAC,CAAC,0CAAE,CAAC,KAAI,CAAC,CAAC,CAAC;QAC/D,CAAC,CAAC,CAAC;IACL,CAAC;IAED,aAAa,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA0B;QAC9E,MAAM,GAAG,GAAa,EAAE,KAAK,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC;QAErD,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YAC9C,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;SACxC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE;YAC3D,IAAI,GAAG,EAAE;gBACP,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACd,OAAO;aACR;YAED,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;QACvC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAhDD,0EAgDC;AAED,yBAAa,CAAC,+BAA+B,EAAE;IAC7C,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/eval.js b/node_modules/mongodb/lib/operations/eval.js new file mode 100644 index 0000000..83a3648 --- /dev/null +++ b/node_modules/mongodb/lib/operations/eval.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EvalOperation = void 0; +const command_1 = require("./command"); +const bson_1 = require("../bson"); +const read_preference_1 = require("../read_preference"); +const error_1 = require("../error"); +/** @internal */ +class EvalOperation extends command_1.CommandOperation { + constructor(db, code, parameters, options) { + super(db, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.code = code; + this.parameters = parameters; + // force primary read preference + Object.defineProperty(this, 'readPreference', { + value: read_preference_1.ReadPreference.primary, + configurable: false, + writable: false + }); + } + execute(server, session, callback) { + let finalCode = this.code; + let finalParameters = []; + // If not a code object translate to one + if (!(finalCode && finalCode._bsontype === 'Code')) { + finalCode = new bson_1.Code(finalCode); + } + // Ensure the parameters are correct + if (this.parameters != null && typeof this.parameters !== 'function') { + finalParameters = Array.isArray(this.parameters) ? this.parameters : [this.parameters]; + } + // Create execution selector + const cmd = { $eval: finalCode, args: finalParameters }; + // Check if the nolock parameter is passed in + if (this.options.nolock) { + cmd.nolock = this.options.nolock; + } + // Execute the command + super.executeCommand(server, session, cmd, (err, result) => { + if (err) + return callback(err); + if (result && result.ok === 1) { + return callback(undefined, result.retval); + } + if (result) { + callback(new error_1.MongoServerError({ message: `eval failed: ${result.errmsg}` })); + return; + } + callback(err, result); + }); + } +} +exports.EvalOperation = EvalOperation; +//# sourceMappingURL=eval.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/eval.js.map b/node_modules/mongodb/lib/operations/eval.js.map new file mode 100644 index 0000000..bbd955d --- /dev/null +++ b/node_modules/mongodb/lib/operations/eval.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eval.js","sourceRoot":"","sources":["../../src/operations/eval.ts"],"names":[],"mappings":";;;AAAA,uCAAsE;AACtE,kCAAyC;AACzC,wDAAoD;AACpD,oCAA4C;AAY5C,gBAAgB;AAChB,MAAa,aAAc,SAAQ,0BAA0B;IAK3D,YACE,EAAmB,EACnB,IAAU,EACV,UAAkC,EAClC,OAAqB;QAErB,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAEnB,IAAI,CAAC,OAAO,GAAG,OAAO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,IAAI,GAAG;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9B,IAAI,MAAM,IAAI,MAAM,CAAC,EAAE,KAAK,CAAC,EAAE;gBAC7B,OAAO,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;aAC3C;YAED,IAAI,MAAM,EAAE;gBACV,QAAQ,CAAC,IAAI,wBAAgB,CAAC,EAAE,OAAO,EAAE,gBAAgB,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC;gBAC7E,OAAO;aACR;YAED,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QACxB,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA7DD,sCA6DC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/execute_operation.js b/node_modules/mongodb/lib/operations/execute_operation.js new file mode 100644 index 0000000..b6073e4 --- /dev/null +++ b/node_modules/mongodb/lib/operations/execute_operation.js @@ -0,0 +1,162 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.executeOperation = void 0; +const read_preference_1 = require("../read_preference"); +const error_1 = require("../error"); +const operation_1 = require("./operation"); +const utils_1 = require("../utils"); +const utils_2 = require("../utils"); +const MMAPv1_RETRY_WRITES_ERROR_CODE = error_1.MONGODB_ERROR_CODES.IllegalOperation; +const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; +function executeOperation(topology, operation, callback) { + if (!(operation instanceof operation_1.AbstractOperation)) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('This method requires a valid operation instance'); + } + return utils_1.maybePromise(callback, cb => { + if (topology.shouldCheckForSessionSupport()) { + return topology.selectServer(read_preference_1.ReadPreference.primaryPreferred, err => { + if (err) + return cb(err); + executeOperation(topology, operation, cb); + }); + } + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session = operation.session; + let owner; + if (topology.hasSessionSupport()) { + if (session == null) { + owner = Symbol(); + session = topology.startSession({ owner, explicit: false }); + } + else if (session.hasEnded) { + return cb(new error_1.MongoExpiredSessionError('Use of expired sessions is not permitted')); + } + else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + return cb(new error_1.MongoCompatibilityError('Snapshot reads require MongoDB 5.0 or later')); + } + } + else if (session) { + // If the user passed an explicit session and we are still, after server selection, + // trying to run against a topology that doesn't support sessions we error out. + return cb(new error_1.MongoCompatibilityError('Current topology does not support sessions')); + } + try { + executeWithServerSelection(topology, session, operation, (err, result) => { + if (session && session.owner && session.owner === owner) { + return session.endSession(err2 => cb(err2 || err, result)); + } + cb(err, result); + }); + } + catch (e) { + if (session && session.owner && session.owner === owner) { + session.endSession(); + } + throw e; + } + }); +} +exports.executeOperation = executeOperation; +function supportsRetryableReads(server) { + return utils_1.maxWireVersion(server) >= 6; +} +function executeWithServerSelection(topology, session, operation, callback) { + const readPreference = operation.readPreference || read_preference_1.ReadPreference.primary; + const inTransaction = session && session.inTransaction(); + if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary)) { + callback(new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`)); + return; + } + if (session && + session.isPinned && + session.transaction.isCommitted && + !operation.bypassPinningCheck) { + session.unpin(); + } + const serverSelectionOptions = { session }; + function callbackWithRetry(err, result) { + if (err == null) { + return callback(undefined, result); + } + const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); + const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION); + const itShouldRetryWrite = shouldRetryWrite(err); + if ((hasReadAspect && !error_1.isRetryableError(err)) || (hasWriteAspect && !itShouldRetryWrite)) { + return callback(err); + } + if (hasWriteAspect && + itShouldRetryWrite && + err.code === MMAPv1_RETRY_WRITES_ERROR_CODE && + err.errmsg.match(/Transaction numbers/)) { + callback(new error_1.MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError: err + })); + return; + } + // select a new server, and attempt to retry the operation + topology.selectServer(readPreference, serverSelectionOptions, (e, server) => { + if (e || + (operation.hasAspect(operation_1.Aspect.READ_OPERATION) && !supportsRetryableReads(server)) || + (operation.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !utils_2.supportsRetryableWrites(server))) { + callback(e); + return; + } + // If we have a cursor and the initial command fails with a network error, + // we can retry it on another connection. So we need to check it back in, clear the + // pool for the service id, and retry again. + if (err && + err instanceof error_1.MongoNetworkError && + server.loadBalanced && + session && + session.isPinned && + !session.inTransaction() && + operation.hasAspect(operation_1.Aspect.CURSOR_CREATING)) { + session.unpin({ force: true, forceClear: true }); + } + operation.execute(server, session, callback); + }); + } + if (readPreference && + !readPreference.equals(read_preference_1.ReadPreference.primary) && + session && + session.inTransaction()) { + callback(new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`)); + return; + } + // select a server, and execute the operation against it + topology.selectServer(readPreference, serverSelectionOptions, (err, server) => { + if (err) { + callback(err); + return; + } + if (session && operation.hasAspect(operation_1.Aspect.RETRYABLE)) { + const willRetryRead = topology.s.options.retryReads !== false && + !inTransaction && + supportsRetryableReads(server) && + operation.canRetryRead; + const willRetryWrite = topology.s.options.retryWrites === true && + !inTransaction && + utils_2.supportsRetryableWrites(server) && + operation.canRetryWrite; + const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); + const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION); + if ((hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite)) { + if (hasWriteAspect && willRetryWrite) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + operation.execute(server, session, callbackWithRetry); + return; + } + } + operation.execute(server, session, callback); + }); +} +function shouldRetryWrite(err) { + return err instanceof error_1.MongoError && err.hasErrorLabel('RetryableWriteError'); +} +//# sourceMappingURL=execute_operation.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/execute_operation.js.map b/node_modules/mongodb/lib/operations/execute_operation.js.map new file mode 100644 index 0000000..8ff11bb --- /dev/null +++ b/node_modules/mongodb/lib/operations/execute_operation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"execute_operation.js","sourceRoot":"","sources":["../../src/operations/execute_operation.ts"],"names":[],"mappings":";;;AAAA,wDAAoD;AACpD,oCAUkB;AAClB,2CAAwD;AACxD,oCAAkE;AAKlE,oCAAmD;AAEnD,MAAM,8BAA8B,GAAG,2BAAmB,CAAC,gBAAgB,CAAC;AAC5E,MAAM,iCAAiC,GACrC,oHAAoH,CAAC;AA2CvH,SAAgB,gBAAgB,CAG9B,QAAkB,EAAE,SAAY,EAAE,QAA4B;IAC9D,IAAI,CAAC,CAAC,SAAS,YAAY,6BAAiB,CAAC,EAAE;QAC7C,kBAAkB;QAClB,MAAM,IAAI,yBAAiB,CAAC,iDAAiD,CAAC,CAAC;KAChF;IAED,OAAO,oBAAY,CAAC,QAAQ,EAAE,EAAE,CAAC,EAAE;QACjC,IAAI,QAAQ,CAAC,4BAA4B,EAAE,EAAE;YAC3C,OAAO,QAAQ,CAAC,YAAY,CAAC,gCAAc,CAAC,gBAAgB,EAAE,GAAG,CAAC,EAAE;gBAClE,IAAI,GAAG;oBAAE,OAAO,EAAE,CAAC,GAAG,CAAC,CAAC;gBAExB,gBAAgB,CAAa,QAAQ,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;YACxD,CAAC,CAAC,CAAC;SACJ;QAED,sFAAsF;QACtF,mDAAmD;QACnD,IAAI,OAAO,GAA8B,SAAS,CAAC,OAAO,CAAC;QAC3D,IAAI,KAAyB,CAAC;QAC9B,IAAI,QAAQ,CAAC,iBAAiB,EAAE,EAAE;YAChC,IAAI,OAAO,IAAI,IAAI,EAAE;gBACnB,KAAK,GAAG,MAAM,EAAE,CAAC;gBACjB,OAAO,GAAG,QAAQ,CAAC,YAAY,CAAC,EAAE,KAAK,EAAE,QAA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AAG,YAAY,kBAAU,IAAI,GAAG,CAAC,aAAa,CAAC,qBAAqB,CAAC,CAAC;AAC/E,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/find.js b/node_modules/mongodb/lib/operations/find.js new file mode 100644 index 0000000..bbaebc5 --- /dev/null +++ b/node_modules/mongodb/lib/operations/find.js @@ -0,0 +1,211 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FindOperation = void 0; +const operation_1 = require("./operation"); +const utils_1 = require("../utils"); +const error_1 = require("../error"); +const command_1 = require("./command"); +const sort_1 = require("../sort"); +const shared_1 = require("../cmap/wire_protocol/shared"); +const read_concern_1 = require("../read_concern"); +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; +/** @internal */ +class FindOperation extends command_1.CommandOperation { + constructor(collection, ns, filter = {}, options = {}) { + super(collection, options); + this.options = options; + this.ns = ns; + if (typeof filter !== 'object' || Array.isArray(filter)) { + throw new error_1.MongoInvalidArgumentError('Query filter must be a plain object or ObjectId'); + } + // If the filter is a buffer, validate that is a valid BSON document + if (Buffer.isBuffer(filter)) { + const objectSize = filter[0] | (filter[1] << 8) | (filter[2] << 16) | (filter[3] << 24); + if (objectSize !== filter.length) { + throw new error_1.MongoInvalidArgumentError(`Query filter raw message size does not match message header size [${filter.length}] != [${objectSize}]`); + } + } + // special case passing in an ObjectId as a filter + this.filter = filter != null && filter._bsontype === 'ObjectID' ? { _id: filter } : filter; + } + execute(server, session, callback) { + this.server = server; + const serverWireVersion = utils_1.maxWireVersion(server); + const options = this.options; + if (options.allowDiskUse != null && serverWireVersion < 4) { + callback(new error_1.MongoCompatibilityError('Option "allowDiskUse" is not supported on MongoDB < 3.2')); + return; + } + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`)); + return; + } + if (serverWireVersion < 4) { + if (this.readConcern && this.readConcern.level !== 'local') { + callback(new error_1.MongoCompatibilityError(`Server find command does not support a readConcern level of ${this.readConcern.level}`)); + return; + } + const findCommand = makeLegacyFindCommand(this.ns, this.filter, options); + if (shared_1.isSharded(server) && this.readPreference) { + findCommand.$readPreference = this.readPreference.toJSON(); + } + server.query(this.ns, findCommand, { + ...this.options, + ...this.bsonOptions, + documentsReturnedIn: 'firstBatch', + readPreference: this.readPreference + }, callback); + return; + } + let findCommand = makeFindCommand(this.ns, this.filter, options); + if (this.explain) { + findCommand = utils_1.decorateWithExplain(findCommand, this.explain); + } + server.command(this.ns, findCommand, { + ...this.options, + ...this.bsonOptions, + documentsReturnedIn: 'firstBatch', + session + }, callback); + } +} +exports.FindOperation = FindOperation; +function makeFindCommand(ns, filter, options) { + const findCommand = { + find: ns.collection, + filter + }; + if (options.sort) { + findCommand.sort = sort_1.formatSort(options.sort); + } + if (options.projection) { + let projection = options.projection; + if (projection && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; + } + findCommand.projection = projection; + } + if (options.hint) { + findCommand.hint = utils_1.normalizeHintField(options.hint); + } + if (typeof options.skip === 'number') { + findCommand.skip = options.skip; + } + if (typeof options.limit === 'number') { + if (options.limit < 0) { + findCommand.limit = -options.limit; + findCommand.singleBatch = true; + } + else { + findCommand.limit = options.limit; + } + } + if (typeof options.batchSize === 'number') { + if (options.batchSize < 0) { + if (options.limit && + options.limit !== 0 && + Math.abs(options.batchSize) < Math.abs(options.limit)) { + findCommand.limit = -options.batchSize; + } + findCommand.singleBatch = true; + } + else { + findCommand.batchSize = options.batchSize; + } + } + if (typeof options.singleBatch === 'boolean') { + findCommand.singleBatch = options.singleBatch; + } + if (options.comment) { + findCommand.comment = options.comment; + } + if (typeof options.maxTimeMS === 'number') { + findCommand.maxTimeMS = options.maxTimeMS; + } + const readConcern = read_concern_1.ReadConcern.fromOptions(options); + if (readConcern) { + findCommand.readConcern = readConcern.toJSON(); + } + if (options.max) { + findCommand.max = options.max; + } + if (options.min) { + findCommand.min = options.min; + } + if (typeof options.returnKey === 'boolean') { + findCommand.returnKey = options.returnKey; + } + if (typeof options.showRecordId === 'boolean') { + findCommand.showRecordId = options.showRecordId; + } + if (typeof options.tailable === 'boolean') { + findCommand.tailable = options.tailable; + } + if (typeof options.timeout === 'boolean') { + findCommand.noCursorTimeout = !options.timeout; + } + else if (typeof options.noCursorTimeout === 'boolean') { + findCommand.noCursorTimeout = options.noCursorTimeout; + } + if (typeof options.awaitData === 'boolean') { + findCommand.awaitData = options.awaitData; + } + if (typeof options.allowPartialResults === 'boolean') { + findCommand.allowPartialResults = options.allowPartialResults; + } + if (options.collation) { + findCommand.collation = options.collation; + } + if (typeof options.allowDiskUse === 'boolean') { + findCommand.allowDiskUse = options.allowDiskUse; + } + if (options.let) { + findCommand.let = options.let; + } + return findCommand; +} +function makeLegacyFindCommand(ns, filter, options) { + const findCommand = { + $query: filter + }; + if (options.sort) { + findCommand.$orderby = sort_1.formatSort(options.sort); + } + if (options.hint) { + findCommand.$hint = utils_1.normalizeHintField(options.hint); + } + if (typeof options.returnKey === 'boolean') { + findCommand.$returnKey = options.returnKey; + } + if (options.max) { + findCommand.$max = options.max; + } + if (options.min) { + findCommand.$min = options.min; + } + if (typeof options.showRecordId === 'boolean') { + findCommand.$showDiskLoc = options.showRecordId; + } + if (options.comment) { + findCommand.$comment = options.comment; + } + if (typeof options.maxTimeMS === 'number') { + findCommand.$maxTimeMS = options.maxTimeMS; + } + if (options.explain != null) { + findCommand.$explain = true; + } + return findCommand; +} +operation_1.defineAspects(FindOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=find.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/find.js.map b/node_modules/mongodb/lib/operations/find.js.map new file mode 100644 index 0000000..0de5689 --- /dev/null +++ b/node_modules/mongodb/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AO,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;QACzC,WAAW,CAAC,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;KAC5C;IAED,IAAI,OAAO,CAAC,OAAO,IAAI,IAAI,EAAE;QAC3B,WAAW,CAAC,QAAQ,GAAG,IAAI,CAAC;KAC7B;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;AAED,yBAAa,CAAC,aAAa,EAAE;IAC3B,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/find_and_modify.js b/node_modules/mongodb/lib/operations/find_and_modify.js new file mode 100644 index 0000000..a88a61d --- /dev/null +++ b/node_modules/mongodb/lib/operations/find_and_modify.js @@ -0,0 +1,151 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FindOneAndUpdateOperation = exports.FindOneAndReplaceOperation = exports.FindOneAndDeleteOperation = exports.ReturnDocument = void 0; +const read_preference_1 = require("../read_preference"); +const utils_1 = require("../utils"); +const error_1 = require("../error"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +const sort_1 = require("../sort"); +/** @public */ +exports.ReturnDocument = Object.freeze({ + BEFORE: 'before', + AFTER: 'after' +}); +function configureFindAndModifyCmdBaseUpdateOpts(cmdBase, options) { + cmdBase.new = options.returnDocument === exports.ReturnDocument.AFTER; + cmdBase.upsert = options.upsert === true; + if (options.bypassDocumentValidation === true) { + cmdBase.bypassDocumentValidation = options.bypassDocumentValidation; + } + return cmdBase; +} +/** @internal */ +class FindAndModifyOperation extends command_1.CommandOperation { + constructor(collection, query, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.cmdBase = { + remove: false, + new: false, + upsert: false + }; + const sort = sort_1.formatSort(options.sort); + if (sort) { + this.cmdBase.sort = sort; + } + if (options.projection) { + this.cmdBase.fields = options.projection; + } + if (options.maxTimeMS) { + this.cmdBase.maxTimeMS = options.maxTimeMS; + } + // Decorate the findAndModify command with the write Concern + if (options.writeConcern) { + this.cmdBase.writeConcern = options.writeConcern; + } + if (options.let) { + this.cmdBase.let = options.let; + } + // force primary read preference + this.readPreference = read_preference_1.ReadPreference.primary; + this.collection = collection; + this.query = query; + } + execute(server, session, callback) { + var _a; + const coll = this.collection; + const query = this.query; + const options = { ...this.options, ...this.bsonOptions }; + // Create findAndModify command object + const cmd = { + findAndModify: coll.collectionName, + query: query, + ...this.cmdBase + }; + // Have we specified collation + try { + utils_1.decorateWithCollation(cmd, coll, options); + } + catch (err) { + return callback(err); + } + if (options.hint) { + // TODO: once this method becomes a CommandOperation we will have the server + // in place to check. + const unacknowledgedWrite = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) === 0; + if (unacknowledgedWrite || utils_1.maxWireVersion(server) < 8) { + callback(new error_1.MongoCompatibilityError('The current topology does not support a hint on findAndModify commands')); + return; + } + cmd.hint = options.hint; + } + if (this.explain && utils_1.maxWireVersion(server) < 4) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on findAndModify`)); + return; + } + // Execute the command + super.executeCommand(server, session, cmd, (err, result) => { + if (err) + return callback(err); + return callback(undefined, result); + }); + } +} +/** @internal */ +class FindOneAndDeleteOperation extends FindAndModifyOperation { + constructor(collection, filter, options) { + // Basic validation + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + super(collection, filter, options); + this.cmdBase.remove = true; + } +} +exports.FindOneAndDeleteOperation = FindOneAndDeleteOperation; +/** @internal */ +class FindOneAndReplaceOperation extends FindAndModifyOperation { + constructor(collection, filter, replacement, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + if (replacement == null || typeof replacement !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "replacement" must be an object'); + } + if (utils_1.hasAtomicOperators(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + super(collection, filter, options); + this.cmdBase.update = replacement; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + } +} +exports.FindOneAndReplaceOperation = FindOneAndReplaceOperation; +/** @internal */ +class FindOneAndUpdateOperation extends FindAndModifyOperation { + constructor(collection, filter, update, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + if (update == null || typeof update !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "update" must be an object'); + } + if (!utils_1.hasAtomicOperators(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + super(collection, filter, options); + this.cmdBase.update = update; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + if (options.arrayFilters) { + this.cmdBase.arrayFilters = options.arrayFilters; + } + } +} +exports.FindOneAndUpdateOperation = FindOneAndUpdateOperation; +operation_1.defineAspects(FindAndModifyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE +]); +//# sourceMappingURL=find_and_modify.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/find_and_modify.js.map b/node_modules/mongodb/lib/operations/find_and_modify.js.map new file mode 100644 index 0000000..5a34978 --- /dev/null +++ b/node_modules/mongodb/lib/operations/find_and_modify.js.map @@ -0,0 +1 @@ +{"version":3,"file":"find_and_modify.js","sourceRoot":"","sources":["../../src/operations/find_and_modify.ts"],"names":[],"mappings":";;;AAAA,wDAAoD;AACpD,oCAA+F;AAC/F,oCAA8E;AAC9E,uCAAsE;AACtE,2CAAoD;AAIpD,kCAAuD;AAIvD,cAAc;AACD,QAAA,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC;IAC1C,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,OAAO;CACN,CAAC,CAAC;AAsEZ,SAAS,uCAAuC,CAC9C,OAA6B,EAC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,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,WAAW,CAAC;QAClC,uCAAuC,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACjE,CAAC;CACF;AAvBD,gEAuBC;AAED,gBAAgB;AAChB,MAAa,yBAA0B,SAAQ,sBAAsB;IACnE,YACE,UAAsB,EACtB,MAAgB,EAChB,MAAgB,EAChB,OAAgC;QAEhC,IAAI,MAAM,IAAI,IAAI,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;YAChD,MAAM,IAAI,iCAAyB,CAAC,qCAAqC,CAAC,CAAC;SAC5E;QAED,IAAI,MAAM,IAAI,IAAI,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;YAChD,MAAM,IAAI,iCAAyB,CAAC,qCAAqC,CAAC,CAAC;SAC5E;QAED,IAAI,CAAC,0BAAkB,CAAC,MAAM,CAAC,EAAE;YAC/B,MAAM,IAAI,iCAAyB,CAAC,2CAA2C,CAAC,CAAC;SAClF;QAED,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;QACnC,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC;QAC7B,uCAAuC,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAE/D,IAAI,OAAO,CAAC,YAAY,EAAE;YACxB,IAAI,CAAC,OAAO,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;SAClD;IACH,CAAC;CACF;AA3BD,8DA2BC;AAED,yBAAa,CAAC,sBAAsB,EAAE;IACpC,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,WAAW;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/indexes.js b/node_modules/mongodb/lib/operations/indexes.js new file mode 100644 index 0000000..b3560cb --- /dev/null +++ b/node_modules/mongodb/lib/operations/indexes.js @@ -0,0 +1,297 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IndexInformationOperation = exports.IndexExistsOperation = exports.ListIndexesCursor = exports.ListIndexesOperation = exports.DropIndexesOperation = exports.DropIndexOperation = exports.EnsureIndexOperation = exports.CreateIndexOperation = exports.CreateIndexesOperation = exports.IndexesOperation = void 0; +const common_functions_1 = require("./common_functions"); +const operation_1 = require("./operation"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const read_preference_1 = require("../read_preference"); +const abstract_cursor_1 = require("../cursor/abstract_cursor"); +const execute_operation_1 = require("./execute_operation"); +const LIST_INDEXES_WIRE_VERSION = 3; +const VALID_INDEX_OPTIONS = new Set([ + 'background', + 'unique', + 'name', + 'partialFilterExpression', + 'sparse', + 'hidden', + 'expireAfterSeconds', + 'storageEngine', + 'collation', + 'version', + // text indexes + 'weights', + 'default_language', + 'language_override', + 'textIndexVersion', + // 2d-sphere indexes + '2dsphereIndexVersion', + // 2d indexes + 'bits', + 'min', + 'max', + // geoHaystack Indexes + 'bucketSize', + // wildcard indexes + 'wildcardProjection' +]); +function makeIndexSpec(indexSpec, options) { + const indexParameters = utils_1.parseIndexOptions(indexSpec); + // Generate the index name + const name = typeof options.name === 'string' ? options.name : indexParameters.name; + // Set up the index + const finalIndexSpec = { name, key: indexParameters.fieldHash }; + // merge valid index options into the index spec + for (const optionName in options) { + if (VALID_INDEX_OPTIONS.has(optionName)) { + finalIndexSpec[optionName] = options[optionName]; + } + } + return finalIndexSpec; +} +/** @internal */ +class IndexesOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + execute(server, session, callback) { + const coll = this.collection; + const options = this.options; + common_functions_1.indexInformation(coll.s.db, coll.collectionName, { full: true, ...options, readPreference: this.readPreference, session }, callback); + } +} +exports.IndexesOperation = IndexesOperation; +/** @internal */ +class CreateIndexesOperation extends command_1.CommandOperation { + constructor(parent, collectionName, indexes, options) { + super(parent, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collectionName = collectionName; + this.indexes = indexes; + } + execute(server, session, callback) { + const options = this.options; + const indexes = this.indexes; + const serverWireVersion = utils_1.maxWireVersion(server); + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexes.length; i++) { + // Did the user pass in a collation, check if our write server supports it + if (indexes[i].collation && serverWireVersion < 5) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name}, which reports wire version ${serverWireVersion}, ` + + 'does not support collation')); + return; + } + if (indexes[i].name == null) { + const keys = []; + for (const name in indexes[i].key) { + keys.push(`${name}_${indexes[i].key[name]}`); + } + // Set the name + indexes[i].name = keys.join('_'); + } + } + const cmd = { createIndexes: this.collectionName, indexes }; + if (options.commitQuorum != null) { + if (serverWireVersion < 9) { + callback(new error_1.MongoCompatibilityError('Option `commitQuorum` for `createIndexes` not supported on servers < 4.4')); + return; + } + cmd.commitQuorum = options.commitQuorum; + } + // collation is set on each index, it should not be defined at the root + this.options.collation = undefined; + super.executeCommand(server, session, cmd, err => { + if (err) { + callback(err); + return; + } + const indexNames = indexes.map(index => index.name || ''); + callback(undefined, indexNames); + }); + } +} +exports.CreateIndexesOperation = CreateIndexesOperation; +/** @internal */ +class CreateIndexOperation extends CreateIndexesOperation { + constructor(parent, collectionName, indexSpec, options) { + // createIndex can be called with a variety of styles: + // coll.createIndex('a'); + // coll.createIndex({ a: 1 }); + // coll.createIndex([['a', 1]]); + // createIndexes is always called with an array of index spec objects + super(parent, collectionName, [makeIndexSpec(indexSpec, options)], options); + } + execute(server, session, callback) { + super.execute(server, session, (err, indexNames) => { + if (err || !indexNames) + return callback(err); + return callback(undefined, indexNames[0]); + }); + } +} +exports.CreateIndexOperation = CreateIndexOperation; +/** @internal */ +class EnsureIndexOperation extends CreateIndexOperation { + constructor(db, collectionName, indexSpec, options) { + super(db, collectionName, indexSpec, options); + this.readPreference = read_preference_1.ReadPreference.primary; + this.db = db; + this.collectionName = collectionName; + } + execute(server, session, callback) { + const indexName = this.indexes[0].name; + const cursor = this.db.collection(this.collectionName).listIndexes({ session }); + cursor.toArray((err, indexes) => { + /// ignore "NamespaceNotFound" errors + if (err && err.code !== error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + return callback(err); + } + if (indexes) { + indexes = Array.isArray(indexes) ? indexes : [indexes]; + if (indexes.some(index => index.name === indexName)) { + callback(undefined, indexName); + return; + } + } + super.execute(server, session, callback); + }); + } +} +exports.EnsureIndexOperation = EnsureIndexOperation; +/** @internal */ +class DropIndexOperation extends command_1.CommandOperation { + constructor(collection, indexName, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collection = collection; + this.indexName = indexName; + } + execute(server, session, callback) { + const cmd = { dropIndexes: this.collection.collectionName, index: this.indexName }; + super.executeCommand(server, session, cmd, callback); + } +} +exports.DropIndexOperation = DropIndexOperation; +/** @internal */ +class DropIndexesOperation extends DropIndexOperation { + constructor(collection, options) { + super(collection, '*', options); + } + execute(server, session, callback) { + super.execute(server, session, err => { + if (err) + return callback(err, false); + callback(undefined, true); + }); + } +} +exports.DropIndexesOperation = DropIndexesOperation; +/** @internal */ +class ListIndexesOperation extends command_1.CommandOperation { + constructor(collection, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collectionNamespace = collection.s.namespace; + } + execute(server, session, callback) { + const serverWireVersion = utils_1.maxWireVersion(server); + if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) { + const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes'); + const collectionNS = this.collectionNamespace.toString(); + server.query(systemIndexesNS, { query: { ns: collectionNS } }, { ...this.options, readPreference: this.readPreference }, callback); + return; + } + const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; + super.executeCommand(server, session, { listIndexes: this.collectionNamespace.collection, cursor }, callback); + } +} +exports.ListIndexesOperation = ListIndexesOperation; +/** @public */ +class ListIndexesCursor extends abstract_cursor_1.AbstractCursor { + constructor(collection, options) { + super(utils_1.getTopology(collection), collection.s.namespace, options); + this.parent = collection; + this.options = options; + } + clone() { + return new ListIndexesCursor(this.parent, { + ...this.options, + ...this.cursorOptions + }); + } + /** @internal */ + _initialize(session, callback) { + const operation = new ListIndexesOperation(this.parent, { + ...this.cursorOptions, + ...this.options, + session + }); + execute_operation_1.executeOperation(utils_1.getTopology(this.parent), operation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: NODE-2882 + callback(undefined, { server: operation.server, session, response }); + }); + } +} +exports.ListIndexesCursor = ListIndexesCursor; +/** @internal */ +class IndexExistsOperation extends operation_1.AbstractOperation { + constructor(collection, indexes, options) { + super(options); + this.options = options; + this.collection = collection; + this.indexes = indexes; + } + execute(server, session, callback) { + const coll = this.collection; + const indexes = this.indexes; + common_functions_1.indexInformation(coll.s.db, coll.collectionName, { ...this.options, readPreference: this.readPreference, session }, (err, indexInformation) => { + // If we have an error return + if (err != null) + return callback(err); + // Let's check for the index names + if (!Array.isArray(indexes)) + return callback(undefined, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return callback(undefined, false); + } + } + // All keys found return true + return callback(undefined, true); + }); + } +} +exports.IndexExistsOperation = IndexExistsOperation; +/** @internal */ +class IndexInformationOperation extends operation_1.AbstractOperation { + constructor(db, name, options) { + super(options); + this.options = options !== null && options !== void 0 ? options : {}; + this.db = db; + this.name = name; + } + execute(server, session, callback) { + const db = this.db; + const name = this.name; + common_functions_1.indexInformation(db, name, { ...this.options, readPreference: this.readPreference, session }, callback); + } +} +exports.IndexInformationOperation = IndexInformationOperation; +operation_1.defineAspects(ListIndexesOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +operation_1.defineAspects(CreateIndexesOperation, [operation_1.Aspect.WRITE_OPERATION]); +operation_1.defineAspects(CreateIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +operation_1.defineAspects(EnsureIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +operation_1.defineAspects(DropIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +operation_1.defineAspects(DropIndexesOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=indexes.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/indexes.js.map b/node_modules/mongodb/lib/operations/indexes.js.map new file mode 100644 index 0000000..12222d5 --- /dev/null +++ b/node_modules/mongodb/lib/operations/indexes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"indexes.js","sourceRoot":"","sources":["../../src/operations/indexes.ts"],"names":[],"mappings":";;;AAAA,yDAA+E;AAC/E,2CAAuE;AACvE,oCAA0F;AAC1F,oCAMkB;AAClB,uCAKmB;AACnB,wDAAoD;AAKpD,+DAA2D;AAE3D,2DAAwE;AAGxE,MAAM,yBAAyB,GAAG,CAAC,CAAC;AACpC,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IAClC,YAAY;IACZ,QAAQ;IACR,MAAM;IACN,yBAAyB;IACzB,QAAQ;IACR,QAAQ;IACR,oBAAoB;IACpB,eAAe;IACf,WAAW;IACX,SAAS;IAET,eAAe;IACf,SAAS;IACT,kBAAkB;IAClB,mBAAmB;IACnB,kBAAkB;IAElB,oBAAoB;IACpB,sBAAsB;IAEtB,aAAa;IACb,MAAM;IACN,KAAK;IACL,KAAK;IAEL,sBAAsB;IACtB,YAAY;IAEZ,mBAAmB;IACnB,oBAAoB;CACrB,CAAC,CAAC;AAmFH,SAAS,aAAa,CAAC,SAA6B,EAAE,OAAY;IAChE,MAAM,eAAe,GAAG,yBAAiB,CAAC,SAAS,CAAC,CAAC;IAErD,0BAA0B;IAC1B,MAAM,IAAI,GAAG,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC;IAEpF,mBAAmB;IACnB,MAAM,cAAc,GAAa,EAAE,IAAI,EAAE,GAAG,EAAE,eAAe,CAAC,SAAS,EAAE,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AC,cAAc,EAAE,OAAO,EAAE,EACjE,QAAQ,CACT,CAAC;IACJ,CAAC;CACF;AAvBD,8DAuBC;AAED,yBAAa,CAAC,oBAAoB,EAAE;IAClC,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC;AACH,yBAAa,CAAC,sBAAsB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAChE,yBAAa,CAAC,oBAAoB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC9D,yBAAa,CAAC,oBAAoB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC9D,yBAAa,CAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC5D,yBAAa,CAAC,oBAAoB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/insert.js b/node_modules/mongodb/lib/operations/insert.js new file mode 100644 index 0000000..9f87726 --- /dev/null +++ b/node_modules/mongodb/lib/operations/insert.js @@ -0,0 +1,93 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InsertManyOperation = exports.InsertOneOperation = exports.InsertOperation = void 0; +const error_1 = require("../error"); +const operation_1 = require("./operation"); +const command_1 = require("./command"); +const common_functions_1 = require("./common_functions"); +const write_concern_1 = require("../write_concern"); +const bulk_write_1 = require("./bulk_write"); +/** @internal */ +class InsertOperation extends command_1.CommandOperation { + constructor(ns, documents, options) { + var _a; + super(undefined, options); + this.options = { ...options, checkKeys: (_a = options.checkKeys) !== null && _a !== void 0 ? _a : false }; + this.ns = ns; + this.documents = documents; + } + execute(server, session, callback) { + var _a; + const options = (_a = this.options) !== null && _a !== void 0 ? _a : {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + insert: this.ns.collection, + documents: this.documents, + ordered + }; + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + if (options.comment != null) { + command.comment = options.comment; + } + super.executeCommand(server, session, command, callback); + } +} +exports.InsertOperation = InsertOperation; +class InsertOneOperation extends InsertOperation { + constructor(collection, doc, options) { + super(collection.s.namespace, common_functions_1.prepareDocs(collection, [doc], options), options); + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || res == null) + return callback(err); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) { + // This should be a WriteError but we can't change it now because of error hierarchy + return callback(new error_1.MongoServerError(res.writeErrors[0])); + } + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + insertedId: this.documents[0]._id + }); + }); + } +} +exports.InsertOneOperation = InsertOneOperation; +/** @internal */ +class InsertManyOperation extends operation_1.AbstractOperation { + constructor(collection, docs, options) { + super(options); + if (!Array.isArray(docs)) { + throw new error_1.MongoInvalidArgumentError('Argument "docs" must be an array of documents'); + } + this.options = options; + this.collection = collection; + this.docs = docs; + } + execute(server, session, callback) { + const coll = this.collection; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + const bulkWriteOperation = new bulk_write_1.BulkWriteOperation(coll, common_functions_1.prepareDocs(coll, this.docs, options).map(document => ({ insertOne: { document } })), options); + bulkWriteOperation.execute(server, session, (err, res) => { + var _a; + if (err || res == null) + return callback(err); + callback(undefined, { + acknowledged: (_a = (writeConcern === null || writeConcern === void 0 ? void 0 : writeConcern.w) !== 0) !== null && _a !== void 0 ? _a : true, + insertedCount: res.insertedCount, + insertedIds: res.insertedIds + }); + }); + } +} +exports.InsertManyOperation = InsertManyOperation; +operation_1.defineAspects(InsertOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +operation_1.defineAspects(InsertOneOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +operation_1.defineAspects(InsertManyOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=insert.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/insert.js.map b/node_modules/mongodb/lib/operations/insert.js.map new file mode 100644 index 0000000..c8ab1df --- /dev/null +++ b/node_modules/mongodb/lib/operations/insert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"insert.js","sourceRoot":"","sources":["../../src/operations/insert.ts"],"names":[],"mappings":";;;AAAA,oCAAuE;AACvE,2CAAuE;AACvE,uCAAsE;AACtE,yDAAiD;AAMjD,oDAAgD;AAEhD,6CAAkD;AAGlD,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,0BAA0B;IAI7D,YAAY,EAAoB,EAAE,SAAqB,EAAE,OAAyB;;QAChF,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,MAAA,OAAO,CAAC,SAAS,mCAAI,KAAK,EAAE,CAAC;QACrE,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA4B;;QAC1E,MAAM,OAAO,GAAG,MAAA,IAAI,CAAC,OAAO,mCAAI,EAAE,CAAC;QACnC,MAAM,OAAO,GAAG,OAAO,OAAO,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;QAC9E,MAAM,OAAO,GAAa;YACxB,MAAM,EAAE,IAAI,CAAC,EAAE,CAAC,UAAU;YAC1B,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO;SACR,CAAC;QAEF,IAAI,OAAO,OAAO,CAAC,wBAAwB,KAAK,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AA,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,CAAC,MAAK,CAAC,mCAAI,IAAI;gBAC3C,aAAa,EAAE,GAAG,CAAC,aAAa;gBAChC,WAAW,EAAE,GAAG,CAAC,WAAW;aAC7B,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AApCD,kDAoCC;AAED,yBAAa,CAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC3E,yBAAa,CAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC9E,yBAAa,CAAC,mBAAmB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/is_capped.js b/node_modules/mongodb/lib/operations/is_capped.js new file mode 100644 index 0000000..16e0a31 --- /dev/null +++ b/node_modules/mongodb/lib/operations/is_capped.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IsCappedOperation = void 0; +const operation_1 = require("./operation"); +const error_1 = require("../error"); +/** @internal */ +class IsCappedOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + execute(server, session, callback) { + const coll = this.collection; + coll.s.db + .listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }) + .toArray((err, collections) => { + if (err || !collections) + return callback(err); + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`)); + } + const collOptions = collections[0].options; + callback(undefined, !!(collOptions && collOptions.capped)); + }); + } +} +exports.IsCappedOperation = IsCappedOperation; +//# sourceMappingURL=is_capped.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/is_capped.js.map b/node_modules/mongodb/lib/operations/is_capped.js.map new file mode 100644 index 0000000..227f156 --- /dev/null +++ b/node_modules/mongodb/lib/operations/is_capped.js.map @@ -0,0 +1 @@ +{"version":3,"file":"is_capped.js","sourceRoot":"","sources":["../../src/operations/is_capped.ts"],"names":[],"mappings":";;;AAEA,2CAAkE;AAGlE,oCAAyC;AAEzC,gBAAgB;AAChB,MAAa,iBAAkB,SAAQ,6BAA0B;IAI/D,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA2B;QACzE,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAE7B,IAAI,CAAC,CAAC,CAAC,EAAE;aACN,eAAe,CACd,EAAE,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE,EAC7B,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CACnF;aACA,OAAO,CAAC,CAAC,GAAG,EAAE,WAAW,EAAE,EAAE;YAC5B,IAAI,GAAG,IAAI,CAAC,WAAW;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9C,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC5B,kBAAkB;gBAClB,OAAO,QAAQ,CAAC,IAAI,qBAAa,CAAC,cAAc,IAAI,CAAC,SAAS,YAAY,CAAC,CAAC,CAAC;aAC9E;YAED,MAAM,WAAW,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;YAC3C,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;QAC7D,CAAC,CAAC,CAAC;IACP,CAAC;CACF;AA7BD,8CA6BC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/list_collections.js b/node_modules/mongodb/lib/operations/list_collections.js new file mode 100644 index 0000000..7ff7277 --- /dev/null +++ b/node_modules/mongodb/lib/operations/list_collections.js @@ -0,0 +1,105 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListCollectionsCursor = exports.ListCollectionsOperation = void 0; +const command_1 = require("./command"); +const operation_1 = require("./operation"); +const utils_1 = require("../utils"); +const CONSTANTS = require("../constants"); +const abstract_cursor_1 = require("../cursor/abstract_cursor"); +const execute_operation_1 = require("./execute_operation"); +const LIST_COLLECTIONS_WIRE_VERSION = 3; +/** @internal */ +class ListCollectionsOperation extends command_1.CommandOperation { + constructor(db, filter, options) { + super(db, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.db = db; + this.filter = filter; + this.nameOnly = !!this.options.nameOnly; + if (typeof this.options.batchSize === 'number') { + this.batchSize = this.options.batchSize; + } + } + execute(server, session, callback) { + if (utils_1.maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) { + let filter = this.filter; + const databaseName = this.db.s.namespace.db; + // If we have legacy mode and have not provided a full db name filter it + if (typeof filter.name === 'string' && !new RegExp(`^${databaseName}\\.`).test(filter.name)) { + filter = Object.assign({}, filter); + filter.name = this.db.s.namespace.withCollection(filter.name).toString(); + } + // No filter, filter by current database + if (filter == null) { + filter = { name: `/${databaseName}/` }; + } + // Rewrite the filter to use $and to filter out indexes + if (filter.name) { + filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; + } + else { + filter = { name: /^((?!\$).)*$/ }; + } + const documentTransform = (doc) => { + const matching = `${databaseName}.`; + const index = doc.name.indexOf(matching); + // Remove database name if available + if (doc.name && index === 0) { + doc.name = doc.name.substr(index + matching.length); + } + return doc; + }; + server.query(new utils_1.MongoDBNamespace(databaseName, CONSTANTS.SYSTEM_NAMESPACE_COLLECTION), { query: filter }, { batchSize: this.batchSize || 1000, readPreference: this.readPreference }, (err, result) => { + if (result && result.documents && Array.isArray(result.documents)) { + result.documents = result.documents.map(documentTransform); + } + callback(err, result); + }); + return; + } + const command = { + listCollections: 1, + filter: this.filter, + cursor: this.batchSize ? { batchSize: this.batchSize } : {}, + nameOnly: this.nameOnly + }; + return super.executeCommand(server, session, command, callback); + } +} +exports.ListCollectionsOperation = ListCollectionsOperation; +/** @public */ +class ListCollectionsCursor extends abstract_cursor_1.AbstractCursor { + constructor(db, filter, options) { + super(utils_1.getTopology(db), db.s.namespace, options); + this.parent = db; + this.filter = filter; + this.options = options; + } + clone() { + return new ListCollectionsCursor(this.parent, this.filter, { + ...this.options, + ...this.cursorOptions + }); + } + /** @internal */ + _initialize(session, callback) { + const operation = new ListCollectionsOperation(this.parent, this.filter, { + ...this.cursorOptions, + ...this.options, + session + }); + execute_operation_1.executeOperation(utils_1.getTopology(this.parent), operation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: NODE-2882 + callback(undefined, { server: operation.server, session, response }); + }); + } +} +exports.ListCollectionsCursor = ListCollectionsCursor; +operation_1.defineAspects(ListCollectionsOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=list_collections.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/list_collections.js.map b/node_modules/mongodb/lib/operations/list_collections.js.map new file mode 100644 index 0000000..8e90772 --- /dev/null +++ b/node_modules/mongodb/lib/operations/list_collections.js.map @@ -0,0 +1 @@ +{"version":3,"file":"list_collections.js","sourceRoot":"","sources":["../../src/operations/list_collections.ts"],"names":[],"mappings":";;;AAAA,uCAAsE;AACtE,2CAAoD;AACpD,oCAAmF;AACnF,0CAA0C;AAI1C,+DAA2D;AAE3D,2DAAwE;AAExE,MAAM,6BAA6B,GAAG,CAAC,CAAC;AAUxC,gBAAgB;AAChB,MAAa,wBAAyB,SAAQ,0BAA0B;IAOtE,YAAY,EAAM,EAAE,MAAgB,EAAE,OAA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,IAAI,IAAI;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAElD,kBAAkB;YAClB,QAAQ,CAAC,SAAS,EAAE,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;QACvE,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAtCD,sDAsCC;AAED,yBAAa,CAAC,wBAAwB,EAAE;IACtC,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/list_databases.js b/node_modules/mongodb/lib/operations/list_databases.js new file mode 100644 index 0000000..5133b32 --- /dev/null +++ b/node_modules/mongodb/lib/operations/list_databases.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListDatabasesOperation = void 0; +const command_1 = require("./command"); +const operation_1 = require("./operation"); +const utils_1 = require("../utils"); +/** @internal */ +class ListDatabasesOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.ns = new utils_1.MongoDBNamespace('admin', '$cmd'); + } + execute(server, session, callback) { + const cmd = { listDatabases: 1 }; + if (this.options.nameOnly) { + cmd.nameOnly = Number(cmd.nameOnly); + } + if (this.options.filter) { + cmd.filter = this.options.filter; + } + if (typeof this.options.authorizedDatabases === 'boolean') { + cmd.authorizedDatabases = this.options.authorizedDatabases; + } + super.executeCommand(server, session, cmd, callback); + } +} +exports.ListDatabasesOperation = ListDatabasesOperation; +operation_1.defineAspects(ListDatabasesOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); +//# sourceMappingURL=list_databases.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/list_databases.js.map b/node_modules/mongodb/lib/operations/list_databases.js.map new file mode 100644 index 0000000..36e0057 --- /dev/null +++ b/node_modules/mongodb/lib/operations/list_databases.js.map @@ -0,0 +1 @@ +{"version":3,"file":"list_databases.js","sourceRoot":"","sources":["../../src/operations/list_databases.ts"],"names":[],"mappings":";;;AAAA,uCAAsE;AACtE,2CAAoD;AACpD,oCAAsD;AAmBtD,gBAAgB;AAChB,MAAa,sBAAuB,SAAQ,0BAAqC;IAG/E,YAAY,EAAM,EAAE,OAA8B;QAChD,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,EAAE,GAAG,IAAI,wBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAClD,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAAuC;QACrF,MAAM,GAAG,GAAa,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC;QAC3C,IAAI,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE;YACzB,GAAG,CAAC,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;SACrC;QAED,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;YACvB,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;SAClC;QAED,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,mBAAmB,KAAK,SAAS,EAAE;YACzD,GAAG,CAAC,mBAAmB,GAAG,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC;SAC5D;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;IACvD,CAAC;CACF;AAzBD,wDAyBC;AAED,yBAAa,CAAC,sBAAsB,EAAE,CAAC,kBAAM,CAAC,cAAc,EAAE,kBAAM,CAAC,SAAS,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/map_reduce.js b/node_modules/mongodb/lib/operations/map_reduce.js new file mode 100644 index 0000000..45fd0f2 --- /dev/null +++ b/node_modules/mongodb/lib/operations/map_reduce.js @@ -0,0 +1,166 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MapReduceOperation = void 0; +const bson_1 = require("../bson"); +const utils_1 = require("../utils"); +const read_preference_1 = require("../read_preference"); +const command_1 = require("./command"); +const error_1 = require("../error"); +const operation_1 = require("./operation"); +const db_1 = require("../db"); +const exclusionList = [ + 'explain', + 'readPreference', + 'readConcern', + 'session', + 'bypassDocumentValidation', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined', + 'scope' // this option is reformatted thus exclude the original +]; +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * @internal + */ +class MapReduceOperation extends command_1.CommandOperation { + /** + * Constructs a MapReduce operation. + * + * @param collection - Collection instance. + * @param map - The mapping function. + * @param reduce - The reduce function. + * @param options - Optional settings. See Collection.prototype.mapReduce for a list of options. + */ + constructor(collection, map, reduce, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collection = collection; + this.map = map; + this.reduce = reduce; + } + execute(server, session, callback) { + const coll = this.collection; + const map = this.map; + const reduce = this.reduce; + let options = this.options; + const mapCommandHash = { + mapReduce: coll.collectionName, + map: map, + reduce: reduce + }; + if (options.scope) { + mapCommandHash.scope = processScope(options.scope); + } + // Add any other options passed in + for (const n in options) { + // Only include if not in exclusion list + if (exclusionList.indexOf(n) === -1) { + mapCommandHash[n] = options[n]; + } + } + options = Object.assign({}, options); + // If we have a read preference and inline is not set as output fail hard + if (this.readPreference.mode === read_preference_1.ReadPreferenceMode.primary && + options.out && + options.out.inline !== 1 && + options.out !== 'inline') { + // Force readPreference to primary + options.readPreference = read_preference_1.ReadPreference.primary; + // Decorate command with writeConcern if supported + utils_1.applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); + } + else { + utils_1.decorateWithReadConcern(mapCommandHash, coll, options); + } + // Is bypassDocumentValidation specified + if (options.bypassDocumentValidation === true) { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + // Have we specified collation + try { + utils_1.decorateWithCollation(mapCommandHash, coll, options); + } + catch (err) { + return callback(err); + } + if (this.explain && utils_1.maxWireVersion(server) < 9) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on mapReduce`)); + return; + } + // Execute command + super.executeCommand(server, session, mapCommandHash, (err, result) => { + if (err) + return callback(err); + // Check if we have an error + if (1 !== result.ok || result.err || result.errmsg) { + return callback(new error_1.MongoServerError(result)); + } + // If an explain option was executed, don't process the server results + if (this.explain) + return callback(undefined, result); + // Create statistics value + const stats = {}; + if (result.timeMillis) + stats['processtime'] = result.timeMillis; + if (result.counts) + stats['counts'] = result.counts; + if (result.timing) + stats['timing'] = result.timing; + // invoked with inline? + if (result.results) { + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return callback(undefined, result.results); + } + return callback(undefined, { results: result.results, stats: stats }); + } + // The returned collection + let collection = null; + // If we have an object it's a different db + if (result.result != null && typeof result.result === 'object') { + const doc = result.result; + // Return a collection from another db + collection = new db_1.Db(coll.s.db.s.client, doc.db, coll.s.db.s.options).collection(doc.collection); + } + else { + // Create a collection object that wraps the result collection + collection = coll.s.db.collection(result.result); + } + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return callback(err, collection); + } + // Return stats as third set of values + callback(err, { collection, stats }); + }); + } +} +exports.MapReduceOperation = MapReduceOperation; +/** Functions that are passed as scope args must be converted to Code instances. */ +function processScope(scope) { + if (!utils_1.isObject(scope) || scope._bsontype === 'ObjectID') { + return scope; + } + const newScope = {}; + for (const key of Object.keys(scope)) { + if ('function' === typeof scope[key]) { + newScope[key] = new bson_1.Code(String(scope[key])); + } + else if (scope[key]._bsontype === 'Code') { + newScope[key] = scope[key]; + } + else { + newScope[key] = processScope(scope[key]); + } + } + return newScope; +} +operation_1.defineAspects(MapReduceOperation, [operation_1.Aspect.EXPLAINABLE]); +//# sourceMappingURL=map_reduce.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/map_reduce.js.map b/node_modules/mongodb/lib/operations/map_reduce.js.map new file mode 100644 index 0000000..249bce7 --- /dev/null +++ b/node_modules/mongodb/lib/operations/map_reduce.js.map @@ -0,0 +1 @@ +{"version":3,"file":"map_reduce.js","sourceRoot":"","sources":["../../src/operations/map_reduce.ts"],"names":[],"mappings":";;;AAAA,kCAAyC;AACzC,oCAOkB;AAClB,wDAAwE;AACxE,uCAAsE;AAItE,oCAAqE;AAErE,2CAAoD;AAEpD,8BAA2B;AAE3B,MAAM,aAAa,GAAG;IACpB,SAAS;IACT,gBAAgB;IAChB,aAAa;IACb,SAAS;IACT,0BAA0B;IAC1B,cAAc;IACd,KAAK;IACL,aAAa;IACb,cAAc;IACd,eAAe;IACf,gBAAgB;IAChB,YAAY;IACZ,oBAAoB;IACpB,iBAAiB;IACjB,OAAO,CAAC,uDAAuD;CAChE,CAAC;AA2CF;;;GAGG;AACH,MAAa,kBAAmB,SAAQ,0BAAuC;IAQ7E;;;;;;;OAOG;IACH,YACE,UAAsB,EACtB,GAAyB,EACzB,MAA+B,EAC/B,OAA0B;QAE1B,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAE3B,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAAyC;QACvF,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAC7B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAA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AA0B;IAC9C,IAAI,CAAC,gBAAQ,CAAC,KAAK,CAAC,IAAK,KAAa,CAAC,SAAS,KAAK,UAAU,EAAE;QAC/D,OAAO,KAAK,CAAC;KACd;IAED,MAAM,QAAQ,GAAa,EAAE,CAAC;IAE9B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;QACpC,IAAI,UAAU,KAAK,OAAQ,KAAkB,CAAC,GAAG,CAAC,EAAE;YAClD,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,WAAI,CAAC,MAAM,CAAE,KAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;SAC5D;aAAM,IAAK,KAAkB,CAAC,GAAG,CAAC,CAAC,SAAS,KAAK,MAAM,EAAE;YACxD,QAAQ,CAAC,GAAG,CAAC,GAAI,KAAkB,CAAC,GAAG,CAAC,CAAC;SAC1C;aAAM;YACL,QAAQ,CAAC,GAAG,CAAC,GAAG,YAAY,CAAE,KAAkB,CAAC,GAAG,CAAC,CAAC,CAAC;SACxD;KACF;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,yBAAa,CAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,WAAW,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/operation.js b/node_modules/mongodb/lib/operations/operation.js new file mode 100644 index 0000000..f7d7c6c --- /dev/null +++ b/node_modules/mongodb/lib/operations/operation.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defineAspects = exports.AbstractOperation = exports.Aspect = void 0; +const read_preference_1 = require("../read_preference"); +const bson_1 = require("../bson"); +exports.Aspect = { + READ_OPERATION: Symbol('READ_OPERATION'), + WRITE_OPERATION: Symbol('WRITE_OPERATION'), + RETRYABLE: Symbol('RETRYABLE'), + EXPLAINABLE: Symbol('EXPLAINABLE'), + SKIP_COLLATION: Symbol('SKIP_COLLATION'), + CURSOR_CREATING: Symbol('CURSOR_CREATING') +}; +/** @internal */ +const kSession = Symbol('session'); +/** + * This class acts as a parent class for any operation and is responsible for setting this.options, + * as well as setting and getting a session. + * Additionally, this class implements `hasAspect`, which determines whether an operation has + * a specific aspect. + * @internal + */ +class AbstractOperation { + constructor(options = {}) { + var _a; + this.readPreference = this.hasAspect(exports.Aspect.WRITE_OPERATION) + ? read_preference_1.ReadPreference.primary + : (_a = read_preference_1.ReadPreference.fromOptions(options)) !== null && _a !== void 0 ? _a : read_preference_1.ReadPreference.primary; + // Pull the BSON serialize options from the already-resolved options + this.bsonOptions = bson_1.resolveBSONOptions(options); + if (options.session) { + this[kSession] = options.session; + } + this.options = options; + this.bypassPinningCheck = !!options.bypassPinningCheck; + } + hasAspect(aspect) { + const ctor = this.constructor; + if (ctor.aspects == null) { + return false; + } + return ctor.aspects.has(aspect); + } + get session() { + return this[kSession]; + } + get canRetryRead() { + return true; + } + get canRetryWrite() { + return true; + } +} +exports.AbstractOperation = AbstractOperation; +function defineAspects(operation, aspects) { + if (!Array.isArray(aspects) && !(aspects instanceof Set)) { + aspects = [aspects]; + } + aspects = new Set(aspects); + Object.defineProperty(operation, 'aspects', { + value: aspects, + writable: false + }); + return aspects; +} +exports.defineAspects = defineAspects; +//# sourceMappingURL=operation.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/operation.js.map b/node_modules/mongodb/lib/operations/operation.js.map new file mode 100644 index 0000000..be2f2ce --- /dev/null +++ b/node_modules/mongodb/lib/operations/operation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"operation.js","sourceRoot":"","sources":["../../src/operations/operation.ts"],"names":[],"mappings":";;;AAAA,wDAAwE;AAExE,kCAA6E;AAIhE,QAAA,MAAM,GAAG;IACpB,cAAc,EAAE,MAAM,CAAC,gBAAgB,CAAC;IACxC,eAAe,EAAE,MAAM,CAAC,iBAAiB,CAAC;IAC1C,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC;IAC9B,WAAW,EAAE,MAAM,CAAC,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AExC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,YAAY,GAAG,CAAC,EAAE;QACxD,OAAO,GAAG,CAAC,OAAO,CAAC,CAAC;KACrB;IAED,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;IAC3B,MAAM,CAAC,cAAc,CAAC,SAAS,EAAE,SAAS,EAAE;QAC1C,KAAK,EAAE,OAAO;QACd,QAAQ,EAAE,KAAK;KAChB,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AACjB,CAAC;AAfD,sCAeC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/options_operation.js b/node_modules/mongodb/lib/operations/options_operation.js new file mode 100644 index 0000000..ab6d4c8 --- /dev/null +++ b/node_modules/mongodb/lib/operations/options_operation.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OptionsOperation = void 0; +const operation_1 = require("./operation"); +const error_1 = require("../error"); +/** @internal */ +class OptionsOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + execute(server, session, callback) { + const coll = this.collection; + coll.s.db + .listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }) + .toArray((err, collections) => { + if (err || !collections) + return callback(err); + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`)); + } + callback(err, collections[0].options); + }); + } +} +exports.OptionsOperation = OptionsOperation; +//# sourceMappingURL=options_operation.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/options_operation.js.map b/node_modules/mongodb/lib/operations/options_operation.js.map new file mode 100644 index 0000000..d009af4 --- /dev/null +++ b/node_modules/mongodb/lib/operations/options_operation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"options_operation.js","sourceRoot":"","sources":["../../src/operations/options_operation.ts"],"names":[],"mappings":";;;AAAA,2CAAkE;AAClE,oCAAyC;AAOzC,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,6BAA2B;IAI/D,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA4B;QAC1E,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAE7B,IAAI,CAAC,CAAC,CAAC,EAAE;aACN,eAAe,CACd,EAAE,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE,EAC7B,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CACnF;aACA,OAAO,CAAC,CAAC,GAAG,EAAE,WAAW,EAAE,EAAE;YAC5B,IAAI,GAAG,IAAI,CAAC,WAAW;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9C,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC5B,kBAAkB;gBAClB,OAAO,QAAQ,CAAC,IAAI,qBAAa,CAAC,cAAc,IAAI,CAAC,SAAS,YAAY,CAAC,CAAC,CAAC;aAC9E;YAED,QAAQ,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;QACxC,CAAC,CAAC,CAAC;IACP,CAAC;CACF;AA5BD,4CA4BC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/profiling_level.js b/node_modules/mongodb/lib/operations/profiling_level.js new file mode 100644 index 0000000..8d40268 --- /dev/null +++ b/node_modules/mongodb/lib/operations/profiling_level.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProfilingLevelOperation = void 0; +const command_1 = require("./command"); +const error_1 = require("../error"); +/** @internal */ +class ProfilingLevelOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + execute(server, session, callback) { + super.executeCommand(server, session, { profile: -1 }, (err, doc) => { + if (err == null && doc.ok === 1) { + const was = doc.was; + if (was === 0) + return callback(undefined, 'off'); + if (was === 1) + return callback(undefined, 'slow_only'); + if (was === 2) + return callback(undefined, 'all'); + // TODO(NODE-3483) + return callback(new error_1.MongoRuntimeError(`Illegal profiling level value ${was}`)); + } + else { + // TODO(NODE-3483): Consider MongoUnexpectedServerResponseError + err != null ? callback(err) : callback(new error_1.MongoRuntimeError('Error with profile command')); + } + }); + } +} +exports.ProfilingLevelOperation = ProfilingLevelOperation; +//# sourceMappingURL=profiling_level.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/profiling_level.js.map b/node_modules/mongodb/lib/operations/profiling_level.js.map new file mode 100644 index 0000000..a95d93b --- /dev/null +++ b/node_modules/mongodb/lib/operations/profiling_level.js.map @@ -0,0 +1 @@ +{"version":3,"file":"profiling_level.js","sourceRoot":"","sources":["../../src/operations/profiling_level.ts"],"names":[],"mappings":";;;AAAA,uCAAsE;AAKtE,oCAA6C;AAK7C,gBAAgB;AAChB,MAAa,uBAAwB,SAAQ,0BAAwB;IAGnE,YAAY,EAAM,EAAE,OAA8B;QAChD,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA0B;QACxE,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YAClE,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,CAAC,EAAE,KAAK,CAAC,EAAE;gBAC/B,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC;gBACpB,IAAI,GAAG,KAAK,CAAC;oBAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;gBACjD,IAAI,GAAG,KAAK,CAAC;oBAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;gBACvD,IAAI,GAAG,KAAK,CAAC;oBAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;gBACjD,kBAAkB;gBAClB,OAAO,QAAQ,CAAC,IAAI,yBAAiB,CAAC,iCAAiC,GAAG,EAAE,CAAC,CAAC,CAAC;aAChF;iBAAM;gBACL,+DAA+D;gBAC/D,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,yBAAiB,CAAC,4BAA4B,CAAC,CAAC,CAAC;aAC7F;QACH,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAvBD,0DAuBC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/remove_user.js b/node_modules/mongodb/lib/operations/remove_user.js new file mode 100644 index 0000000..4b3705f --- /dev/null +++ b/node_modules/mongodb/lib/operations/remove_user.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RemoveUserOperation = void 0; +const operation_1 = require("./operation"); +const command_1 = require("./command"); +/** @internal */ +class RemoveUserOperation extends command_1.CommandOperation { + constructor(db, username, options) { + super(db, options); + this.options = options; + this.username = username; + } + execute(server, session, callback) { + super.executeCommand(server, session, { dropUser: this.username }, err => { + callback(err, err ? false : true); + }); + } +} +exports.RemoveUserOperation = RemoveUserOperation; +operation_1.defineAspects(RemoveUserOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=remove_user.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/remove_user.js.map b/node_modules/mongodb/lib/operations/remove_user.js.map new file mode 100644 index 0000000..a4239ab --- /dev/null +++ b/node_modules/mongodb/lib/operations/remove_user.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remove_user.js","sourceRoot":"","sources":["../../src/operations/remove_user.ts"],"names":[],"mappings":";;;AAAA,2CAAoD;AACpD,uCAAsE;AAStE,gBAAgB;AAChB,MAAa,mBAAoB,SAAQ,0BAAyB;IAIhE,YAAY,EAAM,EAAE,QAAgB,EAAE,OAA0B;QAC9D,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA2B;QACzE,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,EAAE,GAAG,CAAC,EAAE;YACvE,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QACpC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAfD,kDAeC;AAED,yBAAa,CAAC,mBAAmB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/rename.js b/node_modules/mongodb/lib/operations/rename.js new file mode 100644 index 0000000..498cc6b --- /dev/null +++ b/node_modules/mongodb/lib/operations/rename.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RenameOperation = void 0; +const utils_1 = require("../utils"); +const run_command_1 = require("./run_command"); +const operation_1 = require("./operation"); +const collection_1 = require("../collection"); +const error_1 = require("../error"); +/** @internal */ +class RenameOperation extends run_command_1.RunAdminCommandOperation { + constructor(collection, newName, options) { + // Check the collection name + utils_1.checkCollectionName(newName); + // Build the command + const renameCollection = collection.namespace; + const toCollection = collection.s.namespace.withCollection(newName).toString(); + const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; + const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; + super(collection, cmd, options); + this.options = options; + this.collection = collection; + this.newName = newName; + } + execute(server, session, callback) { + const coll = this.collection; + super.execute(server, session, (err, doc) => { + if (err) + return callback(err); + // We have an error + if (doc.errmsg) { + return callback(new error_1.MongoServerError(doc)); + } + let newColl; + try { + newColl = new collection_1.Collection(coll.s.db, this.newName, coll.s.options); + } + catch (err) { + return callback(err); + } + return callback(undefined, newColl); + }); + } +} +exports.RenameOperation = RenameOperation; +operation_1.defineAspects(RenameOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=rename.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/rename.js.map b/node_modules/mongodb/lib/operations/rename.js.map new file mode 100644 index 0000000..3a47354 --- /dev/null +++ b/node_modules/mongodb/lib/operations/rename.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rename.js","sourceRoot":"","sources":["../../src/operations/rename.ts"],"names":[],"mappings":";;;AAAA,oCAAyD;AACzD,+CAAyD;AACzD,2CAAoD;AAEpD,8CAA2C;AAE3C,oCAA4C;AAY5C,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,sCAAwB;IAK3D,YAAY,UAAsB,EAAE,OAAe,EAAE,OAAsB;QACzE,4BAA4B;QAC5B,2BAAmB,CAAC,OAAO,CAAC,CAAC;QAE7B,oBAAoB;QACpB,MAAM,gBAAgB,GAAG,UAAU,CAAC,SAAS,CAAC;QAC9C,MAAM,YAAY,GAAG,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC/E,MAAM,UAAU,GAAG,OAAO,OAAO,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC;QACxF,MAAM,GAAG,GAAG,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,EAAE,EAAE,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC;QAE7F,KAAK,CAAC,UAAU,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;QAChC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA8B;QAC5E,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAE7B,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YAC1C,IAAI,GAAG;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9B,mBAAmB;YACnB,IAAI,GAAG,CAAC,MAAM,EAAE;gBACd,OAAO,QAAQ,CAAC,IAAI,wBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC;aAC5C;YAED,IAAI,OAA6B,CAAC;YAClC,IAAI;gBACF,OAAO,GAAG,IAAI,uBAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;aACnE;YAAC,OAAO,GAAG,EAAE;gBACZ,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;aACtB;YAED,OAAO,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAzCD,0CAyCC;AAED,yBAAa,CAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/run_command.js b/node_modules/mongodb/lib/operations/run_command.js new file mode 100644 index 0000000..c3be601 --- /dev/null +++ b/node_modules/mongodb/lib/operations/run_command.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RunAdminCommandOperation = exports.RunCommandOperation = void 0; +const command_1 = require("./command"); +const utils_1 = require("../utils"); +/** @internal */ +class RunCommandOperation extends command_1.CommandOperation { + constructor(parent, command, options) { + super(parent, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.command = command; + } + execute(server, session, callback) { + const command = this.command; + this.executeCommand(server, session, command, callback); + } +} +exports.RunCommandOperation = RunCommandOperation; +class RunAdminCommandOperation extends RunCommandOperation { + constructor(parent, command, options) { + super(parent, command, options); + this.ns = new utils_1.MongoDBNamespace('admin'); + } +} +exports.RunAdminCommandOperation = RunAdminCommandOperation; +//# sourceMappingURL=run_command.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/run_command.js.map b/node_modules/mongodb/lib/operations/run_command.js.map new file mode 100644 index 0000000..2723160 --- /dev/null +++ b/node_modules/mongodb/lib/operations/run_command.js.map @@ -0,0 +1 @@ +{"version":3,"file":"run_command.js","sourceRoot":"","sources":["../../src/operations/run_command.ts"],"names":[],"mappings":";;;AAAA,uCAAuF;AACvF,oCAAsD;AAQtD,gBAAgB;AAChB,MAAa,mBAAkC,SAAQ,0BAAmB;IAIxE,YAAY,MAAmC,EAAE,OAAiB,EAAE,OAA2B;QAC7F,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAAkB;QAChE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC7B,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC1D,CAAC;CACF;AAdD,kDAcC;AAED,MAAa,wBAAuC,SAAQ,mBAAsB;IAChF,YAAY,MAAmC,EAAE,OAAiB,EAAE,OAA2B;QAC7F,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAChC,IAAI,CAAC,EAAE,GAAG,IAAI,wBAAgB,CAAC,OAAO,CAAC,CAAC;IAC1C,CAAC;CACF;AALD,4DAKC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/set_profiling_level.js b/node_modules/mongodb/lib/operations/set_profiling_level.js new file mode 100644 index 0000000..0d6305f --- /dev/null +++ b/node_modules/mongodb/lib/operations/set_profiling_level.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SetProfilingLevelOperation = exports.ProfilingLevel = void 0; +const command_1 = require("./command"); +const utils_1 = require("../utils"); +const error_1 = require("../error"); +const levelValues = new Set(['off', 'slow_only', 'all']); +/** @public */ +exports.ProfilingLevel = Object.freeze({ + off: 'off', + slowOnly: 'slow_only', + all: 'all' +}); +/** @internal */ +class SetProfilingLevelOperation extends command_1.CommandOperation { + constructor(db, level, options) { + super(db, options); + this.options = options; + switch (level) { + case exports.ProfilingLevel.off: + this.profile = 0; + break; + case exports.ProfilingLevel.slowOnly: + this.profile = 1; + break; + case exports.ProfilingLevel.all: + this.profile = 2; + break; + default: + this.profile = 0; + break; + } + this.level = level; + } + execute(server, session, callback) { + const level = this.level; + if (!levelValues.has(level)) { + return callback(new error_1.MongoInvalidArgumentError(`Profiling level must be one of "${utils_1.enumToString(exports.ProfilingLevel)}"`)); + } + // TODO(NODE-3483): Determine error to put here + super.executeCommand(server, session, { profile: this.profile }, (err, doc) => { + if (err == null && doc.ok === 1) + return callback(undefined, level); + return err != null + ? callback(err) + : callback(new error_1.MongoRuntimeError('Error with profile command')); + }); + } +} +exports.SetProfilingLevelOperation = SetProfilingLevelOperation; +//# sourceMappingURL=set_profiling_level.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/set_profiling_level.js.map b/node_modules/mongodb/lib/operations/set_profiling_level.js.map new file mode 100644 index 0000000..699b3e4 --- /dev/null +++ b/node_modules/mongodb/lib/operations/set_profiling_level.js.map @@ -0,0 +1 @@ +{"version":3,"file":"set_profiling_level.js","sourceRoot":"","sources":["../../src/operations/set_profiling_level.ts"],"names":[],"mappings":";;;AAAA,uCAAsE;AAEtE,oCAAwC;AAIxC,oCAAwE;AACxE,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;AAEzD,cAAc;AACD,QAAA,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC;IAC1C,GAAG,EAAE,KAAK;IACV,QAAQ,EAAE,WAAW;IACrB,GAAG,EAAE,KAAK;CACF,CAAC,CAAC;AAQZ,gBAAgB;AAChB,MAAa,0BAA2B,SAAQ,0BAAgC;IAK9E,YAAY,EAAM,EAAE,KAAqB,EAAE,OAAiC;QAC1E,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,QAAQ,KAAK,EAAE;YACb,KAAK,sBAAc,CAAC,GAAG;gBACrB,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;YACR,KAAK,sBAAc,CAAC,QAAQ;gBAC1B,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;YACR,KAAK,sBAAc,CAAC,GAAG;gBACrB,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;YACR;gBACE,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;SACT;QAED,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAAkC;QAChF,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;QAEzB,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,QAAQ,CACb,IAAI,iCAAyB,CAC3B,mCAAmC,oBAAY,CAAC,sBAAc,CAAC,GAAG,CACnE,CACF,CAAC;SACH;QAED,+CAA+C;QAC/C,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YAC5E,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,CAAC,EAAE,KAAK,CAAC;gBAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;YACnE,OAAO,GAAG,IAAI,IAAI;gBAChB,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC;gBACf,CAAC,CAAC,QAAQ,CAAC,IAAI,yBAAiB,CAAC,4BAA4B,CAAC,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA7CD,gEA6CC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/stats.js b/node_modules/mongodb/lib/operations/stats.js new file mode 100644 index 0000000..5cf92bc --- /dev/null +++ b/node_modules/mongodb/lib/operations/stats.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DbStatsOperation = exports.CollStatsOperation = void 0; +const operation_1 = require("./operation"); +const command_1 = require("./command"); +/** + * Get all the collection statistics. + * @internal + */ +class CollStatsOperation extends command_1.CommandOperation { + /** + * Construct a Stats operation. + * + * @param collection - Collection instance + * @param options - Optional settings. See Collection.prototype.stats for a list of options. + */ + constructor(collection, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collectionName = collection.collectionName; + } + execute(server, session, callback) { + const command = { collStats: this.collectionName }; + if (this.options.scale != null) { + command.scale = this.options.scale; + } + super.executeCommand(server, session, command, callback); + } +} +exports.CollStatsOperation = CollStatsOperation; +/** @internal */ +class DbStatsOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + execute(server, session, callback) { + const command = { dbStats: true }; + if (this.options.scale != null) { + command.scale = this.options.scale; + } + super.executeCommand(server, session, command, callback); + } +} +exports.DbStatsOperation = DbStatsOperation; +operation_1.defineAspects(CollStatsOperation, [operation_1.Aspect.READ_OPERATION]); +operation_1.defineAspects(DbStatsOperation, [operation_1.Aspect.READ_OPERATION]); +//# sourceMappingURL=stats.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/stats.js.map b/node_modules/mongodb/lib/operations/stats.js.map new file mode 100644 index 0000000..bfc1a8b --- /dev/null +++ b/node_modules/mongodb/lib/operations/stats.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stats.js","sourceRoot":"","sources":["../../src/operations/stats.ts"],"names":[],"mappings":";;;AAAA,2CAAoD;AACpD,uCAAsE;AActE;;;GAGG;AACH,MAAa,kBAAmB,SAAQ,0BAA0B;IAIhE;;;;;OAKG;IACH,YAAY,UAAsB,EAAE,OAA0B;QAC5D,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,cAAc,CAAC;IAClD,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA6B;QAC3E,MAAM,OAAO,GAAa,EAAE,SAAS,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC;QAC7D,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,IAAI,IAAI,EAAE;YAC9B,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;SACpC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC3D,CAAC;CACF;AAxBD,gDAwBC;AAQD,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,0BAA0B;IAG9D,YAAY,EAAM,EAAE,OAAuB;QACzC,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,QAA4B;QAC1E,MAAM,OAAO,GAAa,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC5C,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,IAAI,IAAI,EAAE;YAC9B,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;SACpC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC3D,CAAC;CACF;AAhBD,4CAgBC;AAiMD,yBAAa,CAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,cAAc,CAAC,CAAC,CAAC;AAC3D,yBAAa,CAAC,gBAAgB,EAAE,CAAC,kBAAM,CAAC,cAAc,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/update.js b/node_modules/mongodb/lib/operations/update.js new file mode 100644 index 0000000..9c35629 --- /dev/null +++ b/node_modules/mongodb/lib/operations/update.js @@ -0,0 +1,195 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.makeUpdateStatement = exports.ReplaceOneOperation = exports.UpdateManyOperation = exports.UpdateOneOperation = exports.UpdateOperation = void 0; +const operation_1 = require("./operation"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const error_1 = require("../error"); +/** @internal */ +class UpdateOperation extends command_1.CommandOperation { + constructor(ns, statements, options) { + super(undefined, options); + this.options = options; + this.ns = ns; + this.statements = statements; + } + get canRetryWrite() { + if (super.canRetryWrite === false) { + return false; + } + return this.statements.every(op => op.multi == null || op.multi === false); + } + execute(server, session, callback) { + var _a; + const options = (_a = this.options) !== null && _a !== void 0 ? _a : {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + update: this.ns.collection, + updates: this.statements, + ordered + }; + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + if (options.let) { + command.let = options.let; + } + const statementWithCollation = this.statements.find(statement => !!statement.collation); + if (utils_1.collationNotSupported(server, options) || + (statementWithCollation && utils_1.collationNotSupported(server, statementWithCollation))) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support collation`)); + return; + } + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite || utils_1.maxWireVersion(server) < 5) { + if (this.statements.find((o) => o.hint)) { + callback(new error_1.MongoCompatibilityError(`Servers < 3.4 do not support hint on update`)); + return; + } + } + if (this.explain && utils_1.maxWireVersion(server) < 3) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on update`)); + return; + } + if (this.statements.some(statement => !!statement.arrayFilters) && utils_1.maxWireVersion(server) < 6) { + callback(new error_1.MongoCompatibilityError('Option "arrayFilters" is only supported on MongoDB 3.6+')); + return; + } + super.executeCommand(server, session, command, callback); + } +} +exports.UpdateOperation = UpdateOperation; +/** @internal */ +class UpdateOneOperation extends UpdateOperation { + constructor(collection, filter, update, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: false })], options); + if (!utils_1.hasAtomicOperators(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || !res) + return callback(err); + if (this.explain != null) + return callback(undefined, res); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} +exports.UpdateOneOperation = UpdateOneOperation; +/** @internal */ +class UpdateManyOperation extends UpdateOperation { + constructor(collection, filter, update, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: true })], options); + if (!utils_1.hasAtomicOperators(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || !res) + return callback(err); + if (this.explain != null) + return callback(undefined, res); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} +exports.UpdateManyOperation = UpdateManyOperation; +/** @internal */ +class ReplaceOneOperation extends UpdateOperation { + constructor(collection, filter, replacement, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, replacement, { ...options, multi: false })], options); + if (utils_1.hasAtomicOperators(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || !res) + return callback(err); + if (this.explain != null) + return callback(undefined, res); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} +exports.ReplaceOneOperation = ReplaceOneOperation; +function makeUpdateStatement(filter, update, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Selector must be a valid JavaScript object'); + } + if (update == null || typeof update !== 'object') { + throw new error_1.MongoInvalidArgumentError('Document must be a valid JavaScript object'); + } + const op = { q: filter, u: update }; + if (typeof options.upsert === 'boolean') { + op.upsert = options.upsert; + } + if (options.multi) { + op.multi = options.multi; + } + if (options.hint) { + op.hint = options.hint; + } + if (options.arrayFilters) { + op.arrayFilters = options.arrayFilters; + } + if (options.collation) { + op.collation = options.collation; + } + return op; +} +exports.makeUpdateStatement = makeUpdateStatement; +operation_1.defineAspects(UpdateOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.SKIP_COLLATION]); +operation_1.defineAspects(UpdateOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +operation_1.defineAspects(UpdateManyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +operation_1.defineAspects(ReplaceOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.SKIP_COLLATION +]); +//# sourceMappingURL=update.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/update.js.map b/node_modules/mongodb/lib/operations/update.js.map new file mode 100644 index 0000000..306eaff --- /dev/null +++ b/node_modules/mongodb/lib/operations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AI,OAAO,CAAC,KAAK,EAAE;QACjB,EAAE,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;KAC1B;IAED,IAAI,OAAO,CAAC,IAAI,EAAE;QAChB,EAAE,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;KACxB;IAED,IAAI,OAAO,CAAC,YAAY,EAAE;QACxB,EAAE,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;KACxC;IAED,IAAI,OAAO,CAAC,SAAS,EAAE;QACrB,EAAE,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;KAClC;IAED,OAAO,EAAE,CAAC;AACZ,CAAC;AAnCD,kDAmCC;AAED,yBAAa,CAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,eAAe,EAAE,kBAAM,CAAC,cAAc,CAAC,CAAC,CAAC;AAClG,yBAAa,CAAC,kBAAkB,EAAE;IAChC,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC;AACH,yBAAa,CAAC,mBAAmB,EAAE;IACjC,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC;AACH,yBAAa,CAAC,mBAAmB,EAAE;IACjC,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/validate_collection.js b/node_modules/mongodb/lib/operations/validate_collection.js new file mode 100644 index 0000000..c797524 --- /dev/null +++ b/node_modules/mongodb/lib/operations/validate_collection.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValidateCollectionOperation = void 0; +const command_1 = require("./command"); +const error_1 = require("../error"); +/** @internal */ +class ValidateCollectionOperation extends command_1.CommandOperation { + constructor(admin, collectionName, options) { + // Decorate command with extra options + const command = { validate: collectionName }; + const keys = Object.keys(options); + for (let i = 0; i < keys.length; i++) { + if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== 'session') { + command[keys[i]] = options[keys[i]]; + } + } + super(admin.s.db, options); + this.options = options; + this.command = command; + this.collectionName = collectionName; + } + execute(server, session, callback) { + const collectionName = this.collectionName; + super.executeCommand(server, session, this.command, (err, doc) => { + if (err != null) + return callback(err); + // TODO(NODE-3483): Replace these with MongoUnexpectedServerResponseError + if (doc.ok === 0) + return callback(new error_1.MongoRuntimeError('Error with validate command')); + if (doc.result != null && typeof doc.result !== 'string') + return callback(new error_1.MongoRuntimeError('Error with validation data')); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new error_1.MongoRuntimeError(`Invalid collection ${collectionName}`)); + if (doc.valid != null && !doc.valid) + return callback(new error_1.MongoRuntimeError(`Invalid collection ${collectionName}`)); + return callback(undefined, doc); + }); + } +} +exports.ValidateCollectionOperation = ValidateCollectionOperation; +//# sourceMappingURL=validate_collection.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/operations/validate_collection.js.map b/node_modules/mongodb/lib/operations/validate_collection.js.map new file mode 100644 index 0000000..517c29b --- /dev/null +++ b/node_modules/mongodb/lib/operations/validate_collection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validate_collection.js","sourceRoot":"","sources":["../../src/operations/validate_collection.ts"],"names":[],"mappings":";;;AAAA,uCAAsE;AAMtE,oCAA6C;AAQ7C,gBAAgB;AAChB,MAAa,2BAA4B,SAAQ,0BAA0B;IAKzE,YAAY,KAAY,EAAE,cAAsB,EAAE,OAAkC;QAClF,sCAAsC;QACtC,MAAM,OAAO,GAAa,EAAE,QAAQ,EAAE,cAAc,EAAE,CAAC;QACvD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAClC,KAAK,IAAI,CAAC,GAAG,CAA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ACrE,OAAO,QAAQ,CAAC,IAAI,yBAAiB,CAAC,sBAAsB,cAAc,EAAE,CAAC,CAAC,CAAC;YACjF,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK;gBACjC,OAAO,QAAQ,CAAC,IAAI,yBAAiB,CAAC,sBAAsB,cAAc,EAAE,CAAC,CAAC,CAAC;YAEjF,OAAO,QAAQ,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;QAClC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAvCD,kEAuCC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/promise_provider.js b/node_modules/mongodb/lib/promise_provider.js new file mode 100644 index 0000000..e76480a --- /dev/null +++ b/node_modules/mongodb/lib/promise_provider.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PromiseProvider = void 0; +const error_1 = require("./error"); +/** @internal */ +const kPromise = Symbol('promise'); +const store = { + [kPromise]: undefined +}; +/** + * Global promise store allowing user-provided promises + * @public + */ +class PromiseProvider { + /** Validates the passed in promise library */ + static validate(lib) { + if (typeof lib !== 'function') + throw new error_1.MongoInvalidArgumentError(`Promise must be a function, got ${lib}`); + return !!lib; + } + /** Sets the promise library */ + static set(lib) { + if (!PromiseProvider.validate(lib)) { + // validate + return; + } + store[kPromise] = lib; + } + /** Get the stored promise library, or resolves passed in */ + static get() { + return store[kPromise]; + } +} +exports.PromiseProvider = PromiseProvider; +PromiseProvider.set(global.Promise); +//# sourceMappingURL=promise_provider.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/promise_provider.js.map b/node_modules/mongodb/lib/promise_provider.js.map new file mode 100644 index 0000000..703bee2 --- /dev/null +++ b/node_modules/mongodb/lib/promise_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"promise_provider.js","sourceRoot":"","sources":["../src/promise_provider.ts"],"names":[],"mappings":";;;AAAA,mCAAoD;AAEpD,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AAMnC,MAAM,KAAK,GAAiB;IAC1B,CAAC,QAAQ,CAAC,EAAE,SAAS;CACtB,CAAC;AAEF;;;GAGG;AACH,MAAa,eAAe;IAC1B,8CAA8C;IAC9C,MAAM,CAAC,QAAQ,CAAC,GAAY;QAC1B,IAAI,OAAO,GAAG,KAAK,UAAU;YAC3B,MAAM,IAAI,iCAAyB,CAAC,mCAAmC,GAAG,EAAE,CAAC,CAAC;QAChF,OAAO,CAAC,CAAC,GAAG,CAAC;IACf,CAAC;IAED,+BAA+B;IAC/B,MAAM,CAAC,GAAG,CAAC,GAAuB;QAChC,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;YAClC,WAAW;YACX,OAAO;SACR;QACD,KAAK,CAAC,QAAQ,CAAC,GAAG,GAAG,CAAC;IACxB,CAAC;IAED,4DAA4D;IAC5D,MAAM,CAAC,GAAG;QACR,OAAO,KAAK,CAAC,QAAQ,CAAuB,CAAC;IAC/C,CAAC;CACF;AArBD,0CAqBC;AAED,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/read_concern.js b/node_modules/mongodb/lib/read_concern.js new file mode 100644 index 0000000..b4ea201 --- /dev/null +++ b/node_modules/mongodb/lib/read_concern.js @@ -0,0 +1,73 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReadConcern = exports.ReadConcernLevel = void 0; +/** @public */ +exports.ReadConcernLevel = Object.freeze({ + local: 'local', + majority: 'majority', + linearizable: 'linearizable', + available: 'available', + snapshot: 'snapshot' +}); +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @public + * + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html + */ +class ReadConcern { + /** Constructs a ReadConcern from the read concern level.*/ + constructor(level) { + var _a; + /** + * A spec test exists that allows level to be any string. + * "invalid readConcern with out stage" + * @see ./test/spec/crud/v2/aggregate-out-readConcern.json + * @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#unknown-levels-and-additional-options-for-string-based-readconcerns + */ + this.level = (_a = exports.ReadConcernLevel[level]) !== null && _a !== void 0 ? _a : level; + } + /** + * Construct a ReadConcern given an options object. + * + * @param options - The options object from which to extract the write concern. + */ + static fromOptions(options) { + if (options == null) { + return; + } + if (options.readConcern) { + const { readConcern } = options; + if (readConcern instanceof ReadConcern) { + return readConcern; + } + else if (typeof readConcern === 'string') { + return new ReadConcern(readConcern); + } + else if ('level' in readConcern && readConcern.level) { + return new ReadConcern(readConcern.level); + } + } + if (options.level) { + return new ReadConcern(options.level); + } + } + static get MAJORITY() { + return exports.ReadConcernLevel.majority; + } + static get AVAILABLE() { + return exports.ReadConcernLevel.available; + } + static get LINEARIZABLE() { + return exports.ReadConcernLevel.linearizable; + } + static get SNAPSHOT() { + return exports.ReadConcernLevel.snapshot; + } + toJSON() { + return { level: this.level }; + } +} +exports.ReadConcern = ReadConcern; +//# sourceMappingURL=read_concern.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/read_concern.js.map b/node_modules/mongodb/lib/read_concern.js.map new file mode 100644 index 0000000..d92bca1 --- /dev/null +++ b/node_modules/mongodb/lib/read_concern.js.map @@ -0,0 +1 @@ +{"version":3,"file":"read_concern.js","sourceRoot":"","sources":["../src/read_concern.ts"],"names":[],"mappings":";;;AAEA,cAAc;AACD,QAAA,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5C,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,UAAU;IACpB,YAAY,EAAE,cAAc;IAC5B,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;CACZ,CAAC,CAAC;AAQZ;;;;;;GAMG;AACH,MAAa,WAAW;IAGtB,2DAA2D;IAC3D,YAAY,KAAuB;;QACjC;;;;;WAKG;QACH,IAAI,CAAC,KAAK,GAAG,MAAA,wBAAgB,CAAC,KAAK,CAAC,mCAAI,KAAK,CAAC;IAChD,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,WAAW,CAAC,OAGlB;QACC,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO;SACR;QAED,IAAI,OAAO,CAAC,WAAW,EAAE;YACvB,MAAM,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;YAChC,IAAI,WAAW,YAAY,WAAW,EAAE;gBACtC,OAAO,WAAW,CAAC;aACpB;iBAAM,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;gBAC1C,OAAO,IAAI,WAAW,CAAC,WAAW,CAAC,CAAC;aACrC;iBAAM,IAAI,OAAO,IAAI,WAAW,IAAI,WAAW,CAAC,KAAK,EAAE;gBACtD,OAAO,IAAI,WAAW,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;aAC3C;SACF;QAED,IAAI,OAAO,CAAC,KAAK,EAAE;YACjB,OAAO,IAAI,WAAW,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;SACvC;IACH,CAAC;IAED,MAAM,KAAK,QAAQ;QACjB,OAAO,wBAAgB,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,MAAM,KAAK,SAAS;QAClB,OAAO,wBAAgB,CAAC,SAAS,CAAC;IACpC,CAAC;IAED,MAAM,KAAK,YAAY;QACrB,OAAO,wBAAgB,CAAC,YAAY,CAAC;IACvC,CAAC;IAED,MAAM,KAAK,QAAQ;QACjB,OAAO,wBAAgB,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,MAAM;QACJ,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;CACF;AA9DD,kCA8DC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/read_preference.js b/node_modules/mongodb/lib/read_preference.js new file mode 100644 index 0000000..7eee465 --- /dev/null +++ b/node_modules/mongodb/lib/read_preference.js @@ -0,0 +1,194 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReadPreference = exports.ReadPreferenceMode = void 0; +const error_1 = require("./error"); +/** @public */ +exports.ReadPreferenceMode = Object.freeze({ + primary: 'primary', + primaryPreferred: 'primaryPreferred', + secondary: 'secondary', + secondaryPreferred: 'secondaryPreferred', + nearest: 'nearest' +}); +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @public + * + * @see https://docs.mongodb.com/manual/core/read-preference/ + */ +class ReadPreference { + /** + * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. + * @param options - Additional read preference options + */ + constructor(mode, tags, options) { + if (!ReadPreference.isValid(mode)) { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`); + } + if (options == null && typeof tags === 'object' && !Array.isArray(tags)) { + options = tags; + tags = undefined; + } + else if (tags && !Array.isArray(tags)) { + throw new error_1.MongoInvalidArgumentError('ReadPreference tags must be an array'); + } + this.mode = mode; + this.tags = tags; + this.hedge = options === null || options === void 0 ? void 0 : options.hedge; + this.maxStalenessSeconds = undefined; + this.minWireVersion = undefined; + options = options !== null && options !== void 0 ? options : {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new error_1.MongoInvalidArgumentError('maxStalenessSeconds must be a positive integer'); + } + this.maxStalenessSeconds = options.maxStalenessSeconds; + // NOTE: The minimum required wire version is 5 for this read preference. If the existing + // topology has a lower value then a MongoError will be thrown during server selection. + this.minWireVersion = 5; + } + if (this.mode === ReadPreference.PRIMARY) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with tags'); + } + if (this.maxStalenessSeconds) { + throw new error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with maxStalenessSeconds'); + } + if (this.hedge) { + throw new error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with hedge'); + } + } + } + // Support the deprecated `preference` property introduced in the porcelain layer + get preference() { + return this.mode; + } + static fromString(mode) { + return new ReadPreference(mode); + } + /** + * Construct a ReadPreference given an options object. + * + * @param options - The options object from which to extract the read preference. + */ + static fromOptions(options) { + var _a, _b, _c; + if (!options) + return; + const readPreference = (_a = options.readPreference) !== null && _a !== void 0 ? _a : (_b = options.session) === null || _b === void 0 ? void 0 : _b.transaction.options.readPreference; + const readPreferenceTags = options.readPreferenceTags; + if (readPreference == null) { + return; + } + if (typeof readPreference === 'string') { + return new ReadPreference(readPreference, readPreferenceTags); + } + else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + return new ReadPreference(mode, (_c = readPreference.tags) !== null && _c !== void 0 ? _c : readPreferenceTags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds, + hedge: options.hedge + }); + } + } + if (readPreferenceTags) { + readPreference.tags = readPreferenceTags; + } + return readPreference; + } + /** + * Replaces options.readPreference with a ReadPreference instance + */ + static translate(options) { + if (options.readPreference == null) + return options; + const r = options.readPreference; + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r); + } + else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } + else if (!(r instanceof ReadPreference)) { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${r}`); + } + return options; + } + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + static isValid(mode) { + const VALID_MODES = new Set([ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + null + ]); + return VALID_MODES.has(mode); + } + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + isValid(mode) { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); + } + /** + * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire + * + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ + slaveOk() { + const NEEDS_SLAVEOK = new Set([ + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST + ]); + return NEEDS_SLAVEOK.has(this.mode); + } + /** + * Check if the two ReadPreferences are equivalent + * + * @param readPreference - The read preference with which to check equality + */ + equals(readPreference) { + return readPreference.mode === this.mode; + } + /** Return JSON representation */ + toJSON() { + const readPreference = { mode: this.mode }; + if (Array.isArray(this.tags)) + readPreference.tags = this.tags; + if (this.maxStalenessSeconds) + readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + if (this.hedge) + readPreference.hedge = this.hedge; + return readPreference; + } +} +exports.ReadPreference = ReadPreference; +ReadPreference.PRIMARY = exports.ReadPreferenceMode.primary; +ReadPreference.PRIMARY_PREFERRED = exports.ReadPreferenceMode.primaryPreferred; +ReadPreference.SECONDARY = exports.ReadPreferenceMode.secondary; +ReadPreference.SECONDARY_PREFERRED = exports.ReadPreferenceMode.secondaryPreferred; +ReadPreference.NEAREST = exports.ReadPreferenceMode.nearest; +ReadPreference.primary = new ReadPreference(exports.ReadPreferenceMode.primary); +ReadPreference.primaryPreferred = new ReadPreference(exports.ReadPreferenceMode.primaryPreferred); +ReadPreference.secondary = new ReadPreference(exports.ReadPreferenceMode.secondary); +ReadPreference.secondaryPreferred = new ReadPreference(exports.ReadPreferenceMode.secondaryPreferred); +ReadPreference.nearest = new ReadPreference(exports.ReadPreferenceMode.nearest); +//# sourceMappingURL=read_preference.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/read_preference.js.map b/node_modules/mongodb/lib/read_preference.js.map new file mode 100644 index 0000000..95e65af --- /dev/null +++ b/node_modules/mongodb/lib/read_preference.js.map @@ -0,0 +1 @@ +{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/mongodb/lib/sdam/common.js new file mode 100644 index 0000000..f8d382b --- /dev/null +++ b/node_modules/mongodb/lib/sdam/common.js @@ -0,0 +1,61 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports._advanceClusterTime = exports.clearAndRemoveTimerFrom = exports.drainTimerQueue = exports.ServerType = exports.TopologyType = exports.STATE_CONNECTED = exports.STATE_CONNECTING = exports.STATE_CLOSED = exports.STATE_CLOSING = void 0; +// shared state names +exports.STATE_CLOSING = 'closing'; +exports.STATE_CLOSED = 'closed'; +exports.STATE_CONNECTING = 'connecting'; +exports.STATE_CONNECTED = 'connected'; +/** + * An enumeration of topology types we know about + * @public + */ +exports.TopologyType = Object.freeze({ + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown', + LoadBalanced: 'LoadBalanced' +}); +/** + * An enumeration of server types we know about + * @public + */ +exports.ServerType = Object.freeze({ + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown', + LoadBalancer: 'LoadBalancer' +}); +/** @internal */ +function drainTimerQueue(queue) { + queue.forEach(clearTimeout); + queue.clear(); +} +exports.drainTimerQueue = drainTimerQueue; +/** @internal */ +function clearAndRemoveTimerFrom(timer, timers) { + clearTimeout(timer); + return timers.delete(timer); +} +exports.clearAndRemoveTimerFrom = clearAndRemoveTimerFrom; +/** Shared function to determine clusterTime for a given topology or session */ +function _advanceClusterTime(entity, $clusterTime) { + if (entity.clusterTime == null) { + entity.clusterTime = $clusterTime; + } + else { + if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) { + entity.clusterTime = $clusterTime; + } + } +} +exports._advanceClusterTime = _advanceClusterTime; +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/common.js.map b/node_modules/mongodb/lib/sdam/common.js.map new file mode 100644 index 0000000..b54682f --- /dev/null +++ b/node_modules/mongodb/lib/sdam/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/sdam/common.ts"],"names":[],"mappings":";;;AAIA,qBAAqB;AACR,QAAA,aAAa,GAAG,SAAS,CAAC;AAC1B,QAAA,YAAY,GAAG,QAAQ,CAAC;AACxB,QAAA,gBAAgB,GAAG,YAAY,CAAC;AAChC,QAAA,eAAe,GAAG,WAAW,CAAC;AAE3C;;;GAGG;AACU,QAAA,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC;IACxC,MAAM,EAAE,QAAQ;IAChB,mBAAmB,EAAE,qBAAqB;IAC1C,qBAAqB,EAAE,uBAAuB;IAC9C,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,YAAY,EAAE,cAAc;CACpB,CAAC,CAAC;AAKZ;;;GAGG;AACU,QAAA,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;IACtC,UAAU,EAAE,YAAY;IACxB,MAAM,EAAE,QAAQ;IAChB,eAAe,EAAE,iBAAiB;IAClC,SAAS,EAAE,WAAW;IACtB,WAAW,EAAE,aAAa;IAC1B,SAAS,EAAE,WAAW;IACtB,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,YAAY,EAAE,cAAc;CACpB,CAAC,CAAC;AAQZ,gBAAgB;AAChB,SAAgB,eAAe,CAAC,KAAiB;IAC/C,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC5B,KAAK,CAAC,KAAK,EAAE,CAAC;AAChB,CAAC;AAHD,0CAGC;AAED,gBAAgB;AAChB,SAAgB,uBAAuB,CAAC,KAAqB,EAAE,MAAkB;IAC/E,YAAY,CAAC,KAAK,CAAC,CAAC;IACpB,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAHD,0DAGC;AAWD,+EAA+E;AAC/E,SAAgB,mBAAmB,CACjC,MAAgC,EAChC,YAAyB;IAEzB,IAAI,MAAM,CAAC,WAAW,IAAI,IAAI,EAAE;QAC9B,MAAM,CAAC,WAAW,GAAG,YAAY,CAAC;KACnC;SAAM;QACL,IAAI,YAAY,CAAC,WAAW,CAAC,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE;YACxE,MAAM,CAAC,WAAW,GAAG,YAAY,CAAC;SACnC;KACF;AACH,CAAC;AAXD,kDAWC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/events.js b/node_modules/mongodb/lib/sdam/events.js new file mode 100644 index 0000000..6e11b5d --- /dev/null +++ b/node_modules/mongodb/lib/sdam/events.js @@ -0,0 +1,125 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerHeartbeatFailedEvent = exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.TopologyClosedEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.ServerClosedEvent = exports.ServerOpeningEvent = exports.ServerDescriptionChangedEvent = void 0; +/** + * Emitted when server description changes, but does NOT include changes to the RTT. + * @public + * @category Event + */ +class ServerDescriptionChangedEvent { + /** @internal */ + constructor(topologyId, address, previousDescription, newDescription) { + this.topologyId = topologyId; + this.address = address; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} +exports.ServerDescriptionChangedEvent = ServerDescriptionChangedEvent; +/** + * Emitted when server is initialized. + * @public + * @category Event + */ +class ServerOpeningEvent { + /** @internal */ + constructor(topologyId, address) { + this.topologyId = topologyId; + this.address = address; + } +} +exports.ServerOpeningEvent = ServerOpeningEvent; +/** + * Emitted when server is closed. + * @public + * @category Event + */ +class ServerClosedEvent { + /** @internal */ + constructor(topologyId, address) { + this.topologyId = topologyId; + this.address = address; + } +} +exports.ServerClosedEvent = ServerClosedEvent; +/** + * Emitted when topology description changes. + * @public + * @category Event + */ +class TopologyDescriptionChangedEvent { + /** @internal */ + constructor(topologyId, previousDescription, newDescription) { + this.topologyId = topologyId; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} +exports.TopologyDescriptionChangedEvent = TopologyDescriptionChangedEvent; +/** + * Emitted when topology is initialized. + * @public + * @category Event + */ +class TopologyOpeningEvent { + /** @internal */ + constructor(topologyId) { + this.topologyId = topologyId; + } +} +exports.TopologyOpeningEvent = TopologyOpeningEvent; +/** + * Emitted when topology is closed. + * @public + * @category Event + */ +class TopologyClosedEvent { + /** @internal */ + constructor(topologyId) { + this.topologyId = topologyId; + } +} +exports.TopologyClosedEvent = TopologyClosedEvent; +/** + * Emitted when the server monitor’s ismaster command is started - immediately before + * the ismaster command is serialized into raw BSON and written to the socket. + * + * @public + * @category Event + */ +class ServerHeartbeatStartedEvent { + /** @internal */ + constructor(connectionId) { + this.connectionId = connectionId; + } +} +exports.ServerHeartbeatStartedEvent = ServerHeartbeatStartedEvent; +/** + * Emitted when the server monitor’s ismaster succeeds. + * @public + * @category Event + */ +class ServerHeartbeatSucceededEvent { + /** @internal */ + constructor(connectionId, duration, reply) { + this.connectionId = connectionId; + this.duration = duration; + this.reply = reply; + } +} +exports.ServerHeartbeatSucceededEvent = ServerHeartbeatSucceededEvent; +/** + * Emitted when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. + * @public + * @category Event + */ +class ServerHeartbeatFailedEvent { + /** @internal */ + constructor(connectionId, duration, failure) { + this.connectionId = connectionId; + this.duration = duration; + this.failure = failure; + } +} +exports.ServerHeartbeatFailedEvent = ServerHeartbeatFailedEvent; +//# sourceMappingURL=events.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/events.js.map b/node_modules/mongodb/lib/sdam/events.js.map new file mode 100644 index 0000000..ab62978 --- /dev/null +++ b/node_modules/mongodb/lib/sdam/events.js.map @@ -0,0 +1 @@ +{"version":3,"file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,UAAkB;QAC5B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;CACF;AARD,kDAQC;AAED;;;;;;GAMG;AACH,MAAa,2BAA2B;IAItC,gBAAgB;IAChB,YAAY,YAAoB;QAC9B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACnC,CAAC;CACF;AARD,kEAQC;AAED;;;;GAIG;AACH,MAAa,6BAA6B;IAQxC,gBAAgB;IAChB,YAAY,YAAoB,EAAE,QAAgB,EAAE,KAAe;QACjE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF;AAdD,sEAcC;AAED;;;;GAIG;AACH,MAAa,0BAA0B;IAQrC,gBAAgB;IAChB,YAAY,YAAoB,EAAE,QAAgB,EAAE,OAAc;QAChE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAdD,gEAcC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/monitor.js b/node_modules/mongodb/lib/sdam/monitor.js new file mode 100644 index 0000000..c783455 --- /dev/null +++ b/node_modules/mongodb/lib/sdam/monitor.js @@ -0,0 +1,319 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RTTPinger = exports.Monitor = void 0; +const common_1 = require("./common"); +const utils_1 = require("../utils"); +const connect_1 = require("../cmap/connect"); +const connection_1 = require("../cmap/connection"); +const error_1 = require("../error"); +const bson_1 = require("../bson"); +const events_1 = require("./events"); +const server_1 = require("./server"); +const mongo_types_1 = require("../mongo_types"); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kMonitorId = Symbol('monitorId'); +/** @internal */ +const kConnection = Symbol('connection'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kRTTPinger = Symbol('rttPinger'); +/** @internal */ +const kRoundTripTime = Symbol('roundTripTime'); +const STATE_IDLE = 'idle'; +const STATE_MONITORING = 'monitoring'; +const stateTransition = utils_1.makeStateMachine({ + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, STATE_IDLE, common_1.STATE_CLOSED], + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, STATE_MONITORING], + [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, common_1.STATE_CLOSING], + [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, common_1.STATE_CLOSING] +}); +const INVALID_REQUEST_CHECK_STATES = new Set([common_1.STATE_CLOSING, common_1.STATE_CLOSED, STATE_MONITORING]); +function isInCloseState(monitor) { + return monitor.s.state === common_1.STATE_CLOSED || monitor.s.state === common_1.STATE_CLOSING; +} +/** @internal */ +class Monitor extends mongo_types_1.TypedEventEmitter { + constructor(server, options) { + var _a, _b, _c; + super(); + this[kServer] = server; + this[kConnection] = undefined; + this[kCancellationToken] = new mongo_types_1.CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kMonitorId] = undefined; + this.s = { + state: common_1.STATE_CLOSED + }; + this.address = server.description.address; + this.options = Object.freeze({ + connectTimeoutMS: (_a = options.connectTimeoutMS) !== null && _a !== void 0 ? _a : 10000, + heartbeatFrequencyMS: (_b = options.heartbeatFrequencyMS) !== null && _b !== void 0 ? _b : 10000, + minHeartbeatFrequencyMS: (_c = options.minHeartbeatFrequencyMS) !== null && _c !== void 0 ? _c : 500 + }); + const cancellationToken = this[kCancellationToken]; + // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration + const connectOptions = Object.assign({ + id: '', + generation: server.s.pool.generation, + connectionType: connection_1.Connection, + cancellationToken, + hostAddress: server.description.hostAddress + }, options, + // force BSON serialization options + { + raw: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: true + }); + // ensure no authentication is used for monitoring + delete connectOptions.credentials; + if (connectOptions.autoEncrypter) { + delete connectOptions.autoEncrypter; + } + this.connectOptions = Object.freeze(connectOptions); + } + connect() { + if (this.s.state !== common_1.STATE_CLOSED) { + return; + } + // start + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = utils_1.makeInterruptibleAsyncInterval(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS, + immediate: true + }); + } + requestCheck() { + var _a; + if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { + return; + } + (_a = this[kMonitorId]) === null || _a === void 0 ? void 0 : _a.wake(); + } + reset() { + const topologyVersion = this[kServer].description.topologyVersion; + if (isInCloseState(this) || topologyVersion == null) { + return; + } + stateTransition(this, common_1.STATE_CLOSING); + resetMonitorState(this); + // restart monitor + stateTransition(this, STATE_IDLE); + // restart monitoring + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = utils_1.makeInterruptibleAsyncInterval(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS + }); + } + close() { + if (isInCloseState(this)) { + return; + } + stateTransition(this, common_1.STATE_CLOSING); + resetMonitorState(this); + // close monitor + this.emit('close'); + stateTransition(this, common_1.STATE_CLOSED); + } +} +exports.Monitor = Monitor; +function resetMonitorState(monitor) { + var _a, _b, _c; + (_a = monitor[kMonitorId]) === null || _a === void 0 ? void 0 : _a.stop(); + monitor[kMonitorId] = undefined; + (_b = monitor[kRTTPinger]) === null || _b === void 0 ? void 0 : _b.close(); + monitor[kRTTPinger] = undefined; + monitor[kCancellationToken].emit('cancel'); + (_c = monitor[kConnection]) === null || _c === void 0 ? void 0 : _c.destroy({ force: true }); + monitor[kConnection] = undefined; +} +function checkServer(monitor, callback) { + let start = utils_1.now(); + monitor.emit(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address)); + function failureHandler(err) { + var _a; + (_a = monitor[kConnection]) === null || _a === void 0 ? void 0 : _a.destroy({ force: true }); + monitor[kConnection] = undefined; + monitor.emit(server_1.Server.SERVER_HEARTBEAT_FAILED, new events_1.ServerHeartbeatFailedEvent(monitor.address, utils_1.calculateDurationInMs(start), err)); + monitor.emit('resetServer', err); + monitor.emit('resetConnectionPool'); + callback(err); + } + const connection = monitor[kConnection]; + if (connection && !connection.closed) { + const { serverApi, helloOk } = connection; + const connectTimeoutMS = monitor.options.connectTimeoutMS; + const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS; + const topologyVersion = monitor[kServer].description.topologyVersion; + const isAwaitable = topologyVersion != null; + const cmd = { + [(serverApi === null || serverApi === void 0 ? void 0 : serverApi.version) || helloOk ? 'hello' : 'ismaster']: true, + ...(isAwaitable && topologyVersion + ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } + : {}) + }; + const options = isAwaitable + ? { + socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0, + exhaustAllowed: true + } + : { socketTimeoutMS: connectTimeoutMS }; + if (isAwaitable && monitor[kRTTPinger] == null) { + monitor[kRTTPinger] = new RTTPinger(monitor[kCancellationToken], Object.assign({ heartbeatFrequencyMS: monitor.options.heartbeatFrequencyMS }, monitor.connectOptions)); + } + connection.command(utils_1.ns('admin.$cmd'), cmd, options, (err, isMaster) => { + var _a; + if (err) { + failureHandler(err); + return; + } + if ('isWritablePrimary' in isMaster) { + // Provide pre-hello-style response document. + isMaster.ismaster = isMaster.isWritablePrimary; + } + const rttPinger = monitor[kRTTPinger]; + const duration = isAwaitable && rttPinger ? rttPinger.roundTripTime : utils_1.calculateDurationInMs(start); + monitor.emit(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration, isMaster)); + // if we are using the streaming protocol then we immediately issue another `started` + // event, otherwise the "check" is complete and return to the main monitor loop + if (isAwaitable && isMaster.topologyVersion) { + monitor.emit(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address)); + start = utils_1.now(); + } + else { + (_a = monitor[kRTTPinger]) === null || _a === void 0 ? void 0 : _a.close(); + monitor[kRTTPinger] = undefined; + callback(undefined, isMaster); + } + }); + return; + } + // connecting does an implicit `ismaster` + connect_1.connect(monitor.connectOptions, (err, conn) => { + if (err) { + monitor[kConnection] = undefined; + // we already reset the connection pool on network errors in all cases + if (!(err instanceof error_1.MongoNetworkError)) { + monitor.emit('resetConnectionPool'); + } + failureHandler(err); + return; + } + if (conn) { + if (isInCloseState(monitor)) { + conn.destroy({ force: true }); + return; + } + monitor[kConnection] = conn; + monitor.emit(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, new events_1.ServerHeartbeatSucceededEvent(monitor.address, utils_1.calculateDurationInMs(start), conn.ismaster)); + callback(undefined, conn.ismaster); + } + }); +} +function monitorServer(monitor) { + return (callback) => { + stateTransition(monitor, STATE_MONITORING); + function done() { + if (!isInCloseState(monitor)) { + stateTransition(monitor, STATE_IDLE); + } + callback(); + } + checkServer(monitor, (err, isMaster) => { + if (err) { + // otherwise an error occurred on initial discovery, also bail + if (monitor[kServer].description.type === common_1.ServerType.Unknown) { + monitor.emit('resetServer', err); + return done(); + } + } + // if the check indicates streaming is supported, immediately reschedule monitoring + if (isMaster && isMaster.topologyVersion) { + setTimeout(() => { + var _a; + if (!isInCloseState(monitor)) { + (_a = monitor[kMonitorId]) === null || _a === void 0 ? void 0 : _a.wake(); + } + }, 0); + } + done(); + }); + }; +} +function makeTopologyVersion(tv) { + return { + processId: tv.processId, + // tests mock counter as just number, but in a real situation counter should always be a Long + counter: bson_1.Long.isLong(tv.counter) ? tv.counter : bson_1.Long.fromNumber(tv.counter) + }; +} +/** @internal */ +class RTTPinger { + constructor(cancellationToken, options) { + this[kConnection] = undefined; + this[kCancellationToken] = cancellationToken; + this[kRoundTripTime] = 0; + this.closed = false; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + this[kMonitorId] = setTimeout(() => measureRoundTripTime(this, options), heartbeatFrequencyMS); + } + get roundTripTime() { + return this[kRoundTripTime]; + } + close() { + var _a; + this.closed = true; + clearTimeout(this[kMonitorId]); + (_a = this[kConnection]) === null || _a === void 0 ? void 0 : _a.destroy({ force: true }); + this[kConnection] = undefined; + } +} +exports.RTTPinger = RTTPinger; +function measureRoundTripTime(rttPinger, options) { + const start = utils_1.now(); + options.cancellationToken = rttPinger[kCancellationToken]; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + if (rttPinger.closed) { + return; + } + function measureAndReschedule(conn) { + if (rttPinger.closed) { + conn === null || conn === void 0 ? void 0 : conn.destroy({ force: true }); + return; + } + if (rttPinger[kConnection] == null) { + rttPinger[kConnection] = conn; + } + rttPinger[kRoundTripTime] = utils_1.calculateDurationInMs(start); + rttPinger[kMonitorId] = setTimeout(() => measureRoundTripTime(rttPinger, options), heartbeatFrequencyMS); + } + const connection = rttPinger[kConnection]; + if (connection == null) { + connect_1.connect(options, (err, conn) => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + measureAndReschedule(conn); + }); + return; + } + connection.command(utils_1.ns('admin.$cmd'), { ismaster: 1 }, undefined, err => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + measureAndReschedule(); + }); +} +//# sourceMappingURL=monitor.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/monitor.js.map b/node_modules/mongodb/lib/sdam/monitor.js.map new file mode 100644 index 0000000..abb35ff --- /dev/null +++ b/node_modules/mongodb/lib/sdam/monitor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"monitor.js","sourceRoot":"","sources":["../../src/sdam/monitor.ts"],"names":[],"mappings":";;;AAAA,qCAAmE;AACnE,oCAOkB;AAClB,6CAA0C;AAC1C,mDAAmE;AACnE,oCAA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,CAAC,cAAc,CAAC,GAAG,6BAAqB,CAAC,KAAK,CAAC,CAAC;QACzD,SAAS,CAAC,UAAU,CAAC,GAAG,UAAU,CAChC,GAAG,EAAE,CAAC,oBAAoB,CAAC,SAAS,EAAE,OAAO,CAAC,EAC9C,oBAAoB,CACrB,CAAC;IACJ,CAAC;IAED,MAAM,UAAU,GAAG,SAAS,CAAC,WAAW,CAAC,CAAC;IAC1C,IAAI,UAAU,IAAI,IAAI,EAAE;QACtB,iBAAO,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;YAC7B,IAAI,GAAG,EAAE;gBACP,SAAS,CAAC,WAAW,CAAC,GAAG,SAAS,CAAC;gBACnC,SAAS,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;gBAC9B,OAAO;aACR;YAED,oBAAoB,CAAC,IAAI,CAAC,CAAC;QAC7B,CAAC,CAAC,CAAC;QAEH,OAAO;KACR;IAED,UAAU,CAAC,OAAO,CAAC,UAAE,CAAC,YAAY,CAAC,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,GAAG,CAAC,EAAE;QACrE,IAAI,GAAG,EAAE;YACP,SAAS,CAAC,WAAW,CAAC,GAAG,SAAS,CAAC;YACnC,SAAS,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;YAC9B,OAAO;SACR;QAED,oBAAoB,EAAE,CAAC;IACzB,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/server.js b/node_modules/mongodb/lib/sdam/server.js new file mode 100644 index 0000000..0b0273f --- /dev/null +++ b/node_modules/mongodb/lib/sdam/server.js @@ -0,0 +1,366 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HEARTBEAT_EVENTS = exports.Server = void 0; +const logger_1 = require("../logger"); +const connection_pool_1 = require("../cmap/connection_pool"); +const server_description_1 = require("./server_description"); +const monitor_1 = require("./monitor"); +const transactions_1 = require("../transactions"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const error_1 = require("../error"); +const connection_1 = require("../cmap/connection"); +const mongo_types_1 = require("../mongo_types"); +const utils_2 = require("../utils"); +const stateTransition = utils_1.makeStateMachine({ + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING], + [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED], + [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED], + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED] +}); +/** @internal */ +const kMonitor = Symbol('monitor'); +/** @internal */ +class Server extends mongo_types_1.TypedEventEmitter { + /** + * Create a server + */ + constructor(topology, description, options) { + super(); + this.serverApi = options.serverApi; + const poolOptions = { hostAddress: description.hostAddress, ...options }; + this.s = { + description, + options, + logger: new logger_1.Logger('Server'), + state: common_1.STATE_CLOSED, + topology, + pool: new connection_pool_1.ConnectionPool(poolOptions) + }; + for (const event of [...connection_pool_1.CMAP_EVENTS, ...connection_1.APM_EVENTS]) { + this.s.pool.on(event, (e) => this.emit(event, e)); + } + this.s.pool.on(connection_1.Connection.CLUSTER_TIME_RECEIVED, (clusterTime) => { + this.clusterTime = clusterTime; + }); + // monitoring is disabled in load balancing mode + if (this.loadBalanced) + return; + // create the monitor + this[kMonitor] = new monitor_1.Monitor(this, this.s.options); + for (const event of exports.HEARTBEAT_EVENTS) { + this[kMonitor].on(event, (e) => this.emit(event, e)); + } + this[kMonitor].on('resetConnectionPool', () => { + this.s.pool.clear(); + }); + this[kMonitor].on('resetServer', (error) => markServerUnknown(this, error)); + this[kMonitor].on(Server.SERVER_HEARTBEAT_SUCCEEDED, (event) => { + this.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(this.description.hostAddress, event.reply, { + roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration) + })); + if (this.s.state === common_1.STATE_CONNECTING) { + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + }); + } + get description() { + return this.s.description; + } + get name() { + return this.s.description.address; + } + get autoEncrypter() { + if (this.s.options && this.s.options.autoEncrypter) { + return this.s.options.autoEncrypter; + } + } + get loadBalanced() { + return this.s.topology.description.type === common_1.TopologyType.LoadBalanced; + } + /** + * Initiate server connect + */ + connect() { + if (this.s.state !== common_1.STATE_CLOSED) { + return; + } + stateTransition(this, common_1.STATE_CONNECTING); + // If in load balancer mode we automatically set the server to + // a load balancer. It never transitions out of this state and + // has no monitor. + if (!this.loadBalanced) { + this[kMonitor].connect(); + } + else { + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + } + /** Destroy the server connection */ + destroy(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = Object.assign({}, { force: false }, options); + if (this.s.state === common_1.STATE_CLOSED) { + if (typeof callback === 'function') { + callback(); + } + return; + } + stateTransition(this, common_1.STATE_CLOSING); + if (!this.loadBalanced) { + this[kMonitor].close(); + } + this.s.pool.close(options, err => { + stateTransition(this, common_1.STATE_CLOSED); + this.emit('closed'); + if (typeof callback === 'function') { + callback(err); + } + }); + } + /** + * Immediately schedule monitoring of this server. If there already an attempt being made + * this will be a no-op. + */ + requestCheck() { + if (!this.loadBalanced) { + this[kMonitor].requestCheck(); + } + } + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options !== null && options !== void 0 ? options : {}); + } + if (callback == null) { + throw new error_1.MongoInvalidArgumentError('Callback must be provided'); + } + if (ns.db == null || typeof ns === 'string') { + throw new error_1.MongoInvalidArgumentError('Namespace must not be a string'); + } + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + callback(new error_1.MongoServerClosedError()); + return; + } + // Clone the options + const finalOptions = Object.assign({}, options, { wireProtocolCommand: false }); + // error if collation not supported + if (utils_1.collationNotSupported(this, cmd)) { + callback(new error_1.MongoCompatibilityError(`Server ${this.name} does not support collation`)); + return; + } + const session = finalOptions.session; + const conn = session === null || session === void 0 ? void 0 : session.pinnedConnection; + // NOTE: This is a hack! We can't retrieve the connections used for executing an operation + // (and prevent them from being checked back in) at the point of operation execution. + // This should be considered as part of the work for NODE-2882 + if (this.loadBalanced && session && conn == null && isPinnableCommand(cmd, session)) { + this.s.pool.checkOut((err, checkedOut) => { + if (err || checkedOut == null) { + if (callback) + return callback(err); + return; + } + session.pin(checkedOut); + this.command(ns, cmd, finalOptions, callback); + }); + return; + } + this.s.pool.withConnection(conn, (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, err); + return cb(err); + } + conn.command(ns, cmd, finalOptions, makeOperationHandler(this, conn, cmd, finalOptions, cb)); + }, callback); + } + /** + * Execute a query against the server + * @internal + */ + query(ns, cmd, options, callback) { + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + callback(new error_1.MongoServerClosedError()); + return; + } + this.s.pool.withConnection(undefined, (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, err); + return cb(err); + } + conn.query(ns, cmd, options, makeOperationHandler(this, conn, cmd, options, cb)); + }, callback); + } + /** + * Execute a `getMore` against the server + * @internal + */ + getMore(ns, cursorId, options, callback) { + var _a; + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + callback(new error_1.MongoServerClosedError()); + return; + } + this.s.pool.withConnection((_a = options.session) === null || _a === void 0 ? void 0 : _a.pinnedConnection, (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, err); + return cb(err); + } + conn.getMore(ns, cursorId, options, makeOperationHandler(this, conn, {}, options, cb)); + }, callback); + } + /** + * Execute a `killCursors` command against the server + * @internal + */ + killCursors(ns, cursorIds, options, callback) { + var _a; + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + if (typeof callback === 'function') { + callback(new error_1.MongoServerClosedError()); + } + return; + } + this.s.pool.withConnection((_a = options.session) === null || _a === void 0 ? void 0 : _a.pinnedConnection, (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, err); + return cb(err); + } + conn.killCursors(ns, cursorIds, options, makeOperationHandler(this, conn, {}, undefined, cb)); + }, callback); + } +} +exports.Server = Server; +/** @event */ +Server.SERVER_HEARTBEAT_STARTED = 'serverHeartbeatStarted'; +/** @event */ +Server.SERVER_HEARTBEAT_SUCCEEDED = 'serverHeartbeatSucceeded'; +/** @event */ +Server.SERVER_HEARTBEAT_FAILED = 'serverHeartbeatFailed'; +/** @event */ +Server.CONNECT = 'connect'; +/** @event */ +Server.DESCRIPTION_RECEIVED = 'descriptionReceived'; +/** @event */ +Server.CLOSED = 'closed'; +/** @event */ +Server.ENDED = 'ended'; +exports.HEARTBEAT_EVENTS = [ + Server.SERVER_HEARTBEAT_STARTED, + Server.SERVER_HEARTBEAT_SUCCEEDED, + Server.SERVER_HEARTBEAT_FAILED +]; +Object.defineProperty(Server.prototype, 'clusterTime', { + get() { + return this.s.topology.clusterTime; + }, + set(clusterTime) { + this.s.topology.clusterTime = clusterTime; + } +}); +function calculateRoundTripTime(oldRtt, duration) { + if (oldRtt === -1) { + return duration; + } + const alpha = 0.2; + return alpha * duration + (1 - alpha) * oldRtt; +} +function markServerUnknown(server, error) { + // Load balancer servers can never be marked unknown. + if (server.loadBalanced) { + return; + } + if (error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError)) { + server[kMonitor].reset(); + } + server.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(server.description.hostAddress, undefined, { + error, + topologyVersion: error && error.topologyVersion ? error.topologyVersion : server.description.topologyVersion + })); +} +function isPinnableCommand(cmd, session) { + if (session) { + return (session.inTransaction() || + 'aggregate' in cmd || + 'find' in cmd || + 'getMore' in cmd || + 'listCollections' in cmd || + 'listIndexes' in cmd); + } + return false; +} +function connectionIsStale(pool, connection) { + if (connection.serviceId) { + return (connection.generation !== pool.serviceGenerations.get(connection.serviceId.toHexString())); + } + return connection.generation !== pool.generation; +} +function shouldHandleStateChangeError(server, err) { + const etv = err.topologyVersion; + const stv = server.description.topologyVersion; + return server_description_1.compareTopologyVersion(stv, etv) < 0; +} +function inActiveTransaction(session, cmd) { + return session && session.inTransaction() && !transactions_1.isTransactionCommand(cmd); +} +/** this checks the retryWrites option passed down from the client options, it + * does not check if the server supports retryable writes */ +function isRetryableWritesEnabled(topology) { + return topology.s.options.retryWrites !== false; +} +function makeOperationHandler(server, connection, cmd, options, callback) { + const session = options === null || options === void 0 ? void 0 : options.session; + return function handleOperationResult(err, result) { + if (err && !connectionIsStale(server.s.pool, connection)) { + if (err instanceof error_1.MongoNetworkError) { + if (session && !session.hasEnded && session.serverSession) { + session.serverSession.isDirty = true; + } + // inActiveTransaction check handles commit and abort. + if (inActiveTransaction(session, cmd) && !err.hasErrorLabel('TransientTransactionError')) { + err.addErrorLabel('TransientTransactionError'); + } + if ((isRetryableWritesEnabled(server.s.topology) || transactions_1.isTransactionCommand(cmd)) && + utils_2.supportsRetryableWrites(server) && + !inActiveTransaction(session, cmd)) { + err.addErrorLabel('RetryableWriteError'); + } + if (!(err instanceof error_1.MongoNetworkTimeoutError) || error_1.isNetworkErrorBeforeHandshake(err)) { + // In load balanced mode we never mark the server as unknown and always + // clear for the specific service id. + server.s.pool.clear(connection.serviceId); + if (!server.loadBalanced) { + markServerUnknown(server, err); + } + } + } + else { + // if pre-4.4 server, then add error label if its a retryable write error + if ((isRetryableWritesEnabled(server.s.topology) || transactions_1.isTransactionCommand(cmd)) && + utils_1.maxWireVersion(server) < 9 && + error_1.isRetryableWriteError(err) && + !inActiveTransaction(session, cmd)) { + err.addErrorLabel('RetryableWriteError'); + } + if (error_1.isSDAMUnrecoverableError(err)) { + if (shouldHandleStateChangeError(server, err)) { + if (utils_1.maxWireVersion(server) <= 7 || error_1.isNodeShuttingDownError(err)) { + server.s.pool.clear(connection.serviceId); + } + if (!server.loadBalanced) { + markServerUnknown(server, err); + process.nextTick(() => server.requestCheck()); + } + } + } + } + if (session && session.isPinned && err.hasErrorLabel('TransientTransactionError')) { + session.unpin({ force: true }); + } + } + callback(err, result); + }; +} +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/server.js.map b/node_modules/mongodb/lib/sdam/server.js.map new file mode 100644 index 0000000..fbb9796 --- /dev/null +++ b/node_modules/mongodb/lib/sdam/server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/sdam/server.ts"],"names":[],"mappings":";;;AAAA,sCAAmC;AACnC,6DAKiC;AACjC,6DAAiF;AACjF,uCAAoD;AACpD,kDAAuD;AACvD,oCAQkB;AAClB,qCAOkB;AAClB,oCAWkB;AAClB,mDAO4B;AAW5B,gDAAmD;AACnD,oCAAmD;AAEnD,MAAM,eAAe,GAAG,wBAAgB,CAAC;IACvC,CAAC,qBAAY,CAAC,EAAE,CAAC,qBAAY,EAAE,yBAAgB,CAAC;IAChD,CAAC,yBAAgB,CAAC,EAAE,CAAC,yBAAgB,EAAE,sBAAa,EAAE,wBAAe,EAAE,qBAAY,CAAC;IACpF,CAAC,wBAAe,CAAC,EAAE,CAAC,wBAAe,EAAE,sBAAa,EAAE,qBAAY,CAAC;IACjE,CAAC,sBAAa,CAAC,EAAE,CAAC,sBAAa,EAAE,qBAAY,CAAC;CAC/C,CAAC,CAAC;AAEH,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AAqCnC,gBAAgB;AAChB,MAAa,MAAO,SAAQ,+BAA+B;IAuBzD;;OAEG;IACH,YAAY,QAAkB,EAAE,WAA8B,EAAE,OAAsB;QACpF,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QAEnC,MAAM,WAAW,GAAG,EAAE,WAAW,EAAE,WAAW,CAAC,WAAW,EAAE,GAAG,OAAO,EAAE,CA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BAAmB,CAAC,OAAO,EAAE,GAAG,CAAC,EAClC;oBACA,GAAG,CAAC,aAAa,CAAC,qBAAqB,CAAC,CAAC;iBAC1C;gBAED,IAAI,gCAAwB,CAAC,GAAG,CAAC,EAAE;oBACjC,IAAI,4BAA4B,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE;wBAC7C,IAAI,sBAAc,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,+BAAuB,CAAC,GAAG,CAAC,EAAE;4BAC/D,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;yBAC3C;wBAED,IAAI,CAAC,MAAM,CAAC,YAAY,EAAE;4BACxB,iBAAiB,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;4BAC/B,OAAO,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC;yBAC/C;qBACF;iBACF;aACF;YAED,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,IAAI,GAAG,CAAC,aAAa,CAAC,2BAA2B,CAAC,EAAE;gBACjF,OAAO,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;aAChC;SACF;QAED,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACxB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/server_description.js b/node_modules/mongodb/lib/sdam/server_description.js new file mode 100644 index 0000000..6277ad9 --- /dev/null +++ b/node_modules/mongodb/lib/sdam/server_description.js @@ -0,0 +1,197 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.compareTopologyVersion = exports.parseServerType = exports.ServerDescription = void 0; +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const bson_1 = require("../bson"); +const WRITABLE_SERVER_TYPES = new Set([ + common_1.ServerType.RSPrimary, + common_1.ServerType.Standalone, + common_1.ServerType.Mongos, + common_1.ServerType.LoadBalancer +]); +const DATA_BEARING_SERVER_TYPES = new Set([ + common_1.ServerType.RSPrimary, + common_1.ServerType.RSSecondary, + common_1.ServerType.Mongos, + common_1.ServerType.Standalone, + common_1.ServerType.LoadBalancer +]); +/** + * The client's view of a single server, based on the most recent ismaster outcome. + * + * Internal type, not meant to be directly instantiated + * @public + */ +class ServerDescription { + /** + * Create a ServerDescription + * @internal + * + * @param address - The address of the server + * @param ismaster - An optional ismaster response for this server + */ + constructor(address, ismaster, options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + if (typeof address === 'string') { + this._hostAddress = new utils_1.HostAddress(address); + this.address = this._hostAddress.toString(); + } + else { + this._hostAddress = address; + this.address = this._hostAddress.toString(); + } + this.type = parseServerType(ismaster, options); + this.hosts = (_b = (_a = ismaster === null || ismaster === void 0 ? void 0 : ismaster.hosts) === null || _a === void 0 ? void 0 : _a.map((host) => host.toLowerCase())) !== null && _b !== void 0 ? _b : []; + this.passives = (_d = (_c = ismaster === null || ismaster === void 0 ? void 0 : ismaster.passives) === null || _c === void 0 ? void 0 : _c.map((host) => host.toLowerCase())) !== null && _d !== void 0 ? _d : []; + this.arbiters = (_f = (_e = ismaster === null || ismaster === void 0 ? void 0 : ismaster.arbiters) === null || _e === void 0 ? void 0 : _e.map((host) => host.toLowerCase())) !== null && _f !== void 0 ? _f : []; + this.tags = (_g = ismaster === null || ismaster === void 0 ? void 0 : ismaster.tags) !== null && _g !== void 0 ? _g : {}; + this.minWireVersion = (_h = ismaster === null || ismaster === void 0 ? void 0 : ismaster.minWireVersion) !== null && _h !== void 0 ? _h : 0; + this.maxWireVersion = (_j = ismaster === null || ismaster === void 0 ? void 0 : ismaster.maxWireVersion) !== null && _j !== void 0 ? _j : 0; + this.roundTripTime = (_k = options === null || options === void 0 ? void 0 : options.roundTripTime) !== null && _k !== void 0 ? _k : -1; + this.lastUpdateTime = utils_1.now(); + this.lastWriteDate = (_m = (_l = ismaster === null || ismaster === void 0 ? void 0 : ismaster.lastWrite) === null || _l === void 0 ? void 0 : _l.lastWriteDate) !== null && _m !== void 0 ? _m : 0; + if (options === null || options === void 0 ? void 0 : options.topologyVersion) { + this.topologyVersion = options.topologyVersion; + } + else if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.topologyVersion) { + this.topologyVersion = ismaster.topologyVersion; + } + if (options === null || options === void 0 ? void 0 : options.error) { + this.error = options.error; + } + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.primary) { + this.primary = ismaster.primary; + } + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.me) { + this.me = ismaster.me.toLowerCase(); + } + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.setName) { + this.setName = ismaster.setName; + } + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.setVersion) { + this.setVersion = ismaster.setVersion; + } + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.electionId) { + this.electionId = ismaster.electionId; + } + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.logicalSessionTimeoutMinutes) { + this.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; + } + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.$clusterTime) { + this.$clusterTime = ismaster.$clusterTime; + } + } + get hostAddress() { + if (this._hostAddress) + return this._hostAddress; + else + return new utils_1.HostAddress(this.address); + } + get allHosts() { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + /** Is this server available for reads*/ + get isReadable() { + return this.type === common_1.ServerType.RSSecondary || this.isWritable; + } + /** Is this server data bearing */ + get isDataBearing() { + return DATA_BEARING_SERVER_TYPES.has(this.type); + } + /** Is this server available for writes */ + get isWritable() { + return WRITABLE_SERVER_TYPES.has(this.type); + } + get host() { + const chopLength = `:${this.port}`.length; + return this.address.slice(0, -chopLength); + } + get port() { + const port = this.address.split(':').pop(); + return port ? Number.parseInt(port, 10) : 27017; + } + /** + * Determines if another `ServerDescription` is equal to this one per the rules defined + * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} + */ + equals(other) { + const topologyVersionsEqual = this.topologyVersion === other.topologyVersion || + compareTopologyVersion(this.topologyVersion, other.topologyVersion) === 0; + const electionIdsEqual = this.electionId && other.electionId + ? other.electionId && this.electionId.equals(other.electionId) + : this.electionId === other.electionId; + return (other != null && + utils_1.errorStrictEqual(this.error, other.error) && + this.type === other.type && + this.minWireVersion === other.minWireVersion && + utils_1.arrayStrictEqual(this.hosts, other.hosts) && + tagsStrictEqual(this.tags, other.tags) && + this.setName === other.setName && + this.setVersion === other.setVersion && + electionIdsEqual && + this.primary === other.primary && + this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && + topologyVersionsEqual); + } +} +exports.ServerDescription = ServerDescription; +// Parses an `ismaster` message and determines the server type +function parseServerType(ismaster, options) { + if (options === null || options === void 0 ? void 0 : options.loadBalanced) { + return common_1.ServerType.LoadBalancer; + } + if (!ismaster || !ismaster.ok) { + return common_1.ServerType.Unknown; + } + if (ismaster.isreplicaset) { + return common_1.ServerType.RSGhost; + } + if (ismaster.msg && ismaster.msg === 'isdbgrid') { + return common_1.ServerType.Mongos; + } + if (ismaster.setName) { + if (ismaster.hidden) { + return common_1.ServerType.RSOther; + } + else if (ismaster.ismaster || ismaster.isWritablePrimary) { + return common_1.ServerType.RSPrimary; + } + else if (ismaster.secondary) { + return common_1.ServerType.RSSecondary; + } + else if (ismaster.arbiterOnly) { + return common_1.ServerType.RSArbiter; + } + else { + return common_1.ServerType.RSOther; + } + } + return common_1.ServerType.Standalone; +} +exports.parseServerType = parseServerType; +function tagsStrictEqual(tags, tags2) { + const tagsKeys = Object.keys(tags); + const tags2Keys = Object.keys(tags2); + return (tagsKeys.length === tags2Keys.length && + tagsKeys.every((key) => tags2[key] === tags[key])); +} +/** + * Compares two topology versions. + * + * @returns A negative number if `lhs` is older than `rhs`; positive if `lhs` is newer than `rhs`; 0 if they are equivalent. + */ +function compareTopologyVersion(lhs, rhs) { + if (lhs == null || rhs == null) { + return -1; + } + if (lhs.processId.equals(rhs.processId)) { + // tests mock counter as just number, but in a real situation counter should always be a Long + const lhsCounter = bson_1.Long.isLong(lhs.counter) ? lhs.counter : bson_1.Long.fromNumber(lhs.counter); + const rhsCounter = bson_1.Long.isLong(rhs.counter) ? lhs.counter : bson_1.Long.fromNumber(rhs.counter); + return lhsCounter.compare(rhsCounter); + } + return -1; +} +exports.compareTopologyVersion = compareTopologyVersion; +//# sourceMappingURL=server_description.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/server_description.js.map b/node_modules/mongodb/lib/sdam/server_description.js.map new file mode 100644 index 0000000..072d11d --- /dev/null +++ b/node_modules/mongodb/lib/sdam/server_description.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server_description.js","sourceRoot":"","sources":["../../src/sdam/server_description.ts"],"names":[],"mappings":";;;AAAA,oCAAgF;AAChF,qCAAsC;AACtC,kCAAmD;AAInD,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAa;IAChD,mBAAU,CAAC,SAAS;IACpB,mBAAU,CAAC,UAAU;IACrB,mBAAU,CAAC,MAAM;IACjB,mBAAU,CAAC,YAAY;CACxB,CAAC,CAAC;AAEH,MAAM,yBAAyB,GAAG,IAAI,GAAG,CAAa;IACpD,mBAAU,CAAC,SAAS;IACpB,mBAAU,CAAC,WAAW;IACtB,mBAAU,CAAC,MAAM;IACjB,mBAAU,CAAC,UAAU;IACrB,mBAAU,CAAC,YAAY;CACxB,CAAC,CAAC;AA0BH;;;;;GAKG;AACH,MAAa,iBAAiB;IA2B5B;;;;;;OAMG;IACH,YACE,OAA6B,EAC7B,QAAmB,EACnB,OAAkC;;QAElC,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;YAC/B,IAAI,CAAC,YAAY,GAAG,IAAI,mBAAW,CAAC,OAAO,CAAC,CAAC;YAC7C,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,QAAQ,EA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C;AAED;;;;GAIG;AACH,SAAgB,sBAAsB,CAAC,GAAqB,EAAE,GAAqB;IACjF,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,EAAE;QAC9B,OAAO,CAAC,CAAC,CAAC;KACX;IAED,IAAI,GAAG,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;QACvC,6FAA6F;QAC7F,MAAM,UAAU,GAAG,WAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,WAAI,CAAC,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QACzF,MAAM,UAAU,GAAG,WAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,WAAI,CAAC,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QACzF,OAAO,UAAU,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;KACvC;IAED,OAAO,CAAC,CAAC,CAAC;AACZ,CAAC;AAbD,wDAaC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/server_selection.js b/node_modules/mongodb/lib/sdam/server_selection.js new file mode 100644 index 0000000..3c31f59 --- /dev/null +++ b/node_modules/mongodb/lib/sdam/server_selection.js @@ -0,0 +1,193 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readPreferenceServerSelector = exports.writableServerSelector = void 0; +const common_1 = require("./common"); +const read_preference_1 = require("../read_preference"); +const error_1 = require("../error"); +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; +/** + * Returns a server selector that selects for writable servers + */ +function writableServerSelector() { + return (topologyDescription, servers) => latencyWindowReducer(topologyDescription, servers.filter((s) => s.isWritable)); +} +exports.writableServerSelector = writableServerSelector; +/** + * Reduces the passed in array of servers by the rules of the "Max Staleness" specification + * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst + * + * @param readPreference - The read preference providing max staleness guidance + * @param topologyDescription - The topology description + * @param servers - The list of server descriptions to be reduced + * @returns The list of servers that satisfy the requirements of max staleness + */ +function maxStalenessReducer(readPreference, topologyDescription, servers) { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; + } + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds`); + } + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`); + } + if (topologyDescription.type === common_1.TopologyType.ReplicaSetWithPrimary) { + const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0]; + return servers.reduce((result, server) => { + var _a; + const stalenessMS = server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = (_a = readPreference.maxStalenessSeconds) !== null && _a !== void 0 ? _a : 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + return result; + }, []); + } + if (topologyDescription.type === common_1.TopologyType.ReplicaSetNoPrimary) { + if (servers.length === 0) { + return servers; + } + const sMax = servers.reduce((max, s) => s.lastWriteDate > max.lastWriteDate ? s : max); + return servers.reduce((result, server) => { + var _a; + const stalenessMS = sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = (_a = readPreference.maxStalenessSeconds) !== null && _a !== void 0 ? _a : 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + return result; + }, []); + } + return servers; +} +/** + * Determines whether a server's tags match a given set of tags + * + * @param tagSet - The requested tag set to match + * @param serverTags - The server's tags + */ +function tagSetMatch(tagSet, serverTags) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } + } + return true; +} +/** + * Reduces a set of server descriptions based on tags requested by the read preference + * + * @param readPreference - The read preference providing the requested tags + * @param servers - The list of server descriptions to reduce + * @returns The list of servers matching the requested tags + */ +function tagSetReducer(readPreference, servers) { + if (readPreference.tags == null || + (Array.isArray(readPreference.tags) && readPreference.tags.length === 0)) { + return servers; + } + for (let i = 0; i < readPreference.tags.length; ++i) { + const tagSet = readPreference.tags[i]; + const serversMatchingTagset = servers.reduce((matched, server) => { + if (tagSetMatch(tagSet, server.tags)) + matched.push(server); + return matched; + }, []); + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } + } + return []; +} +/** + * Reduces a list of servers to ensure they fall within an acceptable latency window. This is + * further specified in the "Server Selection" specification, found here: + * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst + * + * @param topologyDescription - The topology description + * @param servers - The list of servers to reduce + * @returns The servers which fall within an acceptable latency window + */ +function latencyWindowReducer(topologyDescription, servers) { + const low = servers.reduce((min, server) => min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min), -1); + const high = low + topologyDescription.localThresholdMS; + return servers.reduce((result, server) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) + result.push(server); + return result; + }, []); +} +// filters +function primaryFilter(server) { + return server.type === common_1.ServerType.RSPrimary; +} +function secondaryFilter(server) { + return server.type === common_1.ServerType.RSSecondary; +} +function nearestFilter(server) { + return server.type === common_1.ServerType.RSSecondary || server.type === common_1.ServerType.RSPrimary; +} +function knownFilter(server) { + return server.type !== common_1.ServerType.Unknown; +} +function loadBalancerFilter(server) { + return server.type === common_1.ServerType.LoadBalancer; +} +/** + * Returns a function which selects servers based on a provided read preference + * + * @param readPreference - The read preference to select with + */ +function readPreferenceServerSelector(readPreference) { + if (!readPreference.isValid()) { + throw new error_1.MongoInvalidArgumentError('Invalid read preference specified'); + } + return (topologyDescription, servers) => { + const commonWireVersion = topologyDescription.commonWireVersion; + if (commonWireVersion && + readPreference.minWireVersion && + readPreference.minWireVersion > commonWireVersion) { + throw new error_1.MongoCompatibilityError(`Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'`); + } + if (topologyDescription.type === common_1.TopologyType.LoadBalanced) { + return servers.filter(loadBalancerFilter); + } + if (topologyDescription.type === common_1.TopologyType.Unknown) { + return []; + } + if (topologyDescription.type === common_1.TopologyType.Single || + topologyDescription.type === common_1.TopologyType.Sharded) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); + } + const mode = readPreference.mode; + if (mode === read_preference_1.ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); + } + if (mode === read_preference_1.ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } + } + const filter = mode === read_preference_1.ReadPreference.NEAREST ? nearestFilter : secondaryFilter; + const selectedServers = latencyWindowReducer(topologyDescription, tagSetReducer(readPreference, maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)))); + if (mode === read_preference_1.ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { + return servers.filter(primaryFilter); + } + return selectedServers; + }; +} +exports.readPreferenceServerSelector = readPreferenceServerSelector; +//# sourceMappingURL=server_selection.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/server_selection.js.map b/node_modules/mongodb/lib/sdam/server_selection.js.map new file mode 100644 index 0000000..5f115f3 --- /dev/null +++ b/node_modules/mongodb/lib/sdam/server_selection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server_selection.js","sourceRoot":"","sources":["../../src/sdam/server_selection.ts"],"names":[],"mappings":";;;AAAA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B,EAAE;YAC7C,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;YAC7C,IAAI,MAAM,CAAC,MAAM,EAAE;gBACjB,OAAO,MAAM,CAAC;aACf;SACF;QAED,MAAM,MAAM,GAAG,IAAI,KAAK,gCAAc,CAAC,OAAO,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,eAAe,CAAC;QACjF,MAAM,eAAe,GAAG,oBAAoB,CAC1C,mBAAmB,EACnB,aAAa,CACX,cAAc,EACd,mBAAmB,CAAC,cAAc,EAAE,mBAAmB,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CACjF,CACF,CAAC;QAEF,IAAI,IAAI,KAAK,gCAAc,CAAC,mBAAmB,IAAI,eAAe,CAAC,MAAM,KAAK,CAAC,EAAE;YAC/E,OAAO,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;SACtC;QAED,OAAO,eAAe,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC;AA9DD,oEA8DC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/srv_polling.js b/node_modules/mongodb/lib/sdam/srv_polling.js new file mode 100644 index 0000000..a7c80e3 --- /dev/null +++ b/node_modules/mongodb/lib/sdam/srv_polling.js @@ -0,0 +1,121 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SrvPoller = exports.SrvPollingEvent = void 0; +const dns = require("dns"); +const logger_1 = require("../logger"); +const utils_1 = require("../utils"); +const mongo_types_1 = require("../mongo_types"); +const error_1 = require("../error"); +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param srvAddress - The address to check against a domain + * @param parentDomain - The domain to check the provided address against + * @returns Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} +/** + * @internal + * @category Event + */ +class SrvPollingEvent { + constructor(srvRecords) { + this.srvRecords = srvRecords; + } + addresses() { + return new Map(this.srvRecords.map(record => { + const host = new utils_1.HostAddress(`${record.name}:${record.port}`); + return [host.toString(), host]; + })); + } +} +exports.SrvPollingEvent = SrvPollingEvent; +/** @internal */ +class SrvPoller extends mongo_types_1.TypedEventEmitter { + constructor(options) { + super(); + if (!options || !options.srvHost) { + throw new error_1.MongoRuntimeError('Options for SrvPoller must exist and include srvHost'); + } + this.srvHost = options.srvHost; + this.rescanSrvIntervalMS = 60000; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + this.logger = new logger_1.Logger('srvPoller', options); + this.haMode = false; + this.generation = 0; + this._timeout = undefined; + } + get srvAddress() { + return `_mongodb._tcp.${this.srvHost}`; + } + get intervalMS() { + return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; + } + start() { + if (!this._timeout) { + this.schedule(); + } + } + stop() { + if (this._timeout) { + clearTimeout(this._timeout); + this.generation += 1; + this._timeout = undefined; + } + } + schedule() { + if (this._timeout) { + clearTimeout(this._timeout); + } + this._timeout = setTimeout(() => this._poll(), this.intervalMS); + } + success(srvRecords) { + this.haMode = false; + this.schedule(); + this.emit(SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords)); + } + failure(message, obj) { + this.logger.warn(message, obj); + this.haMode = true; + this.schedule(); + } + parentDomainMismatch(srvRecord) { + this.logger.warn(`parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, srvRecord); + } + _poll() { + const generation = this.generation; + dns.resolveSrv(this.srvAddress, (err, srvRecords) => { + if (generation !== this.generation) { + return; + } + if (err) { + this.failure('DNS error', err); + return; + } + const finalAddresses = []; + srvRecords.forEach((record) => { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } + else { + this.parentDomainMismatch(record); + } + }); + if (!finalAddresses.length) { + this.failure('No valid addresses found at host'); + return; + } + this.success(finalAddresses); + }); + } +} +exports.SrvPoller = SrvPoller; +/** @event */ +SrvPoller.SRV_RECORD_DISCOVERY = 'srvRecordDiscovery'; +//# sourceMappingURL=srv_polling.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/srv_polling.js.map b/node_modules/mongodb/lib/sdam/srv_polling.js.map new file mode 100644 index 0000000..d3d2f35 --- /dev/null +++ b/node_modules/mongodb/lib/sdam/srv_polling.js.map @@ -0,0 +1 @@ +{"version":3,"file":"srv_polling.js","sourceRoot":"","sources":["../../src/sdam/srv_polling.ts"],"names":[],"mappings":";;;AAAA,2BAA2B;AAC3B,sCAAkD;AAClD,oCAAuC;AACvC,gDAAmD;AACnD,oCAA6C;AAE7C;;;;;;;GAOG;AACH,SAAS,mBAAmB,CAAC,UAAkB,EAAE,YAAoB;IACnE,MAAM,KAAK,GAAG,QAAQ,CAAC;IACvB,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC;IAChD,MAAM,MAAM,GAAG,IAAI,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC;IACrD,OAAO,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED;;;GAGG;AACH,MAAa,eAAe;IAE1B,YAAY,UAA2B;QACrC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,SAAS;QACP,OAAO,IAAI,GAAG,CACZ,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;YAC3B,MAAM,IAAI,GAAG,IAAI,mBAAW,CAAC,GAAG,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;YAC9D,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,IAAI,CAAC,CAAC;QACjC,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;CACF;AAdD,0CAcC;AAaD,gBAAgB;AA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,CAAC;iBAC7B;qBAAM;oBACL,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC;iBACnC;YACH,CAAC,CAAC,CAAC;YAEH,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE;gBAC1B,IAAI,CAAC,OAAO,CAAC,kCAAkC,CAAC,CAAC;gBACjD,OAAO;aACR;YAED,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QAC/B,CAAC,CAAC,CAAC;IACL,CAAC;;AA3GH,8BA4GC;AAnGC,aAAa;AACG,8BAAoB,GAAG,oBAA6B,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/topology.js b/node_modules/mongodb/lib/sdam/topology.js new file mode 100644 index 0000000..e9fd1f0 --- /dev/null +++ b/node_modules/mongodb/lib/sdam/topology.js @@ -0,0 +1,722 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerCapabilities = exports.TOPOLOGY_EVENTS = exports.Topology = void 0; +const Denque = require("denque"); +const read_preference_1 = require("../read_preference"); +const server_description_1 = require("./server_description"); +const topology_description_1 = require("./topology_description"); +const server_1 = require("./server"); +const sessions_1 = require("../sessions"); +const srv_polling_1 = require("./srv_polling"); +const connection_pool_1 = require("../cmap/connection_pool"); +const error_1 = require("../error"); +const server_selection_1 = require("./server_selection"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const events_1 = require("./events"); +const connection_1 = require("../cmap/connection"); +const connection_string_1 = require("../connection_string"); +const bson_1 = require("../bson"); +const mongo_types_1 = require("../mongo_types"); +// Global state +let globalTopologyCounter = 0; +// events that we relay to the `Topology` +const SERVER_RELAY_EVENTS = [ + server_1.Server.SERVER_HEARTBEAT_STARTED, + server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, + server_1.Server.SERVER_HEARTBEAT_FAILED, + connection_1.Connection.COMMAND_STARTED, + connection_1.Connection.COMMAND_SUCCEEDED, + connection_1.Connection.COMMAND_FAILED, + ...connection_pool_1.CMAP_EVENTS +]; +// all events we listen to from `Server` instances +const LOCAL_SERVER_EVENTS = [ + server_1.Server.CONNECT, + server_1.Server.DESCRIPTION_RECEIVED, + server_1.Server.CLOSED, + server_1.Server.ENDED +]; +const stateTransition = utils_1.makeStateMachine({ + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING], + [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED], + [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED], + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED] +}); +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); +/** + * A container of server instances representing a connection to a MongoDB topology. + * @internal + */ +class Topology extends mongo_types_1.TypedEventEmitter { + /** + * @param seedlist - a list of HostAddress instances to connect to + */ + constructor(seeds, options) { + var _a; + super(); + // Legacy CSFLE support + this.bson = Object.create(null); + this.bson.serialize = bson_1.serialize; + this.bson.deserialize = bson_1.deserialize; + // Options should only be undefined in tests, MongoClient will always have defined options + options = options !== null && options !== void 0 ? options : { + hosts: [utils_1.HostAddress.fromString('localhost:27017')], + retryReads: connection_string_1.DEFAULT_OPTIONS.get('retryReads'), + retryWrites: connection_string_1.DEFAULT_OPTIONS.get('retryWrites'), + serverSelectionTimeoutMS: connection_string_1.DEFAULT_OPTIONS.get('serverSelectionTimeoutMS'), + directConnection: connection_string_1.DEFAULT_OPTIONS.get('directConnection'), + loadBalanced: connection_string_1.DEFAULT_OPTIONS.get('loadBalanced'), + metadata: connection_string_1.DEFAULT_OPTIONS.get('metadata'), + monitorCommands: connection_string_1.DEFAULT_OPTIONS.get('monitorCommands'), + tls: connection_string_1.DEFAULT_OPTIONS.get('tls'), + maxPoolSize: connection_string_1.DEFAULT_OPTIONS.get('maxPoolSize'), + minPoolSize: connection_string_1.DEFAULT_OPTIONS.get('minPoolSize'), + waitQueueTimeoutMS: connection_string_1.DEFAULT_OPTIONS.get('waitQueueTimeoutMS'), + connectionType: connection_string_1.DEFAULT_OPTIONS.get('connectionType'), + connectTimeoutMS: connection_string_1.DEFAULT_OPTIONS.get('connectTimeoutMS'), + maxIdleTimeMS: connection_string_1.DEFAULT_OPTIONS.get('maxIdleTimeMS'), + heartbeatFrequencyMS: connection_string_1.DEFAULT_OPTIONS.get('heartbeatFrequencyMS'), + minHeartbeatFrequencyMS: connection_string_1.DEFAULT_OPTIONS.get('minHeartbeatFrequencyMS') + }; + if (typeof seeds === 'string') { + seeds = [utils_1.HostAddress.fromString(seeds)]; + } + else if (!Array.isArray(seeds)) { + seeds = [seeds]; + } + const seedlist = []; + for (const seed of seeds) { + if (typeof seed === 'string') { + seedlist.push(utils_1.HostAddress.fromString(seed)); + } + else if (seed instanceof utils_1.HostAddress) { + seedlist.push(seed); + } + else { + // FIXME(NODE-3483): May need to be a MongoParseError + throw new error_1.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(seed)}`); + } + } + const topologyType = topologyTypeFromOptions(options); + const topologyId = globalTopologyCounter++; + const serverDescriptions = new Map(); + for (const hostAddress of seedlist) { + serverDescriptions.set(hostAddress.toString(), new server_description_1.ServerDescription(hostAddress)); + } + this[kWaitQueue] = new Denque(); + this.s = { + // the id of this topology + id: topologyId, + // passed in options + options, + // initial seedlist of servers to connect to + seedlist, + // initial state + state: common_1.STATE_CLOSED, + // the topology description + description: new topology_description_1.TopologyDescription(topologyType, serverDescriptions, options.replicaSet, undefined, undefined, undefined, options), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, + // a map of server instances to normalized addresses + servers: new Map(), + // Server Session Pool + sessionPool: new sessions_1.ServerSessionPool(this), + // Active client sessions + sessions: new Set(), + credentials: options === null || options === void 0 ? void 0 : options.credentials, + clusterTime: undefined, + // timer management + connectionTimers: new Set(), + detectShardedTopology: ev => this.detectShardedTopology(ev), + detectSrvRecords: ev => this.detectSrvRecords(ev) + }; + if (options.srvHost && !options.loadBalanced) { + this.s.srvPoller = + (_a = options.srvPoller) !== null && _a !== void 0 ? _a : new srv_polling_1.SrvPoller({ + heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, + srvHost: options.srvHost + }); + this.on(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + } + } + detectShardedTopology(event) { + var _a, _b, _c; + const previousType = event.previousDescription.type; + const newType = event.newDescription.type; + const transitionToSharded = previousType !== common_1.TopologyType.Sharded && newType === common_1.TopologyType.Sharded; + const srvListeners = (_a = this.s.srvPoller) === null || _a === void 0 ? void 0 : _a.listeners(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY); + const listeningToSrvPolling = !!(srvListeners === null || srvListeners === void 0 ? void 0 : srvListeners.includes(this.s.detectSrvRecords)); + if (transitionToSharded && !listeningToSrvPolling) { + (_b = this.s.srvPoller) === null || _b === void 0 ? void 0 : _b.on(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + (_c = this.s.srvPoller) === null || _c === void 0 ? void 0 : _c.start(); + } + } + detectSrvRecords(ev) { + const previousTopologyDescription = this.s.description; + this.s.description = this.s.description.updateFromSrvPollingEvent(ev); + if (this.s.description === previousTopologyDescription) { + // Nothing changed, so return + return; + } + updateServers(this); + this.emit(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description)); + } + /** + * @returns A `TopologyDescription` for this topology + */ + get description() { + return this.s.description; + } + get loadBalanced() { + return this.s.options.loadBalanced; + } + get capabilities() { + return new ServerCapabilities(this.lastIsMaster()); + } + /** Initiate server connect */ + connect(options, callback) { + var _a; + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + if (this.s.state === common_1.STATE_CONNECTED) { + if (typeof callback === 'function') { + callback(); + } + return; + } + stateTransition(this, common_1.STATE_CONNECTING); + // emit SDAM monitoring events + this.emit(Topology.TOPOLOGY_OPENING, new events_1.TopologyOpeningEvent(this.s.id)); + // emit an event for the topology change + this.emit(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, new topology_description_1.TopologyDescription(common_1.TopologyType.Unknown), // initial is always Unknown + this.s.description)); + // connect all known servers, then attempt server selection to connect + const serverDescriptions = Array.from(this.s.description.servers.values()); + connectServers(this, serverDescriptions); + // In load balancer mode we need to fake a server description getting + // emitted from the monitor, since the monitor doesn't exist. + if (this.s.options.loadBalanced) { + for (const description of serverDescriptions) { + const newDescription = new server_description_1.ServerDescription(description.hostAddress, undefined, { + loadBalanced: this.s.options.loadBalanced + }); + this.serverUpdateHandler(newDescription); + } + } + const readPreference = (_a = options.readPreference) !== null && _a !== void 0 ? _a : read_preference_1.ReadPreference.primary; + this.selectServer(server_selection_1.readPreferenceServerSelector(readPreference), options, (err, server) => { + if (err) { + this.close(); + typeof callback === 'function' ? callback(err) : this.emit(Topology.ERROR, err); + return; + } + // TODO: NODE-2471 + if (server && this.s.credentials) { + server.command(utils_1.ns('admin.$cmd'), { ping: 1 }, err => { + if (err) { + typeof callback === 'function' ? callback(err) : this.emit(Topology.ERROR, err); + return; + } + stateTransition(this, common_1.STATE_CONNECTED); + // TODO(NODE-3273) - remove err + this.emit(Topology.OPEN, err, this); + this.emit(Topology.CONNECT, this); + if (typeof callback === 'function') + callback(undefined, this); + }); + return; + } + stateTransition(this, common_1.STATE_CONNECTED); + // TODO(NODE-3273) - remove err + this.emit(Topology.OPEN, err, this); + this.emit(Topology.CONNECT, this); + if (typeof callback === 'function') + callback(undefined, this); + }); + } + /** Close this topology */ + close(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + if (typeof options === 'boolean') { + options = { force: options }; + } + options = options !== null && options !== void 0 ? options : {}; + if (this.s.state === common_1.STATE_CLOSED || this.s.state === common_1.STATE_CLOSING) { + if (typeof callback === 'function') { + callback(); + } + return; + } + stateTransition(this, common_1.STATE_CLOSING); + drainWaitQueue(this[kWaitQueue], new error_1.MongoTopologyClosedError()); + common_1.drainTimerQueue(this.s.connectionTimers); + if (this.s.srvPoller) { + this.s.srvPoller.stop(); + this.s.srvPoller.removeListener(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + } + this.removeListener(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + utils_1.eachAsync(Array.from(this.s.sessions.values()), (session, cb) => session.endSession(cb), () => { + this.s.sessionPool.endAllPooledSessions(() => { + utils_1.eachAsync(Array.from(this.s.servers.values()), (server, cb) => destroyServer(server, this, options, cb), err => { + this.s.servers.clear(); + // emit an event for close + this.emit(Topology.TOPOLOGY_CLOSED, new events_1.TopologyClosedEvent(this.s.id)); + stateTransition(this, common_1.STATE_CLOSED); + if (typeof callback === 'function') { + callback(err); + } + }); + }); + }); + } + selectServer(selector, _options, _callback) { + let options = _options; + const callback = (_callback !== null && _callback !== void 0 ? _callback : _options); + if (typeof options === 'function') { + options = {}; + } + let serverSelector; + if (typeof selector !== 'function') { + if (typeof selector === 'string') { + serverSelector = server_selection_1.readPreferenceServerSelector(read_preference_1.ReadPreference.fromString(selector)); + } + else { + let readPreference; + if (selector instanceof read_preference_1.ReadPreference) { + readPreference = selector; + } + else { + read_preference_1.ReadPreference.translate(options); + readPreference = options.readPreference || read_preference_1.ReadPreference.primary; + } + serverSelector = server_selection_1.readPreferenceServerSelector(readPreference); + } + } + else { + serverSelector = selector; + } + options = Object.assign({}, { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, options); + const isSharded = this.description.type === common_1.TopologyType.Sharded; + const session = options.session; + const transaction = session && session.transaction; + if (isSharded && transaction && transaction.server) { + callback(undefined, transaction.server); + return; + } + const waitQueueMember = { + serverSelector, + transaction, + callback + }; + const serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; + if (serverSelectionTimeoutMS) { + waitQueueMember.timer = setTimeout(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description); + waitQueueMember.callback(timeoutError); + }, serverSelectionTimeoutMS); + } + this[kWaitQueue].push(waitQueueMember); + processWaitQueue(this); + } + // Sessions related methods + /** + * @returns Whether the topology should initiate selection to determine session support + */ + shouldCheckForSessionSupport() { + if (this.description.type === common_1.TopologyType.Single) { + return !this.description.hasKnownServers; + } + return !this.description.hasDataBearingServers; + } + /** + * @returns Whether sessions are supported on the current topology + */ + hasSessionSupport() { + return this.loadBalanced || this.description.logicalSessionTimeoutMinutes != null; + } + /** Start a logical session */ + startSession(options, clientOptions) { + const session = new sessions_1.ClientSession(this, this.s.sessionPool, options, clientOptions); + session.once('ended', () => { + this.s.sessions.delete(session); + }); + this.s.sessions.add(session); + return session; + } + /** Send endSessions command(s) with the given session ids */ + endSessions(sessions, callback) { + if (!Array.isArray(sessions)) { + sessions = [sessions]; + } + this.selectServer(server_selection_1.readPreferenceServerSelector(read_preference_1.ReadPreference.primaryPreferred), (err, server) => { + if (err || !server) { + if (typeof callback === 'function') + callback(err); + return; + } + server.command(utils_1.ns('admin.$cmd'), { endSessions: sessions }, { noResponse: true }, (err, result) => { + if (typeof callback === 'function') + callback(err, result); + }); + }); + } + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param serverDescription - The server to update in the internal list of server descriptions + */ + serverUpdateHandler(serverDescription) { + if (!this.s.description.hasServer(serverDescription.address)) { + return; + } + // ignore this server update if its from an outdated topologyVersion + if (isStaleServerDescription(this.s.description, serverDescription)) { + return; + } + // these will be used for monitoring events later + const previousTopologyDescription = this.s.description; + const previousServerDescription = this.s.description.servers.get(serverDescription.address); + if (!previousServerDescription) { + return; + } + // Driver Sessions Spec: "Whenever a driver receives a cluster time from + // a server it MUST compare it to the current highest seen cluster time + // for the deployment. If the new cluster time is higher than the + // highest seen cluster time it MUST become the new highest seen cluster + // time. Two cluster times are compared using only the BsonTimestamp + // value of the clusterTime embedded field." + const clusterTime = serverDescription.$clusterTime; + if (clusterTime) { + common_1._advanceClusterTime(this, clusterTime); + } + // If we already know all the information contained in this updated description, then + // we don't need to emit SDAM events, but still need to update the description, in order + // to keep client-tracked attributes like last update time and round trip time up to date + const equalDescriptions = previousServerDescription && previousServerDescription.equals(serverDescription); + // first update the TopologyDescription + this.s.description = this.s.description.update(serverDescription); + if (this.s.description.compatibilityError) { + this.emit(Topology.ERROR, new error_1.MongoCompatibilityError(this.s.description.compatibilityError)); + return; + } + // emit monitoring events for this change + if (!equalDescriptions) { + const newDescription = this.s.description.servers.get(serverDescription.address); + if (newDescription) { + this.emit(Topology.SERVER_DESCRIPTION_CHANGED, new events_1.ServerDescriptionChangedEvent(this.s.id, serverDescription.address, previousServerDescription, newDescription)); + } + } + // update server list from updated descriptions + updateServers(this, serverDescription); + // attempt to resolve any outstanding server selection attempts + if (this[kWaitQueue].length > 0) { + processWaitQueue(this); + } + if (!equalDescriptions) { + this.emit(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description)); + } + } + auth(credentials, callback) { + if (typeof credentials === 'function') + (callback = credentials), (credentials = undefined); + if (typeof callback === 'function') + callback(undefined, true); + } + get clientMetadata() { + return this.s.options.metadata; + } + isConnected() { + return this.s.state === common_1.STATE_CONNECTED; + } + isDestroyed() { + return this.s.state === common_1.STATE_CLOSED; + } + /** + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref() { + utils_1.emitWarning('`unref` is a noop and will be removed in the next major version'); + } + // NOTE: There are many places in code where we explicitly check the last isMaster + // to do feature support detection. This should be done any other way, but for + // now we will just return the first isMaster seen, which should suffice. + lastIsMaster() { + const serverDescriptions = Array.from(this.description.servers.values()); + if (serverDescriptions.length === 0) + return {}; + const sd = serverDescriptions.filter((sd) => sd.type !== common_1.ServerType.Unknown)[0]; + const result = sd || { maxWireVersion: this.description.commonWireVersion }; + return result; + } + get logicalSessionTimeoutMinutes() { + return this.description.logicalSessionTimeoutMinutes; + } + get clusterTime() { + return this.s.clusterTime; + } + set clusterTime(clusterTime) { + this.s.clusterTime = clusterTime; + } +} +exports.Topology = Topology; +/** @event */ +Topology.SERVER_OPENING = 'serverOpening'; +/** @event */ +Topology.SERVER_CLOSED = 'serverClosed'; +/** @event */ +Topology.SERVER_DESCRIPTION_CHANGED = 'serverDescriptionChanged'; +/** @event */ +Topology.TOPOLOGY_OPENING = 'topologyOpening'; +/** @event */ +Topology.TOPOLOGY_CLOSED = 'topologyClosed'; +/** @event */ +Topology.TOPOLOGY_DESCRIPTION_CHANGED = 'topologyDescriptionChanged'; +/** @event */ +Topology.ERROR = 'error'; +/** @event */ +Topology.OPEN = 'open'; +/** @event */ +Topology.CONNECT = 'connect'; +/** @event */ +Topology.CLOSE = 'close'; +/** @event */ +Topology.TIMEOUT = 'timeout'; +/** @public */ +exports.TOPOLOGY_EVENTS = [ + Topology.SERVER_OPENING, + Topology.SERVER_CLOSED, + Topology.SERVER_DESCRIPTION_CHANGED, + Topology.TOPOLOGY_OPENING, + Topology.TOPOLOGY_CLOSED, + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + Topology.ERROR, + Topology.TIMEOUT, + Topology.CLOSE +]; +/** Destroys a server, and removes all event listeners from the instance */ +function destroyServer(server, topology, options, callback) { + options = options !== null && options !== void 0 ? options : {}; + for (const event of LOCAL_SERVER_EVENTS) { + server.removeAllListeners(event); + } + server.destroy(options, () => { + topology.emit(Topology.SERVER_CLOSED, new events_1.ServerClosedEvent(topology.s.id, server.description.address)); + for (const event of SERVER_RELAY_EVENTS) { + server.removeAllListeners(event); + } + if (typeof callback === 'function') { + callback(); + } + }); +} +/** Predicts the TopologyType from options */ +function topologyTypeFromOptions(options) { + if (options === null || options === void 0 ? void 0 : options.directConnection) { + return common_1.TopologyType.Single; + } + if (options === null || options === void 0 ? void 0 : options.replicaSet) { + return common_1.TopologyType.ReplicaSetNoPrimary; + } + if (options === null || options === void 0 ? void 0 : options.loadBalanced) { + return common_1.TopologyType.LoadBalanced; + } + return common_1.TopologyType.Unknown; +} +function randomSelection(array) { + return array[Math.floor(Math.random() * array.length)]; +} +/** + * Creates new server instances and attempts to connect them + * + * @param topology - The topology that this server belongs to + * @param serverDescription - The description for the server to initialize and connect to + * @param connectDelay - Time to wait before attempting initial connection + */ +function createAndConnectServer(topology, serverDescription, connectDelay) { + topology.emit(Topology.SERVER_OPENING, new events_1.ServerOpeningEvent(topology.s.id, serverDescription.address)); + const server = new server_1.Server(topology, serverDescription, topology.s.options); + for (const event of SERVER_RELAY_EVENTS) { + server.on(event, (e) => topology.emit(event, e)); + } + server.on(server_1.Server.DESCRIPTION_RECEIVED, description => topology.serverUpdateHandler(description)); + if (connectDelay) { + const connectTimer = setTimeout(() => { + common_1.clearAndRemoveTimerFrom(connectTimer, topology.s.connectionTimers); + server.connect(); + }, connectDelay); + topology.s.connectionTimers.add(connectTimer); + return server; + } + server.connect(); + return server; +} +/** + * Create `Server` instances for all initially known servers, connect them, and assign + * them to the passed in `Topology`. + * + * @param topology - The topology responsible for the servers + * @param serverDescriptions - A list of server descriptions to connect + */ +function connectServers(topology, serverDescriptions) { + topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { + const server = createAndConnectServer(topology, serverDescription); + servers.set(serverDescription.address, server); + return servers; + }, new Map()); +} +/** + * @param topology - Topology to update. + * @param incomingServerDescription - New server description. + */ +function updateServers(topology, incomingServerDescription) { + // update the internal server's description + if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { + const server = topology.s.servers.get(incomingServerDescription.address); + if (server) { + server.s.description = incomingServerDescription; + } + } + // add new servers for all descriptions we currently don't know about locally + for (const serverDescription of topology.description.servers.values()) { + if (!topology.s.servers.has(serverDescription.address)) { + const server = createAndConnectServer(topology, serverDescription); + topology.s.servers.set(serverDescription.address, server); + } + } + // for all servers no longer known, remove their descriptions and destroy their instances + for (const entry of topology.s.servers) { + const serverAddress = entry[0]; + if (topology.description.hasServer(serverAddress)) { + continue; + } + if (!topology.s.servers.has(serverAddress)) { + continue; + } + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + // prepare server for garbage collection + if (server) { + destroyServer(server, topology); + } + } +} +function drainWaitQueue(queue, err) { + while (queue.length) { + const waitQueueMember = queue.shift(); + if (!waitQueueMember) { + continue; + } + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + if (!waitQueueMember[kCancelled]) { + waitQueueMember.callback(err); + } + } +} +function processWaitQueue(topology) { + if (topology.s.state === common_1.STATE_CLOSED) { + drainWaitQueue(topology[kWaitQueue], new error_1.MongoTopologyClosedError()); + return; + } + const isSharded = topology.description.type === common_1.TopologyType.Sharded; + const serverDescriptions = Array.from(topology.description.servers.values()); + const membersToProcess = topology[kWaitQueue].length; + for (let i = 0; i < membersToProcess; ++i) { + const waitQueueMember = topology[kWaitQueue].shift(); + if (!waitQueueMember) { + continue; + } + if (waitQueueMember[kCancelled]) { + continue; + } + let selectedDescriptions; + try { + const serverSelector = waitQueueMember.serverSelector; + selectedDescriptions = serverSelector + ? serverSelector(topology.description, serverDescriptions) + : serverDescriptions; + } + catch (e) { + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(e); + continue; + } + if (selectedDescriptions.length === 0) { + topology[kWaitQueue].push(waitQueueMember); + continue; + } + const selectedServerDescription = randomSelection(selectedDescriptions); + const selectedServer = topology.s.servers.get(selectedServerDescription.address); + const transaction = waitQueueMember.transaction; + if (isSharded && transaction && transaction.isActive && selectedServer) { + transaction.pinServer(selectedServer); + } + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(undefined, selectedServer); + } + if (topology[kWaitQueue].length > 0) { + // ensure all server monitors attempt monitoring soon + for (const [, server] of topology.s.servers) { + process.nextTick(function scheduleServerCheck() { + return server.requestCheck(); + }); + } + } +} +function isStaleServerDescription(topologyDescription, incomingServerDescription) { + const currentServerDescription = topologyDescription.servers.get(incomingServerDescription.address); + const currentTopologyVersion = currentServerDescription === null || currentServerDescription === void 0 ? void 0 : currentServerDescription.topologyVersion; + return (server_description_1.compareTopologyVersion(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0); +} +/** @public */ +class ServerCapabilities { + constructor(ismaster) { + this.minWireVersion = ismaster.minWireVersion || 0; + this.maxWireVersion = ismaster.maxWireVersion || 0; + } + get hasAggregationCursor() { + return this.maxWireVersion >= 1; + } + get hasWriteCommands() { + return this.maxWireVersion >= 2; + } + get hasTextSearch() { + return this.minWireVersion >= 0; + } + get hasAuthCommands() { + return this.maxWireVersion >= 1; + } + get hasListCollectionsCommand() { + return this.maxWireVersion >= 3; + } + get hasListIndexesCommand() { + return this.maxWireVersion >= 3; + } + get supportsSnapshotReads() { + return this.maxWireVersion >= 13; + } + get commandsTakeWriteConcern() { + return this.maxWireVersion >= 5; + } + get commandsTakeCollation() { + return this.maxWireVersion >= 5; + } +} +exports.ServerCapabilities = ServerCapabilities; +//# sourceMappingURL=topology.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/topology.js.map b/node_modules/mongodb/lib/sdam/topology.js.map new file mode 100644 index 0000000..8210e35 --- /dev/null +++ b/node_modules/mongodb/lib/sdam/topology.js.map @@ -0,0 +1 @@ +{"version":3,"file":"topology.js","sourceRoot":"","sources":["../../src/sdam/topology.ts"],"names":[],"mappings":";;;AAAA,iCAAkC;AAClC,wDAAwE;AACxE,6DAAiF;AACjF,iEAA6D;AAC7D,qCAA+D;AAC/D,0CAKqB;AACrB,+CAA2D;AAC3D,6DAA4E;AAC5E,oCAMkB;AAClB,yDAAkF;AAClF,oCASkB;AAClB,qCAYkB;AAClB,qCAOkB;AAKlB,mDAAkF;AAElF,4DAAuD;AACvD,kCAAiD;AACjD,gDAAmD;AAEnD,eAAe;A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,IAAI,gBAAgB;QAClB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IACD,IAAI,aAAa;QACf,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,yBAAyB;QAC3B,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,qBAAqB;QACvB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,qBAAqB;QACvB,OAAO,IAAI,CAAC,cAAc,IAAI,EAAE,CAAC;IACnC,CAAC;IAED,IAAI,wBAAwB;QAC1B,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,qBAAqB;QACvB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AA3CD,gDA2CC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/topology_description.js b/node_modules/mongodb/lib/sdam/topology_description.js new file mode 100644 index 0000000..37276a9 --- /dev/null +++ b/node_modules/mongodb/lib/sdam/topology_description.js @@ -0,0 +1,337 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TopologyDescription = void 0; +const server_description_1 = require("./server_description"); +const WIRE_CONSTANTS = require("../cmap/wire_protocol/constants"); +const common_1 = require("./common"); +const error_1 = require("../error"); +// constants related to compatibility checks +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; +const MONGOS_OR_UNKNOWN = new Set([common_1.ServerType.Mongos, common_1.ServerType.Unknown]); +const MONGOS_OR_STANDALONE = new Set([common_1.ServerType.Mongos, common_1.ServerType.Standalone]); +const NON_PRIMARY_RS_MEMBERS = new Set([ + common_1.ServerType.RSSecondary, + common_1.ServerType.RSArbiter, + common_1.ServerType.RSOther +]); +/** + * Representation of a deployment of servers + * @public + */ +class TopologyDescription { + /** + * Create a TopologyDescription + */ + constructor(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, options) { + var _a, _b; + options = options !== null && options !== void 0 ? options : {}; + // TODO: consider assigning all these values to a temporary value `s` which + // we use `Object.freeze` on, ensuring the internal state of this type + // is immutable. + this.type = topologyType !== null && topologyType !== void 0 ? topologyType : common_1.TopologyType.Unknown; + this.servers = serverDescriptions !== null && serverDescriptions !== void 0 ? serverDescriptions : new Map(); + this.stale = false; + this.compatible = true; + this.heartbeatFrequencyMS = (_a = options.heartbeatFrequencyMS) !== null && _a !== void 0 ? _a : 0; + this.localThresholdMS = (_b = options.localThresholdMS) !== null && _b !== void 0 ? _b : 0; + if (setName) { + this.setName = setName; + } + if (maxSetVersion) { + this.maxSetVersion = maxSetVersion; + } + if (maxElectionId) { + this.maxElectionId = maxElectionId; + } + if (commonWireVersion) { + this.commonWireVersion = commonWireVersion; + } + // determine server compatibility + for (const serverDescription of this.servers.values()) { + // Load balancer mode is always compatible. + if (serverDescription.type === common_1.ServerType.Unknown || + serverDescription.type === common_1.ServerType.LoadBalancer) { + continue; + } + if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + } + if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; + break; + } + } + // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set + // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes + // value among ServerDescriptions of all data-bearing server types. If any have a null + // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be + // set to null. + this.logicalSessionTimeoutMinutes = undefined; + for (const [, server] of this.servers) { + if (server.isReadable) { + if (server.logicalSessionTimeoutMinutes == null) { + // If any of the servers have a null logicalSessionsTimeout, then the whole topology does + this.logicalSessionTimeoutMinutes = undefined; + break; + } + if (this.logicalSessionTimeoutMinutes == null) { + // First server with a non null logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes; + continue; + } + // Always select the smaller of the: + // current server logicalSessionsTimeout and the topologies logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = Math.min(this.logicalSessionTimeoutMinutes, server.logicalSessionTimeoutMinutes); + } + } + } + /** + * Returns a new TopologyDescription based on the SrvPollingEvent + * @internal + */ + updateFromSrvPollingEvent(ev) { + const newAddresses = ev.addresses(); + const serverDescriptions = new Map(this.servers); + for (const address of this.servers.keys()) { + if (newAddresses.has(address)) { + newAddresses.delete(address); + } + else { + serverDescriptions.delete(address); + } + } + if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) { + return this; + } + for (const [address, host] of newAddresses) { + serverDescriptions.set(address, new server_description_1.ServerDescription(host)); + } + return new TopologyDescription(this.type, serverDescriptions, this.setName, this.maxSetVersion, this.maxElectionId, this.commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); + } + /** + * Returns a copy of this description updated with a given ServerDescription + * @internal + */ + update(serverDescription) { + const address = serverDescription.address; + // potentially mutated values + let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this; + if (serverDescription.setName && setName && serverDescription.setName !== setName) { + serverDescription = new server_description_1.ServerDescription(address, undefined); + } + const serverType = serverDescription.type; + const serverDescriptions = new Map(this.servers); + // update common wire version + if (serverDescription.maxWireVersion !== 0) { + if (commonWireVersion == null) { + commonWireVersion = serverDescription.maxWireVersion; + } + else { + commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); + } + } + // update the actual server description + serverDescriptions.set(address, serverDescription); + if (topologyType === common_1.TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription(common_1.TopologyType.Single, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); + } + if (topologyType === common_1.TopologyType.Unknown) { + if (serverType === common_1.ServerType.Standalone && this.servers.size !== 1) { + serverDescriptions.delete(address); + } + else { + topologyType = topologyTypeForServerType(serverType); + } + } + if (topologyType === common_1.TopologyType.Sharded) { + if (!MONGOS_OR_UNKNOWN.has(serverType)) { + serverDescriptions.delete(address); + } + } + if (topologyType === common_1.TopologyType.ReplicaSetNoPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + } + if (serverType === common_1.ServerType.RSPrimary) { + const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId); + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } + else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName); + topologyType = result[0]; + setName = result[1]; + } + } + if (topologyType === common_1.TopologyType.ReplicaSetWithPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } + else if (serverType === common_1.ServerType.RSPrimary) { + const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId); + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } + else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + topologyType = updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName); + } + else { + topologyType = checkHasPrimary(serverDescriptions); + } + } + return new TopologyDescription(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); + } + get error() { + const descriptionsWithError = Array.from(this.servers.values()).filter((sd) => sd.error); + if (descriptionsWithError.length > 0) { + return descriptionsWithError[0].error; + } + } + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers() { + return Array.from(this.servers.values()).some((sd) => sd.type !== common_1.ServerType.Unknown); + } + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers() { + return Array.from(this.servers.values()).some((sd) => sd.isDataBearing); + } + /** + * Determines if the topology has a definition for the provided address + * @internal + */ + hasServer(address) { + return this.servers.has(address); + } +} +exports.TopologyDescription = TopologyDescription; +function topologyTypeForServerType(serverType) { + switch (serverType) { + case common_1.ServerType.Standalone: + return common_1.TopologyType.Single; + case common_1.ServerType.Mongos: + return common_1.TopologyType.Sharded; + case common_1.ServerType.RSPrimary: + return common_1.TopologyType.ReplicaSetWithPrimary; + case common_1.ServerType.RSOther: + case common_1.ServerType.RSSecondary: + return common_1.TopologyType.ReplicaSetNoPrimary; + default: + return common_1.TopologyType.Unknown; + } +} +// TODO: improve these docs when ObjectId is properly typed +function compareObjectId(oid1, oid2) { + if (oid1 == null) { + return -1; + } + if (oid2 == null) { + return 1; + } + if (oid1.id instanceof Buffer && oid2.id instanceof Buffer) { + const oid1Buffer = oid1.id; + const oid2Buffer = oid2.id; + return oid1Buffer.compare(oid2Buffer); + } + const oid1String = oid1.toString(); + const oid2String = oid2.toString(); + return oid1String.localeCompare(oid2String); +} +function updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId) { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + const electionId = serverDescription.electionId ? serverDescription.electionId : null; + if (serverDescription.setVersion && electionId) { + if (maxSetVersion && maxElectionId) { + if (maxSetVersion > serverDescription.setVersion || + compareObjectId(maxElectionId, electionId) > 0) { + // this primary is stale, we must remove it + serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address)); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + maxElectionId = serverDescription.electionId; + } + if (serverDescription.setVersion != null && + (maxSetVersion == null || serverDescription.setVersion > maxSetVersion)) { + maxSetVersion = serverDescription.setVersion; + } + // We've heard from the primary. Is it the same primary as before? + for (const [address, server] of serverDescriptions) { + if (server.type === common_1.ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new server_description_1.ServerDescription(server.address)); + // There can only be one primary + break; + } + } + // Discover new hosts from this primary's response. + serverDescription.allHosts.forEach((address) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new server_description_1.ServerDescription(address)); + } + }); + // Remove hosts not in the response. + const currentAddresses = Array.from(serverDescriptions.keys()); + const responseAddresses = serverDescription.allHosts; + currentAddresses + .filter((addr) => responseAddresses.indexOf(addr) === -1) + .forEach((address) => { + serverDescriptions.delete(address); + }); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; +} +function updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName) { + if (setName == null) { + // TODO(NODE-3483): should be an appropriate runtime error + throw new error_1.MongoRuntimeError('Argument "setName" is required if connected to a replica set'); + } + if (setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me)) { + serverDescriptions.delete(serverDescription.address); + } + return checkHasPrimary(serverDescriptions); +} +function updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName) { + const topologyType = common_1.TopologyType.ReplicaSetNoPrimary; + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [topologyType, setName]; + } + serverDescription.allHosts.forEach((address) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new server_description_1.ServerDescription(address)); + } + }); + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + return [topologyType, setName]; +} +function checkHasPrimary(serverDescriptions) { + for (const serverDescription of serverDescriptions.values()) { + if (serverDescription.type === common_1.ServerType.RSPrimary) { + return common_1.TopologyType.ReplicaSetWithPrimary; + } + } + return common_1.TopologyType.ReplicaSetNoPrimary; +} +//# sourceMappingURL=topology_description.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/sdam/topology_description.js.map b/node_modules/mongodb/lib/sdam/topology_description.js.map new file mode 100644 index 0000000..48c164f --- /dev/null +++ b/node_modules/mongodb/lib/sdam/topology_description.js.map @@ -0,0 +1 @@ +{"version":3,"file":"topology_description.js","sourceRoot":"","sources":["../../src/sdam/topology_description.ts"],"names":[],"mappings":";;;AAAA,6DAAyD;AACzD,kEAAkE;AAClE,qCAAoD;AAGpD,oCAAyD;AAEzD,4CAA4C;AAC5C,MAAM,4BAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;AACjF,MAAM,4BAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;AACjF,MAAM,0BAA0B,GAAG,cAAc,CAAC,0BAA0B,CAAC;AAC7E,MAAM,0BAA0B,GAAG,cAAc,CAAC,0BAA0B,CAAC;AAE7E,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAa,CAAC,mBAAU,CAAC,MAAM,EAAE,mBAAU,CAAC,OAAO,CAAC,CAAC,CAAC;AACvF,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAa,CAAC,mBAAU,CAAC,MAAM,EAAE,mBAAU,CAAC,UAAU,CAAC,CAAC,CAAC;AAC7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CAAC,CAAC;AACjC,CAAC;AAED,SAAS,eAAe,CAAC,kBAAkD;IACzE,KAAK,MAAM,iBAAiB,IAAI,kBAAkB,CAAC,MAAM,EAAE,EAAE;QAC3D,IAAI,iBAAiB,CAAC,IAAI,KAAK,mBAAU,CAAC,SAAS,EAAE;YACnD,OAAO,qBAAY,CAAC,qBAAqB,CAAC;SAC3C;KACF;IAED,OAAO,qBAAY,CAAC,mBAAmB,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/sessions.js b/node_modules/mongodb/lib/sessions.js new file mode 100644 index 0000000..982b49b --- /dev/null +++ b/node_modules/mongodb/lib/sessions.js @@ -0,0 +1,726 @@ +"use strict"; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.updateSessionFromResponse = exports.applySession = exports.commandSupportsReadConcern = exports.ServerSessionPool = exports.ServerSession = exports.maybeClearPinnedConnection = exports.ClientSession = void 0; +const promise_provider_1 = require("./promise_provider"); +const bson_1 = require("./bson"); +const read_preference_1 = require("./read_preference"); +const transactions_1 = require("./transactions"); +const common_1 = require("./sdam/common"); +const shared_1 = require("./cmap/wire_protocol/shared"); +const error_1 = require("./error"); +const utils_1 = require("./utils"); +const execute_operation_1 = require("./operations/execute_operation"); +const run_command_1 = require("./operations/run_command"); +const connection_1 = require("./cmap/connection"); +const metrics_1 = require("./cmap/metrics"); +const mongo_types_1 = require("./mongo_types"); +const read_concern_1 = require("./read_concern"); +const minWireVersionForShardedTransactions = 8; +function assertAlive(session, callback) { + if (session.serverSession == null) { + const error = new error_1.MongoExpiredSessionError(); + if (typeof callback === 'function') { + callback(error); + return false; + } + throw error; + } + return true; +} +/** @internal */ +const kServerSession = Symbol('serverSession'); +/** @internal */ +const kSnapshotTime = Symbol('snapshotTime'); +/** @internal */ +const kSnapshotEnabled = Symbol('snapshotEnabled'); +/** @internal */ +const kPinnedConnection = Symbol('pinnedConnection'); +/** + * A class representing a client session on the server + * + * NOTE: not meant to be instantiated directly. + * @public + */ +class ClientSession extends mongo_types_1.TypedEventEmitter { + /** + * Create a client session. + * @internal + * @param topology - The current client's topology (Internal Class) + * @param sessionPool - The server session pool (Internal Class) + * @param options - Optional settings + * @param clientOptions - Optional settings provided when creating a MongoClient + */ + constructor(topology, sessionPool, options, clientOptions) { + super(); + /** @internal */ + this[_a] = false; + if (topology == null) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('ClientSession requires a topology'); + } + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('ClientSession requires a ServerSessionPool'); + } + options = options !== null && options !== void 0 ? options : {}; + if (options.snapshot === true) { + this[kSnapshotEnabled] = true; + if (options.causalConsistency === true) { + throw new error_1.MongoInvalidArgumentError('Properties "causalConsistency" and "snapshot" are mutually exclusive'); + } + } + this.topology = topology; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.clientOptions = clientOptions; + this[kServerSession] = undefined; + this.supports = { + causalConsistency: options.snapshot !== true && options.causalConsistency !== false + }; + this.clusterTime = options.initialClusterTime; + this.operationTime = undefined; + this.explicit = !!options.explicit; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new transactions_1.Transaction(); + } + /** The server id associated with this session */ + get id() { + var _b; + return (_b = this.serverSession) === null || _b === void 0 ? void 0 : _b.id; + } + get serverSession() { + if (this[kServerSession] == null) { + this[kServerSession] = this.sessionPool.acquire(); + } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return this[kServerSession]; + } + /** Whether or not this session is configured for snapshot reads */ + get snapshotEnabled() { + return this[kSnapshotEnabled]; + } + get loadBalanced() { + return this.topology.description.type === common_1.TopologyType.LoadBalanced; + } + /** @internal */ + get pinnedConnection() { + return this[kPinnedConnection]; + } + /** @internal */ + pin(conn) { + if (this[kPinnedConnection]) { + throw TypeError('Cannot pin multiple connections to the same session'); + } + this[kPinnedConnection] = conn; + conn.emit(connection_1.Connection.PINNED, this.inTransaction() ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR); + } + /** @internal */ + unpin(options) { + if (this.loadBalanced) { + return maybeClearPinnedConnection(this, options); + } + this.transaction.unpinServer(); + } + get isPinned() { + return this.loadBalanced ? !!this[kPinnedConnection] : this.transaction.isPinned; + } + endSession(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + const finalOptions = { force: true, ...options }; + return utils_1.maybePromise(callback, done => { + if (this.hasEnded) { + maybeClearPinnedConnection(this, finalOptions); + return done(); + } + const completeEndSession = () => { + maybeClearPinnedConnection(this, finalOptions); + // release the server session back to the pool + this.sessionPool.release(this.serverSession); + this[kServerSession] = undefined; + // mark the session as ended, and emit a signal + this.hasEnded = true; + this.emit('ended', this); + // spec indicates that we should ignore all errors for `endSessions` + done(); + }; + if (this.serverSession && this.inTransaction()) { + this.abortTransaction(err => { + if (err) + return done(err); + completeEndSession(); + }); + return; + } + completeEndSession(); + }); + } + /** + * Advances the operationTime for a ClientSession. + * + * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime) { + if (this.operationTime == null) { + this.operationTime = operationTime; + return; + } + if (operationTime.greaterThan(this.operationTime)) { + this.operationTime = operationTime; + } + } + /** + * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession + * + * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature + */ + advanceClusterTime(clusterTime) { + var _b, _c; + if (!clusterTime || typeof clusterTime !== 'object') { + throw new error_1.MongoInvalidArgumentError('input cluster time must be an object'); + } + if (!clusterTime.clusterTime || clusterTime.clusterTime._bsontype !== 'Timestamp') { + throw new error_1.MongoInvalidArgumentError('input cluster time "clusterTime" property must be a valid BSON Timestamp'); + } + if (!clusterTime.signature || + ((_b = clusterTime.signature.hash) === null || _b === void 0 ? void 0 : _b._bsontype) !== 'Binary' || + (typeof clusterTime.signature.keyId !== 'number' && + ((_c = clusterTime.signature.keyId) === null || _c === void 0 ? void 0 : _c._bsontype) !== 'Long') // apparently we decode the key to number? + ) { + throw new error_1.MongoInvalidArgumentError('input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId'); + } + common_1._advanceClusterTime(this, clusterTime); + } + /** + * Used to determine if this session equals another + * + * @param session - The session to compare to + */ + equals(session) { + if (!(session instanceof ClientSession)) { + return false; + } + if (this.id == null || session.id == null) { + return false; + } + return this.id.id.buffer.equals(session.id.id.buffer); + } + /** Increment the transaction number on the internal ServerSession */ + incrementTransactionNumber() { + if (this.serverSession) { + this.serverSession.txnNumber = + typeof this.serverSession.txnNumber === 'number' ? this.serverSession.txnNumber + 1 : 0; + } + } + /** @returns whether this session is currently in a transaction or not */ + inTransaction() { + return this.transaction.isActive; + } + /** + * Starts a new transaction with the given options. + * + * @param options - Options for the transaction + */ + startTransaction(options) { + var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + if (this[kSnapshotEnabled]) { + throw new error_1.MongoCompatibilityError('Transactions are not allowed with snapshot sessions'); + } + assertAlive(this); + if (this.inTransaction()) { + throw new error_1.MongoTransactionError('Transaction already in progress'); + } + if (this.isPinned && this.transaction.isCommitted) { + this.unpin(); + } + const topologyMaxWireVersion = utils_1.maxWireVersion(this.topology); + if (shared_1.isSharded(this.topology) && + topologyMaxWireVersion != null && + topologyMaxWireVersion < minWireVersionForShardedTransactions) { + throw new error_1.MongoCompatibilityError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); + } + // increment txnNumber + this.incrementTransactionNumber(); + // create transaction state + this.transaction = new transactions_1.Transaction({ + readConcern: (_c = (_b = options === null || options === void 0 ? void 0 : options.readConcern) !== null && _b !== void 0 ? _b : this.defaultTransactionOptions.readConcern) !== null && _c !== void 0 ? _c : (_d = this.clientOptions) === null || _d === void 0 ? void 0 : _d.readConcern, + writeConcern: (_f = (_e = options === null || options === void 0 ? void 0 : options.writeConcern) !== null && _e !== void 0 ? _e : this.defaultTransactionOptions.writeConcern) !== null && _f !== void 0 ? _f : (_g = this.clientOptions) === null || _g === void 0 ? void 0 : _g.writeConcern, + readPreference: (_j = (_h = options === null || options === void 0 ? void 0 : options.readPreference) !== null && _h !== void 0 ? _h : this.defaultTransactionOptions.readPreference) !== null && _j !== void 0 ? _j : (_k = this.clientOptions) === null || _k === void 0 ? void 0 : _k.readPreference, + maxCommitTimeMS: (_l = options === null || options === void 0 ? void 0 : options.maxCommitTimeMS) !== null && _l !== void 0 ? _l : this.defaultTransactionOptions.maxCommitTimeMS + }); + this.transaction.transition(transactions_1.TxnState.STARTING_TRANSACTION); + } + commitTransaction(callback) { + return utils_1.maybePromise(callback, cb => endTransaction(this, 'commitTransaction', cb)); + } + abortTransaction(callback) { + return utils_1.maybePromise(callback, cb => endTransaction(this, 'abortTransaction', cb)); + } + /** + * This is here to ensure that ClientSession is never serialized to BSON. + */ + toBSON() { + throw new error_1.MongoRuntimeError('ClientSession cannot be serialized to BSON.'); + } + /** + * Runs a provided lambda within a transaction, retrying either the commit operation + * or entire transaction as needed (and when the error permits) to better ensure that + * the transaction can complete successfully. + * + * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not + * return a Promise will result in undefined behavior. + * + * @param fn - A lambda to run within a transaction + * @param options - Optional settings for the transaction + */ + withTransaction(fn, options) { + const startTime = utils_1.now(); + return attemptTransaction(this, startTime, fn, options); + } +} +exports.ClientSession = ClientSession; +_a = kSnapshotEnabled; +const MAX_WITH_TRANSACTION_TIMEOUT = 120000; +const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ + 'CannotSatisfyWriteConcern', + 'UnknownReplWriteConcern', + 'UnsatisfiableWriteConcern' +]); +function hasNotTimedOut(startTime, max) { + return utils_1.calculateDurationInMs(startTime) < max; +} +function isUnknownTransactionCommitResult(err) { + const isNonDeterministicWriteConcernError = err instanceof error_1.MongoServerError && + err.codeName && + NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName); + return (isMaxTimeMSExpiredError(err) || + (!isNonDeterministicWriteConcernError && + err.code !== error_1.MONGODB_ERROR_CODES.UnsatisfiableWriteConcern && + err.code !== error_1.MONGODB_ERROR_CODES.UnknownReplWriteConcern)); +} +function maybeClearPinnedConnection(session, options) { + // unpin a connection if it has been pinned + const conn = session[kPinnedConnection]; + const error = options === null || options === void 0 ? void 0 : options.error; + if (session.inTransaction() && + error && + error instanceof error_1.MongoError && + error.hasErrorLabel('TransientTransactionError')) { + return; + } + // NOTE: the spec talks about what to do on a network error only, but the tests seem to + // to validate that we don't unpin on _all_ errors? + if (conn) { + const servers = Array.from(session.topology.s.servers.values()); + const loadBalancer = servers[0]; + if ((options === null || options === void 0 ? void 0 : options.error) == null || (options === null || options === void 0 ? void 0 : options.force)) { + loadBalancer.s.pool.checkIn(conn); + conn.emit(connection_1.Connection.UNPINNED, session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION + ? metrics_1.ConnectionPoolMetrics.TXN + : metrics_1.ConnectionPoolMetrics.CURSOR); + if (options === null || options === void 0 ? void 0 : options.forceClear) { + loadBalancer.s.pool.clear(conn.serviceId); + } + } + session[kPinnedConnection] = undefined; + } +} +exports.maybeClearPinnedConnection = maybeClearPinnedConnection; +function isMaxTimeMSExpiredError(err) { + if (err == null || !(err instanceof error_1.MongoServerError)) { + return false; + } + return (err.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired || + (err.writeConcernError && err.writeConcernError.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired)); +} +function attemptTransactionCommit(session, startTime, fn, options) { + return session.commitTransaction().catch((err) => { + if (err instanceof error_1.MongoError && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && + !isMaxTimeMSExpiredError(err)) { + if (err.hasErrorLabel('UnknownTransactionCommitResult')) { + return attemptTransactionCommit(session, startTime, fn, options); + } + if (err.hasErrorLabel('TransientTransactionError')) { + return attemptTransaction(session, startTime, fn, options); + } + } + throw err; + }); +} +const USER_EXPLICIT_TXN_END_STATES = new Set([ + transactions_1.TxnState.NO_TRANSACTION, + transactions_1.TxnState.TRANSACTION_COMMITTED, + transactions_1.TxnState.TRANSACTION_ABORTED +]); +function userExplicitlyEndedTransaction(session) { + return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); +} +function attemptTransaction(session, startTime, fn, options) { + const Promise = promise_provider_1.PromiseProvider.get(); + session.startTransaction(options); + let promise; + try { + promise = fn(session); + } + catch (err) { + promise = Promise.reject(err); + } + if (!utils_1.isPromiseLike(promise)) { + session.abortTransaction(); + throw new error_1.MongoInvalidArgumentError('Function provided to `withTransaction` must return a Promise'); + } + return promise.then(() => { + if (userExplicitlyEndedTransaction(session)) { + return; + } + return attemptTransactionCommit(session, startTime, fn, options); + }, err => { + function maybeRetryOrThrow(err) { + if (err instanceof error_1.MongoError && + err.hasErrorLabel('TransientTransactionError') && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT)) { + return attemptTransaction(session, startTime, fn, options); + } + if (isMaxTimeMSExpiredError(err)) { + err.addErrorLabel('UnknownTransactionCommitResult'); + } + throw err; + } + if (session.transaction.isActive) { + return session.abortTransaction().then(() => maybeRetryOrThrow(err)); + } + return maybeRetryOrThrow(err); + }); +} +function endTransaction(session, commandName, callback) { + if (!assertAlive(session, callback)) { + // checking result in case callback was called + return; + } + // handle any initial problematic cases + const txnState = session.transaction.state; + if (txnState === transactions_1.TxnState.NO_TRANSACTION) { + callback(new error_1.MongoTransactionError('No transaction started')); + return; + } + if (commandName === 'commitTransaction') { + if (txnState === transactions_1.TxnState.STARTING_TRANSACTION || + txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) { + // the transaction was never started, we can safely exit here + session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(); + return; + } + if (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) { + callback(new error_1.MongoTransactionError('Cannot call commitTransaction after calling abortTransaction')); + return; + } + } + else { + if (txnState === transactions_1.TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED); + callback(); + return; + } + if (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) { + callback(new error_1.MongoTransactionError('Cannot call abortTransaction twice')); + return; + } + if (txnState === transactions_1.TxnState.TRANSACTION_COMMITTED || + txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) { + callback(new error_1.MongoTransactionError('Cannot call abortTransaction after calling commitTransaction')); + return; + } + } + // construct and send the command + const command = { [commandName]: 1 }; + // apply a writeConcern if specified + let writeConcern; + if (session.transaction.options.writeConcern) { + writeConcern = Object.assign({}, session.transaction.options.writeConcern); + } + else if (session.clientOptions && session.clientOptions.writeConcern) { + writeConcern = { w: session.clientOptions.writeConcern.w }; + } + if (txnState === transactions_1.TxnState.TRANSACTION_COMMITTED) { + writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); + } + if (writeConcern) { + Object.assign(command, { writeConcern }); + } + if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { + Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); + } + function commandHandler(e, r) { + if (commandName !== 'commitTransaction') { + session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED); + if (session.loadBalanced) { + maybeClearPinnedConnection(session, { force: false }); + } + // The spec indicates that we should ignore all errors on `abortTransaction` + return callback(); + } + session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED); + if (e) { + if (e instanceof error_1.MongoNetworkError || + e instanceof error_1.MongoWriteConcernError || + error_1.isRetryableError(e) || + isMaxTimeMSExpiredError(e)) { + if (isUnknownTransactionCommitResult(e)) { + e.addErrorLabel('UnknownTransactionCommitResult'); + // per txns spec, must unpin session in this case + session.unpin({ error: e }); + } + } + else if (e.hasErrorLabel('TransientTransactionError')) { + session.unpin({ error: e }); + } + } + callback(e, r); + } + // Assumption here that commandName is "commitTransaction" or "abortTransaction" + if (session.transaction.recoveryToken) { + command.recoveryToken = session.transaction.recoveryToken; + } + // send the command + execute_operation_1.executeOperation(session.topology, new run_command_1.RunAdminCommandOperation(undefined, command, { + session, + readPreference: read_preference_1.ReadPreference.primary, + bypassPinningCheck: true + }), (err, reply) => { + if (command.abortTransaction) { + // always unpin on abort regardless of command outcome + session.unpin(); + } + if (err && error_1.isRetryableError(err)) { + // SPEC-1185: apply majority write concern when retrying commitTransaction + if (command.commitTransaction) { + // per txns spec, must unpin session in this case + session.unpin({ force: true }); + command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { + w: 'majority' + }); + } + return execute_operation_1.executeOperation(session.topology, new run_command_1.RunAdminCommandOperation(undefined, command, { + session, + readPreference: read_preference_1.ReadPreference.primary, + bypassPinningCheck: true + }), (_err, _reply) => commandHandler(_err, _reply)); + } + commandHandler(err, reply); + }); +} +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @public + */ +class ServerSession { + /** @internal */ + constructor() { + this.id = { id: new bson_1.Binary(utils_1.uuidV4(), bson_1.Binary.SUBTYPE_UUID) }; + this.lastUse = utils_1.now(); + this.txnNumber = 0; + this.isDirty = false; + } + /** + * Determines if the server session has timed out. + * + * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" + */ + hasTimedOut(sessionTimeoutMinutes) { + // Take the difference of the lastUse timestamp and now, which will result in a value in + // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` + const idleTimeMinutes = Math.round(((utils_1.calculateDurationInMs(this.lastUse) % 86400000) % 3600000) / 60000); + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } +} +exports.ServerSession = ServerSession; +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @internal + */ +class ServerSessionPool { + constructor(topology) { + if (topology == null) { + throw new error_1.MongoRuntimeError('ServerSessionPool requires a topology'); + } + this.topology = topology; + this.sessions = []; + } + /** Ends all sessions in the session pool */ + endAllPooledSessions(callback) { + if (this.sessions.length) { + this.topology.endSessions(this.sessions.map((session) => session.id), () => { + this.sessions = []; + if (typeof callback === 'function') { + callback(); + } + }); + return; + } + if (typeof callback === 'function') { + callback(); + } + } + /** + * Acquire a Server Session from the pool. + * Iterates through each session in the pool, removing any stale sessions + * along the way. The first non-stale session found is removed from the + * pool and returned. If no non-stale session is found, a new ServerSession is created. + */ + acquire() { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes || 10; + while (this.sessions.length) { + const session = this.sessions.shift(); + if (session && (this.topology.loadBalanced || !session.hasTimedOut(sessionTimeoutMinutes))) { + return session; + } + } + return new ServerSession(); + } + /** + * Release a session to the session pool + * Adds the session back to the session pool if the session has not timed out yet. + * This method also removes any stale sessions from the pool. + * + * @param session - The session to release to the pool + */ + release(session) { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + if (this.topology.loadBalanced && !sessionTimeoutMinutes) { + this.sessions.unshift(session); + } + if (!sessionTimeoutMinutes) { + return; + } + while (this.sessions.length) { + const pooledSession = this.sessions[this.sessions.length - 1]; + if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.pop(); + } + else { + break; + } + } + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + if (session.isDirty) { + return; + } + // otherwise, readd this session to the session pool + this.sessions.unshift(session); + } + } +} +exports.ServerSessionPool = ServerSessionPool; +// TODO: this should be codified in command construction +// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern +function commandSupportsReadConcern(command, options) { + if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) { + return true; + } + if (command.mapReduce && + options && + options.out && + (options.out.inline === 1 || options.out === 'inline')) { + return true; + } + return false; +} +exports.commandSupportsReadConcern = commandSupportsReadConcern; +/** + * Optionally decorate a command with sessions specific keys + * + * @param session - the session tracking transaction state + * @param command - the command to decorate + * @param options - Optional settings passed to calling operation + */ +function applySession(session, command, options) { + var _b; + // TODO: merge this with `assertAlive`, did not want to throw a try/catch here + if (session.hasEnded) { + return new error_1.MongoExpiredSessionError(); + } + const serverSession = session.serverSession; + if (serverSession == null) { + return new error_1.MongoRuntimeError('Unable to acquire server session'); + } + // SPEC-1019: silently ignore explicit session with unacknowledged write for backwards compatibility + // FIXME: NODE-2781, this check for write concern shouldn't be happening here, but instead during command construction + if (options && options.writeConcern && options.writeConcern.w === 0) { + if (session && session.explicit) { + return new error_1.MongoAPIError('Cannot have explicit session with unacknowledged writes'); + } + return; + } + // mark the last use of this session, and apply the `lsid` + serverSession.lastUse = utils_1.now(); + command.lsid = serverSession.id; + // first apply non-transaction-specific sessions data + const inTransaction = session.inTransaction() || transactions_1.isTransactionCommand(command); + const isRetryableWrite = (options === null || options === void 0 ? void 0 : options.willRetryWrite) || false; + if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { + command.txnNumber = bson_1.Long.fromNumber(serverSession.txnNumber); + } + if (!inTransaction) { + if (session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION) { + session.transaction.transition(transactions_1.TxnState.NO_TRANSACTION); + } + if (session.supports.causalConsistency && + session.operationTime && + commandSupportsReadConcern(command, options)) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + else if (session[kSnapshotEnabled]) { + command.readConcern = command.readConcern || { level: read_concern_1.ReadConcernLevel.snapshot }; + if (session[kSnapshotTime] != null) { + Object.assign(command.readConcern, { atClusterTime: session[kSnapshotTime] }); + } + } + return; + } + // now attempt to apply transaction-specific sessions data + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + if (session.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) { + session.transaction.transition(transactions_1.TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + const readConcern = session.transaction.options.readConcern || ((_b = session === null || session === void 0 ? void 0 : session.clientOptions) === null || _b === void 0 ? void 0 : _b.readConcern); + if (readConcern) { + command.readConcern = readConcern; + } + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + } +} +exports.applySession = applySession; +function updateSessionFromResponse(session, document) { + var _b; + if (document.$clusterTime) { + common_1._advanceClusterTime(session, document.$clusterTime); + } + if (document.operationTime && session && session.supports.causalConsistency) { + session.advanceOperationTime(document.operationTime); + } + if (document.recoveryToken && session && session.inTransaction()) { + session.transaction._recoveryToken = document.recoveryToken; + } + if ((session === null || session === void 0 ? void 0 : session[kSnapshotEnabled]) && session[kSnapshotTime] == null) { + // find and aggregate commands return atClusterTime on the cursor + // distinct includes it in the response body + const atClusterTime = ((_b = document.cursor) === null || _b === void 0 ? void 0 : _b.atClusterTime) || document.atClusterTime; + if (atClusterTime) { + session[kSnapshotTime] = atClusterTime; + } + } +} +exports.updateSessionFromResponse = updateSessionFromResponse; +//# sourceMappingURL=sessions.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/sessions.js.map b/node_modules/mongodb/lib/sessions.js.map new file mode 100644 index 0000000..fef06fa --- /dev/null +++ b/node_modules/mongodb/lib/sessions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sessions.js","sourceRoot":"","sources":["../src/sessions.ts"],"names":[],"mappings":";;;;AAAA,yDAAqD;AACrD,iCAA2D;AAC3D,uDAAmD;AACnD,iDAAiG;AACjG,0CAA+E;AAC/E,wDAAwD;AACxD,mCAeiB;AACjB,mCAQiB;AAGjB,sEAAkE;AAClE,0DAAoE;AAGpE,kDAA+C;AAC/C,4CAAuD;AAEvD,+CAAkD;AAClD,iDAAkD;AAElD,MAAM,oCAAoC,GAAG,CAAC,CAAC;AAE/C,SAAS,WAAW,CAAC,OAAsB,EAAE,QAAmB;IAC9D,IAAI,OAAO,CAAC,aAAa,IAAI,IAAI,EAAE;QACjC,MAAM,KAAK,GAAG,IAAI,gCAAwB,EAAE,CAAC;QAC7C,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;YAClC,QAAQ,CAAC,KAAK,CAAC,CAAC;YAChB,OAAO,KAAK,CAAC;SACd;QAED,MA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,MAAM,aAAa,GAAG,CAAA,MAAA,QAAQ,CAAC,MAAM,0CAAE,aAAa,KAAI,QAAQ,CAAC,aAAa,CAAC;QAC/E,IAAI,aAAa,EAAE;YACjB,OAAO,CAAC,aAAa,CAAC,GAAG,aAAa,CAAC;SACxC;KACF;AACH,CAAC;AArBD,8DAqBC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/sort.js b/node_modules/mongodb/lib/sort.js new file mode 100644 index 0000000..c04b6b5 --- /dev/null +++ b/node_modules/mongodb/lib/sort.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.formatSort = void 0; +const error_1 = require("./error"); +/** @internal */ +function prepareDirection(direction = 1) { + const value = `${direction}`.toLowerCase(); + if (isMeta(direction)) + return direction; + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new error_1.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`); + } +} +/** @internal */ +function isMeta(t) { + return typeof t === 'object' && t != null && '$meta' in t && typeof t.$meta === 'string'; +} +/** @internal */ +function isPair(t) { + if (Array.isArray(t) && t.length === 2) { + try { + prepareDirection(t[1]); + return true; + } + catch (e) { + return false; + } + } + return false; +} +function isDeep(t) { + return Array.isArray(t) && Array.isArray(t[0]); +} +function isMap(t) { + return t instanceof Map && t.size > 0; +} +/** @internal */ +function pairToMap(v) { + return new Map([[`${v[0]}`, prepareDirection([v[1]])]]); +} +/** @internal */ +function deepToMap(t) { + const sortEntries = t.map(([k, v]) => [`${k}`, prepareDirection(v)]); + return new Map(sortEntries); +} +/** @internal */ +function stringsToMap(t) { + const sortEntries = t.map(key => [`${key}`, 1]); + return new Map(sortEntries); +} +/** @internal */ +function objectToMap(t) { + const sortEntries = Object.entries(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} +/** @internal */ +function mapToMap(t) { + const sortEntries = Array.from(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} +/** converts a Sort type into a type that is valid for the server (SortForCmd) */ +function formatSort(sort, direction) { + if (sort == null) + return undefined; + if (typeof sort === 'string') + return new Map([[sort, prepareDirection(direction)]]); + if (typeof sort !== 'object') { + throw new error_1.MongoInvalidArgumentError(`Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object`); + } + if (!Array.isArray(sort)) { + return isMap(sort) ? mapToMap(sort) : Object.keys(sort).length ? objectToMap(sort) : undefined; + } + if (!sort.length) + return undefined; + if (isDeep(sort)) + return deepToMap(sort); + if (isPair(sort)) + return pairToMap(sort); + return stringsToMap(sort); +} +exports.formatSort = formatSort; +//# sourceMappingURL=sort.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/sort.js.map b/node_modules/mongodb/lib/sort.js.map new file mode 100644 index 0000000..4072af4 --- /dev/null +++ b/node_modules/mongodb/lib/sort.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.js","sourceRoot":"","sources":["../src/sort.ts"],"names":[],"mappings":";;;AAAA,mCAAoD;AAiCpD,gBAAgB;AAChB,SAAS,gBAAgB,CAAC,YAAiB,CAAC;IAC1C,MAAM,KAAK,GAAG,GAAG,SAAS,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3C,IAAI,MAAM,CAAC,SAAS,CAAC;QAAE,OAAO,SAAS,CAAC;IACxC,QAAQ,KAAK,EAAE;QACb,KAAK,WAAW,CAAC;QACjB,KAAK,KAAK,CAAC;QACX,KAAK,GAAG;YACN,OAAO,CAAC,CAAC;QACX,KAAK,YAAY,CAAC;QAClB,KAAK,MAAM,CAAC;QACZ,KAAK,IAAI;YACP,OAAO,CAAC,CAAC,CAAC;QACZ;YACE,MAAM,IAAI,iCAAyB,CAAC,2BAA2B,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;KAC/F;AACH,CAAC;AAED,gBAAgB;AAChB,SAAS,MAAM,CAAC,CAAgB;IAC9B,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IAAI,CAAC,8BAA8B,CAC3E,CAAC;KACH;IACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;QACxB,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;KAChG;IACD,IAAI,CAAC,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IACnC,IAAI,MAAM,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;IACzC,IAAI,MAAM,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;IACzC,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC;AAC5B,CAAC;AAlBD,gCAkBC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/transactions.js b/node_modules/mongodb/lib/transactions.js new file mode 100644 index 0000000..d74b673 --- /dev/null +++ b/node_modules/mongodb/lib/transactions.js @@ -0,0 +1,138 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isTransactionCommand = exports.Transaction = exports.TxnState = void 0; +const read_preference_1 = require("./read_preference"); +const error_1 = require("./error"); +const read_concern_1 = require("./read_concern"); +const write_concern_1 = require("./write_concern"); +/** @internal */ +exports.TxnState = Object.freeze({ + NO_TRANSACTION: 'NO_TRANSACTION', + STARTING_TRANSACTION: 'STARTING_TRANSACTION', + TRANSACTION_IN_PROGRESS: 'TRANSACTION_IN_PROGRESS', + TRANSACTION_COMMITTED: 'TRANSACTION_COMMITTED', + TRANSACTION_COMMITTED_EMPTY: 'TRANSACTION_COMMITTED_EMPTY', + TRANSACTION_ABORTED: 'TRANSACTION_ABORTED' +}); +const stateMachine = { + [exports.TxnState.NO_TRANSACTION]: [exports.TxnState.NO_TRANSACTION, exports.TxnState.STARTING_TRANSACTION], + [exports.TxnState.STARTING_TRANSACTION]: [ + exports.TxnState.TRANSACTION_IN_PROGRESS, + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.TRANSACTION_ABORTED + ], + [exports.TxnState.TRANSACTION_IN_PROGRESS]: [ + exports.TxnState.TRANSACTION_IN_PROGRESS, + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_ABORTED + ], + [exports.TxnState.TRANSACTION_COMMITTED]: [ + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.STARTING_TRANSACTION, + exports.TxnState.NO_TRANSACTION + ], + [exports.TxnState.TRANSACTION_ABORTED]: [exports.TxnState.STARTING_TRANSACTION, exports.TxnState.NO_TRANSACTION], + [exports.TxnState.TRANSACTION_COMMITTED_EMPTY]: [ + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.NO_TRANSACTION + ] +}; +const ACTIVE_STATES = new Set([ + exports.TxnState.STARTING_TRANSACTION, + exports.TxnState.TRANSACTION_IN_PROGRESS +]); +const COMMITTED_STATES = new Set([ + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.TRANSACTION_ABORTED +]); +/** + * @public + * A class maintaining state related to a server transaction. Internal Only + */ +class Transaction { + /** Create a transaction @internal */ + constructor(options) { + options = options !== null && options !== void 0 ? options : {}; + this.state = exports.TxnState.NO_TRANSACTION; + this.options = {}; + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (writeConcern) { + if (writeConcern.w === 0) { + throw new error_1.MongoTransactionError('Transactions do not support unacknowledged write concern'); + } + this.options.writeConcern = writeConcern; + } + if (options.readConcern) { + this.options.readConcern = read_concern_1.ReadConcern.fromOptions(options); + } + if (options.readPreference) { + this.options.readPreference = read_preference_1.ReadPreference.fromOptions(options); + } + if (options.maxCommitTimeMS) { + this.options.maxTimeMS = options.maxCommitTimeMS; + } + // TODO: This isn't technically necessary + this._pinnedServer = undefined; + this._recoveryToken = undefined; + } + /** @internal */ + get server() { + return this._pinnedServer; + } + get recoveryToken() { + return this._recoveryToken; + } + get isPinned() { + return !!this.server; + } + /** @returns Whether the transaction has started */ + get isStarting() { + return this.state === exports.TxnState.STARTING_TRANSACTION; + } + /** + * @returns Whether this session is presently in a transaction + */ + get isActive() { + return ACTIVE_STATES.has(this.state); + } + get isCommitted() { + return COMMITTED_STATES.has(this.state); + } + /** + * Transition the transaction in the state machine + * @internal + * @param nextState - The new state to transition to + */ + transition(nextState) { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.includes(nextState)) { + this.state = nextState; + if (this.state === exports.TxnState.NO_TRANSACTION || + this.state === exports.TxnState.STARTING_TRANSACTION || + this.state === exports.TxnState.TRANSACTION_ABORTED) { + this.unpinServer(); + } + return; + } + throw new error_1.MongoRuntimeError(`Attempted illegal state transition from [${this.state}] to [${nextState}]`); + } + /** @internal */ + pinServer(server) { + if (this.isActive) { + this._pinnedServer = server; + } + } + /** @internal */ + unpinServer() { + this._pinnedServer = undefined; + } +} +exports.Transaction = Transaction; +function isTransactionCommand(command) { + return !!(command.commitTransaction || command.abortTransaction); +} +exports.isTransactionCommand = isTransactionCommand; +//# sourceMappingURL=transactions.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/transactions.js.map b/node_modules/mongodb/lib/transactions.js.map new file mode 100644 index 0000000..0f55f61 --- /dev/null +++ b/node_modules/mongodb/lib/transactions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transactions.js","sourceRoot":"","sources":["../src/transactions.ts"],"names":[],"mappings":";;;AAAA,uDAAmD;AACnD,mCAAmE;AACnE,iDAA6C;AAC7C,mDAA+C;AAK/C,gBAAgB;AACH,QAAA,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC;IACpC,cAAc,EAAE,gBAAgB;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AAFD,oDAEC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/utils.js b/node_modules/mongodb/lib/utils.js new file mode 100644 index 0000000..00df726 --- /dev/null +++ b/node_modules/mongodb/lib/utils.js @@ -0,0 +1,1150 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enumToString = exports.emitWarningOnce = exports.emitWarning = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.deepCopy = exports.isRecord = exports.setDifference = exports.isSuperset = exports.resolveOptions = exports.hasAtomicOperators = exports.makeInterruptibleAsyncInterval = exports.calculateDurationInMs = exports.now = exports.makeClientMetadata = exports.makeStateMachine = exports.errorStrictEqual = exports.arrayStrictEqual = exports.eachAsyncSeries = exports.eachAsync = exports.collationNotSupported = exports.maxWireVersion = exports.uuidV4 = exports.collectionNamespace = exports.databaseNamespace = exports.maybePromise = exports.makeCounter = exports.MongoDBNamespace = exports.ns = exports.deprecateOptions = exports.defaultMsgHandler = exports.getTopology = exports.decorateWithExplain = exports.decorateWithReadConcern = exports.decorateWithCollation = exports.isPromiseLike = exports.applyWriteConcern = exports.applyRetryableWrites = exports.executeLegacyOperation = exports.filterOptions = exports.mergeOptions = exports.decorateCommand = exports.isObject = exports.parseIndexOptions = exports.normalizeHintField = exports.checkCollectionName = exports.getSingleProperty = exports.MAX_JS_INT = void 0; +exports.parsePackageVersion = exports.supportsRetryableWrites = void 0; +const os = require("os"); +const crypto = require("crypto"); +const promise_provider_1 = require("./promise_provider"); +const error_1 = require("./error"); +const write_concern_1 = require("./write_concern"); +const common_1 = require("./sdam/common"); +const read_concern_1 = require("./read_concern"); +const bson_1 = require("./bson"); +const read_preference_1 = require("./read_preference"); +const url_1 = require("url"); +const constants_1 = require("./cmap/wire_protocol/constants"); +exports.MAX_JS_INT = Number.MAX_SAFE_INTEGER + 1; +/** + * Add a readonly enumerable property. + * @internal + */ +function getSingleProperty(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable: true, + get() { + return value; + } + }); +} +exports.getSingleProperty = getSingleProperty; +/** + * Throws if collectionName is not a valid mongodb collection namespace. + * @internal + */ +function checkCollectionName(collectionName) { + if ('string' !== typeof collectionName) { + throw new error_1.MongoInvalidArgumentError('Collection name must be a String'); + } + if (!collectionName || collectionName.indexOf('..') !== -1) { + throw new error_1.MongoInvalidArgumentError('Collection names cannot be empty'); + } + if (collectionName.indexOf('$') !== -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoInvalidArgumentError("Collection names must not contain '$'"); + } + if (collectionName.match(/^\.|\.$/) != null) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoInvalidArgumentError("Collection names must not start or end with '.'"); + } + // Validate that we are not passing 0x00 in the collection name + if (collectionName.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoInvalidArgumentError('Collection names cannot contain a null character'); + } +} +exports.checkCollectionName = checkCollectionName; +/** + * Ensure Hint field is in a shape we expect: + * - object of index names mapping to 1 or -1 + * - just an index name + * @internal + */ +function normalizeHintField(hint) { + let finalHint = undefined; + if (typeof hint === 'string') { + finalHint = hint; + } + else if (Array.isArray(hint)) { + finalHint = {}; + hint.forEach(param => { + finalHint[param] = 1; + }); + } + else if (hint != null && typeof hint === 'object') { + finalHint = {}; + for (const name in hint) { + finalHint[name] = hint[name]; + } + } + return finalHint; +} +exports.normalizeHintField = normalizeHintField; +/** + * Create an index specifier based on + * @internal + */ +function parseIndexOptions(indexSpec) { + const fieldHash = {}; + const indexes = []; + let keys; + // Get all the fields accordingly + if ('string' === typeof indexSpec) { + // 'type' + indexes.push(indexSpec + '_' + 1); + fieldHash[indexSpec] = 1; + } + else if (Array.isArray(indexSpec)) { + indexSpec.forEach((f) => { + if ('string' === typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } + else if (Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } + else if (isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(k => { + indexes.push(k + '_' + f[k]); + fieldHash[k] = f[k]; + }); + } + else { + // undefined (ignore) + } + }); + } + else if (isObject(indexSpec)) { + // {location:'2d', type:1} + keys = Object.keys(indexSpec); + Object.entries(indexSpec).forEach(([key, value]) => { + indexes.push(key + '_' + value); + fieldHash[key] = value; + }); + } + return { + name: indexes.join('_'), + keys: keys, + fieldHash: fieldHash + }; +} +exports.parseIndexOptions = parseIndexOptions; +/** + * Checks if arg is an Object: + * - **NOTE**: the check is based on the `[Symbol.toStringTag]() === 'Object'` + * @internal + */ +// eslint-disable-next-line @typescript-eslint/ban-types +function isObject(arg) { + return '[object Object]' === Object.prototype.toString.call(arg); +} +exports.isObject = isObject; +/** @internal */ +function decorateCommand(command, options, exclude) { + for (const name in options) { + if (!exclude.includes(name)) { + command[name] = options[name]; + } + } + return command; +} +exports.decorateCommand = decorateCommand; +/** @internal */ +function mergeOptions(target, source) { + return { ...target, ...source }; +} +exports.mergeOptions = mergeOptions; +/** @internal */ +function filterOptions(options, names) { + const filterOptions = {}; + for (const name in options) { + if (names.includes(name)) { + filterOptions[name] = options[name]; + } + } + // Filtered options + return filterOptions; +} +exports.filterOptions = filterOptions; +/** + * Executes the given operation with provided arguments. + * + * @remarks + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @internal + * + * @param topology - The topology to execute this operation on + * @param operation - The operation to execute + * @param args - Arguments to apply the provided operation + * @param options - Options that modify the behavior of the method + */ +function executeLegacyOperation(topology, operation, args, options) { + const Promise = promise_provider_1.PromiseProvider.get(); + if (!Array.isArray(args)) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('This method requires an array of arguments to apply'); + } + options = options !== null && options !== void 0 ? options : {}; + let callback = args[args.length - 1]; + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session; + let opOptions; + let owner; + if (!options.skipSessions && topology.hasSessionSupport()) { + opOptions = args[args.length - 2]; + if (opOptions == null || opOptions.session == null) { + owner = Symbol(); + session = topology.startSession({ owner }); + const optionsIndex = args.length - 2; + args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); + } + else if (opOptions.session && opOptions.session.hasEnded) { + throw new error_1.MongoExpiredSessionError(); + } + } + function makeExecuteCallback(resolve, reject) { + return function (err, result) { + if (session && session.owner === owner && !(options === null || options === void 0 ? void 0 : options.returnsCursor)) { + session.endSession(() => { + delete opOptions.session; + if (err) + return reject(err); + resolve(result); + }); + } + else { + if (err) + return reject(err); + resolve(result); + } + }; + } + // Execute using callback + if (typeof callback === 'function') { + callback = args.pop(); + const handler = makeExecuteCallback(result => callback(undefined, result), err => callback(err, null)); + args.push(handler); + try { + return operation(...args); + } + catch (e) { + handler(e); + throw e; + } + } + // Return a Promise + if (args[args.length - 1] != null) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('Final argument to `executeLegacyOperation` must be a callback'); + } + return new Promise((resolve, reject) => { + const handler = makeExecuteCallback(resolve, reject); + args[args.length - 1] = handler; + try { + return operation(...args); + } + catch (e) { + handler(e); + } + }); +} +exports.executeLegacyOperation = executeLegacyOperation; +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * @internal + * + * @param target - The target command to which we will apply retryWrites. + * @param db - The database from which we can inherit a retryWrites value. + */ +function applyRetryableWrites(target, db) { + var _a; + if (db && ((_a = db.s.options) === null || _a === void 0 ? void 0 : _a.retryWrites)) { + target.retryWrites = true; + } + return target; +} +exports.applyRetryableWrites = applyRetryableWrites; +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * @internal + * + * @param target - the target command we will be applying the write concern to + * @param sources - sources where we can inherit default write concerns from + * @param options - optional settings passed into a command for write concern overrides + */ +function applyWriteConcern(target, sources, options) { + options = options !== null && options !== void 0 ? options : {}; + const db = sources.db; + const coll = sources.collection; + if (options.session && options.session.inTransaction()) { + // writeConcern is not allowed within a multi-statement transaction + if (target.writeConcern) { + delete target.writeConcern; + } + return target; + } + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (writeConcern) { + return Object.assign(target, { writeConcern }); + } + if (coll && coll.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); + } + if (db && db.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); + } + return target; +} +exports.applyWriteConcern = applyWriteConcern; +/** + * Checks if a given value is a Promise + * + * @typeParam T - The result type of maybePromise + * @param maybePromise - An object that could be a promise + * @returns true if the provided value is a Promise + */ +function isPromiseLike(maybePromise) { + return !!maybePromise && typeof maybePromise.then === 'function'; +} +exports.isPromiseLike = isPromiseLike; +/** + * Applies collation to a given command. + * @internal + * + * @param command - the command on which to apply collation + * @param target - target of command + * @param options - options containing collation settings + */ +function decorateWithCollation(command, target, options) { + const capabilities = getTopology(target).capabilities; + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; + } + else { + throw new error_1.MongoCompatibilityError(`Current topology does not support collation`); + } + } +} +exports.decorateWithCollation = decorateWithCollation; +/** + * Applies a read concern to a given command. + * @internal + * + * @param command - the command on which to apply the read concern + * @param coll - the parent collection of the operation calling this method + */ +function decorateWithReadConcern(command, coll, options) { + if (options && options.session && options.session.inTransaction()) { + return; + } + const readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern: readConcern }); + } +} +exports.decorateWithReadConcern = decorateWithReadConcern; +/** + * Applies an explain to a given command. + * @internal + * + * @param command - the command on which to apply the explain + * @param options - the options containing the explain verbosity + */ +function decorateWithExplain(command, explain) { + if (command.explain) { + return command; + } + return { explain: command, verbosity: explain.verbosity }; +} +exports.decorateWithExplain = decorateWithExplain; +/** + * A helper function to get the topology from a given provider. Throws + * if the topology cannot be found. + * @internal + */ +function getTopology(provider) { + if (`topology` in provider && provider.topology) { + return provider.topology; + } + else if ('client' in provider.s && provider.s.client.topology) { + return provider.s.client.topology; + } + else if ('db' in provider.s && provider.s.db.s.client.topology) { + return provider.s.db.s.client.topology; + } + throw new error_1.MongoNotConnectedError('MongoClient must be connected to perform this operation'); +} +exports.getTopology = getTopology; +/** + * Default message handler for generating deprecation warnings. + * @internal + * + * @param name - function name + * @param option - option name + * @returns warning message + */ +function defaultMsgHandler(name, option) { + return `${name} option [${option}] is deprecated and will be removed in a later version.`; +} +exports.defaultMsgHandler = defaultMsgHandler; +/** + * Deprecates a given function's options. + * @internal + * + * @param this - the bound class if this is a method + * @param config - configuration for deprecation + * @param fn - the target function of deprecation + * @returns modified function that warns once per deprecated option, and executes original function + */ +function deprecateOptions(config, fn) { + if (process.noDeprecation === true) { + return fn; + } + const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; + const optionsWarned = new Set(); + function deprecated(...args) { + const options = args[config.optionsIndex]; + // ensure options is a valid, non-empty object, otherwise short-circuit + if (!isObject(options) || Object.keys(options).length === 0) { + return fn.bind(this)(...args); // call the function, no change + } + // interrupt the function call with a warning + for (const deprecatedOption of config.deprecatedOptions) { + if (deprecatedOption in options && !optionsWarned.has(deprecatedOption)) { + optionsWarned.add(deprecatedOption); + const msg = msgHandler(config.name, deprecatedOption); + emitWarning(msg); + if (this && 'getLogger' in this) { + const logger = this.getLogger(); + if (logger) { + logger.warn(msg); + } + } + } + } + return fn.bind(this)(...args); + } + // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 + // The wrapper will keep the same prototype as fn to maintain prototype chain + Object.setPrototypeOf(deprecated, fn); + if (fn.prototype) { + // Setting this (rather than using Object.setPrototype, as above) ensures + // that calling the unwrapped constructor gives an instanceof the wrapped + // constructor. + deprecated.prototype = fn.prototype; + } + return deprecated; +} +exports.deprecateOptions = deprecateOptions; +/** @internal */ +function ns(ns) { + return MongoDBNamespace.fromString(ns); +} +exports.ns = ns; +/** @public */ +class MongoDBNamespace { + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(db, collection) { + this.db = db; + this.collection = collection; + } + toString() { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + withCollection(collection) { + return new MongoDBNamespace(this.db, collection); + } + static fromString(namespace) { + if (!namespace) { + // TODO(NODE-3483): Replace with MongoNamespaceError + throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); + } + const [db, ...collection] = namespace.split('.'); + return new MongoDBNamespace(db, collection.join('.')); + } +} +exports.MongoDBNamespace = MongoDBNamespace; +/** @internal */ +function* makeCounter(seed = 0) { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} +exports.makeCounter = makeCounter; +/** + * Helper function for either accepting a callback, or returning a promise + * @internal + * + * @param callback - The last function argument in exposed method, controls if a Promise is returned + * @param wrapper - A function that wraps the callback + * @returns Returns void if a callback is supplied, else returns a Promise. + */ +function maybePromise(callback, wrapper) { + const Promise = promise_provider_1.PromiseProvider.get(); + let result; + if (typeof callback !== 'function') { + result = new Promise((resolve, reject) => { + callback = (err, res) => { + if (err) + return reject(err); + resolve(res); + }; + }); + } + wrapper((err, res) => { + if (err != null) { + try { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + callback(err); + } + catch (error) { + process.nextTick(() => { + throw error; + }); + } + return; + } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + callback(err, res); + }); + return result; +} +exports.maybePromise = maybePromise; +/** @internal */ +function databaseNamespace(ns) { + return ns.split('.')[0]; +} +exports.databaseNamespace = databaseNamespace; +/** @internal */ +function collectionNamespace(ns) { + return ns.split('.').slice(1).join('.'); +} +exports.collectionNamespace = collectionNamespace; +/** + * Synchronously Generate a UUIDv4 + * @internal + */ +function uuidV4() { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +} +exports.uuidV4 = uuidV4; +/** + * A helper function for determining `maxWireVersion` between legacy and new topology instances + * @internal + */ +function maxWireVersion(topologyOrServer) { + if (topologyOrServer) { + if (topologyOrServer.loadBalanced) { + // Since we do not have a monitor, we assume the load balanced server is always + // pointed at the latest mongodb version. There is a risk that for on-prem + // deployments that don't upgrade immediately that this could alert to the + // application that a feature is avaiable that is actually not. + return constants_1.MAX_SUPPORTED_WIRE_VERSION; + } + if (topologyOrServer.ismaster) { + return topologyOrServer.ismaster.maxWireVersion; + } + if ('lastIsMaster' in topologyOrServer && typeof topologyOrServer.lastIsMaster === 'function') { + const lastIsMaster = topologyOrServer.lastIsMaster(); + if (lastIsMaster) { + return lastIsMaster.maxWireVersion; + } + } + if (topologyOrServer.description && + 'maxWireVersion' in topologyOrServer.description && + topologyOrServer.description.maxWireVersion != null) { + return topologyOrServer.description.maxWireVersion; + } + } + return 0; +} +exports.maxWireVersion = maxWireVersion; +/** + * Checks that collation is supported by server. + * @internal + * + * @param server - to check against + * @param cmd - object where collation may be specified + */ +function collationNotSupported(server, cmd) { + return cmd && cmd.collation && maxWireVersion(server) < 5; +} +exports.collationNotSupported = collationNotSupported; +/** + * Applies the function `eachFn` to each item in `arr`, in parallel. + * @internal + * + * @param arr - An array of items to asynchronously iterate over + * @param eachFn - A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. + * @param callback - The callback called after every item has been iterated + */ +function eachAsync(arr, eachFn, callback) { + arr = arr || []; + let idx = 0; + let awaiting = 0; + for (idx = 0; idx < arr.length; ++idx) { + awaiting++; + eachFn(arr[idx], eachCallback); + } + if (awaiting === 0) { + callback(); + return; + } + function eachCallback(err) { + awaiting--; + if (err) { + callback(err); + return; + } + if (idx === arr.length && awaiting <= 0) { + callback(); + } + } +} +exports.eachAsync = eachAsync; +/** @internal */ +function eachAsyncSeries(arr, eachFn, callback) { + arr = arr || []; + let idx = 0; + let awaiting = arr.length; + if (awaiting === 0) { + callback(); + return; + } + function eachCallback(err) { + idx++; + awaiting--; + if (err) { + callback(err); + return; + } + if (idx === arr.length && awaiting <= 0) { + callback(); + return; + } + eachFn(arr[idx], eachCallback); + } + eachFn(arr[idx], eachCallback); +} +exports.eachAsyncSeries = eachAsyncSeries; +/** @internal */ +function arrayStrictEqual(arr, arr2) { + if (!Array.isArray(arr) || !Array.isArray(arr2)) { + return false; + } + return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); +} +exports.arrayStrictEqual = arrayStrictEqual; +/** @internal */ +function errorStrictEqual(lhs, rhs) { + if (lhs === rhs) { + return true; + } + if (!lhs || !rhs) { + return lhs === rhs; + } + if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { + return false; + } + if (lhs.constructor.name !== rhs.constructor.name) { + return false; + } + if (lhs.message !== rhs.message) { + return false; + } + return true; +} +exports.errorStrictEqual = errorStrictEqual; +/** @internal */ +function makeStateMachine(stateTable) { + return function stateTransition(target, newState) { + const legalStates = stateTable[target.s.state]; + if (legalStates && legalStates.indexOf(newState) < 0) { + throw new error_1.MongoRuntimeError(`illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`); + } + target.emit('stateChanged', target.s.state, newState); + target.s.state = newState; + }; +} +exports.makeStateMachine = makeStateMachine; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const NODE_DRIVER_VERSION = require('../package.json').version; +function makeClientMetadata(options) { + options = options !== null && options !== void 0 ? options : {}; + const metadata = { + driver: { + name: 'nodejs', + version: NODE_DRIVER_VERSION + }, + os: { + type: os.type(), + name: process.platform, + architecture: process.arch, + version: os.release() + }, + platform: `Node.js ${process.version}, ${os.endianness()} (unified)` + }; + // support optionally provided wrapping driver info + if (options.driverInfo) { + if (options.driverInfo.name) { + metadata.driver.name = `${metadata.driver.name}|${options.driverInfo.name}`; + } + if (options.driverInfo.version) { + metadata.version = `${metadata.driver.version}|${options.driverInfo.version}`; + } + if (options.driverInfo.platform) { + metadata.platform = `${metadata.platform}|${options.driverInfo.platform}`; + } + } + if (options.appName) { + // MongoDB requires the appName not exceed a byte length of 128 + const buffer = Buffer.from(options.appName); + metadata.application = { + name: buffer.byteLength > 128 ? buffer.slice(0, 128).toString('utf8') : options.appName + }; + } + return metadata; +} +exports.makeClientMetadata = makeClientMetadata; +/** @internal */ +function now() { + const hrtime = process.hrtime(); + return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1000000); +} +exports.now = now; +/** @internal */ +function calculateDurationInMs(started) { + if (typeof started !== 'number') { + throw new error_1.MongoInvalidArgumentError('Numeric value required to calculate duration'); + } + const elapsed = now() - started; + return elapsed < 0 ? 0 : elapsed; +} +exports.calculateDurationInMs = calculateDurationInMs; +/** + * Creates an interval timer which is able to be woken up sooner than + * the interval. The timer will also debounce multiple calls to wake + * ensuring that the function is only ever called once within a minimum + * interval window. + * @internal + * + * @param fn - An async function to run on an interval, must accept a `callback` as its only parameter + */ +function makeInterruptibleAsyncInterval(fn, options) { + let timerId; + let lastCallTime; + let lastWakeTime; + let stopped = false; + options = options !== null && options !== void 0 ? options : {}; + const interval = options.interval || 1000; + const minInterval = options.minInterval || 500; + const immediate = typeof options.immediate === 'boolean' ? options.immediate : false; + const clock = typeof options.clock === 'function' ? options.clock : now; + function wake() { + const currentTime = clock(); + const timeSinceLastWake = currentTime - lastWakeTime; + const timeSinceLastCall = currentTime - lastCallTime; + const timeUntilNextCall = interval - timeSinceLastCall; + lastWakeTime = currentTime; + // For the streaming protocol: there is nothing obviously stopping this + // interval from being woken up again while we are waiting "infinitely" + // for `fn` to be called again`. Since the function effectively + // never completes, the `timeUntilNextCall` will continue to grow + // negatively unbounded, so it will never trigger a reschedule here. + // debounce multiple calls to wake within the `minInterval` + if (timeSinceLastWake < minInterval) { + return; + } + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeUntilNextCall > minInterval) { + reschedule(minInterval); + } + // This is possible in virtualized environments like AWS Lambda where our + // clock is unreliable. In these cases the timer is "running" but never + // actually completes, so we want to execute immediately and then attempt + // to reschedule. + if (timeUntilNextCall < 0) { + executeAndReschedule(); + } + } + function stop() { + stopped = true; + if (timerId) { + clearTimeout(timerId); + timerId = undefined; + } + lastCallTime = 0; + lastWakeTime = 0; + } + function reschedule(ms) { + if (stopped) + return; + if (timerId) { + clearTimeout(timerId); + } + timerId = setTimeout(executeAndReschedule, ms || interval); + } + function executeAndReschedule() { + lastWakeTime = 0; + lastCallTime = clock(); + fn(err => { + if (err) + throw err; + reschedule(interval); + }); + } + if (immediate) { + executeAndReschedule(); + } + else { + lastCallTime = clock(); + reschedule(undefined); + } + return { wake, stop }; +} +exports.makeInterruptibleAsyncInterval = makeInterruptibleAsyncInterval; +/** @internal */ +function hasAtomicOperators(doc) { + if (Array.isArray(doc)) { + for (const document of doc) { + if (hasAtomicOperators(document)) { + return true; + } + } + return false; + } + const keys = Object.keys(doc); + return keys.length > 0 && keys[0][0] === '$'; +} +exports.hasAtomicOperators = hasAtomicOperators; +/** + * Merge inherited properties from parent into options, prioritizing values from options, + * then values from parent. + * @internal + */ +function resolveOptions(parent, options) { + var _a, _b, _c; + const result = Object.assign({}, options, bson_1.resolveBSONOptions(options, parent)); + // Users cannot pass a readConcern/writeConcern to operations in a transaction + const session = options === null || options === void 0 ? void 0 : options.session; + if (!(session === null || session === void 0 ? void 0 : session.inTransaction())) { + const readConcern = (_a = read_concern_1.ReadConcern.fromOptions(options)) !== null && _a !== void 0 ? _a : parent === null || parent === void 0 ? void 0 : parent.readConcern; + if (readConcern) { + result.readConcern = readConcern; + } + const writeConcern = (_b = write_concern_1.WriteConcern.fromOptions(options)) !== null && _b !== void 0 ? _b : parent === null || parent === void 0 ? void 0 : parent.writeConcern; + if (writeConcern) { + result.writeConcern = writeConcern; + } + } + const readPreference = (_c = read_preference_1.ReadPreference.fromOptions(options)) !== null && _c !== void 0 ? _c : parent === null || parent === void 0 ? void 0 : parent.readPreference; + if (readPreference) { + result.readPreference = readPreference; + } + return result; +} +exports.resolveOptions = resolveOptions; +function isSuperset(set, subset) { + set = Array.isArray(set) ? new Set(set) : set; + subset = Array.isArray(subset) ? new Set(subset) : subset; + for (const elem of subset) { + if (!set.has(elem)) { + return false; + } + } + return true; +} +exports.isSuperset = isSuperset; +function setDifference(setA, setB) { + const difference = new Set(setA); + for (const elem of setB) { + difference.delete(elem); + } + return difference; +} +exports.setDifference = setDifference; +function isRecord(value, requiredKeys = undefined) { + const toString = Object.prototype.toString; + const hasOwnProperty = Object.prototype.hasOwnProperty; + const isObject = (v) => toString.call(v) === '[object Object]'; + if (!isObject(value)) { + return false; + } + const ctor = value.constructor; + if (ctor && ctor.prototype) { + if (!isObject(ctor.prototype)) { + return false; + } + // Check to see if some method exists from the Object exists + if (!hasOwnProperty.call(ctor.prototype, 'isPrototypeOf')) { + return false; + } + } + if (requiredKeys) { + const keys = Object.keys(value); + return isSuperset(keys, requiredKeys); + } + return true; +} +exports.isRecord = isRecord; +/** + * Make a deep copy of an object + * + * NOTE: This is not meant to be the perfect implementation of a deep copy, + * but instead something that is good enough for the purposes of + * command monitoring. + */ +function deepCopy(value) { + if (value == null) { + return value; + } + else if (Array.isArray(value)) { + return value.map(item => deepCopy(item)); + } + else if (isRecord(value)) { + const res = {}; + for (const key in value) { + res[key] = deepCopy(value[key]); + } + return res; + } + const ctor = value.constructor; + if (ctor) { + switch (ctor.name.toLowerCase()) { + case 'date': + return new ctor(Number(value)); + case 'map': + return new Map(value); + case 'set': + return new Set(value); + case 'buffer': + return Buffer.from(value); + } + } + return value; +} +exports.deepCopy = deepCopy; +/** @internal */ +const kBuffers = Symbol('buffers'); +/** @internal */ +const kLength = Symbol('length'); +/** + * A pool of Buffers which allow you to read them as if they were one + * @internal + */ +class BufferPool { + constructor() { + this[kBuffers] = []; + this[kLength] = 0; + } + get length() { + return this[kLength]; + } + /** Adds a buffer to the internal buffer pool list */ + append(buffer) { + this[kBuffers].push(buffer); + this[kLength] += buffer.length; + } + /** Returns the requested number of bytes without consuming them */ + peek(size) { + return this.read(size, false); + } + /** Reads the requested number of bytes, optionally consuming them */ + read(size, consume = true) { + if (typeof size !== 'number' || size < 0) { + throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + } + if (size > this[kLength]) { + return Buffer.alloc(0); + } + let result; + // read the whole buffer + if (size === this.length) { + result = Buffer.concat(this[kBuffers]); + if (consume) { + this[kBuffers] = []; + this[kLength] = 0; + } + } + // size is within first buffer, no need to concat + else if (size <= this[kBuffers][0].length) { + result = this[kBuffers][0].slice(0, size); + if (consume) { + this[kBuffers][0] = this[kBuffers][0].slice(size); + this[kLength] -= size; + } + } + // size is beyond first buffer, need to track and copy + else { + result = Buffer.allocUnsafe(size); + let idx; + let offset = 0; + let bytesToCopy = size; + for (idx = 0; idx < this[kBuffers].length; ++idx) { + let bytesCopied; + if (bytesToCopy > this[kBuffers][idx].length) { + bytesCopied = this[kBuffers][idx].copy(result, offset, 0); + offset += bytesCopied; + } + else { + bytesCopied = this[kBuffers][idx].copy(result, offset, 0, bytesToCopy); + if (consume) { + this[kBuffers][idx] = this[kBuffers][idx].slice(bytesCopied); + } + offset += bytesCopied; + break; + } + bytesToCopy -= bytesCopied; + } + // compact the internal buffer array + if (consume) { + this[kBuffers] = this[kBuffers].slice(idx); + this[kLength] -= size; + } + } + return result; + } +} +exports.BufferPool = BufferPool; +/** @public */ +class HostAddress { + constructor(hostString) { + const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts + const { hostname, port } = new url_1.URL(`mongodb://${escapedHost}`); + if (hostname.endsWith('.sock')) { + // heuristically determine if we're working with a domain socket + this.socketPath = decodeURIComponent(hostname); + } + else if (typeof hostname === 'string') { + this.isIPv6 = false; + let normalized = decodeURIComponent(hostname).toLowerCase(); + if (normalized.startsWith('[') && normalized.endsWith(']')) { + this.isIPv6 = true; + normalized = normalized.substring(1, hostname.length - 1); + } + this.host = normalized.toLowerCase(); + if (typeof port === 'number') { + this.port = port; + } + else if (typeof port === 'string' && port !== '') { + this.port = Number.parseInt(port, 10); + } + else { + this.port = 27017; + } + if (this.port === 0) { + throw new error_1.MongoParseError('Invalid port (zero) with hostname'); + } + } + else { + throw new error_1.MongoInvalidArgumentError('Either socketPath or host must be defined.'); + } + Object.freeze(this); + } + /** + * @param ipv6Brackets - optionally request ipv6 bracket notation required for connection strings + */ + toString(ipv6Brackets = false) { + if (typeof this.host === 'string') { + if (this.isIPv6 && ipv6Brackets) { + return `[${this.host}]:${this.port}`; + } + return `${this.host}:${this.port}`; + } + return `${this.socketPath}`; + } + static fromString(s) { + return new HostAddress(s); + } +} +exports.HostAddress = HostAddress; +exports.DEFAULT_PK_FACTORY = { + // We prefer not to rely on ObjectId having a createPk method + createPk() { + return new bson_1.ObjectId(); + } +}; +/** + * When the driver used emitWarning the code will be equal to this. + * @public + * + * @example + * ```js + * process.on('warning', (warning) => { + * if (warning.code === MONGODB_WARNING_CODE) console.error('Ah an important warning! :)') + * }) + * ``` + */ +exports.MONGODB_WARNING_CODE = 'MONGODB DRIVER'; +/** @internal */ +function emitWarning(message) { + return process.emitWarning(message, { code: exports.MONGODB_WARNING_CODE }); +} +exports.emitWarning = emitWarning; +const emittedWarnings = new Set(); +/** + * Will emit a warning once for the duration of the application. + * Uses the message to identify if it has already been emitted + * so using string interpolation can cause multiple emits + * @internal + */ +function emitWarningOnce(message) { + if (!emittedWarnings.has(message)) { + emittedWarnings.add(message); + return emitWarning(message); + } +} +exports.emitWarningOnce = emitWarningOnce; +/** + * Takes a JS object and joins the values into a string separated by ', ' + */ +function enumToString(en) { + return Object.values(en).join(', '); +} +exports.enumToString = enumToString; +/** + * Determine if a server supports retryable writes. + * + * @internal + */ +function supportsRetryableWrites(server) { + return (!!server.loadBalanced || + (server.description.maxWireVersion >= 6 && + !!server.description.logicalSessionTimeoutMinutes && + server.description.type !== common_1.ServerType.Standalone)); +} +exports.supportsRetryableWrites = supportsRetryableWrites; +function parsePackageVersion({ version }) { + const [major, minor, patch] = version.split('.').map((n) => Number.parseInt(n, 10)); + return { major, minor, patch }; +} +exports.parsePackageVersion = parsePackageVersion; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/utils.js.map b/node_modules/mongodb/lib/utils.js.map new file mode 100644 index 0000000..4f545bf --- /dev/null +++ b/node_modules/mongodb/lib/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;AAAA,yBAAyB;AACzB,iCAAiC;AACjC,yDAAqD;AACrD,mCAQiB;AACjB,mDAAuE;AAGvE,0CAA2C;AAK3C,iDAA6C;AAE7C,iCAAgE;AAKhE,uDAAmD;AACnD,6BAA0B;AAC1B,8DAA4E;AAU/D,QAAA,UAAU,GAAG,MAAM,CAAC,gBAAgB,GAAG,CAAC,CAAC;AAItD;;;GAGG;AACH,SAAgB,iBAAiB,CAC/B,GAAe,EACf,IAA8B,EAC9B,KAAc;IAEd,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE;QAC/B,UAAU,EAAE,IAAI;QAChB,GAAG;YACD,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAXD,8CAWC;AAED;;;GAGG;AACH,SAAgB,mBAAmB,CAAC,cAAsB;IACxD,IAAI,QAAQ,KAAK,OAAO,cAAc,EAAE;QACtC,MAAM,IAAI,iCAAyB,CAAC,kCAAkC,CAAC,CAAC;KACzE;IAED,IAAI,CAAC,cAAc,IAAI,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE;QAC1D,MAAM,IAAI,iCAAyB,CAAC,kCAAkC,CAAC,CAAC;KACzE;IAED,IACE,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAClC,cAA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E,CAAC;AAFD,kCAEC;AAED,MAAM,eAAe,GAAG,IAAI,GAAG,EAAE,CAAC;AAClC;;;;;GAKG;AACH,SAAgB,eAAe,CAAC,OAAe;IAC7C,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;QACjC,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC7B,OAAO,WAAW,CAAC,OAAO,CAAC,CAAC;KAC7B;AACH,CAAC;AALD,0CAKC;AAED;;GAEG;AACH,SAAgB,YAAY,CAAC,EAA2B;IACtD,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACtC,CAAC;AAFD,oCAEC;AAED;;;;GAIG;AACH,SAAgB,uBAAuB,CAAC,MAAc;IACpD,OAAO,CACL,CAAC,CAAC,MAAM,CAAC,YAAY;QACrB,CAAC,MAAM,CAAC,WAAW,CAAC,cAAc,IAAI,CAAC;YACrC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,4BAA4B;YACjD,MAAM,CAAC,WAAW,CAAC,IAAI,KAAK,mBAAU,CAAC,UAAU,CAAC,CACrD,CAAC;AACJ,CAAC;AAPD,0DAOC;AAED,SAAgB,mBAAmB,CAAC,EAAE,OAAO,EAAuB;IAKlE,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAS,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;IAC5F,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AACjC,CAAC;AAPD,kDAOC"} \ No newline at end of file diff --git a/node_modules/mongodb/lib/write_concern.js b/node_modules/mongodb/lib/write_concern.js new file mode 100644 index 0000000..4816b00 --- /dev/null +++ b/node_modules/mongodb/lib/write_concern.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WriteConcern = exports.WRITE_CONCERN_KEYS = void 0; +exports.WRITE_CONCERN_KEYS = ['w', 'wtimeout', 'j', 'journal', 'fsync']; +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @public + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ +class WriteConcern { + /** + * Constructs a WriteConcern from the write concern properties. + * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. + * @param wtimeout - specify a time limit to prevent write operations from blocking indefinitely + * @param j - request acknowledgment that the write operation has been written to the on-disk journal + * @param fsync - equivalent to the j option + */ + constructor(w, wtimeout, j, fsync) { + if (w != null) { + if (!Number.isNaN(Number(w))) { + this.w = Number(w); + } + else { + this.w = w; + } + } + if (wtimeout != null) { + this.wtimeout = wtimeout; + } + if (j != null) { + this.j = j; + } + if (fsync != null) { + this.fsync = fsync; + } + } + /** Construct a WriteConcern given an options object. */ + static fromOptions(options, inherit) { + if (options == null) + return undefined; + inherit = inherit !== null && inherit !== void 0 ? inherit : {}; + let opts; + if (typeof options === 'string' || typeof options === 'number') { + opts = { w: options }; + } + else if (options instanceof WriteConcern) { + opts = options; + } + else { + opts = options.writeConcern; + } + const parentOpts = inherit instanceof WriteConcern ? inherit : inherit.writeConcern; + const { w = undefined, wtimeout = undefined, j = undefined, fsync = undefined, journal = undefined, wtimeoutMS = undefined } = { + ...parentOpts, + ...opts + }; + if (w != null || + wtimeout != null || + wtimeoutMS != null || + j != null || + journal != null || + fsync != null) { + return new WriteConcern(w, wtimeout !== null && wtimeout !== void 0 ? wtimeout : wtimeoutMS, j !== null && j !== void 0 ? j : journal, fsync); + } + return undefined; + } +} +exports.WriteConcern = WriteConcern; +//# sourceMappingURL=write_concern.js.map \ No newline at end of file diff --git a/node_modules/mongodb/lib/write_concern.js.map b/node_modules/mongodb/lib/write_concern.js.map new file mode 100644 index 0000000..c2e21b7 --- /dev/null +++ b/node_modules/mongodb/lib/write_concern.js.map @@ -0,0 +1 @@ +{"version":3,"file":"write_concern.js","sourceRoot":"","sources":["../src/write_concern.ts"],"names":[],"mappings":";;;AA2Ba,QAAA,kBAAkB,GAAG,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AAE7E;;;;;;GAMG;AACH,MAAa,YAAY;IAUvB;;;;;;OAMG;IACH,YAAY,CAAK,EAAE,QAAiB,EAAE,CAAW,EAAE,KAAmB;QACpE,IAAI,CAAC,IAAI,IAAI,EAAE;YACb,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE;gBAC5B,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;aACpB;iBAAM;gBACL,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;aACZ;SACF;QACD,IAAI,QAAQ,IAAI,IAAI,EAAE;YACpB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;SAC1B;QACD,IAAI,CAAC,IAAI,IAAI,EAAE;YACb,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;SACZ;QACD,IAAI,KAAK,IAAI,IAAI,EAAE;YACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;SACpB;IACH,CAAC;IAED,wDAAwD;IACxD,MAAM,CAAC,WAAW,CAChB,OAAgD,EAChD,OAA4C;QAE5C,IAAI,OAAO,IAAI,IAAI;YAAE,OAAO,SAAS,CAAC;QACtC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QACxB,IAAI,IAAqD,CAAC;QAC1D,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;YAC9D,IAAI,GAAG,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC;SACvB;aAAM,IAAI,OAAO,YAAY,YAAY,EAAE;YAC1C,IAAI,GAAG,OAAO,CAAC;SAChB;aAAM;YACL,IAAI,GAAG,OAAO,CAAC,YAAY,CAAC;SAC7B;QACD,MAAM,UAAU,GACd,OAAO,YAAY,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC;QAEnE,MAAM,EACJ,CAAC,GAAG,SAAS,EACb,QAAQ,GAAG,SAAS,EACpB,CAAC,GAAG,SAAS,EACb,KAAK,GAAG,SAAS,EACjB,OAAO,GAAG,SAAS,EACnB,UAAU,GAAG,SAAS,EACvB,GAAG;YACF,GAAG,UAAU;YACb,GAAG,IAAI;SACR,CAAC;QACF,IACE,CAAC,IAAI,IAAI;YACT,QAAQ,IAAI,IAAI;YAChB,UAAU,IAAI,IAAI;YAClB,CAAC,IAAI,IAAI;YACT,OAAO,IAAI,IAAI;YACf,KAAK,IAAI,IAAI,EACb;YACA,OAAO,IAAI,YAAY,CAAC,CAAC,EAAE,QAAQ,aAAR,QAAQ,cAAR,QAAQ,GAAI,UAAU,EAAE,CAAC,aAAD,CAAC,cAAD,CAAC,GAAI,OAAO,EAAE,KAAK,CAAC,CAAC;SACzE;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AA7ED,oCA6EC"} \ No newline at end of file diff --git a/node_modules/mongodb/mongodb.d.ts b/node_modules/mongodb/mongodb.d.ts new file mode 100644 index 0000000..d1ae58c --- /dev/null +++ b/node_modules/mongodb/mongodb.d.ts @@ -0,0 +1,5944 @@ +/// + +import { Binary } from 'bson'; +import { BSONRegExp } from 'bson'; +import { BSONSymbol } from 'bson'; +import { Code } from 'bson'; +import type { ConnectionOptions as ConnectionOptions_2 } from 'tls'; +import { DBRef } from 'bson'; +import { Decimal128 } from 'bson'; +import Denque = require('denque'); +import type { deserialize as deserialize_2 } from 'bson'; +import type { DeserializeOptions } from 'bson'; +import * as dns from 'dns'; +import { Document } from 'bson'; +import { Double } from 'bson'; +import { Duplex } from 'stream'; +import { DuplexOptions } from 'stream'; +import { EventEmitter } from 'events'; +import { Int32 } from 'bson'; +import { Long } from 'bson'; +import { Map as Map_2 } from 'bson'; +import { MaxKey } from 'bson'; +import { MinKey } from 'bson'; +import { ObjectId } from 'bson'; +import { Readable } from 'stream'; +import type { serialize as serialize_2 } from 'bson'; +import type { SerializeOptions } from 'bson'; +import type { Socket } from 'net'; +import type { TcpNetConnectOpts } from 'net'; +import { Timestamp } from 'bson'; +import type { TLSSocket } from 'tls'; +import type { TLSSocketOptions } from 'tls'; +import { Writable } from 'stream'; + +/** @public */ +export declare abstract class AbstractCursor extends TypedEventEmitter { + /* Excluded from this release type: [kId] */ + /* Excluded from this release type: [kSession] */ + /* Excluded from this release type: [kServer] */ + /* Excluded from this release type: [kNamespace] */ + /* Excluded from this release type: [kDocuments] */ + /* Excluded from this release type: [kTopology] */ + /* Excluded from this release type: [kTransform] */ + /* Excluded from this release type: [kInitialized] */ + /* Excluded from this release type: [kClosed] */ + /* Excluded from this release type: [kKilled] */ + /* Excluded from this release type: [kOptions] */ + /** @event */ + static readonly CLOSE: "close"; + /* Excluded from this release type: __constructor */ + get id(): Long | undefined; + /* Excluded from this release type: topology */ + /* Excluded from this release type: server */ + get namespace(): MongoDBNamespace; + get readPreference(): ReadPreference; + get readConcern(): ReadConcern | undefined; + /* Excluded from this release type: session */ + /* Excluded from this release type: session */ + /* Excluded from this release type: cursorOptions */ + get closed(): boolean; + get killed(): boolean; + get loadBalanced(): boolean; + /** Returns current buffered documents length */ + bufferedCount(): number; + /** Returns current buffered documents */ + readBufferedDocuments(number?: number): TSchema[]; + [Symbol.asyncIterator](): AsyncIterator; + stream(options?: CursorStreamOptions): Readable; + hasNext(): Promise; + hasNext(callback: Callback): void; + /** Get the next available document from the cursor, returns null if no more documents are available. */ + next(): Promise; + next(callback: Callback): void; + next(callback?: Callback): Promise | void; + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + tryNext(callback: Callback): void; + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * @param iterator - The iteration callback. + * @param callback - The end callback. + */ + forEach(iterator: (doc: TSchema) => boolean | void): Promise; + forEach(iterator: (doc: TSchema) => boolean | void, callback: Callback): void; + close(): void; + close(callback: Callback): void; + /** + * @deprecated options argument is deprecated + */ + close(options: CursorCloseOptions): Promise; + /** + * @deprecated options argument is deprecated + */ + close(options: CursorCloseOptions, callback: Callback): void; + /** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * + * @param callback - The result callback. + */ + toArray(): Promise; + toArray(callback: Callback): void; + /** + * Add a cursor flag to the cursor + * + * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. + * @param value - The flag boolean value. + */ + addCursorFlag(flag: CursorFlag, value: boolean): this; + /** + * Map all documents using the provided function + * If there is a transform set on the cursor, that will be called first and the result passed to + * this function's transform. + * + * @remarks + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling map, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor = coll.find(); + * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); + * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] + * ``` + * @param transform - The mapping transformation method. + */ + map(transform: (doc: TSchema) => T): AbstractCursor; + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadPreference(readPreference: ReadPreferenceLike): this; + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadConcern(readConcern: ReadConcernLike): this; + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this; + /** + * Set the batch size for the cursor. + * + * @param value - The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + */ + batchSize(value: number): this; + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind(): void; + /** + * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance + */ + abstract clone(): AbstractCursor; + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: _getMore */ +} + +/** @public */ +export declare type AbstractCursorEvents = { + [AbstractCursor.CLOSE](): void; +}; + +/** @public */ +export declare interface AbstractCursorOptions extends BSONSerializeOptions { + session?: ClientSession; + readPreference?: ReadPreferenceLike; + readConcern?: ReadConcernLike; + batchSize?: number; + maxTimeMS?: number; + comment?: Document | string; + tailable?: boolean; + awaitData?: boolean; + noCursorTimeout?: boolean; +} + +/* Excluded from this release type: AbstractOperation */ + +/** @public */ +export declare type AcceptedFields = { + readonly [key in KeysOfAType]?: AssignableType; +}; + +/** @public */ +export declare type AddToSetOperators = { + $each?: Array>; +}; + +/** @public */ +export declare interface AddUserOptions extends CommandOperationOptions { + /** @deprecated Please use db.command('createUser', ...) instead for this option */ + digestPassword?: null; + /** Roles associated with the created user */ + roles?: string | string[] | RoleSpecification | RoleSpecification[]; + /** Custom data associated with the user (only Mongodb 2.6 or higher) */ + customData?: Document; +} + +/** + * The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Use the admin database for the operation + * const adminDb = client.db(dbName).admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * expect(err).to.not.exist; + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + * ``` + */ +export declare class Admin { + /* Excluded from this release type: s */ + /* Excluded from this release type: __constructor */ + /** + * Execute a command + * + * @param command - The command to execute + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + command(command: Document): Promise; + command(command: Document, callback: Callback): void; + command(command: Document, options: RunCommandOptions): Promise; + command(command: Document, options: RunCommandOptions, callback: Callback): void; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + buildInfo(): Promise; + buildInfo(callback: Callback): void; + buildInfo(options: CommandOperationOptions): Promise; + buildInfo(options: CommandOperationOptions, callback: Callback): void; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + serverInfo(): Promise; + serverInfo(callback: Callback): void; + serverInfo(options: CommandOperationOptions): Promise; + serverInfo(options: CommandOperationOptions, callback: Callback): void; + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + serverStatus(): Promise; + serverStatus(callback: Callback): void; + serverStatus(options: CommandOperationOptions): Promise; + serverStatus(options: CommandOperationOptions, callback: Callback): void; + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + ping(): Promise; + ping(callback: Callback): void; + ping(options: CommandOperationOptions): Promise; + ping(options: CommandOperationOptions, callback: Callback): void; + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param password - An optional password for the new user + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + addUser(username: string): Promise; + addUser(username: string, callback: Callback): void; + addUser(username: string, password: string): Promise; + addUser(username: string, password: string, callback: Callback): void; + addUser(username: string, options: AddUserOptions): Promise; + addUser(username: string, options: AddUserOptions, callback: Callback): void; + addUser(username: string, password: string, options: AddUserOptions): Promise; + addUser(username: string, password: string, options: AddUserOptions, callback: Callback): void; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + removeUser(username: string): Promise; + removeUser(username: string, callback: Callback): void; + removeUser(username: string, options: RemoveUserOptions): Promise; + removeUser(username: string, options: RemoveUserOptions, callback: Callback): void; + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + validateCollection(collectionName: string): Promise; + validateCollection(collectionName: string, callback: Callback): void; + validateCollection(collectionName: string, options: ValidateCollectionOptions): Promise; + validateCollection(collectionName: string, options: ValidateCollectionOptions, callback: Callback): void; + /** + * List the available databases + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + listDatabases(): Promise; + listDatabases(callback: Callback): void; + listDatabases(options: ListDatabasesOptions): Promise; + listDatabases(options: ListDatabasesOptions, callback: Callback): void; + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + replSetGetStatus(): Promise; + replSetGetStatus(callback: Callback): void; + replSetGetStatus(options: CommandOperationOptions): Promise; + replSetGetStatus(options: CommandOperationOptions, callback: Callback): void; +} + +/* Excluded from this release type: AdminPrivate */ + +/* Excluded from this release type: AggregateOperation */ + +/** @public */ +export declare interface AggregateOptions extends CommandOperationOptions { + /** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */ + allowDiskUse?: boolean; + /** The number of documents to return per batch. See [aggregation documentation](https://docs.mongodb.com/manual/reference/command/aggregate). */ + batchSize?: number; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */ + cursor?: Document; + /** specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */ + maxAwaitTimeMS?: number; + /** Specify collation. */ + collation?: CollationOptions; + /** Add an index selection hint to an aggregation command */ + hint?: Hint; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + out?: string; +} + +/** + * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * @public + */ +export declare class AggregationCursor extends AbstractCursor { + /* Excluded from this release type: [kPipeline] */ + /* Excluded from this release type: [kOptions] */ + /* Excluded from this release type: __constructor */ + get pipeline(): Document[]; + clone(): AggregationCursor; + map(transform: (doc: TSchema) => T): AggregationCursor; + /* Excluded from this release type: _initialize */ + /** Execute the explain for the cursor */ + explain(): Promise; + explain(callback: Callback): void; + explain(verbosity: ExplainVerbosityLike): Promise; + /** Add a group stage to the aggregation pipeline */ + group($group: Document): AggregationCursor; + /** Add a limit stage to the aggregation pipeline */ + limit($limit: number): this; + /** Add a match stage to the aggregation pipeline */ + match($match: Document): this; + /** Add an out stage to the aggregation pipeline */ + out($out: { + db: string; + coll: string; + } | string): this; + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.aggregate().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project($project: Document): AggregationCursor; + /** Add a lookup stage to the aggregation pipeline */ + lookup($lookup: Document): this; + /** Add a redact stage to the aggregation pipeline */ + redact($redact: Document): this; + /** Add a skip stage to the aggregation pipeline */ + skip($skip: number): this; + /** Add a sort stage to the aggregation pipeline */ + sort($sort: Sort): this; + /** Add a unwind stage to the aggregation pipeline */ + unwind($unwind: Document | string): this; + /** @deprecated Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear: Document): this; +} + +/** @public */ +export declare interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions { +} + +/** + * It is possible to search using alternative types in mongodb e.g. + * string types can be searched using a regex in mongo + * array types can be searched using their element type + * @public + */ +export declare type AlternativeType = T extends ReadonlyArray ? T | RegExpOrString : RegExpOrString; + +/** @public */ +export declare type AnyBulkWriteOperation = { + insertOne: InsertOneModel; +} | { + replaceOne: ReplaceOneModel; +} | { + updateOne: UpdateOneModel; +} | { + updateMany: UpdateManyModel; +} | { + deleteOne: DeleteOneModel; +} | { + deleteMany: DeleteManyModel; +}; + +/** @public */ +export declare type AnyError = MongoError | Error; + +/** @public */ +export declare type ArrayOperator = { + $each?: Array>; + $slice?: number; + $position?: number; + $sort?: Sort; +}; + +/** @public */ +export declare interface Auth { + /** The username for auth */ + username?: string; + /** The password for auth */ + password?: string; +} + +/** @public */ +export declare const AuthMechanism: Readonly<{ + readonly MONGODB_AWS: "MONGODB-AWS"; + readonly MONGODB_CR: "MONGODB-CR"; + readonly MONGODB_DEFAULT: "DEFAULT"; + readonly MONGODB_GSSAPI: "GSSAPI"; + readonly MONGODB_PLAIN: "PLAIN"; + readonly MONGODB_SCRAM_SHA1: "SCRAM-SHA-1"; + readonly MONGODB_SCRAM_SHA256: "SCRAM-SHA-256"; + readonly MONGODB_X509: "MONGODB-X509"; +}>; + +/** @public */ +export declare type AuthMechanism = typeof AuthMechanism[keyof typeof AuthMechanism]; + +/** @public */ +export declare interface AuthMechanismProperties extends Document { + SERVICE_NAME?: string; + SERVICE_REALM?: string; + CANONICALIZE_HOST_NAME?: boolean; + AWS_SESSION_TOKEN?: string; +} + +/** @public */ +export declare interface AutoEncrypter { + new (client: MongoClient, options: AutoEncryptionOptions): AutoEncrypter; + init(cb: Callback): void; + teardown(force: boolean, callback: Callback): void; + encrypt(ns: string, cmd: Document, options: any, callback: Callback): void; + decrypt(cmd: Document, options: any, callback: Callback): void; +} + +/** @public */ +export declare const AutoEncryptionLoggerLevel: Readonly<{ + readonly FatalError: 0; + readonly Error: 1; + readonly Warning: 2; + readonly Info: 3; + readonly Trace: 4; +}>; + +/** @public */ +export declare type AutoEncryptionLoggerLevel = typeof AutoEncryptionLoggerLevel[keyof typeof AutoEncryptionLoggerLevel]; + +/** @public */ +export declare interface AutoEncryptionOptions { + /* Excluded from this release type: bson */ + /* Excluded from this release type: metadataClient */ + /** A `MongoClient` used to fetch keys from a key vault */ + keyVaultClient?: MongoClient; + /** The namespace where keys are stored in the key vault */ + keyVaultNamespace?: string; + /** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */ + kmsProviders?: { + /** Configuration options for using 'aws' as your KMS provider */ + aws?: { + /** The access key used for the AWS KMS provider */ + accessKeyId: string; + /** The secret access key used for the AWS KMS provider */ + secretAccessKey: string; + /** + * An optional AWS session token that will be used as the + * X-Amz-Security-Token header for AWS requests. + */ + sessionToken?: string; + }; + /** Configuration options for using 'local' as your KMS provider */ + local?: { + /** + * The master key used to encrypt/decrypt data keys. + * A 96-byte long Buffer or base64 encoded string. + */ + key: Buffer | string; + }; + /** Configuration options for using 'azure' as your KMS provider */ + azure?: { + /** The tenant ID identifies the organization for the account */ + tenantId: string; + /** The client ID to authenticate a registered application */ + clientId: string; + /** The client secret to authenticate a registered application */ + clientSecret: string; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * This is optional, and only needed if customer is using a non-commercial Azure instance + * (e.g. a government or China account, which use different URLs). + * Defaults to "login.microsoftonline.com" + */ + identityPlatformEndpoint?: string | undefined; + }; + /** Configuration options for using 'gcp' as your KMS provider */ + gcp?: { + /** The service account email to authenticate */ + email: string; + /** A PKCS#8 encrypted key. This can either be a base64 string or a binary representation */ + privateKey: string | Buffer; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * Defaults to "oauth2.googleapis.com" + */ + endpoint?: string | undefined; + }; + }; + /** + * A map of namespaces to a local JSON schema for encryption + * + * **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server. + * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted. + * Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption. + * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. + */ + schemaMap?: Document; + /** Allows the user to bypass auto encryption, maintaining implicit decryption */ + bypassAutoEncryption?: boolean; + options?: { + /** An optional hook to catch logging messages from the underlying encryption engine */ + logger?: (level: AutoEncryptionLoggerLevel, message: string) => void; + }; + extraOptions?: { + /** + * A local process the driver communicates with to determine how to encrypt values in a command. + * Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise + */ + mongocryptdURI?: string; + /** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */ + mongocryptdBypassSpawn?: boolean; + /** The path to the mongocryptd executable on the system */ + mongocryptdSpawnPath?: string; + /** Command line arguments to use when auto-spawning a mongocryptd */ + mongocryptdSpawnArgs?: string[]; + }; +} + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +export declare class Batch { + originalZeroIndex: number; + currentIndex: number; + originalIndexes: number[]; + batchType: BatchType; + operations: T[]; + size: number; + sizeBytes: number; + constructor(batchType: BatchType, originalZeroIndex: number); +} + +/** @public */ +export declare const BatchType: Readonly<{ + readonly INSERT: 1; + readonly UPDATE: 2; + readonly DELETE: 3; +}>; + +/** @public */ +export declare type BatchType = typeof BatchType[keyof typeof BatchType]; + +export { Binary } + +/** @public */ +export declare type BitwiseFilter = number /** numeric bit mask */ | Binary /** BinData bit mask */ | ReadonlyArray; + +export { BSONRegExp } + +/** + * BSON Serialization options. + * @public + */ +export declare interface BSONSerializeOptions extends Omit, Omit { + /** Return BSON filled buffers from operations */ + raw?: boolean; +} + +export { BSONSymbol } + +/** @public */ +export declare const BSONType: Readonly<{ + readonly double: 1; + readonly string: 2; + readonly object: 3; + readonly array: 4; + readonly binData: 5; + readonly undefined: 6; + readonly objectId: 7; + readonly bool: 8; + readonly date: 9; + readonly null: 10; + readonly regex: 11; + readonly dbPointer: 12; + readonly javascript: 13; + readonly symbol: 14; + readonly javascriptWithScope: 15; + readonly int: 16; + readonly timestamp: 17; + readonly long: 18; + readonly decimal: 19; + readonly minKey: -1; + readonly maxKey: 127; +}>; + +/** @public */ +export declare type BSONType = typeof BSONType[keyof typeof BSONType]; + +/** @public */ +export declare type BSONTypeAlias = keyof typeof BSONType; + +/* Excluded from this release type: BufferPool */ + +/** @public */ +export declare abstract class BulkOperationBase { + isOrdered: boolean; + /* Excluded from this release type: s */ + operationId?: number; + /* Excluded from this release type: __constructor */ + /** + * Add a single insert document to the bulk operation + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + * ``` + */ + insert(document: Document): BulkOperationBase; + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }}); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + * ``` + */ + find(selector: Document): FindOperators; + /** Specifies a raw operation to perform in the bulk write. */ + raw(op: AnyBulkWriteOperation): this; + get bsonOptions(): BSONSerializeOptions; + get writeConcern(): WriteConcern | undefined; + get batches(): Batch[]; + /** An internal helper method. Do not invoke directly. Will be going away in the future */ + execute(options?: BulkWriteOptions, callback?: Callback): Promise | void; + /* Excluded from this release type: handleWriteError */ + abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/* Excluded from this release type: BulkOperationPrivate */ + +/** @public */ +export declare interface BulkResult { + ok: number; + writeErrors: WriteError[]; + writeConcernErrors: WriteConcernError[]; + insertedIds: Document[]; + nInserted: number; + nUpserted: number; + nMatched: number; + nModified: number; + nRemoved: number; + upserted: Document[]; + opTime?: Document; +} + +/** @public */ +export declare interface BulkWriteOperationError { + index: number; + code: number; + errmsg: string; + errInfo: Document; + op: Document | UpdateStatement | DeleteStatement; +} + +/** @public */ +export declare interface BulkWriteOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** @deprecated use `ordered` instead */ + keepGoing?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; +} + +/** + * @public + * The result of a bulk write. + */ +export declare class BulkWriteResult { + result: BulkResult; + /* Excluded from this release type: __constructor */ + /** Number of documents inserted. */ + get insertedCount(): number; + /** Number of documents matched for update. */ + get matchedCount(): number; + /** Number of documents modified. */ + get modifiedCount(): number; + /** Number of documents deleted. */ + get deletedCount(): number; + /** Number of documents upserted. */ + get upsertedCount(): number; + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds(): { + [key: number]: any; + }; + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds(): { + [key: number]: any; + }; + /** Evaluates to true if the bulk operation correctly executes */ + get ok(): number; + /** The number of inserted documents */ + get nInserted(): number; + /** Number of upserted documents */ + get nUpserted(): number; + /** Number of matched documents */ + get nMatched(): number; + /** Number of documents updated physically on disk */ + get nModified(): number; + /** Number of removed documents */ + get nRemoved(): number; + /** Returns an array of all inserted ids */ + getInsertedIds(): Document[]; + /** Returns an array of all upserted ids */ + getUpsertedIds(): Document[]; + /** Returns the upserted id at the given index */ + getUpsertedIdAt(index: number): Document | undefined; + /** Returns raw internal result */ + getRawResponse(): Document; + /** Returns true if the bulk operation contains a write error */ + hasWriteErrors(): boolean; + /** Returns the number of write errors off the bulk operation */ + getWriteErrorCount(): number; + /** Returns a specific write error object */ + getWriteErrorAt(index: number): WriteError | undefined; + /** Retrieve all write errors */ + getWriteErrors(): WriteError[]; + /** Retrieve lastOp if available */ + getLastOp(): Document | undefined; + /** Retrieve the write concern error if one exists */ + getWriteConcernError(): WriteConcernError | undefined; + toJSON(): BulkResult; + toString(): string; + isOk(): boolean; +} + +/** + * MongoDB Driver style callback + * @public + */ +export declare type Callback = (error?: AnyError, result?: T) => void; + +/** @public */ +export declare class CancellationToken extends TypedEventEmitter<{ + cancel(): void; +}> { +} + +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @public + */ +export declare class ChangeStream extends TypedEventEmitter { + pipeline: Document[]; + options: ChangeStreamOptions; + parent: MongoClient | Db | Collection; + namespace: MongoDBNamespace; + type: symbol; + /* Excluded from this release type: cursor */ + streamOptions?: CursorStreamOptions; + /* Excluded from this release type: [kResumeQueue] */ + /* Excluded from this release type: [kCursorStream] */ + /* Excluded from this release type: [kClosed] */ + /* Excluded from this release type: [kMode] */ + /** @event */ + static readonly RESPONSE: "response"; + /** @event */ + static readonly MORE: "more"; + /** @event */ + static readonly INIT: "init"; + /** @event */ + static readonly CLOSE: "close"; + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * @event + */ + static readonly CHANGE: "change"; + /** @event */ + static readonly END: "end"; + /** @event */ + static readonly ERROR: "error"; + /** + * Emitted each time the change stream stores a new resume token. + * @event + */ + static readonly RESUME_TOKEN_CHANGED: "resumeTokenChanged"; + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: cursorStream */ + /** The cached resume token that is used to resume after the most recently returned change. */ + get resumeToken(): ResumeToken; + /** Check if there is any document still available in the Change Stream */ + hasNext(callback?: Callback): Promise | void; + /** Get the next available document from the Change Stream. */ + next(): Promise>; + next(callback: Callback>): void; + /** Is the cursor closed */ + get closed(): boolean; + /** Close the Change Stream */ + close(callback?: Callback): Promise | void; + /** + * Return a modified Readable stream including a possible transform method. + * @throws MongoDriverError if this.cursor is undefined + */ + stream(options?: CursorStreamOptions): Readable; + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + tryNext(callback: Callback): void; +} + +/* Excluded from this release type: ChangeStreamCursor */ + +/* Excluded from this release type: ChangeStreamCursorOptions */ + +/** @public */ +export declare interface ChangeStreamDocument { + /** + * The id functions as an opaque token for use when resuming an interrupted + * change stream. + */ + _id: InferIdType; + /** + * Describes the type of operation represented in this change notification. + */ + operationType: 'insert' | 'update' | 'replace' | 'delete' | 'invalidate' | 'drop' | 'dropDatabase' | 'rename'; + /** + * Contains two fields: “db” and “coll” containing the database and + * collection name in which the change happened. + */ + ns: { + db: string; + coll: string; + }; + /** + * Only present for ops of type ‘insert’, ‘update’, ‘replace’, and + * ‘delete’. + * + * For unsharded collections this contains a single field, _id, with the + * value of the _id of the document updated. For sharded collections, + * this will contain all the components of the shard key in order, + * followed by the _id if the _id isn’t part of the shard key. + */ + documentKey?: InferIdType; + /** + * Only present for ops of type ‘update’. + * + * Contains a description of updated and removed fields in this + * operation. + */ + updateDescription?: UpdateDescription; + /** + * Always present for operations of type ‘insert’ and ‘replace’. Also + * present for operations of type ‘update’ if the user has specified ‘updateLookup’ + * in the ‘fullDocument’ arguments to the ‘$changeStream’ stage. + * + * For operations of type ‘insert’ and ‘replace’, this key will contain the + * document being inserted, or the new version of the document that is replacing + * the existing document, respectively. + * + * For operations of type ‘update’, this key will contain a copy of the full + * version of the document from some point after the update occurred. If the + * document was deleted since the updated happened, it will be null. + */ + fullDocument?: TSchema; +} + +/** @public */ +export declare type ChangeStreamEvents = { + resumeTokenChanged(token: ResumeToken): void; + init(response: Document): void; + more(response?: Document | undefined): void; + response(): void; + end(): void; + error(error: Error): void; + change(change: ChangeStreamDocument): void; +} & AbstractCursorEvents; + +/** + * Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. + * @public + */ +export declare interface ChangeStreamOptions extends AggregateOptions { + /** Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. */ + fullDocument?: string; + /** The maximum amount of time for the server to wait on new documents to satisfy a change stream query. */ + maxAwaitTimeMS?: number; + /** Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. */ + resumeAfter?: ResumeToken; + /** Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. */ + startAfter?: ResumeToken; + /** Will start the changeStream after the specified operationTime. */ + startAtOperationTime?: OperationTime; + /** The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. */ + batchSize?: number; +} + +/** @public */ +export declare interface ClientMetadata { + driver: { + name: string; + version: string; + }; + os: { + type: string; + name: NodeJS.Platform; + architecture: string; + version: string; + }; + platform: string; + version?: string; + application?: { + name: string; + }; +} + +/** @public */ +export declare interface ClientMetadataOptions { + driverInfo?: { + name?: string; + version?: string; + platform?: string; + }; + appName?: string; +} + +/** + * A class representing a client session on the server + * + * NOTE: not meant to be instantiated directly. + * @public + */ +export declare class ClientSession extends TypedEventEmitter { + /* Excluded from this release type: topology */ + /* Excluded from this release type: sessionPool */ + hasEnded: boolean; + clientOptions?: MongoOptions; + supports: { + causalConsistency: boolean; + }; + clusterTime?: ClusterTime; + operationTime?: Timestamp; + explicit: boolean; + /* Excluded from this release type: owner */ + defaultTransactionOptions: TransactionOptions; + transaction: Transaction; + /* Excluded from this release type: [kServerSession] */ + /* Excluded from this release type: [kSnapshotTime] */ + /* Excluded from this release type: [kSnapshotEnabled] */ + /* Excluded from this release type: [kPinnedConnection] */ + /* Excluded from this release type: __constructor */ + /** The server id associated with this session */ + get id(): ServerSessionId | undefined; + get serverSession(): ServerSession; + /** Whether or not this session is configured for snapshot reads */ + get snapshotEnabled(): boolean; + get loadBalanced(): boolean; + /* Excluded from this release type: pinnedConnection */ + /* Excluded from this release type: pin */ + /* Excluded from this release type: unpin */ + get isPinned(): boolean; + /** + * Ends this session on the server + * + * @param options - Optional settings. Currently reserved for future use + * @param callback - Optional callback for completion of this operation + */ + endSession(): Promise; + endSession(callback: Callback): void; + endSession(options: EndSessionOptions): Promise; + endSession(options: EndSessionOptions, callback: Callback): void; + /** + * Advances the operationTime for a ClientSession. + * + * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime: Timestamp): void; + /** + * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession + * + * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature + */ + advanceClusterTime(clusterTime: ClusterTime): void; + /** + * Used to determine if this session equals another + * + * @param session - The session to compare to + */ + equals(session: ClientSession): boolean; + /** Increment the transaction number on the internal ServerSession */ + incrementTransactionNumber(): void; + /** @returns whether this session is currently in a transaction or not */ + inTransaction(): boolean; + /** + * Starts a new transaction with the given options. + * + * @param options - Options for the transaction + */ + startTransaction(options?: TransactionOptions): void; + /** + * Commits the currently active transaction in this session. + * + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + commitTransaction(): Promise; + commitTransaction(callback: Callback): void; + /** + * Aborts the currently active transaction in this session. + * + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + abortTransaction(): Promise; + abortTransaction(callback: Callback): void; + /** + * This is here to ensure that ClientSession is never serialized to BSON. + */ + toBSON(): never; + /** + * Runs a provided lambda within a transaction, retrying either the commit operation + * or entire transaction as needed (and when the error permits) to better ensure that + * the transaction can complete successfully. + * + * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not + * return a Promise will result in undefined behavior. + * + * @param fn - A lambda to run within a transaction + * @param options - Optional settings for the transaction + */ + withTransaction(fn: WithTransactionCallback, options?: TransactionOptions): ReturnType; +} + +/** @public */ +export declare type ClientSessionEvents = { + ended(session: ClientSession): void; +}; + +/** @public */ +export declare interface ClientSessionOptions { + /** Whether causal consistency should be enabled on this session */ + causalConsistency?: boolean; + /** Whether all read operations should be read from the same snapshot for this session (NOTE: not compatible with `causalConsistency=true`) */ + snapshot?: boolean; + /** The default TransactionOptions to use for transactions started on this session. */ + defaultTransactionOptions?: TransactionOptions; + /* Excluded from this release type: owner */ + /* Excluded from this release type: explicit */ + /* Excluded from this release type: initialClusterTime */ +} + +/** @public */ +export declare interface CloseOptions { + force?: boolean; +} + +/** @public */ +export declare interface ClusterTime { + clusterTime: Timestamp; + signature: { + hash: Binary; + keyId: Long; + }; +} + +export { Code } + +/** @public */ +export declare interface CollationOptions { + locale: string; + caseLevel?: boolean; + caseFirst?: string; + strength?: number; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + normalization?: boolean; +} + +/** + * The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * expect(err).to.not.exist; + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * ``` + */ +export declare class Collection { + /* Excluded from this release type: s */ + /* Excluded from this release type: __constructor */ + /** + * The name of the database this collection belongs to + */ + get dbName(): string; + /** + * The name of this collection + */ + get collectionName(): string; + /** + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + */ + get namespace(): string; + /** + * The current readConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readConcern(): ReadConcern | undefined; + /** + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readPreference(): ReadPreference | undefined; + get bsonOptions(): BSONSerializeOptions; + /** + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get writeConcern(): WriteConcern | undefined; + /** The current index hint for the collection */ + get hint(): Hint | undefined; + set hint(v: Hint | undefined); + /** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param doc - The document to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insertOne(doc: OptionalId): Promise>; + insertOne(doc: OptionalId, callback: Callback>): void; + insertOne(doc: OptionalId, options: InsertOneOptions): Promise>; + insertOne(doc: OptionalId, options: InsertOneOptions, callback: Callback>): void; + /** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insertMany(docs: OptionalId[]): Promise>; + insertMany(docs: OptionalId[], callback: Callback>): void; + insertMany(docs: OptionalId[], options: BulkWriteOptions): Promise>; + insertMany(docs: OptionalId[], options: BulkWriteOptions, callback: Callback>): void; + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * ```js + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true} } + *``` + * Please note that raw operations are no longer accepted as of driver version 4.0. + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param operations - Bulk operations to perform + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * @throws MongoDriverError if operations is not an array + */ + bulkWrite(operations: AnyBulkWriteOperation[]): Promise; + bulkWrite(operations: AnyBulkWriteOperation[], callback: Callback): void; + bulkWrite(operations: AnyBulkWriteOperation[], options: BulkWriteOptions): Promise; + bulkWrite(operations: AnyBulkWriteOperation[], options: BulkWriteOptions, callback: Callback): void; + /** + * Update a single document in a collection + * + * @param filter - The filter used to select the document to update + * @param update - The update operations to be applied to the document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + updateOne(filter: Filter, update: UpdateFilter | Partial): Promise; + updateOne(filter: Filter, update: UpdateFilter | Partial, callback: Callback): void; + updateOne(filter: Filter, update: UpdateFilter | Partial, options: UpdateOptions): Promise; + updateOne(filter: Filter, update: UpdateFilter | Partial, options: UpdateOptions, callback: Callback): void; + /** + * Replace a document in a collection with another document + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + replaceOne(filter: Filter, replacement: TSchema): Promise; + replaceOne(filter: Filter, replacement: TSchema, callback: Callback): void; + replaceOne(filter: Filter, replacement: TSchema, options: ReplaceOptions): Promise; + replaceOne(filter: Filter, replacement: TSchema, options: ReplaceOptions, callback: Callback): void; + /** + * Update multiple documents in a collection + * + * @param filter - The filter used to select the documents to update + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + updateMany(filter: Filter, update: UpdateFilter): Promise; + updateMany(filter: Filter, update: UpdateFilter, callback: Callback): void; + updateMany(filter: Filter, update: UpdateFilter, options: UpdateOptions): Promise; + updateMany(filter: Filter, update: UpdateFilter, options: UpdateOptions, callback: Callback): void; + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + deleteOne(filter: Filter): Promise; + deleteOne(filter: Filter, callback: Callback): void; + deleteOne(filter: Filter, options: DeleteOptions): Promise; + deleteOne(filter: Filter, options: DeleteOptions, callback?: Callback): void; + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + deleteMany(filter: Filter): Promise; + deleteMany(filter: Filter, callback: Callback): void; + deleteMany(filter: Filter, options: DeleteOptions): Promise; + deleteMany(filter: Filter, options: DeleteOptions, callback: Callback): void; + /** + * Rename the collection. + * + * @remarks + * This operation does not inherit options from the Db or MongoClient. + * + * @param newName - New name of of the collection. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + rename(newName: string): Promise; + rename(newName: string, callback: Callback): void; + rename(newName: string, options: RenameOptions): Promise; + rename(newName: string, options: RenameOptions, callback: Callback): void; + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + drop(): Promise; + drop(callback: Callback): void; + drop(options: DropCollectionOptions): Promise; + drop(options: DropCollectionOptions, callback: Callback): void; + /** + * Fetches the first document that matches the filter + * + * @param filter - Query for find Operation + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOne(): Promise; + findOne(callback: Callback): void; + findOne(filter: Filter): Promise; + findOne(filter: Filter, callback: Callback): void; + findOne(filter: Filter, options: FindOptions): Promise; + findOne(filter: Filter, options: FindOptions, callback: Callback): void; + findOne(): Promise; + findOne(callback: Callback): void; + findOne(filter: Filter): Promise; + findOne(filter: Filter, options?: FindOptions): Promise; + findOne(filter: Filter, options?: FindOptions, callback?: Callback): void; + /** + * Creates a cursor for a filter that can be used to iterate over results from MongoDB + * + * @param filter - The filter predicate. If unspecified, then all documents in the collection will match the predicate + */ + find(): FindCursor; + find(filter: Filter, options?: FindOptions): FindCursor; + find(filter: Filter, options?: FindOptions): FindCursor; + /** + * Returns the options of the collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + options(): Promise; + options(callback: Callback): void; + options(options: OperationOptions): Promise; + options(options: OperationOptions, callback: Callback): void; + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + isCapped(): Promise; + isCapped(callback: Callback): void; + isCapped(options: OperationOptions): Promise; + isCapped(options: OperationOptions, callback: Callback): void; + /** + * Creates an index on the db and collection collection. + * + * @param indexSpec - The field name or index specification to create an index for + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @example + * ```js + * const collection = client.db('foo').collection('bar'); + * + * await collection.createIndex({ a: 1, b: -1 }); + * + * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes + * await collection.createIndex([ [c, 1], [d, -1] ]); + * + * // Equivalent to { e: 1 } + * await collection.createIndex('e'); + * + * // Equivalent to { f: 1, g: 1 } + * await collection.createIndex(['f', 'g']) + * + * // Equivalent to { h: 1, i: -1 } + * await collection.createIndex([ { h: 1 }, { i: -1 } ]); + * + * // Equivalent to { j: 1, k: -1, l: 2d } + * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) + * ``` + */ + createIndex(indexSpec: IndexSpecification): Promise; + createIndex(indexSpec: IndexSpecification, callback: Callback): void; + createIndex(indexSpec: IndexSpecification, options: CreateIndexesOptions): Promise; + createIndex(indexSpec: IndexSpecification, options: CreateIndexesOptions, callback: Callback): void; + /** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. + * + * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications. + * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/| here}. + * + * @param indexSpecs - An array of index specifications to be created + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @example + * ```js + * const collection = client.db('foo').collection('bar'); + * await collection.createIndexes([ + * // Simple index on field fizz + * { + * key: { fizz: 1 }, + * } + * // wildcard index + * { + * key: { '$**': 1 } + * }, + * // named index on darmok and jalad + * { + * key: { darmok: 1, jalad: -1 } + * name: 'tanagra' + * } + * ]); + * ``` + */ + createIndexes(indexSpecs: IndexDescription[]): Promise; + createIndexes(indexSpecs: IndexDescription[], callback: Callback): void; + createIndexes(indexSpecs: IndexDescription[], options: CreateIndexesOptions): Promise; + createIndexes(indexSpecs: IndexDescription[], options: CreateIndexesOptions, callback: Callback): void; + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropIndex(indexName: string): Promise; + dropIndex(indexName: string, callback: Callback): void; + dropIndex(indexName: string, options: DropIndexesOptions): Promise; + dropIndex(indexName: string, options: DropIndexesOptions, callback: Callback): void; + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropIndexes(): Promise; + dropIndexes(callback: Callback): void; + dropIndexes(options: DropIndexesOptions): Promise; + dropIndexes(options: DropIndexesOptions, callback: Callback): void; + /** + * Get the list of all indexes information for the collection. + * + * @param options - Optional settings for the command + */ + listIndexes(options?: ListIndexesOptions): ListIndexesCursor; + /** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * + * @param indexes - One or more index names to check. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexExists(indexes: string | string[]): Promise; + indexExists(indexes: string | string[], callback: Callback): void; + indexExists(indexes: string | string[], options: IndexInformationOptions): Promise; + indexExists(indexes: string | string[], options: IndexInformationOptions, callback: Callback): void; + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexInformation(): Promise; + indexInformation(callback: Callback): void; + indexInformation(options: IndexInformationOptions): Promise; + indexInformation(options: IndexInformationOptions, callback: Callback): void; + /** + * Gets an estimate of the count of documents in a collection using collection metadata. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + estimatedDocumentCount(): Promise; + estimatedDocumentCount(callback: Callback): void; + estimatedDocumentCount(options: EstimatedDocumentCountOptions): Promise; + estimatedDocumentCount(options: EstimatedDocumentCountOptions, callback: Callback): void; + /** + * Gets the number of documents matching the filter. + * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ + * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param filter - The filter for the count + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ + * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + countDocuments(): Promise; + countDocuments(callback: Callback): void; + countDocuments(filter: Filter): Promise; + countDocuments(callback: Callback): void; + countDocuments(filter: Filter, options: CountDocumentsOptions): Promise; + countDocuments(filter: Filter, options: CountDocumentsOptions, callback: Callback): void; + countDocuments(filter: Filter, callback: Callback): void; + /** + * The distinct command returns a list of distinct values for the given key across a collection. + * + * @param key - Field of the document to find distinct values for + * @param filter - The filter for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + distinct>(key: Key): Promise[Key]>>>; + distinct>(key: Key, callback: Callback[Key]>>>): void; + distinct>(key: Key, filter: Filter): Promise[Key]>>>; + distinct>(key: Key, filter: Filter, callback: Callback[Key]>>>): void; + distinct>(key: Key, filter: Filter, options: DistinctOptions): Promise[Key]>>>; + distinct>(key: Key, filter: Filter, options: DistinctOptions, callback: Callback[Key]>>>): void; + distinct(key: string): Promise; + distinct(key: string, callback: Callback): void; + distinct(key: string, filter: Filter): Promise; + distinct(key: string, filter: Filter, callback: Callback): void; + distinct(key: string, filter: Filter, options: DistinctOptions): Promise; + distinct(key: string, filter: Filter, options: DistinctOptions, callback: Callback): void; + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexes(): Promise; + indexes(callback: Callback): void; + indexes(options: IndexInformationOptions): Promise; + indexes(options: IndexInformationOptions, callback: Callback): void; + /** + * Get all the collection statistics. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + stats(): Promise; + stats(callback: Callback): void; + stats(options: CollStatsOptions): Promise; + stats(options: CollStatsOptions, callback: Callback): void; + /** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndDelete(filter: Filter): Promise>; + findOneAndDelete(filter: Filter, options: FindOneAndDeleteOptions): Promise>; + findOneAndDelete(filter: Filter, callback: Callback>): void; + findOneAndDelete(filter: Filter, options: FindOneAndDeleteOptions, callback: Callback>): void; + /** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndReplace(filter: Filter, replacement: Document): Promise>; + findOneAndReplace(filter: Filter, replacement: Document, callback: Callback>): void; + findOneAndReplace(filter: Filter, replacement: Document, options: FindOneAndReplaceOptions): Promise>; + findOneAndReplace(filter: Filter, replacement: Document, options: FindOneAndReplaceOptions, callback: Callback>): void; + /** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to update + * @param update - Update operations to be performed on the document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndUpdate(filter: Filter, update: UpdateFilter): Promise>; + findOneAndUpdate(filter: Filter, update: UpdateFilter, callback: Callback>): void; + findOneAndUpdate(filter: Filter, update: UpdateFilter, options: FindOneAndUpdateOptions): Promise>; + findOneAndUpdate(filter: Filter, update: UpdateFilter, options: FindOneAndUpdateOptions, callback: Callback>): void; + /** + * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 + * + * @param pipeline - An array of aggregation pipelines to execute + * @param options - Optional settings for the command + */ + aggregate(pipeline?: Document[], options?: AggregateOptions): AggregationCursor; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * + * @since 3.0.0 + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; + /** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @param map - The mapping function. + * @param reduce - The reduce function. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction): Promise; + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction, callback: Callback): void; + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction, options: MapReduceOptions): Promise; + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction, options: MapReduceOptions, callback: Callback): void; + /** Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. */ + initializeUnorderedBulkOp(options?: BulkWriteOptions): UnorderedBulkOperation; + /** Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. */ + initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation; + /** Get the db scoped logger */ + getLogger(): Logger; + get logger(): Logger; + /** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @deprecated Use insertOne, insertMany or bulkWrite instead. + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insert(docs: OptionalId[], options: BulkWriteOptions, callback: Callback>): Promise> | void; + /** + * Updates documents. + * + * @deprecated use updateOne, updateMany or bulkWrite + * @param selector - The selector for the update operation. + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + update(selector: Filter, update: UpdateFilter, options: UpdateOptions, callback: Callback): Promise | void; + /** + * Remove documents. + * + * @deprecated use deleteOne, deleteMany or bulkWrite + * @param selector - The selector for the update operation. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + remove(selector: Filter, options: DeleteOptions, callback: Callback): Promise | void; + /** + * An estimated count of matching documents in the db to a filter. + * + * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents + * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}. + * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * + * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead + * + * @param filter - The filter for the count. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + count(): Promise; + count(callback: Callback): void; + count(filter: Filter): Promise; + count(filter: Filter, callback: Callback): void; + count(filter: Filter, options: CountOptions): Promise; + count(filter: Filter, options: CountOptions, callback: Callback): Promise | void; +} + +/** @public */ +export declare interface CollectionInfo extends Document { + name: string; + type?: string; + options?: Document; + info?: { + readOnly?: false; + uuid?: Binary; + }; + idIndex?: Document; +} + +/** @public */ +export declare interface CollectionOptions extends BSONSerializeOptions, WriteConcernOptions, LoggerOptions { + slaveOk?: boolean; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; +} + +/* Excluded from this release type: CollectionPrivate */ + +/** + * @public + * @see https://docs.mongodb.org/manual/reference/command/collStats/ + */ +export declare interface CollStats extends Document { + /** Namespace */ + ns: string; + /** Number of documents */ + count: number; + /** Collection size in bytes */ + size: number; + /** Average object size in bytes */ + avgObjSize: number; + /** (Pre)allocated space for the collection in bytes */ + storageSize: number; + /** Number of extents (contiguously allocated chunks of datafile space) */ + numExtents: number; + /** Number of indexes */ + nindexes: number; + /** Size of the most recently created extent in bytes */ + lastExtentSize: number; + /** Padding can speed up updates if documents grow */ + paddingFactor: number; + /** A number that indicates the user-set flags on the collection. userFlags only appears when using the mmapv1 storage engine */ + userFlags?: number; + /** Total index size in bytes */ + totalIndexSize: number; + /** Size of specific indexes in bytes */ + indexSizes: { + _id_: number; + [index: string]: number; + }; + /** `true` if the collection is capped */ + capped: boolean; + /** The maximum number of documents that may be present in a capped collection */ + max: number; + /** The maximum size of a capped collection */ + maxSize: number; + /** This document contains data reported directly by the WiredTiger engine and other data for internal diagnostic use */ + wiredTiger?: WiredTigerData; + /** The fields in this document are the names of the indexes, while the values themselves are documents that contain statistics for the index provided by the storage engine */ + indexDetails?: any; + ok: number; + /** The amount of storage available for reuse. The scale argument affects this value. */ + freeStorageSize?: number; + /** An array that contains the names of the indexes that are currently being built on the collection */ + indexBuilds?: number; + /** The sum of the storageSize and totalIndexSize. The scale argument affects this value */ + totalSize: number; + /** The scale value used by the command. */ + scaleFactor: number; +} + +/** @public */ +export declare interface CollStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} + +/** + * An event indicating the failure of a given command + * @public + * @category Event + */ +export declare class CommandFailedEvent { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + failure: Error; + serviceId?: ObjectId; + /* Excluded from this release type: __constructor */ + get hasServiceId(): boolean; +} + +/* Excluded from this release type: CommandOperation */ + +/** @public */ +export declare interface CommandOperationOptions extends OperationOptions, WriteConcernOptions, ExplainOptions { + /** @deprecated This option does nothing */ + fullResponse?: boolean; + /** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** Collation */ + collation?: CollationOptions; + maxTimeMS?: number; + /** A user-provided comment to attach to this command */ + comment?: string | Document; + /** Should retry failed writes */ + retryWrites?: boolean; + dbName?: string; + authdb?: string; + noResponse?: boolean; +} + +/* Excluded from this release type: CommandOptions */ + +/** + * An event indicating the start of a given + * @public + * @category Event + */ +export declare class CommandStartedEvent { + commandObj?: Document; + requestId: number; + databaseName: string; + commandName: string; + command: Document; + address: string; + connectionId?: string | number; + serviceId?: ObjectId; + /* Excluded from this release type: __constructor */ + get hasServiceId(): boolean; +} + +/** + * An event indicating the success of a given command + * @public + * @category Event + */ +export declare class CommandSucceededEvent { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + reply: unknown; + serviceId?: ObjectId; + /* Excluded from this release type: __constructor */ + get hasServiceId(): boolean; +} + +/** @public */ +export declare type CommonEvents = 'newListener' | 'removeListener'; + +/** @public */ +export declare const Compressor: Readonly<{ + readonly none: 0; + readonly snappy: 1; + readonly zlib: 2; +}>; + +/** @public */ +export declare type Compressor = typeof Compressor[CompressorName]; + +/** @public */ +export declare type CompressorName = keyof typeof Compressor; + +/** @public */ +export declare type Condition = AlternativeType | FilterOperators>; + +/* Excluded from this release type: Connection */ + +/** + * An event published when a connection is checked into the connection pool + * @public + * @category Event + */ +export declare class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection is checked out of the connection pool + * @public + * @category Event + */ +export declare class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a request to check a connection out fails + * @public + * @category Event + */ +export declare class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + /** The reason the attempt to check out failed */ + reason: AnyError | string; + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a request to check a connection out begins + * @public + * @category Event + */ +export declare class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection is closed + * @public + * @category Event + */ +export declare class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /** The reason the connection was closed */ + reason: string; + serviceId?: ObjectId; + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection pool creates a new connection + * @public + * @category Event + */ +export declare class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + /** A monotonically increasing, per-pool id for the newly created connection */ + connectionId: number | ''; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare type ConnectionEvents = { + commandStarted(event: CommandStartedEvent): void; + commandSucceeded(event: CommandSucceededEvent): void; + commandFailed(event: CommandFailedEvent): void; + clusterTimeReceived(clusterTime: Document): void; + close(): void; + message(message: any): void; + pinned(pinType: string): void; + unpinned(pinType: string): void; +}; + +/** @public */ +export declare interface ConnectionOptions extends SupportedNodeConnectionOptions, StreamDescriptionOptions { + id: number | ''; + generation: number; + hostAddress: HostAddress; + autoEncrypter?: AutoEncrypter; + serverApi?: ServerApi; + monitorCommands: boolean; + /* Excluded from this release type: connectionType */ + credentials?: MongoCredentials; + connectTimeoutMS?: number; + tls: boolean; + keepAlive?: boolean; + keepAliveInitialDelay?: number; + noDelay?: boolean; + socketTimeoutMS?: number; + cancellationToken?: CancellationToken; + metadata: ClientMetadata; +} + +/* Excluded from this release type: ConnectionPool */ + +/** + * An event published when a connection pool is cleared + * @public + * @category Event + */ +export declare class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: serviceId */ + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection pool is closed + * @public + * @category Event + */ +export declare class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection pool is created + * @public + * @category Event + */ +export declare class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + /** The options used to create this connection pool */ + options?: ConnectionPoolOptions; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare type ConnectionPoolEvents = { + connectionPoolCreated(event: ConnectionPoolCreatedEvent): void; + connectionPoolClosed(event: ConnectionPoolClosedEvent): void; + connectionPoolCleared(event: ConnectionPoolClearedEvent): void; + connectionCreated(event: ConnectionCreatedEvent): void; + connectionReady(event: ConnectionReadyEvent): void; + connectionClosed(event: ConnectionClosedEvent): void; + connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void; + connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void; + connectionCheckedOut(event: ConnectionCheckedOutEvent): void; + connectionCheckedIn(event: ConnectionCheckedInEvent): void; +} & Omit; + +/* Excluded from this release type: ConnectionPoolMetrics */ + +/** + * The base export class for all monitoring events published from the connection pool + * @public + * @category Event + */ +export declare class ConnectionPoolMonitoringEvent { + /** A timestamp when the event was created */ + time: Date; + /** The address (host/port pair) of the pool */ + address: string; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare interface ConnectionPoolOptions extends Omit { + /** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */ + maxPoolSize: number; + /** The minimum number of connections that MUST exist at any moment in a single connection pool. */ + minPoolSize: number; + /** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */ + maxIdleTimeMS: number; + /** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. */ + waitQueueTimeoutMS: number; + /** If we are in load balancer mode. */ + loadBalanced: boolean; +} + +/** + * An event published when a connection is ready for use + * @public + * @category Event + */ +export declare class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare interface ConnectOptions { + readPreference?: ReadPreference; +} + +/** @public */ +export declare interface CountDocumentsOptions extends AggregateOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; +} + +/** @public */ +export declare interface CountOptions extends CommandOperationOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** An index name hint for the query. */ + hint?: string | Document; +} + +/** @public */ +export declare interface CreateCollectionOptions extends CommandOperationOptions { + /** Returns an error if the collection does not exist */ + strict?: boolean; + /** Create a capped collection */ + capped?: boolean; + /** @deprecated Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 */ + autoIndexId?: boolean; + /** The size of the capped collection in bytes */ + size?: number; + /** The maximum number of documents in the capped collection */ + max?: number; + /** Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag */ + flags?: number; + /** Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher */ + storageEngine?: Document; + /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher */ + validator?: Document; + /** Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher */ + validationLevel?: string; + /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher */ + validationAction?: string; + /** Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher */ + indexOptionDefaults?: Document; + /** The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher */ + viewOn?: string; + /** An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher */ + pipeline?: Document[]; + /** A primary key factory function for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** A document specifying configuration options for timeseries collections. */ + timeseries?: TimeSeriesCollectionOptions; + /** The number of seconds after which a document in a timeseries collection expires. */ + expireAfterSeconds?: number; +} + +/** @public */ +export declare interface CreateIndexesOptions extends CommandOperationOptions { + /** Creates the index in the background, yielding whenever possible. */ + background?: boolean; + /** Creates an unique index. */ + unique?: boolean; + /** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */ + name?: string; + /** Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */ + partialFilterExpression?: Document; + /** Creates a sparse index. */ + sparse?: boolean; + /** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */ + expireAfterSeconds?: number; + /** Allows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher) */ + storageEngine?: Document; + /** (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. */ + commitQuorum?: number | string; + /** Specifies the index version number, either 0 or 1. */ + version?: number; + weights?: Document; + default_language?: string; + language_override?: string; + textIndexVersion?: number; + '2dsphereIndexVersion'?: number; + bits?: number; + /** For geospatial indexes set the lower bound for the co-ordinates. */ + min?: number; + /** For geospatial indexes set the high bound for the co-ordinates. */ + max?: number; + bucketSize?: number; + wildcardProjection?: Document; + /** Specifies that the index should exist on the target collection but should not be used by the query planner when executing operations. (MongoDB 4.4 or higher) */ + hidden?: boolean; +} + +/** @public */ +export declare const CURSOR_FLAGS: readonly ["tailable", "oplogReplay", "noCursorTimeout", "awaitData", "exhaust", "partial"]; + +/** @public + * @deprecated This interface is deprecated */ +export declare interface CursorCloseOptions { + /** Bypass calling killCursors when closing the cursor. */ + /** @deprecated the skipKillCursors option is deprecated */ + skipKillCursors?: boolean; +} + +/** @public */ +export declare type CursorFlag = typeof CURSOR_FLAGS[number]; + +/** @public */ +export declare interface CursorStreamOptions { + /** A transformation method applied to each document emitted by the stream */ + transform?(doc: Document): Document; +} + +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```js + * const { MongoClient } = require('mongodb'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); + * }); + * ``` + */ +export declare class Db { + /* Excluded from this release type: s */ + static SYSTEM_NAMESPACE_COLLECTION: string; + static SYSTEM_INDEX_COLLECTION: string; + static SYSTEM_PROFILE_COLLECTION: string; + static SYSTEM_USER_COLLECTION: string; + static SYSTEM_COMMAND_COLLECTION: string; + static SYSTEM_JS_COLLECTION: string; + /** + * Creates a new Db instance + * + * @param client - The MongoClient for the database. + * @param databaseName - The name of the database this instance represents. + * @param options - Optional settings for Db construction + */ + constructor(client: MongoClient, databaseName: string, options?: DbOptions); + get databaseName(): string; + get options(): DbOptions | undefined; + get slaveOk(): boolean; + get readConcern(): ReadConcern | undefined; + /** + * The current readPreference of the Db. If not explicitly defined for + * this Db, will be inherited from the parent MongoClient + */ + get readPreference(): ReadPreference; + get bsonOptions(): BSONSerializeOptions; + get writeConcern(): WriteConcern | undefined; + get namespace(): string; + /** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @param name - The name of the collection to create + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + createCollection(name: string): Promise>; + createCollection(name: string, callback: Callback>): void; + createCollection(name: string, options: CreateCollectionOptions): Promise>; + createCollection(name: string, options: CreateCollectionOptions, callback: Callback>): void; + /** + * Execute a command + * + * @remarks + * This command does not inherit options from the MongoClient. + * + * @param command - The command to run + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + command(command: Document): Promise; + command(command: Document, callback: Callback): void; + command(command: Document, options: RunCommandOptions): Promise; + command(command: Document, options: RunCommandOptions, callback: Callback): void; + /** + * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6 + * + * @param pipeline - An array of aggregation stages to be executed + * @param options - Optional settings for the command + */ + aggregate(pipeline?: Document[], options?: AggregateOptions): AggregationCursor; + /** Return the Admin db instance */ + admin(): Admin; + /** + * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. + * + * @param name - the collection name we wish to access. + * @returns return the new Collection instance + */ + collection(name: string, options?: CollectionOptions): Collection; + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + stats(): Promise; + stats(callback: Callback): void; + stats(options: DbStatsOptions): Promise; + stats(options: DbStatsOptions, callback: Callback): void; + /** + * List all collections of this database with optional filter + * + * @param filter - Query to filter collections by + * @param options - Optional settings for the command + */ + listCollections(filter: Document, options: Exclude & { + nameOnly: true; + }): ListCollectionsCursor>; + listCollections(filter: Document, options: Exclude & { + nameOnly: false; + }): ListCollectionsCursor; + listCollections | CollectionInfo = Pick | CollectionInfo>(filter?: Document, options?: ListCollectionsOptions): ListCollectionsCursor; + /** + * Rename a collection. + * + * @remarks + * This operation does not inherit options from the MongoClient. + * + * @param fromCollection - Name of current collection to rename + * @param toCollection - New name of of the collection + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + renameCollection(fromCollection: string, toCollection: string): Promise>; + renameCollection(fromCollection: string, toCollection: string, callback: Callback>): void; + renameCollection(fromCollection: string, toCollection: string, options: RenameOptions): Promise>; + renameCollection(fromCollection: string, toCollection: string, options: RenameOptions, callback: Callback>): void; + /** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param name - Name of collection to drop + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropCollection(name: string): Promise; + dropCollection(name: string, callback: Callback): void; + dropCollection(name: string, options: DropCollectionOptions): Promise; + dropCollection(name: string, options: DropCollectionOptions, callback: Callback): void; + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropDatabase(): Promise; + dropDatabase(callback: Callback): void; + dropDatabase(options: DropDatabaseOptions): Promise; + dropDatabase(options: DropDatabaseOptions, callback: Callback): void; + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + collections(): Promise; + collections(callback: Callback): void; + collections(options: ListCollectionsOptions): Promise; + collections(options: ListCollectionsOptions, callback: Callback): void; + /** + * Creates an index on the db and collection. + * + * @param name - Name of the collection to create the index on. + * @param indexSpec - Specify the field to index, or an index specification + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + createIndex(name: string, indexSpec: IndexSpecification): Promise; + createIndex(name: string, indexSpec: IndexSpecification, callback?: Callback): void; + createIndex(name: string, indexSpec: IndexSpecification, options: CreateIndexesOptions): Promise; + createIndex(name: string, indexSpec: IndexSpecification, options: CreateIndexesOptions, callback: Callback): void; + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param password - An optional password for the new user + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + addUser(username: string): Promise; + addUser(username: string, callback: Callback): void; + addUser(username: string, password: string): Promise; + addUser(username: string, password: string, callback: Callback): void; + addUser(username: string, options: AddUserOptions): Promise; + addUser(username: string, options: AddUserOptions, callback: Callback): void; + addUser(username: string, password: string, options: AddUserOptions): Promise; + addUser(username: string, password: string, options: AddUserOptions, callback: Callback): void; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + removeUser(username: string): Promise; + removeUser(username: string, callback: Callback): void; + removeUser(username: string, options: RemoveUserOptions): Promise; + removeUser(username: string, options: RemoveUserOptions, callback: Callback): void; + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + setProfilingLevel(level: ProfilingLevel): Promise; + setProfilingLevel(level: ProfilingLevel, callback: Callback): void; + setProfilingLevel(level: ProfilingLevel, options: SetProfilingLevelOptions): Promise; + setProfilingLevel(level: ProfilingLevel, options: SetProfilingLevelOptions, callback: Callback): void; + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + profilingLevel(): Promise; + profilingLevel(callback: Callback): void; + profilingLevel(options: ProfilingLevelOptions): Promise; + profilingLevel(options: ProfilingLevelOptions, callback: Callback): void; + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexInformation(name: string): Promise; + indexInformation(name: string, callback: Callback): void; + indexInformation(name: string, options: IndexInformationOptions): Promise; + indexInformation(name: string, options: IndexInformationOptions, callback: Callback): void; + /** + * Unref all sockets + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref(): void; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this database. Will ignore all + * changes to system collections. + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; + /** Return the db logger */ + getLogger(): Logger; + get logger(): Logger; +} + +/* Excluded from this release type: DB_AGGREGATE_COLLECTION */ + +/** @public */ +export declare interface DbOptions extends BSONSerializeOptions, WriteConcernOptions, LoggerOptions { + /** If the database authentication is dependent on another databaseName. */ + authSource?: string; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; + /** A primary key factory object for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcern; + /** Should retry failed writes */ + retryWrites?: boolean; +} + +/* Excluded from this release type: DbPrivate */ +export { DBRef } + +/** @public */ +export declare interface DbStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} + +export { Decimal128 } + +/** @public */ +export declare interface DeleteManyModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export declare interface DeleteOneModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export declare interface DeleteOptions extends CommandOperationOptions, WriteConcernOptions { + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** A user-provided comment to attach to this command */ + comment?: string | Document; + /** Specifies the collation to use for the operation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + /** @deprecated use `removeOne` or `removeMany` to implicitly specify the limit */ + single?: boolean; +} + +/** @public */ +export declare interface DeleteResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined. */ + acknowledged: boolean; + /** The number of documents that were deleted */ + deletedCount: number; +} + +/** @public */ +export declare interface DeleteStatement { + /** The query that matches documents to delete. */ + q: Document; + /** The number of matching documents to delete. */ + limit: number; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; + /** A user-provided comment to attach to this command */ + comment?: string | Document; +} + +/* Excluded from this release type: deserialize */ + +/** @public */ +export declare interface DestroyOptions { + /** Force the destruction. */ + force?: boolean; +} + +/** @public */ +export declare type DistinctOptions = CommandOperationOptions; + +export { Document } + +export { Double } + +/** @public */ +export declare interface DriverInfo { + name?: string; + version?: string; + platform?: string; +} + +/** @public */ +export declare type DropCollectionOptions = CommandOperationOptions; + +/** @public */ +export declare type DropDatabaseOptions = CommandOperationOptions; + +/** @public */ +export declare type DropIndexesOptions = CommandOperationOptions; + +/* Excluded from this release type: Encrypter */ + +/* Excluded from this release type: EncrypterOptions */ + +/** @public */ +export declare interface EndSessionOptions { + /* Excluded from this release type: error */ + force?: boolean; + forceClear?: boolean; +} + +/** TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions @public */ +export declare type EnhancedOmit = string extends keyof TRecordOrUnion ? TRecordOrUnion : TRecordOrUnion extends any ? Pick> : never; + +/** @public */ +export declare interface ErrorDescription extends Document { + message?: string; + errmsg?: string; + $err?: string; + errorLabels?: string[]; + errInfo?: Document; +} + +/** @public */ +export declare interface EstimatedDocumentCountOptions extends CommandOperationOptions { + /** + * The maximum amount of time to allow the operation to run. + * + * This option is sent only if the caller explicitly provides a value. The default is to not send a value. + */ + maxTimeMS?: number; +} + +/** @public */ +export declare interface EvalOptions extends CommandOperationOptions { + nolock?: boolean; +} + +/** @public */ +export declare type EventEmitterWithState = { + /* Excluded from this release type: stateChanged */ +}; + +/** + * Event description type + * @public + */ +export declare type EventsDescription = Record; + +/* Excluded from this release type: ExecutionResult */ + +/* Excluded from this release type: Explain */ + +/** @public */ +export declare interface ExplainOptions { + /** Specifies the verbosity mode for the explain output. */ + explain?: ExplainVerbosityLike; +} + +/** @public */ +export declare const ExplainVerbosity: Readonly<{ + readonly queryPlanner: "queryPlanner"; + readonly queryPlannerExtended: "queryPlannerExtended"; + readonly executionStats: "executionStats"; + readonly allPlansExecution: "allPlansExecution"; +}>; + +/** @public */ +export declare type ExplainVerbosity = string; + +/** + * For backwards compatibility, true is interpreted as "allPlansExecution" + * and false as "queryPlanner". Prior to server version 3.6, aggregate() + * ignores the verbosity parameter and executes in "queryPlanner". + * @public + */ +export declare type ExplainVerbosityLike = ExplainVerbosity | boolean; + +/** A MongoDB filter can be some portion of the schema or a set of operators @public */ +export declare type Filter = { + [P in keyof TSchema]?: Condition; +} & RootFilterOperators; + +/** @public */ +export declare type FilterOperations = T extends Record ? { + [key in keyof T]?: FilterOperators; +} : FilterOperators; + +/** @public */ +export declare interface FilterOperators extends Document { + $eq?: TValue; + $gt?: TValue; + $gte?: TValue; + $in?: ReadonlyArray; + $lt?: TValue; + $lte?: TValue; + $ne?: TValue; + $nin?: ReadonlyArray; + $not?: TValue extends string ? FilterOperators | RegExp : FilterOperators; + /** + * When `true`, `$exists` matches the documents that contain the field, + * including documents where the field value is null. + */ + $exists?: boolean; + $type?: BSONType | BSONTypeAlias; + $expr?: Record; + $jsonSchema?: Record; + $mod?: TValue extends number ? [number, number] : never; + $regex?: TValue extends string ? RegExp | BSONRegExp | string : never; + $options?: TValue extends string ? string : never; + $geoIntersects?: { + $geometry: Document; + }; + $geoWithin?: Document; + $near?: Document; + $nearSphere?: Document; + $maxDistance?: number; + $all?: ReadonlyArray; + $elemMatch?: Document; + $size?: TValue extends ReadonlyArray ? number : never; + $bitsAllClear?: BitwiseFilter; + $bitsAllSet?: BitwiseFilter; + $bitsAnyClear?: BitwiseFilter; + $bitsAnySet?: BitwiseFilter; + $rand?: Record; +} + +/** @public */ +export declare type FinalizeFunction = (key: TKey, reducedValue: TValue) => TValue; + +/** @public */ +export declare class FindCursor extends AbstractCursor { + /* Excluded from this release type: [kFilter] */ + /* Excluded from this release type: [kNumReturned] */ + /* Excluded from this release type: [kBuiltOptions] */ + /* Excluded from this release type: __constructor */ + clone(): FindCursor; + map(transform: (doc: TSchema) => T): FindCursor; + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: _getMore */ + /** Get the count of documents for this cursor */ + count(): Promise; + count(callback: Callback): void; + count(options: CountOptions): Promise; + count(options: CountOptions, callback: Callback): void; + /** Execute the explain for the cursor */ + explain(): Promise; + explain(callback: Callback): void; + explain(verbosity?: ExplainVerbosityLike): Promise; + /** Set the cursor query */ + filter(filter: Document): this; + /** + * Set the cursor hint + * + * @param hint - If specified, then the query system will only consider plans using the hinted index. + */ + hint(hint: Hint): this; + /** + * Set the cursor min + * + * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + */ + min(min: Document): this; + /** + * Set the cursor max + * + * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + */ + max(max: Document): this; + /** + * Set the cursor returnKey. + * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. + * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * + * @param value - the returnKey value. + */ + returnKey(value: boolean): this; + /** + * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. + * + * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + */ + showRecordId(value: boolean): this; + /** + * Add a query modifier to the cursor query + * + * @param name - The query modifier (must start with $, such as $orderby etc) + * @param value - The modifier value. + */ + addQueryModifier(name: string, value: string | boolean | number | Document): this; + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * + * @param value - The comment attached to this query. + */ + comment(value: string): this; + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * + * @param value - Number of milliseconds to wait before aborting the tailed query. + */ + maxAwaitTimeMS(value: number): this; + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this; + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic + * {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: FindCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.find().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project(value: Document): FindCursor; + /** + * Sets the sort order of the cursor query. + * + * @param sort - The key or keys set for the sort. + * @param direction - The direction of the sorting (1 or -1). + */ + sort(sort: Sort | string, direction?: SortDirection): this; + /** + * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) + * + * @remarks + * {@link https://docs.mongodb.com/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} + */ + allowDiskUse(): this; + /** + * Set the collation options for the cursor. + * + * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + */ + collation(value: CollationOptions): this; + /** + * Set the limit for the cursor. + * + * @param value - The limit for the cursor query. + */ + limit(value: number): this; + /** + * Set the skip for the cursor. + * + * @param value - The skip for the cursor query. + */ + skip(value: number): this; +} + +/** @public */ +export declare interface FindOneAndDeleteOptions extends CommandOperationOptions { + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export declare interface FindOneAndReplaceOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export declare interface FindOneAndUpdateOptions extends CommandOperationOptions { + /** Optional list of array filters referenced in filtered positional operators */ + arrayFilters?: Document[]; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +export declare class FindOperators { + bulkOperation: BulkOperationBase; + /* Excluded from this release type: __constructor */ + /** Add a multiple update operation to the bulk operation */ + update(updateDocument: Document): BulkOperationBase; + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument: Document): BulkOperationBase; + /** Add a replace one operation to the bulk operation */ + replaceOne(replacement: Document): BulkOperationBase; + /** Add a delete one operation to the bulk operation */ + deleteOne(): BulkOperationBase; + /** Add a delete many operation to the bulk operation */ + delete(): BulkOperationBase; + /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ + upsert(): this; + /** Specifies the collation for the query condition. */ + collation(collation: CollationOptions): this; + /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ + arrayFilters(arrayFilters: Document[]): this; +} + +/** + * @public + * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic + */ +export declare interface FindOptions extends CommandOperationOptions { + /** Sets the limit of documents returned in the query. */ + limit?: number; + /** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */ + sort?: Sort; + /** The fields to return in the query. Object of fields to either include or exclude (one of, not both), `{'a':1, 'b': 1}` **or** `{'a': 0, 'b': 0}` */ + projection?: Document; + /** Set to skip N documents ahead in your query (useful for pagination). */ + skip?: number; + /** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */ + hint?: Hint; + /** Specify if the cursor can timeout. */ + timeout?: boolean; + /** Specify if the cursor is tailable. */ + tailable?: boolean; + /** Specify if the cursor is a a tailable-await cursor. Requires `tailable` to be true */ + awaitData?: boolean; + /** Set the batchSize for the getMoreCommand when iterating over the query results. */ + batchSize?: number; + /** If true, returns only the index keys in the resulting documents. */ + returnKey?: boolean; + /** The inclusive lower bound for a specific index */ + min?: Document; + /** The exclusive upper bound for a specific index */ + max?: Document; + /** You can put a $comment field on a query to make looking in the profiler logs simpler. */ + comment?: string | Document; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true */ + maxAwaitTimeMS?: number; + /** The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. */ + noCursorTimeout?: boolean; + /** Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */ + collation?: CollationOptions; + /** Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) */ + allowDiskUse?: boolean; + /** Determines whether to close the cursor after the first batch. Defaults to false. */ + singleBatch?: boolean; + /** For queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable. */ + allowPartialResults?: boolean; + /** Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents. */ + showRecordId?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export declare type Flatten = Type extends ReadonlyArray ? Item : Type; + +/** @public */ +export declare type GenericListener = (...args: any[]) => void; + +/* Excluded from this release type: GetMore */ + +/* Excluded from this release type: GetMoreOptions */ + +/** + * Constructor for a streaming GridFS interface + * @public + */ +export declare class GridFSBucket extends TypedEventEmitter { + /* Excluded from this release type: s */ + /** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * @event + */ + static readonly INDEX: "index"; + constructor(db: Db, options?: GridFSBucketOptions); + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + openUploadStream(filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream; + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + */ + openUploadStreamWithId(id: ObjectId, filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream; + /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ + openDownloadStream(id: ObjectId, options?: GridFSBucketReadStreamOptions): GridFSBucketReadStream; + /** + * Deletes a file with the given id + * + * @param id - The id of the file doc + */ + delete(id: ObjectId): Promise; + delete(id: ObjectId, callback: Callback): void; + /** Convenience wrapper around find on the files collection */ + find(filter?: Filter, options?: FindOptions): FindCursor; + /** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + */ + openDownloadStreamByName(filename: string, options?: GridFSBucketReadStreamOptionsWithRevision): GridFSBucketReadStream; + /** + * Renames the file with the given _id to the given string + * + * @param id - the id of the file to rename + * @param filename - new name for the file + */ + rename(id: ObjectId, filename: string): Promise; + rename(id: ObjectId, filename: string, callback: Callback): void; + /** Removes this bucket's files collection, followed by its chunks collection. */ + drop(): Promise; + drop(callback: Callback): void; + /** Get the Db scoped logger. */ + getLogger(): Logger; +} + +/** @public */ +export declare type GridFSBucketEvents = { + index(): void; +}; + +/** @public */ +export declare interface GridFSBucketOptions extends WriteConcernOptions { + /** The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. */ + bucketName?: string; + /** Number of bytes stored in each chunk. Defaults to 255KB */ + chunkSizeBytes?: number; + /** Read preference to be passed to read operations */ + readPreference?: ReadPreference; +} + +/* Excluded from this release type: GridFSBucketPrivate */ + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * @public + */ +export declare class GridFSBucketReadStream extends Readable implements NodeJS.ReadableStream { + /* Excluded from this release type: s */ + /** + * An error occurred + * @event + */ + static readonly ERROR: "error"; + /** + * Fires when the stream loaded the file document corresponding to the provided id. + * @event + */ + static readonly FILE: "file"; + /** + * Emitted when a chunk of data is available to be consumed. + * @event + */ + static readonly DATA: "data"; + /** + * Fired when the stream is exhausted (no more data events). + * @event + */ + static readonly END: "end"; + /** + * Fired when the stream is exhausted and the underlying cursor is killed + * @event + */ + static readonly CLOSE: "close"; + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: _read */ + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param start - 0-based offset in bytes to start streaming from + */ + start(start?: number): this; + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param end - Offset in bytes to stop reading at + */ + end(end?: number): this; + /** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @param callback - called when the cursor is successfully closed or an error occurred. + */ + abort(callback?: Callback): void; +} + +/** @public */ +export declare interface GridFSBucketReadStreamOptions { + sort?: Sort; + skip?: number; + /** 0-based offset in bytes to start streaming from */ + start?: number; + /** 0-based offset in bytes to stop streaming before */ + end?: number; +} + +/** @public */ +export declare interface GridFSBucketReadStreamOptionsWithRevision extends GridFSBucketReadStreamOptions { + /** The revision number relative to the oldest file with the given filename. 0 + * gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the + * newest. */ + revision?: number; +} + +/* Excluded from this release type: GridFSBucketReadStreamPrivate */ + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * @public + */ +export declare class GridFSBucketWriteStream extends Writable implements NodeJS.WritableStream { + bucket: GridFSBucket; + chunks: Collection; + filename: string; + files: Collection; + options: GridFSBucketWriteStreamOptions; + done: boolean; + id: ObjectId; + chunkSizeBytes: number; + bufToStore: Buffer; + length: number; + n: number; + pos: number; + state: { + streamEnd: boolean; + outstandingRequests: number; + errored: boolean; + aborted: boolean; + }; + writeConcern?: WriteConcern; + /** @event */ + static readonly CLOSE = "close"; + /** @event */ + static readonly ERROR = "error"; + /** + * `end()` was called and the write stream successfully wrote the file metadata and all the chunks to MongoDB. + * @event + */ + static readonly FINISH = "finish"; + /* Excluded from this release type: __constructor */ + /** + * Write a buffer to the stream. + * + * @param chunk - Buffer to write + * @param encodingOrCallback - Optional encoding for the buffer + * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @returns False if this write required flushing a chunk to MongoDB. True otherwise. + */ + write(chunk: Buffer | string): boolean; + write(chunk: Buffer | string, callback: Callback): boolean; + write(chunk: Buffer | string, encoding: BufferEncoding | undefined): boolean; + write(chunk: Buffer | string, encoding: BufferEncoding | undefined, callback: Callback): boolean; + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + * + * @param callback - called when chunks are successfully removed or error occurred + */ + abort(): Promise; + abort(callback: Callback): void; + /** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @param chunk - Buffer to write + * @param encoding - Optional encoding for the buffer + * @param callback - Function to call when all files and chunks have been persisted to MongoDB + */ + end(): void; + end(chunk: Buffer): void; + end(callback: Callback): void; + end(chunk: Buffer, callback: Callback): void; + end(chunk: Buffer, encoding: BufferEncoding): void; + end(chunk: Buffer, encoding: BufferEncoding | undefined, callback: Callback): void; +} + +/** @public */ +export declare interface GridFSBucketWriteStreamOptions extends WriteConcernOptions { + /** Overwrite this bucket's chunkSizeBytes for this file */ + chunkSizeBytes?: number; + /** Custom file id for the GridFS file. */ + id?: ObjectId; + /** Object to store in the file document's `metadata` field */ + metadata?: Document; + /** String to store in the file document's `contentType` field */ + contentType?: string; + /** Array of strings to store in the file document's `aliases` field */ + aliases?: string[]; +} + +/** @public */ +export declare interface GridFSChunk { + _id: ObjectId; + files_id: ObjectId; + n: number; + data: Buffer | Uint8Array; +} + +/** @public */ +export declare interface GridFSFile { + _id: ObjectId; + length: number; + chunkSize: number; + filename: string; + contentType?: string; + aliases?: string[]; + metadata?: Document; + uploadDate: Date; +} + +/** @public */ +export declare interface HedgeOptions { + /** Explicitly enable or disable hedged reads. */ + enabled?: boolean; +} + +/** @public */ +export declare type Hint = string | Document; + +/** @public */ +export declare class HostAddress { + host: string | undefined; + port: number | undefined; + socketPath: string | undefined; + isIPv6: boolean | undefined; + constructor(hostString: string); + /** + * @param ipv6Brackets - optionally request ipv6 bracket notation required for connection strings + */ + toString(ipv6Brackets?: boolean): string; + static fromString(s: string): HostAddress; +} + +/** @public */ +export declare interface IndexDescription extends Pick { + collation?: CollationOptions; + name?: string; + key: Document; +} + +/** @public */ +export declare type IndexDirection = -1 | 1 | '2d' | '2dsphere' | 'text' | 'geoHaystack' | number; + +/** @public */ +export declare interface IndexInformationOptions { + full?: boolean; + readPreference?: ReadPreference; + session?: ClientSession; +} + +/** @public */ +export declare type IndexSpecification = OneOrMore; + +/** Given an object shaped type, return the type of the _id field or default to ObjectId @public */ +export declare type InferIdType = TSchema extends { + _id: infer IdType; +} ? {} extends IdType ? Exclude : unknown extends IdType ? ObjectId : IdType : ObjectId; + +/** @public */ +export declare interface InsertManyResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of inserted documents for this operations */ + insertedCount: number; + /** Map of the index of the inserted document to the id of the inserted document */ + insertedIds: { + [key: number]: InferIdType; + }; +} + +/** @public */ +export declare interface InsertOneModel { + /** The document to insert. */ + document: OptionalId; +} + +/** @public */ +export declare interface InsertOneOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; +} + +/** @public */ +export declare interface InsertOneResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The identifier that was inserted. If the server generated the identifier, this value will be null as the driver does not have access to that data */ + insertedId: InferIdType; +} + +export { Int32 } + +/** @public */ +export declare type IntegerType = number | Int32 | Long; + +/* Excluded from this release type: InternalAbstractCursorOptions */ + +/* Excluded from this release type: InterruptibleAsyncInterval */ + +/** @public */ +export declare type IsAny = true extends false & Type ? ResultIfAny : ResultIfNotAny; + +/* Excluded from this release type: kBeforeHandshake */ + +/* Excluded from this release type: kBuffer */ + +/* Excluded from this release type: kBuffers */ + +/* Excluded from this release type: kBuiltOptions */ + +/* Excluded from this release type: kCancellationToken */ + +/* Excluded from this release type: kCancellationToken_2 */ + +/* Excluded from this release type: kCancelled */ + +/* Excluded from this release type: kCancelled_2 */ + +/* Excluded from this release type: kCheckedOut */ + +/* Excluded from this release type: kClosed */ + +/* Excluded from this release type: kClosed_2 */ + +/* Excluded from this release type: kClusterTime */ + +/* Excluded from this release type: kConnection */ + +/* Excluded from this release type: kConnectionCounter */ + +/* Excluded from this release type: kConnections */ + +/* Excluded from this release type: kCursorStream */ + +/* Excluded from this release type: kDescription */ + +/* Excluded from this release type: kDocuments */ + +/* Excluded from this release type: kErrorLabels */ + +/** @public */ +export declare type KeysOfAType = { + [key in keyof TSchema]: NonNullable extends Type ? key : never; +}[keyof TSchema]; + +/** @public */ +export declare type KeysOfOtherType = { + [key in keyof TSchema]: NonNullable extends Type ? never : key; +}[keyof TSchema]; + +/* Excluded from this release type: kFilter */ + +/* Excluded from this release type: kFullResult */ + +/* Excluded from this release type: kGeneration */ + +/* Excluded from this release type: kGeneration_2 */ + +/* Excluded from this release type: kId */ + +/* Excluded from this release type: KillCursor */ + +/* Excluded from this release type: kInitialized */ + +/* Excluded from this release type: kInternalClient */ + +/* Excluded from this release type: kIsMaster */ + +/* Excluded from this release type: kKilled */ + +/* Excluded from this release type: kLastUseTime */ + +/* Excluded from this release type: kLength */ + +/* Excluded from this release type: kLogger */ + +/* Excluded from this release type: kMessageStream */ + +/* Excluded from this release type: kMetrics */ + +/* Excluded from this release type: kMinPoolSizeTimer */ + +/* Excluded from this release type: kMode */ + +/* Excluded from this release type: kMonitor */ + +/* Excluded from this release type: kMonitorId */ + +/* Excluded from this release type: kNamespace */ + +/* Excluded from this release type: kNumReturned */ + +/* Excluded from this release type: kOptions */ + +/* Excluded from this release type: kOptions_2 */ + +/* Excluded from this release type: kOptions_3 */ + +/* Excluded from this release type: kPermits */ + +/* Excluded from this release type: kPinnedConnection */ + +/* Excluded from this release type: kPipeline */ + +/* Excluded from this release type: kProcessingWaitQueue */ + +/* Excluded from this release type: kQueue */ + +/* Excluded from this release type: kResumeQueue */ + +/* Excluded from this release type: kRoundTripTime */ + +/* Excluded from this release type: kRTTPinger */ + +/* Excluded from this release type: kServer */ + +/* Excluded from this release type: kServer_2 */ + +/* Excluded from this release type: kServerError */ + +/* Excluded from this release type: kServerSession */ + +/* Excluded from this release type: kServiceGenerations */ + +/* Excluded from this release type: kSession */ + +/* Excluded from this release type: kSession_2 */ + +/* Excluded from this release type: kSnapshotEnabled */ + +/* Excluded from this release type: kSnapshotTime */ + +/* Excluded from this release type: kStream */ + +/* Excluded from this release type: kTopology */ + +/* Excluded from this release type: kTransform */ + +/* Excluded from this release type: kWaitQueue */ + +/* Excluded from this release type: kWaitQueue_2 */ + +/** @public */ +export declare const LEGAL_TCP_SOCKET_OPTIONS: readonly ["family", "hints", "localAddress", "localPort", "lookup"]; + +/** @public */ +export declare const LEGAL_TLS_SOCKET_OPTIONS: readonly ["ALPNProtocols", "ca", "cert", "checkServerIdentity", "ciphers", "crl", "ecdhCurve", "key", "minDHSize", "passphrase", "pfx", "rejectUnauthorized", "secureContext", "secureProtocol", "servername", "session"]; + +/** @public */ +export declare class ListCollectionsCursor | CollectionInfo = Pick | CollectionInfo> extends AbstractCursor { + parent: Db; + filter: Document; + options?: ListCollectionsOptions; + constructor(db: Db, filter: Document, options?: ListCollectionsOptions); + clone(): ListCollectionsCursor; + /* Excluded from this release type: _initialize */ +} + +/** @public */ +export declare interface ListCollectionsOptions extends CommandOperationOptions { + /** Since 4.0: If true, will only return the collection name in the response, and will omit additional info */ + nameOnly?: boolean; + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** @public */ +export declare interface ListDatabasesOptions extends CommandOperationOptions { + /** A query predicate that determines which databases are listed */ + filter?: Document; + /** A flag to indicate whether the command should return just the database names, or return both database names and size information */ + nameOnly?: boolean; + /** A flag that determines which databases are returned based on the user privileges when access control is enabled */ + authorizedDatabases?: boolean; +} + +/** @public */ +export declare type ListDatabasesResult = string[] | Document[]; + +/** @public */ +export declare class ListIndexesCursor extends AbstractCursor { + parent: Collection; + options?: ListIndexesOptions; + constructor(collection: Collection, options?: ListIndexesOptions); + clone(): ListIndexesCursor; + /* Excluded from this release type: _initialize */ +} + +/** @public */ +export declare interface ListIndexesOptions extends CommandOperationOptions { + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** + * @public + */ +export declare class Logger { + className: string; + /** + * Creates a new Logger instance + * + * @param className - The Class name associated with the logging instance + * @param options - Optional logging settings + */ + constructor(className: string, options?: LoggerOptions); + /** + * Log a message at the debug level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + debug(message: string, object?: unknown): void; + /** + * Log a message at the warn level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + warn(message: string, object?: unknown): void; + /** + * Log a message at the info level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + info(message: string, object?: unknown): void; + /** + * Log a message at the error level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + error(message: string, object?: unknown): void; + /** Is the logger set at info level */ + isInfo(): boolean; + /** Is the logger set at error level */ + isError(): boolean; + /** Is the logger set at error level */ + isWarn(): boolean; + /** Is the logger set at debug level */ + isDebug(): boolean; + /** Resets the logger to default settings, error and no filtered classes */ + static reset(): void; + /** Get the current logger function */ + static currentLogger(): LoggerFunction; + /** + * Set the current logger function + * + * @param logger - Custom logging function + */ + static setCurrentLogger(logger: LoggerFunction): void; + /** + * Filter log messages for a particular class + * + * @param type - The type of filter (currently only class) + * @param values - The filters to apply + */ + static filter(type: string, values: string[]): void; + /** + * Set the current log level + * + * @param newLevel - Set current log level (debug, warn, info, error) + */ + static setLevel(newLevel: LoggerLevel): void; +} + +/** @public */ +export declare type LoggerFunction = (message?: any, ...optionalParams: any[]) => void; + +/** @public */ +export declare const LoggerLevel: Readonly<{ + readonly ERROR: "error"; + readonly WARN: "warn"; + readonly INFO: "info"; + readonly DEBUG: "debug"; + readonly error: "error"; + readonly warn: "warn"; + readonly info: "info"; + readonly debug: "debug"; +}>; + +/** @public */ +export declare type LoggerLevel = typeof LoggerLevel[keyof typeof LoggerLevel]; + +/** @public */ +export declare interface LoggerOptions { + logger?: LoggerFunction; + loggerLevel?: LoggerLevel; +} + +export { Long } + +export { Map_2 as Map } + +/** @public */ +export declare type MapFunction = (this: TSchema) => void; + +/** @public */ +export declare interface MapReduceOptions extends CommandOperationOptions { + /** Sets the output target for the map reduce job. */ + out?: 'inline' | { + inline: 1; + } | { + replace: string; + } | { + merge: string; + } | { + reduce: string; + }; + /** Query filter object. */ + query?: Document; + /** Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. */ + sort?: Sort; + /** Number of objects to return from collection. */ + limit?: number; + /** Keep temporary data. */ + keeptemp?: boolean; + /** Finalize function. */ + finalize?: FinalizeFunction | string; + /** Can pass in variables that can be access from map/reduce/finalize. */ + scope?: Document; + /** It is possible to make the execution stay in JS. Provided in MongoDB \> 2.0.X. */ + jsMode?: boolean; + /** Provide statistics on job execution time. */ + verbose?: boolean; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; +} + +/** @public */ +export declare type MatchKeysAndValues = Readonly> & Record; + +export { MaxKey } + +/* Excluded from this release type: MessageStream */ + +/* Excluded from this release type: MessageStreamOptions */ +export { MinKey } + +/** @public */ +export declare interface ModifyResult { + value: TSchema | null; + lastErrorObject?: Document; + ok: 0 | 1; +} + +/** @public */ +export declare const MONGO_CLIENT_EVENTS: readonly ["connectionPoolCreated", "connectionPoolClosed", "connectionCreated", "connectionReady", "connectionClosed", "connectionCheckOutStarted", "connectionCheckOutFailed", "connectionCheckedOut", "connectionCheckedIn", "connectionPoolCleared", ...("error" | "close" | "commandStarted" | "commandSucceeded" | "commandFailed" | "serverHeartbeatStarted" | "serverHeartbeatSucceeded" | "serverHeartbeatFailed" | "timeout" | "serverOpening" | "serverClosed" | "serverDescriptionChanged" | "topologyOpening" | "topologyClosed" | "topologyDescriptionChanged")[]]; + +/** + * An error generated when the driver API is used incorrectly + * + * @privateRemarks + * Should **never** be directly instantiated + * + * @public + * @category Error + */ +export declare class MongoAPIError extends MongoDriverError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when a batch command is reexecuted after one of the commands in the batch + * has failed + * + * @public + * @category Error + */ +export declare class MongoBatchReExecutionError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** + * An error indicating an unsuccessful Bulk Write + * @public + * @category Error + */ +export declare class MongoBulkWriteError extends MongoServerError { + result: BulkWriteResult; + writeErrors: OneOrMore; + err?: WriteConcernError; + /** Creates a new MongoBulkWriteError */ + constructor(error: { + message: string; + code: number; + writeErrors?: WriteError[]; + } | WriteConcernError | AnyError, result: BulkWriteResult); + get name(): string; + /** Number of documents inserted. */ + get insertedCount(): number; + /** Number of documents matched for update. */ + get matchedCount(): number; + /** Number of documents modified. */ + get modifiedCount(): number; + /** Number of documents deleted. */ + get deletedCount(): number; + /** Number of documents upserted. */ + get upsertedCount(): number; + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds(): { + [key: number]: any; + }; + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds(): { + [key: number]: any; + }; +} + +/** + * An error generated when a ChangeStream operation fails to execute. + * + * @public + * @category Error + */ +export declare class MongoChangeStreamError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** + * The **MongoClient** class is a class that allows for making Connections to MongoDB. + * @public + * + * @remarks + * The programmatically provided options take precedent over the URI options. + * + * @example + * ```js + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + * + * @example + * ```js + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + */ +export declare class MongoClient extends TypedEventEmitter { + /* Excluded from this release type: s */ + /* Excluded from this release type: topology */ + /* Excluded from this release type: [kOptions] */ + constructor(url: string, options?: MongoClientOptions); + get options(): Readonly; + get serverApi(): Readonly; + /* Excluded from this release type: monitorCommands */ + /* Excluded from this release type: monitorCommands */ + get autoEncrypter(): AutoEncrypter | undefined; + get readConcern(): ReadConcern | undefined; + get writeConcern(): WriteConcern | undefined; + get readPreference(): ReadPreference; + get bsonOptions(): BSONSerializeOptions; + get logger(): Logger; + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + connect(): Promise; + connect(callback: Callback): void; + /** + * Close the db and its underlying connections + * + * @param force - Force close, emitting no events + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + close(): Promise; + close(callback: Callback): void; + close(force: boolean): Promise; + close(force: boolean, callback: Callback): void; + /** + * Create a new Db instance sharing the current socket connections. + * + * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. + * @param options - Optional settings for Db construction + */ + db(dbName?: string, options?: DbOptions): Db; + /** + * Connect to MongoDB using a url + * + * @remarks + * The programmatically provided options take precedent over the URI options. + * + * @see https://docs.mongodb.org/manual/reference/connection-string/ + */ + static connect(url: string): Promise; + static connect(url: string, callback: Callback): void; + static connect(url: string, options: MongoClientOptions): Promise; + static connect(url: string, options: MongoClientOptions, callback: Callback): void; + /** Starts a new session on the server */ + startSession(): ClientSession; + startSession(options: ClientSessionOptions): ClientSession; + /** + * Runs a given operation with an implicitly created session. The lifetime of the session + * will be handled without the need for user interaction. + * + * NOTE: presently the operation MUST return a Promise (either explicit or implicitly as an async function) + * + * @param options - Optional settings for the command + * @param callback - An callback to execute with an implicitly created session + */ + withSession(callback: WithSessionCallback): Promise; + withSession(options: ClientSessionOptions, callback: WithSessionCallback): Promise; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this cluster. Will ignore all + * changes to system collections, as well as the local, admin, and config databases. + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; + /** Return the mongo client logger */ + getLogger(): Logger; +} + +/** @public */ +export declare type MongoClientEvents = Pick & { + open(mongoClient: MongoClient): void; +}; + +/** + * Describes all possible URI query options for the mongo client + * @public + * @see https://docs.mongodb.com/manual/reference/connection-string + */ +export declare interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeConnectionOptions { + /** Specifies the name of the replica set, if the mongod is a member of a replica set. */ + replicaSet?: string; + /** Enables or disables TLS/SSL for the connection. */ + tls?: boolean; + /** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */ + ssl?: boolean; + /** Specifies the location of a local TLS Certificate */ + tlsCertificateFile?: string; + /** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key or only the client's TLS/SSL key when tlsCertificateFile is used to provide the certificate. */ + tlsCertificateKeyFile?: string; + /** Specifies the password to de-crypt the tlsCertificateKeyFile. */ + tlsCertificateKeyFilePassword?: string; + /** Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance. */ + tlsCAFile?: string; + /** Bypasses validation of the certificates presented by the mongod/mongos instance */ + tlsAllowInvalidCertificates?: boolean; + /** Disables hostname validation of the certificate presented by the mongod/mongos instance. */ + tlsAllowInvalidHostnames?: boolean; + /** Disables various certificate validations. */ + tlsInsecure?: boolean; + /** The time in milliseconds to attempt a connection before timing out. */ + connectTimeoutMS?: number; + /** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */ + socketTimeoutMS?: number; + /** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */ + compressors?: CompressorName[] | string; + /** An integer that specifies the compression level if using zlib for network compression. */ + zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined; + /** The maximum number of connections in the connection pool. */ + maxPoolSize?: number; + /** The minimum number of connections in the connection pool. */ + minPoolSize?: number; + /** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */ + maxIdleTimeMS?: number; + /** The maximum time in milliseconds that a thread can wait for a connection to become available. */ + waitQueueTimeoutMS?: number; + /** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The level of isolation */ + readConcernLevel?: ReadConcernLevel; + /** Specifies the read preferences for this connection */ + readPreference?: ReadPreferenceMode | ReadPreference; + /** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */ + maxStalenessSeconds?: number; + /** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */ + readPreferenceTags?: TagSet[]; + /** The auth settings for when connection to server. */ + auth?: Auth; + /** Specify the database name associated with the user’s credentials. */ + authSource?: string; + /** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */ + authMechanism?: AuthMechanism; + /** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */ + authMechanismProperties?: AuthMechanismProperties; + /** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */ + localThresholdMS?: number; + /** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */ + serverSelectionTimeoutMS?: number; + /** heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one. */ + heartbeatFrequencyMS?: number; + /** Sets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort. */ + minHeartbeatFrequencyMS?: number; + /** The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections */ + appName?: string; + /** Enables retryable reads. */ + retryReads?: boolean; + /** Enable retryable writes. */ + retryWrites?: boolean; + /** Allow a driver to force a Single topology type with a connection string containing one host */ + directConnection?: boolean; + /** Instruct the driver it is connecting to a load balancer fronting a mongos like service */ + loadBalanced?: boolean; + /** The write concern w value */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + /** Validate mongod server certificate against Certificate Authority */ + sslValidate?: boolean; + /** SSL Certificate file path. */ + sslCA?: string; + /** SSL Certificate file path. */ + sslCert?: string; + /** SSL Key file file path. */ + sslKey?: string; + /** SSL Certificate pass phrase. */ + sslPass?: string; + /** SSL Certificate revocation list file path. */ + sslCRL?: string; + /** TCP Connection no delay */ + noDelay?: boolean; + /** TCP Connection keep alive enabled */ + keepAlive?: boolean; + /** The number of milliseconds to wait before initiating keepAlive on the TCP socket */ + keepAliveInitialDelay?: number; + /** Force server to assign `_id` values instead of driver */ + forceServerObjectId?: boolean; + /** Return document results as raw BSON buffers */ + raw?: boolean; + /** A primary key factory function for generation of custom `_id` keys */ + pkFactory?: PkFactory; + /** A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible */ + promiseLibrary?: any; + /** The logging level */ + loggerLevel?: LoggerLevel; + /** Custom logger object */ + logger?: Logger; + /** Enable command monitoring for this client */ + monitorCommands?: boolean; + /** Server API version */ + serverApi?: ServerApi | ServerApiVersion; + /** + * Optionally enable client side auto encryption + * + * @remarks + * Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error + * (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts. + * + * Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://docs.mongodb.com/manual/reference/command/listCollections/#dbcmd.listCollections). + * + * If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true: + * - AutoEncryptionOptions.keyVaultClient is not passed. + * - AutoEncryptionOptions.bypassAutomaticEncryption is false. + * + * If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted. + */ + autoEncryption?: AutoEncryptionOptions; + /** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */ + driverInfo?: DriverInfo; + /* Excluded from this release type: srvPoller */ + /* Excluded from this release type: connectionType */ +} + +/* Excluded from this release type: MongoClientPrivate */ + +/** + * An error generated when a feature that is not enabled or allowed for the current server + * configuration is used + * + * + * @public + * @category Error + */ +export declare class MongoCompatibilityError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * A representation of the credentials used by MongoDB + * @public + */ +export declare class MongoCredentials { + /** The username used for authentication */ + readonly username: string; + /** The password used for authentication */ + readonly password: string; + /** The database that the user should authenticate against */ + readonly source: string; + /** The method used to authenticate */ + readonly mechanism: AuthMechanism; + /** Special properties used by some types of auth mechanisms */ + readonly mechanismProperties: AuthMechanismProperties; + constructor(options: MongoCredentialsOptions); + /** Determines if two MongoCredentials objects are equivalent */ + equals(other: MongoCredentials): boolean; + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param ismaster - An ismaster response from the server + */ + resolveAuthMechanism(ismaster?: Document): MongoCredentials; + validate(): void; + static merge(creds: MongoCredentials | undefined, options: Partial): MongoCredentials; +} + +/** @public */ +export declare interface MongoCredentialsOptions { + username: string; + password: string; + source: string; + db?: string; + mechanism?: AuthMechanism; + mechanismProperties: AuthMechanismProperties; +} + +/** + * An error thrown when an attempt is made to read from a cursor that has been exhausted + * + * @public + * @category Error + */ +export declare class MongoCursorExhaustedError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** + * An error thrown when the user attempts to add options to a cursor that has already been + * initialized + * + * @public + * @category Error + */ +export declare class MongoCursorInUseError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** @public */ +export declare class MongoDBNamespace { + db: string; + collection?: string; + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(db: string, collection?: string); + toString(): string; + withCollection(collection: string): MongoDBNamespace; + static fromString(namespace?: string): MongoDBNamespace; +} + +/** + * An error generated when the driver fails to decompress + * data received from the server. + * + * @public + * @category Error + */ +export declare class MongoDecompressionError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated by the driver + * + * @public + * @category Error + */ +export declare class MongoDriverError extends MongoError { + constructor(message: string); + get name(): string; +} + +/** + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error, it uses the constructor with a string argument + */ +export declare class MongoError extends Error { + /* Excluded from this release type: [kErrorLabels] */ + /** + * This is a number in MongoServerError and a string in MongoDriverError + * @privateRemarks + * Define the type override on the subclasses when we can use the override keyword + */ + code?: number | string; + topologyVersion?: TopologyVersion; + constructor(message: string | Error); + get name(): string; + /** Legacy name for server error responses */ + get errmsg(): string; + /** + * Checks the error to see if it has an error label + * + * @param label - The error label to check for + * @returns returns true if the error has the provided error label + */ + hasErrorLabel(label: string): boolean; + addErrorLabel(label: string): void; + get errorLabels(): string[]; +} + +/** + * An error generated when the user attempts to operate + * on a session that has expired or has been closed. + * + * @public + * @category Error + */ +export declare class MongoExpiredSessionError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** + * An error generated when a malformed or invalid chunk is + * encountered when reading from a GridFSStream. + * + * @public + * @category Error + */ +export declare class MongoGridFSChunkError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** An error generated when a GridFSStream operation fails to execute. + * + * @public + * @category Error + */ +export declare class MongoGridFSStreamError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when the user supplies malformed or unexpected arguments + * or when a required argument or field is not provided. + * + * + * @public + * @category Error + */ +export declare class MongoInvalidArgumentError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * A error generated when the user attempts to authenticate + * via Kerberos, but fails to connect to the Kerberos client. + * + * @public + * @category Error + */ +export declare class MongoKerberosError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when the user fails to provide authentication credentials before attempting + * to connect to a mongo server instance. + * + * + * @public + * @category Error + */ +export declare class MongoMissingCredentialsError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when a required module or dependency is not present in the local environment + * + * @public + * @category Error + */ +export declare class MongoMissingDependencyError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * An error indicating an issue with the network, including TCP errors and timeouts. + * @public + * @category Error + */ +export declare class MongoNetworkError extends MongoError { + /* Excluded from this release type: [kBeforeHandshake] */ + constructor(message: string | Error, options?: MongoNetworkErrorOptions); + get name(): string; +} + +/** @public */ +export declare interface MongoNetworkErrorOptions { + /** Indicates the timeout happened before a connection handshake completed */ + beforeHandshake: boolean; +} + +/** + * An error indicating a network timeout occurred + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error with an instanceof check + */ +export declare class MongoNetworkTimeoutError extends MongoNetworkError { + constructor(message: string, options?: MongoNetworkErrorOptions); + get name(): string; +} + +/** + * An error thrown when the user attempts to operate on a database or collection through a MongoClient + * that has not yet successfully called the "connect" method + * + * @public + * @category Error + */ +export declare class MongoNotConnectedError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * Mongo Client Options + * @public + */ +export declare interface MongoOptions extends Required>, SupportedNodeConnectionOptions { + hosts: HostAddress[]; + srvHost?: string; + credentials?: MongoCredentials; + readPreference: ReadPreference; + readConcern: ReadConcern; + loadBalanced: boolean; + serverApi: ServerApi; + compressors: CompressorName[]; + writeConcern: WriteConcern; + dbName: string; + metadata: ClientMetadata; + autoEncrypter?: AutoEncrypter; + /* Excluded from this release type: connectionType */ + /* Excluded from this release type: encrypter */ + /* Excluded from this release type: userSpecifiedAuthSource */ + /* Excluded from this release type: userSpecifiedReplicaSet */ + /** + * # NOTE ABOUT TLS Options + * + * If set TLS enabled, equivalent to setting the ssl option. + * + * ### Additional options: + * + * | nodejs option | MongoDB equivalent | type | + * |:---------------------|--------------------------------------------------------- |:---------------------------------------| + * | `ca` | `sslCA`, `tlsCAFile` | `string \| Buffer \| Buffer[]` | + * | `crl` | `sslCRL` | `string \| Buffer \| Buffer[]` | + * | `cert` | `sslCert`, `tlsCertificateFile`, `tlsCertificateKeyFile` | `string \| Buffer \| Buffer[]` | + * | `key` | `sslKey`, `tlsCertificateKeyFile` | `string \| Buffer \| KeyObject[]` | + * | `passphrase` | `sslPass`, `tlsCertificateKeyFilePassword` | `string` | + * | `rejectUnauthorized` | `sslValidate` | `boolean` | + * + */ + tls: boolean; + /** + * Turn these options into a reusable connection URI + */ + toURI(): string; +} + +/** + * An error used when attempting to parse a value (like a connection string) + * @public + * @category Error + */ +export declare class MongoParseError extends MongoDriverError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when the driver encounters unexpected input + * or reaches an unexpected/invalid internal state + * + * @privateRemarks + * Should **never** be directly instantiated. + * + * @public + * @category Error + */ +export declare class MongoRuntimeError extends MongoDriverError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when an attempt is made to operate + * on a closed/closing server. + * + * @public + * @category Error + */ +export declare class MongoServerClosedError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** + * An error coming from the mongo server + * + * @public + * @category Error + */ +export declare class MongoServerError extends MongoError { + codeName?: string; + writeConcernError?: Document; + errInfo?: Document; + ok?: number; + [key: string]: any; + constructor(message: ErrorDescription); + get name(): string; +} + +/** + * An error signifying a client-side server selection error + * @public + * @category Error + */ +export declare class MongoServerSelectionError extends MongoSystemError { + constructor(message: string, reason: TopologyDescription); + get name(): string; +} + +/** + * An error signifying a general system issue + * @public + * @category Error + */ +export declare class MongoSystemError extends MongoError { + /** An optional reason context, such as an error saved during flow of monitoring and selecting servers */ + reason?: TopologyDescription; + constructor(message: string, reason: TopologyDescription); + get name(): string; +} + +/** + * An error generated when an attempt is made to operate on a + * dropped, or otherwise unavailable, database. + * + * @public + * @category Error + */ +export declare class MongoTopologyClosedError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** + * An error generated when the user makes a mistake in the usage of transactions. + * (e.g. attempting to commit a transaction with a readPreference other than primary) + * + * @public + * @category Error + */ +export declare class MongoTransactionError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * An error thrown when the server reports a writeConcernError + * @public + * @category Error + */ +export declare class MongoWriteConcernError extends MongoServerError { + /** The result document (provided if ok: 1) */ + result?: Document; + errInfo?: Document; + constructor(message: ErrorDescription, result?: Document); + get name(): string; +} + +/* Excluded from this release type: Monitor */ + +/** @public */ +export declare type MonitorEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + resetServer(error?: Error): void; + resetConnectionPool(): void; + close(): void; +} & EventEmitterWithState; + +/** @public */ +export declare interface MonitorOptions extends Omit { + connectTimeoutMS: number; + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; +} + +/* Excluded from this release type: MonitorPrivate */ + +/* Excluded from this release type: Msg */ + +/** It avoids using fields with not acceptable types @public */ +export declare type NotAcceptedFields = { + readonly [key in KeysOfOtherType]?: never; +}; + +/** @public */ +export declare type NumericType = IntegerType | Decimal128 | Double; + +/** + * @public + * @deprecated Please use `ObjectId` + */ +export declare const ObjectID: typeof ObjectId; + +export { ObjectId } + +/** @public */ +export declare type OneOrMore = T | ReadonlyArray; + +/** @public */ +export declare type OnlyFieldsOfType = IsAny, AcceptedFields & NotAcceptedFields & Record>; + +/* Excluded from this release type: OperationDescription */ + +/** @public */ +export declare interface OperationOptions extends BSONSerializeOptions { + /** Specify ClientSession for this command */ + session?: ClientSession; + willRetryWrites?: boolean; + /** The preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest). */ + readPreference?: ReadPreferenceLike; + /* Excluded from this release type: bypassPinningCheck */ +} + +/* Excluded from this release type: OperationParent */ + +/** + * Represents a specific point in time on a server. Can be retrieved by using {@link Db#command} + * @public + * @remarks + * See {@link https://docs.mongodb.com/manual/reference/method/db.runCommand/#response| Run Command Response} + */ +export declare type OperationTime = Timestamp; + +/* Excluded from this release type: OpGetMoreOptions */ + +/* Excluded from this release type: OpQueryOptions */ + +/** + * Add an optional _id field to an object shaped type + * @public + * + * @privateRemarks + * `ObjectId extends TSchema['_id']` is a confusing ordering at first glance. Rather than ask + * `TSchema['_id'] extends ObjectId` which translated to "Is the _id property ObjectId?" + * we instead ask "Does ObjectId look like (have the same shape) as the _id?" + */ +export declare type OptionalId = ObjectId extends TSchema['_id'] ? EnhancedOmit & { + _id?: InferIdType; +} : WithId; + +/** @public */ +export declare class OrderedBulkOperation extends BulkOperationBase { + constructor(collection: Collection, options: BulkWriteOptions); + addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/** @public */ +export declare interface PipeOptions { + end?: boolean; +} + +/** @public */ +export declare interface PkFactory { + createPk(): any; +} + +/** @public */ +export declare const ProfilingLevel: Readonly<{ + readonly off: "off"; + readonly slowOnly: "slow_only"; + readonly all: "all"; +}>; + +/** @public */ +export declare type ProfilingLevel = typeof ProfilingLevel[keyof typeof ProfilingLevel]; + +/** @public */ +export declare type ProfilingLevelOptions = CommandOperationOptions; + +/** + * @public + * Projection is flexible to permit the wide array of aggregation operators + * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further + */ +export declare type Projection = Document; + +/** + * @public + * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further + */ +export declare type ProjectionOperators = Document; + +/** + * Global promise store allowing user-provided promises + * @public + */ +declare class Promise_2 { + /** Validates the passed in promise library */ + static validate(lib: unknown): lib is PromiseConstructor; + /** Sets the promise library */ + static set(lib: PromiseConstructor): void; + /** Get the stored promise library, or resolves passed in */ + static get(): PromiseConstructor; +} +export { Promise_2 as Promise } + +/** @public */ +export declare type PullAllOperator = ({ + readonly [key in KeysOfAType>]?: TSchema[key]; +} & NotAcceptedFields>) & { + readonly [key: string]: ReadonlyArray; +}; + +/** @public */ +export declare type PullOperator = ({ + readonly [key in KeysOfAType>]?: Partial> | FilterOperations>; +} & NotAcceptedFields>) & { + readonly [key: string]: FilterOperators | any; +}; + +/** @public */ +export declare type PushOperator = ({ + readonly [key in KeysOfAType>]?: Flatten | ArrayOperator>>; +} & NotAcceptedFields>) & { + readonly [key: string]: ArrayOperator | any; +}; + +/* Excluded from this release type: Query */ + +/* Excluded from this release type: QueryOptions */ + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @public + * + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html + */ +export declare class ReadConcern { + level: ReadConcernLevel | string; + /** Constructs a ReadConcern from the read concern level.*/ + constructor(level: ReadConcernLevel); + /** + * Construct a ReadConcern given an options object. + * + * @param options - The options object from which to extract the write concern. + */ + static fromOptions(options?: { + readConcern?: ReadConcernLike; + level?: ReadConcernLevel; + }): ReadConcern | undefined; + static get MAJORITY(): 'majority'; + static get AVAILABLE(): 'available'; + static get LINEARIZABLE(): 'linearizable'; + static get SNAPSHOT(): 'snapshot'; + toJSON(): Document; +} + +/** @public */ +export declare const ReadConcernLevel: Readonly<{ + readonly local: "local"; + readonly majority: "majority"; + readonly linearizable: "linearizable"; + readonly available: "available"; + readonly snapshot: "snapshot"; +}>; + +/** @public */ +export declare type ReadConcernLevel = typeof ReadConcernLevel[keyof typeof ReadConcernLevel]; + +/** @public */ +export declare type ReadConcernLike = ReadConcern | { + level: ReadConcernLevel; +} | ReadConcernLevel; + +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @public + * + * @see https://docs.mongodb.com/manual/core/read-preference/ + */ +export declare class ReadPreference { + mode: ReadPreferenceMode; + tags?: TagSet[]; + hedge?: HedgeOptions; + maxStalenessSeconds?: number; + minWireVersion?: number; + static PRIMARY: "primary"; + static PRIMARY_PREFERRED: "primaryPreferred"; + static SECONDARY: "secondary"; + static SECONDARY_PREFERRED: "secondaryPreferred"; + static NEAREST: "nearest"; + static primary: ReadPreference; + static primaryPreferred: ReadPreference; + static secondary: ReadPreference; + static secondaryPreferred: ReadPreference; + static nearest: ReadPreference; + /** + * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. + * @param options - Additional read preference options + */ + constructor(mode: ReadPreferenceMode, tags?: TagSet[], options?: ReadPreferenceOptions); + get preference(): ReadPreferenceMode; + static fromString(mode: string): ReadPreference; + /** + * Construct a ReadPreference given an options object. + * + * @param options - The options object from which to extract the read preference. + */ + static fromOptions(options?: ReadPreferenceFromOptions): ReadPreference | undefined; + /** + * Replaces options.readPreference with a ReadPreference instance + */ + static translate(options: ReadPreferenceLikeOptions): ReadPreferenceLikeOptions; + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + static isValid(mode: string): boolean; + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + isValid(mode?: string): boolean; + /** + * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire + * + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ + slaveOk(): boolean; + /** + * Check if the two ReadPreferences are equivalent + * + * @param readPreference - The read preference with which to check equality + */ + equals(readPreference: ReadPreference): boolean; + /** Return JSON representation */ + toJSON(): Document; +} + +/** @public */ +export declare interface ReadPreferenceFromOptions extends ReadPreferenceLikeOptions { + session?: ClientSession; + readPreferenceTags?: TagSet[]; + hedge?: HedgeOptions; +} + +/** @public */ +export declare type ReadPreferenceLike = ReadPreference | ReadPreferenceMode; + +/** @public */ +export declare interface ReadPreferenceLikeOptions extends ReadPreferenceOptions { + readPreference?: ReadPreferenceLike | { + mode?: ReadPreferenceMode; + preference?: ReadPreferenceMode; + tags?: TagSet[]; + maxStalenessSeconds?: number; + }; +} + +/** @public */ +export declare const ReadPreferenceMode: Readonly<{ + readonly primary: "primary"; + readonly primaryPreferred: "primaryPreferred"; + readonly secondary: "secondary"; + readonly secondaryPreferred: "secondaryPreferred"; + readonly nearest: "nearest"; +}>; + +/** @public */ +export declare type ReadPreferenceMode = typeof ReadPreferenceMode[keyof typeof ReadPreferenceMode]; + +/** @public */ +export declare interface ReadPreferenceOptions { + /** Max secondary read staleness in seconds, Minimum value is 90 seconds.*/ + maxStalenessSeconds?: number; + /** Server mode in which the same query is dispatched in parallel to multiple replica set members. */ + hedge?: HedgeOptions; +} + +/** @public */ +export declare type ReduceFunction = (key: TKey, values: TValue[]) => TValue; + +/** @public */ +export declare type RegExpOrString = T extends string ? BSONRegExp | RegExp | T : T; + +/** @public */ +export declare type RemoveUserOptions = CommandOperationOptions; + +/** @public */ +export declare interface RenameOptions extends CommandOperationOptions { + /** Drop the target name collection if it previously exists. */ + dropTarget?: boolean; + /** Unclear */ + new_collection?: boolean; +} + +/** @public */ +export declare interface ReplaceOneModel { + /** The filter to limit the replaced document. */ + filter: Filter; + /** The document with which to replace the matched document. */ + replacement: TSchema; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export declare interface ReplaceOptions extends CommandOperationOptions { + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; +} + +/** @public */ +export declare interface ResumeOptions { + startAtOperationTime?: Timestamp; + batchSize?: number; + maxAwaitTimeMS?: number; + collation?: CollationOptions; + readPreference?: ReadPreference; +} + +/** + * Represents the logical starting point for a new or resuming {@link https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token| Change Stream} on the server. + * @public + */ +export declare type ResumeToken = unknown; + +/** @public */ +export declare const ReturnDocument: Readonly<{ + readonly BEFORE: "before"; + readonly AFTER: "after"; +}>; + +/** @public */ +export declare type ReturnDocument = typeof ReturnDocument[keyof typeof ReturnDocument]; + +/** @public */ +export declare interface RoleSpecification { + /** + * A role grants privileges to perform sets of actions on defined resources. + * A given role applies to the database on which it is defined and can grant access down to a collection level of granularity. + */ + role: string; + /** The database this user's role should effect. */ + db: string; +} + +/** @public */ +export declare interface RootFilterOperators extends Document { + $and?: Filter[]; + $nor?: Filter[]; + $or?: Filter[]; + $text?: { + $search: string; + $language?: string; + $caseSensitive?: boolean; + $diacriticSensitive?: boolean; + }; + $where?: string | ((this: TSchema) => boolean); + $comment?: string | Document; +} + +/* Excluded from this release type: RTTPinger */ + +/* Excluded from this release type: RTTPingerOptions */ + +/** @public */ +export declare type RunCommandOptions = CommandOperationOptions; + +/** @public */ +export declare type SchemaMember = { + [P in keyof T]?: V; +} | { + [key: string]: V; +}; + +/** @public */ +export declare interface SelectServerOptions { + readPreference?: ReadPreferenceLike; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS?: number; + session?: ClientSession; +} + +/* Excluded from this release type: serialize */ + +/* Excluded from this release type: Server */ + +/** @public */ +export declare interface ServerApi { + version: ServerApiVersion; + strict?: boolean; + deprecationErrors?: boolean; +} + +/** @public */ +export declare const ServerApiVersion: Readonly<{ + readonly v1: "1"; +}>; + +/** @public */ +export declare type ServerApiVersion = typeof ServerApiVersion[keyof typeof ServerApiVersion]; + +/** @public */ +export declare class ServerCapabilities { + maxWireVersion: number; + minWireVersion: number; + constructor(ismaster: Document); + get hasAggregationCursor(): boolean; + get hasWriteCommands(): boolean; + get hasTextSearch(): boolean; + get hasAuthCommands(): boolean; + get hasListCollectionsCommand(): boolean; + get hasListIndexesCommand(): boolean; + get supportsSnapshotReads(): boolean; + get commandsTakeWriteConcern(): boolean; + get commandsTakeCollation(): boolean; +} + +/** + * Emitted when server is closed. + * @public + * @category Event + */ +export declare class ServerClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /* Excluded from this release type: __constructor */ +} + +/** + * The client's view of a single server, based on the most recent ismaster outcome. + * + * Internal type, not meant to be directly instantiated + * @public + */ +export declare class ServerDescription { + private _hostAddress; + address: string; + type: ServerType; + hosts: string[]; + passives: string[]; + arbiters: string[]; + tags: TagSet; + error?: MongoError; + topologyVersion?: TopologyVersion; + minWireVersion: number; + maxWireVersion: number; + roundTripTime: number; + lastUpdateTime: number; + lastWriteDate: number; + me?: string; + primary?: string; + setName?: string; + setVersion?: number; + electionId?: ObjectId; + logicalSessionTimeoutMinutes?: number; + $clusterTime?: ClusterTime; + /* Excluded from this release type: __constructor */ + get hostAddress(): HostAddress; + get allHosts(): string[]; + /** Is this server available for reads*/ + get isReadable(): boolean; + /** Is this server data bearing */ + get isDataBearing(): boolean; + /** Is this server available for writes */ + get isWritable(): boolean; + get host(): string; + get port(): number; + /** + * Determines if another `ServerDescription` is equal to this one per the rules defined + * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} + */ + equals(other: ServerDescription): boolean; +} + +/** + * Emitted when server description changes, but does NOT include changes to the RTT. + * @public + * @category Event + */ +export declare class ServerDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /** The previous server description */ + previousDescription: ServerDescription; + /** The new server description */ + newDescription: ServerDescription; + /* Excluded from this release type: __constructor */ +} + +/* Excluded from this release type: ServerDescriptionOptions */ + +/** @public */ +export declare type ServerEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + /* Excluded from this release type: connect */ + descriptionReceived(description: ServerDescription): void; + closed(): void; + ended(): void; +} & ConnectionPoolEvents & EventEmitterWithState; + +/** + * Emitted when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. + * @public + * @category Event + */ +export declare class ServerHeartbeatFailedEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command failure */ + failure: Error; + /* Excluded from this release type: __constructor */ +} + +/** + * Emitted when the server monitor’s ismaster command is started - immediately before + * the ismaster command is serialized into raw BSON and written to the socket. + * + * @public + * @category Event + */ +export declare class ServerHeartbeatStartedEvent { + /** The connection id for the command */ + connectionId: string; + /* Excluded from this release type: __constructor */ +} + +/** + * Emitted when the server monitor’s ismaster succeeds. + * @public + * @category Event + */ +export declare class ServerHeartbeatSucceededEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command reply */ + reply: Document; + /* Excluded from this release type: __constructor */ +} + +/** + * Emitted when server is initialized. + * @public + * @category Event + */ +export declare class ServerOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare type ServerOptions = Omit & MonitorOptions; + +/* Excluded from this release type: ServerPrivate */ + +/* Excluded from this release type: ServerSelectionCallback */ + +/* Excluded from this release type: ServerSelectionRequest */ + +/** @public */ +export declare type ServerSelector = (topologyDescription: TopologyDescription, servers: ServerDescription[]) => ServerDescription[]; + +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @public + */ +export declare class ServerSession { + id: ServerSessionId; + lastUse: number; + txnNumber: number; + isDirty: boolean; + /* Excluded from this release type: __constructor */ + /** + * Determines if the server session has timed out. + * + * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" + */ + hasTimedOut(sessionTimeoutMinutes: number): boolean; +} + +/** @public */ +export declare type ServerSessionId = { + id: Binary; +}; + +/* Excluded from this release type: ServerSessionPool */ + +/** + * An enumeration of server types we know about + * @public + */ +export declare const ServerType: Readonly<{ + readonly Standalone: "Standalone"; + readonly Mongos: "Mongos"; + readonly PossiblePrimary: "PossiblePrimary"; + readonly RSPrimary: "RSPrimary"; + readonly RSSecondary: "RSSecondary"; + readonly RSArbiter: "RSArbiter"; + readonly RSOther: "RSOther"; + readonly RSGhost: "RSGhost"; + readonly Unknown: "Unknown"; + readonly LoadBalancer: "LoadBalancer"; +}>; + +/** @public */ +export declare type ServerType = typeof ServerType[keyof typeof ServerType]; + +/** @public */ +export declare type SetFields = ({ + readonly [key in KeysOfAType | undefined>]?: OptionalId> | AddToSetOperators>>>; +} & NotAcceptedFields | undefined>) & { + readonly [key: string]: AddToSetOperators | any; +}; + +/** @public */ +export declare type SetProfilingLevelOptions = CommandOperationOptions; + +/** @public */ +export declare type Sort = string | Exclude | string[] | { + [key: string]: SortDirection; +} | Map | [string, SortDirection][] | [string, SortDirection]; + +/** @public */ +export declare type SortDirection = 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending' | { + $meta: string; +}; + +/* Excluded from this release type: SortDirectionForCmd */ + +/* Excluded from this release type: SortForCmd */ + +/* Excluded from this release type: SrvPoller */ + +/* Excluded from this release type: SrvPollerEvents */ + +/* Excluded from this release type: SrvPollerOptions */ + +/* Excluded from this release type: SrvPollingEvent */ + +/** @public */ +export declare type Stream = Socket | TLSSocket; + +/** @public */ +export declare class StreamDescription { + address: string; + type: string; + minWireVersion?: number; + maxWireVersion?: number; + maxBsonObjectSize: number; + maxMessageSizeBytes: number; + maxWriteBatchSize: number; + compressors: CompressorName[]; + compressor?: CompressorName; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; + __nodejs_mock_server__?: boolean; + zlibCompressionLevel?: number; + constructor(address: string, options?: StreamDescriptionOptions); + receiveResponse(response: Document): void; +} + +/** @public */ +export declare interface StreamDescriptionOptions { + compressors?: CompressorName[]; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; +} + +/** @public */ +export declare type SupportedNodeConnectionOptions = SupportedTLSConnectionOptions & SupportedTLSSocketOptions & SupportedSocketOptions; + +/** @public */ +export declare type SupportedSocketOptions = Pick; + +/** @public */ +export declare type SupportedTLSConnectionOptions = Pick>; + +/** @public */ +export declare type SupportedTLSSocketOptions = Pick>; + +/** @public */ +export declare type TagSet = { + [key: string]: string; +}; + +/* Excluded from this release type: TimerQueue */ + +/** @public + * Configuration options for timeseries collections + * @see https://docs.mongodb.com/manual/core/timeseries-collections/ + */ +export declare interface TimeSeriesCollectionOptions extends Document { + timeField: string; + metaField?: string; + granularity?: string; +} + +export { Timestamp } + +/* Excluded from this release type: Topology */ + +/** + * Emitted when topology is closed. + * @public + * @category Event + */ +export declare class TopologyClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /* Excluded from this release type: __constructor */ +} + +/** + * Representation of a deployment of servers + * @public + */ +export declare class TopologyDescription { + type: TopologyType; + setName?: string; + maxSetVersion?: number; + maxElectionId?: ObjectId; + servers: Map; + stale: boolean; + compatible: boolean; + compatibilityError?: string; + logicalSessionTimeoutMinutes?: number; + heartbeatFrequencyMS: number; + localThresholdMS: number; + commonWireVersion?: number; + /** + * Create a TopologyDescription + */ + constructor(topologyType: TopologyType, serverDescriptions?: Map, setName?: string, maxSetVersion?: number, maxElectionId?: ObjectId, commonWireVersion?: number, options?: TopologyDescriptionOptions); + /* Excluded from this release type: updateFromSrvPollingEvent */ + /* Excluded from this release type: update */ + get error(): MongoError | undefined; + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers(): boolean; + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers(): boolean; + /* Excluded from this release type: hasServer */ +} + +/** + * Emitted when topology description changes. + * @public + * @category Event + */ +export declare class TopologyDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The old topology description */ + previousDescription: TopologyDescription; + /** The new topology description */ + newDescription: TopologyDescription; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare interface TopologyDescriptionOptions { + heartbeatFrequencyMS?: number; + localThresholdMS?: number; +} + +/** @public */ +export declare type TopologyEvents = { + /* Excluded from this release type: connect */ + serverOpening(event: ServerOpeningEvent): void; + serverClosed(event: ServerClosedEvent): void; + serverDescriptionChanged(event: ServerDescriptionChangedEvent): void; + topologyClosed(event: TopologyClosedEvent): void; + topologyOpening(event: TopologyOpeningEvent): void; + topologyDescriptionChanged(event: TopologyDescriptionChangedEvent): void; + error(error: Error): void; + /* Excluded from this release type: open */ + close(): void; + timeout(): void; +} & Omit & ConnectionPoolEvents & ConnectionEvents & EventEmitterWithState; + +/** + * Emitted when topology is initialized. + * @public + * @category Event + */ +export declare class TopologyOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare interface TopologyOptions extends BSONSerializeOptions, ServerOptions { + hosts: HostAddress[]; + retryWrites: boolean; + retryReads: boolean; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS: number; + /** The name of the replica set to connect to */ + replicaSet?: string; + srvHost?: string; + /* Excluded from this release type: srvPoller */ + /** Indicates that a client should directly connect to a node without attempting to discover its topology type */ + directConnection: boolean; + loadBalanced: boolean; + metadata: ClientMetadata; + /** MongoDB server API version */ + serverApi?: ServerApi; +} + +/* Excluded from this release type: TopologyPrivate */ + +/** + * An enumeration of topology types we know about + * @public + */ +export declare const TopologyType: Readonly<{ + readonly Single: "Single"; + readonly ReplicaSetNoPrimary: "ReplicaSetNoPrimary"; + readonly ReplicaSetWithPrimary: "ReplicaSetWithPrimary"; + readonly Sharded: "Sharded"; + readonly Unknown: "Unknown"; + readonly LoadBalanced: "LoadBalanced"; +}>; + +/** @public */ +export declare type TopologyType = typeof TopologyType[keyof typeof TopologyType]; + +/** @public */ +export declare interface TopologyVersion { + processId: ObjectId; + counter: Long; +} + +/** + * @public + * A class maintaining state related to a server transaction. Internal Only + */ +export declare class Transaction { + /* Excluded from this release type: state */ + options: TransactionOptions; + /* Excluded from this release type: _pinnedServer */ + /* Excluded from this release type: _recoveryToken */ + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: server */ + get recoveryToken(): Document | undefined; + get isPinned(): boolean; + /** @returns Whether the transaction has started */ + get isStarting(): boolean; + /** + * @returns Whether this session is presently in a transaction + */ + get isActive(): boolean; + get isCommitted(): boolean; + /* Excluded from this release type: transition */ + /* Excluded from this release type: pinServer */ + /* Excluded from this release type: unpinServer */ +} + +/** + * Configuration options for a transaction. + * @public + */ +export declare interface TransactionOptions extends CommandOperationOptions { + /** A default read concern for commands in this transaction */ + readConcern?: ReadConcern; + /** A default writeConcern for commands in this transaction */ + writeConcern?: WriteConcern; + /** A default read preference for commands in this transaction */ + readPreference?: ReadPreference; + maxCommitTimeMS?: number; +} + +/* Excluded from this release type: TxnState */ + +/** + * Typescript type safe event emitter + * @public + */ +export declare interface TypedEventEmitter extends EventEmitter { + addListener(event: EventKey, listener: Events[EventKey]): this; + addListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + addListener(event: string | symbol, listener: GenericListener): this; + on(event: EventKey, listener: Events[EventKey]): this; + on(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + on(event: string | symbol, listener: GenericListener): this; + once(event: EventKey, listener: Events[EventKey]): this; + once(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + once(event: string | symbol, listener: GenericListener): this; + removeListener(event: EventKey, listener: Events[EventKey]): this; + removeListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + removeListener(event: string | symbol, listener: GenericListener): this; + off(event: EventKey, listener: Events[EventKey]): this; + off(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + off(event: string | symbol, listener: GenericListener): this; + removeAllListeners(event?: EventKey | CommonEvents | symbol | string): this; + listeners(event: EventKey | CommonEvents | symbol | string): Events[EventKey][]; + rawListeners(event: EventKey | CommonEvents | symbol | string): Events[EventKey][]; + emit(event: EventKey | symbol, ...args: Parameters): boolean; + listenerCount(type: EventKey | CommonEvents | symbol | string): number; + prependListener(event: EventKey, listener: Events[EventKey]): this; + prependListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + prependListener(event: string | symbol, listener: GenericListener): this; + prependOnceListener(event: EventKey, listener: Events[EventKey]): this; + prependOnceListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + prependOnceListener(event: string | symbol, listener: GenericListener): this; + eventNames(): string[]; + getMaxListeners(): number; + setMaxListeners(n: number): this; +} + +/** + * Typescript type safe event emitter + * @public + */ +export declare class TypedEventEmitter extends EventEmitter { +} + +/** @public */ +export declare class UnorderedBulkOperation extends BulkOperationBase { + constructor(collection: Collection, options: BulkWriteOptions); + handleWriteError(callback: Callback, writeResult: BulkWriteResult): boolean | undefined; + addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/** @public */ +export declare interface UpdateDescription { + /** + * A document containing key:value pairs of names of the fields that were + * changed, and the new value for those fields. + */ + updatedFields: Partial; + /** + * An array of field names that were removed from the document. + */ + removedFields: string[]; +} + +/** @public */ +export declare type UpdateFilter = { + $currentDate?: OnlyFieldsOfType; + $inc?: OnlyFieldsOfType; + $min?: MatchKeysAndValues; + $max?: MatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: MatchKeysAndValues; + $setOnInsert?: MatchKeysAndValues; + $unset?: OnlyFieldsOfType; + $addToSet?: SetFields; + $pop?: OnlyFieldsOfType, 1 | -1>; + $pull?: PullOperator; + $push?: PushOperator; + $pullAll?: PullAllOperator; + $bit?: OnlyFieldsOfType; +} & Document; + +/** @public */ +export declare interface UpdateManyModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** A document or pipeline containing update operators. */ + update: UpdateFilter | UpdateFilter[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export declare interface UpdateOneModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** A document or pipeline containing update operators. */ + update: UpdateFilter | UpdateFilter[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export declare interface UpdateOptions extends CommandOperationOptions { + /** A set of filters specifying to which array elements an update should apply */ + arrayFilters?: Document[]; + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export declare interface UpdateResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of documents that matched the filter */ + matchedCount: number; + /** The number of documents that were modified */ + modifiedCount: number; + /** The number of documents that were upserted */ + upsertedCount: number; + /** The identifier of the inserted document if an upsert took place */ + upsertedId: ObjectId; +} + +/** @public */ +export declare interface UpdateStatement { + /** The query that matches documents to update. */ + q: Document; + /** The modifications to apply. */ + u: Document | Document[]; + /** If true, perform an insert if no documents match the query. */ + upsert?: boolean; + /** If true, updates all documents that meet the query criteria. */ + multi?: boolean; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** An array of filter documents that determines which array elements to modify for an update operation on an array field. */ + arrayFilters?: Document[]; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; +} + +/** @public */ +export declare interface ValidateCollectionOptions extends CommandOperationOptions { + /** Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) */ + background?: boolean; +} + +/** @public */ +export declare type W = number | 'majority'; + +/* Excluded from this release type: WaitQueueMember */ + +/** @public */ +export declare interface WiredTigerData extends Document { + LSM: { + 'bloom filter false positives': number; + 'bloom filter hits': number; + 'bloom filter misses': number; + 'bloom filter pages evicted from cache': number; + 'bloom filter pages read into cache': number; + 'bloom filters in the LSM tree': number; + 'chunks in the LSM tree': number; + 'highest merge generation in the LSM tree': number; + 'queries that could have benefited from a Bloom filter that did not exist': number; + 'sleep for LSM checkpoint throttle': number; + 'sleep for LSM merge throttle': number; + 'total size of bloom filters': number; + } & Document; + 'block-manager': { + 'allocations requiring file extension': number; + 'blocks allocated': number; + 'blocks freed': number; + 'checkpoint size': number; + 'file allocation unit size': number; + 'file bytes available for reuse': number; + 'file magic number': number; + 'file major version number': number; + 'file size in bytes': number; + 'minor version number': number; + }; + btree: { + 'btree checkpoint generation': number; + 'column-store fixed-size leaf pages': number; + 'column-store internal pages': number; + 'column-store variable-size RLE encoded values': number; + 'column-store variable-size deleted values': number; + 'column-store variable-size leaf pages': number; + 'fixed-record size': number; + 'maximum internal page key size': number; + 'maximum internal page size': number; + 'maximum leaf page key size': number; + 'maximum leaf page size': number; + 'maximum leaf page value size': number; + 'maximum tree depth': number; + 'number of key/value pairs': number; + 'overflow pages': number; + 'pages rewritten by compaction': number; + 'row-store internal pages': number; + 'row-store leaf pages': number; + } & Document; + cache: { + 'bytes currently in the cache': number; + 'bytes read into cache': number; + 'bytes written from cache': number; + 'checkpoint blocked page eviction': number; + 'data source pages selected for eviction unable to be evicted': number; + 'hazard pointer blocked page eviction': number; + 'in-memory page passed criteria to be split': number; + 'in-memory page splits': number; + 'internal pages evicted': number; + 'internal pages split during eviction': number; + 'leaf pages split during eviction': number; + 'modified pages evicted': number; + 'overflow pages read into cache': number; + 'overflow values cached in memory': number; + 'page split during eviction deepened the tree': number; + 'page written requiring lookaside records': number; + 'pages read into cache': number; + 'pages read into cache requiring lookaside entries': number; + 'pages requested from the cache': number; + 'pages written from cache': number; + 'pages written requiring in-memory restoration': number; + 'tracked dirty bytes in the cache': number; + 'unmodified pages evicted': number; + } & Document; + cache_walk: { + 'Average difference between current eviction generation when the page was last considered': number; + 'Average on-disk page image size seen': number; + 'Clean pages currently in cache': number; + 'Current eviction generation': number; + 'Dirty pages currently in cache': number; + 'Entries in the root page': number; + 'Internal pages currently in cache': number; + 'Leaf pages currently in cache': number; + 'Maximum difference between current eviction generation when the page was last considered': number; + 'Maximum page size seen': number; + 'Minimum on-disk page image size seen': number; + 'On-disk page image sizes smaller than a single allocation unit': number; + 'Pages created in memory and never written': number; + 'Pages currently queued for eviction': number; + 'Pages that could not be queued for eviction': number; + 'Refs skipped during cache traversal': number; + 'Size of the root page': number; + 'Total number of pages currently in cache': number; + } & Document; + compression: { + 'compressed pages read': number; + 'compressed pages written': number; + 'page written failed to compress': number; + 'page written was too small to compress': number; + 'raw compression call failed, additional data available': number; + 'raw compression call failed, no additional data available': number; + 'raw compression call succeeded': number; + } & Document; + cursor: { + 'bulk-loaded cursor-insert calls': number; + 'create calls': number; + 'cursor-insert key and value bytes inserted': number; + 'cursor-remove key bytes removed': number; + 'cursor-update value bytes updated': number; + 'insert calls': number; + 'next calls': number; + 'prev calls': number; + 'remove calls': number; + 'reset calls': number; + 'restarted searches': number; + 'search calls': number; + 'search near calls': number; + 'truncate calls': number; + 'update calls': number; + }; + reconciliation: { + 'dictionary matches': number; + 'fast-path pages deleted': number; + 'internal page key bytes discarded using suffix compression': number; + 'internal page multi-block writes': number; + 'internal-page overflow keys': number; + 'leaf page key bytes discarded using prefix compression': number; + 'leaf page multi-block writes': number; + 'leaf-page overflow keys': number; + 'maximum blocks required for a page': number; + 'overflow values written': number; + 'page checksum matches': number; + 'page reconciliation calls': number; + 'page reconciliation calls for eviction': number; + 'pages deleted': number; + } & Document; +} + +/* Excluded from this release type: WithConnectionCallback */ + +/** Add an _id field to an object shaped type @public */ +export declare type WithId = EnhancedOmit & { + _id: InferIdType; +}; + +/** Remove the _id field from an object shaped type @public */ +export declare type WithoutId = Omit; + +/** @public */ +export declare type WithSessionCallback = (session: ClientSession) => Promise | void; + +/** @public */ +export declare type WithTransactionCallback = (session: ClientSession) => Promise; + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @public + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ +export declare class WriteConcern { + /** request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. */ + w?: W; + /** specify a time limit to prevent write operations from blocking indefinitely */ + wtimeout?: number; + /** request acknowledgment that the write operation has been written to the on-disk journal */ + j?: boolean; + /** equivalent to the j option */ + fsync?: boolean | 1; + /** + * Constructs a WriteConcern from the write concern properties. + * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. + * @param wtimeout - specify a time limit to prevent write operations from blocking indefinitely + * @param j - request acknowledgment that the write operation has been written to the on-disk journal + * @param fsync - equivalent to the j option + */ + constructor(w?: W, wtimeout?: number, j?: boolean, fsync?: boolean | 1); + /** Construct a WriteConcern given an options object. */ + static fromOptions(options?: WriteConcernOptions | WriteConcern | W, inherit?: WriteConcernOptions | WriteConcern): WriteConcern | undefined; +} + +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +export declare class WriteConcernError { + /* Excluded from this release type: [kServerError] */ + constructor(error: WriteConcernErrorData); + /** Write concern error code. */ + get code(): number | undefined; + /** Write concern error message. */ + get errmsg(): string | undefined; + /** Write concern error info. */ + get errInfo(): Document | undefined; + /** @deprecated The `err` prop that contained a MongoServerError has been deprecated. */ + get err(): WriteConcernErrorData; + toJSON(): WriteConcernErrorData; + toString(): string; +} + +/** @public */ +export declare interface WriteConcernErrorData { + code: number; + errmsg: string; + errInfo?: Document; +} + +/** @public */ +export declare interface WriteConcernOptions { + /** Write Concern as an object */ + writeConcern?: WriteConcern | WriteConcernSettings; +} + +/** @public */ +export declare interface WriteConcernSettings { + /** The write concern */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + /** The journal write concern */ + j?: boolean; + /** The write concern timeout */ + wtimeout?: number; + /** The file sync write concern */ + fsync?: boolean | 1; +} + +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +export declare class WriteError { + err: BulkWriteOperationError; + constructor(err: BulkWriteOperationError); + /** WriteError code. */ + get code(): number; + /** WriteError original bulk operation index. */ + get index(): number; + /** WriteError message. */ + get errmsg(): string | undefined; + /** WriteError details. */ + get errInfo(): Document | undefined; + /** Returns the underlying operation that caused the error */ + getOperation(): Document; + toJSON(): { + code: number; + index: number; + errmsg?: string; + op: Document; + }; + toString(): string; +} + +/* Excluded from this release type: WriteProtocolMessageType */ + +export { } diff --git a/node_modules/mongodb/mongodb.ts34.d.ts b/node_modules/mongodb/mongodb.ts34.d.ts new file mode 100644 index 0000000..85d83c2 --- /dev/null +++ b/node_modules/mongodb/mongodb.ts34.d.ts @@ -0,0 +1,5504 @@ +/// +import { Binary } from 'bson'; +import { BSONRegExp } from 'bson'; +import { BSONSymbol } from 'bson'; +import { Code } from 'bson'; +import { ConnectionOptions as ConnectionOptions_2 } from 'tls'; +import { DBRef } from 'bson'; +import { Decimal128 } from 'bson'; +import Denque = require('denque'); +import { deserialize as deserialize_2 } from 'bson'; +import { DeserializeOptions } from 'bson'; +import * as dns from 'dns'; +import { Document } from 'bson'; +import { Double } from 'bson'; +import { Duplex } from 'stream'; +import { DuplexOptions } from 'stream'; +import { EventEmitter } from 'events'; +import { Int32 } from 'bson'; +import { Long } from 'bson'; +import { Map as Map_2 } from 'bson'; +import { MaxKey } from 'bson'; +import { MinKey } from 'bson'; +import { ObjectId } from 'bson'; +import { Readable } from 'stream'; +import { serialize as serialize_2 } from 'bson'; +import { SerializeOptions } from 'bson'; +import { Socket } from 'net'; +import { TcpNetConnectOpts } from 'net'; +import { Timestamp } from 'bson'; +import { TLSSocket } from 'tls'; +import { TLSSocketOptions } from 'tls'; +import { Writable } from 'stream'; +/** @public */ +export declare abstract class AbstractCursor extends TypedEventEmitter { + /* Excluded from this release type: [kId] */ + /* Excluded from this release type: [kSession] */ + /* Excluded from this release type: [kServer] */ + /* Excluded from this release type: [kNamespace] */ + /* Excluded from this release type: [kDocuments] */ + /* Excluded from this release type: [kTopology] */ + /* Excluded from this release type: [kTransform] */ + /* Excluded from this release type: [kInitialized] */ + /* Excluded from this release type: [kClosed] */ + /* Excluded from this release type: [kKilled] */ + /* Excluded from this release type: [kOptions] */ + /** @event */ + static readonly CLOSE: "close"; + /*Excluded from this release type: __constructor */ + readonly id: Long | undefined; + /*Excluded from this release type: topology + Excluded from this release type: server */ + readonly namespace: MongoDBNamespace; + readonly readPreference: ReadPreference; + readonly readConcern: ReadConcern | undefined; + /*Excluded from this release type: session + Excluded from this release type: session + Excluded from this release type: cursorOptions */ + readonly closed: boolean; + readonly killed: boolean; + readonly loadBalanced: boolean; + /** Returns current buffered documents length */ + bufferedCount(): number; + /** Returns current buffered documents */ + readBufferedDocuments(number?: number): TSchema[]; + [Symbol.asyncIterator](): AsyncIterator; + stream(options?: CursorStreamOptions): Readable; + hasNext(): Promise; + hasNext(callback: Callback): void; + /** Get the next available document from the cursor, returns null if no more documents are available. */ + next(): Promise; + next(callback: Callback): void; + next(callback?: Callback): Promise | void; + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + tryNext(callback: Callback): void; + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * @param iterator - The iteration callback. + * @param callback - The end callback. + */ + forEach(iterator: (doc: TSchema) => boolean | void): Promise; + forEach(iterator: (doc: TSchema) => boolean | void, callback: Callback): void; + close(): void; + close(callback: Callback): void; + /** + * @deprecated options argument is deprecated + */ + close(options: CursorCloseOptions): Promise; + /** + * @deprecated options argument is deprecated + */ + close(options: CursorCloseOptions, callback: Callback): void; + /** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * + * @param callback - The result callback. + */ + toArray(): Promise; + toArray(callback: Callback): void; + /** + * Add a cursor flag to the cursor + * + * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. + * @param value - The flag boolean value. + */ + addCursorFlag(flag: CursorFlag, value: boolean): this; + /** + * Map all documents using the provided function + * If there is a transform set on the cursor, that will be called first and the result passed to + * this function's transform. + * + * @remarks + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling map, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor = coll.find(); + * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); + * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] + * ``` + * @param transform - The mapping transformation method. + */ + map(transform: (doc: TSchema) => T): AbstractCursor; + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadPreference(readPreference: ReadPreferenceLike): this; + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadConcern(readConcern: ReadConcernLike): this; + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this; + /** + * Set the batch size for the cursor. + * + * @param value - The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + */ + batchSize(value: number): this; + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind(): void; + /** + * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance + */ + abstract clone(): AbstractCursor; +} +/** @public */ +export declare type AbstractCursorEvents = { + [AbstractCursor.CLOSE](): void; +}; +/** @public */ +export declare interface AbstractCursorOptions extends BSONSerializeOptions { + session?: ClientSession; + readPreference?: ReadPreferenceLike; + readConcern?: ReadConcernLike; + batchSize?: number; + maxTimeMS?: number; + comment?: Document | string; + tailable?: boolean; + awaitData?: boolean; + noCursorTimeout?: boolean; +} +/* Excluded from this release type: AbstractOperation */ +/** @public */ +export declare type AcceptedFields = { + readonly [key in KeysOfAType]?: AssignableType; +}; +/** @public */ +export declare type AddToSetOperators = { + $each?: Array>; +}; +/** @public */ +export declare interface AddUserOptions extends CommandOperationOptions { + /** @deprecated Please use db.command('createUser', ...) instead for this option */ + digestPassword?: null; + /** Roles associated with the created user */ + roles?: string | string[] | RoleSpecification | RoleSpecification[]; + /** Custom data associated with the user (only Mongodb 2.6 or higher) */ + customData?: Document; +} +/** + * The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Use the admin database for the operation + * const adminDb = client.db(dbName).admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * expect(err).to.not.exist; + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + * ``` + */ +export declare class Admin { + /* Excluded from this release type: s */ + /* Excluded from this release type: __constructor */ + /** + * Execute a command + * + * @param command - The command to execute + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + command(command: Document): Promise; + command(command: Document, callback: Callback): void; + command(command: Document, options: RunCommandOptions): Promise; + command(command: Document, options: RunCommandOptions, callback: Callback): void; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + buildInfo(): Promise; + buildInfo(callback: Callback): void; + buildInfo(options: CommandOperationOptions): Promise; + buildInfo(options: CommandOperationOptions, callback: Callback): void; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + serverInfo(): Promise; + serverInfo(callback: Callback): void; + serverInfo(options: CommandOperationOptions): Promise; + serverInfo(options: CommandOperationOptions, callback: Callback): void; + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + serverStatus(): Promise; + serverStatus(callback: Callback): void; + serverStatus(options: CommandOperationOptions): Promise; + serverStatus(options: CommandOperationOptions, callback: Callback): void; + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + ping(): Promise; + ping(callback: Callback): void; + ping(options: CommandOperationOptions): Promise; + ping(options: CommandOperationOptions, callback: Callback): void; + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param password - An optional password for the new user + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + addUser(username: string): Promise; + addUser(username: string, callback: Callback): void; + addUser(username: string, password: string): Promise; + addUser(username: string, password: string, callback: Callback): void; + addUser(username: string, options: AddUserOptions): Promise; + addUser(username: string, options: AddUserOptions, callback: Callback): void; + addUser(username: string, password: string, options: AddUserOptions): Promise; + addUser(username: string, password: string, options: AddUserOptions, callback: Callback): void; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + removeUser(username: string): Promise; + removeUser(username: string, callback: Callback): void; + removeUser(username: string, options: RemoveUserOptions): Promise; + removeUser(username: string, options: RemoveUserOptions, callback: Callback): void; + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + validateCollection(collectionName: string): Promise; + validateCollection(collectionName: string, callback: Callback): void; + validateCollection(collectionName: string, options: ValidateCollectionOptions): Promise; + validateCollection(collectionName: string, options: ValidateCollectionOptions, callback: Callback): void; + /** + * List the available databases + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + listDatabases(): Promise; + listDatabases(callback: Callback): void; + listDatabases(options: ListDatabasesOptions): Promise; + listDatabases(options: ListDatabasesOptions, callback: Callback): void; + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + replSetGetStatus(): Promise; + replSetGetStatus(callback: Callback): void; + replSetGetStatus(options: CommandOperationOptions): Promise; + replSetGetStatus(options: CommandOperationOptions, callback: Callback): void; +} +/* Excluded from this release type: AdminPrivate */ +/* Excluded from this release type: AggregateOperation */ +/** @public */ +export declare interface AggregateOptions extends CommandOperationOptions { + /** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */ + allowDiskUse?: boolean; + /** The number of documents to return per batch. See [aggregation documentation](https://docs.mongodb.com/manual/reference/command/aggregate). */ + batchSize?: number; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */ + cursor?: Document; + /** specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */ + maxAwaitTimeMS?: number; + /** Specify collation. */ + collation?: CollationOptions; + /** Add an index selection hint to an aggregation command */ + hint?: Hint; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + out?: string; +} +/** + * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * @public + */ +export declare class AggregationCursor extends AbstractCursor { + /*Excluded from this release type: [kPipeline] + Excluded from this release type: [kOptions] + Excluded from this release type: __constructor */ + readonly pipeline: Document[]; + clone(): AggregationCursor; + map(transform: (doc: TSchema) => T): AggregationCursor; + /* Excluded from this release type: _initialize */ + /** Execute the explain for the cursor */ + explain(): Promise; + explain(callback: Callback): void; + explain(verbosity: ExplainVerbosityLike): Promise; + /** Add a group stage to the aggregation pipeline */ + group($group: Document): AggregationCursor; + /** Add a limit stage to the aggregation pipeline */ + limit($limit: number): this; + /** Add a match stage to the aggregation pipeline */ + match($match: Document): this; + /** Add an out stage to the aggregation pipeline */ + out($out: { + db: string; + coll: string; + } | string): this; + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.aggregate().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project($project: Document): AggregationCursor; + /** Add a lookup stage to the aggregation pipeline */ + lookup($lookup: Document): this; + /** Add a redact stage to the aggregation pipeline */ + redact($redact: Document): this; + /** Add a skip stage to the aggregation pipeline */ + skip($skip: number): this; + /** Add a sort stage to the aggregation pipeline */ + sort($sort: Sort): this; + /** Add a unwind stage to the aggregation pipeline */ + unwind($unwind: Document | string): this; + /** @deprecated Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear: Document): this; +} +/** @public */ +export declare interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions { +} +/** + * It is possible to search using alternative types in mongodb e.g. + * string types can be searched using a regex in mongo + * array types can be searched using their element type + * @public + */ +export declare type AlternativeType = T extends ReadonlyArray ? T | RegExpOrString : RegExpOrString; +/** @public */ +export declare type AnyBulkWriteOperation = { + insertOne: InsertOneModel; +} | { + replaceOne: ReplaceOneModel; +} | { + updateOne: UpdateOneModel; +} | { + updateMany: UpdateManyModel; +} | { + deleteOne: DeleteOneModel; +} | { + deleteMany: DeleteManyModel; +}; +/** @public */ +export declare type AnyError = MongoError | Error; +/** @public */ +export declare type ArrayOperator = { + $each?: Array>; + $slice?: number; + $position?: number; + $sort?: Sort; +}; +/** @public */ +export declare interface Auth { + /** The username for auth */ + username?: string; + /** The password for auth */ + password?: string; +} +/** @public */ +export declare const AuthMechanism: Readonly<{ + readonly MONGODB_AWS: "MONGODB-AWS"; + readonly MONGODB_CR: "MONGODB-CR"; + readonly MONGODB_DEFAULT: "DEFAULT"; + readonly MONGODB_GSSAPI: "GSSAPI"; + readonly MONGODB_PLAIN: "PLAIN"; + readonly MONGODB_SCRAM_SHA1: "SCRAM-SHA-1"; + readonly MONGODB_SCRAM_SHA256: "SCRAM-SHA-256"; + readonly MONGODB_X509: "MONGODB-X509"; +}>; +/** @public */ +export declare type AuthMechanism = typeof AuthMechanism[keyof typeof AuthMechanism]; +/** @public */ +export declare interface AuthMechanismProperties extends Document { + SERVICE_NAME?: string; + SERVICE_REALM?: string; + CANONICALIZE_HOST_NAME?: boolean; + AWS_SESSION_TOKEN?: string; +} +/** @public */ +export declare interface AutoEncrypter { + new (client: MongoClient, options: AutoEncryptionOptions): AutoEncrypter; + init(cb: Callback): void; + teardown(force: boolean, callback: Callback): void; + encrypt(ns: string, cmd: Document, options: any, callback: Callback): void; + decrypt(cmd: Document, options: any, callback: Callback): void; +} +/** @public */ +export declare const AutoEncryptionLoggerLevel: Readonly<{ + readonly FatalError: 0; + readonly Error: 1; + readonly Warning: 2; + readonly Info: 3; + readonly Trace: 4; +}>; +/** @public */ +export declare type AutoEncryptionLoggerLevel = typeof AutoEncryptionLoggerLevel[keyof typeof AutoEncryptionLoggerLevel]; +/** @public */ +export declare interface AutoEncryptionOptions { + /* Excluded from this release type: bson */ + /* Excluded from this release type: metadataClient */ + /** A `MongoClient` used to fetch keys from a key vault */ + keyVaultClient?: MongoClient; + /** The namespace where keys are stored in the key vault */ + keyVaultNamespace?: string; + /** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */ + kmsProviders?: { + /** Configuration options for using 'aws' as your KMS provider */ + aws?: { + /** The access key used for the AWS KMS provider */ + accessKeyId: string; + /** The secret access key used for the AWS KMS provider */ + secretAccessKey: string; + /** + * An optional AWS session token that will be used as the + * X-Amz-Security-Token header for AWS requests. + */ + sessionToken?: string; + }; + /** Configuration options for using 'local' as your KMS provider */ + local?: { + /** + * The master key used to encrypt/decrypt data keys. + * A 96-byte long Buffer or base64 encoded string. + */ + key: Buffer | string; + }; + /** Configuration options for using 'azure' as your KMS provider */ + azure?: { + /** The tenant ID identifies the organization for the account */ + tenantId: string; + /** The client ID to authenticate a registered application */ + clientId: string; + /** The client secret to authenticate a registered application */ + clientSecret: string; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * This is optional, and only needed if customer is using a non-commercial Azure instance + * (e.g. a government or China account, which use different URLs). + * Defaults to "login.microsoftonline.com" + */ + identityPlatformEndpoint?: string | undefined; + }; + /** Configuration options for using 'gcp' as your KMS provider */ + gcp?: { + /** The service account email to authenticate */ + email: string; + /** A PKCS#8 encrypted key. This can either be a base64 string or a binary representation */ + privateKey: string | Buffer; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * Defaults to "oauth2.googleapis.com" + */ + endpoint?: string | undefined; + }; + }; + /** + * A map of namespaces to a local JSON schema for encryption + * + * **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server. + * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted. + * Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption. + * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. + */ + schemaMap?: Document; + /** Allows the user to bypass auto encryption, maintaining implicit decryption */ + bypassAutoEncryption?: boolean; + options?: { + /** An optional hook to catch logging messages from the underlying encryption engine */ + logger?: (level: AutoEncryptionLoggerLevel, message: string) => void; + }; + extraOptions?: { + /** + * A local process the driver communicates with to determine how to encrypt values in a command. + * Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise + */ + mongocryptdURI?: string; + /** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */ + mongocryptdBypassSpawn?: boolean; + /** The path to the mongocryptd executable on the system */ + mongocryptdSpawnPath?: string; + /** Command line arguments to use when auto-spawning a mongocryptd */ + mongocryptdSpawnArgs?: string[]; + }; +} +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +export declare class Batch { + originalZeroIndex: number; + currentIndex: number; + originalIndexes: number[]; + batchType: BatchType; + operations: T[]; + size: number; + sizeBytes: number; + constructor(batchType: BatchType, originalZeroIndex: number); +} +/** @public */ +export declare const BatchType: Readonly<{ + readonly INSERT: 1; + readonly UPDATE: 2; + readonly DELETE: 3; +}>; +/** @public */ +export declare type BatchType = typeof BatchType[keyof typeof BatchType]; +export { Binary }; +/** @public */ +export declare type BitwiseFilter = number /** numeric bit mask */ | Binary /** BinData bit mask */ | ReadonlyArray; +export { BSONRegExp }; +/** + * BSON Serialization options. + * @public + */ +export declare interface BSONSerializeOptions extends Pick>, Pick> { + /** Return BSON filled buffers from operations */ + raw?: boolean; +} +export { BSONSymbol }; +/** @public */ +export declare const BSONType: Readonly<{ + readonly double: 1; + readonly string: 2; + readonly object: 3; + readonly array: 4; + readonly binData: 5; + readonly undefined: 6; + readonly objectId: 7; + readonly bool: 8; + readonly date: 9; + readonly null: 10; + readonly regex: 11; + readonly dbPointer: 12; + readonly javascript: 13; + readonly symbol: 14; + readonly javascriptWithScope: 15; + readonly int: 16; + readonly timestamp: 17; + readonly long: 18; + readonly decimal: 19; + readonly minKey: -1; + readonly maxKey: 127; +}>; +/** @public */ +export declare type BSONType = typeof BSONType[keyof typeof BSONType]; +/** @public */ +export declare type BSONTypeAlias = keyof typeof BSONType; +/* Excluded from this release type: BufferPool */ +/** @public */ +export declare abstract class BulkOperationBase { + isOrdered: boolean; + /* Excluded from this release type: s */ + operationId?: number; + /* Excluded from this release type: __constructor */ + /** + * Add a single insert document to the bulk operation + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + * ``` + */ + insert(document: Document): BulkOperationBase; + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }}); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + * ``` + */ + find(selector: Document): FindOperators; + /** Specifies a raw operation to perform in the bulk write. */ + raw(op: AnyBulkWriteOperation): this; + readonly bsonOptions: BSONSerializeOptions; + readonly writeConcern: WriteConcern | undefined; + readonly batches: Batch[]; + /** An internal helper method. Do not invoke directly. Will be going away in the future */ + execute(options?: BulkWriteOptions, callback?: Callback): Promise | void; + /* Excluded from this release type: handleWriteError */ + abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} +/* Excluded from this release type: BulkOperationPrivate */ +/** @public */ +export declare interface BulkResult { + ok: number; + writeErrors: WriteError[]; + writeConcernErrors: WriteConcernError[]; + insertedIds: Document[]; + nInserted: number; + nUpserted: number; + nMatched: number; + nModified: number; + nRemoved: number; + upserted: Document[]; + opTime?: Document; +} +/** @public */ +export declare interface BulkWriteOperationError { + index: number; + code: number; + errmsg: string; + errInfo: Document; + op: Document | UpdateStatement | DeleteStatement; +} +/** @public */ +export declare interface BulkWriteOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** @deprecated use `ordered` instead */ + keepGoing?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; +} +/** + * @public + * The result of a bulk write. + */ +export declare class BulkWriteResult { + result: BulkResult; + /*Excluded from this release type: __constructor + Number of documents inserted. */ + readonly insertedCount: number; + /*Number of documents matched for update. */ + readonly matchedCount: number; + /*Number of documents modified. */ + readonly modifiedCount: number; + /*Number of documents deleted. */ + readonly deletedCount: number; + /*Number of documents upserted. */ + readonly upsertedCount: number; + /*Upserted document generated Id's, hash key is the index of the originating operation */ + readonly upsertedIds: { + [key: number]: any; + }; + /*Inserted document generated Id's, hash key is the index of the originating operation */ + readonly insertedIds: { + [key: number]: any; + }; + /*Evaluates to true if the bulk operation correctly executes */ + readonly ok: number; + /*The number of inserted documents */ + readonly nInserted: number; + /*Number of upserted documents */ + readonly nUpserted: number; + /*Number of matched documents */ + readonly nMatched: number; + /*Number of documents updated physically on disk */ + readonly nModified: number; + /*Number of removed documents */ + readonly nRemoved: number; + /** Returns an array of all inserted ids */ + getInsertedIds(): Document[]; + /** Returns an array of all upserted ids */ + getUpsertedIds(): Document[]; + /** Returns the upserted id at the given index */ + getUpsertedIdAt(index: number): Document | undefined; + /** Returns raw internal result */ + getRawResponse(): Document; + /** Returns true if the bulk operation contains a write error */ + hasWriteErrors(): boolean; + /** Returns the number of write errors off the bulk operation */ + getWriteErrorCount(): number; + /** Returns a specific write error object */ + getWriteErrorAt(index: number): WriteError | undefined; + /** Retrieve all write errors */ + getWriteErrors(): WriteError[]; + /** Retrieve lastOp if available */ + getLastOp(): Document | undefined; + /** Retrieve the write concern error if one exists */ + getWriteConcernError(): WriteConcernError | undefined; + toJSON(): BulkResult; + toString(): string; + isOk(): boolean; +} +/** + * MongoDB Driver style callback + * @public + */ +export declare type Callback = (error?: AnyError, result?: T) => void; +/** @public */ +export declare class CancellationToken extends TypedEventEmitter<{ + cancel(): void; +}> { +} +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @public + */ +export declare class ChangeStream extends TypedEventEmitter { + pipeline: Document[]; + options: ChangeStreamOptions; + parent: MongoClient | Db | Collection; + namespace: MongoDBNamespace; + type: symbol; + /* Excluded from this release type: cursor */ + streamOptions?: CursorStreamOptions; + /* Excluded from this release type: [kResumeQueue] */ + /* Excluded from this release type: [kCursorStream] */ + /* Excluded from this release type: [kClosed] */ + /* Excluded from this release type: [kMode] */ + /** @event */ + static readonly RESPONSE: "response"; + /** @event */ + static readonly MORE: "more"; + /** @event */ + static readonly INIT: "init"; + /** @event */ + static readonly CLOSE: "close"; + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * @event + */ + static readonly CHANGE: "change"; + /** @event */ + static readonly END: "end"; + /** @event */ + static readonly ERROR: "error"; + /** + * Emitted each time the change stream stores a new resume token. + * @event + */ + static readonly RESUME_TOKEN_CHANGED: "resumeTokenChanged"; + /*Excluded from this release type: __constructor + Excluded from this release type: cursorStream + The cached resume token that is used to resume after the most recently returned change. */ + readonly resumeToken: ResumeToken; + /** Check if there is any document still available in the Change Stream */ + hasNext(callback?: Callback): Promise | void; + /** Get the next available document from the Change Stream. */ + next(): Promise>; + next(callback: Callback>): void; + /*Is the cursor closed */ + readonly closed: boolean; + /** Close the Change Stream */ + close(callback?: Callback): Promise | void; + /** + * Return a modified Readable stream including a possible transform method. + * @throws MongoDriverError if this.cursor is undefined + */ + stream(options?: CursorStreamOptions): Readable; + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + tryNext(callback: Callback): void; +} +/* Excluded from this release type: ChangeStreamCursor */ +/* Excluded from this release type: ChangeStreamCursorOptions */ +/** @public */ +export declare interface ChangeStreamDocument { + /** + * The id functions as an opaque token for use when resuming an interrupted + * change stream. + */ + _id: InferIdType; + /** + * Describes the type of operation represented in this change notification. + */ + operationType: 'insert' | 'update' | 'replace' | 'delete' | 'invalidate' | 'drop' | 'dropDatabase' | 'rename'; + /** + * Contains two fields: “db” and “coll” containing the database and + * collection name in which the change happened. + */ + ns: { + db: string; + coll: string; + }; + /** + * Only present for ops of type ‘insert’, ‘update’, ‘replace’, and + * ‘delete’. + * + * For unsharded collections this contains a single field, _id, with the + * value of the _id of the document updated. For sharded collections, + * this will contain all the components of the shard key in order, + * followed by the _id if the _id isn’t part of the shard key. + */ + documentKey?: InferIdType; + /** + * Only present for ops of type ‘update’. + * + * Contains a description of updated and removed fields in this + * operation. + */ + updateDescription?: UpdateDescription; + /** + * Always present for operations of type ‘insert’ and ‘replace’. Also + * present for operations of type ‘update’ if the user has specified ‘updateLookup’ + * in the ‘fullDocument’ arguments to the ‘$changeStream’ stage. + * + * For operations of type ‘insert’ and ‘replace’, this key will contain the + * document being inserted, or the new version of the document that is replacing + * the existing document, respectively. + * + * For operations of type ‘update’, this key will contain a copy of the full + * version of the document from some point after the update occurred. If the + * document was deleted since the updated happened, it will be null. + */ + fullDocument?: TSchema; +} +/** @public */ +export declare type ChangeStreamEvents = { + resumeTokenChanged(token: ResumeToken): void; + init(response: Document): void; + more(response?: Document | undefined): void; + response(): void; + end(): void; + error(error: Error): void; + change(change: ChangeStreamDocument): void; +} & AbstractCursorEvents; +/** + * Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. + * @public + */ +export declare interface ChangeStreamOptions extends AggregateOptions { + /** Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. */ + fullDocument?: string; + /** The maximum amount of time for the server to wait on new documents to satisfy a change stream query. */ + maxAwaitTimeMS?: number; + /** Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. */ + resumeAfter?: ResumeToken; + /** Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. */ + startAfter?: ResumeToken; + /** Will start the changeStream after the specified operationTime. */ + startAtOperationTime?: OperationTime; + /** The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. */ + batchSize?: number; +} +/** @public */ +export declare interface ClientMetadata { + driver: { + name: string; + version: string; + }; + os: { + type: string; + name: NodeJS.Platform; + architecture: string; + version: string; + }; + platform: string; + version?: string; + application?: { + name: string; + }; +} +/** @public */ +export declare interface ClientMetadataOptions { + driverInfo?: { + name?: string; + version?: string; + platform?: string; + }; + appName?: string; +} +/** + * A class representing a client session on the server + * + * NOTE: not meant to be instantiated directly. + * @public + */ +export declare class ClientSession extends TypedEventEmitter { + /* Excluded from this release type: topology */ + /* Excluded from this release type: sessionPool */ + hasEnded: boolean; + clientOptions?: MongoOptions; + supports: { + causalConsistency: boolean; + }; + clusterTime?: ClusterTime; + operationTime?: Timestamp; + explicit: boolean; + /* Excluded from this release type: owner */ + defaultTransactionOptions: TransactionOptions; + transaction: Transaction; + /*Excluded from this release type: [kServerSession] + Excluded from this release type: [kSnapshotTime] + Excluded from this release type: [kSnapshotEnabled] + Excluded from this release type: [kPinnedConnection] + Excluded from this release type: __constructor + The server id associated with this session */ + readonly id: ServerSessionId | undefined; + readonly serverSession: ServerSession; + /*Whether or not this session is configured for snapshot reads */ + readonly snapshotEnabled: boolean; + readonly loadBalanced: boolean; + /*Excluded from this release type: pinnedConnection + Excluded from this release type: pin + Excluded from this release type: unpin */ + readonly isPinned: boolean; + /** + * Ends this session on the server + * + * @param options - Optional settings. Currently reserved for future use + * @param callback - Optional callback for completion of this operation + */ + endSession(): Promise; + endSession(callback: Callback): void; + endSession(options: EndSessionOptions): Promise; + endSession(options: EndSessionOptions, callback: Callback): void; + /** + * Advances the operationTime for a ClientSession. + * + * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime: Timestamp): void; + /** + * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession + * + * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature + */ + advanceClusterTime(clusterTime: ClusterTime): void; + /** + * Used to determine if this session equals another + * + * @param session - The session to compare to + */ + equals(session: ClientSession): boolean; + /** Increment the transaction number on the internal ServerSession */ + incrementTransactionNumber(): void; + /** @returns whether this session is currently in a transaction or not */ + inTransaction(): boolean; + /** + * Starts a new transaction with the given options. + * + * @param options - Options for the transaction + */ + startTransaction(options?: TransactionOptions): void; + /** + * Commits the currently active transaction in this session. + * + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + commitTransaction(): Promise; + commitTransaction(callback: Callback): void; + /** + * Aborts the currently active transaction in this session. + * + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + abortTransaction(): Promise; + abortTransaction(callback: Callback): void; + /** + * This is here to ensure that ClientSession is never serialized to BSON. + */ + toBSON(): never; + /** + * Runs a provided lambda within a transaction, retrying either the commit operation + * or entire transaction as needed (and when the error permits) to better ensure that + * the transaction can complete successfully. + * + * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not + * return a Promise will result in undefined behavior. + * + * @param fn - A lambda to run within a transaction + * @param options - Optional settings for the transaction + */ + withTransaction(fn: WithTransactionCallback, options?: TransactionOptions): ReturnType; +} +/** @public */ +export declare type ClientSessionEvents = { + ended(session: ClientSession): void; +}; +/** @public */ +export declare interface ClientSessionOptions { + /** Whether causal consistency should be enabled on this session */ + causalConsistency?: boolean; + /** Whether all read operations should be read from the same snapshot for this session (NOTE: not compatible with `causalConsistency=true`) */ + snapshot?: boolean; + /** The default TransactionOptions to use for transactions started on this session. */ + defaultTransactionOptions?: TransactionOptions; +} +/** @public */ +export declare interface CloseOptions { + force?: boolean; +} +/** @public */ +export declare interface ClusterTime { + clusterTime: Timestamp; + signature: { + hash: Binary; + keyId: Long; + }; +} +export { Code }; +/** @public */ +export declare interface CollationOptions { + locale: string; + caseLevel?: boolean; + caseFirst?: string; + strength?: number; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + normalization?: boolean; +} +/** + * The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * expect(err).to.not.exist; + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * ``` + */ +export declare class Collection { + /*Excluded from this release type: s + Excluded from this release type: __constructor + + * The name of the database this collection belongs to + */ + readonly dbName: string; + /* + * The name of this collection + */ + readonly collectionName: string; + /* + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + */ + readonly namespace: string; + /* + * The current readConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + readonly readConcern: ReadConcern | undefined; + /* + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + readonly readPreference: ReadPreference | undefined; + readonly bsonOptions: BSONSerializeOptions; + /* + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + readonly writeConcern: WriteConcern | undefined; + /*The current index hint for the collection */ + hint: Hint | undefined; + /** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param doc - The document to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insertOne(doc: OptionalId): Promise>; + insertOne(doc: OptionalId, callback: Callback>): void; + insertOne(doc: OptionalId, options: InsertOneOptions): Promise>; + insertOne(doc: OptionalId, options: InsertOneOptions, callback: Callback>): void; + /** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insertMany(docs: OptionalId[]): Promise>; + insertMany(docs: OptionalId[], callback: Callback>): void; + insertMany(docs: OptionalId[], options: BulkWriteOptions): Promise>; + insertMany(docs: OptionalId[], options: BulkWriteOptions, callback: Callback>): void; + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * ```js + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true} } + *``` + * Please note that raw operations are no longer accepted as of driver version 4.0. + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param operations - Bulk operations to perform + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * @throws MongoDriverError if operations is not an array + */ + bulkWrite(operations: AnyBulkWriteOperation[]): Promise; + bulkWrite(operations: AnyBulkWriteOperation[], callback: Callback): void; + bulkWrite(operations: AnyBulkWriteOperation[], options: BulkWriteOptions): Promise; + bulkWrite(operations: AnyBulkWriteOperation[], options: BulkWriteOptions, callback: Callback): void; + /** + * Update a single document in a collection + * + * @param filter - The filter used to select the document to update + * @param update - The update operations to be applied to the document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + updateOne(filter: Filter, update: UpdateFilter | Partial): Promise; + updateOne(filter: Filter, update: UpdateFilter | Partial, callback: Callback): void; + updateOne(filter: Filter, update: UpdateFilter | Partial, options: UpdateOptions): Promise; + updateOne(filter: Filter, update: UpdateFilter | Partial, options: UpdateOptions, callback: Callback): void; + /** + * Replace a document in a collection with another document + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + replaceOne(filter: Filter, replacement: TSchema): Promise; + replaceOne(filter: Filter, replacement: TSchema, callback: Callback): void; + replaceOne(filter: Filter, replacement: TSchema, options: ReplaceOptions): Promise; + replaceOne(filter: Filter, replacement: TSchema, options: ReplaceOptions, callback: Callback): void; + /** + * Update multiple documents in a collection + * + * @param filter - The filter used to select the documents to update + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + updateMany(filter: Filter, update: UpdateFilter): Promise; + updateMany(filter: Filter, update: UpdateFilter, callback: Callback): void; + updateMany(filter: Filter, update: UpdateFilter, options: UpdateOptions): Promise; + updateMany(filter: Filter, update: UpdateFilter, options: UpdateOptions, callback: Callback): void; + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + deleteOne(filter: Filter): Promise; + deleteOne(filter: Filter, callback: Callback): void; + deleteOne(filter: Filter, options: DeleteOptions): Promise; + deleteOne(filter: Filter, options: DeleteOptions, callback?: Callback): void; + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + deleteMany(filter: Filter): Promise; + deleteMany(filter: Filter, callback: Callback): void; + deleteMany(filter: Filter, options: DeleteOptions): Promise; + deleteMany(filter: Filter, options: DeleteOptions, callback: Callback): void; + /** + * Rename the collection. + * + * @remarks + * This operation does not inherit options from the Db or MongoClient. + * + * @param newName - New name of of the collection. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + rename(newName: string): Promise; + rename(newName: string, callback: Callback): void; + rename(newName: string, options: RenameOptions): Promise; + rename(newName: string, options: RenameOptions, callback: Callback): void; + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + drop(): Promise; + drop(callback: Callback): void; + drop(options: DropCollectionOptions): Promise; + drop(options: DropCollectionOptions, callback: Callback): void; + /** + * Fetches the first document that matches the filter + * + * @param filter - Query for find Operation + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOne(): Promise; + findOne(callback: Callback): void; + findOne(filter: Filter): Promise; + findOne(filter: Filter, callback: Callback): void; + findOne(filter: Filter, options: FindOptions): Promise; + findOne(filter: Filter, options: FindOptions, callback: Callback): void; + findOne(): Promise; + findOne(callback: Callback): void; + findOne(filter: Filter): Promise; + findOne(filter: Filter, options?: FindOptions): Promise; + findOne(filter: Filter, options?: FindOptions, callback?: Callback): void; + /** + * Creates a cursor for a filter that can be used to iterate over results from MongoDB + * + * @param filter - The filter predicate. If unspecified, then all documents in the collection will match the predicate + */ + find(): FindCursor; + find(filter: Filter, options?: FindOptions): FindCursor; + find(filter: Filter, options?: FindOptions): FindCursor; + /** + * Returns the options of the collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + options(): Promise; + options(callback: Callback): void; + options(options: OperationOptions): Promise; + options(options: OperationOptions, callback: Callback): void; + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + isCapped(): Promise; + isCapped(callback: Callback): void; + isCapped(options: OperationOptions): Promise; + isCapped(options: OperationOptions, callback: Callback): void; + /** + * Creates an index on the db and collection collection. + * + * @param indexSpec - The field name or index specification to create an index for + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @example + * ```js + * const collection = client.db('foo').collection('bar'); + * + * await collection.createIndex({ a: 1, b: -1 }); + * + * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes + * await collection.createIndex([ [c, 1], [d, -1] ]); + * + * // Equivalent to { e: 1 } + * await collection.createIndex('e'); + * + * // Equivalent to { f: 1, g: 1 } + * await collection.createIndex(['f', 'g']) + * + * // Equivalent to { h: 1, i: -1 } + * await collection.createIndex([ { h: 1 }, { i: -1 } ]); + * + * // Equivalent to { j: 1, k: -1, l: 2d } + * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) + * ``` + */ + createIndex(indexSpec: IndexSpecification): Promise; + createIndex(indexSpec: IndexSpecification, callback: Callback): void; + createIndex(indexSpec: IndexSpecification, options: CreateIndexesOptions): Promise; + createIndex(indexSpec: IndexSpecification, options: CreateIndexesOptions, callback: Callback): void; + /** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. + * + * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications. + * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/| here}. + * + * @param indexSpecs - An array of index specifications to be created + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @example + * ```js + * const collection = client.db('foo').collection('bar'); + * await collection.createIndexes([ + * // Simple index on field fizz + * { + * key: { fizz: 1 }, + * } + * // wildcard index + * { + * key: { '$**': 1 } + * }, + * // named index on darmok and jalad + * { + * key: { darmok: 1, jalad: -1 } + * name: 'tanagra' + * } + * ]); + * ``` + */ + createIndexes(indexSpecs: IndexDescription[]): Promise; + createIndexes(indexSpecs: IndexDescription[], callback: Callback): void; + createIndexes(indexSpecs: IndexDescription[], options: CreateIndexesOptions): Promise; + createIndexes(indexSpecs: IndexDescription[], options: CreateIndexesOptions, callback: Callback): void; + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropIndex(indexName: string): Promise; + dropIndex(indexName: string, callback: Callback): void; + dropIndex(indexName: string, options: DropIndexesOptions): Promise; + dropIndex(indexName: string, options: DropIndexesOptions, callback: Callback): void; + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropIndexes(): Promise; + dropIndexes(callback: Callback): void; + dropIndexes(options: DropIndexesOptions): Promise; + dropIndexes(options: DropIndexesOptions, callback: Callback): void; + /** + * Get the list of all indexes information for the collection. + * + * @param options - Optional settings for the command + */ + listIndexes(options?: ListIndexesOptions): ListIndexesCursor; + /** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * + * @param indexes - One or more index names to check. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexExists(indexes: string | string[]): Promise; + indexExists(indexes: string | string[], callback: Callback): void; + indexExists(indexes: string | string[], options: IndexInformationOptions): Promise; + indexExists(indexes: string | string[], options: IndexInformationOptions, callback: Callback): void; + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexInformation(): Promise; + indexInformation(callback: Callback): void; + indexInformation(options: IndexInformationOptions): Promise; + indexInformation(options: IndexInformationOptions, callback: Callback): void; + /** + * Gets an estimate of the count of documents in a collection using collection metadata. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + estimatedDocumentCount(): Promise; + estimatedDocumentCount(callback: Callback): void; + estimatedDocumentCount(options: EstimatedDocumentCountOptions): Promise; + estimatedDocumentCount(options: EstimatedDocumentCountOptions, callback: Callback): void; + /** + * Gets the number of documents matching the filter. + * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ + * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param filter - The filter for the count + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ + * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + countDocuments(): Promise; + countDocuments(callback: Callback): void; + countDocuments(filter: Filter): Promise; + countDocuments(callback: Callback): void; + countDocuments(filter: Filter, options: CountDocumentsOptions): Promise; + countDocuments(filter: Filter, options: CountDocumentsOptions, callback: Callback): void; + countDocuments(filter: Filter, callback: Callback): void; + /** + * The distinct command returns a list of distinct values for the given key across a collection. + * + * @param key - Field of the document to find distinct values for + * @param filter - The filter for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + distinct>(key: Key): Promise[Key]>>>; + distinct>(key: Key, callback: Callback[Key]>>>): void; + distinct>(key: Key, filter: Filter): Promise[Key]>>>; + distinct>(key: Key, filter: Filter, callback: Callback[Key]>>>): void; + distinct>(key: Key, filter: Filter, options: DistinctOptions): Promise[Key]>>>; + distinct>(key: Key, filter: Filter, options: DistinctOptions, callback: Callback[Key]>>>): void; + distinct(key: string): Promise; + distinct(key: string, callback: Callback): void; + distinct(key: string, filter: Filter): Promise; + distinct(key: string, filter: Filter, callback: Callback): void; + distinct(key: string, filter: Filter, options: DistinctOptions): Promise; + distinct(key: string, filter: Filter, options: DistinctOptions, callback: Callback): void; + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexes(): Promise; + indexes(callback: Callback): void; + indexes(options: IndexInformationOptions): Promise; + indexes(options: IndexInformationOptions, callback: Callback): void; + /** + * Get all the collection statistics. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + stats(): Promise; + stats(callback: Callback): void; + stats(options: CollStatsOptions): Promise; + stats(options: CollStatsOptions, callback: Callback): void; + /** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndDelete(filter: Filter): Promise>; + findOneAndDelete(filter: Filter, options: FindOneAndDeleteOptions): Promise>; + findOneAndDelete(filter: Filter, callback: Callback>): void; + findOneAndDelete(filter: Filter, options: FindOneAndDeleteOptions, callback: Callback>): void; + /** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndReplace(filter: Filter, replacement: Document): Promise>; + findOneAndReplace(filter: Filter, replacement: Document, callback: Callback>): void; + findOneAndReplace(filter: Filter, replacement: Document, options: FindOneAndReplaceOptions): Promise>; + findOneAndReplace(filter: Filter, replacement: Document, options: FindOneAndReplaceOptions, callback: Callback>): void; + /** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to update + * @param update - Update operations to be performed on the document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndUpdate(filter: Filter, update: UpdateFilter): Promise>; + findOneAndUpdate(filter: Filter, update: UpdateFilter, callback: Callback>): void; + findOneAndUpdate(filter: Filter, update: UpdateFilter, options: FindOneAndUpdateOptions): Promise>; + findOneAndUpdate(filter: Filter, update: UpdateFilter, options: FindOneAndUpdateOptions, callback: Callback>): void; + /** + * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 + * + * @param pipeline - An array of aggregation pipelines to execute + * @param options - Optional settings for the command + */ + aggregate(pipeline?: Document[], options?: AggregateOptions): AggregationCursor; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * + * @since 3.0.0 + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; + /** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @param map - The mapping function. + * @param reduce - The reduce function. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction): Promise; + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction, callback: Callback): void; + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction, options: MapReduceOptions): Promise; + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction, options: MapReduceOptions, callback: Callback): void; + /** Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. */ + initializeUnorderedBulkOp(options?: BulkWriteOptions): UnorderedBulkOperation; + /** Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. */ + initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation; + /** Get the db scoped logger */ + getLogger(): Logger; + readonly logger: Logger; + /** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @deprecated Use insertOne, insertMany or bulkWrite instead. + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insert(docs: OptionalId[], options: BulkWriteOptions, callback: Callback>): Promise> | void; + /** + * Updates documents. + * + * @deprecated use updateOne, updateMany or bulkWrite + * @param selector - The selector for the update operation. + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + update(selector: Filter, update: UpdateFilter, options: UpdateOptions, callback: Callback): Promise | void; + /** + * Remove documents. + * + * @deprecated use deleteOne, deleteMany or bulkWrite + * @param selector - The selector for the update operation. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + remove(selector: Filter, options: DeleteOptions, callback: Callback): Promise | void; + /** + * An estimated count of matching documents in the db to a filter. + * + * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents + * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}. + * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * + * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead + * + * @param filter - The filter for the count. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + count(): Promise; + count(callback: Callback): void; + count(filter: Filter): Promise; + count(filter: Filter, callback: Callback): void; + count(filter: Filter, options: CountOptions): Promise; + count(filter: Filter, options: CountOptions, callback: Callback): Promise | void; +} +/** @public */ +export declare interface CollectionInfo extends Document { + name: string; + type?: string; + options?: Document; + info?: { + readOnly?: false; + uuid?: Binary; + }; + idIndex?: Document; +} +/** @public */ +export declare interface CollectionOptions extends BSONSerializeOptions, WriteConcernOptions, LoggerOptions { + slaveOk?: boolean; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; +} +/* Excluded from this release type: CollectionPrivate */ +/** + * @public + * @see https://docs.mongodb.org/manual/reference/command/collStats/ + */ +export declare interface CollStats extends Document { + /** Namespace */ + ns: string; + /** Number of documents */ + count: number; + /** Collection size in bytes */ + size: number; + /** Average object size in bytes */ + avgObjSize: number; + /** (Pre)allocated space for the collection in bytes */ + storageSize: number; + /** Number of extents (contiguously allocated chunks of datafile space) */ + numExtents: number; + /** Number of indexes */ + nindexes: number; + /** Size of the most recently created extent in bytes */ + lastExtentSize: number; + /** Padding can speed up updates if documents grow */ + paddingFactor: number; + /** A number that indicates the user-set flags on the collection. userFlags only appears when using the mmapv1 storage engine */ + userFlags?: number; + /** Total index size in bytes */ + totalIndexSize: number; + /** Size of specific indexes in bytes */ + indexSizes: { + _id_: number; + [index: string]: number; + }; + /** `true` if the collection is capped */ + capped: boolean; + /** The maximum number of documents that may be present in a capped collection */ + max: number; + /** The maximum size of a capped collection */ + maxSize: number; + /** This document contains data reported directly by the WiredTiger engine and other data for internal diagnostic use */ + wiredTiger?: WiredTigerData; + /** The fields in this document are the names of the indexes, while the values themselves are documents that contain statistics for the index provided by the storage engine */ + indexDetails?: any; + ok: number; + /** The amount of storage available for reuse. The scale argument affects this value. */ + freeStorageSize?: number; + /** An array that contains the names of the indexes that are currently being built on the collection */ + indexBuilds?: number; + /** The sum of the storageSize and totalIndexSize. The scale argument affects this value */ + totalSize: number; + /** The scale value used by the command. */ + scaleFactor: number; +} +/** @public */ +export declare interface CollStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} +/** + * An event indicating the failure of a given command + * @public + * @category Event + */ +export declare class CommandFailedEvent { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + failure: Error; + serviceId?: ObjectId; + /*Excluded from this release type: __constructor */ + readonly hasServiceId: boolean; +} +/* Excluded from this release type: CommandOperation */ +/** @public */ +export declare interface CommandOperationOptions extends OperationOptions, WriteConcernOptions, ExplainOptions { + /** @deprecated This option does nothing */ + fullResponse?: boolean; + /** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** Collation */ + collation?: CollationOptions; + maxTimeMS?: number; + /** A user-provided comment to attach to this command */ + comment?: string | Document; + /** Should retry failed writes */ + retryWrites?: boolean; + dbName?: string; + authdb?: string; + noResponse?: boolean; +} +/* Excluded from this release type: CommandOptions */ +/** + * An event indicating the start of a given + * @public + * @category Event + */ +export declare class CommandStartedEvent { + commandObj?: Document; + requestId: number; + databaseName: string; + commandName: string; + command: Document; + address: string; + connectionId?: string | number; + serviceId?: ObjectId; + /*Excluded from this release type: __constructor */ + readonly hasServiceId: boolean; +} +/** + * An event indicating the success of a given command + * @public + * @category Event + */ +export declare class CommandSucceededEvent { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + reply: unknown; + serviceId?: ObjectId; + /*Excluded from this release type: __constructor */ + readonly hasServiceId: boolean; +} +/** @public */ +export declare type CommonEvents = 'newListener' | 'removeListener'; +/** @public */ +export declare const Compressor: Readonly<{ + readonly none: 0; + readonly snappy: 1; + readonly zlib: 2; +}>; +/** @public */ +export declare type Compressor = typeof Compressor[CompressorName]; +/** @public */ +export declare type CompressorName = keyof typeof Compressor; +/** @public */ +export declare type Condition = AlternativeType | FilterOperators>; +/* Excluded from this release type: Connection */ +/** + * An event published when a connection is checked into the connection pool + * @public + * @category Event + */ +export declare class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; +} +/** + * An event published when a connection is checked out of the connection pool + * @public + * @category Event + */ +export declare class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; +} +/** + * An event published when a request to check a connection out fails + * @public + * @category Event + */ +export declare class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + /** The reason the attempt to check out failed */ + reason: AnyError | string; +} +/** + * An event published when a request to check a connection out begins + * @public + * @category Event + */ +export declare class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { +} +/** + * An event published when a connection is closed + * @public + * @category Event + */ +export declare class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /** The reason the connection was closed */ + reason: string; + serviceId?: ObjectId; +} +/** + * An event published when a connection pool creates a new connection + * @public + * @category Event + */ +export declare class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + /** A monotonically increasing, per-pool id for the newly created connection */ + connectionId: number | ''; +} +/** @public */ +export declare type ConnectionEvents = { + commandStarted(event: CommandStartedEvent): void; + commandSucceeded(event: CommandSucceededEvent): void; + commandFailed(event: CommandFailedEvent): void; + clusterTimeReceived(clusterTime: Document): void; + close(): void; + message(message: any): void; + pinned(pinType: string): void; + unpinned(pinType: string): void; +}; +/** @public */ +export declare interface ConnectionOptions extends SupportedNodeConnectionOptions, StreamDescriptionOptions { + id: number | ''; + generation: number; + hostAddress: HostAddress; + autoEncrypter?: AutoEncrypter; + serverApi?: ServerApi; + monitorCommands: boolean; + /* Excluded from this release type: connectionType */ + credentials?: MongoCredentials; + connectTimeoutMS?: number; + tls: boolean; + keepAlive?: boolean; + keepAliveInitialDelay?: number; + noDelay?: boolean; + socketTimeoutMS?: number; + cancellationToken?: CancellationToken; + metadata: ClientMetadata; +} +/* Excluded from this release type: ConnectionPool */ +/** + * An event published when a connection pool is cleared + * @public + * @category Event + */ +export declare class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { +} +/** + * An event published when a connection pool is closed + * @public + * @category Event + */ +export declare class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { +} +/** + * An event published when a connection pool is created + * @public + * @category Event + */ +export declare class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + /** The options used to create this connection pool */ + options?: ConnectionPoolOptions; +} +/** @public */ +export declare type ConnectionPoolEvents = { + connectionPoolCreated(event: ConnectionPoolCreatedEvent): void; + connectionPoolClosed(event: ConnectionPoolClosedEvent): void; + connectionPoolCleared(event: ConnectionPoolClearedEvent): void; + connectionCreated(event: ConnectionCreatedEvent): void; + connectionReady(event: ConnectionReadyEvent): void; + connectionClosed(event: ConnectionClosedEvent): void; + connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void; + connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void; + connectionCheckedOut(event: ConnectionCheckedOutEvent): void; + connectionCheckedIn(event: ConnectionCheckedInEvent): void; +} & Pick>; +/* Excluded from this release type: ConnectionPoolMetrics */ +/** + * The base export class for all monitoring events published from the connection pool + * @public + * @category Event + */ +export declare class ConnectionPoolMonitoringEvent { + /** A timestamp when the event was created */ + time: Date; + /** The address (host/port pair) of the pool */ + address: string; +} +/** @public */ +export declare interface ConnectionPoolOptions extends Pick> { + /** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */ + maxPoolSize: number; + /** The minimum number of connections that MUST exist at any moment in a single connection pool. */ + minPoolSize: number; + /** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */ + maxIdleTimeMS: number; + /** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. */ + waitQueueTimeoutMS: number; + /** If we are in load balancer mode. */ + loadBalanced: boolean; +} +/** + * An event published when a connection is ready for use + * @public + * @category Event + */ +export declare class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; +} +/** @public */ +export declare interface ConnectOptions { + readPreference?: ReadPreference; +} +/** @public */ +export declare interface CountDocumentsOptions extends AggregateOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; +} +/** @public */ +export declare interface CountOptions extends CommandOperationOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** An index name hint for the query. */ + hint?: string | Document; +} +/** @public */ +export declare interface CreateCollectionOptions extends CommandOperationOptions { + /** Returns an error if the collection does not exist */ + strict?: boolean; + /** Create a capped collection */ + capped?: boolean; + /** @deprecated Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 */ + autoIndexId?: boolean; + /** The size of the capped collection in bytes */ + size?: number; + /** The maximum number of documents in the capped collection */ + max?: number; + /** Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag */ + flags?: number; + /** Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher */ + storageEngine?: Document; + /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher */ + validator?: Document; + /** Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher */ + validationLevel?: string; + /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher */ + validationAction?: string; + /** Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher */ + indexOptionDefaults?: Document; + /** The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher */ + viewOn?: string; + /** An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher */ + pipeline?: Document[]; + /** A primary key factory function for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** A document specifying configuration options for timeseries collections. */ + timeseries?: TimeSeriesCollectionOptions; + /** The number of seconds after which a document in a timeseries collection expires. */ + expireAfterSeconds?: number; +} +/** @public */ +export declare interface CreateIndexesOptions extends CommandOperationOptions { + /** Creates the index in the background, yielding whenever possible. */ + background?: boolean; + /** Creates an unique index. */ + unique?: boolean; + /** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */ + name?: string; + /** Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */ + partialFilterExpression?: Document; + /** Creates a sparse index. */ + sparse?: boolean; + /** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */ + expireAfterSeconds?: number; + /** Allows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher) */ + storageEngine?: Document; + /** (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. */ + commitQuorum?: number | string; + /** Specifies the index version number, either 0 or 1. */ + version?: number; + weights?: Document; + default_language?: string; + language_override?: string; + textIndexVersion?: number; + '2dsphereIndexVersion'?: number; + bits?: number; + /** For geospatial indexes set the lower bound for the co-ordinates. */ + min?: number; + /** For geospatial indexes set the high bound for the co-ordinates. */ + max?: number; + bucketSize?: number; + wildcardProjection?: Document; + /** Specifies that the index should exist on the target collection but should not be used by the query planner when executing operations. (MongoDB 4.4 or higher) */ + hidden?: boolean; +} +/** @public */ +export declare const CURSOR_FLAGS: readonly [ + "tailable", + "oplogReplay", + "noCursorTimeout", + "awaitData", + "exhaust", + "partial" +]; +/** @public + * @deprecated This interface is deprecated */ +export declare interface CursorCloseOptions { + /** Bypass calling killCursors when closing the cursor. */ + /** @deprecated the skipKillCursors option is deprecated */ + skipKillCursors?: boolean; +} +/** @public */ +export declare type CursorFlag = typeof CURSOR_FLAGS[number]; +/** @public */ +export declare interface CursorStreamOptions { + /** A transformation method applied to each document emitted by the stream */ + transform?(doc: Document): Document; +} +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```js + * const { MongoClient } = require('mongodb'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); + * }); + * ``` + */ +export declare class Db { + /* Excluded from this release type: s */ + static SYSTEM_NAMESPACE_COLLECTION: string; + static SYSTEM_INDEX_COLLECTION: string; + static SYSTEM_PROFILE_COLLECTION: string; + static SYSTEM_USER_COLLECTION: string; + static SYSTEM_COMMAND_COLLECTION: string; + static SYSTEM_JS_COLLECTION: string; + /** + * Creates a new Db instance + * + * @param client - The MongoClient for the database. + * @param databaseName - The name of the database this instance represents. + * @param options - Optional settings for Db construction + */ + constructor(client: MongoClient, databaseName: string, options?: DbOptions); + readonly databaseName: string; + readonly options: DbOptions | undefined; + readonly slaveOk: boolean; + readonly readConcern: ReadConcern | undefined; + /* + * The current readPreference of the Db. If not explicitly defined for + * this Db, will be inherited from the parent MongoClient + */ + readonly readPreference: ReadPreference; + readonly bsonOptions: BSONSerializeOptions; + readonly writeConcern: WriteConcern | undefined; + readonly namespace: string; + /** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @param name - The name of the collection to create + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + createCollection(name: string): Promise>; + createCollection(name: string, callback: Callback>): void; + createCollection(name: string, options: CreateCollectionOptions): Promise>; + createCollection(name: string, options: CreateCollectionOptions, callback: Callback>): void; + /** + * Execute a command + * + * @remarks + * This command does not inherit options from the MongoClient. + * + * @param command - The command to run + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + command(command: Document): Promise; + command(command: Document, callback: Callback): void; + command(command: Document, options: RunCommandOptions): Promise; + command(command: Document, options: RunCommandOptions, callback: Callback): void; + /** + * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6 + * + * @param pipeline - An array of aggregation stages to be executed + * @param options - Optional settings for the command + */ + aggregate(pipeline?: Document[], options?: AggregateOptions): AggregationCursor; + /** Return the Admin db instance */ + admin(): Admin; + /** + * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. + * + * @param name - the collection name we wish to access. + * @returns return the new Collection instance + */ + collection(name: string, options?: CollectionOptions): Collection; + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + stats(): Promise; + stats(callback: Callback): void; + stats(options: DbStatsOptions): Promise; + stats(options: DbStatsOptions, callback: Callback): void; + /** + * List all collections of this database with optional filter + * + * @param filter - Query to filter collections by + * @param options - Optional settings for the command + */ + listCollections(filter: Document, options: Exclude & { + nameOnly: true; + }): ListCollectionsCursor>; + listCollections(filter: Document, options: Exclude & { + nameOnly: false; + }): ListCollectionsCursor; + listCollections | CollectionInfo = Pick | CollectionInfo>(filter?: Document, options?: ListCollectionsOptions): ListCollectionsCursor; + /** + * Rename a collection. + * + * @remarks + * This operation does not inherit options from the MongoClient. + * + * @param fromCollection - Name of current collection to rename + * @param toCollection - New name of of the collection + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + renameCollection(fromCollection: string, toCollection: string): Promise>; + renameCollection(fromCollection: string, toCollection: string, callback: Callback>): void; + renameCollection(fromCollection: string, toCollection: string, options: RenameOptions): Promise>; + renameCollection(fromCollection: string, toCollection: string, options: RenameOptions, callback: Callback>): void; + /** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param name - Name of collection to drop + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropCollection(name: string): Promise; + dropCollection(name: string, callback: Callback): void; + dropCollection(name: string, options: DropCollectionOptions): Promise; + dropCollection(name: string, options: DropCollectionOptions, callback: Callback): void; + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropDatabase(): Promise; + dropDatabase(callback: Callback): void; + dropDatabase(options: DropDatabaseOptions): Promise; + dropDatabase(options: DropDatabaseOptions, callback: Callback): void; + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + collections(): Promise; + collections(callback: Callback): void; + collections(options: ListCollectionsOptions): Promise; + collections(options: ListCollectionsOptions, callback: Callback): void; + /** + * Creates an index on the db and collection. + * + * @param name - Name of the collection to create the index on. + * @param indexSpec - Specify the field to index, or an index specification + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + createIndex(name: string, indexSpec: IndexSpecification): Promise; + createIndex(name: string, indexSpec: IndexSpecification, callback?: Callback): void; + createIndex(name: string, indexSpec: IndexSpecification, options: CreateIndexesOptions): Promise; + createIndex(name: string, indexSpec: IndexSpecification, options: CreateIndexesOptions, callback: Callback): void; + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param password - An optional password for the new user + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + addUser(username: string): Promise; + addUser(username: string, callback: Callback): void; + addUser(username: string, password: string): Promise; + addUser(username: string, password: string, callback: Callback): void; + addUser(username: string, options: AddUserOptions): Promise; + addUser(username: string, options: AddUserOptions, callback: Callback): void; + addUser(username: string, password: string, options: AddUserOptions): Promise; + addUser(username: string, password: string, options: AddUserOptions, callback: Callback): void; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + removeUser(username: string): Promise; + removeUser(username: string, callback: Callback): void; + removeUser(username: string, options: RemoveUserOptions): Promise; + removeUser(username: string, options: RemoveUserOptions, callback: Callback): void; + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + setProfilingLevel(level: ProfilingLevel): Promise; + setProfilingLevel(level: ProfilingLevel, callback: Callback): void; + setProfilingLevel(level: ProfilingLevel, options: SetProfilingLevelOptions): Promise; + setProfilingLevel(level: ProfilingLevel, options: SetProfilingLevelOptions, callback: Callback): void; + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + profilingLevel(): Promise; + profilingLevel(callback: Callback): void; + profilingLevel(options: ProfilingLevelOptions): Promise; + profilingLevel(options: ProfilingLevelOptions, callback: Callback): void; + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexInformation(name: string): Promise; + indexInformation(name: string, callback: Callback): void; + indexInformation(name: string, options: IndexInformationOptions): Promise; + indexInformation(name: string, options: IndexInformationOptions, callback: Callback): void; + /** + * Unref all sockets + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref(): void; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this database. Will ignore all + * changes to system collections. + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; + /** Return the db logger */ + getLogger(): Logger; + readonly logger: Logger; +} +/* Excluded from this release type: DB_AGGREGATE_COLLECTION */ +/** @public */ +export declare interface DbOptions extends BSONSerializeOptions, WriteConcernOptions, LoggerOptions { + /** If the database authentication is dependent on another databaseName. */ + authSource?: string; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; + /** A primary key factory object for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcern; + /** Should retry failed writes */ + retryWrites?: boolean; +} +/* Excluded from this release type: DbPrivate */ +export { DBRef }; +/** @public */ +export declare interface DbStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} +export { Decimal128 }; +/** @public */ +export declare interface DeleteManyModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} +/** @public */ +export declare interface DeleteOneModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} +/** @public */ +export declare interface DeleteOptions extends CommandOperationOptions, WriteConcernOptions { + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** A user-provided comment to attach to this command */ + comment?: string | Document; + /** Specifies the collation to use for the operation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + /** @deprecated use `removeOne` or `removeMany` to implicitly specify the limit */ + single?: boolean; +} +/** @public */ +export declare interface DeleteResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined. */ + acknowledged: boolean; + /** The number of documents that were deleted */ + deletedCount: number; +} +/** @public */ +export declare interface DeleteStatement { + /** The query that matches documents to delete. */ + q: Document; + /** The number of matching documents to delete. */ + limit: number; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; + /** A user-provided comment to attach to this command */ + comment?: string | Document; +} +/* Excluded from this release type: deserialize */ +/** @public */ +export declare interface DestroyOptions { + /** Force the destruction. */ + force?: boolean; +} +/** @public */ +export declare type DistinctOptions = CommandOperationOptions; +export { Document }; +export { Double }; +/** @public */ +export declare interface DriverInfo { + name?: string; + version?: string; + platform?: string; +} +/** @public */ +export declare type DropCollectionOptions = CommandOperationOptions; +/** @public */ +export declare type DropDatabaseOptions = CommandOperationOptions; +/** @public */ +export declare type DropIndexesOptions = CommandOperationOptions; +/* Excluded from this release type: Encrypter */ +/* Excluded from this release type: EncrypterOptions */ +/** @public */ +export declare interface EndSessionOptions { + /* Excluded from this release type: error */ + force?: boolean; + forceClear?: boolean; +} +/** TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions @public */ +export declare type EnhancedOmit = string extends keyof TRecordOrUnion ? TRecordOrUnion : TRecordOrUnion extends any ? Pick> : never; +/** @public */ +export declare interface ErrorDescription extends Document { + message?: string; + errmsg?: string; + $err?: string; + errorLabels?: string[]; + errInfo?: Document; +} +/** @public */ +export declare interface EstimatedDocumentCountOptions extends CommandOperationOptions { + /** + * The maximum amount of time to allow the operation to run. + * + * This option is sent only if the caller explicitly provides a value. The default is to not send a value. + */ + maxTimeMS?: number; +} +/** @public */ +export declare interface EvalOptions extends CommandOperationOptions { + nolock?: boolean; +} +/** @public */ +export declare type EventEmitterWithState = {}; +/** + * Event description type + * @public + */ +export declare type EventsDescription = Record; +/* Excluded from this release type: ExecutionResult */ +/* Excluded from this release type: Explain */ +/** @public */ +export declare interface ExplainOptions { + /** Specifies the verbosity mode for the explain output. */ + explain?: ExplainVerbosityLike; +} +/** @public */ +export declare const ExplainVerbosity: Readonly<{ + readonly queryPlanner: "queryPlanner"; + readonly queryPlannerExtended: "queryPlannerExtended"; + readonly executionStats: "executionStats"; + readonly allPlansExecution: "allPlansExecution"; +}>; +/** @public */ +export declare type ExplainVerbosity = string; +/** + * For backwards compatibility, true is interpreted as "allPlansExecution" + * and false as "queryPlanner". Prior to server version 3.6, aggregate() + * ignores the verbosity parameter and executes in "queryPlanner". + * @public + */ +export declare type ExplainVerbosityLike = ExplainVerbosity | boolean; +/** A MongoDB filter can be some portion of the schema or a set of operators @public */ +export declare type Filter = { + [P in keyof TSchema]?: Condition; +} & RootFilterOperators; +/** @public */ +export declare type FilterOperations = T extends Record ? { + [key in keyof T]?: FilterOperators; +} : FilterOperators; +/** @public */ +export declare interface FilterOperators extends Document { + $eq?: TValue; + $gt?: TValue; + $gte?: TValue; + $in?: ReadonlyArray; + $lt?: TValue; + $lte?: TValue; + $ne?: TValue; + $nin?: ReadonlyArray; + $not?: TValue extends string ? FilterOperators | RegExp : FilterOperators; + /** + * When `true`, `$exists` matches the documents that contain the field, + * including documents where the field value is null. + */ + $exists?: boolean; + $type?: BSONType | BSONTypeAlias; + $expr?: Record; + $jsonSchema?: Record; + $mod?: TValue extends number ? [ + number, + number + ] : never; + $regex?: TValue extends string ? RegExp | BSONRegExp | string : never; + $options?: TValue extends string ? string : never; + $geoIntersects?: { + $geometry: Document; + }; + $geoWithin?: Document; + $near?: Document; + $nearSphere?: Document; + $maxDistance?: number; + $all?: ReadonlyArray; + $elemMatch?: Document; + $size?: TValue extends ReadonlyArray ? number : never; + $bitsAllClear?: BitwiseFilter; + $bitsAllSet?: BitwiseFilter; + $bitsAnyClear?: BitwiseFilter; + $bitsAnySet?: BitwiseFilter; + $rand?: Record; +} +/** @public */ +export declare type FinalizeFunction = (key: TKey, reducedValue: TValue) => TValue; +/** @public */ +export declare class FindCursor extends AbstractCursor { + /* Excluded from this release type: [kFilter] */ + /* Excluded from this release type: [kNumReturned] */ + /* Excluded from this release type: [kBuiltOptions] */ + /* Excluded from this release type: __constructor */ + clone(): FindCursor; + map(transform: (doc: TSchema) => T): FindCursor; + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: _getMore */ + /** Get the count of documents for this cursor */ + count(): Promise; + count(callback: Callback): void; + count(options: CountOptions): Promise; + count(options: CountOptions, callback: Callback): void; + /** Execute the explain for the cursor */ + explain(): Promise; + explain(callback: Callback): void; + explain(verbosity?: ExplainVerbosityLike): Promise; + /** Set the cursor query */ + filter(filter: Document): this; + /** + * Set the cursor hint + * + * @param hint - If specified, then the query system will only consider plans using the hinted index. + */ + hint(hint: Hint): this; + /** + * Set the cursor min + * + * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + */ + min(min: Document): this; + /** + * Set the cursor max + * + * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + */ + max(max: Document): this; + /** + * Set the cursor returnKey. + * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. + * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * + * @param value - the returnKey value. + */ + returnKey(value: boolean): this; + /** + * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. + * + * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + */ + showRecordId(value: boolean): this; + /** + * Add a query modifier to the cursor query + * + * @param name - The query modifier (must start with $, such as $orderby etc) + * @param value - The modifier value. + */ + addQueryModifier(name: string, value: string | boolean | number | Document): this; + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * + * @param value - The comment attached to this query. + */ + comment(value: string): this; + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * + * @param value - Number of milliseconds to wait before aborting the tailed query. + */ + maxAwaitTimeMS(value: number): this; + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this; + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic + * {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: FindCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.find().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project(value: Document): FindCursor; + /** + * Sets the sort order of the cursor query. + * + * @param sort - The key or keys set for the sort. + * @param direction - The direction of the sorting (1 or -1). + */ + sort(sort: Sort | string, direction?: SortDirection): this; + /** + * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) + * + * @remarks + * {@link https://docs.mongodb.com/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} + */ + allowDiskUse(): this; + /** + * Set the collation options for the cursor. + * + * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + */ + collation(value: CollationOptions): this; + /** + * Set the limit for the cursor. + * + * @param value - The limit for the cursor query. + */ + limit(value: number): this; + /** + * Set the skip for the cursor. + * + * @param value - The skip for the cursor query. + */ + skip(value: number): this; +} +/** @public */ +export declare interface FindOneAndDeleteOptions extends CommandOperationOptions { + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} +/** @public */ +export declare interface FindOneAndReplaceOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} +/** @public */ +export declare interface FindOneAndUpdateOptions extends CommandOperationOptions { + /** Optional list of array filters referenced in filtered positional operators */ + arrayFilters?: Document[]; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +export declare class FindOperators { + bulkOperation: BulkOperationBase; + /* Excluded from this release type: __constructor */ + /** Add a multiple update operation to the bulk operation */ + update(updateDocument: Document): BulkOperationBase; + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument: Document): BulkOperationBase; + /** Add a replace one operation to the bulk operation */ + replaceOne(replacement: Document): BulkOperationBase; + /** Add a delete one operation to the bulk operation */ + deleteOne(): BulkOperationBase; + /** Add a delete many operation to the bulk operation */ + delete(): BulkOperationBase; + /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ + upsert(): this; + /** Specifies the collation for the query condition. */ + collation(collation: CollationOptions): this; + /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ + arrayFilters(arrayFilters: Document[]): this; +} +/** + * @public + * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic + */ +export declare interface FindOptions extends CommandOperationOptions { + /** Sets the limit of documents returned in the query. */ + limit?: number; + /** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */ + sort?: Sort; + /** The fields to return in the query. Object of fields to either include or exclude (one of, not both), `{'a':1, 'b': 1}` **or** `{'a': 0, 'b': 0}` */ + projection?: Document; + /** Set to skip N documents ahead in your query (useful for pagination). */ + skip?: number; + /** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */ + hint?: Hint; + /** Specify if the cursor can timeout. */ + timeout?: boolean; + /** Specify if the cursor is tailable. */ + tailable?: boolean; + /** Specify if the cursor is a a tailable-await cursor. Requires `tailable` to be true */ + awaitData?: boolean; + /** Set the batchSize for the getMoreCommand when iterating over the query results. */ + batchSize?: number; + /** If true, returns only the index keys in the resulting documents. */ + returnKey?: boolean; + /** The inclusive lower bound for a specific index */ + min?: Document; + /** The exclusive upper bound for a specific index */ + max?: Document; + /** You can put a $comment field on a query to make looking in the profiler logs simpler. */ + comment?: string | Document; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true */ + maxAwaitTimeMS?: number; + /** The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. */ + noCursorTimeout?: boolean; + /** Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */ + collation?: CollationOptions; + /** Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) */ + allowDiskUse?: boolean; + /** Determines whether to close the cursor after the first batch. Defaults to false. */ + singleBatch?: boolean; + /** For queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable. */ + allowPartialResults?: boolean; + /** Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents. */ + showRecordId?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} +/** @public */ +export declare type Flatten = Type extends ReadonlyArray ? Item : Type; +/** @public */ +export declare type GenericListener = (...args: any[]) => void; +/* Excluded from this release type: GetMore */ +/* Excluded from this release type: GetMoreOptions */ +/** + * Constructor for a streaming GridFS interface + * @public + */ +export declare class GridFSBucket extends TypedEventEmitter { + /* Excluded from this release type: s */ + /** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * @event + */ + static readonly INDEX: "index"; + constructor(db: Db, options?: GridFSBucketOptions); + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + openUploadStream(filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream; + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + */ + openUploadStreamWithId(id: ObjectId, filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream; + /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ + openDownloadStream(id: ObjectId, options?: GridFSBucketReadStreamOptions): GridFSBucketReadStream; + /** + * Deletes a file with the given id + * + * @param id - The id of the file doc + */ + delete(id: ObjectId): Promise; + delete(id: ObjectId, callback: Callback): void; + /** Convenience wrapper around find on the files collection */ + find(filter?: Filter, options?: FindOptions): FindCursor; + /** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + */ + openDownloadStreamByName(filename: string, options?: GridFSBucketReadStreamOptionsWithRevision): GridFSBucketReadStream; + /** + * Renames the file with the given _id to the given string + * + * @param id - the id of the file to rename + * @param filename - new name for the file + */ + rename(id: ObjectId, filename: string): Promise; + rename(id: ObjectId, filename: string, callback: Callback): void; + /** Removes this bucket's files collection, followed by its chunks collection. */ + drop(): Promise; + drop(callback: Callback): void; + /** Get the Db scoped logger. */ + getLogger(): Logger; +} +/** @public */ +export declare type GridFSBucketEvents = { + index(): void; +}; +/** @public */ +export declare interface GridFSBucketOptions extends WriteConcernOptions { + /** The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. */ + bucketName?: string; + /** Number of bytes stored in each chunk. Defaults to 255KB */ + chunkSizeBytes?: number; + /** Read preference to be passed to read operations */ + readPreference?: ReadPreference; +} +/* Excluded from this release type: GridFSBucketPrivate */ +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * @public + */ +export declare class GridFSBucketReadStream extends Readable implements NodeJS.ReadableStream { + /* Excluded from this release type: s */ + /** + * An error occurred + * @event + */ + static readonly ERROR: "error"; + /** + * Fires when the stream loaded the file document corresponding to the provided id. + * @event + */ + static readonly FILE: "file"; + /** + * Emitted when a chunk of data is available to be consumed. + * @event + */ + static readonly DATA: "data"; + /** + * Fired when the stream is exhausted (no more data events). + * @event + */ + static readonly END: "end"; + /** + * Fired when the stream is exhausted and the underlying cursor is killed + * @event + */ + static readonly CLOSE: "close"; + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: _read */ + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param start - 0-based offset in bytes to start streaming from + */ + start(start?: number): this; + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param end - Offset in bytes to stop reading at + */ + end(end?: number): this; + /** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @param callback - called when the cursor is successfully closed or an error occurred. + */ + abort(callback?: Callback): void; +} +/** @public */ +export declare interface GridFSBucketReadStreamOptions { + sort?: Sort; + skip?: number; + /** 0-based offset in bytes to start streaming from */ + start?: number; + /** 0-based offset in bytes to stop streaming before */ + end?: number; +} +/** @public */ +export declare interface GridFSBucketReadStreamOptionsWithRevision extends GridFSBucketReadStreamOptions { + /** The revision number relative to the oldest file with the given filename. 0 + * gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the + * newest. */ + revision?: number; +} +/* Excluded from this release type: GridFSBucketReadStreamPrivate */ +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * @public + */ +export declare class GridFSBucketWriteStream extends Writable implements NodeJS.WritableStream { + bucket: GridFSBucket; + chunks: Collection; + filename: string; + files: Collection; + options: GridFSBucketWriteStreamOptions; + done: boolean; + id: ObjectId; + chunkSizeBytes: number; + bufToStore: Buffer; + length: number; + n: number; + pos: number; + state: { + streamEnd: boolean; + outstandingRequests: number; + errored: boolean; + aborted: boolean; + }; + writeConcern?: WriteConcern; + /** @event */ + static readonly CLOSE = "close"; + /** @event */ + static readonly ERROR = "error"; + /** + * `end()` was called and the write stream successfully wrote the file metadata and all the chunks to MongoDB. + * @event + */ + static readonly FINISH = "finish"; + /* Excluded from this release type: __constructor */ + /** + * Write a buffer to the stream. + * + * @param chunk - Buffer to write + * @param encodingOrCallback - Optional encoding for the buffer + * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @returns False if this write required flushing a chunk to MongoDB. True otherwise. + */ + write(chunk: Buffer | string): boolean; + write(chunk: Buffer | string, callback: Callback): boolean; + write(chunk: Buffer | string, encoding: BufferEncoding | undefined): boolean; + write(chunk: Buffer | string, encoding: BufferEncoding | undefined, callback: Callback): boolean; + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + * + * @param callback - called when chunks are successfully removed or error occurred + */ + abort(): Promise; + abort(callback: Callback): void; + /** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @param chunk - Buffer to write + * @param encoding - Optional encoding for the buffer + * @param callback - Function to call when all files and chunks have been persisted to MongoDB + */ + end(): void; + end(chunk: Buffer): void; + end(callback: Callback): void; + end(chunk: Buffer, callback: Callback): void; + end(chunk: Buffer, encoding: BufferEncoding): void; + end(chunk: Buffer, encoding: BufferEncoding | undefined, callback: Callback): void; +} +/** @public */ +export declare interface GridFSBucketWriteStreamOptions extends WriteConcernOptions { + /** Overwrite this bucket's chunkSizeBytes for this file */ + chunkSizeBytes?: number; + /** Custom file id for the GridFS file. */ + id?: ObjectId; + /** Object to store in the file document's `metadata` field */ + metadata?: Document; + /** String to store in the file document's `contentType` field */ + contentType?: string; + /** Array of strings to store in the file document's `aliases` field */ + aliases?: string[]; +} +/** @public */ +export declare interface GridFSChunk { + _id: ObjectId; + files_id: ObjectId; + n: number; + data: Buffer | Uint8Array; +} +/** @public */ +export declare interface GridFSFile { + _id: ObjectId; + length: number; + chunkSize: number; + filename: string; + contentType?: string; + aliases?: string[]; + metadata?: Document; + uploadDate: Date; +} +/** @public */ +export declare interface HedgeOptions { + /** Explicitly enable or disable hedged reads. */ + enabled?: boolean; +} +/** @public */ +export declare type Hint = string | Document; +/** @public */ +export declare class HostAddress { + host: string | undefined; + port: number | undefined; + socketPath: string | undefined; + isIPv6: boolean | undefined; + constructor(hostString: string); + /** + * @param ipv6Brackets - optionally request ipv6 bracket notation required for connection strings + */ + toString(ipv6Brackets?: boolean): string; + static fromString(s: string): HostAddress; +} +/** @public */ +export declare interface IndexDescription extends Pick { + collation?: CollationOptions; + name?: string; + key: Document; +} +/** @public */ +export declare type IndexDirection = -1 | 1 | '2d' | '2dsphere' | 'text' | 'geoHaystack' | number; +/** @public */ +export declare interface IndexInformationOptions { + full?: boolean; + readPreference?: ReadPreference; + session?: ClientSession; +} +/** @public */ +export declare type IndexSpecification = OneOrMore; +/** Given an object shaped type, return the type of the _id field or default to ObjectId @public */ +export declare type InferIdType = TSchema extends { + _id: infer IdType; +} ? {} extends IdType ? Exclude : unknown extends IdType ? ObjectId : IdType : ObjectId; +/** @public */ +export declare interface InsertManyResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of inserted documents for this operations */ + insertedCount: number; + /** Map of the index of the inserted document to the id of the inserted document */ + insertedIds: { + [key: number]: InferIdType; + }; +} +/** @public */ +export declare interface InsertOneModel { + /** The document to insert. */ + document: OptionalId; +} +/** @public */ +export declare interface InsertOneOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; +} +/** @public */ +export declare interface InsertOneResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The identifier that was inserted. If the server generated the identifier, this value will be null as the driver does not have access to that data */ + insertedId: InferIdType; +} +export { Int32 }; +/** @public */ +export declare type IntegerType = number | Int32 | Long; +/* Excluded from this release type: InternalAbstractCursorOptions */ +/* Excluded from this release type: InterruptibleAsyncInterval */ +/** @public */ +export declare type IsAny = true extends false & Type ? ResultIfAny : ResultIfNotAny; +/* Excluded from this release type: kBeforeHandshake */ +/* Excluded from this release type: kBuffer */ +/* Excluded from this release type: kBuffers */ +/* Excluded from this release type: kBuiltOptions */ +/* Excluded from this release type: kCancellationToken */ +/* Excluded from this release type: kCancellationToken_2 */ +/* Excluded from this release type: kCancelled */ +/* Excluded from this release type: kCancelled_2 */ +/* Excluded from this release type: kCheckedOut */ +/* Excluded from this release type: kClosed */ +/* Excluded from this release type: kClosed_2 */ +/* Excluded from this release type: kClusterTime */ +/* Excluded from this release type: kConnection */ +/* Excluded from this release type: kConnectionCounter */ +/* Excluded from this release type: kConnections */ +/* Excluded from this release type: kCursorStream */ +/* Excluded from this release type: kDescription */ +/* Excluded from this release type: kDocuments */ +/* Excluded from this release type: kErrorLabels */ +/** @public */ +export declare type KeysOfAType = { + [key in keyof TSchema]: NonNullable extends Type ? key : never; +}[keyof TSchema]; +/** @public */ +export declare type KeysOfOtherType = { + [key in keyof TSchema]: NonNullable extends Type ? never : key; +}[keyof TSchema]; +/* Excluded from this release type: kFilter */ +/* Excluded from this release type: kFullResult */ +/* Excluded from this release type: kGeneration */ +/* Excluded from this release type: kGeneration_2 */ +/* Excluded from this release type: kId */ +/* Excluded from this release type: KillCursor */ +/* Excluded from this release type: kInitialized */ +/* Excluded from this release type: kInternalClient */ +/* Excluded from this release type: kIsMaster */ +/* Excluded from this release type: kKilled */ +/* Excluded from this release type: kLastUseTime */ +/* Excluded from this release type: kLength */ +/* Excluded from this release type: kLogger */ +/* Excluded from this release type: kMessageStream */ +/* Excluded from this release type: kMetrics */ +/* Excluded from this release type: kMinPoolSizeTimer */ +/* Excluded from this release type: kMode */ +/* Excluded from this release type: kMonitor */ +/* Excluded from this release type: kMonitorId */ +/* Excluded from this release type: kNamespace */ +/* Excluded from this release type: kNumReturned */ +/* Excluded from this release type: kOptions */ +/* Excluded from this release type: kOptions_2 */ +/* Excluded from this release type: kOptions_3 */ +/* Excluded from this release type: kPermits */ +/* Excluded from this release type: kPinnedConnection */ +/* Excluded from this release type: kPipeline */ +/* Excluded from this release type: kProcessingWaitQueue */ +/* Excluded from this release type: kQueue */ +/* Excluded from this release type: kResumeQueue */ +/* Excluded from this release type: kRoundTripTime */ +/* Excluded from this release type: kRTTPinger */ +/* Excluded from this release type: kServer */ +/* Excluded from this release type: kServer_2 */ +/* Excluded from this release type: kServerError */ +/* Excluded from this release type: kServerSession */ +/* Excluded from this release type: kServiceGenerations */ +/* Excluded from this release type: kSession */ +/* Excluded from this release type: kSession_2 */ +/* Excluded from this release type: kSnapshotEnabled */ +/* Excluded from this release type: kSnapshotTime */ +/* Excluded from this release type: kStream */ +/* Excluded from this release type: kTopology */ +/* Excluded from this release type: kTransform */ +/* Excluded from this release type: kWaitQueue */ +/* Excluded from this release type: kWaitQueue_2 */ +/** @public */ +export declare const LEGAL_TCP_SOCKET_OPTIONS: readonly [ + "family", + "hints", + "localAddress", + "localPort", + "lookup" +]; +/** @public */ +export declare const LEGAL_TLS_SOCKET_OPTIONS: readonly [ + "ALPNProtocols", + "ca", + "cert", + "checkServerIdentity", + "ciphers", + "crl", + "ecdhCurve", + "key", + "minDHSize", + "passphrase", + "pfx", + "rejectUnauthorized", + "secureContext", + "secureProtocol", + "servername", + "session" +]; +/** @public */ +export declare class ListCollectionsCursor | CollectionInfo = Pick | CollectionInfo> extends AbstractCursor { + parent: Db; + filter: Document; + options?: ListCollectionsOptions; + constructor(db: Db, filter: Document, options?: ListCollectionsOptions); + clone(): ListCollectionsCursor; +} +/** @public */ +export declare interface ListCollectionsOptions extends CommandOperationOptions { + /** Since 4.0: If true, will only return the collection name in the response, and will omit additional info */ + nameOnly?: boolean; + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} +/** @public */ +export declare interface ListDatabasesOptions extends CommandOperationOptions { + /** A query predicate that determines which databases are listed */ + filter?: Document; + /** A flag to indicate whether the command should return just the database names, or return both database names and size information */ + nameOnly?: boolean; + /** A flag that determines which databases are returned based on the user privileges when access control is enabled */ + authorizedDatabases?: boolean; +} +/** @public */ +export declare type ListDatabasesResult = string[] | Document[]; +/** @public */ +export declare class ListIndexesCursor extends AbstractCursor { + parent: Collection; + options?: ListIndexesOptions; + constructor(collection: Collection, options?: ListIndexesOptions); + clone(): ListIndexesCursor; +} +/** @public */ +export declare interface ListIndexesOptions extends CommandOperationOptions { + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} +/** + * @public + */ +export declare class Logger { + className: string; + /** + * Creates a new Logger instance + * + * @param className - The Class name associated with the logging instance + * @param options - Optional logging settings + */ + constructor(className: string, options?: LoggerOptions); + /** + * Log a message at the debug level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + debug(message: string, object?: unknown): void; + /** + * Log a message at the warn level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + warn(message: string, object?: unknown): void; + /** + * Log a message at the info level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + info(message: string, object?: unknown): void; + /** + * Log a message at the error level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + error(message: string, object?: unknown): void; + /** Is the logger set at info level */ + isInfo(): boolean; + /** Is the logger set at error level */ + isError(): boolean; + /** Is the logger set at error level */ + isWarn(): boolean; + /** Is the logger set at debug level */ + isDebug(): boolean; + /** Resets the logger to default settings, error and no filtered classes */ + static reset(): void; + /** Get the current logger function */ + static currentLogger(): LoggerFunction; + /** + * Set the current logger function + * + * @param logger - Custom logging function + */ + static setCurrentLogger(logger: LoggerFunction): void; + /** + * Filter log messages for a particular class + * + * @param type - The type of filter (currently only class) + * @param values - The filters to apply + */ + static filter(type: string, values: string[]): void; + /** + * Set the current log level + * + * @param newLevel - Set current log level (debug, warn, info, error) + */ + static setLevel(newLevel: LoggerLevel): void; +} +/** @public */ +export declare type LoggerFunction = (message?: any, ...optionalParams: any[]) => void; +/** @public */ +export declare const LoggerLevel: Readonly<{ + readonly ERROR: "error"; + readonly WARN: "warn"; + readonly INFO: "info"; + readonly DEBUG: "debug"; + readonly error: "error"; + readonly warn: "warn"; + readonly info: "info"; + readonly debug: "debug"; +}>; +/** @public */ +export declare type LoggerLevel = typeof LoggerLevel[keyof typeof LoggerLevel]; +/** @public */ +export declare interface LoggerOptions { + logger?: LoggerFunction; + loggerLevel?: LoggerLevel; +} +export { Long }; +export { Map_2 as Map }; +/** @public */ +export declare type MapFunction = (this: TSchema) => void; +/** @public */ +export declare interface MapReduceOptions extends CommandOperationOptions { + /** Sets the output target for the map reduce job. */ + out?: 'inline' | { + inline: 1; + } | { + replace: string; + } | { + merge: string; + } | { + reduce: string; + }; + /** Query filter object. */ + query?: Document; + /** Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. */ + sort?: Sort; + /** Number of objects to return from collection. */ + limit?: number; + /** Keep temporary data. */ + keeptemp?: boolean; + /** Finalize function. */ + finalize?: FinalizeFunction | string; + /** Can pass in variables that can be access from map/reduce/finalize. */ + scope?: Document; + /** It is possible to make the execution stay in JS. Provided in MongoDB \> 2.0.X. */ + jsMode?: boolean; + /** Provide statistics on job execution time. */ + verbose?: boolean; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; +} +/** @public */ +export declare type MatchKeysAndValues = Readonly> & Record; +export { MaxKey }; +/* Excluded from this release type: MessageStream */ +/* Excluded from this release type: MessageStreamOptions */ +export { MinKey }; +/** @public */ +export declare interface ModifyResult { + value: TSchema | null; + lastErrorObject?: Document; + ok: 0 | 1; +} +/** @public */ +export declare const MONGO_CLIENT_EVENTS: readonly [ + "connectionPoolCreated", + "connectionPoolClosed", + "connectionCreated", + "connectionReady", + "connectionClosed", + "connectionCheckOutStarted", + "connectionCheckOutFailed", + "connectionCheckedOut", + "connectionCheckedIn", + "connectionPoolCleared", + ...("error" | "close" | "commandStarted" | "commandSucceeded" | "commandFailed" | "serverHeartbeatStarted" | "serverHeartbeatSucceeded" | "serverHeartbeatFailed" | "timeout" | "serverOpening" | "serverClosed" | "serverDescriptionChanged" | "topologyOpening" | "topologyClosed" | "topologyDescriptionChanged")[] +]; +/** + * An error generated when the driver API is used incorrectly + * + * @privateRemarks + * Should **never** be directly instantiated + * + * @public + * @category Error + */ +export declare class MongoAPIError extends MongoDriverError { + constructor(message: string); + readonly name: string; +} +/** + * An error generated when a batch command is reexecuted after one of the commands in the batch + * has failed + * + * @public + * @category Error + */ +export declare class MongoBatchReExecutionError extends MongoAPIError { + constructor(message?: string); + readonly name: string; +} +/** + * An error indicating an unsuccessful Bulk Write + * @public + * @category Error + */ +export declare class MongoBulkWriteError extends MongoServerError { + result: BulkWriteResult; + writeErrors: OneOrMore; + err?: WriteConcernError; + /** Creates a new MongoBulkWriteError */ + constructor(error: { + message: string; + code: number; + writeErrors?: WriteError[]; + } | WriteConcernError | AnyError, result: BulkWriteResult); + readonly name: string; + /*Number of documents inserted. */ + readonly insertedCount: number; + /*Number of documents matched for update. */ + readonly matchedCount: number; + /*Number of documents modified. */ + readonly modifiedCount: number; + /*Number of documents deleted. */ + readonly deletedCount: number; + /*Number of documents upserted. */ + readonly upsertedCount: number; + /*Inserted document generated Id's, hash key is the index of the originating operation */ + readonly insertedIds: { + [key: number]: any; + }; + /*Upserted document generated Id's, hash key is the index of the originating operation */ + readonly upsertedIds: { + [key: number]: any; + }; +} +/** + * An error generated when a ChangeStream operation fails to execute. + * + * @public + * @category Error + */ +export declare class MongoChangeStreamError extends MongoRuntimeError { + constructor(message: string); + readonly name: string; +} +/** + * The **MongoClient** class is a class that allows for making Connections to MongoDB. + * @public + * + * @remarks + * The programmatically provided options take precedent over the URI options. + * + * @example + * ```js + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + * + * @example + * ```js + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + */ +export declare class MongoClient extends TypedEventEmitter { + /* Excluded from this release type: s */ + /* Excluded from this release type: topology */ + /* Excluded from this release type: [kOptions] */ + constructor(url: string, options?: MongoClientOptions); + readonly options: Readonly; + readonly serverApi: Readonly; + /*Excluded from this release type: monitorCommands + Excluded from this release type: monitorCommands */ + readonly autoEncrypter: AutoEncrypter | undefined; + readonly readConcern: ReadConcern | undefined; + readonly writeConcern: WriteConcern | undefined; + readonly readPreference: ReadPreference; + readonly bsonOptions: BSONSerializeOptions; + readonly logger: Logger; + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + connect(): Promise; + connect(callback: Callback): void; + /** + * Close the db and its underlying connections + * + * @param force - Force close, emitting no events + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + close(): Promise; + close(callback: Callback): void; + close(force: boolean): Promise; + close(force: boolean, callback: Callback): void; + /** + * Create a new Db instance sharing the current socket connections. + * + * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. + * @param options - Optional settings for Db construction + */ + db(dbName?: string, options?: DbOptions): Db; + /** + * Connect to MongoDB using a url + * + * @remarks + * The programmatically provided options take precedent over the URI options. + * + * @see https://docs.mongodb.org/manual/reference/connection-string/ + */ + static connect(url: string): Promise; + static connect(url: string, callback: Callback): void; + static connect(url: string, options: MongoClientOptions): Promise; + static connect(url: string, options: MongoClientOptions, callback: Callback): void; + /** Starts a new session on the server */ + startSession(): ClientSession; + startSession(options: ClientSessionOptions): ClientSession; + /** + * Runs a given operation with an implicitly created session. The lifetime of the session + * will be handled without the need for user interaction. + * + * NOTE: presently the operation MUST return a Promise (either explicit or implicitly as an async function) + * + * @param options - Optional settings for the command + * @param callback - An callback to execute with an implicitly created session + */ + withSession(callback: WithSessionCallback): Promise; + withSession(options: ClientSessionOptions, callback: WithSessionCallback): Promise; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this cluster. Will ignore all + * changes to system collections, as well as the local, admin, and config databases. + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; + /** Return the mongo client logger */ + getLogger(): Logger; +} +/** @public */ +export declare type MongoClientEvents = Pick & { + open(mongoClient: MongoClient): void; +}; +/** + * Describes all possible URI query options for the mongo client + * @public + * @see https://docs.mongodb.com/manual/reference/connection-string + */ +export declare interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeConnectionOptions { + /** Specifies the name of the replica set, if the mongod is a member of a replica set. */ + replicaSet?: string; + /** Enables or disables TLS/SSL for the connection. */ + tls?: boolean; + /** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */ + ssl?: boolean; + /** Specifies the location of a local TLS Certificate */ + tlsCertificateFile?: string; + /** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key or only the client's TLS/SSL key when tlsCertificateFile is used to provide the certificate. */ + tlsCertificateKeyFile?: string; + /** Specifies the password to de-crypt the tlsCertificateKeyFile. */ + tlsCertificateKeyFilePassword?: string; + /** Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance. */ + tlsCAFile?: string; + /** Bypasses validation of the certificates presented by the mongod/mongos instance */ + tlsAllowInvalidCertificates?: boolean; + /** Disables hostname validation of the certificate presented by the mongod/mongos instance. */ + tlsAllowInvalidHostnames?: boolean; + /** Disables various certificate validations. */ + tlsInsecure?: boolean; + /** The time in milliseconds to attempt a connection before timing out. */ + connectTimeoutMS?: number; + /** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */ + socketTimeoutMS?: number; + /** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */ + compressors?: CompressorName[] | string; + /** An integer that specifies the compression level if using zlib for network compression. */ + zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined; + /** The maximum number of connections in the connection pool. */ + maxPoolSize?: number; + /** The minimum number of connections in the connection pool. */ + minPoolSize?: number; + /** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */ + maxIdleTimeMS?: number; + /** The maximum time in milliseconds that a thread can wait for a connection to become available. */ + waitQueueTimeoutMS?: number; + /** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The level of isolation */ + readConcernLevel?: ReadConcernLevel; + /** Specifies the read preferences for this connection */ + readPreference?: ReadPreferenceMode | ReadPreference; + /** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */ + maxStalenessSeconds?: number; + /** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */ + readPreferenceTags?: TagSet[]; + /** The auth settings for when connection to server. */ + auth?: Auth; + /** Specify the database name associated with the user’s credentials. */ + authSource?: string; + /** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */ + authMechanism?: AuthMechanism; + /** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */ + authMechanismProperties?: AuthMechanismProperties; + /** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */ + localThresholdMS?: number; + /** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */ + serverSelectionTimeoutMS?: number; + /** heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one. */ + heartbeatFrequencyMS?: number; + /** Sets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort. */ + minHeartbeatFrequencyMS?: number; + /** The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections */ + appName?: string; + /** Enables retryable reads. */ + retryReads?: boolean; + /** Enable retryable writes. */ + retryWrites?: boolean; + /** Allow a driver to force a Single topology type with a connection string containing one host */ + directConnection?: boolean; + /** Instruct the driver it is connecting to a load balancer fronting a mongos like service */ + loadBalanced?: boolean; + /** The write concern w value */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + /** Validate mongod server certificate against Certificate Authority */ + sslValidate?: boolean; + /** SSL Certificate file path. */ + sslCA?: string; + /** SSL Certificate file path. */ + sslCert?: string; + /** SSL Key file file path. */ + sslKey?: string; + /** SSL Certificate pass phrase. */ + sslPass?: string; + /** SSL Certificate revocation list file path. */ + sslCRL?: string; + /** TCP Connection no delay */ + noDelay?: boolean; + /** TCP Connection keep alive enabled */ + keepAlive?: boolean; + /** The number of milliseconds to wait before initiating keepAlive on the TCP socket */ + keepAliveInitialDelay?: number; + /** Force server to assign `_id` values instead of driver */ + forceServerObjectId?: boolean; + /** Return document results as raw BSON buffers */ + raw?: boolean; + /** A primary key factory function for generation of custom `_id` keys */ + pkFactory?: PkFactory; + /** A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible */ + promiseLibrary?: any; + /** The logging level */ + loggerLevel?: LoggerLevel; + /** Custom logger object */ + logger?: Logger; + /** Enable command monitoring for this client */ + monitorCommands?: boolean; + /** Server API version */ + serverApi?: ServerApi | ServerApiVersion; + /** + * Optionally enable client side auto encryption + * + * @remarks + * Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error + * (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts. + * + * Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://docs.mongodb.com/manual/reference/command/listCollections/#dbcmd.listCollections). + * + * If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true: + * - AutoEncryptionOptions.keyVaultClient is not passed. + * - AutoEncryptionOptions.bypassAutomaticEncryption is false. + * + * If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted. + */ + autoEncryption?: AutoEncryptionOptions; + /** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */ + driverInfo?: DriverInfo; +} +/* Excluded from this release type: MongoClientPrivate */ +/** + * An error generated when a feature that is not enabled or allowed for the current server + * configuration is used + * + * + * @public + * @category Error + */ +export declare class MongoCompatibilityError extends MongoAPIError { + constructor(message: string); + readonly name: string; +} +/** + * A representation of the credentials used by MongoDB + * @public + */ +export declare class MongoCredentials { + /** The username used for authentication */ + readonly username: string; + /** The password used for authentication */ + readonly password: string; + /** The database that the user should authenticate against */ + readonly source: string; + /** The method used to authenticate */ + readonly mechanism: AuthMechanism; + /** Special properties used by some types of auth mechanisms */ + readonly mechanismProperties: AuthMechanismProperties; + constructor(options: MongoCredentialsOptions); + /** Determines if two MongoCredentials objects are equivalent */ + equals(other: MongoCredentials): boolean; + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param ismaster - An ismaster response from the server + */ + resolveAuthMechanism(ismaster?: Document): MongoCredentials; + validate(): void; + static merge(creds: MongoCredentials | undefined, options: Partial): MongoCredentials; +} +/** @public */ +export declare interface MongoCredentialsOptions { + username: string; + password: string; + source: string; + db?: string; + mechanism?: AuthMechanism; + mechanismProperties: AuthMechanismProperties; +} +/** + * An error thrown when an attempt is made to read from a cursor that has been exhausted + * + * @public + * @category Error + */ +export declare class MongoCursorExhaustedError extends MongoAPIError { + constructor(message?: string); + readonly name: string; +} +/** + * An error thrown when the user attempts to add options to a cursor that has already been + * initialized + * + * @public + * @category Error + */ +export declare class MongoCursorInUseError extends MongoAPIError { + constructor(message?: string); + readonly name: string; +} +/** @public */ +export declare class MongoDBNamespace { + db: string; + collection?: string; + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(db: string, collection?: string); + toString(): string; + withCollection(collection: string): MongoDBNamespace; + static fromString(namespace?: string): MongoDBNamespace; +} +/** + * An error generated when the driver fails to decompress + * data received from the server. + * + * @public + * @category Error + */ +export declare class MongoDecompressionError extends MongoRuntimeError { + constructor(message: string); + readonly name: string; +} +/** + * An error generated by the driver + * + * @public + * @category Error + */ +export declare class MongoDriverError extends MongoError { + constructor(message: string); + readonly name: string; +} +/** + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error, it uses the constructor with a string argument + */ +export declare class MongoError extends Error { + /* Excluded from this release type: [kErrorLabels] */ + /** + * This is a number in MongoServerError and a string in MongoDriverError + * @privateRemarks + * Define the type override on the subclasses when we can use the override keyword + */ + code?: number | string; + topologyVersion?: TopologyVersion; + constructor(message: string | Error); + readonly name: string; + /*Legacy name for server error responses */ + readonly errmsg: string; + /** + * Checks the error to see if it has an error label + * + * @param label - The error label to check for + * @returns returns true if the error has the provided error label + */ + hasErrorLabel(label: string): boolean; + addErrorLabel(label: string): void; + readonly errorLabels: string[]; +} +/** + * An error generated when the user attempts to operate + * on a session that has expired or has been closed. + * + * @public + * @category Error + */ +export declare class MongoExpiredSessionError extends MongoAPIError { + constructor(message?: string); + readonly name: string; +} +/** + * An error generated when a malformed or invalid chunk is + * encountered when reading from a GridFSStream. + * + * @public + * @category Error + */ +export declare class MongoGridFSChunkError extends MongoRuntimeError { + constructor(message: string); + readonly name: string; +} +/** An error generated when a GridFSStream operation fails to execute. + * + * @public + * @category Error + */ +export declare class MongoGridFSStreamError extends MongoRuntimeError { + constructor(message: string); + readonly name: string; +} +/** + * An error generated when the user supplies malformed or unexpected arguments + * or when a required argument or field is not provided. + * + * + * @public + * @category Error + */ +export declare class MongoInvalidArgumentError extends MongoAPIError { + constructor(message: string); + readonly name: string; +} +/** + * A error generated when the user attempts to authenticate + * via Kerberos, but fails to connect to the Kerberos client. + * + * @public + * @category Error + */ +export declare class MongoKerberosError extends MongoRuntimeError { + constructor(message: string); + readonly name: string; +} +/** + * An error generated when the user fails to provide authentication credentials before attempting + * to connect to a mongo server instance. + * + * + * @public + * @category Error + */ +export declare class MongoMissingCredentialsError extends MongoAPIError { + constructor(message: string); + readonly name: string; +} +/** + * An error generated when a required module or dependency is not present in the local environment + * + * @public + * @category Error + */ +export declare class MongoMissingDependencyError extends MongoAPIError { + constructor(message: string); + readonly name: string; +} +/** + * An error indicating an issue with the network, including TCP errors and timeouts. + * @public + * @category Error + */ +export declare class MongoNetworkError extends MongoError { + /* Excluded from this release type: [kBeforeHandshake] */ + constructor(message: string | Error, options?: MongoNetworkErrorOptions); + readonly name: string; +} +/** @public */ +export declare interface MongoNetworkErrorOptions { + /** Indicates the timeout happened before a connection handshake completed */ + beforeHandshake: boolean; +} +/** + * An error indicating a network timeout occurred + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error with an instanceof check + */ +export declare class MongoNetworkTimeoutError extends MongoNetworkError { + constructor(message: string, options?: MongoNetworkErrorOptions); + readonly name: string; +} +/** + * An error thrown when the user attempts to operate on a database or collection through a MongoClient + * that has not yet successfully called the "connect" method + * + * @public + * @category Error + */ +export declare class MongoNotConnectedError extends MongoAPIError { + constructor(message: string); + readonly name: string; +} +/** + * Mongo Client Options + * @public + */ +export declare interface MongoOptions extends Required>, SupportedNodeConnectionOptions { + hosts: HostAddress[]; + srvHost?: string; + credentials?: MongoCredentials; + readPreference: ReadPreference; + readConcern: ReadConcern; + loadBalanced: boolean; + serverApi: ServerApi; + compressors: CompressorName[]; + writeConcern: WriteConcern; + dbName: string; + metadata: ClientMetadata; + autoEncrypter?: AutoEncrypter; + /* Excluded from this release type: connectionType */ + /* Excluded from this release type: encrypter */ + /* Excluded from this release type: userSpecifiedAuthSource */ + /* Excluded from this release type: userSpecifiedReplicaSet */ + /** + * # NOTE ABOUT TLS Options + * + * If set TLS enabled, equivalent to setting the ssl option. + * + * ### Additional options: + * + * | nodejs option | MongoDB equivalent | type | + * |:---------------------|--------------------------------------------------------- |:---------------------------------------| + * | `ca` | `sslCA`, `tlsCAFile` | `string \| Buffer \| Buffer[]` | + * | `crl` | `sslCRL` | `string \| Buffer \| Buffer[]` | + * | `cert` | `sslCert`, `tlsCertificateFile`, `tlsCertificateKeyFile` | `string \| Buffer \| Buffer[]` | + * | `key` | `sslKey`, `tlsCertificateKeyFile` | `string \| Buffer \| KeyObject[]` | + * | `passphrase` | `sslPass`, `tlsCertificateKeyFilePassword` | `string` | + * | `rejectUnauthorized` | `sslValidate` | `boolean` | + * + */ + tls: boolean; + /** + * Turn these options into a reusable connection URI + */ + toURI(): string; +} +/** + * An error used when attempting to parse a value (like a connection string) + * @public + * @category Error + */ +export declare class MongoParseError extends MongoDriverError { + constructor(message: string); + readonly name: string; +} +/** + * An error generated when the driver encounters unexpected input + * or reaches an unexpected/invalid internal state + * + * @privateRemarks + * Should **never** be directly instantiated. + * + * @public + * @category Error + */ +export declare class MongoRuntimeError extends MongoDriverError { + constructor(message: string); + readonly name: string; +} +/** + * An error generated when an attempt is made to operate + * on a closed/closing server. + * + * @public + * @category Error + */ +export declare class MongoServerClosedError extends MongoAPIError { + constructor(message?: string); + readonly name: string; +} +/** + * An error coming from the mongo server + * + * @public + * @category Error + */ +export declare class MongoServerError extends MongoError { + codeName?: string; + writeConcernError?: Document; + errInfo?: Document; + ok?: number; + [key: string]: any; + constructor(message: ErrorDescription); + readonly name: string; +} +/** + * An error signifying a client-side server selection error + * @public + * @category Error + */ +export declare class MongoServerSelectionError extends MongoSystemError { + constructor(message: string, reason: TopologyDescription); + readonly name: string; +} +/** + * An error signifying a general system issue + * @public + * @category Error + */ +export declare class MongoSystemError extends MongoError { + /** An optional reason context, such as an error saved during flow of monitoring and selecting servers */ + reason?: TopologyDescription; + constructor(message: string, reason: TopologyDescription); + readonly name: string; +} +/** + * An error generated when an attempt is made to operate on a + * dropped, or otherwise unavailable, database. + * + * @public + * @category Error + */ +export declare class MongoTopologyClosedError extends MongoAPIError { + constructor(message?: string); + readonly name: string; +} +/** + * An error generated when the user makes a mistake in the usage of transactions. + * (e.g. attempting to commit a transaction with a readPreference other than primary) + * + * @public + * @category Error + */ +export declare class MongoTransactionError extends MongoAPIError { + constructor(message: string); + readonly name: string; +} +/** + * An error thrown when the server reports a writeConcernError + * @public + * @category Error + */ +export declare class MongoWriteConcernError extends MongoServerError { + /** The result document (provided if ok: 1) */ + result?: Document; + errInfo?: Document; + constructor(message: ErrorDescription, result?: Document); + readonly name: string; +} +/* Excluded from this release type: Monitor */ +/** @public */ +export declare type MonitorEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + resetServer(error?: Error): void; + resetConnectionPool(): void; + close(): void; +} & EventEmitterWithState; +/** @public */ +export declare interface MonitorOptions extends Pick> { + connectTimeoutMS: number; + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; +} +/* Excluded from this release type: MonitorPrivate */ +/* Excluded from this release type: Msg */ +/** It avoids using fields with not acceptable types @public */ +export declare type NotAcceptedFields = { + readonly [key in KeysOfOtherType]?: never; +}; +/** @public */ +export declare type NumericType = IntegerType | Decimal128 | Double; +/** + * @public + * @deprecated Please use `ObjectId` + */ +export declare const ObjectID: typeof ObjectId; +export { ObjectId }; +/** @public */ +export declare type OneOrMore = T | ReadonlyArray; +/** @public */ +export declare type OnlyFieldsOfType = IsAny, AcceptedFields & NotAcceptedFields & Record>; +/* Excluded from this release type: OperationDescription */ +/** @public */ +export declare interface OperationOptions extends BSONSerializeOptions { + /** Specify ClientSession for this command */ + session?: ClientSession; + willRetryWrites?: boolean; + /** The preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest). */ + readPreference?: ReadPreferenceLike; +} +/* Excluded from this release type: OperationParent */ +/** + * Represents a specific point in time on a server. Can be retrieved by using {@link Db#command} + * @public + * @remarks + * See {@link https://docs.mongodb.com/manual/reference/method/db.runCommand/#response| Run Command Response} + */ +export declare type OperationTime = Timestamp; +/* Excluded from this release type: OpGetMoreOptions */ +/* Excluded from this release type: OpQueryOptions */ +/** + * Add an optional _id field to an object shaped type + * @public + * + * @privateRemarks + * `ObjectId extends TSchema['_id']` is a confusing ordering at first glance. Rather than ask + * `TSchema['_id'] extends ObjectId` which translated to "Is the _id property ObjectId?" + * we instead ask "Does ObjectId look like (have the same shape) as the _id?" + */ +export declare type OptionalId = ObjectId extends TSchema['_id'] ? EnhancedOmit & { + _id?: InferIdType; +} : WithId; +/** @public */ +export declare class OrderedBulkOperation extends BulkOperationBase { + constructor(collection: Collection, options: BulkWriteOptions); + addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} +/** @public */ +export declare interface PipeOptions { + end?: boolean; +} +/** @public */ +export declare interface PkFactory { + createPk(): any; +} +/** @public */ +export declare const ProfilingLevel: Readonly<{ + readonly off: "off"; + readonly slowOnly: "slow_only"; + readonly all: "all"; +}>; +/** @public */ +export declare type ProfilingLevel = typeof ProfilingLevel[keyof typeof ProfilingLevel]; +/** @public */ +export declare type ProfilingLevelOptions = CommandOperationOptions; +/** + * @public + * Projection is flexible to permit the wide array of aggregation operators + * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further + */ +export declare type Projection = Document; +/** + * @public + * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further + */ +export declare type ProjectionOperators = Document; +/** + * Global promise store allowing user-provided promises + * @public + */ +declare class Promise_2 { + /** Validates the passed in promise library */ + static validate(lib: unknown): lib is PromiseConstructor; + /** Sets the promise library */ + static set(lib: PromiseConstructor): void; + /** Get the stored promise library, or resolves passed in */ + static get(): PromiseConstructor; +} +export { Promise_2 as Promise }; +/** @public */ +export declare type PullAllOperator = ({ + readonly [key in KeysOfAType>]?: TSchema[key]; +} & NotAcceptedFields>) & { + readonly [key: string]: ReadonlyArray; +}; +/** @public */ +export declare type PullOperator = ({ + readonly [key in KeysOfAType>]?: Partial> | FilterOperations>; +} & NotAcceptedFields>) & { + readonly [key: string]: FilterOperators | any; +}; +/** @public */ +export declare type PushOperator = ({ + readonly [key in KeysOfAType>]?: Flatten | ArrayOperator>>; +} & NotAcceptedFields>) & { + readonly [key: string]: ArrayOperator | any; +}; +/* Excluded from this release type: Query */ +/* Excluded from this release type: QueryOptions */ +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @public + * + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html + */ +export declare class ReadConcern { + level: ReadConcernLevel | string; + /** Constructs a ReadConcern from the read concern level.*/ + constructor(level: ReadConcernLevel); + /** + * Construct a ReadConcern given an options object. + * + * @param options - The options object from which to extract the write concern. + */ + static fromOptions(options?: { + readConcern?: ReadConcernLike; + level?: ReadConcernLevel; + }): ReadConcern | undefined; + static readonly MAJORITY: 'majority'; + static readonly AVAILABLE: 'available'; + static readonly LINEARIZABLE: 'linearizable'; + static readonly SNAPSHOT: 'snapshot'; + toJSON(): Document; +} +/** @public */ +export declare const ReadConcernLevel: Readonly<{ + readonly local: "local"; + readonly majority: "majority"; + readonly linearizable: "linearizable"; + readonly available: "available"; + readonly snapshot: "snapshot"; +}>; +/** @public */ +export declare type ReadConcernLevel = typeof ReadConcernLevel[keyof typeof ReadConcernLevel]; +/** @public */ +export declare type ReadConcernLike = ReadConcern | { + level: ReadConcernLevel; +} | ReadConcernLevel; +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @public + * + * @see https://docs.mongodb.com/manual/core/read-preference/ + */ +export declare class ReadPreference { + mode: ReadPreferenceMode; + tags?: TagSet[]; + hedge?: HedgeOptions; + maxStalenessSeconds?: number; + minWireVersion?: number; + static PRIMARY: "primary"; + static PRIMARY_PREFERRED: "primaryPreferred"; + static SECONDARY: "secondary"; + static SECONDARY_PREFERRED: "secondaryPreferred"; + static NEAREST: "nearest"; + static primary: ReadPreference; + static primaryPreferred: ReadPreference; + static secondary: ReadPreference; + static secondaryPreferred: ReadPreference; + static nearest: ReadPreference; + /** + * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. + * @param options - Additional read preference options + */ + constructor(mode: ReadPreferenceMode, tags?: TagSet[], options?: ReadPreferenceOptions); + readonly preference: ReadPreferenceMode; + static fromString(mode: string): ReadPreference; + /** + * Construct a ReadPreference given an options object. + * + * @param options - The options object from which to extract the read preference. + */ + static fromOptions(options?: ReadPreferenceFromOptions): ReadPreference | undefined; + /** + * Replaces options.readPreference with a ReadPreference instance + */ + static translate(options: ReadPreferenceLikeOptions): ReadPreferenceLikeOptions; + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + static isValid(mode: string): boolean; + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + isValid(mode?: string): boolean; + /** + * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire + * + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ + slaveOk(): boolean; + /** + * Check if the two ReadPreferences are equivalent + * + * @param readPreference - The read preference with which to check equality + */ + equals(readPreference: ReadPreference): boolean; + /** Return JSON representation */ + toJSON(): Document; +} +/** @public */ +export declare interface ReadPreferenceFromOptions extends ReadPreferenceLikeOptions { + session?: ClientSession; + readPreferenceTags?: TagSet[]; + hedge?: HedgeOptions; +} +/** @public */ +export declare type ReadPreferenceLike = ReadPreference | ReadPreferenceMode; +/** @public */ +export declare interface ReadPreferenceLikeOptions extends ReadPreferenceOptions { + readPreference?: ReadPreferenceLike | { + mode?: ReadPreferenceMode; + preference?: ReadPreferenceMode; + tags?: TagSet[]; + maxStalenessSeconds?: number; + }; +} +/** @public */ +export declare const ReadPreferenceMode: Readonly<{ + readonly primary: "primary"; + readonly primaryPreferred: "primaryPreferred"; + readonly secondary: "secondary"; + readonly secondaryPreferred: "secondaryPreferred"; + readonly nearest: "nearest"; +}>; +/** @public */ +export declare type ReadPreferenceMode = typeof ReadPreferenceMode[keyof typeof ReadPreferenceMode]; +/** @public */ +export declare interface ReadPreferenceOptions { + /** Max secondary read staleness in seconds, Minimum value is 90 seconds.*/ + maxStalenessSeconds?: number; + /** Server mode in which the same query is dispatched in parallel to multiple replica set members. */ + hedge?: HedgeOptions; +} +/** @public */ +export declare type ReduceFunction = (key: TKey, values: TValue[]) => TValue; +/** @public */ +export declare type RegExpOrString = T extends string ? BSONRegExp | RegExp | T : T; +/** @public */ +export declare type RemoveUserOptions = CommandOperationOptions; +/** @public */ +export declare interface RenameOptions extends CommandOperationOptions { + /** Drop the target name collection if it previously exists. */ + dropTarget?: boolean; + /** Unclear */ + new_collection?: boolean; +} +/** @public */ +export declare interface ReplaceOneModel { + /** The filter to limit the replaced document. */ + filter: Filter; + /** The document with which to replace the matched document. */ + replacement: TSchema; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} +/** @public */ +export declare interface ReplaceOptions extends CommandOperationOptions { + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; +} +/** @public */ +export declare interface ResumeOptions { + startAtOperationTime?: Timestamp; + batchSize?: number; + maxAwaitTimeMS?: number; + collation?: CollationOptions; + readPreference?: ReadPreference; +} +/** + * Represents the logical starting point for a new or resuming {@link https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token| Change Stream} on the server. + * @public + */ +export declare type ResumeToken = unknown; +/** @public */ +export declare const ReturnDocument: Readonly<{ + readonly BEFORE: "before"; + readonly AFTER: "after"; +}>; +/** @public */ +export declare type ReturnDocument = typeof ReturnDocument[keyof typeof ReturnDocument]; +/** @public */ +export declare interface RoleSpecification { + /** + * A role grants privileges to perform sets of actions on defined resources. + * A given role applies to the database on which it is defined and can grant access down to a collection level of granularity. + */ + role: string; + /** The database this user's role should effect. */ + db: string; +} +/** @public */ +export declare interface RootFilterOperators extends Document { + $and?: Filter[]; + $nor?: Filter[]; + $or?: Filter[]; + $text?: { + $search: string; + $language?: string; + $caseSensitive?: boolean; + $diacriticSensitive?: boolean; + }; + $where?: string | ((this: TSchema) => boolean); + $comment?: string | Document; +} +/* Excluded from this release type: RTTPinger */ +/* Excluded from this release type: RTTPingerOptions */ +/** @public */ +export declare type RunCommandOptions = CommandOperationOptions; +/** @public */ +export declare type SchemaMember = { + [P in keyof T]?: V; +} | { + [key: string]: V; +}; +/** @public */ +export declare interface SelectServerOptions { + readPreference?: ReadPreferenceLike; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS?: number; + session?: ClientSession; +} +/* Excluded from this release type: serialize */ +/* Excluded from this release type: Server */ +/** @public */ +export declare interface ServerApi { + version: ServerApiVersion; + strict?: boolean; + deprecationErrors?: boolean; +} +/** @public */ +export declare const ServerApiVersion: Readonly<{ + readonly v1: "1"; +}>; +/** @public */ +export declare type ServerApiVersion = typeof ServerApiVersion[keyof typeof ServerApiVersion]; +/** @public */ +export declare class ServerCapabilities { + maxWireVersion: number; + minWireVersion: number; + constructor(ismaster: Document); + readonly hasAggregationCursor: boolean; + readonly hasWriteCommands: boolean; + readonly hasTextSearch: boolean; + readonly hasAuthCommands: boolean; + readonly hasListCollectionsCommand: boolean; + readonly hasListIndexesCommand: boolean; + readonly supportsSnapshotReads: boolean; + readonly commandsTakeWriteConcern: boolean; + readonly commandsTakeCollation: boolean; +} +/** + * Emitted when server is closed. + * @public + * @category Event + */ +export declare class ServerClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; +} +/** + * The client's view of a single server, based on the most recent ismaster outcome. + * + * Internal type, not meant to be directly instantiated + * @public + */ +export declare class ServerDescription { + private _hostAddress; + address: string; + type: ServerType; + hosts: string[]; + passives: string[]; + arbiters: string[]; + tags: TagSet; + error?: MongoError; + topologyVersion?: TopologyVersion; + minWireVersion: number; + maxWireVersion: number; + roundTripTime: number; + lastUpdateTime: number; + lastWriteDate: number; + me?: string; + primary?: string; + setName?: string; + setVersion?: number; + electionId?: ObjectId; + logicalSessionTimeoutMinutes?: number; + $clusterTime?: ClusterTime; + /*Excluded from this release type: __constructor */ + readonly hostAddress: HostAddress; + readonly allHosts: string[]; + /*Is this server available for reads*/ + readonly isReadable: boolean; + /*Is this server data bearing */ + readonly isDataBearing: boolean; + /*Is this server available for writes */ + readonly isWritable: boolean; + readonly host: string; + readonly port: number; + /** + * Determines if another `ServerDescription` is equal to this one per the rules defined + * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} + */ + equals(other: ServerDescription): boolean; +} +/** + * Emitted when server description changes, but does NOT include changes to the RTT. + * @public + * @category Event + */ +export declare class ServerDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /** The previous server description */ + previousDescription: ServerDescription; + /** The new server description */ + newDescription: ServerDescription; +} +/* Excluded from this release type: ServerDescriptionOptions */ +/** @public */ +export declare type ServerEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + /* Excluded from this release type: connect */ + descriptionReceived(description: ServerDescription): void; + closed(): void; + ended(): void; +} & ConnectionPoolEvents & EventEmitterWithState; +/** + * Emitted when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. + * @public + * @category Event + */ +export declare class ServerHeartbeatFailedEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command failure */ + failure: Error; +} +/** + * Emitted when the server monitor’s ismaster command is started - immediately before + * the ismaster command is serialized into raw BSON and written to the socket. + * + * @public + * @category Event + */ +export declare class ServerHeartbeatStartedEvent { + /** The connection id for the command */ + connectionId: string; +} +/** + * Emitted when the server monitor’s ismaster succeeds. + * @public + * @category Event + */ +export declare class ServerHeartbeatSucceededEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command reply */ + reply: Document; +} +/** + * Emitted when server is initialized. + * @public + * @category Event + */ +export declare class ServerOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; +} +/** @public */ +export declare type ServerOptions = Pick> & MonitorOptions; +/* Excluded from this release type: ServerPrivate */ +/* Excluded from this release type: ServerSelectionCallback */ +/* Excluded from this release type: ServerSelectionRequest */ +/** @public */ +export declare type ServerSelector = (topologyDescription: TopologyDescription, servers: ServerDescription[]) => ServerDescription[]; +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @public + */ +export declare class ServerSession { + id: ServerSessionId; + lastUse: number; + txnNumber: number; + isDirty: boolean; + /* Excluded from this release type: __constructor */ + /** + * Determines if the server session has timed out. + * + * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" + */ + hasTimedOut(sessionTimeoutMinutes: number): boolean; +} +/** @public */ +export declare type ServerSessionId = { + id: Binary; +}; +/* Excluded from this release type: ServerSessionPool */ +/** + * An enumeration of server types we know about + * @public + */ +export declare const ServerType: Readonly<{ + readonly Standalone: "Standalone"; + readonly Mongos: "Mongos"; + readonly PossiblePrimary: "PossiblePrimary"; + readonly RSPrimary: "RSPrimary"; + readonly RSSecondary: "RSSecondary"; + readonly RSArbiter: "RSArbiter"; + readonly RSOther: "RSOther"; + readonly RSGhost: "RSGhost"; + readonly Unknown: "Unknown"; + readonly LoadBalancer: "LoadBalancer"; +}>; +/** @public */ +export declare type ServerType = typeof ServerType[keyof typeof ServerType]; +/** @public */ +export declare type SetFields = ({ + readonly [key in KeysOfAType | undefined>]?: OptionalId> | AddToSetOperators>>>; +} & NotAcceptedFields | undefined>) & { + readonly [key: string]: AddToSetOperators | any; +}; +/** @public */ +export declare type SetProfilingLevelOptions = CommandOperationOptions; +/** @public */ +export declare type Sort = string | Exclude | string[] | { + [key: string]: SortDirection; +} | Map | [ + string, + SortDirection +][] | [ + string, + SortDirection +]; +/** @public */ +export declare type SortDirection = 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending' | { + $meta: string; +}; +/* Excluded from this release type: SortDirectionForCmd */ +/* Excluded from this release type: SortForCmd */ +/* Excluded from this release type: SrvPoller */ +/* Excluded from this release type: SrvPollerEvents */ +/* Excluded from this release type: SrvPollerOptions */ +/* Excluded from this release type: SrvPollingEvent */ +/** @public */ +export declare type Stream = Socket | TLSSocket; +/** @public */ +export declare class StreamDescription { + address: string; + type: string; + minWireVersion?: number; + maxWireVersion?: number; + maxBsonObjectSize: number; + maxMessageSizeBytes: number; + maxWriteBatchSize: number; + compressors: CompressorName[]; + compressor?: CompressorName; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; + __nodejs_mock_server__?: boolean; + zlibCompressionLevel?: number; + constructor(address: string, options?: StreamDescriptionOptions); + receiveResponse(response: Document): void; +} +/** @public */ +export declare interface StreamDescriptionOptions { + compressors?: CompressorName[]; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; +} +/** @public */ +export declare type SupportedNodeConnectionOptions = SupportedTLSConnectionOptions & SupportedTLSSocketOptions & SupportedSocketOptions; +/** @public */ +export declare type SupportedSocketOptions = Pick; +/** @public */ +export declare type SupportedTLSConnectionOptions = Pick>; +/** @public */ +export declare type SupportedTLSSocketOptions = Pick>; +/** @public */ +export declare type TagSet = { + [key: string]: string; +}; +/* Excluded from this release type: TimerQueue */ +/** @public + * Configuration options for timeseries collections + * @see https://docs.mongodb.com/manual/core/timeseries-collections/ + */ +export declare interface TimeSeriesCollectionOptions extends Document { + timeField: string; + metaField?: string; + granularity?: string; +} +export { Timestamp }; +/* Excluded from this release type: Topology */ +/** + * Emitted when topology is closed. + * @public + * @category Event + */ +export declare class TopologyClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; +} +/** + * Representation of a deployment of servers + * @public + */ +export declare class TopologyDescription { + type: TopologyType; + setName?: string; + maxSetVersion?: number; + maxElectionId?: ObjectId; + servers: Map; + stale: boolean; + compatible: boolean; + compatibilityError?: string; + logicalSessionTimeoutMinutes?: number; + heartbeatFrequencyMS: number; + localThresholdMS: number; + commonWireVersion?: number; + /** + * Create a TopologyDescription + */ + constructor(topologyType: TopologyType, serverDescriptions?: Map, setName?: string, maxSetVersion?: number, maxElectionId?: ObjectId, commonWireVersion?: number, options?: TopologyDescriptionOptions); + /*Excluded from this release type: updateFromSrvPollingEvent + Excluded from this release type: update */ + readonly error: MongoError | undefined; + /* + * Determines if the topology description has any known servers + */ + readonly hasKnownServers: boolean; + /* + * Determines if this topology description has a data-bearing server available. + */ + readonly hasDataBearingServers: boolean; +} +/** + * Emitted when topology description changes. + * @public + * @category Event + */ +export declare class TopologyDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The old topology description */ + previousDescription: TopologyDescription; + /** The new topology description */ + newDescription: TopologyDescription; +} +/** @public */ +export declare interface TopologyDescriptionOptions { + heartbeatFrequencyMS?: number; + localThresholdMS?: number; +} +/** @public */ +export declare type TopologyEvents = { + /* Excluded from this release type: connect */ + serverOpening(event: ServerOpeningEvent): void; + serverClosed(event: ServerClosedEvent): void; + serverDescriptionChanged(event: ServerDescriptionChangedEvent): void; + topologyClosed(event: TopologyClosedEvent): void; + topologyOpening(event: TopologyOpeningEvent): void; + topologyDescriptionChanged(event: TopologyDescriptionChangedEvent): void; + error(error: Error): void; + /* Excluded from this release type: open */ + close(): void; + timeout(): void; +} & Pick> & ConnectionPoolEvents & ConnectionEvents & EventEmitterWithState; +/** + * Emitted when topology is initialized. + * @public + * @category Event + */ +export declare class TopologyOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; +} +/** @public */ +export declare interface TopologyOptions extends BSONSerializeOptions, ServerOptions { + hosts: HostAddress[]; + retryWrites: boolean; + retryReads: boolean; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS: number; + /** The name of the replica set to connect to */ + replicaSet?: string; + srvHost?: string; + /* Excluded from this release type: srvPoller */ + /** Indicates that a client should directly connect to a node without attempting to discover its topology type */ + directConnection: boolean; + loadBalanced: boolean; + metadata: ClientMetadata; + /** MongoDB server API version */ + serverApi?: ServerApi; +} +/* Excluded from this release type: TopologyPrivate */ +/** + * An enumeration of topology types we know about + * @public + */ +export declare const TopologyType: Readonly<{ + readonly Single: "Single"; + readonly ReplicaSetNoPrimary: "ReplicaSetNoPrimary"; + readonly ReplicaSetWithPrimary: "ReplicaSetWithPrimary"; + readonly Sharded: "Sharded"; + readonly Unknown: "Unknown"; + readonly LoadBalanced: "LoadBalanced"; +}>; +/** @public */ +export declare type TopologyType = typeof TopologyType[keyof typeof TopologyType]; +/** @public */ +export declare interface TopologyVersion { + processId: ObjectId; + counter: Long; +} +/** + * @public + * A class maintaining state related to a server transaction. Internal Only + */ +export declare class Transaction { + /* Excluded from this release type: state */ + options: TransactionOptions; + /*Excluded from this release type: _pinnedServer + Excluded from this release type: _recoveryToken + Excluded from this release type: __constructor + Excluded from this release type: server */ + readonly recoveryToken: Document | undefined; + readonly isPinned: boolean; + /*@returns Whether the transaction has started */ + readonly isStarting: boolean; + /* + * @returns Whether this session is presently in a transaction + */ + readonly isActive: boolean; + readonly isCommitted: boolean; +} +/** + * Configuration options for a transaction. + * @public + */ +export declare interface TransactionOptions extends CommandOperationOptions { + /** A default read concern for commands in this transaction */ + readConcern?: ReadConcern; + /** A default writeConcern for commands in this transaction */ + writeConcern?: WriteConcern; + /** A default read preference for commands in this transaction */ + readPreference?: ReadPreference; + maxCommitTimeMS?: number; +} +/* Excluded from this release type: TxnState */ +/** + * Typescript type safe event emitter + * @public + */ +export declare interface TypedEventEmitter extends EventEmitter { + addListener(event: EventKey, listener: Events[EventKey]): this; + addListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + addListener(event: string | symbol, listener: GenericListener): this; + on(event: EventKey, listener: Events[EventKey]): this; + on(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + on(event: string | symbol, listener: GenericListener): this; + once(event: EventKey, listener: Events[EventKey]): this; + once(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + once(event: string | symbol, listener: GenericListener): this; + removeListener(event: EventKey, listener: Events[EventKey]): this; + removeListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + removeListener(event: string | symbol, listener: GenericListener): this; + off(event: EventKey, listener: Events[EventKey]): this; + off(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + off(event: string | symbol, listener: GenericListener): this; + removeAllListeners(event?: EventKey | CommonEvents | symbol | string): this; + listeners(event: EventKey | CommonEvents | symbol | string): Events[EventKey][]; + rawListeners(event: EventKey | CommonEvents | symbol | string): Events[EventKey][]; + emit(event: EventKey | symbol, ...args: Parameters): boolean; + listenerCount(type: EventKey | CommonEvents | symbol | string): number; + prependListener(event: EventKey, listener: Events[EventKey]): this; + prependListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + prependListener(event: string | symbol, listener: GenericListener): this; + prependOnceListener(event: EventKey, listener: Events[EventKey]): this; + prependOnceListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + prependOnceListener(event: string | symbol, listener: GenericListener): this; + eventNames(): string[]; + getMaxListeners(): number; + setMaxListeners(n: number): this; +} +/** + * Typescript type safe event emitter + * @public + */ +export declare class TypedEventEmitter extends EventEmitter { +} +/** @public */ +export declare class UnorderedBulkOperation extends BulkOperationBase { + constructor(collection: Collection, options: BulkWriteOptions); + handleWriteError(callback: Callback, writeResult: BulkWriteResult): boolean | undefined; + addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} +/** @public */ +export declare interface UpdateDescription { + /** + * A document containing key:value pairs of names of the fields that were + * changed, and the new value for those fields. + */ + updatedFields: Partial; + /** + * An array of field names that were removed from the document. + */ + removedFields: string[]; +} +/** @public */ +export declare type UpdateFilter = { + $currentDate?: OnlyFieldsOfType; + $inc?: OnlyFieldsOfType; + $min?: MatchKeysAndValues; + $max?: MatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: MatchKeysAndValues; + $setOnInsert?: MatchKeysAndValues; + $unset?: OnlyFieldsOfType; + $addToSet?: SetFields; + $pop?: OnlyFieldsOfType, 1 | -1>; + $pull?: PullOperator; + $push?: PushOperator; + $pullAll?: PullAllOperator; + $bit?: OnlyFieldsOfType; +} & Document; +/** @public */ +export declare interface UpdateManyModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** A document or pipeline containing update operators. */ + update: UpdateFilter | UpdateFilter[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} +/** @public */ +export declare interface UpdateOneModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** A document or pipeline containing update operators. */ + update: UpdateFilter | UpdateFilter[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} +/** @public */ +export declare interface UpdateOptions extends CommandOperationOptions { + /** A set of filters specifying to which array elements an update should apply */ + arrayFilters?: Document[]; + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} +/** @public */ +export declare interface UpdateResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of documents that matched the filter */ + matchedCount: number; + /** The number of documents that were modified */ + modifiedCount: number; + /** The number of documents that were upserted */ + upsertedCount: number; + /** The identifier of the inserted document if an upsert took place */ + upsertedId: ObjectId; +} +/** @public */ +export declare interface UpdateStatement { + /** The query that matches documents to update. */ + q: Document; + /** The modifications to apply. */ + u: Document | Document[]; + /** If true, perform an insert if no documents match the query. */ + upsert?: boolean; + /** If true, updates all documents that meet the query criteria. */ + multi?: boolean; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** An array of filter documents that determines which array elements to modify for an update operation on an array field. */ + arrayFilters?: Document[]; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; +} +/** @public */ +export declare interface ValidateCollectionOptions extends CommandOperationOptions { + /** Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) */ + background?: boolean; +} +/** @public */ +export declare type W = number | 'majority'; +/* Excluded from this release type: WaitQueueMember */ +/** @public */ +export declare interface WiredTigerData extends Document { + LSM: { + 'bloom filter false positives': number; + 'bloom filter hits': number; + 'bloom filter misses': number; + 'bloom filter pages evicted from cache': number; + 'bloom filter pages read into cache': number; + 'bloom filters in the LSM tree': number; + 'chunks in the LSM tree': number; + 'highest merge generation in the LSM tree': number; + 'queries that could have benefited from a Bloom filter that did not exist': number; + 'sleep for LSM checkpoint throttle': number; + 'sleep for LSM merge throttle': number; + 'total size of bloom filters': number; + } & Document; + 'block-manager': { + 'allocations requiring file extension': number; + 'blocks allocated': number; + 'blocks freed': number; + 'checkpoint size': number; + 'file allocation unit size': number; + 'file bytes available for reuse': number; + 'file magic number': number; + 'file major version number': number; + 'file size in bytes': number; + 'minor version number': number; + }; + btree: { + 'btree checkpoint generation': number; + 'column-store fixed-size leaf pages': number; + 'column-store internal pages': number; + 'column-store variable-size RLE encoded values': number; + 'column-store variable-size deleted values': number; + 'column-store variable-size leaf pages': number; + 'fixed-record size': number; + 'maximum internal page key size': number; + 'maximum internal page size': number; + 'maximum leaf page key size': number; + 'maximum leaf page size': number; + 'maximum leaf page value size': number; + 'maximum tree depth': number; + 'number of key/value pairs': number; + 'overflow pages': number; + 'pages rewritten by compaction': number; + 'row-store internal pages': number; + 'row-store leaf pages': number; + } & Document; + cache: { + 'bytes currently in the cache': number; + 'bytes read into cache': number; + 'bytes written from cache': number; + 'checkpoint blocked page eviction': number; + 'data source pages selected for eviction unable to be evicted': number; + 'hazard pointer blocked page eviction': number; + 'in-memory page passed criteria to be split': number; + 'in-memory page splits': number; + 'internal pages evicted': number; + 'internal pages split during eviction': number; + 'leaf pages split during eviction': number; + 'modified pages evicted': number; + 'overflow pages read into cache': number; + 'overflow values cached in memory': number; + 'page split during eviction deepened the tree': number; + 'page written requiring lookaside records': number; + 'pages read into cache': number; + 'pages read into cache requiring lookaside entries': number; + 'pages requested from the cache': number; + 'pages written from cache': number; + 'pages written requiring in-memory restoration': number; + 'tracked dirty bytes in the cache': number; + 'unmodified pages evicted': number; + } & Document; + cache_walk: { + 'Average difference between current eviction generation when the page was last considered': number; + 'Average on-disk page image size seen': number; + 'Clean pages currently in cache': number; + 'Current eviction generation': number; + 'Dirty pages currently in cache': number; + 'Entries in the root page': number; + 'Internal pages currently in cache': number; + 'Leaf pages currently in cache': number; + 'Maximum difference between current eviction generation when the page was last considered': number; + 'Maximum page size seen': number; + 'Minimum on-disk page image size seen': number; + 'On-disk page image sizes smaller than a single allocation unit': number; + 'Pages created in memory and never written': number; + 'Pages currently queued for eviction': number; + 'Pages that could not be queued for eviction': number; + 'Refs skipped during cache traversal': number; + 'Size of the root page': number; + 'Total number of pages currently in cache': number; + } & Document; + compression: { + 'compressed pages read': number; + 'compressed pages written': number; + 'page written failed to compress': number; + 'page written was too small to compress': number; + 'raw compression call failed, additional data available': number; + 'raw compression call failed, no additional data available': number; + 'raw compression call succeeded': number; + } & Document; + cursor: { + 'bulk-loaded cursor-insert calls': number; + 'create calls': number; + 'cursor-insert key and value bytes inserted': number; + 'cursor-remove key bytes removed': number; + 'cursor-update value bytes updated': number; + 'insert calls': number; + 'next calls': number; + 'prev calls': number; + 'remove calls': number; + 'reset calls': number; + 'restarted searches': number; + 'search calls': number; + 'search near calls': number; + 'truncate calls': number; + 'update calls': number; + }; + reconciliation: { + 'dictionary matches': number; + 'fast-path pages deleted': number; + 'internal page key bytes discarded using suffix compression': number; + 'internal page multi-block writes': number; + 'internal-page overflow keys': number; + 'leaf page key bytes discarded using prefix compression': number; + 'leaf page multi-block writes': number; + 'leaf-page overflow keys': number; + 'maximum blocks required for a page': number; + 'overflow values written': number; + 'page checksum matches': number; + 'page reconciliation calls': number; + 'page reconciliation calls for eviction': number; + 'pages deleted': number; + } & Document; +} +/* Excluded from this release type: WithConnectionCallback */ +/** Add an _id field to an object shaped type @public */ +export declare type WithId = EnhancedOmit & { + _id: InferIdType; +}; +/** Remove the _id field from an object shaped type @public */ +export declare type WithoutId = Pick>; +/** @public */ +export declare type WithSessionCallback = (session: ClientSession) => Promise | void; +/** @public */ +export declare type WithTransactionCallback = (session: ClientSession) => Promise; +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @public + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ +export declare class WriteConcern { + /** request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. */ + w?: W; + /** specify a time limit to prevent write operations from blocking indefinitely */ + wtimeout?: number; + /** request acknowledgment that the write operation has been written to the on-disk journal */ + j?: boolean; + /** equivalent to the j option */ + fsync?: boolean | 1; + /** + * Constructs a WriteConcern from the write concern properties. + * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. + * @param wtimeout - specify a time limit to prevent write operations from blocking indefinitely + * @param j - request acknowledgment that the write operation has been written to the on-disk journal + * @param fsync - equivalent to the j option + */ + constructor(w?: W, wtimeout?: number, j?: boolean, fsync?: boolean | 1); + /** Construct a WriteConcern given an options object. */ + static fromOptions(options?: WriteConcernOptions | WriteConcern | W, inherit?: WriteConcernOptions | WriteConcern): WriteConcern | undefined; +} +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +export declare class WriteConcernError { + /* Excluded from this release type: [kServerError] */ + constructor(error: WriteConcernErrorData); + /*Write concern error code. */ + readonly code: number | undefined; + /*Write concern error message. */ + readonly errmsg: string | undefined; + /*Write concern error info. */ + readonly errInfo: Document | undefined; + /*@deprecated The `err` prop that contained a MongoServerError has been deprecated. */ + readonly err: WriteConcernErrorData; + toJSON(): WriteConcernErrorData; + toString(): string; +} +/** @public */ +export declare interface WriteConcernErrorData { + code: number; + errmsg: string; + errInfo?: Document; +} +/** @public */ +export declare interface WriteConcernOptions { + /** Write Concern as an object */ + writeConcern?: WriteConcern | WriteConcernSettings; +} +/** @public */ +export declare interface WriteConcernSettings { + /** The write concern */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + /** The journal write concern */ + j?: boolean; + /** The write concern timeout */ + wtimeout?: number; + /** The file sync write concern */ + fsync?: boolean | 1; +} +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +export declare class WriteError { + err: BulkWriteOperationError; + constructor(err: BulkWriteOperationError); + /*WriteError code. */ + readonly code: number; + /*WriteError original bulk operation index. */ + readonly index: number; + /*WriteError message. */ + readonly errmsg: string | undefined; + /*WriteError details. */ + readonly errInfo: Document | undefined; + /** Returns the underlying operation that caused the error */ + getOperation(): Document; + toJSON(): { + code: number; + index: number; + errmsg?: string; + op: Document; + }; + toString(): string; +} +/* Excluded from this release type: WriteProtocolMessageType */ +export {}; diff --git a/node_modules/mongodb/package.json b/node_modules/mongodb/package.json new file mode 100644 index 0000000..753bb62 --- /dev/null +++ b/node_modules/mongodb/package.json @@ -0,0 +1,130 @@ +{ + "name": "mongodb", + "version": "4.1.2", + "description": "The official MongoDB driver for Node.js", + "main": "lib/index.js", + "files": [ + "lib", + "src", + "etc/prepare.js", + "mongodb.d.ts", + "mongodb.ts34.d.ts" + ], + "types": "mongodb.d.ts", + "typesVersions": { + "<=4.0.2": { + "mongodb.d.ts": [ + "mongodb.ts34.d.ts" + ] + } + }, + "repository": { + "type": "git", + "url": "git@github.com:mongodb/node-mongodb-native.git" + }, + "keywords": [ + "mongodb", + "driver", + "official" + ], + "author": { + "name": "The MongoDB NodeJS Team", + "email": "dbx-node@mongodb.com" + }, + "dependencies": { + "bson": "^4.5.2", + "denque": "^2.0.1", + "mongodb-connection-string-url": "^2.0.0" + }, + "devDependencies": { + "@istanbuljs/nyc-config-typescript": "^1.0.1", + "@microsoft/api-extractor": "^7.18.7", + "@microsoft/tsdoc-config": "^0.15.2", + "@types/chai": "^4.2.21", + "@types/chai-subset": "^1.3.3", + "@types/kerberos": "^1.1.1", + "@types/mocha": "^9.0.0", + "@types/node": "^16.7.13", + "@types/saslprep": "^1.0.1", + "@types/semver": "^7.3.8", + "@types/whatwg-url": "^8.2.1", + "@typescript-eslint/eslint-plugin": "^4.31.0", + "@typescript-eslint/parser": "^4.31.0", + "bluebird": "^3.7.2", + "chai": "^4.3.4", + "chai-subset": "^1.6.0", + "chalk": "^4.1.2", + "co": "4.6.0", + "downlevel-dts": "^0.7.0", + "eslint": "^7.32.0", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-jsdoc": "^36.1.0", + "eslint-plugin-prettier": "^4.0.0", + "eslint-plugin-tsdoc": "^0.2.14", + "js-yaml": "^4.1.0", + "jsdoc": "^3.6.7", + "lodash.camelcase": "^4.3.0", + "mocha": "^9.1.1", + "mocha-sinon": "^2.1.2", + "mongodb-mock-server": "^2.0.1", + "nyc": "^15.1.0", + "prettier": "^2.3.2", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "sinon": "^11.1.2", + "sinon-chai": "^3.7.0", + "source-map-support": "^0.5.19", + "standard-version": "^9.3.1", + "ts-node": "^10.2.1", + "tsd": "^0.17.0", + "typedoc": "^0.21.9", + "typescript": "4.3.5", + "typescript-cached-transpile": "^0.0.6", + "xml2js": "^0.4.23", + "yargs": "^17.1.1" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=12.9.0" + }, + "bugs": { + "url": "https://jira.mongodb.org/projects/NODE/issues/" + }, + "homepage": "https://github.com/mongodb/node-mongodb-native", + "optionalDependencies": { + "saslprep": "^1.0.3" + }, + "scripts": { + "build:evergreen": "node .evergreen/generate_evergreen_tasks.js", + "build:ts": "rimraf lib && tsc", + "build:dts": "npm run build:ts && api-extractor run && rimraf 'lib/**/*.d.ts*' && downlevel-dts mongodb.d.ts mongodb.ts34.d.ts", + "build:docs": "typedoc", + "check:bench": "node test/benchmarks/driverBench", + "check:coverage": "nyc npm run check:test", + "check:lint": "npm run build:dts && npm run check:dts && npm run check:eslint && npm run check:tsd", + "check:eslint": "eslint -v && eslint --max-warnings=0 --ext '.js,.ts' src test", + "check:tsd": "tsd --version && tsd", + "check:dts": "tsc --noEmit mongodb.d.ts && tsd", + "check:test": "mocha --recursive test/functional test/unit", + "check:ts": "tsc -v && tsc --noEmit", + "check:atlas": "mocha --config \"test/manual/mocharc.json\" test/manual/atlas_connectivity.test.js", + "check:adl": "mocha test/manual/data_lake.test.js", + "check:ocsp": "mocha --config \"test/manual/mocharc.json\" test/manual/ocsp_support.test.js", + "check:kerberos": "mocha --config \"test/manual/mocharc.json\" test/manual/kerberos.test.js", + "check:tls": "mocha --config \"test/manual/mocharc.json\" test/manual/tls_support.test.js", + "check:ldap": "mocha --config \"test/manual/mocharc.json\" test/manual/ldap.test.js", + "check:csfle": "mocha test/functional/client_side_encryption", + "prepare": "node etc/prepare.js", + "release": "standard-version -i HISTORY.md", + "test": "npm run check:lint && npm run check:test" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "strict": true, + "target": "esnext", + "module": "commonjs", + "moduleResolution": "node" + } + } +} diff --git a/node_modules/mongodb/src/admin.ts b/node_modules/mongodb/src/admin.ts new file mode 100644 index 0000000..30093cc --- /dev/null +++ b/node_modules/mongodb/src/admin.ts @@ -0,0 +1,314 @@ +import { AddUserOperation, AddUserOptions } from './operations/add_user'; +import { RemoveUserOperation, RemoveUserOptions } from './operations/remove_user'; +import { + ValidateCollectionOperation, + ValidateCollectionOptions +} from './operations/validate_collection'; +import { + ListDatabasesOperation, + ListDatabasesOptions, + ListDatabasesResult +} from './operations/list_databases'; +import { executeOperation } from './operations/execute_operation'; +import { RunCommandOperation, RunCommandOptions } from './operations/run_command'; +import { Callback, getTopology } from './utils'; +import type { Document } from './bson'; +import type { CommandOperationOptions } from './operations/command'; +import type { Db } from './db'; + +/** @internal */ +export interface AdminPrivate { + db: Db; +} + +/** + * The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Use the admin database for the operation + * const adminDb = client.db(dbName).admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * expect(err).to.not.exist; + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + * ``` + */ +export class Admin { + /** @internal */ + s: AdminPrivate; + + /** + * Create a new Admin instance + * @internal + */ + constructor(db: Db) { + this.s = { db }; + } + + /** + * Execute a command + * + * @param command - The command to execute + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + command(command: Document): Promise; + command(command: Document, callback: Callback): void; + command(command: Document, options: RunCommandOptions): Promise; + command(command: Document, options: RunCommandOptions, callback: Callback): void; + command( + command: Document, + options?: RunCommandOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({ dbName: 'admin' }, options); + + return executeOperation( + getTopology(this.s.db), + new RunCommandOperation(this.s.db, command, options), + callback + ); + } + + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + buildInfo(): Promise; + buildInfo(callback: Callback): void; + buildInfo(options: CommandOperationOptions): Promise; + buildInfo(options: CommandOperationOptions, callback: Callback): void; + buildInfo( + options?: CommandOperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + return this.command({ buildinfo: 1 }, options, callback as Callback); + } + + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + serverInfo(): Promise; + serverInfo(callback: Callback): void; + serverInfo(options: CommandOperationOptions): Promise; + serverInfo(options: CommandOperationOptions, callback: Callback): void; + serverInfo( + options?: CommandOperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + return this.command({ buildinfo: 1 }, options, callback as Callback); + } + + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + serverStatus(): Promise; + serverStatus(callback: Callback): void; + serverStatus(options: CommandOperationOptions): Promise; + serverStatus(options: CommandOperationOptions, callback: Callback): void; + serverStatus( + options?: CommandOperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + return this.command({ serverStatus: 1 }, options, callback as Callback); + } + + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + ping(): Promise; + ping(callback: Callback): void; + ping(options: CommandOperationOptions): Promise; + ping(options: CommandOperationOptions, callback: Callback): void; + ping( + options?: CommandOperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + return this.command({ ping: 1 }, options, callback as Callback); + } + + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param password - An optional password for the new user + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + addUser(username: string): Promise; + addUser(username: string, callback: Callback): void; + addUser(username: string, password: string): Promise; + addUser(username: string, password: string, callback: Callback): void; + addUser(username: string, options: AddUserOptions): Promise; + addUser(username: string, options: AddUserOptions, callback: Callback): void; + addUser(username: string, password: string, options: AddUserOptions): Promise; + addUser( + username: string, + password: string, + options: AddUserOptions, + callback: Callback + ): void; + addUser( + username: string, + password?: string | AddUserOptions | Callback, + options?: AddUserOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof password === 'function') { + (callback = password), (password = undefined), (options = {}); + } else if (typeof password !== 'string') { + if (typeof options === 'function') { + (callback = options), (options = password), (password = undefined); + } else { + (options = password), (callback = undefined), (password = undefined); + } + } else { + if (typeof options === 'function') (callback = options), (options = {}); + } + + options = Object.assign({ dbName: 'admin' }, options); + + return executeOperation( + getTopology(this.s.db), + new AddUserOperation(this.s.db, username, password, options), + callback + ); + } + + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + removeUser(username: string): Promise; + removeUser(username: string, callback: Callback): void; + removeUser(username: string, options: RemoveUserOptions): Promise; + removeUser(username: string, options: RemoveUserOptions, callback: Callback): void; + removeUser( + username: string, + options?: RemoveUserOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({ dbName: 'admin' }, options); + + return executeOperation( + getTopology(this.s.db), + new RemoveUserOperation(this.s.db, username, options), + callback + ); + } + + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + validateCollection(collectionName: string): Promise; + validateCollection(collectionName: string, callback: Callback): void; + validateCollection(collectionName: string, options: ValidateCollectionOptions): Promise; + validateCollection( + collectionName: string, + options: ValidateCollectionOptions, + callback: Callback + ): void; + validateCollection( + collectionName: string, + options?: ValidateCollectionOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return executeOperation( + getTopology(this.s.db), + new ValidateCollectionOperation(this, collectionName, options), + callback + ); + } + + /** + * List the available databases + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + listDatabases(): Promise; + listDatabases(callback: Callback): void; + listDatabases(options: ListDatabasesOptions): Promise; + listDatabases(options: ListDatabasesOptions, callback: Callback): void; + listDatabases( + options?: ListDatabasesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return executeOperation( + getTopology(this.s.db), + new ListDatabasesOperation(this.s.db, options), + callback + ); + } + + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + replSetGetStatus(): Promise; + replSetGetStatus(callback: Callback): void; + replSetGetStatus(options: CommandOperationOptions): Promise; + replSetGetStatus(options: CommandOperationOptions, callback: Callback): void; + replSetGetStatus( + options?: CommandOperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + return this.command({ replSetGetStatus: 1 }, options, callback as Callback); + } +} diff --git a/node_modules/mongodb/src/bson.ts b/node_modules/mongodb/src/bson.ts new file mode 100644 index 0000000..3b44510 --- /dev/null +++ b/node_modules/mongodb/src/bson.ts @@ -0,0 +1,103 @@ +import type { + serialize as serializeFn, + deserialize as deserializeFn, + calculateObjectSize as calculateObjectSizeFn +} from 'bson'; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +let BSON = require('bson'); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + BSON = require('bson-ext'); +} catch {} // eslint-disable-line + +/** @internal */ +export const deserialize = BSON.deserialize as typeof deserializeFn; +/** @internal */ +export const serialize = BSON.serialize as typeof serializeFn; +/** @internal */ +export const calculateObjectSize = BSON.calculateObjectSize as typeof calculateObjectSizeFn; + +export { + Long, + Binary, + ObjectId, + Timestamp, + Code, + MinKey, + MaxKey, + Decimal128, + Int32, + Double, + DBRef, + BSONRegExp, + BSONSymbol, + Map, + Document +} from 'bson'; + +import type { DeserializeOptions, SerializeOptions } from 'bson'; + +/** + * BSON Serialization options. + * @public + */ +export interface BSONSerializeOptions + extends Omit, + Omit< + DeserializeOptions, + | 'evalFunctions' + | 'cacheFunctions' + | 'cacheFunctionsCrc32' + | 'allowObjectSmallerThanBufferSize' + | 'index' + > { + /** Return BSON filled buffers from operations */ + raw?: boolean; +} + +export function pluckBSONSerializeOptions(options: BSONSerializeOptions): BSONSerializeOptions { + const { + fieldsAsRaw, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw + } = options; + return { + fieldsAsRaw, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw + }; +} + +/** + * Merge the given BSONSerializeOptions, preferring options over the parent's options, and + * substituting defaults for values not set. + * + * @internal + */ +export function resolveBSONOptions( + options?: BSONSerializeOptions, + parent?: { bsonOptions?: BSONSerializeOptions } +): BSONSerializeOptions { + const parentOptions = parent?.bsonOptions; + return { + raw: options?.raw ?? parentOptions?.raw ?? false, + promoteLongs: options?.promoteLongs ?? parentOptions?.promoteLongs ?? true, + promoteValues: options?.promoteValues ?? parentOptions?.promoteValues ?? true, + promoteBuffers: options?.promoteBuffers ?? parentOptions?.promoteBuffers ?? false, + ignoreUndefined: options?.ignoreUndefined ?? parentOptions?.ignoreUndefined ?? false, + bsonRegExp: options?.bsonRegExp ?? parentOptions?.bsonRegExp ?? false, + serializeFunctions: options?.serializeFunctions ?? parentOptions?.serializeFunctions ?? false, + fieldsAsRaw: options?.fieldsAsRaw ?? parentOptions?.fieldsAsRaw ?? {} + }; +} diff --git a/node_modules/mongodb/src/bulk/common.ts b/node_modules/mongodb/src/bulk/common.ts new file mode 100644 index 0000000..4afb066 --- /dev/null +++ b/node_modules/mongodb/src/bulk/common.ts @@ -0,0 +1,1340 @@ +import { PromiseProvider } from '../promise_provider'; +import { Long, ObjectId, Document, BSONSerializeOptions, resolveBSONOptions } from '../bson'; +import { + MongoWriteConcernError, + AnyError, + MONGODB_ERROR_CODES, + MongoServerError, + MongoInvalidArgumentError, + MongoBatchReExecutionError +} from '../error'; +import { + applyRetryableWrites, + executeLegacyOperation, + hasAtomicOperators, + Callback, + MongoDBNamespace, + getTopology, + resolveOptions +} from '../utils'; +import { executeOperation } from '../operations/execute_operation'; +import { InsertOperation } from '../operations/insert'; +import { UpdateOperation, UpdateStatement, makeUpdateStatement } from '../operations/update'; +import { DeleteOperation, DeleteStatement, makeDeleteStatement } from '../operations/delete'; +import { WriteConcern } from '../write_concern'; +import type { Collection } from '../collection'; +import type { Topology } from '../sdam/topology'; +import type { CommandOperationOptions, CollationOptions } from '../operations/command'; +import type { Hint } from '../operations/operation'; +import type { Filter, OneOrMore, OptionalId, UpdateFilter } from '../mongo_types'; + +/** @internal */ +const kServerError = Symbol('serverError'); + +/** @public */ +export const BatchType = Object.freeze({ + INSERT: 1, + UPDATE: 2, + DELETE: 3 +} as const); + +/** @public */ +export type BatchType = typeof BatchType[keyof typeof BatchType]; + +/** @public */ +export interface InsertOneModel { + /** The document to insert. */ + document: OptionalId; +} + +/** @public */ +export interface DeleteOneModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export interface DeleteManyModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export interface ReplaceOneModel { + /** The filter to limit the replaced document. */ + filter: Filter; + /** The document with which to replace the matched document. */ + replacement: TSchema; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export interface UpdateOneModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** A document or pipeline containing update operators. */ + update: UpdateFilter | UpdateFilter[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export interface UpdateManyModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** A document or pipeline containing update operators. */ + update: UpdateFilter | UpdateFilter[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export type AnyBulkWriteOperation = + | { insertOne: InsertOneModel } + | { replaceOne: ReplaceOneModel } + | { updateOne: UpdateOneModel } + | { updateMany: UpdateManyModel } + | { deleteOne: DeleteOneModel } + | { deleteMany: DeleteManyModel }; + +/** @public */ +export interface BulkResult { + ok: number; + writeErrors: WriteError[]; + writeConcernErrors: WriteConcernError[]; + insertedIds: Document[]; + nInserted: number; + nUpserted: number; + nMatched: number; + nModified: number; + nRemoved: number; + upserted: Document[]; + opTime?: Document; +} + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +export class Batch { + originalZeroIndex: number; + currentIndex: number; + originalIndexes: number[]; + batchType: BatchType; + operations: T[]; + size: number; + sizeBytes: number; + + constructor(batchType: BatchType, originalZeroIndex: number) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; + } +} + +/** + * @public + * The result of a bulk write. + */ +export class BulkWriteResult { + result: BulkResult; + + /** + * Create a new BulkWriteResult instance + * @internal + */ + constructor(bulkResult: BulkResult) { + this.result = bulkResult; + } + + /** Number of documents inserted. */ + get insertedCount(): number { + return this.result.nInserted ?? 0; + } + /** Number of documents matched for update. */ + get matchedCount(): number { + return this.result.nMatched ?? 0; + } + /** Number of documents modified. */ + get modifiedCount(): number { + return this.result.nModified ?? 0; + } + /** Number of documents deleted. */ + get deletedCount(): number { + return this.result.nRemoved ?? 0; + } + /** Number of documents upserted. */ + get upsertedCount(): number { + return this.result.upserted.length ?? 0; + } + + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds(): { [key: number]: any } { + const upserted: { [index: number]: any } = {}; + for (const doc of this.result.upserted ?? []) { + upserted[doc.index] = doc._id; + } + return upserted; + } + + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds(): { [key: number]: any } { + const inserted: { [index: number]: any } = {}; + for (const doc of this.result.insertedIds ?? []) { + inserted[doc.index] = doc._id; + } + return inserted; + } + + /** Evaluates to true if the bulk operation correctly executes */ + get ok(): number { + return this.result.ok; + } + + /** The number of inserted documents */ + get nInserted(): number { + return this.result.nInserted; + } + + /** Number of upserted documents */ + get nUpserted(): number { + return this.result.nUpserted; + } + + /** Number of matched documents */ + get nMatched(): number { + return this.result.nMatched; + } + + /** Number of documents updated physically on disk */ + get nModified(): number { + return this.result.nModified; + } + + /** Number of removed documents */ + get nRemoved(): number { + return this.result.nRemoved; + } + + /** Returns an array of all inserted ids */ + getInsertedIds(): Document[] { + return this.result.insertedIds; + } + + /** Returns an array of all upserted ids */ + getUpsertedIds(): Document[] { + return this.result.upserted; + } + + /** Returns the upserted id at the given index */ + getUpsertedIdAt(index: number): Document | undefined { + return this.result.upserted[index]; + } + + /** Returns raw internal result */ + getRawResponse(): Document { + return this.result; + } + + /** Returns true if the bulk operation contains a write error */ + hasWriteErrors(): boolean { + return this.result.writeErrors.length > 0; + } + + /** Returns the number of write errors off the bulk operation */ + getWriteErrorCount(): number { + return this.result.writeErrors.length; + } + + /** Returns a specific write error object */ + getWriteErrorAt(index: number): WriteError | undefined { + if (index < this.result.writeErrors.length) { + return this.result.writeErrors[index]; + } + } + + /** Retrieve all write errors */ + getWriteErrors(): WriteError[] { + return this.result.writeErrors; + } + + /** Retrieve lastOp if available */ + getLastOp(): Document | undefined { + return this.result.opTime; + } + + /** Retrieve the write concern error if one exists */ + getWriteConcernError(): WriteConcernError | undefined { + if (this.result.writeConcernErrors.length === 0) { + return; + } else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; + } else { + // Combine the errors + let errmsg = ''; + for (let i = 0; i < this.result.writeConcernErrors.length; i++) { + const err = this.result.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO: Something better + if (i === 0) errmsg = errmsg + ' and '; + } + + return new WriteConcernError({ errmsg, code: MONGODB_ERROR_CODES.WriteConcernFailed }); + } + } + + toJSON(): BulkResult { + return this.result; + } + + toString(): string { + return `BulkWriteResult(${this.toJSON()})`; + } + + isOk(): boolean { + return this.result.ok === 1; + } +} + +/** @public */ +export interface WriteConcernErrorData { + code: number; + errmsg: string; + errInfo?: Document; +} + +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +export class WriteConcernError { + /** @internal */ + [kServerError]: WriteConcernErrorData; + + constructor(error: WriteConcernErrorData) { + this[kServerError] = error; + } + + /** Write concern error code. */ + get code(): number | undefined { + return this[kServerError].code; + } + + /** Write concern error message. */ + get errmsg(): string | undefined { + return this[kServerError].errmsg; + } + + /** Write concern error info. */ + get errInfo(): Document | undefined { + return this[kServerError].errInfo; + } + + /** @deprecated The `err` prop that contained a MongoServerError has been deprecated. */ + get err(): WriteConcernErrorData { + return this[kServerError]; + } + + toJSON(): WriteConcernErrorData { + return this[kServerError]; + } + + toString(): string { + return `WriteConcernError(${this.errmsg})`; + } +} + +/** @public */ +export interface BulkWriteOperationError { + index: number; + code: number; + errmsg: string; + errInfo: Document; + op: Document | UpdateStatement | DeleteStatement; +} + +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +export class WriteError { + err: BulkWriteOperationError; + + constructor(err: BulkWriteOperationError) { + this.err = err; + } + + /** WriteError code. */ + get code(): number { + return this.err.code; + } + + /** WriteError original bulk operation index. */ + get index(): number { + return this.err.index; + } + + /** WriteError message. */ + get errmsg(): string | undefined { + return this.err.errmsg; + } + + /** WriteError details. */ + get errInfo(): Document | undefined { + return this.err.errInfo; + } + + /** Returns the underlying operation that caused the error */ + getOperation(): Document { + return this.err.op; + } + + toJSON(): { code: number; index: number; errmsg?: string; op: Document } { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + + toString(): string { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} + +/** Merges results into shared data structure */ +function mergeBatchResults( + batch: Batch, + bulkResult: BulkResult, + err?: AnyError, + result?: Document +): void { + // If we have an error set the result to be the err object + if (err) { + result = err; + } else if (result && result.result) { + result = result.result; + } + + if (result == null) { + return; + } + + // Do we have a top level error stop processing and return + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + errInfo: result.errInfo, + op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + + // Deal with opTime if available + if (result.opTime || result.lastOp) { + const opTime = result.lastOp || result.opTime; + let lastOpTS = null; + let lastOpT = null; + + // We have a time stamp + if (opTime && opTime._bsontype === 'Timestamp') { + if (bulkResult.opTime == null) { + bulkResult.opTime = opTime; + } else if (opTime.greaterThan(bulkResult.opTime)) { + bulkResult.opTime = opTime; + } + } else { + // Existing TS + if (bulkResult.opTime) { + lastOpTS = + typeof bulkResult.opTime.ts === 'number' + ? Long.fromNumber(bulkResult.opTime.ts) + : bulkResult.opTime.ts; + lastOpT = + typeof bulkResult.opTime.t === 'number' + ? Long.fromNumber(bulkResult.opTime.t) + : bulkResult.opTime.t; + } + + // Current OpTime TS + const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; + const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; + + // Compare the opTime's + if (bulkResult.opTime == null) { + bulkResult.opTime = opTime; + } else if (opTimeTS.greaterThan(lastOpTS)) { + bulkResult.opTime = opTime; + } else if (opTimeTS.equals(lastOpTS)) { + if (opTimeT.greaterThan(lastOpT)) { + bulkResult.opTime = opTime; + } + } + } + } + + // If we have an insert Batch type + if (isInsertBatch(batch) && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if (isDeleteBatch(batch) && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + let nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for (let i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex, + _id: result.upserted[i]._id + }); + } + } else if (result.upserted) { + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + + // If we have an update Batch type + if (isUpdateBatch(batch) && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if (typeof nModified === 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = 0; + } + } + + if (Array.isArray(result.writeErrors)) { + for (let i = 0; i < result.writeErrors.length; i++) { + const writeError = { + index: batch.originalIndexes[result.writeErrors[i].index], + code: result.writeErrors[i].code, + errmsg: result.writeErrors[i].errmsg, + errInfo: result.writeErrors[i].errInfo, + op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +function executeCommands( + bulkOperation: BulkOperationBase, + options: BulkWriteOptions, + callback: Callback +) { + if (bulkOperation.s.batches.length === 0) { + return callback(undefined, new BulkWriteResult(bulkOperation.s.bulkResult)); + } + + const batch = bulkOperation.s.batches.shift() as Batch; + + function resultHandler(err?: AnyError, result?: Document) { + // Error is a driver related error not a bulk op error, return early + if (err && 'message' in err && !(err instanceof MongoWriteConcernError)) { + return callback( + new MongoBulkWriteError(err, new BulkWriteResult(bulkOperation.s.bulkResult)) + ); + } + + if (err instanceof MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); + } + + // Merge the results together + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + if (mergeResult != null) { + return callback(undefined, writeResult); + } + + if (bulkOperation.handleWriteError(callback, writeResult)) return; + + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + + const finalOptions = resolveOptions(bulkOperation, { + ...options, + ordered: bulkOperation.isOrdered + }); + + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + + // Set an operationIf if provided + if (bulkOperation.operationId) { + resultHandler.operationId = bulkOperation.operationId; + } + + // Is the bypassDocumentValidation options specific + if (bulkOperation.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + + // Is the checkKeys option disabled + if (bulkOperation.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + + if (finalOptions.retryWrites) { + if (isUpdateBatch(batch)) { + finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some(op => op.multi); + } + + if (isDeleteBatch(batch)) { + finalOptions.retryWrites = + finalOptions.retryWrites && !batch.operations.some(op => op.limit === 0); + } + } + + try { + if (isInsertBatch(batch)) { + executeOperation( + bulkOperation.s.topology, + new InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions), + resultHandler + ); + } else if (isUpdateBatch(batch)) { + executeOperation( + bulkOperation.s.topology, + new UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions), + resultHandler + ); + } else if (isDeleteBatch(batch)) { + executeOperation( + bulkOperation.s.topology, + new DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions), + resultHandler + ); + } + } catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, undefined); + callback(); + } +} + +function handleMongoWriteConcernError( + batch: Batch, + bulkResult: BulkResult, + err: MongoWriteConcernError, + callback: Callback +) { + mergeBatchResults(batch, bulkResult, undefined, err.result); + + callback( + new MongoBulkWriteError( + { + message: err.result?.writeConcernError.errmsg, + code: err.result?.writeConcernError.result + }, + new BulkWriteResult(bulkResult) + ) + ); +} + +/** + * An error indicating an unsuccessful Bulk Write + * @public + * @category Error + */ +export class MongoBulkWriteError extends MongoServerError { + result: BulkWriteResult; + writeErrors: OneOrMore = []; + err?: WriteConcernError; + + /** Creates a new MongoBulkWriteError */ + constructor( + error: + | { message: string; code: number; writeErrors?: WriteError[] } + | WriteConcernError + | AnyError, + result: BulkWriteResult + ) { + super(error); + + if (error instanceof WriteConcernError) this.err = error; + else if (!(error instanceof Error)) { + this.message = error.message; + this.code = error.code; + this.writeErrors = error.writeErrors ?? []; + } + + this.result = result; + Object.assign(this, error); + } + + get name(): string { + return 'MongoBulkWriteError'; + } + + /** Number of documents inserted. */ + get insertedCount(): number { + return this.result.insertedCount; + } + /** Number of documents matched for update. */ + get matchedCount(): number { + return this.result.matchedCount; + } + /** Number of documents modified. */ + get modifiedCount(): number { + return this.result.modifiedCount; + } + /** Number of documents deleted. */ + get deletedCount(): number { + return this.result.deletedCount; + } + /** Number of documents upserted. */ + get upsertedCount(): number { + return this.result.upsertedCount; + } + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds(): { [key: number]: any } { + return this.result.insertedIds; + } + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds(): { [key: number]: any } { + return this.result.upsertedIds; + } +} + +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +export class FindOperators { + bulkOperation: BulkOperationBase; + + /** + * Creates a new FindOperators object. + * @internal + */ + constructor(bulkOperation: BulkOperationBase) { + this.bulkOperation = bulkOperation; + } + + /** Add a multiple update operation to the bulk operation */ + update(updateDocument: Document): BulkOperationBase { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.UPDATE, + makeUpdateStatement(currentOp.selector, updateDocument, { + ...currentOp, + multi: true + }) + ); + } + + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument: Document): BulkOperationBase { + if (!hasAtomicOperators(updateDocument)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.UPDATE, + makeUpdateStatement(currentOp.selector, updateDocument, { ...currentOp, multi: false }) + ); + } + + /** Add a replace one operation to the bulk operation */ + replaceOne(replacement: Document): BulkOperationBase { + if (hasAtomicOperators(replacement)) { + throw new MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.UPDATE, + makeUpdateStatement(currentOp.selector, replacement, { ...currentOp, multi: false }) + ); + } + + /** Add a delete one operation to the bulk operation */ + deleteOne(): BulkOperationBase { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(currentOp.selector, { ...currentOp, limit: 1 }) + ); + } + + /** Add a delete many operation to the bulk operation */ + delete(): BulkOperationBase { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(currentOp.selector, { ...currentOp, limit: 0 }) + ); + } + + /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ + upsert(): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.upsert = true; + return this; + } + + /** Specifies the collation for the query condition. */ + collation(collation: CollationOptions): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.collation = collation; + return this; + } + + /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ + arrayFilters(arrayFilters: Document[]): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.arrayFilters = arrayFilters; + return this; + } +} + +/** @internal */ +export interface BulkOperationPrivate { + bulkResult: BulkResult; + currentBatch?: Batch; + currentIndex: number; + // ordered specific + currentBatchSize: number; + currentBatchSizeBytes: number; + // unordered specific + currentInsertBatch?: Batch; + currentUpdateBatch?: Batch; + currentRemoveBatch?: Batch; + batches: Batch[]; + // Write concern + writeConcern?: WriteConcern; + // Max batch size options + maxBsonObjectSize: number; + maxBatchSizeBytes: number; + maxWriteBatchSize: number; + maxKeySize: number; + // Namespace + namespace: MongoDBNamespace; + // Topology + topology: Topology; + // Options + options: BulkWriteOptions; + // BSON options + bsonOptions: BSONSerializeOptions; + // Document used to build a bulk operation + currentOp?: Document; + // Executed + executed: boolean; + // Collection + collection: Collection; + // Fundamental error + err?: AnyError; + // check keys + checkKeys: boolean; + bypassDocumentValidation?: boolean; +} + +/** @public */ +export interface BulkWriteOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** @deprecated use `ordered` instead */ + keepGoing?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; +} + +/** @public */ +export abstract class BulkOperationBase { + isOrdered: boolean; + /** @internal */ + s: BulkOperationPrivate; + operationId?: number; + + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance + * @internal + */ + constructor(collection: Collection, options: BulkWriteOptions, isOrdered: boolean) { + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + + const topology = getTopology(collection); + options = options == null ? {} : options; + // TODO Bring from driver information in isMaster + // Get the namespace for the write operations + const namespace = collection.s.namespace; + // Used to mark operation as executed + const executed = false; + + // Current item + const currentOp = undefined; + + // Set max byte size + const isMaster = topology.lastIsMaster(); + + // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents + // over 2mb are still allowed + const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); + const maxBsonObjectSize = + isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; + const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; + const maxWriteBatchSize = + isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; + + // Calculates the largest possible size of an Array key, represented as a BSON string + // element. This calculation: + // 1 byte for BSON type + // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) + // + 1 bytes for null terminator + const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; + + // Final options for retryable writes + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, collection.s.db); + + // Final results + const bulkResult: BulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult, + // Current batch state + currentBatch: undefined, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: undefined, + currentUpdateBatch: undefined, + currentRemoveBatch: undefined, + batches: [], + // Write concern + writeConcern: WriteConcern.fromOptions(options), + // Max batch size options + maxBsonObjectSize, + maxBatchSizeBytes, + maxWriteBatchSize, + maxKeySize, + // Namespace + namespace, + // Topology + topology, + // Options + options: finalOptions, + // BSON options + bsonOptions: resolveBSONOptions(options), + // Current operation + currentOp, + // Executed + executed, + // Collection + collection, + // Fundamental error + err: undefined, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : false + }; + + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + + /** + * Add a single insert document to the bulk operation + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + * ``` + */ + insert(document: Document): BulkOperationBase { + if (document._id == null && !shouldForceServerObjectId(this)) { + document._id = new ObjectId(); + } + + return this.addToOperationsList(BatchType.INSERT, document); + } + + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }}); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + * ``` + */ + find(selector: Document): FindOperators { + if (!selector) { + throw new MongoInvalidArgumentError('Bulk find operation must specify a selector'); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + }; + + return new FindOperators(this); + } + + /** Specifies a raw operation to perform in the bulk write. */ + raw(op: AnyBulkWriteOperation): this { + if ('insertOne' in op) { + const forceServerObjectId = shouldForceServerObjectId(this); + if (op.insertOne && op.insertOne.document == null) { + // NOTE: provided for legacy support, but this is a malformed operation + if (forceServerObjectId !== true && (op.insertOne as Document)._id == null) { + (op.insertOne as Document)._id = new ObjectId(); + } + + return this.addToOperationsList(BatchType.INSERT, op.insertOne); + } + + if (forceServerObjectId !== true && op.insertOne.document._id == null) { + op.insertOne.document._id = new ObjectId(); + } + + return this.addToOperationsList(BatchType.INSERT, op.insertOne.document); + } + + if ('replaceOne' in op || 'updateOne' in op || 'updateMany' in op) { + if ('replaceOne' in op) { + if ('q' in op.replaceOne) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = makeUpdateStatement( + op.replaceOne.filter, + op.replaceOne.replacement, + { ...op.replaceOne, multi: false } + ); + if (hasAtomicOperators(updateStatement.u)) { + throw new MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + return this.addToOperationsList(BatchType.UPDATE, updateStatement); + } + + if ('updateOne' in op) { + if ('q' in op.updateOne) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = makeUpdateStatement(op.updateOne.filter, op.updateOne.update, { + ...op.updateOne, + multi: false + }); + if (!hasAtomicOperators(updateStatement.u)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(BatchType.UPDATE, updateStatement); + } + + if ('updateMany' in op) { + if ('q' in op.updateMany) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = makeUpdateStatement(op.updateMany.filter, op.updateMany.update, { + ...op.updateMany, + multi: true + }); + if (!hasAtomicOperators(updateStatement.u)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(BatchType.UPDATE, updateStatement); + } + } + + if ('deleteOne' in op) { + if ('q' in op.deleteOne) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(op.deleteOne.filter, { ...op.deleteOne, limit: 1 }) + ); + } + + if ('deleteMany' in op) { + if ('q' in op.deleteMany) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(op.deleteMany.filter, { ...op.deleteMany, limit: 0 }) + ); + } + + // otherwise an unknown operation was provided + throw new MongoInvalidArgumentError( + 'bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany' + ); + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + get writeConcern(): WriteConcern | undefined { + return this.s.writeConcern; + } + + get batches(): Batch[] { + const batches = [...this.s.batches]; + if (this.isOrdered) { + if (this.s.currentBatch) batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) batches.push(this.s.currentRemoveBatch); + } + return batches; + } + + /** An internal helper method. Do not invoke directly. Will be going away in the future */ + execute( + options?: BulkWriteOptions, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + if (this.s.executed) { + return handleEarlyError(new MongoBatchReExecutionError(), callback); + } + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + this.s.writeConcern = writeConcern; + } + + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + } + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + const emptyBatchError = new MongoInvalidArgumentError( + 'Invalid BulkOperation, Batch cannot be empty' + ); + return handleEarlyError(emptyBatchError, callback); + } + + this.s.executed = true; + const finalOptions = { ...this.s.options, ...options }; + return executeLegacyOperation(this.s.topology, executeCommands, [this, finalOptions, callback]); + } + + /** + * Handles the write error before executing commands + * @internal + */ + handleWriteError( + callback: Callback, + writeResult: BulkWriteResult + ): boolean | undefined { + if (this.s.bulkResult.writeErrors.length > 0) { + const msg = this.s.bulkResult.writeErrors[0].errmsg + ? this.s.bulkResult.writeErrors[0].errmsg + : 'write operation failed'; + + callback( + new MongoBulkWriteError( + { + message: msg, + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }, + writeResult + ) + ); + + return true; + } + + const writeConcernError = writeResult.getWriteConcernError(); + if (writeConcernError) { + callback(new MongoBulkWriteError(writeConcernError, writeResult)); + return true; + } + } + + abstract addToOperationsList( + batchType: BatchType, + document: Document | UpdateStatement | DeleteStatement + ): this; +} + +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get() { + return this.s.currentIndex; + } +}); + +/** helper function to assist with promiseOrCallback behavior */ +function handleEarlyError( + err?: AnyError, + callback?: Callback +): Promise | void { + const Promise = PromiseProvider.get(); + if (typeof callback === 'function') { + callback(err); + return; + } + + return Promise.reject(err); +} + +function shouldForceServerObjectId(bulkOperation: BulkOperationBase): boolean { + if (typeof bulkOperation.s.options.forceServerObjectId === 'boolean') { + return bulkOperation.s.options.forceServerObjectId; + } + + if (typeof bulkOperation.s.collection.s.db.options?.forceServerObjectId === 'boolean') { + return bulkOperation.s.collection.s.db.options?.forceServerObjectId; + } + + return false; +} + +function isInsertBatch(batch: Batch): boolean { + return batch.batchType === BatchType.INSERT; +} + +function isUpdateBatch(batch: Batch): batch is Batch { + return batch.batchType === BatchType.UPDATE; +} + +function isDeleteBatch(batch: Batch): batch is Batch { + return batch.batchType === BatchType.DELETE; +} + +function buildCurrentOp(bulkOp: BulkOperationBase): Document { + let { currentOp } = bulkOp.s; + bulkOp.s.currentOp = undefined; + if (!currentOp) currentOp = {}; + return currentOp; +} diff --git a/node_modules/mongodb/src/bulk/ordered.ts b/node_modules/mongodb/src/bulk/ordered.ts new file mode 100644 index 0000000..ce99650 --- /dev/null +++ b/node_modules/mongodb/src/bulk/ordered.ts @@ -0,0 +1,82 @@ +import * as BSON from '../bson'; +import { BulkOperationBase, Batch, BatchType, BulkWriteOptions } from './common'; +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { UpdateStatement } from '../operations/update'; +import type { DeleteStatement } from '../operations/delete'; +import { MongoInvalidArgumentError } from '../error'; + +/** @public */ +export class OrderedBulkOperation extends BulkOperationBase { + constructor(collection: Collection, options: BulkWriteOptions) { + super(collection, options, true); + } + + addToOperationsList( + batchType: BatchType, + document: Document | UpdateStatement | DeleteStatement + ): this { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + } as any); + + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) + // TODO(NODE-3483): Change this to MongoBSONError + throw new MongoInvalidArgumentError( + `Document is larger than the maximum size ${this.s.maxBsonObjectSize}` + ); + + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + } + + const maxKeySize = this.s.maxKeySize; + + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatchSize > 0 && + this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType + ) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + + // Create a new batch + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + + // Reset the current size trackers + this.s.currentBatchSize = 0; + this.s.currentBatchSizeBytes = 0; + } + + if (batchType === BatchType.INSERT) { + this.s.bulkResult.insertedIds.push({ + index: this.s.currentIndex, + _id: (document as Document)._id + }); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw new MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentBatch.operations.push(document); + this.s.currentBatchSize += 1; + this.s.currentBatchSizeBytes += maxKeySize + bsonSize; + this.s.currentIndex += 1; + return this; + } +} diff --git a/node_modules/mongodb/src/bulk/unordered.ts b/node_modules/mongodb/src/bulk/unordered.ts new file mode 100644 index 0000000..e241e50 --- /dev/null +++ b/node_modules/mongodb/src/bulk/unordered.ts @@ -0,0 +1,109 @@ +import * as BSON from '../bson'; +import { BulkOperationBase, Batch, BatchType, BulkWriteOptions, BulkWriteResult } from './common'; +import type { Callback } from '../utils'; +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { UpdateStatement } from '../operations/update'; +import type { DeleteStatement } from '../operations/delete'; +import { MongoInvalidArgumentError } from '../error'; + +/** @public */ +export class UnorderedBulkOperation extends BulkOperationBase { + constructor(collection: Collection, options: BulkWriteOptions) { + super(collection, options, false); + } + + handleWriteError(callback: Callback, writeResult: BulkWriteResult): boolean | undefined { + if (this.s.batches.length) { + return false; + } + + return super.handleWriteError(callback, writeResult); + } + + addToOperationsList( + batchType: BatchType, + document: Document | UpdateStatement | DeleteStatement + ): this { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + } as any); + + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) { + // TODO(NODE-3483): Change this to MongoBSONError + throw new MongoInvalidArgumentError( + `Document is larger than the maximum size ${this.s.maxBsonObjectSize}` + ); + } + + // Holds the current batch + this.s.currentBatch = undefined; + // Get the right type of batch + if (batchType === BatchType.INSERT) { + this.s.currentBatch = this.s.currentInsertBatch; + } else if (batchType === BatchType.UPDATE) { + this.s.currentBatch = this.s.currentUpdateBatch; + } else if (batchType === BatchType.DELETE) { + this.s.currentBatch = this.s.currentRemoveBatch; + } + + const maxKeySize = this.s.maxKeySize; + + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + } + + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatch.size + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatch.size > 0 && + this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType + ) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + + // Create a new batch + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw new MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + + this.s.currentBatch.operations.push(document); + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentIndex = this.s.currentIndex + 1; + + // Save back the current Batch to the right type + if (batchType === BatchType.INSERT) { + this.s.currentInsertBatch = this.s.currentBatch; + this.s.bulkResult.insertedIds.push({ + index: this.s.bulkResult.insertedIds.length, + _id: (document as Document)._id + }); + } else if (batchType === BatchType.UPDATE) { + this.s.currentUpdateBatch = this.s.currentBatch; + } else if (batchType === BatchType.DELETE) { + this.s.currentRemoveBatch = this.s.currentBatch; + } + + // Update current batch size + this.s.currentBatch.size += 1; + this.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + + return this; + } +} diff --git a/node_modules/mongodb/src/change_stream.ts b/node_modules/mongodb/src/change_stream.ts new file mode 100644 index 0000000..60b7cf7 --- /dev/null +++ b/node_modules/mongodb/src/change_stream.ts @@ -0,0 +1,827 @@ +import Denque = require('denque'); +import { + MongoError, + AnyError, + isResumableError, + MongoRuntimeError, + MongoAPIError, + MongoChangeStreamError +} from './error'; +import { AggregateOperation, AggregateOptions } from './operations/aggregate'; +import { + maxWireVersion, + calculateDurationInMs, + now, + maybePromise, + MongoDBNamespace, + Callback, + getTopology +} from './utils'; +import type { ReadPreference } from './read_preference'; +import type { Timestamp, Document } from './bson'; +import type { Topology } from './sdam/topology'; +import type { OperationParent, CollationOptions } from './operations/command'; +import { MongoClient } from './mongo_client'; +import { Db } from './db'; +import { Collection } from './collection'; +import type { Readable } from 'stream'; +import { + AbstractCursor, + AbstractCursorEvents, + AbstractCursorOptions, + CursorStreamOptions +} from './cursor/abstract_cursor'; +import type { ClientSession } from './sessions'; +import { executeOperation, ExecutionResult } from './operations/execute_operation'; +import { InferIdType, Nullable, TypedEventEmitter } from './mongo_types'; + +/** @internal */ +const kResumeQueue = Symbol('resumeQueue'); +/** @internal */ +const kCursorStream = Symbol('cursorStream'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kMode = Symbol('mode'); + +const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument']; +const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat( + CHANGE_STREAM_OPTIONS +); + +const CHANGE_DOMAIN_TYPES = { + COLLECTION: Symbol('Collection'), + DATABASE: Symbol('Database'), + CLUSTER: Symbol('Cluster') +}; + +const NO_RESUME_TOKEN_ERROR = + 'A change stream document has been received that lacks a resume token (_id).'; +const NO_CURSOR_ERROR = 'ChangeStream has no cursor'; +const CHANGESTREAM_CLOSED_ERROR = 'ChangeStream is closed'; + +/** @public */ +export interface ResumeOptions { + startAtOperationTime?: Timestamp; + batchSize?: number; + maxAwaitTimeMS?: number; + collation?: CollationOptions; + readPreference?: ReadPreference; +} + +/** + * Represents the logical starting point for a new or resuming {@link https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token| Change Stream} on the server. + * @public + */ +export type ResumeToken = unknown; + +/** + * Represents a specific point in time on a server. Can be retrieved by using {@link Db#command} + * @public + * @remarks + * See {@link https://docs.mongodb.com/manual/reference/method/db.runCommand/#response| Run Command Response} + */ +export type OperationTime = Timestamp; + +/** @public */ +export interface PipeOptions { + end?: boolean; +} + +/** + * Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. + * @public + */ +export interface ChangeStreamOptions extends AggregateOptions { + /** Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. */ + fullDocument?: string; + /** The maximum amount of time for the server to wait on new documents to satisfy a change stream query. */ + maxAwaitTimeMS?: number; + /** Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. */ + resumeAfter?: ResumeToken; + /** Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. */ + startAfter?: ResumeToken; + /** Will start the changeStream after the specified operationTime. */ + startAtOperationTime?: OperationTime; + /** The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. */ + batchSize?: number; +} + +/** @public */ +export interface ChangeStreamDocument { + /** + * The id functions as an opaque token for use when resuming an interrupted + * change stream. + */ + _id: InferIdType; + + /** + * Describes the type of operation represented in this change notification. + */ + operationType: + | 'insert' + | 'update' + | 'replace' + | 'delete' + | 'invalidate' + | 'drop' + | 'dropDatabase' + | 'rename'; + + /** + * Contains two fields: “db” and “coll” containing the database and + * collection name in which the change happened. + */ + ns: { db: string; coll: string }; + + /** + * Only present for ops of type ‘insert’, ‘update’, ‘replace’, and + * ‘delete’. + * + * For unsharded collections this contains a single field, _id, with the + * value of the _id of the document updated. For sharded collections, + * this will contain all the components of the shard key in order, + * followed by the _id if the _id isn’t part of the shard key. + */ + documentKey?: InferIdType; + + /** + * Only present for ops of type ‘update’. + * + * Contains a description of updated and removed fields in this + * operation. + */ + updateDescription?: UpdateDescription; + + /** + * Always present for operations of type ‘insert’ and ‘replace’. Also + * present for operations of type ‘update’ if the user has specified ‘updateLookup’ + * in the ‘fullDocument’ arguments to the ‘$changeStream’ stage. + * + * For operations of type ‘insert’ and ‘replace’, this key will contain the + * document being inserted, or the new version of the document that is replacing + * the existing document, respectively. + * + * For operations of type ‘update’, this key will contain a copy of the full + * version of the document from some point after the update occurred. If the + * document was deleted since the updated happened, it will be null. + */ + fullDocument?: TSchema; +} + +/** @public */ +export interface UpdateDescription { + /** + * A document containing key:value pairs of names of the fields that were + * changed, and the new value for those fields. + */ + updatedFields: Partial; + + /** + * An array of field names that were removed from the document. + */ + removedFields: string[]; +} + +/** @public */ +export type ChangeStreamEvents = { + resumeTokenChanged(token: ResumeToken): void; + init(response: Document): void; + more(response?: Document | undefined): void; + response(): void; + end(): void; + error(error: Error): void; + change(change: ChangeStreamDocument): void; +} & AbstractCursorEvents; + +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @public + */ +export class ChangeStream< + TSchema extends Document = Document +> extends TypedEventEmitter { + pipeline: Document[]; + options: ChangeStreamOptions; + parent: MongoClient | Db | Collection; + namespace: MongoDBNamespace; + type: symbol; + /** @internal */ + cursor?: ChangeStreamCursor; + streamOptions?: CursorStreamOptions; + /** @internal */ + [kResumeQueue]: Denque>>; + /** @internal */ + [kCursorStream]?: Readable; + /** @internal */ + [kClosed]: boolean; + /** @internal */ + [kMode]: false | 'iterator' | 'emitter'; + + /** @event */ + static readonly RESPONSE = 'response' as const; + /** @event */ + static readonly MORE = 'more' as const; + /** @event */ + static readonly INIT = 'init' as const; + /** @event */ + static readonly CLOSE = 'close' as const; + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * @event + */ + static readonly CHANGE = 'change' as const; + /** @event */ + static readonly END = 'end' as const; + /** @event */ + static readonly ERROR = 'error' as const; + /** + * Emitted each time the change stream stores a new resume token. + * @event + */ + static readonly RESUME_TOKEN_CHANGED = 'resumeTokenChanged' as const; + + /** + * @internal + * + * @param parent - The parent object that created this change stream + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + */ + constructor( + parent: OperationParent, + pipeline: Document[] = [], + options: ChangeStreamOptions = {} + ) { + super(); + + this.pipeline = pipeline; + this.options = options; + + if (parent instanceof Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + } else if (parent instanceof Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + } else if (parent instanceof MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + } else { + throw new MongoChangeStreamError( + 'Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient' + ); + } + + this.parent = parent; + this.namespace = parent.s.namespace; + if (!this.options.readPreference && parent.readPreference) { + this.options.readPreference = parent.readPreference; + } + + this[kResumeQueue] = new Denque(); + + // Create contained Change Stream cursor + this.cursor = createChangeStreamCursor(this, options); + + this[kClosed] = false; + this[kMode] = false; + + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + streamEvents(this, this.cursor); + } + }); + + this.on('removeListener', eventName => { + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + this[kCursorStream]?.removeAllListeners('data'); + } + }); + } + + /** @internal */ + get cursorStream(): Readable | undefined { + return this[kCursorStream]; + } + + /** The cached resume token that is used to resume after the most recently returned change. */ + get resumeToken(): ResumeToken { + return this.cursor?.resumeToken; + } + + /** Check if there is any document still available in the Change Stream */ + hasNext(callback?: Callback): Promise | void { + setIsIterator(this); + return maybePromise(callback, cb => { + getCursor(this, (err, cursor) => { + if (err || !cursor) return cb(err); // failed to resume, raise an error + cursor.hasNext(cb); + }); + }); + } + + /** Get the next available document from the Change Stream. */ + next(): Promise>; + next(callback: Callback>): void; + next( + callback?: Callback> + ): Promise> | void { + setIsIterator(this); + return maybePromise(callback, cb => { + getCursor(this, (err, cursor) => { + if (err || !cursor) return cb(err); // failed to resume, raise an error + cursor.next((error, change) => { + if (error) { + this[kResumeQueue].push(() => this.next(cb)); + processError(this, error, cb); + return; + } + processNewChange(this, change, cb); + }); + }); + }); + } + + /** Is the cursor closed */ + get closed(): boolean { + return this[kClosed] || (this.cursor?.closed ?? false); + } + + /** Close the Change Stream */ + close(callback?: Callback): Promise | void { + this[kClosed] = true; + + return maybePromise(callback, cb => { + if (!this.cursor) { + return cb(); + } + + const cursor = this.cursor; + return cursor.close(err => { + endStream(this); + this.cursor = undefined; + return cb(err); + }); + }); + } + + /** + * Return a modified Readable stream including a possible transform method. + * @throws MongoDriverError if this.cursor is undefined + */ + stream(options?: CursorStreamOptions): Readable { + this.streamOptions = options; + if (!this.cursor) throw new MongoChangeStreamError(NO_CURSOR_ERROR); + return this.cursor.stream(options); + } + + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + tryNext(callback: Callback): void; + tryNext(callback?: Callback): Promise | void { + setIsIterator(this); + return maybePromise(callback, cb => { + getCursor(this, (err, cursor) => { + if (err || !cursor) return cb(err); // failed to resume, raise an error + return cursor.tryNext(cb); + }); + }); + } +} + +/** @internal */ +export interface ChangeStreamCursorOptions extends AbstractCursorOptions { + startAtOperationTime?: OperationTime; + resumeAfter?: ResumeToken; + startAfter?: boolean; +} + +/** @internal */ +export class ChangeStreamCursor extends AbstractCursor< + ChangeStreamDocument, + ChangeStreamEvents +> { + _resumeToken: ResumeToken; + startAtOperationTime?: OperationTime; + hasReceived?: boolean; + resumeAfter: ResumeToken; + startAfter: ResumeToken; + options: ChangeStreamCursorOptions; + + postBatchResumeToken?: ResumeToken; + pipeline: Document[]; + + constructor( + topology: Topology, + namespace: MongoDBNamespace, + pipeline: Document[] = [], + options: ChangeStreamCursorOptions = {} + ) { + super(topology, namespace, options); + + this.pipeline = pipeline; + this.options = options; + this._resumeToken = null; + this.startAtOperationTime = options.startAtOperationTime; + + if (options.startAfter) { + this.resumeToken = options.startAfter; + } else if (options.resumeAfter) { + this.resumeToken = options.resumeAfter; + } + } + + set resumeToken(token: ResumeToken) { + this._resumeToken = token; + this.emit(ChangeStream.RESUME_TOKEN_CHANGED, token); + } + + get resumeToken(): ResumeToken { + return this._resumeToken; + } + + get resumeOptions(): ResumeOptions { + const result = {} as ResumeOptions; + for (const optionName of CURSOR_OPTIONS) { + if (Reflect.has(this.options, optionName)) { + Reflect.set(result, optionName, Reflect.get(this.options, optionName)); + } + } + + if (this.resumeToken || this.startAtOperationTime) { + ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => + Reflect.deleteProperty(result, key) + ); + + if (this.resumeToken) { + const resumeKey = + this.options.startAfter && !this.hasReceived ? 'startAfter' : 'resumeAfter'; + Reflect.set(result, resumeKey, this.resumeToken); + } else if (this.startAtOperationTime && maxWireVersion(this.server) >= 7) { + result.startAtOperationTime = this.startAtOperationTime; + } + } + + return result; + } + + cacheResumeToken(resumeToken: ResumeToken): void { + if (this.bufferedCount() === 0 && this.postBatchResumeToken) { + this.resumeToken = this.postBatchResumeToken; + } else { + this.resumeToken = resumeToken; + } + this.hasReceived = true; + } + + _processBatch(batchName: string, response?: Document): void { + const cursor = response?.cursor || {}; + if (cursor.postBatchResumeToken) { + this.postBatchResumeToken = cursor.postBatchResumeToken; + + if (cursor[batchName].length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + } + + clone(): AbstractCursor> { + return new ChangeStreamCursor(this.topology, this.namespace, this.pipeline, { + ...this.cursorOptions + }); + } + + _initialize(session: ClientSession, callback: Callback): void { + const aggregateOperation = new AggregateOperation(this.namespace, this.pipeline, { + ...this.cursorOptions, + ...this.options, + session + }); + + executeOperation(this.topology, aggregateOperation, (err, response) => { + if (err || response == null) { + return callback(err); + } + + const server = aggregateOperation.server; + if ( + this.startAtOperationTime == null && + this.resumeAfter == null && + this.startAfter == null && + maxWireVersion(server) >= 7 + ) { + this.startAtOperationTime = response.operationTime; + } + + this._processBatch('firstBatch', response); + + this.emit(ChangeStream.INIT, response); + this.emit(ChangeStream.RESPONSE); + + // TODO: NODE-2882 + callback(undefined, { server, session, response }); + }); + } + + _getMore(batchSize: number, callback: Callback): void { + super._getMore(batchSize, (err, response) => { + if (err) { + return callback(err); + } + + this._processBatch('nextBatch', response); + + this.emit(ChangeStream.MORE, response); + this.emit(ChangeStream.RESPONSE); + callback(err, response); + }); + } +} + +const CHANGE_STREAM_EVENTS = [ + ChangeStream.RESUME_TOKEN_CHANGED, + ChangeStream.END, + ChangeStream.CLOSE +]; + +function setIsEmitter(changeStream: ChangeStream): void { + if (changeStream[kMode] === 'iterator') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new MongoAPIError( + 'ChangeStream cannot be used as an EventEmitter after being used as an iterator' + ); + } + changeStream[kMode] = 'emitter'; +} + +function setIsIterator(changeStream: ChangeStream): void { + if (changeStream[kMode] === 'emitter') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new MongoAPIError( + 'ChangeStream cannot be used as an iterator after being used as an EventEmitter' + ); + } + changeStream[kMode] = 'iterator'; +} +/** + * Create a new change stream cursor based on self's configuration + * @internal + */ +function createChangeStreamCursor( + changeStream: ChangeStream, + options: ChangeStreamOptions +): ChangeStreamCursor { + const changeStreamStageOptions: Document = { fullDocument: options.fullDocument || 'default' }; + applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS); + if (changeStream.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + + const pipeline = [{ $changeStream: changeStreamStageOptions } as Document].concat( + changeStream.pipeline + ); + + const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); + const changeStreamCursor = new ChangeStreamCursor( + getTopology(changeStream.parent), + changeStream.namespace, + pipeline, + cursorOptions + ); + + for (const event of CHANGE_STREAM_EVENTS) { + changeStreamCursor.on(event, e => changeStream.emit(event, e)); + } + + if (changeStream.listenerCount(ChangeStream.CHANGE) > 0) { + streamEvents(changeStream, changeStreamCursor); + } + + return changeStreamCursor; +} + +function applyKnownOptions(target: Document, source: Document, optionNames: string[]) { + optionNames.forEach(name => { + if (source[name]) { + target[name] = source[name]; + } + }); + + return target; +} + +interface TopologyWaitOptions { + start?: number; + timeout?: number; + readPreference?: ReadPreference; +} +// This method performs a basic server selection loop, satisfying the requirements of +// ChangeStream resumability until the new SDAM layer can be used. +const SELECTION_TIMEOUT = 30000; +function waitForTopologyConnected( + topology: Topology, + options: TopologyWaitOptions, + callback: Callback +) { + setTimeout(() => { + if (options && options.start == null) { + options.start = now(); + } + + const start = options.start || now(); + const timeout = options.timeout || SELECTION_TIMEOUT; + if (topology.isConnected()) { + return callback(); + } + + if (calculateDurationInMs(start) > timeout) { + // TODO(NODE-3497): Replace with MongoNetworkTimeoutError + return callback(new MongoRuntimeError('Timed out waiting for connection')); + } + + waitForTopologyConnected(topology, options, callback); + }, 500); // this is an arbitrary wait time to allow SDAM to transition +} + +function closeWithError( + changeStream: ChangeStream, + error: AnyError, + callback?: Callback +): void { + if (!callback) { + changeStream.emit(ChangeStream.ERROR, error); + } + + changeStream.close(() => callback && callback(error)); +} + +function streamEvents( + changeStream: ChangeStream, + cursor: ChangeStreamCursor +): void { + setIsEmitter(changeStream); + const stream = changeStream[kCursorStream] || cursor.stream(); + changeStream[kCursorStream] = stream; + stream.on('data', change => processNewChange(changeStream, change)); + stream.on('error', error => processError(changeStream, error)); +} + +function endStream(changeStream: ChangeStream): void { + const cursorStream = changeStream[kCursorStream]; + if (cursorStream) { + ['data', 'close', 'end', 'error'].forEach(event => cursorStream.removeAllListeners(event)); + cursorStream.destroy(); + } + + changeStream[kCursorStream] = undefined; +} + +function processNewChange( + changeStream: ChangeStream, + change: Nullable>, + callback?: Callback> +) { + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + if (callback) callback(new MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + return; + } + + // a null change means the cursor has been notified, implicitly closing the change stream + if (change == null) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + return closeWithError(changeStream, new MongoRuntimeError(CHANGESTREAM_CLOSED_ERROR), callback); + } + + if (change && !change._id) { + return closeWithError( + changeStream, + new MongoChangeStreamError(NO_RESUME_TOKEN_ERROR), + callback + ); + } + + // cache the resume token + changeStream.cursor?.cacheResumeToken(change._id); + + // wipe the startAtOperationTime if there was one so that there won't be a conflict + // between resumeToken and startAtOperationTime if we need to reconnect the cursor + changeStream.options.startAtOperationTime = undefined; + + // Return the change + if (!callback) return changeStream.emit(ChangeStream.CHANGE, change); + return callback(undefined, change); +} + +function processError( + changeStream: ChangeStream, + error: AnyError, + callback?: Callback +) { + const cursor = changeStream.cursor; + + // If the change stream has been closed explicitly, do not process error. + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + if (callback) callback(new MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + return; + } + + // if the resume succeeds, continue with the new cursor + function resumeWithCursor(newCursor: ChangeStreamCursor) { + changeStream.cursor = newCursor; + processResumeQueue(changeStream); + } + + // otherwise, raise an error and close the change stream + function unresumableError(err: AnyError) { + if (!callback) { + changeStream.emit(ChangeStream.ERROR, err); + } + + changeStream.close(() => processResumeQueue(changeStream, err)); + } + + if (cursor && isResumableError(error as MongoError, maxWireVersion(cursor.server))) { + changeStream.cursor = undefined; + + // stop listening to all events from old cursor + endStream(changeStream); + + // close internal cursor, ignore errors + cursor.close(); + + const topology = getTopology(changeStream.parent); + waitForTopologyConnected(topology, { readPreference: cursor.readPreference }, err => { + // if the topology can't reconnect, close the stream + if (err) return unresumableError(err); + + // create a new cursor, preserving the old cursor's options + const newCursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); + + // attempt to continue in emitter mode + if (!callback) return resumeWithCursor(newCursor); + + // attempt to continue in iterator mode + newCursor.hasNext(err => { + // if there's an error immediately after resuming, close the stream + if (err) return unresumableError(err); + resumeWithCursor(newCursor); + }); + }); + return; + } + + // if initial error wasn't resumable, raise an error and close the change stream + return closeWithError(changeStream, error, callback); +} + +/** + * Safely provides a cursor across resume attempts + * + * @param changeStream - the parent ChangeStream + */ +function getCursor(changeStream: ChangeStream, callback: Callback>) { + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + callback(new MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + return; + } + + // if a cursor exists and it is open, return it + if (changeStream.cursor) { + callback(undefined, changeStream.cursor); + return; + } + + // no cursor, queue callback until topology reconnects + changeStream[kResumeQueue].push(callback); +} + +/** + * Drain the resume queue when a new has become available + * + * @param changeStream - the parent ChangeStream + * @param err - error getting a new cursor + */ +function processResumeQueue(changeStream: ChangeStream, err?: Error) { + while (changeStream[kResumeQueue].length) { + const request = changeStream[kResumeQueue].pop(); + if (!request) break; // Should never occur but TS can't use the length check in the while condition + + if (!err) { + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + request(new MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + return; + } + if (!changeStream.cursor) { + request(new MongoChangeStreamError(NO_CURSOR_ERROR)); + return; + } + } + request(err, changeStream.cursor); + } +} diff --git a/node_modules/mongodb/src/cmap/auth/auth_provider.ts b/node_modules/mongodb/src/cmap/auth/auth_provider.ts new file mode 100644 index 0000000..306ebd1 --- /dev/null +++ b/node_modules/mongodb/src/cmap/auth/auth_provider.ts @@ -0,0 +1,60 @@ +import type { Document } from '../../bson'; +import type { Connection, ConnectionOptions } from '../connection'; +import type { MongoCredentials } from './mongo_credentials'; +import type { HandshakeDocument } from '../connect'; +import type { ClientMetadataOptions, Callback } from '../../utils'; +import { MongoRuntimeError } from '../../error'; + +export type AuthContextOptions = ConnectionOptions & ClientMetadataOptions; + +/** Context used during authentication */ +export class AuthContext { + /** The connection to authenticate */ + connection: Connection; + /** The credentials to use for authentication */ + credentials?: MongoCredentials; + /** The options passed to the `connect` method */ + options: AuthContextOptions; + + /** A response from an initial auth attempt, only some mechanisms use this (e.g, SCRAM) */ + response?: Document; + /** A random nonce generated for use in an authentication conversation */ + nonce?: Buffer; + + constructor( + connection: Connection, + credentials: MongoCredentials | undefined, + options: AuthContextOptions + ) { + this.connection = connection; + this.credentials = credentials; + this.options = options; + } +} + +export class AuthProvider { + /** + * Prepare the handshake document before the initial handshake. + * + * @param handshakeDoc - The document used for the initial handshake on a connection + * @param authContext - Context for authentication flow + */ + prepare( + handshakeDoc: HandshakeDocument, + authContext: AuthContext, + callback: Callback + ): void { + callback(undefined, handshakeDoc); + } + + /** + * Authenticate + * + * @param context - A shared context for authentication flow + * @param callback - The callback to return the result from the authentication + */ + auth(context: AuthContext, callback: Callback): void { + // TODO(NODE-3483): Replace this with MongoMethodOverrideError + callback(new MongoRuntimeError('`auth` method must be overridden by subclass')); + } +} diff --git a/node_modules/mongodb/src/cmap/auth/defaultAuthProviders.ts b/node_modules/mongodb/src/cmap/auth/defaultAuthProviders.ts new file mode 100644 index 0000000..df937d4 --- /dev/null +++ b/node_modules/mongodb/src/cmap/auth/defaultAuthProviders.ts @@ -0,0 +1,32 @@ +import { MongoCR } from './mongocr'; +import { X509 } from './x509'; +import { Plain } from './plain'; +import { GSSAPI } from './gssapi'; +import { ScramSHA1, ScramSHA256 } from './scram'; +import { MongoDBAWS } from './mongodb_aws'; +import type { AuthProvider } from './auth_provider'; + +/** @public */ +export const AuthMechanism = Object.freeze({ + MONGODB_AWS: 'MONGODB-AWS', + MONGODB_CR: 'MONGODB-CR', + MONGODB_DEFAULT: 'DEFAULT', + MONGODB_GSSAPI: 'GSSAPI', + MONGODB_PLAIN: 'PLAIN', + MONGODB_SCRAM_SHA1: 'SCRAM-SHA-1', + MONGODB_SCRAM_SHA256: 'SCRAM-SHA-256', + MONGODB_X509: 'MONGODB-X509' +} as const); + +/** @public */ +export type AuthMechanism = typeof AuthMechanism[keyof typeof AuthMechanism]; + +export const AUTH_PROVIDERS = new Map([ + [AuthMechanism.MONGODB_AWS, new MongoDBAWS()], + [AuthMechanism.MONGODB_CR, new MongoCR()], + [AuthMechanism.MONGODB_GSSAPI, new GSSAPI()], + [AuthMechanism.MONGODB_PLAIN, new Plain()], + [AuthMechanism.MONGODB_SCRAM_SHA1, new ScramSHA1()], + [AuthMechanism.MONGODB_SCRAM_SHA256, new ScramSHA256()], + [AuthMechanism.MONGODB_X509, new X509()] +]); diff --git a/node_modules/mongodb/src/cmap/auth/gssapi.ts b/node_modules/mongodb/src/cmap/auth/gssapi.ts new file mode 100644 index 0000000..e12d960 --- /dev/null +++ b/node_modules/mongodb/src/cmap/auth/gssapi.ts @@ -0,0 +1,190 @@ +import { AuthProvider, AuthContext } from './auth_provider'; +import { + MongoRuntimeError, + MongoInvalidArgumentError, + MongoMissingCredentialsError, + MongoError, + MongoMissingDependencyError +} from '../../error'; +import { Kerberos, KerberosClient } from '../../deps'; +import { Callback, ns } from '../../utils'; +import type { Document } from '../../bson'; + +type MechanismProperties = { + gssapiCanonicalizeHostName?: boolean; + SERVICE_NAME?: string; + SERVICE_REALM?: string; +}; + +import * as dns from 'dns'; + +export class GSSAPI extends AuthProvider { + auth(authContext: AuthContext, callback: Callback): void { + const { connection, credentials } = authContext; + if (credentials == null) + return callback( + new MongoMissingCredentialsError('Credentials required for GSSAPI authentication') + ); + const { username } = credentials; + function externalCommand( + command: Document, + cb: Callback<{ payload: string; conversationId: any }> + ) { + return connection.command(ns('$external.$cmd'), command, undefined, cb); + } + makeKerberosClient(authContext, (err, client) => { + if (err) return callback(err); + if (client == null) return callback(new MongoMissingDependencyError('GSSAPI client missing')); + client.step('', (err, payload) => { + if (err) return callback(err); + + externalCommand(saslStart(payload), (err, result) => { + if (err) return callback(err); + if (result == null) return callback(); + negotiate(client, 10, result.payload, (err, payload) => { + if (err) return callback(err); + + externalCommand(saslContinue(payload, result.conversationId), (err, result) => { + if (err) return callback(err); + if (result == null) return callback(); + finalize(client, username, result.payload, (err, payload) => { + if (err) return callback(err); + + externalCommand( + { + saslContinue: 1, + conversationId: result.conversationId, + payload + }, + (err, result) => { + if (err) return callback(err); + + callback(undefined, result); + } + ); + }); + }); + }); + }); + }); + }); + } +} +function makeKerberosClient(authContext: AuthContext, callback: Callback): void { + const { hostAddress } = authContext.options; + const { credentials } = authContext; + if (!hostAddress || typeof hostAddress.host !== 'string' || !credentials) { + return callback( + new MongoInvalidArgumentError('Connection must have host and port and credentials defined.') + ); + } + + if ('kModuleError' in Kerberos) { + return callback(Kerberos['kModuleError']); + } + const { initializeClient } = Kerberos; + + const { username, password } = credentials; + const mechanismProperties = credentials.mechanismProperties as MechanismProperties; + + const serviceName = mechanismProperties.SERVICE_NAME ?? 'mongodb'; + + performGssapiCanonicalizeHostName( + hostAddress.host, + mechanismProperties, + (err?: Error | MongoError, host?: string) => { + if (err) return callback(err); + + const initOptions = {}; + if (password != null) { + Object.assign(initOptions, { user: username, password: password }); + } + + let spn = `${serviceName}${process.platform === 'win32' ? '/' : '@'}${host}`; + if ('SERVICE_REALM' in mechanismProperties) { + spn = `${spn}@${mechanismProperties.SERVICE_REALM}`; + } + + initializeClient(spn, initOptions, (err: string, client: KerberosClient): void => { + // TODO(NODE-3483) + if (err) return callback(new MongoRuntimeError(err)); + callback(undefined, client); + }); + } + ); +} + +function saslStart(payload?: string): Document { + return { + saslStart: 1, + mechanism: 'GSSAPI', + payload, + autoAuthorize: 1 + }; +} + +function saslContinue(payload?: string, conversationId?: number): Document { + return { + saslContinue: 1, + conversationId, + payload + }; +} + +function negotiate( + client: KerberosClient, + retries: number, + payload: string, + callback: Callback +): void { + client.step(payload, (err, response) => { + // Retries exhausted, raise error + if (err && retries === 0) return callback(err); + + // Adjust number of retries and call step again + if (err) return negotiate(client, retries - 1, payload, callback); + + // Return the payload + callback(undefined, response || ''); + }); +} + +function finalize( + client: KerberosClient, + user: string, + payload: string, + callback: Callback +): void { + // GSS Client Unwrap + client.unwrap(payload, (err, response) => { + if (err) return callback(err); + + // Wrap the response + client.wrap(response || '', { user }, (err, wrapped) => { + if (err) return callback(err); + + // Return the payload + callback(undefined, wrapped); + }); + }); +} + +function performGssapiCanonicalizeHostName( + host: string, + mechanismProperties: MechanismProperties, + callback: Callback +): void { + if (!mechanismProperties.gssapiCanonicalizeHostName) return callback(undefined, host); + + // Attempt to resolve the host name + dns.resolveCname(host, (err, r) => { + if (err) return callback(err); + + // Get the first resolve host id + if (Array.isArray(r) && r.length > 0) { + return callback(undefined, r[0]); + } + + callback(undefined, host); + }); +} diff --git a/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts b/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts new file mode 100644 index 0000000..cbc4007 --- /dev/null +++ b/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts @@ -0,0 +1,179 @@ +// Resolves the default auth mechanism according to + +import type { Document } from '../../bson'; +import { MongoAPIError, MongoMissingCredentialsError } from '../../error'; +import { AuthMechanism } from './defaultAuthProviders'; + +// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst +function getDefaultAuthMechanism(ismaster?: Document): AuthMechanism { + if (ismaster) { + // If ismaster contains saslSupportedMechs, use scram-sha-256 + // if it is available, else scram-sha-1 + if (Array.isArray(ismaster.saslSupportedMechs)) { + return ismaster.saslSupportedMechs.includes(AuthMechanism.MONGODB_SCRAM_SHA256) + ? AuthMechanism.MONGODB_SCRAM_SHA256 + : AuthMechanism.MONGODB_SCRAM_SHA1; + } + + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (ismaster.maxWireVersion >= 3) { + return AuthMechanism.MONGODB_SCRAM_SHA1; + } + } + + // Default for wireprotocol < 3 + return AuthMechanism.MONGODB_CR; +} + +/** @public */ +export interface AuthMechanismProperties extends Document { + SERVICE_NAME?: string; + SERVICE_REALM?: string; + CANONICALIZE_HOST_NAME?: boolean; + AWS_SESSION_TOKEN?: string; +} + +/** @public */ +export interface MongoCredentialsOptions { + username: string; + password: string; + source: string; + db?: string; + mechanism?: AuthMechanism; + mechanismProperties: AuthMechanismProperties; +} + +/** + * A representation of the credentials used by MongoDB + * @public + */ +export class MongoCredentials { + /** The username used for authentication */ + readonly username: string; + /** The password used for authentication */ + readonly password: string; + /** The database that the user should authenticate against */ + readonly source: string; + /** The method used to authenticate */ + readonly mechanism: AuthMechanism; + /** Special properties used by some types of auth mechanisms */ + readonly mechanismProperties: AuthMechanismProperties; + + constructor(options: MongoCredentialsOptions) { + this.username = options.username; + this.password = options.password; + this.source = options.source; + if (!this.source && options.db) { + this.source = options.db; + } + this.mechanism = options.mechanism || AuthMechanism.MONGODB_DEFAULT; + this.mechanismProperties = options.mechanismProperties || {}; + + if (this.mechanism.match(/MONGODB-AWS/i)) { + if (!this.username && process.env.AWS_ACCESS_KEY_ID) { + this.username = process.env.AWS_ACCESS_KEY_ID; + } + + if (!this.password && process.env.AWS_SECRET_ACCESS_KEY) { + this.password = process.env.AWS_SECRET_ACCESS_KEY; + } + + if ( + this.mechanismProperties.AWS_SESSION_TOKEN == null && + process.env.AWS_SESSION_TOKEN != null + ) { + this.mechanismProperties = { + ...this.mechanismProperties, + AWS_SESSION_TOKEN: process.env.AWS_SESSION_TOKEN + }; + } + } + + Object.freeze(this.mechanismProperties); + Object.freeze(this); + } + + /** Determines if two MongoCredentials objects are equivalent */ + equals(other: MongoCredentials): boolean { + return ( + this.mechanism === other.mechanism && + this.username === other.username && + this.password === other.password && + this.source === other.source + ); + } + + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param ismaster - An ismaster response from the server + */ + resolveAuthMechanism(ismaster?: Document): MongoCredentials { + // If the mechanism is not "default", then it does not need to be resolved + if (this.mechanism.match(/DEFAULT/i)) { + return new MongoCredentials({ + username: this.username, + password: this.password, + source: this.source, + mechanism: getDefaultAuthMechanism(ismaster), + mechanismProperties: this.mechanismProperties + }); + } + + return this; + } + + validate(): void { + if ( + (this.mechanism === AuthMechanism.MONGODB_GSSAPI || + this.mechanism === AuthMechanism.MONGODB_CR || + this.mechanism === AuthMechanism.MONGODB_PLAIN || + this.mechanism === AuthMechanism.MONGODB_SCRAM_SHA1 || + this.mechanism === AuthMechanism.MONGODB_SCRAM_SHA256) && + !this.username + ) { + throw new MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`); + } + + if ( + this.mechanism === AuthMechanism.MONGODB_GSSAPI || + this.mechanism === AuthMechanism.MONGODB_AWS || + this.mechanism === AuthMechanism.MONGODB_X509 + ) { + if (this.source != null && this.source !== '$external') { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new MongoAPIError( + `Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.` + ); + } + } + + if (this.mechanism === AuthMechanism.MONGODB_PLAIN && this.source == null) { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new MongoAPIError('PLAIN Authentication Mechanism needs an auth source'); + } + + if (this.mechanism === AuthMechanism.MONGODB_X509 && this.password != null) { + if (this.password === '') { + Reflect.set(this, 'password', undefined); + return; + } + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new MongoAPIError(`Password not allowed for mechanism MONGODB-X509`); + } + } + + static merge( + creds: MongoCredentials | undefined, + options: Partial + ): MongoCredentials { + return new MongoCredentials({ + username: options.username ?? creds?.username ?? '', + password: options.password ?? creds?.password ?? '', + mechanism: options.mechanism ?? creds?.mechanism ?? AuthMechanism.MONGODB_DEFAULT, + mechanismProperties: options.mechanismProperties ?? creds?.mechanismProperties ?? {}, + source: options.source ?? options.db ?? creds?.source ?? 'admin' + }); + } +} diff --git a/node_modules/mongodb/src/cmap/auth/mongocr.ts b/node_modules/mongodb/src/cmap/auth/mongocr.ts new file mode 100644 index 0000000..fa801ca --- /dev/null +++ b/node_modules/mongodb/src/cmap/auth/mongocr.ts @@ -0,0 +1,46 @@ +import * as crypto from 'crypto'; +import { AuthProvider, AuthContext } from './auth_provider'; +import { Callback, ns } from '../../utils'; +import { MongoMissingCredentialsError } from '../../error'; + +export class MongoCR extends AuthProvider { + auth(authContext: AuthContext, callback: Callback): void { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const username = credentials.username; + const password = credentials.password; + const source = credentials.source; + connection.command(ns(`${source}.$cmd`), { getnonce: 1 }, undefined, (err, r) => { + let nonce = null; + let key = null; + + // Get nonce + if (err == null) { + nonce = r.nonce; + + // Use node md5 generator + let md5 = crypto.createHash('md5'); + + // Generate keys used for authentication + md5.update(`${username}:mongo:${password}`, 'utf8'); + const hash_password = md5.digest('hex'); + + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + + const authenticateCommand = { + authenticate: 1, + user: username, + nonce, + key + }; + + connection.command(ns(`${source}.$cmd`), authenticateCommand, undefined, callback); + }); + } +} diff --git a/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts b/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts new file mode 100644 index 0000000..a6cb48a --- /dev/null +++ b/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts @@ -0,0 +1,289 @@ +import * as http from 'http'; +import * as crypto from 'crypto'; +import * as url from 'url'; +import * as BSON from '../../bson'; +import { AuthProvider, AuthContext } from './auth_provider'; +import { MongoCredentials } from './mongo_credentials'; +import { + MongoRuntimeError, + MongoMissingCredentialsError, + MongoCompatibilityError +} from '../../error'; +import { maxWireVersion, Callback, ns } from '../../utils'; +import type { BSONSerializeOptions } from '../../bson'; + +import { aws4 } from '../../deps'; +import { AuthMechanism } from './defaultAuthProviders'; +import type { Binary } from 'bson'; + +const ASCII_N = 110; +const AWS_RELATIVE_URI = 'http://169.254.170.2'; +const AWS_EC2_URI = 'http://169.254.169.254'; +const AWS_EC2_PATH = '/latest/meta-data/iam/security-credentials'; +const bsonOptions: BSONSerializeOptions = { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false +}; + +interface AWSSaslContinuePayload { + a: string; + d: string; + t?: string; +} + +export class MongoDBAWS extends AuthProvider { + auth(authContext: AuthContext, callback: Callback): void { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + + if ('kModuleError' in aws4) { + return callback(aws4['kModuleError']); + } + const { sign } = aws4; + + if (maxWireVersion(connection) < 9) { + callback( + new MongoCompatibilityError( + 'MONGODB-AWS authentication requires MongoDB version 4.4 or later' + ) + ); + return; + } + + if (!credentials.username) { + makeTempCredentials(credentials, (err, tempCredentials) => { + if (err || !tempCredentials) return callback(err); + + authContext.credentials = tempCredentials; + this.auth(authContext, callback); + }); + + return; + } + + const accessKeyId = credentials.username; + const secretAccessKey = credentials.password; + const sessionToken = credentials.mechanismProperties.AWS_SESSION_TOKEN; + + // If all three defined, include sessionToken, else include username and pass, else no credentials + const awsCredentials = + accessKeyId && secretAccessKey && sessionToken + ? { accessKeyId, secretAccessKey, sessionToken } + : accessKeyId && secretAccessKey + ? { accessKeyId, secretAccessKey } + : undefined; + + const db = credentials.source; + crypto.randomBytes(32, (err, nonce) => { + if (err) { + callback(err); + return; + } + + const saslStart = { + saslStart: 1, + mechanism: 'MONGODB-AWS', + payload: BSON.serialize({ r: nonce, p: ASCII_N }, bsonOptions) + }; + + connection.command(ns(`${db}.$cmd`), saslStart, undefined, (err, res) => { + if (err) return callback(err); + + const serverResponse = BSON.deserialize(res.payload.buffer, bsonOptions) as { + s: Binary; + h: string; + }; + const host = serverResponse.h; + const serverNonce = serverResponse.s.buffer; + if (serverNonce.length !== 64) { + callback( + // TODO(NODE-3483) + new MongoRuntimeError(`Invalid server nonce length ${serverNonce.length}, expected 64`) + ); + + return; + } + + if (serverNonce.compare(nonce, 0, nonce.length, 0, nonce.length) !== 0) { + // TODO(NODE-3483) + callback(new MongoRuntimeError('Server nonce does not begin with client nonce')); + return; + } + + if (host.length < 1 || host.length > 255 || host.indexOf('..') !== -1) { + // TODO(NODE-3483) + callback(new MongoRuntimeError(`Server returned an invalid host: "${host}"`)); + return; + } + + const body = 'Action=GetCallerIdentity&Version=2011-06-15'; + const options = sign( + { + method: 'POST', + host, + region: deriveRegion(serverResponse.h), + service: 'sts', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Length': body.length, + 'X-MongoDB-Server-Nonce': serverNonce.toString('base64'), + 'X-MongoDB-GS2-CB-Flag': 'n' + }, + path: '/', + body + }, + awsCredentials + ); + + const payload: AWSSaslContinuePayload = { + a: options.headers.Authorization, + d: options.headers['X-Amz-Date'] + }; + if (sessionToken) { + payload.t = sessionToken; + } + + const saslContinue = { + saslContinue: 1, + conversationId: 1, + payload: BSON.serialize(payload, bsonOptions) + }; + + connection.command(ns(`${db}.$cmd`), saslContinue, undefined, callback); + }); + }); + } +} + +interface AWSTempCredentials { + AccessKeyId?: string; + SecretAccessKey?: string; + Token?: string; + RoleArn?: string; + Expiration?: Date; +} + +function makeTempCredentials(credentials: MongoCredentials, callback: Callback) { + function done(creds: AWSTempCredentials) { + if (!creds.AccessKeyId || !creds.SecretAccessKey || !creds.Token) { + callback( + new MongoMissingCredentialsError('Could not obtain temporary MONGODB-AWS credentials') + ); + return; + } + + callback( + undefined, + new MongoCredentials({ + username: creds.AccessKeyId, + password: creds.SecretAccessKey, + source: credentials.source, + mechanism: AuthMechanism.MONGODB_AWS, + mechanismProperties: { + AWS_SESSION_TOKEN: creds.Token + } + }) + ); + } + + // If the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI + // is set then drivers MUST assume that it was set by an AWS ECS agent + if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) { + request( + `${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`, + undefined, + (err, res) => { + if (err) return callback(err); + done(res); + } + ); + + return; + } + + // Otherwise assume we are on an EC2 instance + + // get a token + request( + `${AWS_EC2_URI}/latest/api/token`, + { method: 'PUT', json: false, headers: { 'X-aws-ec2-metadata-token-ttl-seconds': 30 } }, + (err, token) => { + if (err) return callback(err); + + // get role name + request( + `${AWS_EC2_URI}/${AWS_EC2_PATH}`, + { json: false, headers: { 'X-aws-ec2-metadata-token': token } }, + (err, roleName) => { + if (err) return callback(err); + + // get temp credentials + request( + `${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, + { headers: { 'X-aws-ec2-metadata-token': token } }, + (err, creds) => { + if (err) return callback(err); + done(creds); + } + ); + } + ); + } + ); +} + +function deriveRegion(host: string) { + const parts = host.split('.'); + if (parts.length === 1 || parts[1] === 'amazonaws') { + return 'us-east-1'; + } + + return parts[1]; +} + +interface RequestOptions { + json?: boolean; + method?: string; + timeout?: number; + headers?: http.OutgoingHttpHeaders; +} + +function request(uri: string, _options: RequestOptions | undefined, callback: Callback) { + const options = Object.assign( + { + method: 'GET', + timeout: 10000, + json: true + }, + url.parse(uri), + _options + ); + + const req = http.request(options, res => { + res.setEncoding('utf8'); + + let data = ''; + res.on('data', d => (data += d)); + res.on('end', () => { + if (options.json === false) { + callback(undefined, data); + return; + } + + try { + const parsed = JSON.parse(data); + callback(undefined, parsed); + } catch (err) { + // TODO(NODE-3483) + callback(new MongoRuntimeError(`Invalid JSON response: "${data}"`)); + } + }); + }); + + req.on('error', err => callback(err)); + req.end(); +} diff --git a/node_modules/mongodb/src/cmap/auth/plain.ts b/node_modules/mongodb/src/cmap/auth/plain.ts new file mode 100644 index 0000000..afbca63 --- /dev/null +++ b/node_modules/mongodb/src/cmap/auth/plain.ts @@ -0,0 +1,25 @@ +import { Binary } from '../../bson'; +import { AuthProvider, AuthContext } from './auth_provider'; +import { MongoMissingCredentialsError } from '../../error'; +import { Callback, ns } from '../../utils'; + +export class Plain extends AuthProvider { + auth(authContext: AuthContext, callback: Callback): void { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const username = credentials.username; + const password = credentials.password; + + const payload = new Binary(Buffer.from(`\x00${username}\x00${password}`)); + const command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + + connection.command(ns('$external.$cmd'), command, undefined, callback); + } +} diff --git a/node_modules/mongodb/src/cmap/auth/scram.ts b/node_modules/mongodb/src/cmap/auth/scram.ts new file mode 100644 index 0000000..7c58eac --- /dev/null +++ b/node_modules/mongodb/src/cmap/auth/scram.ts @@ -0,0 +1,373 @@ +import * as crypto from 'crypto'; +import { Binary, Document } from '../../bson'; +import { + AnyError, + MongoRuntimeError, + MongoServerError, + MongoInvalidArgumentError, + MongoMissingCredentialsError +} from '../../error'; +import { AuthProvider, AuthContext } from './auth_provider'; +import { Callback, ns, emitWarning } from '../../utils'; +import type { MongoCredentials } from './mongo_credentials'; +import type { HandshakeDocument } from '../connect'; + +import { saslprep } from '../../deps'; +import { AuthMechanism } from './defaultAuthProviders'; + +type CryptoMethod = 'sha1' | 'sha256'; + +class ScramSHA extends AuthProvider { + cryptoMethod: CryptoMethod; + constructor(cryptoMethod: CryptoMethod) { + super(); + this.cryptoMethod = cryptoMethod || 'sha1'; + } + + prepare(handshakeDoc: HandshakeDocument, authContext: AuthContext, callback: Callback) { + const cryptoMethod = this.cryptoMethod; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (cryptoMethod === 'sha256' && saslprep == null) { + emitWarning('Warning: no saslprep library specified. Passwords will not be sanitized'); + } + + crypto.randomBytes(24, (err, nonce) => { + if (err) { + return callback(err); + } + + // store the nonce for later use + Object.assign(authContext, { nonce }); + + const request = Object.assign({}, handshakeDoc, { + speculativeAuthenticate: Object.assign(makeFirstMessage(cryptoMethod, credentials, nonce), { + db: credentials.source + }) + }); + + callback(undefined, request); + }); + } + + auth(authContext: AuthContext, callback: Callback) { + const response = authContext.response; + if (response && response.speculativeAuthenticate) { + continueScramConversation( + this.cryptoMethod, + response.speculativeAuthenticate, + authContext, + callback + ); + + return; + } + + executeScram(this.cryptoMethod, authContext, callback); + } +} + +function cleanUsername(username: string) { + return username.replace('=', '=3D').replace(',', '=2C'); +} + +function clientFirstMessageBare(username: string, nonce: Buffer) { + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return Buffer.concat([ + Buffer.from('n=', 'utf8'), + Buffer.from(username, 'utf8'), + Buffer.from(',r=', 'utf8'), + Buffer.from(nonce.toString('base64'), 'utf8') + ]); +} + +function makeFirstMessage( + cryptoMethod: CryptoMethod, + credentials: MongoCredentials, + nonce: Buffer +) { + const username = cleanUsername(credentials.username); + const mechanism = + cryptoMethod === 'sha1' ? AuthMechanism.MONGODB_SCRAM_SHA1 : AuthMechanism.MONGODB_SCRAM_SHA256; + + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return { + saslStart: 1, + mechanism, + payload: new Binary( + Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)]) + ), + autoAuthorize: 1, + options: { skipEmptyExchange: true } + }; +} + +function executeScram(cryptoMethod: CryptoMethod, authContext: AuthContext, callback: Callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (!authContext.nonce) { + return callback( + new MongoInvalidArgumentError('AuthContext must contain a valid nonce property') + ); + } + const nonce = authContext.nonce; + const db = credentials.source; + + const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce); + connection.command(ns(`${db}.$cmd`), saslStartCmd, undefined, (_err, result) => { + const err = resolveError(_err, result); + if (err) { + return callback(err); + } + + continueScramConversation(cryptoMethod, result, authContext, callback); + }); +} + +function continueScramConversation( + cryptoMethod: CryptoMethod, + response: Document, + authContext: AuthContext, + callback: Callback +) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (!authContext.nonce) { + return callback(new MongoInvalidArgumentError('Unable to continue SCRAM without valid nonce')); + } + const nonce = authContext.nonce; + + const db = credentials.source; + const username = cleanUsername(credentials.username); + const password = credentials.password; + + let processedPassword; + if (cryptoMethod === 'sha256') { + processedPassword = 'kModuleError' in saslprep ? password : saslprep(password); + } else { + try { + processedPassword = passwordDigest(username, password); + } catch (e) { + return callback(e); + } + } + + const payload = Buffer.isBuffer(response.payload) + ? new Binary(response.payload) + : response.payload; + const dict = parsePayload(payload.value()); + + const iterations = parseInt(dict.i, 10); + if (iterations && iterations < 4096) { + callback( + // TODO(NODE-3483) + new MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`), + false + ); + return; + } + + const salt = dict.s; + const rnonce = dict.r; + if (rnonce.startsWith('nonce')) { + // TODO(NODE-3483) + callback(new MongoRuntimeError(`Server returned an invalid nonce: ${rnonce}`), false); + return; + } + + // Set up start of proof + const withoutProof = `c=biws,r=${rnonce}`; + const saltedPassword = HI( + processedPassword, + Buffer.from(salt, 'base64'), + iterations, + cryptoMethod + ); + + const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); + const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key'); + const storedKey = H(cryptoMethod, clientKey); + const authMessage = [clientFirstMessageBare(username, nonce), payload.value(), withoutProof].join( + ',' + ); + + const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); + const clientProof = `p=${xor(clientKey, clientSignature)}`; + const clientFinal = [withoutProof, clientProof].join(','); + + const serverSignature = HMAC(cryptoMethod, serverKey, authMessage); + const saslContinueCmd = { + saslContinue: 1, + conversationId: response.conversationId, + payload: new Binary(Buffer.from(clientFinal)) + }; + + connection.command(ns(`${db}.$cmd`), saslContinueCmd, undefined, (_err, r) => { + const err = resolveError(_err, r); + if (err) { + return callback(err); + } + + const parsedResponse = parsePayload(r.payload.value()); + if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) { + callback(new MongoRuntimeError('Server returned an invalid signature')); + return; + } + + if (!r || r.done !== false) { + return callback(err, r); + } + + const retrySaslContinueCmd = { + saslContinue: 1, + conversationId: r.conversationId, + payload: Buffer.alloc(0) + }; + + connection.command(ns(`${db}.$cmd`), retrySaslContinueCmd, undefined, callback); + }); +} + +function parsePayload(payload: string) { + const dict: Document = {}; + const parts = payload.split(','); + for (let i = 0; i < parts.length; i++) { + const valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + + return dict; +} + +function passwordDigest(username: string, password: string) { + if (typeof username !== 'string') { + throw new MongoInvalidArgumentError('Username must be a string'); + } + + if (typeof password !== 'string') { + throw new MongoInvalidArgumentError('Password must be a string'); + } + + if (password.length === 0) { + throw new MongoInvalidArgumentError('Password cannot be empty'); + } + + const md5 = crypto.createHash('md5'); + md5.update(`${username}:mongo:${password}`, 'utf8'); + return md5.digest('hex'); +} + +// XOR two buffers +function xor(a: Buffer, b: Buffer) { + if (!Buffer.isBuffer(a)) { + a = Buffer.from(a); + } + + if (!Buffer.isBuffer(b)) { + b = Buffer.from(b); + } + + const length = Math.max(a.length, b.length); + const res = []; + + for (let i = 0; i < length; i += 1) { + res.push(a[i] ^ b[i]); + } + + return Buffer.from(res).toString('base64'); +} + +function H(method: CryptoMethod, text: Buffer) { + return crypto.createHash(method).update(text).digest(); +} + +function HMAC(method: CryptoMethod, key: Buffer, text: Buffer | string) { + return crypto.createHmac(method, key).update(text).digest(); +} + +interface HICache { + [key: string]: Buffer; +} + +let _hiCache: HICache = {}; +let _hiCacheCount = 0; +function _hiCachePurge() { + _hiCache = {}; + _hiCacheCount = 0; +} + +const hiLengthMap = { + sha256: 32, + sha1: 20 +}; + +function HI(data: string, salt: Buffer, iterations: number, cryptoMethod: CryptoMethod) { + // omit the work if already generated + const key = [data, salt.toString('base64'), iterations].join('_'); + if (_hiCache[key] != null) { + return _hiCache[key]; + } + + // generate the salt + const saltedData = crypto.pbkdf2Sync( + data, + salt, + iterations, + hiLengthMap[cryptoMethod], + cryptoMethod + ); + + // cache a copy to speed up the next lookup, but prevent unbounded cache growth + if (_hiCacheCount >= 200) { + _hiCachePurge(); + } + + _hiCache[key] = saltedData; + _hiCacheCount += 1; + return saltedData; +} + +function compareDigest(lhs: Buffer, rhs: Uint8Array) { + if (lhs.length !== rhs.length) { + return false; + } + + if (typeof crypto.timingSafeEqual === 'function') { + return crypto.timingSafeEqual(lhs, rhs); + } + + let result = 0; + for (let i = 0; i < lhs.length; i++) { + result |= lhs[i] ^ rhs[i]; + } + + return result === 0; +} + +function resolveError(err?: AnyError, result?: Document) { + if (err) return err; + if (result) { + if (result.$err || result.errmsg) return new MongoServerError(result); + } +} + +export class ScramSHA1 extends ScramSHA { + constructor() { + super('sha1'); + } +} + +export class ScramSHA256 extends ScramSHA { + constructor() { + super('sha256'); + } +} diff --git a/node_modules/mongodb/src/cmap/auth/x509.ts b/node_modules/mongodb/src/cmap/auth/x509.ts new file mode 100644 index 0000000..73f7688 --- /dev/null +++ b/node_modules/mongodb/src/cmap/auth/x509.ts @@ -0,0 +1,49 @@ +import { AuthProvider, AuthContext } from './auth_provider'; +import { MongoMissingCredentialsError } from '../../error'; +import type { Document } from '../../bson'; +import { Callback, ns } from '../../utils'; +import type { MongoCredentials } from './mongo_credentials'; +import type { HandshakeDocument } from '../connect'; + +export class X509 extends AuthProvider { + prepare(handshakeDoc: HandshakeDocument, authContext: AuthContext, callback: Callback): void { + const { credentials } = authContext; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + Object.assign(handshakeDoc, { + speculativeAuthenticate: x509AuthenticateCommand(credentials) + }); + + callback(undefined, handshakeDoc); + } + + auth(authContext: AuthContext, callback: Callback): void { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const response = authContext.response; + + if (response && response.speculativeAuthenticate) { + return callback(); + } + + connection.command( + ns('$external.$cmd'), + x509AuthenticateCommand(credentials), + undefined, + callback + ); + } +} + +function x509AuthenticateCommand(credentials: MongoCredentials) { + const command: Document = { authenticate: 1, mechanism: 'MONGODB-X509' }; + if (credentials.username) { + command.user = credentials.username; + } + + return command; +} diff --git a/node_modules/mongodb/src/cmap/command_monitoring_events.ts b/node_modules/mongodb/src/cmap/command_monitoring_events.ts new file mode 100644 index 0000000..5be6372 --- /dev/null +++ b/node_modules/mongodb/src/cmap/command_monitoring_events.ts @@ -0,0 +1,334 @@ +import { GetMore, KillCursor, Msg, WriteProtocolMessageType } from './commands'; +import { calculateDurationInMs, deepCopy } from '../utils'; +import type { Connection } from './connection'; +import type { Document, ObjectId } from '../bson'; + +/** + * An event indicating the start of a given + * @public + * @category Event + */ +export class CommandStartedEvent { + commandObj?: Document; + requestId: number; + databaseName: string; + commandName: string; + command: Document; + address: string; + connectionId?: string | number; + serviceId?: ObjectId; + + /** + * Create a started event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + */ + constructor(connection: Connection, command: WriteProtocolMessageType) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + + // TODO: remove in major revision, this is not spec behavior + if (SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.databaseName = databaseName(command); + this.commandName = commandName; + this.command = maybeRedact(commandName, cmd, cmd); + } + + /* @internal */ + get hasServiceId(): boolean { + return !!this.serviceId; + } +} + +/** + * An event indicating the success of a given command + * @public + * @category Event + */ +export class CommandSucceededEvent { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + reply: unknown; + serviceId?: ObjectId; + + /** + * Create a succeeded event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param reply - the reply for this command from the server + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor( + connection: Connection, + command: WriteProtocolMessageType, + reply: Document | undefined, + started: number + ) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = calculateDurationInMs(started); + this.reply = maybeRedact(commandName, cmd, extractReply(command, reply)); + } + + /* @internal */ + get hasServiceId(): boolean { + return !!this.serviceId; + } +} + +/** + * An event indicating the failure of a given command + * @public + * @category Event + */ +export class CommandFailedEvent { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + failure: Error; + serviceId?: ObjectId; + + /** + * Create a failure event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param error - the generated error or a server error response + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor( + connection: Connection, + command: WriteProtocolMessageType, + error: Error | Document, + started: number + ) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = calculateDurationInMs(started); + this.failure = maybeRedact(commandName, cmd, error) as Error; + } + + /* @internal */ + get hasServiceId(): boolean { + return !!this.serviceId; + } +} + +/** Commands that we want to redact because of the sensitive nature of their contents */ +const SENSITIVE_COMMANDS = new Set([ + 'authenticate', + 'saslStart', + 'saslContinue', + 'getnonce', + 'createUser', + 'updateUser', + 'copydbgetnonce', + 'copydbsaslstart', + 'copydb' +]); + +const HELLO_COMMANDS = new Set(['hello', 'ismaster', 'isMaster']); + +// helper methods +const extractCommandName = (commandDoc: Document) => Object.keys(commandDoc)[0]; +const namespace = (command: WriteProtocolMessageType) => command.ns; +const databaseName = (command: WriteProtocolMessageType) => command.ns.split('.')[0]; +const collectionName = (command: WriteProtocolMessageType) => command.ns.split('.')[1]; +const maybeRedact = (commandName: string, commandDoc: Document, result: Error | Document) => + SENSITIVE_COMMANDS.has(commandName) || + (HELLO_COMMANDS.has(commandName) && commandDoc.speculativeAuthenticate) + ? {} + : result; + +const LEGACY_FIND_QUERY_MAP: { [key: string]: string } = { + $query: 'filter', + $orderby: 'sort', + $hint: 'hint', + $comment: 'comment', + $maxScan: 'maxScan', + $max: 'max', + $min: 'min', + $returnKey: 'returnKey', + $showDiskLoc: 'showRecordId', + $maxTimeMS: 'maxTimeMS', + $snapshot: 'snapshot' +}; + +const LEGACY_FIND_OPTIONS_MAP = { + numberToSkip: 'skip', + numberToReturn: 'batchSize', + returnFieldSelector: 'projection' +} as const; + +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +] as const; + +/** Extract the actual command from the query, possibly up-converting if it's a legacy format */ +function extractCommand(command: WriteProtocolMessageType): Document { + if (command instanceof GetMore) { + return { + getMore: deepCopy(command.cursorId), + collection: collectionName(command), + batchSize: command.numberToReturn + }; + } + + if (command instanceof KillCursor) { + return { + killCursors: collectionName(command), + cursors: deepCopy(command.cursorIds) + }; + } + + if (command instanceof Msg) { + return deepCopy(command.command); + } + + if (command.query?.$query) { + let result: Document; + if (command.ns === 'admin.$cmd') { + // up-convert legacy command + result = Object.assign({}, command.query.$query); + } else { + // up-convert legacy find command + result = { find: collectionName(command) }; + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (command.query[key] != null) { + result[LEGACY_FIND_QUERY_MAP[key]] = deepCopy(command.query[key]); + } + }); + } + + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + const legacyKey = key as keyof typeof LEGACY_FIND_OPTIONS_MAP; + if (command[legacyKey] != null) { + result[LEGACY_FIND_OPTIONS_MAP[legacyKey]] = deepCopy(command[legacyKey]); + } + }); + + OP_QUERY_KEYS.forEach(key => { + const opKey = key as typeof OP_QUERY_KEYS[number]; + if (command[opKey]) { + result[opKey] = command[opKey]; + } + }); + + if (command.pre32Limit != null) { + result.limit = command.pre32Limit; + } + + if (command.query.$explain) { + return { explain: result }; + } + return result; + } + + const clonedQuery: Record = {}; + const clonedCommand: Record = {}; + if (command.query) { + for (const k in command.query) { + clonedQuery[k] = deepCopy(command.query[k]); + } + clonedCommand.query = clonedQuery; + } + + for (const k in command) { + if (k === 'query') continue; + clonedCommand[k] = deepCopy((command as unknown as Record)[k]); + } + return command.query ? clonedQuery : clonedCommand; +} + +function extractReply(command: WriteProtocolMessageType, reply?: Document) { + if (command instanceof KillCursor) { + return { + ok: 1, + cursorsUnknown: command.cursorIds + }; + } + + if (!reply) { + return reply; + } + + if (command instanceof GetMore) { + return { + ok: 1, + cursor: { + id: deepCopy(reply.cursorId), + ns: namespace(command), + nextBatch: deepCopy(reply.documents) + } + }; + } + + if (command instanceof Msg) { + return deepCopy(reply.result ? reply.result : reply); + } + + // is this a legacy find command? + if (command.query && command.query.$query != null) { + return { + ok: 1, + cursor: { + id: deepCopy(reply.cursorId), + ns: namespace(command), + firstBatch: deepCopy(reply.documents) + } + }; + } + + return deepCopy(reply.result ? reply.result : reply); +} + +function extractConnectionDetails(connection: Connection) { + let connectionId; + if ('id' in connection) { + connectionId = connection.id; + } + return { + address: connection.address, + serviceId: connection.serviceId, + connectionId + }; +} diff --git a/node_modules/mongodb/src/cmap/commands.ts b/node_modules/mongodb/src/cmap/commands.ts new file mode 100644 index 0000000..3fa3a71 --- /dev/null +++ b/node_modules/mongodb/src/cmap/commands.ts @@ -0,0 +1,876 @@ +import { ReadPreference } from '../read_preference'; +import * as BSON from '../bson'; +import { databaseNamespace } from '../utils'; +import { OP_QUERY, OP_GETMORE, OP_KILL_CURSORS, OP_MSG } from './wire_protocol/constants'; +import type { Long, Document, BSONSerializeOptions } from '../bson'; +import type { ClientSession } from '../sessions'; +import type { CommandOptions } from './connection'; +import { MongoRuntimeError, MongoInvalidArgumentError } from '../error'; + +// Incrementing request id +let _requestId = 0; + +// Query flags +const OPTS_TAILABLE_CURSOR = 2; +const OPTS_SLAVE = 4; +const OPTS_OPLOG_REPLAY = 8; +const OPTS_NO_CURSOR_TIMEOUT = 16; +const OPTS_AWAIT_DATA = 32; +const OPTS_EXHAUST = 64; +const OPTS_PARTIAL = 128; + +// Response flags +const CURSOR_NOT_FOUND = 1; +const QUERY_FAILURE = 2; +const SHARD_CONFIG_STALE = 4; +const AWAIT_CAPABLE = 8; + +/** @internal */ +export type WriteProtocolMessageType = Query | Msg | GetMore | KillCursor; + +/** @internal */ +export interface OpQueryOptions extends CommandOptions { + socketTimeoutMS?: number; + session?: ClientSession; + documentsReturnedIn?: string; + numberToSkip?: number; + numberToReturn?: number; + returnFieldSelector?: Document; + pre32Limit?: number; + serializeFunctions?: boolean; + ignoreUndefined?: boolean; + maxBsonSize?: number; + checkKeys?: boolean; + slaveOk?: boolean; + + requestId?: number; + moreToCome?: boolean; + exhaustAllowed?: boolean; + readPreference?: ReadPreference; +} + +/************************************************************** + * QUERY + **************************************************************/ +/** @internal */ +export class Query { + ns: string; + query: Document; + numberToSkip: number; + numberToReturn: number; + returnFieldSelector?: Document; + requestId: number; + pre32Limit?: number; + serializeFunctions: boolean; + ignoreUndefined: boolean; + maxBsonSize: number; + checkKeys: boolean; + batchSize: number; + tailable: boolean; + slaveOk: boolean; + oplogReplay: boolean; + noCursorTimeout: boolean; + awaitData: boolean; + exhaust: boolean; + partial: boolean; + documentsReturnedIn?: string; + + constructor(ns: string, query: Document, options: OpQueryOptions) { + // Basic options needed to be passed in + // TODO(NODE-3483): Replace with MongoCommandError + if (ns == null) throw new MongoRuntimeError('Namespace must be specified for query'); + // TODO(NODE-3483): Replace with MongoCommandError + if (query == null) throw new MongoRuntimeError('A query document must be specified for query'); + + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new MongoRuntimeError('Namespace cannot contain a null character'); + } + + // Basic options + this.ns = ns; + this.query = query; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || undefined; + this.requestId = Query.getRequestId(); + + // special case for pre-3.2 find commands, delete ASAP + this.pre32Limit = options.pre32Limit; + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.batchSize = this.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; + } + + /** Assign next request Id. */ + incRequestId(): void { + this.requestId = _requestId++; + } + + /** Peek next request Id. */ + nextRequestId(): number { + return _requestId + 1; + } + + /** Increment then return next request Id. */ + static getRequestId(): number { + return ++_requestId; + } + + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin(): Buffer[] { + const buffers = []; + let projection = null; + + // Set up the flags + let flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + + if (this.slaveOk) { + flags |= OPTS_SLAVE; + } + + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + + if (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + + if (this.exhaust) { + flags |= OPTS_EXHAUST; + } + + if (this.partial) { + flags |= OPTS_PARTIAL; + } + + // If batchSize is different to this.numberToReturn + if (this.batchSize !== this.numberToReturn) this.numberToReturn = this.batchSize; + + // Allocate write protocol header buffer + const header = Buffer.alloc( + 4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(this.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + const query = BSON.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + + // Add query document + buffers.push(query); + + if (this.returnFieldSelector && Object.keys(this.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = BSON.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add projection document + buffers.push(projection); + } + + // Total message size + const totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + let index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = totalLength & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = this.requestId & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = 0 & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (OP_QUERY >> 24) & 0xff; + header[index + 2] = (OP_QUERY >> 16) & 0xff; + header[index + 1] = (OP_QUERY >> 8) & 0xff; + header[index] = OP_QUERY & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = flags & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = this.numberToSkip & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Return the buffers + return buffers; + } +} + +/** @internal */ +export interface OpGetMoreOptions { + numberToReturn?: number; +} + +/************************************************************** + * GETMORE + **************************************************************/ +/** @internal */ +export class GetMore { + numberToReturn: number; + requestId: number; + ns: string; + cursorId: Long; + + constructor(ns: string, cursorId: Long, opts: OpGetMoreOptions = {}) { + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.ns = ns; + this.cursorId = cursorId; + } + + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin(): Buffer[] { + const length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; + // Create command buffer + let index = 0; + // Allocate buffer + const _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (OP_GETMORE >> 8) & 0xff; + _buffer[index] = OP_GETMORE & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getHighBits() & 0xff; + index = index + 4; + + // Return buffer + return [_buffer]; + } +} + +/************************************************************** + * KILLCURSOR + **************************************************************/ +/** @internal */ +export class KillCursor { + ns: string; + requestId: number; + cursorIds: Long[]; + + constructor(ns: string, cursorIds: Long[]) { + this.ns = ns; + this.requestId = _requestId++; + this.cursorIds = cursorIds; + } + + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin(): Buffer[] { + const length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; + + // Create command buffer + let index = 0; + const _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = OP_KILL_CURSORS & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = this.cursorIds.length & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for (let i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; + index = index + 4; + } + + // Return buffer + return [_buffer]; + } +} + +export interface MessageHeader { + length: number; + requestId: number; + responseTo: number; + opCode: number; + fromCompressed?: boolean; +} + +export interface OpResponseOptions extends BSONSerializeOptions { + raw?: boolean; + documentsReturnedIn?: string | null; +} + +/** @internal */ +export class Response { + parsed: boolean; + raw: Buffer; + data: Buffer; + opts: OpResponseOptions; + length: number; + requestId: number; + responseTo: number; + opCode: number; + fromCompressed?: boolean; + responseFlags: number; + cursorId: Long; + startingFrom: number; + numberReturned: number; + documents: (Document | Buffer)[]; + cursorNotFound: boolean; + queryFailure: boolean; + shardConfigStale: boolean; + awaitCapable: boolean; + promoteLongs: boolean; + promoteValues: boolean; + promoteBuffers: boolean; + bsonRegExp?: boolean; + index?: number; + + constructor( + message: Buffer, + msgHeader: MessageHeader, + msgBody: Buffer, + opts?: OpResponseOptions + ) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts ?? { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read the message body + this.responseFlags = msgBody.readInt32LE(0); + this.cursorId = new BSON.Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); + this.startingFrom = msgBody.readInt32LE(12); + this.numberReturned = msgBody.readInt32LE(16); + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + } + + isParsed(): boolean { + return this.parsed; + } + + parse(options: OpResponseOptions): void { + // Don't parse again if not needed + if (this.parsed) return; + options = options ?? {}; + + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs; + const promoteValues = options.promoteValues ?? this.opts.promoteValues; + const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers; + const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp; + let bsonSize; + + // Set up the options + const _options: BSONSerializeOptions = { + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp + }; + + // Position within OP_REPLY at which documents start + // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) + this.index = 20; + + // Parse Body + for (let i = 0; i < this.numberReturned; i++) { + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + + // If we have raw results specified slice the return document + if (raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = BSON.deserialize( + this.data.slice(this.index, this.index + bsonSize), + _options + ); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw: Document = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + const doc = BSON.deserialize(this.documents[0] as Buffer, _options); + this.documents = [doc]; + } + + // Set parsed + this.parsed = true; + } +} + +// Implementation of OP_MSG spec: +// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst +// +// struct Section { +// uint8 payloadType; +// union payload { +// document document; // payloadType == 0 +// struct sequence { // payloadType == 1 +// int32 size; +// cstring identifier; +// document* documents; +// }; +// }; +// }; + +// struct OP_MSG { +// struct MsgHeader { +// int32 messageLength; +// int32 requestID; +// int32 responseTo; +// int32 opCode = 2013; +// }; +// uint32 flagBits; +// Section+ sections; +// [uint32 checksum;] +// }; + +// Msg Flags +const OPTS_CHECKSUM_PRESENT = 1; +const OPTS_MORE_TO_COME = 2; +const OPTS_EXHAUST_ALLOWED = 1 << 16; + +export interface OpMsgOptions { + requestId: number; + serializeFunctions: boolean; + ignoreUndefined: boolean; + checkKeys: boolean; + maxBsonSize: number; + moreToCome: boolean; + exhaustAllowed: boolean; + readPreference: ReadPreference; +} + +/** @internal */ +export class Msg { + ns: string; + command: Document; + options: OpQueryOptions; + requestId: number; + serializeFunctions: boolean; + ignoreUndefined: boolean; + checkKeys: boolean; + maxBsonSize: number; + checksumPresent: boolean; + moreToCome: boolean; + exhaustAllowed: boolean; + + constructor(ns: string, command: Document, options: OpQueryOptions) { + // Basic options needed to be passed in + if (command == null) + throw new MongoInvalidArgumentError('Query document must be specified for query'); + + // Basic options + this.ns = ns; + this.command = command; + this.command.$db = databaseNamespace(ns); + + if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) { + this.command.$readPreference = options.readPreference.toJSON(); + } + + // Ensure empty options + this.options = options ?? {}; + + // Additional options + this.requestId = options.requestId ? options.requestId : Msg.getRequestId(); + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + + // flags + this.checksumPresent = false; + this.moreToCome = options.moreToCome || false; + this.exhaustAllowed = + typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false; + } + + toBin(): Buffer[] { + const buffers: Buffer[] = []; + let flags = 0; + + if (this.checksumPresent) { + flags |= OPTS_CHECKSUM_PRESENT; + } + + if (this.moreToCome) { + flags |= OPTS_MORE_TO_COME; + } + + if (this.exhaustAllowed) { + flags |= OPTS_EXHAUST_ALLOWED; + } + + const header = Buffer.alloc( + 4 * 4 + // Header + 4 // Flags + ); + + buffers.push(header); + + let totalLength = header.length; + const command = this.command; + totalLength += this.makeDocumentSegment(buffers, command); + + header.writeInt32LE(totalLength, 0); // messageLength + header.writeInt32LE(this.requestId, 4); // requestID + header.writeInt32LE(0, 8); // responseTo + header.writeInt32LE(OP_MSG, 12); // opCode + header.writeUInt32LE(flags, 16); // flags + return buffers; + } + + makeDocumentSegment(buffers: Buffer[], document: Document): number { + const payloadTypeBuffer = Buffer.alloc(1); + payloadTypeBuffer[0] = 0; + + const documentBuffer = this.serializeBson(document); + buffers.push(payloadTypeBuffer); + buffers.push(documentBuffer); + + return payloadTypeBuffer.length + documentBuffer.length; + } + + serializeBson(document: Document): Buffer { + return BSON.serialize(document, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + } + + static getRequestId(): number { + _requestId = (_requestId + 1) & 0x7fffffff; + return _requestId; + } +} + +/** @internal */ +export class BinMsg { + parsed: boolean; + raw: Buffer; + data: Buffer; + opts: OpResponseOptions; + length: number; + requestId: number; + responseTo: number; + opCode: number; + fromCompressed?: boolean; + responseFlags: number; + checksumPresent: boolean; + moreToCome: boolean; + exhaustAllowed: boolean; + promoteLongs: boolean; + promoteValues: boolean; + promoteBuffers: boolean; + bsonRegExp: boolean; + documents: (Document | Buffer)[]; + index?: number; + + constructor( + message: Buffer, + msgHeader: MessageHeader, + msgBody: Buffer, + opts?: OpResponseOptions + ) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts ?? { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read response flags + this.responseFlags = msgBody.readInt32LE(0); + this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; + this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; + this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + + this.documents = []; + } + + isParsed(): boolean { + return this.parsed; + } + + parse(options: OpResponseOptions): void { + // Don't parse again if not needed + if (this.parsed) return; + options = options ?? {}; + + this.index = 4; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs; + const promoteValues = options.promoteValues ?? this.opts.promoteValues; + const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers; + const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp; + + // Set up the options + const _options: BSONSerializeOptions = { + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp + }; + + while (this.index < this.data.length) { + const payloadType = this.data.readUInt8(this.index++); + if (payloadType === 0) { + const bsonSize = this.data.readUInt32LE(this.index); + const bin = this.data.slice(this.index, this.index + bsonSize); + this.documents.push(raw ? bin : BSON.deserialize(bin, _options)); + + this.index += bsonSize; + } else if (payloadType === 1) { + // It was decided that no driver makes use of payload type 1 + + // TODO(NODE-3483): Replace with MongoDeprecationError + throw new MongoRuntimeError('OP_MSG Payload Type 1 detected unsupported protocol'); + } + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw: Document = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + const doc = BSON.deserialize(this.documents[0] as Buffer, _options); + this.documents = [doc]; + } + + this.parsed = true; + } +} diff --git a/node_modules/mongodb/src/cmap/connect.ts b/node_modules/mongodb/src/cmap/connect.ts new file mode 100644 index 0000000..07917c8 --- /dev/null +++ b/node_modules/mongodb/src/cmap/connect.ts @@ -0,0 +1,400 @@ +import * as net from 'net'; +import * as tls from 'tls'; +import { Connection, ConnectionOptions, CryptoConnection } from './connection'; +import { + MongoNetworkError, + MongoNetworkTimeoutError, + AnyError, + MongoCompatibilityError, + MongoInvalidArgumentError, + MongoServerError, + MongoRuntimeError +} from '../error'; +import { AUTH_PROVIDERS, AuthMechanism } from './auth/defaultAuthProviders'; +import { AuthContext } from './auth/auth_provider'; +import { makeClientMetadata, ClientMetadata, Callback, CallbackWithType, ns } from '../utils'; +import { + MAX_SUPPORTED_WIRE_VERSION, + MAX_SUPPORTED_SERVER_VERSION, + MIN_SUPPORTED_WIRE_VERSION, + MIN_SUPPORTED_SERVER_VERSION +} from './wire_protocol/constants'; +import type { Document } from '../bson'; +import { Int32 } from '../bson'; + +import type { Socket, SocketConnectOpts } from 'net'; +import type { TLSSocket, ConnectionOptions as TLSConnectionOpts } from 'tls'; + +const FAKE_MONGODB_SERVICE_ID = + typeof process.env.FAKE_MONGODB_SERVICE_ID === 'string' && + process.env.FAKE_MONGODB_SERVICE_ID.toLowerCase() === 'true'; + +/** @public */ +export type Stream = Socket | TLSSocket; + +export function connect(options: ConnectionOptions, callback: Callback): void { + makeConnection(options, (err, socket) => { + if (err || !socket) { + return callback(err); + } + + let ConnectionType = options.connectionType ?? Connection; + if (options.autoEncrypter) { + ConnectionType = CryptoConnection; + } + performInitialHandshake(new ConnectionType(socket, options), options, callback); + }); +} + +function checkSupportedServer(ismaster: Document, options: ConnectionOptions) { + const serverVersionHighEnough = + ismaster && + (typeof ismaster.maxWireVersion === 'number' || ismaster.maxWireVersion instanceof Int32) && + ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION; + const serverVersionLowEnough = + ismaster && + (typeof ismaster.minWireVersion === 'number' || ismaster.minWireVersion instanceof Int32) && + ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION; + + if (serverVersionHighEnough) { + if (serverVersionLowEnough) { + return null; + } + + const message = `Server at ${options.hostAddress} reports minimum wire version ${JSON.stringify( + ismaster.minWireVersion + )}, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + return new MongoCompatibilityError(message); + } + + const message = `Server at ${options.hostAddress} reports maximum wire version ${ + JSON.stringify(ismaster.maxWireVersion) ?? 0 + }, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`; + return new MongoCompatibilityError(message); +} + +function performInitialHandshake( + conn: Connection, + options: ConnectionOptions, + _callback: Callback +) { + const callback: Callback = function (err, ret) { + if (err && conn) { + conn.destroy(); + } + _callback(err, ret); + }; + + const credentials = options.credentials; + if (credentials) { + if ( + !(credentials.mechanism === AuthMechanism.MONGODB_DEFAULT) && + !AUTH_PROVIDERS.get(credentials.mechanism) + ) { + callback( + new MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`) + ); + return; + } + } + + const authContext = new AuthContext(conn, credentials, options); + prepareHandshakeDocument(authContext, (err, handshakeDoc) => { + if (err || !handshakeDoc) { + return callback(err); + } + + const handshakeOptions: Document = Object.assign({}, options); + if (typeof options.connectTimeoutMS === 'number') { + // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS + handshakeOptions.socketTimeoutMS = options.connectTimeoutMS; + } + + const start = new Date().getTime(); + conn.command(ns('admin.$cmd'), handshakeDoc, handshakeOptions, (err, response) => { + if (err) { + callback(err); + return; + } + + if (response?.ok === 0) { + callback(new MongoServerError(response)); + return; + } + + if ('isWritablePrimary' in response) { + // Provide pre-hello-style response document. + response.ismaster = response.isWritablePrimary; + } + + if (response.helloOk) { + conn.helloOk = true; + } + + const supportedServerErr = checkSupportedServer(response, options); + if (supportedServerErr) { + callback(supportedServerErr); + return; + } + + if (options.loadBalanced) { + // TODO: Durran: Remove when server support exists. (NODE-3431) + if (FAKE_MONGODB_SERVICE_ID) { + response.serviceId = response.topologyVersion.processId; + } + if (!response.serviceId) { + return callback( + new MongoCompatibilityError( + 'Driver attempted to initialize in load balancing mode, ' + + 'but the server does not support this mode.' + ) + ); + } + } + + // NOTE: This is metadata attached to the connection while porting away from + // handshake being done in the `Server` class. Likely, it should be + // relocated, or at very least restructured. + conn.ismaster = response; + conn.lastIsMasterMS = new Date().getTime() - start; + + if (!response.arbiterOnly && credentials) { + // store the response on auth context + authContext.response = response; + + const resolvedCredentials = credentials.resolveAuthMechanism(response); + const provider = AUTH_PROVIDERS.get(resolvedCredentials.mechanism); + if (!provider) { + return callback( + new MongoInvalidArgumentError( + `No AuthProvider for ${resolvedCredentials.mechanism} defined.` + ) + ); + } + provider.auth(authContext, err => { + if (err) return callback(err); + callback(undefined, conn); + }); + + return; + } + + callback(undefined, conn); + }); + }); +} + +export interface HandshakeDocument extends Document { + ismaster?: boolean; + hello?: boolean; + helloOk?: boolean; + client: ClientMetadata; + compression: string[]; + saslSupportedMechs?: string; + loadBalanced: boolean; +} + +function prepareHandshakeDocument(authContext: AuthContext, callback: Callback) { + const options = authContext.options; + const compressors = options.compressors ? options.compressors : []; + const { serverApi } = authContext.connection; + + const handshakeDoc: HandshakeDocument = { + [serverApi?.version ? 'hello' : 'ismaster']: true, + helloOk: true, + client: options.metadata || makeClientMetadata(options), + compression: compressors, + loadBalanced: options.loadBalanced + }; + + const credentials = authContext.credentials; + if (credentials) { + if (credentials.mechanism === AuthMechanism.MONGODB_DEFAULT && credentials.username) { + handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`; + + const provider = AUTH_PROVIDERS.get(AuthMechanism.MONGODB_SCRAM_SHA256); + if (!provider) { + // This auth mechanism is always present. + return callback( + new MongoInvalidArgumentError( + `No AuthProvider for ${AuthMechanism.MONGODB_SCRAM_SHA256} defined.` + ) + ); + } + return provider.prepare(handshakeDoc, authContext, callback); + } + const provider = AUTH_PROVIDERS.get(credentials.mechanism); + if (!provider) { + return callback( + new MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`) + ); + } + return provider.prepare(handshakeDoc, authContext, callback); + } + callback(undefined, handshakeDoc); +} + +/** @public */ +export const LEGAL_TLS_SOCKET_OPTIONS = [ + 'ALPNProtocols', + 'ca', + 'cert', + 'checkServerIdentity', + 'ciphers', + 'crl', + 'ecdhCurve', + 'key', + 'minDHSize', + 'passphrase', + 'pfx', + 'rejectUnauthorized', + 'secureContext', + 'secureProtocol', + 'servername', + 'session' +] as const; + +/** @public */ +export const LEGAL_TCP_SOCKET_OPTIONS = [ + 'family', + 'hints', + 'localAddress', + 'localPort', + 'lookup' +] as const; + +function parseConnectOptions(options: ConnectionOptions): SocketConnectOpts { + const hostAddress = options.hostAddress; + if (!hostAddress) throw new MongoInvalidArgumentError('Option "hostAddress" is required'); + + const result: Partial = {}; + for (const name of LEGAL_TCP_SOCKET_OPTIONS) { + if (options[name] != null) { + (result as Document)[name] = options[name]; + } + } + + if (typeof hostAddress.socketPath === 'string') { + result.path = hostAddress.socketPath; + return result as net.IpcNetConnectOpts; + } else if (typeof hostAddress.host === 'string') { + result.host = hostAddress.host; + result.port = hostAddress.port; + return result as net.TcpNetConnectOpts; + } else { + // This should never happen since we set up HostAddresses + // But if we don't throw here the socket could hang until timeout + // TODO(NODE-3483) + throw new MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(hostAddress)}`); + } +} + +function parseSslOptions(options: ConnectionOptions): TLSConnectionOpts { + const result: TLSConnectionOpts = parseConnectOptions(options); + // Merge in valid SSL options + for (const name of LEGAL_TLS_SOCKET_OPTIONS) { + if (options[name] != null) { + (result as Document)[name] = options[name]; + } + } + + // Set default sni servername to be the same as host + if (result.servername == null && result.host && !net.isIP(result.host)) { + result.servername = result.host; + } + + return result; +} + +const SOCKET_ERROR_EVENT_LIST = ['error', 'close', 'timeout', 'parseError'] as const; +type ErrorHandlerEventName = typeof SOCKET_ERROR_EVENT_LIST[number] | 'cancel'; +const SOCKET_ERROR_EVENTS = new Set(SOCKET_ERROR_EVENT_LIST); + +function makeConnection(options: ConnectionOptions, _callback: CallbackWithType) { + const useTLS = options.tls ?? false; + const keepAlive = options.keepAlive ?? true; + const socketTimeoutMS = options.socketTimeoutMS ?? Reflect.get(options, 'socketTimeout') ?? 0; + const noDelay = options.noDelay ?? true; + const connectionTimeout = options.connectTimeoutMS ?? 30000; + const rejectUnauthorized = options.rejectUnauthorized ?? true; + const keepAliveInitialDelay = + ((options.keepAliveInitialDelay ?? 120000) > socketTimeoutMS + ? Math.round(socketTimeoutMS / 2) + : options.keepAliveInitialDelay) ?? 120000; + + let socket: Stream; + const callback: Callback = function (err, ret) { + if (err && socket) { + socket.destroy(); + } + + _callback(err, ret); + }; + + if (useTLS) { + const tlsSocket = tls.connect(parseSslOptions(options)); + if (typeof tlsSocket.disableRenegotiation === 'function') { + tlsSocket.disableRenegotiation(); + } + socket = tlsSocket; + } else { + socket = net.createConnection(parseConnectOptions(options)); + } + + socket.setKeepAlive(keepAlive, keepAliveInitialDelay); + socket.setTimeout(connectionTimeout); + socket.setNoDelay(noDelay); + + const connectEvent = useTLS ? 'secureConnect' : 'connect'; + let cancellationHandler: (err: Error) => void; + function errorHandler(eventName: ErrorHandlerEventName) { + return (err: Error) => { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler && options.cancellationToken) { + options.cancellationToken.removeListener('cancel', cancellationHandler); + } + + socket.removeListener(connectEvent, connectHandler); + callback(connectionFailureError(eventName, err)); + }; + } + + function connectHandler() { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler && options.cancellationToken) { + options.cancellationToken.removeListener('cancel', cancellationHandler); + } + + if ('authorizationError' in socket) { + if (socket.authorizationError && rejectUnauthorized) { + return callback(socket.authorizationError); + } + } + + socket.setTimeout(socketTimeoutMS); + callback(undefined, socket); + } + + SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event))); + if (options.cancellationToken) { + cancellationHandler = errorHandler('cancel'); + options.cancellationToken.once('cancel', cancellationHandler); + } + + socket.once(connectEvent, connectHandler); +} + +function connectionFailureError(type: string, err: Error) { + switch (type) { + case 'error': + return new MongoNetworkError(err); + case 'timeout': + return new MongoNetworkTimeoutError('connection timed out'); + case 'close': + return new MongoNetworkError('connection closed'); + case 'cancel': + return new MongoNetworkError('connection establishment was cancelled'); + default: + return new MongoNetworkError('unknown network error'); + } +} diff --git a/node_modules/mongodb/src/cmap/connection.ts b/node_modules/mongodb/src/cmap/connection.ts new file mode 100644 index 0000000..e7b6e52 --- /dev/null +++ b/node_modules/mongodb/src/cmap/connection.ts @@ -0,0 +1,854 @@ +import { MessageStream, OperationDescription } from './message_stream'; +import { StreamDescription, StreamDescriptionOptions } from './stream_description'; +import { + CommandStartedEvent, + CommandFailedEvent, + CommandSucceededEvent +} from './command_monitoring_events'; +import { applySession, ClientSession, updateSessionFromResponse } from '../sessions'; +import { + uuidV4, + ClientMetadata, + now, + calculateDurationInMs, + Callback, + MongoDBNamespace, + maxWireVersion, + HostAddress +} from '../utils'; +import { + MongoRuntimeError, + MongoMissingDependencyError, + MongoCompatibilityError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoServerError, + MongoWriteConcernError +} from '../error'; +import { + BinMsg, + WriteProtocolMessageType, + Response, + KillCursor, + GetMore, + Query, + OpQueryOptions, + Msg +} from './commands'; +import { BSONSerializeOptions, Document, Long, pluckBSONSerializeOptions, ObjectId } from '../bson'; +import type { AutoEncrypter } from '../deps'; +import type { MongoCredentials } from './auth/mongo_credentials'; +import type { Stream } from './connect'; +import { applyCommonQueryOptions, getReadPreference, isSharded } from './wire_protocol/shared'; +import { ReadPreference, ReadPreferenceLike } from '../read_preference'; +import type { W, WriteConcern, WriteConcernOptions } from '../write_concern'; +import type { ServerApi, SupportedNodeConnectionOptions } from '../mongo_client'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; + +/** @internal */ +const kStream = Symbol('stream'); +/** @internal */ +const kQueue = Symbol('queue'); +/** @internal */ +const kMessageStream = Symbol('messageStream'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kLastUseTime = Symbol('lastUseTime'); +/** @internal */ +const kClusterTime = Symbol('clusterTime'); +/** @internal */ +const kDescription = Symbol('description'); +/** @internal */ +const kIsMaster = Symbol('ismaster'); +/** @internal */ +const kAutoEncrypter = Symbol('autoEncrypter'); +/** @internal */ +const kFullResult = Symbol('fullResult'); + +/** @internal */ +export interface QueryOptions extends BSONSerializeOptions { + readPreference: ReadPreference; + documentsReturnedIn?: string; + batchSize?: number; + limit?: number; + skip?: number; + projection?: Document; + tailable?: boolean; + awaitData?: boolean; + noCursorTimeout?: boolean; + /** @deprecated use `noCursorTimeout` instead */ + timeout?: boolean; + partial?: boolean; + oplogReplay?: boolean; +} + +/** @internal */ +export interface CommandOptions extends BSONSerializeOptions { + command?: boolean; + slaveOk?: boolean; + /** Specify read preference if command supports it */ + readPreference?: ReadPreferenceLike; + raw?: boolean; + monitoring?: boolean; + [kFullResult]?: boolean; + socketTimeoutMS?: number; + /** Session to use for the operation */ + session?: ClientSession; + documentsReturnedIn?: string; + noResponse?: boolean; + + // FIXME: NODE-2802 + willRetryWrite?: boolean; + + // FIXME: NODE-2781 + writeConcern?: WriteConcernOptions | WriteConcern | W; +} + +/** @internal */ +export interface GetMoreOptions extends CommandOptions { + batchSize?: number; + maxTimeMS?: number; + maxAwaitTimeMS?: number; + comment?: Document | string; +} + +/** @public */ +export interface ConnectionOptions + extends SupportedNodeConnectionOptions, + StreamDescriptionOptions { + // Internal creation info + id: number | ''; + generation: number; + hostAddress: HostAddress; + // Settings + autoEncrypter?: AutoEncrypter; + serverApi?: ServerApi; + monitorCommands: boolean; + /** @internal */ + connectionType?: typeof Connection; + credentials?: MongoCredentials; + connectTimeoutMS?: number; + tls: boolean; + keepAlive?: boolean; + keepAliveInitialDelay?: number; + noDelay?: boolean; + socketTimeoutMS?: number; + cancellationToken?: CancellationToken; + + metadata: ClientMetadata; +} + +/** @public */ +export interface DestroyOptions { + /** Force the destruction. */ + force?: boolean; +} + +/** @public */ +export type ConnectionEvents = { + commandStarted(event: CommandStartedEvent): void; + commandSucceeded(event: CommandSucceededEvent): void; + commandFailed(event: CommandFailedEvent): void; + clusterTimeReceived(clusterTime: Document): void; + close(): void; + message(message: any): void; + pinned(pinType: string): void; + unpinned(pinType: string): void; +}; + +/** @internal */ +export class Connection extends TypedEventEmitter { + id: number | ''; + address: string; + socketTimeoutMS: number; + monitorCommands: boolean; + closed: boolean; + destroyed: boolean; + lastIsMasterMS?: number; + serverApi?: ServerApi; + helloOk?: boolean; + /** @internal */ + [kDescription]: StreamDescription; + /** @internal */ + [kGeneration]: number; + /** @internal */ + [kLastUseTime]: number; + /** @internal */ + [kQueue]: Map; + /** @internal */ + [kMessageStream]: MessageStream; + /** @internal */ + [kStream]: Stream; + /** @internal */ + [kIsMaster]: Document; + /** @internal */ + [kClusterTime]: Document; + + /** @event */ + static readonly COMMAND_STARTED = 'commandStarted' as const; + /** @event */ + static readonly COMMAND_SUCCEEDED = 'commandSucceeded' as const; + /** @event */ + static readonly COMMAND_FAILED = 'commandFailed' as const; + /** @event */ + static readonly CLUSTER_TIME_RECEIVED = 'clusterTimeReceived' as const; + /** @event */ + static readonly CLOSE = 'close' as const; + /** @event */ + static readonly MESSAGE = 'message' as const; + /** @event */ + static readonly PINNED = 'pinned' as const; + /** @event */ + static readonly UNPINNED = 'unpinned' as const; + + constructor(stream: Stream, options: ConnectionOptions) { + super(); + this.id = options.id; + this.address = streamIdentifier(stream); + this.socketTimeoutMS = options.socketTimeoutMS ?? 0; + this.monitorCommands = options.monitorCommands; + this.serverApi = options.serverApi; + this.closed = false; + this.destroyed = false; + + this[kDescription] = new StreamDescription(this.address, options); + this[kGeneration] = options.generation; + this[kLastUseTime] = now(); + + // setup parser stream and message handling + this[kQueue] = new Map(); + this[kMessageStream] = new MessageStream({ + ...options, + maxBsonMessageSize: this.ismaster?.maxBsonMessageSize + }); + this[kMessageStream].on('message', messageHandler(this)); + this[kStream] = stream; + stream.on('error', () => { + /* ignore errors, listen to `close` instead */ + }); + + this[kMessageStream].on('error', error => this.handleIssue({ destroy: error })); + stream.on('close', () => this.handleIssue({ isClose: true })); + stream.on('timeout', () => this.handleIssue({ isTimeout: true, destroy: true })); + + // hook the message stream up to the passed in stream + stream.pipe(this[kMessageStream]); + this[kMessageStream].pipe(stream); + } + + get description(): StreamDescription { + return this[kDescription]; + } + + get ismaster(): Document { + return this[kIsMaster]; + } + + // the `connect` method stores the result of the handshake ismaster on the connection + set ismaster(response: Document) { + this[kDescription].receiveResponse(response); + this[kDescription] = Object.freeze(this[kDescription]); + + // TODO: remove this, and only use the `StreamDescription` in the future + this[kIsMaster] = response; + } + + get serviceId(): ObjectId | undefined { + return this.ismaster?.serviceId; + } + + get loadBalanced(): boolean { + return this.description.loadBalanced; + } + + get generation(): number { + return this[kGeneration] || 0; + } + + set generation(generation: number) { + this[kGeneration] = generation; + } + + get idleTime(): number { + return calculateDurationInMs(this[kLastUseTime]); + } + + get clusterTime(): Document { + return this[kClusterTime]; + } + + get stream(): Stream { + return this[kStream]; + } + + markAvailable(): void { + this[kLastUseTime] = now(); + } + + handleIssue(issue: { isTimeout?: boolean; isClose?: boolean; destroy?: boolean | Error }): void { + if (this.closed) { + return; + } + + if (issue.destroy) { + this[kStream].destroy(typeof issue.destroy === 'boolean' ? undefined : issue.destroy); + } + + this.closed = true; + + for (const [, op] of this[kQueue]) { + if (issue.isTimeout) { + op.cb( + new MongoNetworkTimeoutError(`connection ${this.id} to ${this.address} timed out`, { + beforeHandshake: this.ismaster == null + }) + ); + } else if (issue.isClose) { + op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} closed`)); + } else { + op.cb(typeof issue.destroy === 'boolean' ? undefined : issue.destroy); + } + } + + this[kQueue].clear(); + this.emit(Connection.CLOSE); + } + + destroy(): void; + destroy(callback: Callback): void; + destroy(options: DestroyOptions): void; + destroy(options: DestroyOptions, callback: Callback): void; + destroy(options?: DestroyOptions | Callback, callback?: Callback): void { + if (typeof options === 'function') { + callback = options; + options = { force: false }; + } + + this.removeAllListeners(Connection.PINNED); + this.removeAllListeners(Connection.UNPINNED); + + options = Object.assign({ force: false }, options); + if (this[kStream] == null || this.destroyed) { + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + + return; + } + + if (options.force) { + this[kStream].destroy(); + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + + return; + } + + this[kStream].end(() => { + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + }); + } + + /** @internal */ + command( + ns: MongoDBNamespace, + cmd: Document, + options: CommandOptions | undefined, + callback: Callback + ): void { + if (!(ns instanceof MongoDBNamespace)) { + // TODO(NODE-3483): Replace this with a MongoCommandError + throw new MongoRuntimeError('Must provide a MongoDBNamespace instance'); + } + + const readPreference = getReadPreference(cmd, options); + const shouldUseOpMsg = supportsOpMsg(this); + const session = options?.session; + + let clusterTime = this.clusterTime; + let finalCmd = Object.assign({}, cmd); + + if (this.serverApi) { + const { version, strict, deprecationErrors } = this.serverApi; + finalCmd.apiVersion = version; + if (strict != null) finalCmd.apiStrict = strict; + if (deprecationErrors != null) finalCmd.apiDeprecationErrors = deprecationErrors; + } + + if (hasSessionSupport(this) && session) { + if ( + session.clusterTime && + clusterTime && + session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime) + ) { + clusterTime = session.clusterTime; + } + + const err = applySession(session, finalCmd, options as CommandOptions); + if (err) { + return callback(err); + } + } + + // if we have a known cluster time, gossip it + if (clusterTime) { + finalCmd.$clusterTime = clusterTime; + } + + if (isSharded(this) && !shouldUseOpMsg && readPreference && readPreference.mode !== 'primary') { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; + } + + const commandOptions: Document = Object.assign( + { + command: true, + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false, + // This value is not overridable + slaveOk: readPreference.slaveOk() + }, + options + ); + + const cmdNs = `${ns.db}.$cmd`; + const message = shouldUseOpMsg + ? new Msg(cmdNs, finalCmd, commandOptions) + : new Query(cmdNs, finalCmd, commandOptions); + + try { + write(this, message, commandOptions, callback); + } catch (err) { + callback(err); + } + } + + /** @internal */ + query(ns: MongoDBNamespace, cmd: Document, options: QueryOptions, callback: Callback): void { + const isExplain = cmd.$explain != null; + const readPreference = options.readPreference ?? ReadPreference.primary; + const batchSize = options.batchSize || 0; + const limit = options.limit; + const numberToSkip = options.skip || 0; + let numberToReturn = 0; + if ( + limit && + (limit < 0 || (limit !== 0 && limit < batchSize) || (limit > 0 && batchSize === 0)) + ) { + numberToReturn = limit; + } else { + numberToReturn = batchSize; + } + + if (isExplain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(limit || 0); + } + + const queryOptions: OpQueryOptions = { + numberToSkip, + numberToReturn, + pre32Limit: typeof limit === 'number' ? limit : undefined, + checkKeys: false, + slaveOk: readPreference.slaveOk() + }; + + if (options.projection) { + queryOptions.returnFieldSelector = options.projection; + } + + const query = new Query(ns.toString(), cmd, queryOptions); + if (typeof options.tailable === 'boolean') { + query.tailable = options.tailable; + } + + if (typeof options.oplogReplay === 'boolean') { + query.oplogReplay = options.oplogReplay; + } + + if (typeof options.timeout === 'boolean') { + query.noCursorTimeout = !options.timeout; + } else if (typeof options.noCursorTimeout === 'boolean') { + query.noCursorTimeout = options.noCursorTimeout; + } + + if (typeof options.awaitData === 'boolean') { + query.awaitData = options.awaitData; + } + + if (typeof options.partial === 'boolean') { + query.partial = options.partial; + } + + write( + this, + query, + { [kFullResult]: true, ...pluckBSONSerializeOptions(options) }, + (err, result) => { + if (err || !result) return callback(err, result); + if (isExplain && result.documents && result.documents[0]) { + return callback(undefined, result.documents[0]); + } + + callback(undefined, result); + } + ); + } + + /** @internal */ + getMore( + ns: MongoDBNamespace, + cursorId: Long, + options: GetMoreOptions, + callback: Callback + ): void { + const fullResult = !!options[kFullResult]; + const wireVersion = maxWireVersion(this); + if (!cursorId) { + // TODO(NODE-3483): Replace this with a MongoCommandError + callback(new MongoRuntimeError('Invalid internal cursor state, no known cursor id')); + return; + } + + if (wireVersion < 4) { + const getMoreOp = new GetMore(ns.toString(), cursorId, { numberToReturn: options.batchSize }); + const queryOptions = applyCommonQueryOptions( + {}, + Object.assign(options, { ...pluckBSONSerializeOptions(options) }) + ); + + queryOptions[kFullResult] = true; + queryOptions.command = true; + write(this, getMoreOp, queryOptions, (err, response) => { + if (fullResult) return callback(err, response); + if (err) return callback(err); + callback(undefined, { cursor: { id: response.cursorId, nextBatch: response.documents } }); + }); + + return; + } + + const getMoreCmd: Document = { + getMore: cursorId, + collection: ns.collection + }; + + if (typeof options.batchSize === 'number') { + getMoreCmd.batchSize = Math.abs(options.batchSize); + } + + if (typeof options.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = options.maxAwaitTimeMS; + } + + const commandOptions = Object.assign( + { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch' + }, + options + ); + + this.command(ns, getMoreCmd, commandOptions, callback); + } + + /** @internal */ + killCursors( + ns: MongoDBNamespace, + cursorIds: Long[], + options: CommandOptions, + callback: Callback + ): void { + if (!cursorIds || !Array.isArray(cursorIds)) { + // TODO(NODE-3483): Replace this with a MongoCommandError + throw new MongoRuntimeError(`Invalid list of cursor ids provided: ${cursorIds}`); + } + + if (maxWireVersion(this) < 4) { + try { + write( + this, + new KillCursor(ns.toString(), cursorIds), + { noResponse: true, ...options }, + callback + ); + } catch (err) { + callback(err); + } + + return; + } + + this.command( + ns, + { killCursors: ns.collection, cursors: cursorIds }, + { [kFullResult]: true, ...options }, + (err, response) => { + if (err || !response) return callback(err); + if (response.cursorNotFound) { + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + if (!Array.isArray(response.documents) || response.documents.length === 0) { + return callback( + // TODO(NODE-3483) + new MongoRuntimeError( + `invalid killCursors result returned for cursor id ${cursorIds[0]}` + ) + ); + } + + callback(undefined, response.documents[0]); + } + ); + } +} + +/** @public */ +export const APM_EVENTS = [ + Connection.COMMAND_STARTED, + Connection.COMMAND_SUCCEEDED, + Connection.COMMAND_FAILED +]; + +/** @internal */ +export class CryptoConnection extends Connection { + /** @internal */ + [kAutoEncrypter]?: AutoEncrypter; + + constructor(stream: Stream, options: ConnectionOptions) { + super(stream, options); + this[kAutoEncrypter] = options.autoEncrypter; + } + + /** @internal @override */ + command(ns: MongoDBNamespace, cmd: Document, options: CommandOptions, callback: Callback): void { + const autoEncrypter = this[kAutoEncrypter]; + if (!autoEncrypter) { + return callback(new MongoMissingDependencyError('No AutoEncrypter available for encryption')); + } + + const serverWireVersion = maxWireVersion(this); + if (serverWireVersion === 0) { + // This means the initial handshake hasn't happened yet + return super.command(ns, cmd, options, callback); + } + + if (serverWireVersion < 8) { + callback( + new MongoCompatibilityError('Auto-encryption requires a minimum MongoDB version of 4.2') + ); + return; + } + + autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => { + if (err || encrypted == null) { + callback(err, null); + return; + } + + super.command(ns, encrypted, options, (err, response) => { + if (err || response == null) { + callback(err, response); + return; + } + + autoEncrypter.decrypt(response, options, callback); + }); + }); + } +} + +/** @internal */ +export function hasSessionSupport(conn: Connection): boolean { + const description = conn.description; + return description.logicalSessionTimeoutMinutes != null || !!description.loadBalanced; +} + +function supportsOpMsg(conn: Connection) { + const description = conn.description; + if (description == null) { + return false; + } + + return maxWireVersion(conn) >= 6 && !description.__nodejs_mock_server__; +} + +function messageHandler(conn: Connection) { + return function messageHandler(message: BinMsg | Response) { + // always emit the message, in case we are streaming + conn.emit('message', message); + const operationDescription = conn[kQueue].get(message.responseTo); + if (!operationDescription) { + return; + } + + const callback = operationDescription.cb; + + // SERVER-45775: For exhaust responses we should be able to use the same requestId to + // track response, however the server currently synthetically produces remote requests + // making the `responseTo` change on each response + conn[kQueue].delete(message.responseTo); + if ('moreToCome' in message && message.moreToCome) { + // requeue the callback for next synthetic request + conn[kQueue].set(message.requestId, operationDescription); + } else if (operationDescription.socketTimeoutOverride) { + conn[kStream].setTimeout(conn.socketTimeoutMS); + } + + try { + // Pass in the entire description because it has BSON parsing options + message.parse(operationDescription); + } catch (err) { + // If this error is generated by our own code, it will already have the correct class applied + // if it is not, then it is coming from a catastrophic data parse failure or the BSON library + // in either case, it should not be wrapped + callback(err); + return; + } + + if (message.documents[0]) { + const document: Document = message.documents[0]; + const session = operationDescription.session; + if (session) { + updateSessionFromResponse(session, document); + } + + if (document.$clusterTime) { + conn[kClusterTime] = document.$clusterTime; + conn.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime); + } + + if (operationDescription.command) { + if (document.writeConcernError) { + callback(new MongoWriteConcernError(document.writeConcernError, document)); + return; + } + + if (document.ok === 0 || document.$err || document.errmsg || document.code) { + callback(new MongoServerError(document)); + return; + } + } else { + // Pre 3.2 support + if (document.ok === 0 || document.$err || document.errmsg) { + callback(new MongoServerError(document)); + return; + } + } + } + + callback(undefined, operationDescription.fullResult ? message : message.documents[0]); + }; +} + +function streamIdentifier(stream: Stream) { + if (typeof stream.address === 'function') { + return `${stream.remoteAddress}:${stream.remotePort}`; + } + + return uuidV4().toString('hex'); +} + +function write( + conn: Connection, + command: WriteProtocolMessageType, + options: CommandOptions, + callback: Callback +) { + if (typeof options === 'function') { + callback = options; + } + + options = options ?? {}; + const operationDescription: OperationDescription = { + requestId: command.requestId, + cb: callback, + session: options.session, + fullResult: !!options[kFullResult], + noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false, + documentsReturnedIn: options.documentsReturnedIn, + command: !!options.command, + + // for BSON parsing + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false, + raw: typeof options.raw === 'boolean' ? options.raw : false, + started: 0 + }; + + if (conn[kDescription] && conn[kDescription].compressor) { + operationDescription.agreedCompressor = conn[kDescription].compressor; + + if (conn[kDescription].zlibCompressionLevel) { + operationDescription.zlibCompressionLevel = conn[kDescription].zlibCompressionLevel; + } + } + + if (typeof options.socketTimeoutMS === 'number') { + operationDescription.socketTimeoutOverride = true; + conn[kStream].setTimeout(options.socketTimeoutMS); + } + + // if command monitoring is enabled we need to modify the callback here + if (conn.monitorCommands) { + conn.emit(Connection.COMMAND_STARTED, new CommandStartedEvent(conn, command)); + + operationDescription.started = now(); + operationDescription.cb = (err, reply) => { + if (err) { + conn.emit( + Connection.COMMAND_FAILED, + new CommandFailedEvent(conn, command, err, operationDescription.started) + ); + } else { + if (reply && (reply.ok === 0 || reply.$err)) { + conn.emit( + Connection.COMMAND_FAILED, + new CommandFailedEvent(conn, command, reply, operationDescription.started) + ); + } else { + conn.emit( + Connection.COMMAND_SUCCEEDED, + new CommandSucceededEvent(conn, command, reply, operationDescription.started) + ); + } + } + + if (typeof callback === 'function') { + callback(err, reply); + } + }; + } + + if (!operationDescription.noResponse) { + conn[kQueue].set(operationDescription.requestId, operationDescription); + } + + try { + conn[kMessageStream].writeCommand(command, operationDescription); + } catch (e) { + if (!operationDescription.noResponse) { + conn[kQueue].delete(operationDescription.requestId); + operationDescription.cb(e); + return; + } + } + + if (operationDescription.noResponse) { + operationDescription.cb(); + } +} diff --git a/node_modules/mongodb/src/cmap/connection_pool.ts b/node_modules/mongodb/src/cmap/connection_pool.ts new file mode 100644 index 0000000..83c74d7 --- /dev/null +++ b/node_modules/mongodb/src/cmap/connection_pool.ts @@ -0,0 +1,692 @@ +import Denque = require('denque'); +import { APM_EVENTS, Connection, ConnectionEvents, ConnectionOptions } from './connection'; +import type { ObjectId } from 'bson'; +import { Logger } from '../logger'; +import { ConnectionPoolMetrics } from './metrics'; +import { connect } from './connect'; +import { eachAsync, makeCounter, Callback } from '../utils'; +import { MongoError, MongoInvalidArgumentError, MongoRuntimeError } from '../error'; +import { PoolClosedError, WaitQueueTimeoutError } from './errors'; +import { + ConnectionPoolCreatedEvent, + ConnectionPoolClosedEvent, + ConnectionCreatedEvent, + ConnectionReadyEvent, + ConnectionClosedEvent, + ConnectionCheckOutStartedEvent, + ConnectionCheckOutFailedEvent, + ConnectionCheckedOutEvent, + ConnectionCheckedInEvent, + ConnectionPoolClearedEvent +} from './connection_pool_events'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; + +/** @internal */ +const kLogger = Symbol('logger'); +/** @internal */ +const kConnections = Symbol('connections'); +/** @internal */ +const kPermits = Symbol('permits'); +/** @internal */ +const kMinPoolSizeTimer = Symbol('minPoolSizeTimer'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kServiceGenerations = Symbol('serviceGenerations'); +/** @internal */ +const kConnectionCounter = Symbol('connectionCounter'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kMetrics = Symbol('metrics'); +/** @internal */ +const kCheckedOut = Symbol('checkedOut'); +/** @internal */ +const kProcessingWaitQueue = Symbol('processingWaitQueue'); + +/** @public */ +export interface ConnectionPoolOptions extends Omit { + /** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */ + maxPoolSize: number; + /** The minimum number of connections that MUST exist at any moment in a single connection pool. */ + minPoolSize: number; + /** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */ + maxIdleTimeMS: number; + /** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. */ + waitQueueTimeoutMS: number; + /** If we are in load balancer mode. */ + loadBalanced: boolean; +} + +/** @internal */ +export interface WaitQueueMember { + callback: Callback; + timer?: NodeJS.Timeout; + [kCancelled]?: boolean; +} + +/** @public */ +export interface CloseOptions { + force?: boolean; +} + +/** @public */ +export type ConnectionPoolEvents = { + connectionPoolCreated(event: ConnectionPoolCreatedEvent): void; + connectionPoolClosed(event: ConnectionPoolClosedEvent): void; + connectionPoolCleared(event: ConnectionPoolClearedEvent): void; + connectionCreated(event: ConnectionCreatedEvent): void; + connectionReady(event: ConnectionReadyEvent): void; + connectionClosed(event: ConnectionClosedEvent): void; + connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void; + connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void; + connectionCheckedOut(event: ConnectionCheckedOutEvent): void; + connectionCheckedIn(event: ConnectionCheckedInEvent): void; +} & Omit; + +/** + * A pool of connections which dynamically resizes, and emit events related to pool activity + * @internal + */ +export class ConnectionPool extends TypedEventEmitter { + closed: boolean; + options: Readonly; + /** @internal */ + [kLogger]: Logger; + /** @internal */ + [kConnections]: Denque; + /** + * An integer expressing how many total connections are permitted + * @internal + */ + [kPermits]: number; + /** @internal */ + [kMinPoolSizeTimer]?: NodeJS.Timeout; + /** + * An integer representing the SDAM generation of the pool + * @internal + */ + [kGeneration]: number; + /** A map of generations to service ids + * @internal + */ + [kServiceGenerations]: Map; + /** @internal */ + [kConnectionCounter]: Generator; + /** @internal */ + [kCancellationToken]: CancellationToken; + /** @internal */ + [kWaitQueue]: Denque; + /** @internal */ + [kMetrics]: ConnectionPoolMetrics; + /** @internal */ + [kCheckedOut]: number; + /** @internal */ + [kProcessingWaitQueue]: boolean; + + /** + * Emitted when the connection pool is created. + * @event + */ + static readonly CONNECTION_POOL_CREATED = 'connectionPoolCreated' as const; + /** + * Emitted once when the connection pool is closed + * @event + */ + static readonly CONNECTION_POOL_CLOSED = 'connectionPoolClosed' as const; + /** + * Emitted each time the connection pool is cleared and it's generation incremented + * @event + */ + static readonly CONNECTION_POOL_CLEARED = 'connectionPoolCleared' as const; + /** + * Emitted when a connection is created. + * @event + */ + static readonly CONNECTION_CREATED = 'connectionCreated' as const; + /** + * Emitted when a connection becomes established, and is ready to use + * @event + */ + static readonly CONNECTION_READY = 'connectionReady' as const; + /** + * Emitted when a connection is closed + * @event + */ + static readonly CONNECTION_CLOSED = 'connectionClosed' as const; + /** + * Emitted when an attempt to check out a connection begins + * @event + */ + static readonly CONNECTION_CHECK_OUT_STARTED = 'connectionCheckOutStarted' as const; + /** + * Emitted when an attempt to check out a connection fails + * @event + */ + static readonly CONNECTION_CHECK_OUT_FAILED = 'connectionCheckOutFailed' as const; + /** + * Emitted each time a connection is successfully checked out of the connection pool + * @event + */ + static readonly CONNECTION_CHECKED_OUT = 'connectionCheckedOut' as const; + /** + * Emitted each time a connection is successfully checked into the connection pool + * @event + */ + static readonly CONNECTION_CHECKED_IN = 'connectionCheckedIn' as const; + + /** @internal */ + constructor(options: ConnectionPoolOptions) { + super(); + + this.closed = false; + this.options = Object.freeze({ + ...options, + connectionType: Connection, + maxPoolSize: options.maxPoolSize ?? 100, + minPoolSize: options.minPoolSize ?? 0, + maxIdleTimeMS: options.maxIdleTimeMS ?? 0, + waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0, + autoEncrypter: options.autoEncrypter, + metadata: options.metadata + }); + + if (this.options.minPoolSize > this.options.maxPoolSize) { + throw new MongoInvalidArgumentError( + 'Connection pool minimum size must not be greater than maximum pool size' + ); + } + + this[kLogger] = new Logger('ConnectionPool'); + this[kConnections] = new Denque(); + this[kPermits] = this.options.maxPoolSize; + this[kMinPoolSizeTimer] = undefined; + this[kGeneration] = 0; + this[kServiceGenerations] = new Map(); + this[kConnectionCounter] = makeCounter(1); + this[kCancellationToken] = new CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kWaitQueue] = new Denque(); + this[kMetrics] = new ConnectionPoolMetrics(); + this[kCheckedOut] = 0; + this[kProcessingWaitQueue] = false; + + process.nextTick(() => { + this.emit(ConnectionPool.CONNECTION_POOL_CREATED, new ConnectionPoolCreatedEvent(this)); + ensureMinPoolSize(this); + }); + } + + /** The address of the endpoint the pool is connected to */ + get address(): string { + return this.options.hostAddress.toString(); + } + + /** An integer representing the SDAM generation of the pool */ + get generation(): number { + return this[kGeneration]; + } + + /** An integer expressing how many total connections (active + in use) the pool currently has */ + get totalConnectionCount(): number { + return this[kConnections].length + (this.options.maxPoolSize - this[kPermits]); + } + + /** An integer expressing how many connections are currently available in the pool. */ + get availableConnectionCount(): number { + return this[kConnections].length; + } + + get waitQueueSize(): number { + return this[kWaitQueue].length; + } + + get loadBalanced(): boolean { + return this.options.loadBalanced; + } + + get serviceGenerations(): Map { + return this[kServiceGenerations]; + } + + get currentCheckedOutCount(): number { + return this[kCheckedOut]; + } + + /** + * Get the metrics information for the pool when a wait queue timeout occurs. + */ + private waitQueueErrorMetrics(): string { + return this[kMetrics].info(this.options.maxPoolSize); + } + + /** + * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it + * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or + * explicitly destroyed by the new owner. + */ + checkOut(callback: Callback): void { + this.emit( + ConnectionPool.CONNECTION_CHECK_OUT_STARTED, + new ConnectionCheckOutStartedEvent(this) + ); + + if (this.closed) { + this.emit( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(this, 'poolClosed') + ); + callback(new PoolClosedError(this)); + return; + } + + const waitQueueMember: WaitQueueMember = { callback }; + const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; + if (waitQueueTimeoutMS) { + waitQueueMember.timer = setTimeout(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + + this.emit( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(this, 'timeout') + ); + waitQueueMember.callback( + new WaitQueueTimeoutError( + this.loadBalanced + ? this.waitQueueErrorMetrics() + : 'Timed out while checking out a connection from connection pool', + this.address + ) + ); + }, waitQueueTimeoutMS); + } + + this[kCheckedOut] = this[kCheckedOut] + 1; + this[kWaitQueue].push(waitQueueMember); + process.nextTick(processWaitQueue, this); + } + + /** + * Check a connection into the pool. + * + * @param connection - The connection to check in + */ + checkIn(connection: Connection): void { + const poolClosed = this.closed; + const stale = connectionIsStale(this, connection); + const willDestroy = !!(poolClosed || stale || connection.closed); + + if (!willDestroy) { + connection.markAvailable(); + this[kConnections].unshift(connection); + } + + this[kCheckedOut] = this[kCheckedOut] - 1; + this.emit(ConnectionPool.CONNECTION_CHECKED_IN, new ConnectionCheckedInEvent(this, connection)); + + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + destroyConnection(this, connection, reason); + } + + process.nextTick(processWaitQueue, this); + } + + /** + * Clear the pool + * + * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a + * previous generation will eventually be pruned during subsequent checkouts. + */ + clear(serviceId?: ObjectId): void { + if (this.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + // Only need to worry if the generation exists, since it should + // always be there but typescript needs the check. + if (generation == null) { + // TODO(NODE-3483) + throw new MongoRuntimeError('Service generations are required in load balancer mode.'); + } else { + // Increment the generation for the service id. + this.serviceGenerations.set(sid, generation + 1); + } + } else { + this[kGeneration] += 1; + } + + this.emit('connectionPoolCleared', new ConnectionPoolClearedEvent(this, serviceId)); + } + + /** Close the pool */ + close(callback: Callback): void; + close(options: CloseOptions, callback: Callback): void; + close(_options?: CloseOptions | Callback, _cb?: Callback): void { + let options = _options as CloseOptions; + const callback = (_cb ?? _options) as Callback; + if (typeof options === 'function') { + options = {}; + } + + options = Object.assign({ force: false }, options); + if (this.closed) { + return callback(); + } + + // immediately cancel any in-flight connections + this[kCancellationToken].emit('cancel'); + + // drain the wait queue + while (this.waitQueueSize) { + const waitQueueMember = this[kWaitQueue].pop(); + if (waitQueueMember) { + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + if (!waitQueueMember[kCancelled]) { + // TODO(NODE-3483): Replace with MongoConnectionPoolClosedError + waitQueueMember.callback(new MongoRuntimeError('Connection pool closed')); + } + } + } + + // clear the min pool size timer + const minPoolSizeTimer = this[kMinPoolSizeTimer]; + if (minPoolSizeTimer) { + clearTimeout(minPoolSizeTimer); + } + + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(undefined); + } + + // mark the pool as closed immediately + this.closed = true; + eachAsync( + this[kConnections].toArray(), + (conn, cb) => { + this.emit( + ConnectionPool.CONNECTION_CLOSED, + new ConnectionClosedEvent(this, conn, 'poolClosed') + ); + conn.destroy(options, cb); + }, + err => { + this[kConnections].clear(); + this.emit(ConnectionPool.CONNECTION_POOL_CLOSED, new ConnectionPoolClosedEvent(this)); + callback(err); + } + ); + } + + /** + * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda + * has completed by calling back. + * + * NOTE: please note the required signature of `fn` + * + * @remarks When in load balancer mode, connections can be pinned to cursors or transactions. + * In these cases we pass the connection in to this method to ensure it is used and a new + * connection is not checked out. + * + * @param conn - A pinned connection for use in load balancing mode. + * @param fn - A function which operates on a managed connection + * @param callback - The original callback + */ + withConnection( + conn: Connection | undefined, + fn: WithConnectionCallback, + callback?: Callback + ): void { + if (conn) { + // use the provided connection, and do _not_ check it in after execution + fn(undefined, conn, (fnErr, result) => { + if (typeof callback === 'function') { + if (fnErr) { + callback(fnErr); + } else { + callback(undefined, result); + } + } + }); + + return; + } + + this.checkOut((err, conn) => { + // don't callback with `err` here, we might want to act upon it inside `fn` + fn(err as MongoError, conn, (fnErr, result) => { + if (typeof callback === 'function') { + if (fnErr) { + callback(fnErr); + } else { + callback(undefined, result); + } + } + + if (conn) { + this.checkIn(conn); + } + }); + }); + } +} + +function ensureMinPoolSize(pool: ConnectionPool) { + if (pool.closed || pool.options.minPoolSize === 0) { + return; + } + + const minPoolSize = pool.options.minPoolSize; + for (let i = pool.totalConnectionCount; i < minPoolSize; ++i) { + createConnection(pool); + } + + pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 10); +} + +function connectionIsStale(pool: ConnectionPool, connection: Connection) { + const serviceId = connection.serviceId; + if (pool.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = pool.serviceGenerations.get(sid); + return connection.generation !== generation; + } + + return connection.generation !== pool[kGeneration]; +} + +function connectionIsIdle(pool: ConnectionPool, connection: Connection) { + return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS); +} + +function createConnection(pool: ConnectionPool, callback?: Callback) { + const connectOptions: ConnectionOptions = { + ...pool.options, + id: pool[kConnectionCounter].next().value, + generation: pool[kGeneration], + cancellationToken: pool[kCancellationToken] + }; + + pool[kPermits]--; + connect(connectOptions, (err, connection) => { + if (err || !connection) { + pool[kPermits]++; + pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`); + if (typeof callback === 'function') { + callback(err); + } + + return; + } + + // The pool might have closed since we started trying to create a connection + if (pool.closed) { + connection.destroy({ force: true }); + return; + } + + // forward all events from the connection to the pool + for (const event of [...APM_EVENTS, Connection.CLUSTER_TIME_RECEIVED]) { + connection.on(event, (e: any) => pool.emit(event, e)); + } + + pool.emit(ConnectionPool.CONNECTION_CREATED, new ConnectionCreatedEvent(pool, connection)); + + if (pool.loadBalanced) { + connection.on(Connection.PINNED, pinType => pool[kMetrics].markPinned(pinType)); + connection.on(Connection.UNPINNED, pinType => pool[kMetrics].markUnpinned(pinType)); + + const serviceId = connection.serviceId; + if (serviceId) { + let generation; + const sid = serviceId.toHexString(); + if ((generation = pool.serviceGenerations.get(sid))) { + connection.generation = generation; + } else { + pool.serviceGenerations.set(sid, 0); + connection.generation = 0; + } + } + } + + connection.markAvailable(); + pool.emit(ConnectionPool.CONNECTION_READY, new ConnectionReadyEvent(pool, connection)); + + // if a callback has been provided, check out the connection immediately + if (typeof callback === 'function') { + callback(undefined, connection); + return; + } + + // otherwise add it to the pool for later acquisition, and try to process the wait queue + pool[kConnections].push(connection); + process.nextTick(processWaitQueue, pool); + }); +} + +function destroyConnection(pool: ConnectionPool, connection: Connection, reason: string) { + pool.emit(ConnectionPool.CONNECTION_CLOSED, new ConnectionClosedEvent(pool, connection, reason)); + + // allow more connections to be created + pool[kPermits]++; + + // destroy the connection + process.nextTick(() => connection.destroy()); +} + +function processWaitQueue(pool: ConnectionPool) { + if (pool.closed || pool[kProcessingWaitQueue]) { + return; + } + + pool[kProcessingWaitQueue] = true; + while (pool.waitQueueSize) { + const waitQueueMember = pool[kWaitQueue].peekFront(); + if (!waitQueueMember) { + pool[kWaitQueue].shift(); + continue; + } + + if (waitQueueMember[kCancelled]) { + pool[kWaitQueue].shift(); + continue; + } + + if (!pool.availableConnectionCount) { + break; + } + + const connection = pool[kConnections].shift(); + if (!connection) { + break; + } + + const isStale = connectionIsStale(pool, connection); + const isIdle = connectionIsIdle(pool, connection); + if (!isStale && !isIdle && !connection.closed) { + pool.emit( + ConnectionPool.CONNECTION_CHECKED_OUT, + new ConnectionCheckedOutEvent(pool, connection) + ); + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + + pool[kWaitQueue].shift(); + waitQueueMember.callback(undefined, connection); + } else { + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + destroyConnection(pool, connection, reason); + } + } + + const maxPoolSize = pool.options.maxPoolSize; + if (pool.waitQueueSize && (maxPoolSize <= 0 || pool.totalConnectionCount < maxPoolSize)) { + createConnection(pool, (err, connection) => { + const waitQueueMember = pool[kWaitQueue].shift(); + if (!waitQueueMember || waitQueueMember[kCancelled]) { + if (!err && connection) { + pool[kConnections].push(connection); + } + + pool[kProcessingWaitQueue] = false; + return; + } + + if (err) { + pool.emit( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(pool, err) + ); + } else if (connection) { + pool.emit( + ConnectionPool.CONNECTION_CHECKED_OUT, + new ConnectionCheckedOutEvent(pool, connection) + ); + } + + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(err, connection); + pool[kProcessingWaitQueue] = false; + process.nextTick(() => processWaitQueue(pool)); + }); + } else { + pool[kProcessingWaitQueue] = false; + } +} + +export const CMAP_EVENTS = [ + ConnectionPool.CONNECTION_POOL_CREATED, + ConnectionPool.CONNECTION_POOL_CLOSED, + ConnectionPool.CONNECTION_CREATED, + ConnectionPool.CONNECTION_READY, + ConnectionPool.CONNECTION_CLOSED, + ConnectionPool.CONNECTION_CHECK_OUT_STARTED, + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + ConnectionPool.CONNECTION_CHECKED_OUT, + ConnectionPool.CONNECTION_CHECKED_IN, + ConnectionPool.CONNECTION_POOL_CLEARED +] as const; + +/** + * A callback provided to `withConnection` + * @internal + * + * @param error - An error instance representing the error during the execution. + * @param connection - The managed connection which was checked out of the pool. + * @param callback - A function to call back after connection management is complete + */ +export type WithConnectionCallback = ( + error: MongoError | undefined, + connection: Connection | undefined, + callback: Callback +) => void; diff --git a/node_modules/mongodb/src/cmap/connection_pool_events.ts b/node_modules/mongodb/src/cmap/connection_pool_events.ts new file mode 100644 index 0000000..8083f6d --- /dev/null +++ b/node_modules/mongodb/src/cmap/connection_pool_events.ts @@ -0,0 +1,179 @@ +import type { ObjectId } from '../bson'; +import type { Connection } from './connection'; +import type { ConnectionPool, ConnectionPoolOptions } from './connection_pool'; +import type { AnyError } from '../error'; + +/** + * The base export class for all monitoring events published from the connection pool + * @public + * @category Event + */ +export class ConnectionPoolMonitoringEvent { + /** A timestamp when the event was created */ + time: Date; + /** The address (host/port pair) of the pool */ + address: string; + + /** @internal */ + constructor(pool: ConnectionPool) { + this.time = new Date(); + this.address = pool.address; + } +} + +/** + * An event published when a connection pool is created + * @public + * @category Event + */ +export class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + /** The options used to create this connection pool */ + options?: ConnectionPoolOptions; + + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + this.options = pool.options; + } +} + +/** + * An event published when a connection pool is closed + * @public + * @category Event + */ +export class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + } +} + +/** + * An event published when a connection pool creates a new connection + * @public + * @category Event + */ +export class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + /** A monotonically increasing, per-pool id for the newly created connection */ + connectionId: number | ''; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is ready for use + * @public + * @category Event + */ +export class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is closed + * @public + * @category Event + */ +export class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /** The reason the connection was closed */ + reason: string; + serviceId?: ObjectId; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection, reason: string) { + super(pool); + this.connectionId = connection.id; + this.reason = reason || 'unknown'; + this.serviceId = connection.serviceId; + } +} + +/** + * An event published when a request to check a connection out begins + * @public + * @category Event + */ +export class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + } +} + +/** + * An event published when a request to check a connection out fails + * @public + * @category Event + */ +export class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + /** The reason the attempt to check out failed */ + reason: AnyError | string; + + /** @internal */ + constructor(pool: ConnectionPool, reason: AnyError | string) { + super(pool); + this.reason = reason; + } +} + +/** + * An event published when a connection is checked out of the connection pool + * @public + * @category Event + */ +export class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is checked into the connection pool + * @public + * @category Event + */ +export class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection pool is cleared + * @public + * @category Event + */ +export class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + serviceId?: ObjectId; + + /** @internal */ + constructor(pool: ConnectionPool, serviceId?: ObjectId) { + super(pool); + this.serviceId = serviceId; + } +} diff --git a/node_modules/mongodb/src/cmap/errors.ts b/node_modules/mongodb/src/cmap/errors.ts new file mode 100644 index 0000000..7d03198 --- /dev/null +++ b/node_modules/mongodb/src/cmap/errors.ts @@ -0,0 +1,38 @@ +import { MongoDriverError } from '../error'; +import type { ConnectionPool } from './connection_pool'; + +/** + * An error indicating a connection pool is closed + * @category Error + */ +export class PoolClosedError extends MongoDriverError { + /** The address of the connection pool */ + address: string; + + constructor(pool: ConnectionPool) { + super('Attempted to check out a connection from closed connection pool'); + this.address = pool.address; + } + + get name(): string { + return 'MongoPoolClosedError'; + } +} + +/** + * An error thrown when a request to check out a connection times out + * @category Error + */ +export class WaitQueueTimeoutError extends MongoDriverError { + /** The address of the connection pool */ + address: string; + + constructor(message: string, address: string) { + super(message); + this.address = address; + } + + get name(): string { + return 'MongoWaitQueueTimeoutError'; + } +} diff --git a/node_modules/mongodb/src/cmap/message_stream.ts b/node_modules/mongodb/src/cmap/message_stream.ts new file mode 100644 index 0000000..8ab3290 --- /dev/null +++ b/node_modules/mongodb/src/cmap/message_stream.ts @@ -0,0 +1,208 @@ +import { Duplex, DuplexOptions } from 'stream'; +import { Response, Msg, BinMsg, Query, WriteProtocolMessageType, MessageHeader } from './commands'; +import { MongoDecompressionError, MongoParseError } from '../error'; +import { OP_COMPRESSED, OP_MSG } from './wire_protocol/constants'; +import { + compress, + decompress, + uncompressibleCommands, + Compressor, + CompressorName +} from './wire_protocol/compression'; +import type { Document, BSONSerializeOptions } from '../bson'; +import { BufferPool, Callback } from '../utils'; +import type { ClientSession } from '../sessions'; + +const MESSAGE_HEADER_SIZE = 16; +const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID + +const kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4; +/** @internal */ +const kBuffer = Symbol('buffer'); + +/** @internal */ +export interface MessageStreamOptions extends DuplexOptions { + maxBsonMessageSize?: number; +} + +/** @internal */ +export interface OperationDescription extends BSONSerializeOptions { + started: number; + cb: Callback; + command: boolean; + documentsReturnedIn?: string; + fullResult: boolean; + noResponse: boolean; + raw: boolean; + requestId: number; + session?: ClientSession; + socketTimeoutOverride?: boolean; + agreedCompressor?: CompressorName; + zlibCompressionLevel?: number; + $clusterTime?: Document; +} + +/** + * A duplex stream that is capable of reading and writing raw wire protocol messages, with + * support for optional compression + * @internal + */ +export class MessageStream extends Duplex { + /** @internal */ + maxBsonMessageSize: number; + /** @internal */ + [kBuffer]: BufferPool; + + constructor(options: MessageStreamOptions = {}) { + super(options); + this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize; + this[kBuffer] = new BufferPool(); + } + + _write(chunk: Buffer, _: unknown, callback: Callback): void { + this[kBuffer].append(chunk); + processIncomingData(this, callback); + } + + _read(/* size */): void { + // NOTE: This implementation is empty because we explicitly push data to be read + // when `writeMessage` is called. + return; + } + + writeCommand( + command: WriteProtocolMessageType, + operationDescription: OperationDescription + ): void { + // TODO: agreed compressor should live in `StreamDescription` + const compressorName: CompressorName = + operationDescription && operationDescription.agreedCompressor + ? operationDescription.agreedCompressor + : 'none'; + if (compressorName === 'none' || !canCompress(command)) { + const data = command.toBin(); + this.push(Array.isArray(data) ? Buffer.concat(data) : data); + return; + } + // otherwise, compress the message + const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin()); + const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + + // Extract information needed for OP_COMPRESSED from the uncompressed message + const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + + // Compress the message body + compress({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => { + if (err || !compressedMessage) { + operationDescription.cb(err); + return; + } + + // Create the msgHeader of OP_COMPRESSED + const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE( + MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, + 0 + ); // messageLength + msgHeader.writeInt32LE(command.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(OP_COMPRESSED, 12); // opCode + + // Create the compression details of OP_COMPRESSED + const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(Compressor[compressorName], 8); // compressorID + this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + }); + } +} + +// Return whether a command contains an uncompressible command term +// Will return true if command contains no uncompressible command terms +function canCompress(command: WriteProtocolMessageType) { + const commandDoc = command instanceof Msg ? command.command : (command as Query).query; + const commandName = Object.keys(commandDoc)[0]; + return !uncompressibleCommands.has(commandName); +} + +function processIncomingData(stream: MessageStream, callback: Callback) { + const buffer = stream[kBuffer]; + if (buffer.length < 4) { + callback(); + return; + } + + const sizeOfMessage = buffer.peek(4).readInt32LE(); + if (sizeOfMessage < 0) { + callback(new MongoParseError(`Invalid message size: ${sizeOfMessage}`)); + return; + } + + if (sizeOfMessage > stream.maxBsonMessageSize) { + callback( + new MongoParseError( + `Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}` + ) + ); + return; + } + + if (sizeOfMessage > buffer.length) { + callback(); + return; + } + + const message = buffer.read(sizeOfMessage); + const messageHeader: MessageHeader = { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; + + let ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; + if (messageHeader.opCode !== OP_COMPRESSED) { + const messageBody = message.slice(MESSAGE_HEADER_SIZE); + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + + if (buffer.length >= 4) { + processIncomingData(stream, callback); + } else { + callback(); + } + + return; + } + + messageHeader.fromCompressed = true; + messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE); + messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4); + const compressorID: Compressor = message[MESSAGE_HEADER_SIZE + 8] as Compressor; + const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9); + + // recalculate based on wrapped opcode + ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; + decompress(compressorID, compressedBuffer, (err, messageBody) => { + if (err || !messageBody) { + callback(err); + return; + } + + if (messageBody.length !== messageHeader.length) { + callback( + new MongoDecompressionError('Message body and message header must be the same length') + ); + + return; + } + + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + + if (buffer.length >= 4) { + processIncomingData(stream, callback); + } else { + callback(); + } + }); +} diff --git a/node_modules/mongodb/src/cmap/metrics.ts b/node_modules/mongodb/src/cmap/metrics.ts new file mode 100644 index 0000000..b825b53 --- /dev/null +++ b/node_modules/mongodb/src/cmap/metrics.ts @@ -0,0 +1,58 @@ +/** @internal */ +export class ConnectionPoolMetrics { + static readonly TXN = 'txn' as const; + static readonly CURSOR = 'cursor' as const; + static readonly OTHER = 'other' as const; + + txnConnections = 0; + cursorConnections = 0; + otherConnections = 0; + + /** + * Mark a connection as pinned for a specific operation. + */ + markPinned(pinType: string): void { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections += 1; + } else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections += 1; + } else { + this.otherConnections += 1; + } + } + + /** + * Unmark a connection as pinned for an operation. + */ + markUnpinned(pinType: string): void { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections -= 1; + } else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections -= 1; + } else { + this.otherConnections -= 1; + } + } + + /** + * Return information about the cmap metrics as a string. + */ + info(maxPoolSize: number): string { + return ( + 'Timed out while checking out a connection from connection pool: ' + + `maxPoolSize: ${maxPoolSize}, ` + + `connections in use by cursors: ${this.cursorConnections}, ` + + `connections in use by transactions: ${this.txnConnections}, ` + + `connections in use by other operations: ${this.otherConnections}` + ); + } + + /** + * Reset the metrics to the initial values. + */ + reset(): void { + this.txnConnections = 0; + this.cursorConnections = 0; + this.otherConnections = 0; + } +} diff --git a/node_modules/mongodb/src/cmap/stream_description.ts b/node_modules/mongodb/src/cmap/stream_description.ts new file mode 100644 index 0000000..fd0ce61 --- /dev/null +++ b/node_modules/mongodb/src/cmap/stream_description.ts @@ -0,0 +1,73 @@ +import { parseServerType } from '../sdam/server_description'; +import type { Document } from '../bson'; +import type { CompressorName } from './wire_protocol/compression'; +import { ServerType } from '../sdam/common'; + +const RESPONSE_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'maxBsonObjectSize', + 'maxMessageSizeBytes', + 'maxWriteBatchSize', + 'logicalSessionTimeoutMinutes' +] as const; + +/** @public */ +export interface StreamDescriptionOptions { + compressors?: CompressorName[]; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; +} + +/** @public */ +export class StreamDescription { + address: string; + type: string; + minWireVersion?: number; + maxWireVersion?: number; + maxBsonObjectSize: number; + maxMessageSizeBytes: number; + maxWriteBatchSize: number; + compressors: CompressorName[]; + compressor?: CompressorName; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; + + __nodejs_mock_server__?: boolean; + + zlibCompressionLevel?: number; + + constructor(address: string, options?: StreamDescriptionOptions) { + this.address = address; + this.type = ServerType.Unknown; + this.minWireVersion = undefined; + this.maxWireVersion = undefined; + this.maxBsonObjectSize = 16777216; + this.maxMessageSizeBytes = 48000000; + this.maxWriteBatchSize = 100000; + this.logicalSessionTimeoutMinutes = options?.logicalSessionTimeoutMinutes; + this.loadBalanced = !!options?.loadBalanced; + this.compressors = + options && options.compressors && Array.isArray(options.compressors) + ? options.compressors + : []; + } + + receiveResponse(response: Document): void { + this.type = parseServerType(response); + RESPONSE_FIELDS.forEach(field => { + if (typeof response[field] != null) { + this[field] = response[field]; + } + + // testing case + if ('__nodejs_mock_server__' in response) { + this.__nodejs_mock_server__ = response['__nodejs_mock_server__']; + } + }); + + if (response.compression) { + this.compressor = this.compressors.filter(c => response.compression?.includes(c))[0]; + } + } +} diff --git a/node_modules/mongodb/src/cmap/wire_protocol/compression.ts b/node_modules/mongodb/src/cmap/wire_protocol/compression.ts new file mode 100644 index 0000000..957fb45 --- /dev/null +++ b/node_modules/mongodb/src/cmap/wire_protocol/compression.ts @@ -0,0 +1,103 @@ +import * as zlib from 'zlib'; +import type { Callback } from '../../utils'; +import type { OperationDescription } from '../message_stream'; + +import { PKG_VERSION, Snappy } from '../../deps'; +import { MongoDecompressionError, MongoInvalidArgumentError } from '../../error'; + +/** @public */ +export const Compressor = Object.freeze({ + none: 0, + snappy: 1, + zlib: 2 +} as const); + +/** @public */ +export type Compressor = typeof Compressor[CompressorName]; + +/** @public */ +export type CompressorName = keyof typeof Compressor; + +export const uncompressibleCommands = new Set([ + 'ismaster', + 'saslStart', + 'saslContinue', + 'getnonce', + 'authenticate', + 'createUser', + 'updateUser', + 'copydbSaslStart', + 'copydbgetnonce', + 'copydb' +]); + +// Facilitate compressing a message using an agreed compressor +export function compress( + self: { options: OperationDescription & zlib.ZlibOptions }, + dataToBeCompressed: Buffer, + callback: Callback +): void { + const zlibOptions = {} as zlib.ZlibOptions; + switch (self.options.agreedCompressor) { + case 'snappy': { + if ('kModuleError' in Snappy) { + return callback(Snappy['kModuleError']); + } + + if (Snappy[PKG_VERSION].major <= 6) { + Snappy.compress(dataToBeCompressed, callback); + } else { + Snappy.compress(dataToBeCompressed) + .then(buffer => callback(undefined, buffer)) + .catch(error => callback(error)); + } + break; + } + case 'zlib': + // Determine zlibCompressionLevel + if (self.options.zlibCompressionLevel) { + zlibOptions.level = self.options.zlibCompressionLevel; + } + zlib.deflate(dataToBeCompressed, zlibOptions, callback as zlib.CompressCallback); + break; + default: + throw new MongoInvalidArgumentError( + `Unknown compressor ${self.options.agreedCompressor} failed to compress` + ); + } +} + +// Decompress a message using the given compressor +export function decompress( + compressorID: Compressor, + compressedData: Buffer, + callback: Callback +): void { + if (compressorID < 0 || compressorID > Math.max(2)) { + throw new MongoDecompressionError( + `Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})` + ); + } + + switch (compressorID) { + case Compressor.snappy: { + if ('kModuleError' in Snappy) { + return callback(Snappy['kModuleError']); + } + + if (Snappy[PKG_VERSION].major <= 6) { + Snappy.uncompress(compressedData, { asBuffer: true }, callback); + } else { + Snappy.uncompress(compressedData, { asBuffer: true }) + .then(buffer => callback(undefined, buffer)) + .catch(error => callback(error)); + } + break; + } + case Compressor.zlib: + zlib.inflate(compressedData, callback as zlib.CompressCallback); + break; + default: + callback(undefined, compressedData); + } +} diff --git a/node_modules/mongodb/src/cmap/wire_protocol/constants.ts b/node_modules/mongodb/src/cmap/wire_protocol/constants.ts new file mode 100644 index 0000000..f37be82 --- /dev/null +++ b/node_modules/mongodb/src/cmap/wire_protocol/constants.ts @@ -0,0 +1,13 @@ +export const MIN_SUPPORTED_SERVER_VERSION = '2.6'; +export const MAX_SUPPORTED_SERVER_VERSION = '5.0'; +export const MIN_SUPPORTED_WIRE_VERSION = 2; +export const MAX_SUPPORTED_WIRE_VERSION = 13; +export const OP_REPLY = 1; +export const OP_UPDATE = 2001; +export const OP_INSERT = 2002; +export const OP_QUERY = 2004; +export const OP_GETMORE = 2005; +export const OP_DELETE = 2006; +export const OP_KILL_CURSORS = 2007; +export const OP_COMPRESSED = 2012; +export const OP_MSG = 2013; diff --git a/node_modules/mongodb/src/cmap/wire_protocol/shared.ts b/node_modules/mongodb/src/cmap/wire_protocol/shared.ts new file mode 100644 index 0000000..0fd624d --- /dev/null +++ b/node_modules/mongodb/src/cmap/wire_protocol/shared.ts @@ -0,0 +1,71 @@ +import { ServerType } from '../../sdam/common'; +import { TopologyDescription } from '../../sdam/topology_description'; +import { MongoInvalidArgumentError } from '../../error'; +import { ReadPreference } from '../../read_preference'; +import type { Document } from '../../bson'; +import type { OpQueryOptions } from '../commands'; +import type { Topology } from '../../sdam/topology'; +import type { Server } from '../../sdam/server'; +import type { ServerDescription } from '../../sdam/server_description'; +import type { ReadPreferenceLike } from '../../read_preference'; +import type { CommandOptions } from '../connection'; +import type { Connection } from '../connection'; + +export interface ReadPreferenceOption { + readPreference?: ReadPreferenceLike; +} + +export function getReadPreference(cmd: Document, options?: ReadPreferenceOption): ReadPreference { + // Default to command version of the readPreference + let readPreference = cmd.readPreference || ReadPreference.primary; + // If we have an option readPreference override the command one + if (options?.readPreference) { + readPreference = options.readPreference; + } + + if (typeof readPreference === 'string') { + readPreference = ReadPreference.fromString(readPreference); + } + + if (!(readPreference instanceof ReadPreference)) { + throw new MongoInvalidArgumentError( + 'Option "readPreference" must be a ReadPreference instance' + ); + } + + return readPreference; +} + +export function applyCommonQueryOptions( + queryOptions: OpQueryOptions, + options: CommandOptions +): CommandOptions { + Object.assign(queryOptions, { + raw: typeof options.raw === 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false + }); + + if (options.session) { + queryOptions.session = options.session; + } + + return queryOptions; +} + +export function isSharded(topologyOrServer: Topology | Server | Connection): boolean { + if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) { + return true; + } + + // NOTE: This is incredibly inefficient, and should be removed once command construction + // happens based on `Server` not `Topology`. + if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) { + const servers: ServerDescription[] = Array.from(topologyOrServer.description.servers.values()); + return servers.some((server: ServerDescription) => server.type === ServerType.Mongos); + } + + return false; +} diff --git a/node_modules/mongodb/src/collection.ts b/node_modules/mongodb/src/collection.ts new file mode 100644 index 0000000..fd08502 --- /dev/null +++ b/node_modules/mongodb/src/collection.ts @@ -0,0 +1,1617 @@ +import { DEFAULT_PK_FACTORY, emitWarningOnce, resolveOptions } from './utils'; +import { ReadPreference, ReadPreferenceLike } from './read_preference'; +import { + normalizeHintField, + checkCollectionName, + MongoDBNamespace, + Callback, + getTopology +} from './utils'; +import { Document, BSONSerializeOptions, resolveBSONOptions } from './bson'; +import { MongoInvalidArgumentError } from './error'; +import { UnorderedBulkOperation } from './bulk/unordered'; +import { OrderedBulkOperation } from './bulk/ordered'; +import { ChangeStream, ChangeStreamOptions } from './change_stream'; +import { WriteConcern, WriteConcernOptions } from './write_concern'; +import { ReadConcern, ReadConcernLike } from './read_concern'; +import { AggregationCursor } from './cursor/aggregation_cursor'; +import type { AggregateOptions } from './operations/aggregate'; +import { BulkWriteOperation } from './operations/bulk_write'; +import { CountDocumentsOperation, CountDocumentsOptions } from './operations/count_documents'; +import { + CreateIndexesOperation, + CreateIndexOperation, + DropIndexOperation, + DropIndexesOperation, + IndexesOperation, + IndexExistsOperation, + IndexInformationOperation, + CreateIndexesOptions, + DropIndexesOptions, + ListIndexesOptions, + IndexSpecification, + IndexDescription, + ListIndexesCursor +} from './operations/indexes'; +import { DistinctOperation, DistinctOptions } from './operations/distinct'; +import { DropCollectionOperation, DropCollectionOptions } from './operations/drop'; +import { + EstimatedDocumentCountOperation, + EstimatedDocumentCountOptions +} from './operations/estimated_document_count'; +import type { FindOptions } from './operations/find'; +import { + FindOneAndDeleteOperation, + FindOneAndReplaceOperation, + FindOneAndUpdateOperation, + FindOneAndDeleteOptions, + FindOneAndReplaceOptions, + FindOneAndUpdateOptions +} from './operations/find_and_modify'; +import { + InsertOneOperation, + InsertOneOptions, + InsertOneResult, + InsertManyOperation, + InsertManyResult +} from './operations/insert'; +import { + UpdateOneOperation, + UpdateManyOperation, + UpdateOptions, + UpdateResult, + ReplaceOneOperation, + ReplaceOptions +} from './operations/update'; +import { + DeleteOneOperation, + DeleteManyOperation, + DeleteOptions, + DeleteResult +} from './operations/delete'; +import { IsCappedOperation } from './operations/is_capped'; +import { + MapReduceOperation, + MapFunction, + ReduceFunction, + MapReduceOptions +} from './operations/map_reduce'; +import { OptionsOperation } from './operations/options_operation'; +import { RenameOperation, RenameOptions } from './operations/rename'; +import { CollStats, CollStatsOperation, CollStatsOptions } from './operations/stats'; +import { executeOperation } from './operations/execute_operation'; +import type { Db } from './db'; +import type { OperationOptions, Hint } from './operations/operation'; +import type { IndexInformationOptions } from './operations/common_functions'; +import type { BulkWriteResult, BulkWriteOptions, AnyBulkWriteOperation } from './bulk/common'; +import type { PkFactory } from './mongo_client'; +import type { Logger, LoggerOptions } from './logger'; +import { FindCursor } from './cursor/find_cursor'; +import type { CountOptions } from './operations/count'; +import type { + Filter, + TODO_NODE_3286, + UpdateFilter, + WithId, + OptionalId, + Flatten +} from './mongo_types'; + +/** @public */ +export interface ModifyResult { + value: TSchema | null; + lastErrorObject?: Document; + ok: 0 | 1; +} + +/** @public */ +export interface CollectionOptions + extends BSONSerializeOptions, + WriteConcernOptions, + LoggerOptions { + slaveOk?: boolean; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; +} + +/** @internal */ +export interface CollectionPrivate { + pkFactory: PkFactory; + db: Db; + options: any; + namespace: MongoDBNamespace; + readPreference?: ReadPreference; + bsonOptions: BSONSerializeOptions; + slaveOk?: boolean; + collectionHint?: Hint; + readConcern?: ReadConcern; + writeConcern?: WriteConcern; +} + +/** + * The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * expect(err).to.not.exist; + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * ``` + */ +export class Collection { + /** @internal */ + s: CollectionPrivate; + + /** + * Create a new Collection instance + * @internal + */ + constructor(db: Db, name: string, options?: CollectionOptions) { + checkCollectionName(name); + + // Internal state + this.s = { + db, + options, + namespace: new MongoDBNamespace(db.databaseName, name), + pkFactory: db.options?.pkFactory ?? DEFAULT_PK_FACTORY, + readPreference: ReadPreference.fromOptions(options), + bsonOptions: resolveBSONOptions(options, db), + readConcern: ReadConcern.fromOptions(options), + writeConcern: WriteConcern.fromOptions(options), + slaveOk: options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk + }; + } + + /** + * The name of the database this collection belongs to + */ + get dbName(): string { + return this.s.namespace.db; + } + + /** + * The name of this collection + */ + get collectionName(): string { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return this.s.namespace.collection!; + } + + /** + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + */ + get namespace(): string { + return this.s.namespace.toString(); + } + + /** + * The current readConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readConcern(): ReadConcern | undefined { + if (this.s.readConcern == null) { + return this.s.db.readConcern; + } + return this.s.readConcern; + } + + /** + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readPreference(): ReadPreference | undefined { + if (this.s.readPreference == null) { + return this.s.db.readPreference; + } + + return this.s.readPreference; + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + /** + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get writeConcern(): WriteConcern | undefined { + if (this.s.writeConcern == null) { + return this.s.db.writeConcern; + } + return this.s.writeConcern; + } + + /** The current index hint for the collection */ + get hint(): Hint | undefined { + return this.s.collectionHint; + } + + set hint(v: Hint | undefined) { + this.s.collectionHint = normalizeHintField(v); + } + + /** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param doc - The document to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insertOne(doc: OptionalId): Promise>; + insertOne(doc: OptionalId, callback: Callback>): void; + insertOne(doc: OptionalId, options: InsertOneOptions): Promise>; + insertOne( + doc: OptionalId, + options: InsertOneOptions, + callback: Callback> + ): void; + insertOne( + doc: OptionalId, + options?: InsertOneOptions | Callback>, + callback?: Callback> + ): Promise> | void { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // CSFLE passes in { w: 'majority' } to ensure the lib works in both 3.x and 4.x + // we support that option style here only + if (options && Reflect.get(options, 'w')) { + options.writeConcern = WriteConcern.fromOptions(Reflect.get(options, 'w')); + } + + return executeOperation( + getTopology(this), + new InsertOneOperation( + this as TODO_NODE_3286, + doc, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insertMany(docs: OptionalId[]): Promise>; + insertMany(docs: OptionalId[], callback: Callback>): void; + insertMany( + docs: OptionalId[], + options: BulkWriteOptions + ): Promise>; + insertMany( + docs: OptionalId[], + options: BulkWriteOptions, + callback: Callback> + ): void; + insertMany( + docs: OptionalId[], + options?: BulkWriteOptions | Callback>, + callback?: Callback> + ): Promise> | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : { ordered: true }; + + return executeOperation( + getTopology(this), + new InsertManyOperation( + this as TODO_NODE_3286, + docs, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * ```js + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true} } + *``` + * Please note that raw operations are no longer accepted as of driver version 4.0. + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param operations - Bulk operations to perform + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * @throws MongoDriverError if operations is not an array + */ + bulkWrite(operations: AnyBulkWriteOperation[]): Promise; + bulkWrite( + operations: AnyBulkWriteOperation[], + callback: Callback + ): void; + bulkWrite( + operations: AnyBulkWriteOperation[], + options: BulkWriteOptions + ): Promise; + bulkWrite( + operations: AnyBulkWriteOperation[], + options: BulkWriteOptions, + callback: Callback + ): void; + bulkWrite( + operations: AnyBulkWriteOperation[], + options?: BulkWriteOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: true }; + + if (!Array.isArray(operations)) { + throw new MongoInvalidArgumentError('Argument "operations" must be an array of documents'); + } + + return executeOperation( + getTopology(this), + new BulkWriteOperation( + this as TODO_NODE_3286, + operations as TODO_NODE_3286, + resolveOptions(this, options) + ), + callback + ); + } + + /** + * Update a single document in a collection + * + * @param filter - The filter used to select the document to update + * @param update - The update operations to be applied to the document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + updateOne( + filter: Filter, + update: UpdateFilter | Partial + ): Promise; + updateOne( + filter: Filter, + update: UpdateFilter | Partial, + callback: Callback + ): void; + updateOne( + filter: Filter, + update: UpdateFilter | Partial, + options: UpdateOptions + ): Promise; + updateOne( + filter: Filter, + update: UpdateFilter | Partial, + options: UpdateOptions, + callback: Callback + ): void; + updateOne( + filter: Filter, + update: UpdateFilter | Partial, + options?: UpdateOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new UpdateOneOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Replace a document in a collection with another document + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + replaceOne(filter: Filter, replacement: TSchema): Promise; + replaceOne( + filter: Filter, + replacement: TSchema, + callback: Callback + ): void; + replaceOne( + filter: Filter, + replacement: TSchema, + options: ReplaceOptions + ): Promise; + replaceOne( + filter: Filter, + replacement: TSchema, + options: ReplaceOptions, + callback: Callback + ): void; + replaceOne( + filter: Filter, + replacement: TSchema, + options?: ReplaceOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new ReplaceOneOperation( + this as TODO_NODE_3286, + filter, + replacement, + resolveOptions(this, options) + ), + callback + ); + } + + /** + * Update multiple documents in a collection + * + * @param filter - The filter used to select the documents to update + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + updateMany( + filter: Filter, + update: UpdateFilter + ): Promise; + updateMany( + filter: Filter, + update: UpdateFilter, + callback: Callback + ): void; + updateMany( + filter: Filter, + update: UpdateFilter, + options: UpdateOptions + ): Promise; + updateMany( + filter: Filter, + update: UpdateFilter, + options: UpdateOptions, + callback: Callback + ): void; + updateMany( + filter: Filter, + update: UpdateFilter, + options?: UpdateOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new UpdateManyOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ), + callback + ); + } + + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + deleteOne(filter: Filter): Promise; + deleteOne(filter: Filter, callback: Callback): void; + deleteOne(filter: Filter, options: DeleteOptions): Promise; + deleteOne( + filter: Filter, + options: DeleteOptions, + callback?: Callback + ): void; + deleteOne( + filter: Filter, + options?: DeleteOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new DeleteOneOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)), + callback + ); + } + + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + deleteMany(filter: Filter): Promise; + deleteMany(filter: Filter, callback: Callback): void; + deleteMany(filter: Filter, options: DeleteOptions): Promise; + deleteMany( + filter: Filter, + options: DeleteOptions, + callback: Callback + ): void; + deleteMany( + filter: Filter, + options?: DeleteOptions | Callback, + callback?: Callback + ): Promise | void { + if (filter == null) { + filter = {}; + options = {}; + callback = undefined; + } else if (typeof filter === 'function') { + callback = filter as Callback; + filter = {}; + options = {}; + } else if (typeof options === 'function') { + callback = options; + options = {}; + } + + return executeOperation( + getTopology(this), + new DeleteManyOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)), + callback + ); + } + + /** + * Rename the collection. + * + * @remarks + * This operation does not inherit options from the Db or MongoClient. + * + * @param newName - New name of of the collection. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + rename(newName: string): Promise; + rename(newName: string, callback: Callback): void; + rename(newName: string, options: RenameOptions): Promise; + rename(newName: string, options: RenameOptions, callback: Callback): void; + rename( + newName: string, + options?: RenameOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + // Intentionally, we do not inherit options from parent for this operation. + return executeOperation( + getTopology(this), + new RenameOperation(this as TODO_NODE_3286, newName, { + ...options, + readPreference: ReadPreference.PRIMARY + }), + callback + ); + } + + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + drop(): Promise; + drop(callback: Callback): void; + drop(options: DropCollectionOptions): Promise; + drop(options: DropCollectionOptions, callback: Callback): void; + drop( + options?: DropCollectionOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return executeOperation( + getTopology(this), + new DropCollectionOperation(this.s.db, this.collectionName, options), + callback + ); + } + + /** + * Fetches the first document that matches the filter + * + * @param filter - Query for find Operation + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOne(): Promise; + findOne(callback: Callback): void; + findOne(filter: Filter): Promise; + findOne(filter: Filter, callback: Callback): void; + findOne(filter: Filter, options: FindOptions): Promise; + findOne(filter: Filter, options: FindOptions, callback: Callback): void; + + // allow an override of the schema. + findOne(): Promise; + findOne(callback: Callback): void; + findOne(filter: Filter): Promise; + findOne(filter: Filter, options?: FindOptions): Promise; + findOne( + filter: Filter, + options?: FindOptions, + callback?: Callback + ): void; + + findOne( + filter?: Filter | Callback, + options?: FindOptions | Callback, + callback?: Callback + ): Promise | void { + if (callback != null && typeof callback !== 'function') { + throw new MongoInvalidArgumentError( + 'Third parameter to `findOne()` must be a callback or undefined' + ); + } + + if (typeof filter === 'function') { + callback = filter as Callback; + filter = {}; + options = {}; + } + if (typeof options === 'function') { + callback = options; + options = {}; + } + + const finalFilter = filter ?? {}; + const finalOptions = options ?? {}; + return this.find(finalFilter, finalOptions).limit(-1).batchSize(1).next(callback); + } + + /** + * Creates a cursor for a filter that can be used to iterate over results from MongoDB + * + * @param filter - The filter predicate. If unspecified, then all documents in the collection will match the predicate + */ + find(): FindCursor; + find(filter: Filter, options?: FindOptions): FindCursor; + find(filter: Filter, options?: FindOptions): FindCursor; + find(filter?: Filter, options?: FindOptions): FindCursor { + if (arguments.length > 2) { + throw new MongoInvalidArgumentError( + 'Method "collection.find()" accepts at most two arguments' + ); + } + if (typeof options === 'function') { + throw new MongoInvalidArgumentError('Argument "options" must not be function'); + } + + return new FindCursor( + getTopology(this), + this.s.namespace, + filter, + resolveOptions(this as TODO_NODE_3286, options) + ); + } + + /** + * Returns the options of the collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + options(): Promise; + options(callback: Callback): void; + options(options: OperationOptions): Promise; + options(options: OperationOptions, callback: Callback): void; + options( + options?: OperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new OptionsOperation(this as TODO_NODE_3286, resolveOptions(this, options)), + callback + ); + } + + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + isCapped(): Promise; + isCapped(callback: Callback): void; + isCapped(options: OperationOptions): Promise; + isCapped(options: OperationOptions, callback: Callback): void; + isCapped( + options?: OperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new IsCappedOperation(this as TODO_NODE_3286, resolveOptions(this, options)), + callback + ); + } + + /** + * Creates an index on the db and collection collection. + * + * @param indexSpec - The field name or index specification to create an index for + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @example + * ```js + * const collection = client.db('foo').collection('bar'); + * + * await collection.createIndex({ a: 1, b: -1 }); + * + * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes + * await collection.createIndex([ [c, 1], [d, -1] ]); + * + * // Equivalent to { e: 1 } + * await collection.createIndex('e'); + * + * // Equivalent to { f: 1, g: 1 } + * await collection.createIndex(['f', 'g']) + * + * // Equivalent to { h: 1, i: -1 } + * await collection.createIndex([ { h: 1 }, { i: -1 } ]); + * + * // Equivalent to { j: 1, k: -1, l: 2d } + * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) + * ``` + */ + createIndex(indexSpec: IndexSpecification): Promise; + createIndex(indexSpec: IndexSpecification, callback: Callback): void; + createIndex(indexSpec: IndexSpecification, options: CreateIndexesOptions): Promise; + createIndex( + indexSpec: IndexSpecification, + options: CreateIndexesOptions, + callback: Callback + ): void; + createIndex( + indexSpec: IndexSpecification, + options?: CreateIndexesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new CreateIndexOperation( + this as TODO_NODE_3286, + this.collectionName, + indexSpec, + resolveOptions(this, options) + ), + callback + ); + } + + /** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. + * + * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications. + * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/| here}. + * + * @param indexSpecs - An array of index specifications to be created + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @example + * ```js + * const collection = client.db('foo').collection('bar'); + * await collection.createIndexes([ + * // Simple index on field fizz + * { + * key: { fizz: 1 }, + * } + * // wildcard index + * { + * key: { '$**': 1 } + * }, + * // named index on darmok and jalad + * { + * key: { darmok: 1, jalad: -1 } + * name: 'tanagra' + * } + * ]); + * ``` + */ + createIndexes(indexSpecs: IndexDescription[]): Promise; + createIndexes(indexSpecs: IndexDescription[], callback: Callback): void; + createIndexes(indexSpecs: IndexDescription[], options: CreateIndexesOptions): Promise; + createIndexes( + indexSpecs: IndexDescription[], + options: CreateIndexesOptions, + callback: Callback + ): void; + createIndexes( + indexSpecs: IndexDescription[], + options?: CreateIndexesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + return executeOperation( + getTopology(this), + new CreateIndexesOperation( + this as TODO_NODE_3286, + this.collectionName, + indexSpecs, + resolveOptions(this, options) + ), + callback + ); + } + + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropIndex(indexName: string): Promise; + dropIndex(indexName: string, callback: Callback): void; + dropIndex(indexName: string, options: DropIndexesOptions): Promise; + dropIndex(indexName: string, options: DropIndexesOptions, callback: Callback): void; + dropIndex( + indexName: string, + options?: DropIndexesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = resolveOptions(this, options); + + // Run only against primary + options.readPreference = ReadPreference.primary; + + return executeOperation( + getTopology(this), + new DropIndexOperation(this as TODO_NODE_3286, indexName, options), + callback + ); + } + + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropIndexes(): Promise; + dropIndexes(callback: Callback): void; + dropIndexes(options: DropIndexesOptions): Promise; + dropIndexes(options: DropIndexesOptions, callback: Callback): void; + dropIndexes( + options?: DropIndexesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new DropIndexesOperation(this as TODO_NODE_3286, resolveOptions(this, options)), + callback + ); + } + + /** + * Get the list of all indexes information for the collection. + * + * @param options - Optional settings for the command + */ + listIndexes(options?: ListIndexesOptions): ListIndexesCursor { + return new ListIndexesCursor(this as TODO_NODE_3286, resolveOptions(this, options)); + } + + /** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * + * @param indexes - One or more index names to check. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexExists(indexes: string | string[]): Promise; + indexExists(indexes: string | string[], callback: Callback): void; + indexExists(indexes: string | string[], options: IndexInformationOptions): Promise; + indexExists( + indexes: string | string[], + options: IndexInformationOptions, + callback: Callback + ): void; + indexExists( + indexes: string | string[], + options?: IndexInformationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new IndexExistsOperation(this as TODO_NODE_3286, indexes, resolveOptions(this, options)), + callback + ); + } + + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexInformation(): Promise; + indexInformation(callback: Callback): void; + indexInformation(options: IndexInformationOptions): Promise; + indexInformation(options: IndexInformationOptions, callback: Callback): void; + indexInformation( + options?: IndexInformationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new IndexInformationOperation(this.s.db, this.collectionName, resolveOptions(this, options)), + callback + ); + } + + /** + * Gets an estimate of the count of documents in a collection using collection metadata. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + estimatedDocumentCount(): Promise; + estimatedDocumentCount(callback: Callback): void; + estimatedDocumentCount(options: EstimatedDocumentCountOptions): Promise; + estimatedDocumentCount(options: EstimatedDocumentCountOptions, callback: Callback): void; + estimatedDocumentCount( + options?: EstimatedDocumentCountOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + return executeOperation( + getTopology(this), + new EstimatedDocumentCountOperation(this as TODO_NODE_3286, resolveOptions(this, options)), + callback + ); + } + + /** + * Gets the number of documents matching the filter. + * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ + * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param filter - The filter for the count + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ + * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + countDocuments(): Promise; + countDocuments(callback: Callback): void; + countDocuments(filter: Filter): Promise; + countDocuments(callback: Callback): void; + countDocuments(filter: Filter, options: CountDocumentsOptions): Promise; + countDocuments( + filter: Filter, + options: CountDocumentsOptions, + callback: Callback + ): void; + countDocuments(filter: Filter, callback: Callback): void; + countDocuments( + filter?: Document | CountDocumentsOptions | Callback, + options?: CountDocumentsOptions | Callback, + callback?: Callback + ): Promise | void { + if (filter == null) { + (filter = {}), (options = {}), (callback = undefined); + } else if (typeof filter === 'function') { + (callback = filter as Callback), (filter = {}), (options = {}); + } else { + if (arguments.length === 2) { + if (typeof options === 'function') (callback = options), (options = {}); + } + } + + filter ??= {}; + return executeOperation( + getTopology(this), + new CountDocumentsOperation( + this as TODO_NODE_3286, + filter as Document, + resolveOptions(this, options as CountDocumentsOptions) + ), + callback + ); + } + + /** + * The distinct command returns a list of distinct values for the given key across a collection. + * + * @param key - Field of the document to find distinct values for + * @param filter - The filter for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + distinct>( + key: Key + ): Promise[Key]>>>; + distinct>( + key: Key, + callback: Callback[Key]>>> + ): void; + distinct>( + key: Key, + filter: Filter + ): Promise[Key]>>>; + distinct>( + key: Key, + filter: Filter, + callback: Callback[Key]>>> + ): void; + distinct>( + key: Key, + filter: Filter, + options: DistinctOptions + ): Promise[Key]>>>; + distinct>( + key: Key, + filter: Filter, + options: DistinctOptions, + callback: Callback[Key]>>> + ): void; + + // Embedded documents overload + distinct(key: string): Promise; + distinct(key: string, callback: Callback): void; + distinct(key: string, filter: Filter): Promise; + distinct(key: string, filter: Filter, callback: Callback): void; + distinct(key: string, filter: Filter, options: DistinctOptions): Promise; + distinct( + key: string, + filter: Filter, + options: DistinctOptions, + callback: Callback + ): void; + // Implementation + distinct>( + key: Key, + filter?: Filter | DistinctOptions | Callback, + options?: DistinctOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof filter === 'function') { + (callback = filter as Callback), (filter = {}), (options = {}); + } else { + if (arguments.length === 3 && typeof options === 'function') { + (callback = options), (options = {}); + } + } + + filter ??= {}; + return executeOperation( + getTopology(this), + new DistinctOperation( + this as TODO_NODE_3286, + key as TODO_NODE_3286, + filter, + resolveOptions(this, options as DistinctOptions) + ), + callback + ); + } + + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexes(): Promise; + indexes(callback: Callback): void; + indexes(options: IndexInformationOptions): Promise; + indexes(options: IndexInformationOptions, callback: Callback): void; + indexes( + options?: IndexInformationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new IndexesOperation(this as TODO_NODE_3286, resolveOptions(this, options)), + callback + ); + } + + /** + * Get all the collection statistics. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + stats(): Promise; + stats(callback: Callback): void; + stats(options: CollStatsOptions): Promise; + stats(options: CollStatsOptions, callback: Callback): void; + stats( + options?: CollStatsOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return executeOperation( + getTopology(this), + new CollStatsOperation(this as TODO_NODE_3286, options), + callback + ); + } + + /** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndDelete(filter: Filter): Promise>; + findOneAndDelete( + filter: Filter, + options: FindOneAndDeleteOptions + ): Promise>; + findOneAndDelete(filter: Filter, callback: Callback>): void; + findOneAndDelete( + filter: Filter, + options: FindOneAndDeleteOptions, + callback: Callback> + ): void; + findOneAndDelete( + filter: Filter, + options?: FindOneAndDeleteOptions | Callback>, + callback?: Callback> + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new FindOneAndDeleteOperation( + this as TODO_NODE_3286, + filter, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndReplace(filter: Filter, replacement: Document): Promise>; + findOneAndReplace( + filter: Filter, + replacement: Document, + callback: Callback> + ): void; + findOneAndReplace( + filter: Filter, + replacement: Document, + options: FindOneAndReplaceOptions + ): Promise>; + findOneAndReplace( + filter: Filter, + replacement: Document, + options: FindOneAndReplaceOptions, + callback: Callback> + ): void; + findOneAndReplace( + filter: Filter, + replacement: Document, + options?: FindOneAndReplaceOptions | Callback>, + callback?: Callback> + ): Promise> | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new FindOneAndReplaceOperation( + this as TODO_NODE_3286, + filter, + replacement, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to update + * @param update - Update operations to be performed on the document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndUpdate( + filter: Filter, + update: UpdateFilter + ): Promise>; + findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + callback: Callback> + ): void; + findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options: FindOneAndUpdateOptions + ): Promise>; + findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options: FindOneAndUpdateOptions, + callback: Callback> + ): void; + findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options?: FindOneAndUpdateOptions | Callback>, + callback?: Callback> + ): Promise> | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new FindOneAndUpdateOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 + * + * @param pipeline - An array of aggregation pipelines to execute + * @param options - Optional settings for the command + */ + aggregate( + pipeline: Document[] = [], + options?: AggregateOptions + ): AggregationCursor { + if (arguments.length > 2) { + throw new MongoInvalidArgumentError( + 'Method "collection.aggregate()" accepts at most two arguments' + ); + } + if (!Array.isArray(pipeline)) { + throw new MongoInvalidArgumentError( + 'Argument "pipeline" must be an array of aggregation stages' + ); + } + if (typeof options === 'function') { + throw new MongoInvalidArgumentError('Argument "options" must not be function'); + } + + return new AggregationCursor( + getTopology(this), + this.s.namespace, + pipeline, + resolveOptions(this, options) + ); + } + + /** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * + * @since 3.0.0 + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch( + pipeline: Document[] = [], + options: ChangeStreamOptions = {} + ): ChangeStream { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, resolveOptions(this, options)); + } + + /** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @param map - The mapping function. + * @param reduce - The reduce function. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + mapReduce( + map: string | MapFunction, + reduce: string | ReduceFunction + ): Promise; + mapReduce( + map: string | MapFunction, + reduce: string | ReduceFunction, + callback: Callback + ): void; + mapReduce( + map: string | MapFunction, + reduce: string | ReduceFunction, + options: MapReduceOptions + ): Promise; + mapReduce( + map: string | MapFunction, + reduce: string | ReduceFunction, + options: MapReduceOptions, + callback: Callback + ): void; + mapReduce( + map: string | MapFunction, + reduce: string | ReduceFunction, + options?: MapReduceOptions | Callback, + callback?: Callback + ): Promise | void { + if ('function' === typeof options) (callback = options), (options = {}); + // Out must always be defined (make sure we don't break weirdly on pre 1.8+ servers) + // TODO NODE-3339: Figure out if this is still necessary given we no longer officially support pre-1.8 + if (options?.out == null) { + throw new MongoInvalidArgumentError( + 'Option "out" must be defined, see mongodb docs for possible values' + ); + } + + if ('function' === typeof map) { + map = map.toString(); + } + + if ('function' === typeof reduce) { + reduce = reduce.toString(); + } + + if ('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + + return executeOperation( + getTopology(this), + new MapReduceOperation( + this as TODO_NODE_3286, + map, + reduce, + resolveOptions(this, options) as TODO_NODE_3286 + ), + callback + ); + } + + /** Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. */ + initializeUnorderedBulkOp(options?: BulkWriteOptions): UnorderedBulkOperation { + return new UnorderedBulkOperation(this as TODO_NODE_3286, resolveOptions(this, options)); + } + + /** Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. */ + initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation { + return new OrderedBulkOperation(this as TODO_NODE_3286, resolveOptions(this, options)); + } + + /** Get the db scoped logger */ + getLogger(): Logger { + return this.s.db.s.logger; + } + + get logger(): Logger { + return this.s.db.s.logger; + } + + /** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @deprecated Use insertOne, insertMany or bulkWrite instead. + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insert( + docs: OptionalId[], + options: BulkWriteOptions, + callback: Callback> + ): Promise> | void { + emitWarningOnce( + 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.' + ); + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: false }; + docs = !Array.isArray(docs) ? [docs] : docs; + + if (options.keepGoing === true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); + } + + /** + * Updates documents. + * + * @deprecated use updateOne, updateMany or bulkWrite + * @param selector - The selector for the update operation. + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + update( + selector: Filter, + update: UpdateFilter, + options: UpdateOptions, + callback: Callback + ): Promise | void { + emitWarningOnce( + 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.' + ); + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return this.updateMany(selector, update, options, callback); + } + + /** + * Remove documents. + * + * @deprecated use deleteOne, deleteMany or bulkWrite + * @param selector - The selector for the update operation. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + remove( + selector: Filter, + options: DeleteOptions, + callback: Callback + ): Promise | void { + emitWarningOnce( + 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.' + ); + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return this.deleteMany(selector, options, callback); + } + + /** + * An estimated count of matching documents in the db to a filter. + * + * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents + * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}. + * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * + * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead + * + * @param filter - The filter for the count. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + count(): Promise; + count(callback: Callback): void; + count(filter: Filter): Promise; + count(filter: Filter, callback: Callback): void; + count(filter: Filter, options: CountOptions): Promise; + count( + filter: Filter, + options: CountOptions, + callback: Callback + ): Promise | void; + count( + filter?: Filter | CountOptions | Callback, + options?: CountOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof filter === 'function') { + (callback = filter as Callback), (filter = {}), (options = {}); + } else { + if (typeof options === 'function') (callback = options), (options = {}); + } + + filter ??= {}; + return executeOperation( + getTopology(this), + new CountDocumentsOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)), + callback + ); + } +} diff --git a/node_modules/mongodb/src/connection_string.ts b/node_modules/mongodb/src/connection_string.ts new file mode 100644 index 0000000..c188e2d --- /dev/null +++ b/node_modules/mongodb/src/connection_string.ts @@ -0,0 +1,1119 @@ +import * as dns from 'dns'; +import * as fs from 'fs'; +import ConnectionString from 'mongodb-connection-string-url'; +import { URLSearchParams } from 'url'; +import { AuthMechanism } from './cmap/auth/defaultAuthProviders'; +import { ReadPreference, ReadPreferenceMode } from './read_preference'; +import { ReadConcern, ReadConcernLevel } from './read_concern'; +import { W, WriteConcern } from './write_concern'; +import { MongoAPIError, MongoInvalidArgumentError, MongoParseError } from './error'; +import { + AnyOptions, + Callback, + DEFAULT_PK_FACTORY, + isRecord, + makeClientMetadata, + setDifference, + HostAddress, + emitWarning +} from './utils'; +import type { Document } from './bson'; +import { + DriverInfo, + MongoClient, + MongoClientOptions, + MongoOptions, + PkFactory, + ServerApi, + ServerApiVersion +} from './mongo_client'; +import { MongoCredentials } from './cmap/auth/mongo_credentials'; +import type { TagSet } from './sdam/server_description'; +import { Logger, LoggerLevel } from './logger'; +import { PromiseProvider } from './promise_provider'; +import { Encrypter } from './encrypter'; +import { Compressor, CompressorName } from './cmap/wire_protocol/compression'; + +const VALID_TXT_RECORDS = ['authSource', 'replicaSet', 'loadBalanced']; + +const LB_SINGLE_HOST_ERROR = 'loadBalanced option only supported with a single host in the URI'; +const LB_REPLICA_SET_ERROR = 'loadBalanced option not supported with a replicaSet option'; +const LB_DIRECT_CONNECTION_ERROR = + 'loadBalanced option not supported when directConnection is provided'; + +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param srvAddress - The address to check against a domain + * @param parentDomain - The domain to check the provided address against + * @returns Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress: string, parentDomain: string): boolean { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +/** + * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal + * connection string. + * + * @param uri - The connection string to parse + * @param options - Optional user provided connection string options + */ +export function resolveSRVRecord(options: MongoOptions, callback: Callback): void { + if (typeof options.srvHost !== 'string') { + return callback(new MongoAPIError('Option "srvHost" must not be empty')); + } + + if (options.srvHost.split('.').length < 3) { + // TODO(NODE-3484): Replace with MongoConnectionStringError + return callback(new MongoAPIError('URI must include hostname, domain name, and tld')); + } + + // Resolve the SRV record and use the result as the list of hosts to connect to. + const lookupAddress = options.srvHost; + dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new MongoAPIError('No addresses found at host')); + } + + for (const { name } of addresses) { + if (!matchesParentDomain(name, lookupAddress)) { + return callback(new MongoAPIError('Server record does not share hostname with parent URI')); + } + } + + const hostAddresses = addresses.map(r => + HostAddress.fromString(`${r.name}:${r.port ?? 27017}`) + ); + + const lbError = validateLoadBalancedOptions(hostAddresses, options); + if (lbError) { + return callback(lbError); + } + + // Resolve TXT record and add options from there if they exist. + dns.resolveTxt(lookupAddress, (err, record) => { + if (err) { + if (err.code !== 'ENODATA' && err.code !== 'ENOTFOUND') { + return callback(err); + } + } else { + if (record.length > 1) { + return callback(new MongoParseError('Multiple text records not allowed')); + } + + const txtRecordOptions = new URLSearchParams(record[0].join('')); + const txtRecordOptionKeys = [...txtRecordOptions.keys()]; + if (txtRecordOptionKeys.some(key => !VALID_TXT_RECORDS.includes(key))) { + return callback( + new MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`) + ); + } + + const source = txtRecordOptions.get('authSource') ?? undefined; + const replicaSet = txtRecordOptions.get('replicaSet') ?? undefined; + const loadBalanced = txtRecordOptions.get('loadBalanced') ?? undefined; + + if (source === '' || replicaSet === '') { + return callback(new MongoParseError('Cannot have empty URI params in DNS TXT Record')); + } + + if (!options.userSpecifiedAuthSource && source) { + options.credentials = MongoCredentials.merge(options.credentials, { source }); + } + + if (!options.userSpecifiedReplicaSet && replicaSet) { + options.replicaSet = replicaSet; + } + + if (loadBalanced === 'true') { + options.loadBalanced = true; + } + + const lbError = validateLoadBalancedOptions(hostAddresses, options); + if (lbError) { + return callback(lbError); + } + } + + callback(undefined, hostAddresses); + }); + }); +} + +/** + * Checks if TLS options are valid + * + * @param options - The options used for options parsing + * @throws MongoParseError if TLS options are invalid + */ +export function checkTLSOptions(options: AnyOptions): void { + if (!options) return; + const check = (a: string, b: string) => { + if (Reflect.has(options, a) && Reflect.has(options, b)) { + throw new MongoParseError(`The '${a}' option cannot be used with '${b}'`); + } + }; + check('tlsInsecure', 'tlsAllowInvalidCertificates'); + check('tlsInsecure', 'tlsAllowInvalidHostnames'); + check('tlsInsecure', 'tlsDisableCertificateRevocationCheck'); + check('tlsInsecure', 'tlsDisableOCSPEndpointCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableCertificateRevocationCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableOCSPEndpointCheck'); + check('tlsDisableCertificateRevocationCheck', 'tlsDisableOCSPEndpointCheck'); +} + +const TRUTHS = new Set(['true', 't', '1', 'y', 'yes']); +const FALSEHOODS = new Set(['false', 'f', '0', 'n', 'no', '-1']); +function getBoolean(name: string, value: unknown): boolean { + if (typeof value === 'boolean') return value; + const valueString = String(value).toLowerCase(); + if (TRUTHS.has(valueString)) return true; + if (FALSEHOODS.has(valueString)) return false; + throw new MongoParseError(`Expected ${name} to be stringified boolean value, got: ${value}`); +} + +function getInt(name: string, value: unknown): number { + if (typeof value === 'number') return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + if (!Number.isNaN(parsedValue)) return parsedValue; + throw new MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); +} + +function getUint(name: string, value: unknown): number { + const parsedValue = getInt(name, value); + if (parsedValue < 0) { + throw new MongoParseError(`${name} can only be a positive int value, got: ${value}`); + } + return parsedValue; +} + +function toRecord(value: string): Record { + const record = Object.create(null); + const keyValuePairs = value.split(','); + for (const keyValue of keyValuePairs) { + const [key, value] = keyValue.split(':'); + if (value == null) { + throw new MongoParseError('Cannot have undefined values in key value pairs'); + } + try { + // try to get a boolean + record[key] = getBoolean('', value); + } catch { + try { + // try to get a number + record[key] = getInt('', value); + } catch { + // keep value as a string + record[key] = value; + } + } + } + return record; +} + +class CaseInsensitiveMap extends Map { + constructor(entries: Array<[string, any]> = []) { + super(entries.map(([k, v]) => [k.toLowerCase(), v])); + } + has(k: string) { + return super.has(k.toLowerCase()); + } + get(k: string) { + return super.get(k.toLowerCase()); + } + set(k: string, v: any) { + return super.set(k.toLowerCase(), v); + } + delete(k: string): boolean { + return super.delete(k.toLowerCase()); + } +} + +export function parseOptions( + uri: string, + mongoClient: MongoClient | MongoClientOptions | undefined = undefined, + options: MongoClientOptions = {} +): MongoOptions { + if (mongoClient != null && !(mongoClient instanceof MongoClient)) { + options = mongoClient; + mongoClient = undefined; + } + + const url = new ConnectionString(uri); + const { hosts, isSRV } = url; + + const mongoOptions = Object.create(null); + mongoOptions.hosts = isSRV ? [] : hosts.map(HostAddress.fromString); + if (isSRV) { + // SRV Record is resolved upon connecting + mongoOptions.srvHost = hosts[0]; + if (!url.searchParams.has('tls') && !url.searchParams.has('ssl')) { + options.tls = true; + } + } + + const urlOptions = new CaseInsensitiveMap(); + + if (url.pathname !== '/' && url.pathname !== '') { + const dbName = decodeURIComponent( + url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname + ); + if (dbName) { + urlOptions.set('dbName', [dbName]); + } + } + + if (url.username !== '') { + const auth: Document = { + username: decodeURIComponent(url.username) + }; + + if (typeof url.password === 'string') { + auth.password = decodeURIComponent(url.password); + } + + urlOptions.set('auth', [auth]); + } + + for (const key of url.searchParams.keys()) { + const values = [...url.searchParams.getAll(key)]; + + if (values.includes('')) { + throw new MongoAPIError('URI cannot contain options with no value'); + } + + if (key.toLowerCase() === 'serverapi') { + throw new MongoParseError( + 'URI cannot contain `serverApi`, it can only be passed to the client' + ); + } + + if (key.toLowerCase() === 'authsource' && urlOptions.has('authSource')) { + // If authSource is an explicit key in the urlOptions we need to remove the implicit dbName + urlOptions.delete('authSource'); + } + + if (!urlOptions.has(key)) { + urlOptions.set(key, values); + } + } + + const objectOptions = new CaseInsensitiveMap( + Object.entries(options).filter(([, v]) => v != null) + ); + + if (objectOptions.has('loadBalanced')) { + throw new MongoParseError('loadBalanced is only a valid option in the URI'); + } + + const allOptions = new CaseInsensitiveMap(); + + const allKeys = new Set([ + ...urlOptions.keys(), + ...objectOptions.keys(), + ...DEFAULT_OPTIONS.keys() + ]); + + for (const key of allKeys) { + const values = []; + if (objectOptions.has(key)) { + values.push(objectOptions.get(key)); + } + if (urlOptions.has(key)) { + values.push(...urlOptions.get(key)); + } + if (DEFAULT_OPTIONS.has(key)) { + values.push(DEFAULT_OPTIONS.get(key)); + } + allOptions.set(key, values); + } + + if (allOptions.has('tlsCertificateKeyFile') && !allOptions.has('tlsCertificateFile')) { + allOptions.set('tlsCertificateFile', allOptions.get('tlsCertificateKeyFile')); + } + + if (allOptions.has('tls') || allOptions.has('ssl')) { + const tlsAndSslOpts = (allOptions.get('tls') || []) + .concat(allOptions.get('ssl') || []) + .map(getBoolean.bind(null, 'tls/ssl')); + if (new Set(tlsAndSslOpts).size !== 1) { + throw new MongoParseError('All values of tls/ssl must be the same.'); + } + } + + const unsupportedOptions = setDifference( + allKeys, + Array.from(Object.keys(OPTIONS)).map(s => s.toLowerCase()) + ); + if (unsupportedOptions.size !== 0) { + const optionWord = unsupportedOptions.size > 1 ? 'options' : 'option'; + const isOrAre = unsupportedOptions.size > 1 ? 'are' : 'is'; + throw new MongoParseError( + `${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported` + ); + } + + for (const [key, descriptor] of Object.entries(OPTIONS)) { + const values = allOptions.get(key); + if (!values || values.length === 0) continue; + setOption(mongoOptions, key, descriptor, values); + } + + if (mongoOptions.credentials) { + const isGssapi = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_GSSAPI; + const isX509 = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_X509; + const isAws = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_AWS; + if ( + (isGssapi || isX509) && + allOptions.has('authSource') && + mongoOptions.credentials.source !== '$external' + ) { + // If authSource was explicitly given and its incorrect, we error + throw new MongoParseError( + `${mongoOptions.credentials} can only have authSource set to '$external'` + ); + } + + if (!(isGssapi || isX509 || isAws) && mongoOptions.dbName && !allOptions.has('authSource')) { + // inherit the dbName unless GSSAPI or X509, then silently ignore dbName + // and there was no specific authSource given + mongoOptions.credentials = MongoCredentials.merge(mongoOptions.credentials, { + source: mongoOptions.dbName + }); + } + + mongoOptions.credentials.validate(); + } + + if (!mongoOptions.dbName) { + // dbName default is applied here because of the credential validation above + mongoOptions.dbName = 'test'; + } + + checkTLSOptions(mongoOptions); + + if (options.promiseLibrary) PromiseProvider.set(options.promiseLibrary); + + if (mongoOptions.directConnection && typeof mongoOptions.srvHost === 'string') { + throw new MongoAPIError('SRV URI does not support directConnection'); + } + + const lbError = validateLoadBalancedOptions(hosts, mongoOptions); + if (lbError) { + throw lbError; + } + + // Potential SRV Overrides + mongoOptions.userSpecifiedAuthSource = + objectOptions.has('authSource') || urlOptions.has('authSource'); + mongoOptions.userSpecifiedReplicaSet = + objectOptions.has('replicaSet') || urlOptions.has('replicaSet'); + + if (mongoClient && mongoOptions.autoEncryption) { + Encrypter.checkForMongoCrypt(); + mongoOptions.encrypter = new Encrypter(mongoClient, uri, options); + mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter; + } + + return mongoOptions; +} + +function validateLoadBalancedOptions( + hosts: HostAddress[] | string[], + mongoOptions: MongoOptions +): MongoParseError | undefined { + if (mongoOptions.loadBalanced) { + if (hosts.length > 1) { + return new MongoParseError(LB_SINGLE_HOST_ERROR); + } + if (mongoOptions.replicaSet) { + return new MongoParseError(LB_REPLICA_SET_ERROR); + } + if (mongoOptions.directConnection) { + return new MongoParseError(LB_DIRECT_CONNECTION_ERROR); + } + } +} + +function setOption( + mongoOptions: any, + key: string, + descriptor: OptionDescriptor, + values: unknown[] +) { + const { target, type, transform, deprecated } = descriptor; + const name = target ?? key; + + if (deprecated) { + const deprecatedMsg = typeof deprecated === 'string' ? `: ${deprecated}` : ''; + emitWarning(`${key} is a deprecated option${deprecatedMsg}`); + } + + switch (type) { + case 'boolean': + mongoOptions[name] = getBoolean(name, values[0]); + break; + case 'int': + mongoOptions[name] = getInt(name, values[0]); + break; + case 'uint': + mongoOptions[name] = getUint(name, values[0]); + break; + case 'string': + if (values[0] == null) { + break; + } + mongoOptions[name] = String(values[0]); + break; + case 'record': + if (!isRecord(values[0])) { + throw new MongoParseError(`${name} must be an object`); + } + mongoOptions[name] = values[0]; + break; + case 'any': + mongoOptions[name] = values[0]; + break; + default: { + if (!transform) { + throw new MongoParseError('Descriptors missing a type must define a transform'); + } + const transformValue = transform({ name, options: mongoOptions, values }); + mongoOptions[name] = transformValue; + break; + } + } +} + +interface OptionDescriptor { + target?: string; + type?: 'boolean' | 'int' | 'uint' | 'record' | 'string' | 'any'; + default?: any; + + deprecated?: boolean | string; + /** + * @param name - the original option name + * @param options - the options so far for resolution + * @param values - the possible values in precedence order + */ + transform?: (args: { name: string; options: MongoOptions; values: unknown[] }) => unknown; +} + +export const OPTIONS = { + appName: { + target: 'metadata', + transform({ options, values: [value] }): DriverInfo { + return makeClientMetadata({ ...options.driverInfo, appName: String(value) }); + } + }, + auth: { + target: 'credentials', + transform({ name, options, values: [value] }): MongoCredentials { + if (!isRecord(value, ['username', 'password'] as const)) { + throw new MongoParseError( + `${name} must be an object with 'username' and 'password' properties` + ); + } + return MongoCredentials.merge(options.credentials, { + username: value.username, + password: value.password + }); + } + }, + authMechanism: { + target: 'credentials', + transform({ options, values: [value] }): MongoCredentials { + const mechanisms = Object.values(AuthMechanism); + const [mechanism] = mechanisms.filter(m => m.match(RegExp(String.raw`\b${value}\b`, 'i'))); + if (!mechanism) { + throw new MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`); + } + let source = options.credentials?.source; + if ( + mechanism === AuthMechanism.MONGODB_PLAIN || + mechanism === AuthMechanism.MONGODB_GSSAPI || + mechanism === AuthMechanism.MONGODB_AWS || + mechanism === AuthMechanism.MONGODB_X509 + ) { + // some mechanisms have '$external' as the Auth Source + source = '$external'; + } + + let password = options.credentials?.password; + if (mechanism === AuthMechanism.MONGODB_X509 && password === '') { + password = undefined; + } + return MongoCredentials.merge(options.credentials, { + mechanism, + source, + password + }); + } + }, + authMechanismProperties: { + target: 'credentials', + transform({ options, values: [value] }): MongoCredentials { + if (typeof value === 'string') { + value = toRecord(value); + } + if (!isRecord(value)) { + throw new MongoParseError('AuthMechanismProperties must be an object'); + } + return MongoCredentials.merge(options.credentials, { mechanismProperties: value }); + } + }, + authSource: { + target: 'credentials', + transform({ options, values: [value] }): MongoCredentials { + const source = String(value); + return MongoCredentials.merge(options.credentials, { source }); + } + }, + autoEncryption: { + type: 'record' + }, + bsonRegExp: { + type: 'boolean' + }, + serverApi: { + target: 'serverApi', + transform({ values: [version] }): ServerApi { + const serverApiToValidate = + typeof version === 'string' ? ({ version } as ServerApi) : (version as ServerApi); + const versionToValidate = serverApiToValidate && serverApiToValidate.version; + if (!versionToValidate) { + throw new MongoParseError( + `Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values( + ServerApiVersion + ).join('", "')}"]` + ); + } + if (!Object.values(ServerApiVersion).some(v => v === versionToValidate)) { + throw new MongoParseError( + `Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values( + ServerApiVersion + ).join('", "')}"]` + ); + } + return serverApiToValidate; + } + }, + checkKeys: { + type: 'boolean' + }, + compressors: { + default: 'none', + target: 'compressors', + transform({ values }) { + const compressionList = new Set(); + for (const compVal of values as (CompressorName[] | string)[]) { + const compValArray = typeof compVal === 'string' ? compVal.split(',') : compVal; + if (!Array.isArray(compValArray)) { + throw new MongoInvalidArgumentError( + 'compressors must be an array or a comma-delimited list of strings' + ); + } + for (const c of compValArray) { + if (Object.keys(Compressor).includes(String(c))) { + compressionList.add(String(c)); + } else { + throw new MongoInvalidArgumentError( + `${c} is not a valid compression mechanism. Must be one of: ${Object.keys( + Compressor + )}.` + ); + } + } + } + return [...compressionList]; + } + }, + connectTimeoutMS: { + default: 30000, + type: 'uint' + }, + dbName: { + type: 'string' + }, + directConnection: { + default: false, + type: 'boolean' + }, + driverInfo: { + target: 'metadata', + default: makeClientMetadata(), + transform({ options, values: [value] }) { + if (!isRecord(value)) throw new MongoParseError('DriverInfo must be an object'); + return makeClientMetadata({ + driverInfo: value, + appName: options.metadata?.application?.name + }); + } + }, + family: { + transform({ name, values: [value] }): 4 | 6 { + const transformValue = getInt(name, value); + if (transformValue === 4 || transformValue === 6) { + return transformValue; + } + throw new MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`); + } + }, + fieldsAsRaw: { + type: 'record' + }, + forceServerObjectId: { + default: false, + type: 'boolean' + }, + fsync: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }): WriteConcern { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + fsync: getBoolean(name, value) + } + }); + if (!wc) throw new MongoParseError(`Unable to make a writeConcern from fsync=${value}`); + return wc; + } + } as OptionDescriptor, + heartbeatFrequencyMS: { + default: 10000, + type: 'uint' + }, + ignoreUndefined: { + type: 'boolean' + }, + j: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }): WriteConcern { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) throw new MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + } as OptionDescriptor, + journal: { + target: 'writeConcern', + transform({ name, options, values: [value] }): WriteConcern { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) throw new MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + }, + keepAlive: { + default: true, + type: 'boolean' + }, + keepAliveInitialDelay: { + default: 120000, + type: 'uint' + }, + loadBalanced: { + default: false, + type: 'boolean' + }, + localThresholdMS: { + default: 15, + type: 'uint' + }, + logger: { + default: new Logger('MongoClient'), + transform({ values: [value] }) { + if (value instanceof Logger) { + return value; + } + emitWarning('Alternative loggers might not be supported'); + // TODO: make Logger an interface that others can implement, make usage consistent in driver + // DRIVERS-1204 + } + }, + loggerLevel: { + target: 'logger', + transform({ values: [value] }) { + return new Logger('MongoClient', { loggerLevel: value as LoggerLevel }); + } + }, + maxIdleTimeMS: { + default: 0, + type: 'uint' + }, + maxPoolSize: { + default: 100, + type: 'uint' + }, + maxStalenessSeconds: { + target: 'readPreference', + transform({ name, options, values: [value] }) { + const maxStalenessSeconds = getUint(name, value); + if (options.readPreference) { + return ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, maxStalenessSeconds } + }); + } else { + return new ReadPreference('secondary', undefined, { maxStalenessSeconds }); + } + } + }, + minInternalBufferSize: { + type: 'uint' + }, + minPoolSize: { + default: 0, + type: 'uint' + }, + minHeartbeatFrequencyMS: { + default: 500, + type: 'uint' + }, + monitorCommands: { + default: false, + type: 'boolean' + }, + name: { + target: 'driverInfo', + transform({ values: [value], options }) { + return { ...options.driverInfo, name: String(value) }; + } + } as OptionDescriptor, + noDelay: { + default: true, + type: 'boolean' + }, + pkFactory: { + default: DEFAULT_PK_FACTORY, + transform({ values: [value] }): PkFactory { + if (isRecord(value, ['createPk'] as const) && typeof value.createPk === 'function') { + return value as PkFactory; + } + throw new MongoParseError( + `Option pkFactory must be an object with a createPk function, got ${value}` + ); + } + }, + promiseLibrary: { + deprecated: true, + type: 'any' + }, + promoteBuffers: { + type: 'boolean' + }, + promoteLongs: { + type: 'boolean' + }, + promoteValues: { + type: 'boolean' + }, + raw: { + default: false, + type: 'boolean' + }, + readConcern: { + transform({ values: [value], options }) { + if (value instanceof ReadConcern || isRecord(value, ['level'] as const)) { + return ReadConcern.fromOptions({ ...options.readConcern, ...value } as any); + } + throw new MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`); + } + }, + readConcernLevel: { + target: 'readConcern', + transform({ values: [level], options }) { + return ReadConcern.fromOptions({ + ...options.readConcern, + level: level as ReadConcernLevel + }); + } + }, + readPreference: { + default: ReadPreference.primary, + transform({ values: [value], options }) { + if (value instanceof ReadPreference) { + return ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + } as any); + } + if (isRecord(value, ['mode'] as const)) { + const rp = ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + } as any); + if (rp) return rp; + else throw new MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`); + } + if (typeof value === 'string') { + const rpOpts = { + hedge: options.readPreference?.hedge, + maxStalenessSeconds: options.readPreference?.maxStalenessSeconds + }; + return new ReadPreference( + value as ReadPreferenceMode, + options.readPreference?.tags, + rpOpts + ); + } + } + }, + readPreferenceTags: { + target: 'readPreference', + transform({ values, options }) { + const readPreferenceTags = []; + for (const tag of values) { + const readPreferenceTag: TagSet = Object.create(null); + if (typeof tag === 'string') { + for (const [k, v] of Object.entries(toRecord(tag))) { + readPreferenceTag[k] = v; + } + } + if (isRecord(tag)) { + for (const [k, v] of Object.entries(tag)) { + readPreferenceTag[k] = v; + } + } + readPreferenceTags.push(readPreferenceTag); + } + return ReadPreference.fromOptions({ + readPreference: options.readPreference, + readPreferenceTags + }); + } + }, + replicaSet: { + type: 'string' + }, + retryReads: { + default: true, + type: 'boolean' + }, + retryWrites: { + default: true, + type: 'boolean' + }, + serializeFunctions: { + type: 'boolean' + }, + serverSelectionTimeoutMS: { + default: 30000, + type: 'uint' + }, + servername: { + type: 'string' + }, + socketTimeoutMS: { + default: 0, + type: 'uint' + }, + ssl: { + target: 'tls', + type: 'boolean' + }, + sslCA: { + target: 'ca', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslCRL: { + target: 'crl', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslCert: { + target: 'cert', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslKey: { + target: 'key', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslPass: { + deprecated: true, + target: 'passphrase', + type: 'string' + }, + sslValidate: { + target: 'rejectUnauthorized', + type: 'boolean' + }, + tls: { + type: 'boolean' + }, + tlsAllowInvalidCertificates: { + target: 'rejectUnauthorized', + transform({ name, values: [value] }) { + // allowInvalidCertificates is the inverse of rejectUnauthorized + return !getBoolean(name, value); + } + }, + tlsAllowInvalidHostnames: { + target: 'checkServerIdentity', + transform({ name, values: [value] }) { + // tlsAllowInvalidHostnames means setting the checkServerIdentity function to a noop + return getBoolean(name, value) ? () => undefined : undefined; + } + }, + tlsCAFile: { + target: 'ca', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateFile: { + target: 'cert', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateKeyFile: { + target: 'key', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateKeyFilePassword: { + target: 'passphrase', + type: 'any' + }, + tlsInsecure: { + transform({ name, options, values: [value] }) { + const tlsInsecure = getBoolean(name, value); + if (tlsInsecure) { + options.checkServerIdentity = () => undefined; + options.rejectUnauthorized = false; + } else { + options.checkServerIdentity = options.tlsAllowInvalidHostnames + ? () => undefined + : undefined; + options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true; + } + return tlsInsecure; + } + }, + w: { + target: 'writeConcern', + transform({ values: [value], options }) { + return WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value as W } }); + } + }, + waitQueueTimeoutMS: { + default: 0, + type: 'uint' + }, + writeConcern: { + target: 'writeConcern', + transform({ values: [value], options }) { + if (isRecord(value) || value instanceof WriteConcern) { + return WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + ...value + } + }); + } else if (value === 'majority' || typeof value === 'number') { + return WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + w: value + } + }); + } + + throw new MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`); + } + } as OptionDescriptor, + wtimeout: { + deprecated: 'Please use wtimeoutMS instead', + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeout: getUint('wtimeout', value) + } + }); + if (wc) return wc; + throw new MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + } as OptionDescriptor, + wtimeoutMS: { + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeoutMS: getUint('wtimeoutMS', value) + } + }); + if (wc) return wc; + throw new MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + }, + zlibCompressionLevel: { + default: 0, + type: 'int' + }, + // Custom types for modifying core behavior + connectionType: { type: 'any' }, + srvPoller: { type: 'any' }, + // Accepted NodeJS Options + minDHSize: { type: 'any' }, + pskCallback: { type: 'any' }, + secureContext: { type: 'any' }, + enableTrace: { type: 'any' }, + requestCert: { type: 'any' }, + rejectUnauthorized: { type: 'any' }, + checkServerIdentity: { type: 'any' }, + ALPNProtocols: { type: 'any' }, + SNICallback: { type: 'any' }, + session: { type: 'any' }, + requestOCSP: { type: 'any' }, + localAddress: { type: 'any' }, + localPort: { type: 'any' }, + hints: { type: 'any' }, + lookup: { type: 'any' }, + ca: { type: 'any' }, + cert: { type: 'any' }, + ciphers: { type: 'any' }, + crl: { type: 'any' }, + ecdhCurve: { type: 'any' }, + key: { type: 'any' }, + passphrase: { type: 'any' }, + pfx: { type: 'any' }, + secureProtocol: { type: 'any' }, + index: { type: 'any' }, + // Legacy Options, these are unused but left here to avoid errors with CSFLE lib + useNewUrlParser: { type: 'boolean' } as OptionDescriptor, + useUnifiedTopology: { type: 'boolean' } as OptionDescriptor +} as Record; + +export const DEFAULT_OPTIONS = new CaseInsensitiveMap( + Object.entries(OPTIONS) + .filter(([, descriptor]) => descriptor.default != null) + .map(([k, d]) => [k, d.default]) +); diff --git a/node_modules/mongodb/src/constants.ts b/node_modules/mongodb/src/constants.ts new file mode 100644 index 0000000..4a6b538 --- /dev/null +++ b/node_modules/mongodb/src/constants.ts @@ -0,0 +1,6 @@ +export const SYSTEM_NAMESPACE_COLLECTION = 'system.namespaces'; +export const SYSTEM_INDEX_COLLECTION = 'system.indexes'; +export const SYSTEM_PROFILE_COLLECTION = 'system.profile'; +export const SYSTEM_USER_COLLECTION = 'system.users'; +export const SYSTEM_COMMAND_COLLECTION = '$cmd'; +export const SYSTEM_JS_COLLECTION = 'system.js'; diff --git a/node_modules/mongodb/src/cursor/abstract_cursor.ts b/node_modules/mongodb/src/cursor/abstract_cursor.ts new file mode 100644 index 0000000..b4be34b --- /dev/null +++ b/node_modules/mongodb/src/cursor/abstract_cursor.ts @@ -0,0 +1,889 @@ +import { Callback, maybePromise, MongoDBNamespace, ns } from '../utils'; +import { Long, Document, BSONSerializeOptions, pluckBSONSerializeOptions } from '../bson'; +import { ClientSession, maybeClearPinnedConnection } from '../sessions'; +import { + AnyError, + MongoRuntimeError, + MongoNetworkError, + MongoInvalidArgumentError, + MongoCursorExhaustedError, + MongoTailableCursorError, + MongoCursorInUseError +} from '../error'; +import { ReadPreference, ReadPreferenceLike } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { Topology } from '../sdam/topology'; +import { Readable, Transform } from 'stream'; +import type { ExecutionResult } from '../operations/execute_operation'; +import { ReadConcern, ReadConcernLike } from '../read_concern'; +import { TODO_NODE_3286, TypedEventEmitter } from '../mongo_types'; + +/** @internal */ +const kId = Symbol('id'); +/** @internal */ +const kDocuments = Symbol('documents'); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kNamespace = Symbol('namespace'); +/** @internal */ +const kTopology = Symbol('topology'); +/** @internal */ +const kSession = Symbol('session'); +/** @internal */ +const kOptions = Symbol('options'); +/** @internal */ +const kTransform = Symbol('transform'); +/** @internal */ +const kInitialized = Symbol('initialized'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kKilled = Symbol('killed'); + +/** @public */ +export const CURSOR_FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +] as const; + +/** @public + * @deprecated This interface is deprecated */ +export interface CursorCloseOptions { + /** Bypass calling killCursors when closing the cursor. */ + /** @deprecated the skipKillCursors option is deprecated */ + skipKillCursors?: boolean; +} + +/** @public */ +export interface CursorStreamOptions { + /** A transformation method applied to each document emitted by the stream */ + transform?(doc: Document): Document; +} + +/** @public */ +export type CursorFlag = typeof CURSOR_FLAGS[number]; + +/** @public */ +export interface AbstractCursorOptions extends BSONSerializeOptions { + session?: ClientSession; + readPreference?: ReadPreferenceLike; + readConcern?: ReadConcernLike; + batchSize?: number; + maxTimeMS?: number; + comment?: Document | string; + tailable?: boolean; + awaitData?: boolean; + noCursorTimeout?: boolean; +} + +/** @internal */ +export type InternalAbstractCursorOptions = Omit & { + // resolved + readPreference: ReadPreference; + readConcern?: ReadConcern; + + // cursor flags, some are deprecated + oplogReplay?: boolean; + exhaust?: boolean; + partial?: boolean; +}; + +/** @public */ +export type AbstractCursorEvents = { + [AbstractCursor.CLOSE](): void; +}; + +/** @public */ +export abstract class AbstractCursor< + TSchema = any, + CursorEvents extends AbstractCursorEvents = AbstractCursorEvents +> extends TypedEventEmitter { + /** @internal */ + [kId]?: Long; + /** @internal */ + [kSession]?: ClientSession; + /** @internal */ + [kServer]?: Server; + /** @internal */ + [kNamespace]: MongoDBNamespace; + /** @internal */ + [kDocuments]: TSchema[]; + /** @internal */ + [kTopology]: Topology; + /** @internal */ + [kTransform]?: (doc: TSchema) => Document; + /** @internal */ + [kInitialized]: boolean; + /** @internal */ + [kClosed]: boolean; + /** @internal */ + [kKilled]: boolean; + /** @internal */ + [kOptions]: InternalAbstractCursorOptions; + + /** @event */ + static readonly CLOSE = 'close' as const; + + /** @internal */ + constructor( + topology: Topology, + namespace: MongoDBNamespace, + options: AbstractCursorOptions = {} + ) { + super(); + + this[kTopology] = topology; + this[kNamespace] = namespace; + this[kDocuments] = []; // TODO: https://github.com/microsoft/TypeScript/issues/36230 + this[kInitialized] = false; + this[kClosed] = false; + this[kKilled] = false; + this[kOptions] = { + readPreference: + options.readPreference && options.readPreference instanceof ReadPreference + ? options.readPreference + : ReadPreference.primary, + ...pluckBSONSerializeOptions(options) + }; + + const readConcern = ReadConcern.fromOptions(options); + if (readConcern) { + this[kOptions].readConcern = readConcern; + } + + if (typeof options.batchSize === 'number') { + this[kOptions].batchSize = options.batchSize; + } + + if (options.comment != null) { + this[kOptions].comment = options.comment; + } + + if (typeof options.maxTimeMS === 'number') { + this[kOptions].maxTimeMS = options.maxTimeMS; + } + + if (options.session instanceof ClientSession) { + this[kSession] = options.session; + } + } + + get id(): Long | undefined { + return this[kId]; + } + + /** @internal */ + get topology(): Topology { + return this[kTopology]; + } + + /** @internal */ + get server(): Server | undefined { + return this[kServer]; + } + + get namespace(): MongoDBNamespace { + return this[kNamespace]; + } + + get readPreference(): ReadPreference { + return this[kOptions].readPreference; + } + + get readConcern(): ReadConcern | undefined { + return this[kOptions].readConcern; + } + + /** @internal */ + get session(): ClientSession | undefined { + return this[kSession]; + } + + set session(clientSession: ClientSession | undefined) { + this[kSession] = clientSession; + } + + /** @internal */ + get cursorOptions(): InternalAbstractCursorOptions { + return this[kOptions]; + } + + get closed(): boolean { + return this[kClosed]; + } + + get killed(): boolean { + return this[kKilled]; + } + + get loadBalanced(): boolean { + return this[kTopology].loadBalanced; + } + + /** Returns current buffered documents length */ + bufferedCount(): number { + return this[kDocuments].length; + } + + /** Returns current buffered documents */ + readBufferedDocuments(number?: number): TSchema[] { + return this[kDocuments].splice(0, number ?? this[kDocuments].length); + } + + [Symbol.asyncIterator](): AsyncIterator { + return { + next: () => + this.next().then(value => + value != null ? { value, done: false } : { value: undefined, done: true } + ) + }; + } + + stream(options?: CursorStreamOptions): Readable { + if (options?.transform) { + const transform = options.transform; + const readable = makeCursorStream(this); + + return readable.pipe( + new Transform({ + objectMode: true, + highWaterMark: 1, + transform(chunk, _, callback) { + try { + const transformed = transform(chunk); + callback(undefined, transformed); + } catch (err) { + callback(err); + } + } + }) + ); + } + + return makeCursorStream(this); + } + + hasNext(): Promise; + hasNext(callback: Callback): void; + hasNext(callback?: Callback): Promise | void { + return maybePromise(callback, done => { + if (this[kId] === Long.ZERO) { + return done(undefined, false); + } + + if (this[kDocuments].length) { + return done(undefined, true); + } + + next(this, true, (err, doc) => { + if (err) return done(err); + + if (doc) { + this[kDocuments].unshift(doc); + done(undefined, true); + return; + } + + done(undefined, false); + }); + }); + } + + /** Get the next available document from the cursor, returns null if no more documents are available. */ + next(): Promise; + next(callback: Callback): void; + next(callback?: Callback): Promise | void; + next(callback?: Callback): Promise | void { + return maybePromise(callback, done => { + if (this[kId] === Long.ZERO) { + return done(new MongoCursorExhaustedError()); + } + + next(this, true, done); + }); + } + + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + tryNext(callback: Callback): void; + tryNext(callback?: Callback): Promise | void { + return maybePromise(callback, done => { + if (this[kId] === Long.ZERO) { + return done(new MongoCursorExhaustedError()); + } + + next(this, false, done); + }); + } + + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * @param iterator - The iteration callback. + * @param callback - The end callback. + */ + forEach(iterator: (doc: TSchema) => boolean | void): Promise; + forEach(iterator: (doc: TSchema) => boolean | void, callback: Callback): void; + forEach( + iterator: (doc: TSchema) => boolean | void, + callback?: Callback + ): Promise | void { + if (typeof iterator !== 'function') { + throw new MongoInvalidArgumentError('Argument "iterator" must be a function'); + } + return maybePromise(callback, done => { + const transform = this[kTransform]; + const fetchDocs = () => { + next(this, true, (err, doc) => { + if (err || doc == null) return done(err); + let result; + // NOTE: no need to transform because `next` will do this automatically + try { + result = iterator(doc); // TODO(NODE-3283): Improve transform typing + } catch (error) { + return done(error); + } + + if (result === false) return done(); + + // these do need to be transformed since they are copying the rest of the batch + const internalDocs = this[kDocuments].splice(0, this[kDocuments].length); + for (let i = 0; i < internalDocs.length; ++i) { + try { + result = iterator( + (transform ? transform(internalDocs[i]) : internalDocs[i]) as TSchema // TODO(NODE-3283): Improve transform typing + ); + } catch (error) { + return done(error); + } + if (result === false) return done(); + } + + fetchDocs(); + }); + }; + + fetchDocs(); + }); + } + + close(): void; + close(callback: Callback): void; + /** + * @deprecated options argument is deprecated + */ + close(options: CursorCloseOptions): Promise; + /** + * @deprecated options argument is deprecated + */ + close(options: CursorCloseOptions, callback: Callback): void; + close(options?: CursorCloseOptions | Callback, callback?: Callback): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + const needsToEmitClosed = !this[kClosed]; + this[kClosed] = true; + + return maybePromise(callback, done => cleanupCursor(this, { needsToEmitClosed }, done)); + } + + /** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * + * @param callback - The result callback. + */ + toArray(): Promise; + toArray(callback: Callback): void; + toArray(callback?: Callback): Promise | void { + return maybePromise(callback, done => { + const docs: TSchema[] = []; + const transform = this[kTransform]; + const fetchDocs = () => { + // NOTE: if we add a `nextBatch` then we should use it here + next(this, true, (err, doc) => { + if (err) return done(err); + if (doc == null) return done(undefined, docs); + + // NOTE: no need to transform because `next` will do this automatically + docs.push(doc); + + // these do need to be transformed since they are copying the rest of the batch + const internalDocs = ( + transform + ? this[kDocuments].splice(0, this[kDocuments].length).map(transform) + : this[kDocuments].splice(0, this[kDocuments].length) + ) as TSchema[]; // TODO(NODE-3283): Improve transform typing + + if (internalDocs) { + docs.push(...internalDocs); + } + + fetchDocs(); + }); + }; + + fetchDocs(); + }); + } + + /** + * Add a cursor flag to the cursor + * + * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. + * @param value - The flag boolean value. + */ + addCursorFlag(flag: CursorFlag, value: boolean): this { + assertUninitialized(this); + if (!CURSOR_FLAGS.includes(flag)) { + throw new MongoInvalidArgumentError(`Flag ${flag} is not one of ${CURSOR_FLAGS}`); + } + + if (typeof value !== 'boolean') { + throw new MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`); + } + + this[kOptions][flag] = value; + return this; + } + + /** + * Map all documents using the provided function + * If there is a transform set on the cursor, that will be called first and the result passed to + * this function's transform. + * + * @remarks + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling map, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor = coll.find(); + * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); + * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] + * ``` + * @param transform - The mapping transformation method. + */ + map(transform: (doc: TSchema) => T): AbstractCursor { + assertUninitialized(this); + const oldTransform = this[kTransform] as (doc: TSchema) => TSchema; // TODO(NODE-3283): Improve transform typing + if (oldTransform) { + this[kTransform] = doc => { + return transform(oldTransform(doc)); + }; + } else { + this[kTransform] = transform; + } + + return this as unknown as AbstractCursor; + } + + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadPreference(readPreference: ReadPreferenceLike): this { + assertUninitialized(this); + if (readPreference instanceof ReadPreference) { + this[kOptions].readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this[kOptions].readPreference = ReadPreference.fromString(readPreference); + } else { + throw new MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`); + } + + return this; + } + + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadConcern(readConcern: ReadConcernLike): this { + assertUninitialized(this); + const resolvedReadConcern = ReadConcern.fromOptions({ readConcern }); + if (resolvedReadConcern) { + this[kOptions].readConcern = resolvedReadConcern; + } + + return this; + } + + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + + this[kOptions].maxTimeMS = value; + return this; + } + + /** + * Set the batch size for the cursor. + * + * @param value - The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + */ + batchSize(value: number): this { + assertUninitialized(this); + if (this[kOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support batchSize'); + } + + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Operation "batchSize" requires an integer'); + } + + this[kOptions].batchSize = value; + return this; + } + + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind(): void { + if (!this[kInitialized]) { + return; + } + + this[kId] = undefined; + this[kDocuments] = []; + this[kClosed] = false; + this[kKilled] = false; + this[kInitialized] = false; + + const session = this[kSession]; + if (session) { + // We only want to end this session if we created it, and it hasn't ended yet + if (session.explicit === false && !session.hasEnded) { + session.endSession(); + } + + this[kSession] = undefined; + } + } + + /** + * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance + */ + abstract clone(): AbstractCursor; + + /** @internal */ + abstract _initialize( + session: ClientSession | undefined, + callback: Callback + ): void; + + /** @internal */ + _getMore(batchSize: number, callback: Callback): void { + const cursorId = this[kId]; + const cursorNs = this[kNamespace]; + const server = this[kServer]; + + if (cursorId == null) { + callback(new MongoRuntimeError('Unable to iterate cursor with no id')); + return; + } + + if (server == null) { + callback(new MongoRuntimeError('Unable to iterate cursor without selected server')); + return; + } + + server.getMore( + cursorNs, + cursorId, + { + ...this[kOptions], + session: this[kSession], + batchSize + }, + callback + ); + } +} + +function nextDocument(cursor: AbstractCursor): T | null | undefined { + if (cursor[kDocuments] == null || !cursor[kDocuments].length) { + return null; + } + + const doc = cursor[kDocuments].shift(); + if (doc) { + const transform = cursor[kTransform]; + if (transform) { + return transform(doc) as T; + } + + return doc; + } + + return null; +} + +function next(cursor: AbstractCursor, blocking: boolean, callback: Callback): void { + const cursorId = cursor[kId]; + if (cursor.closed) { + return callback(undefined, null); + } + + if (cursor[kDocuments] && cursor[kDocuments].length) { + callback(undefined, nextDocument(cursor)); + return; + } + + if (cursorId == null) { + // All cursors must operate within a session, one must be made implicitly if not explicitly provided + if (cursor[kSession] == null && cursor[kTopology].hasSessionSupport()) { + cursor[kSession] = cursor[kTopology].startSession({ owner: cursor, explicit: false }); + } + + cursor._initialize(cursor[kSession], (err, state) => { + if (state) { + const response = state.response; + cursor[kServer] = state.server; + cursor[kSession] = state.session; + + if (response.cursor) { + cursor[kId] = + typeof response.cursor.id === 'number' + ? Long.fromNumber(response.cursor.id) + : response.cursor.id; + + if (response.cursor.ns) { + cursor[kNamespace] = ns(response.cursor.ns); + } + + cursor[kDocuments] = response.cursor.firstBatch; + } else { + // NOTE: This is for support of older servers (<3.2) which do not use commands + cursor[kId] = + typeof response.cursorId === 'number' + ? Long.fromNumber(response.cursorId) + : response.cursorId; + cursor[kDocuments] = response.documents; + } + + // When server responses return without a cursor document, we close this cursor + // and return the raw server response. This is often the case for explain commands + // for example + if (cursor[kId] == null) { + cursor[kId] = Long.ZERO; + // TODO(NODE-3286): ExecutionResult needs to accept a generic parameter + cursor[kDocuments] = [state.response as TODO_NODE_3286]; + } + } + + // the cursor is now initialized, even if an error occurred or it is dead + cursor[kInitialized] = true; + + if (err || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error: err }, () => callback(err, nextDocument(cursor))); + } + + next(cursor, blocking, callback); + }); + + return; + } + + if (cursorIsDead(cursor)) { + return cleanupCursor(cursor, undefined, () => callback(undefined, null)); + } + + // otherwise need to call getMore + const batchSize = cursor[kOptions].batchSize || 1000; + cursor._getMore(batchSize, (err, response) => { + if (response) { + const cursorId = + typeof response.cursor.id === 'number' + ? Long.fromNumber(response.cursor.id) + : response.cursor.id; + + cursor[kDocuments] = response.cursor.nextBatch; + cursor[kId] = cursorId; + } + + if (err || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error: err }, () => callback(err, nextDocument(cursor))); + } + + if (cursor[kDocuments].length === 0 && blocking === false) { + return callback(undefined, null); + } + + next(cursor, blocking, callback); + }); +} + +function cursorIsDead(cursor: AbstractCursor): boolean { + const cursorId = cursor[kId]; + return !!cursorId && cursorId.isZero(); +} + +function cleanupCursor( + cursor: AbstractCursor, + options: { error?: AnyError | undefined; needsToEmitClosed?: boolean } | undefined, + callback: Callback +): void { + const cursorId = cursor[kId]; + const cursorNs = cursor[kNamespace]; + const server = cursor[kServer]; + const session = cursor[kSession]; + const error = options?.error; + const needsToEmitClosed = options?.needsToEmitClosed ?? cursor[kDocuments].length === 0; + + if (error) { + if (cursor.loadBalanced && error instanceof MongoNetworkError) { + return completeCleanup(); + } + } + + if (cursorId == null || server == null || cursorId.isZero() || cursorNs == null) { + if (needsToEmitClosed) { + cursor[kClosed] = true; + cursor[kId] = Long.ZERO; + cursor.emit(AbstractCursor.CLOSE); + } + + if (session) { + if (session.owner === cursor) { + return session.endSession({ error }, callback); + } + + if (!session.inTransaction()) { + maybeClearPinnedConnection(session, { error }); + } + } + + return callback(); + } + + function completeCleanup() { + if (session) { + if (session.owner === cursor) { + return session.endSession({ error }, () => { + cursor.emit(AbstractCursor.CLOSE); + callback(); + }); + } + + if (!session.inTransaction()) { + maybeClearPinnedConnection(session, { error }); + } + } + + cursor.emit(AbstractCursor.CLOSE); + return callback(); + } + + cursor[kKilled] = true; + server.killCursors( + cursorNs, + [cursorId], + { ...pluckBSONSerializeOptions(cursor[kOptions]), session }, + () => completeCleanup() + ); +} + +/** @internal */ +export function assertUninitialized(cursor: AbstractCursor): void { + if (cursor[kInitialized]) { + throw new MongoCursorInUseError(); + } +} + +function makeCursorStream(cursor: AbstractCursor) { + const readable = new Readable({ + objectMode: true, + autoDestroy: false, + highWaterMark: 1 + }); + + let initialized = false; + let reading = false; + let needToClose = true; // NOTE: we must close the cursor if we never read from it, use `_construct` in future node versions + + readable._read = function () { + if (initialized === false) { + needToClose = false; + initialized = true; + } + + if (!reading) { + reading = true; + readNext(); + } + }; + + readable._destroy = function (error, cb) { + if (needToClose) { + cursor.close(err => process.nextTick(cb, err || error)); + } else { + cb(error); + } + }; + + function readNext() { + needToClose = false; + next(cursor, true, (err, result) => { + needToClose = err ? !cursor.closed : result != null; + + if (err) { + // NOTE: This is questionable, but we have a test backing the behavior. It seems the + // desired behavior is that a stream ends cleanly when a user explicitly closes + // a client during iteration. Alternatively, we could do the "right" thing and + // propagate the error message by removing this special case. + if (err.message.match(/server is closed/)) { + cursor.close(); + return readable.push(null); + } + + // NOTE: This is also perhaps questionable. The rationale here is that these errors tend + // to be "operation interrupted", where a cursor has been closed but there is an + // active getMore in-flight. This used to check if the cursor was killed but once + // that changed to happen in cleanup legitimate errors would not destroy the + // stream. There are change streams test specifically test these cases. + if (err.message.match(/interrupted/)) { + return readable.push(null); + } + + return readable.destroy(err); + } + + if (result == null) { + readable.push(null); + } else if (readable.destroyed) { + cursor.close(); + } else { + if (readable.push(result)) { + return readNext(); + } + + reading = false; + } + }); + } + + return readable; +} diff --git a/node_modules/mongodb/src/cursor/aggregation_cursor.ts b/node_modules/mongodb/src/cursor/aggregation_cursor.ts new file mode 100644 index 0000000..ffe658e --- /dev/null +++ b/node_modules/mongodb/src/cursor/aggregation_cursor.ts @@ -0,0 +1,219 @@ +import { AggregateOperation, AggregateOptions } from '../operations/aggregate'; +import { AbstractCursor, assertUninitialized } from './abstract_cursor'; +import { executeOperation, ExecutionResult } from '../operations/execute_operation'; +import { mergeOptions } from '../utils'; +import type { Document } from '../bson'; +import type { Sort } from '../sort'; +import type { Topology } from '../sdam/topology'; +import type { Callback, MongoDBNamespace } from '../utils'; +import type { ClientSession } from '../sessions'; +import type { AbstractCursorOptions } from './abstract_cursor'; +import type { ExplainVerbosityLike } from '../explain'; + +/** @public */ +export interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions {} + +/** @internal */ +const kPipeline = Symbol('pipeline'); +/** @internal */ +const kOptions = Symbol('options'); + +/** + * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * @public + */ +export class AggregationCursor extends AbstractCursor { + /** @internal */ + [kPipeline]: Document[]; + /** @internal */ + [kOptions]: AggregateOptions; + + /** @internal */ + constructor( + topology: Topology, + namespace: MongoDBNamespace, + pipeline: Document[] = [], + options: AggregateOptions = {} + ) { + super(topology, namespace, options); + + this[kPipeline] = pipeline; + this[kOptions] = options; + } + + get pipeline(): Document[] { + return this[kPipeline]; + } + + clone(): AggregationCursor { + const clonedOptions = mergeOptions({}, this[kOptions]); + delete clonedOptions.session; + return new AggregationCursor(this.topology, this.namespace, this[kPipeline], { + ...clonedOptions + }); + } + + map(transform: (doc: TSchema) => T): AggregationCursor { + return super.map(transform) as AggregationCursor; + } + + /** @internal */ + _initialize(session: ClientSession | undefined, callback: Callback): void { + const aggregateOperation = new AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + session + }); + + executeOperation(this.topology, aggregateOperation, (err, response) => { + if (err || response == null) return callback(err); + + // TODO: NODE-2882 + callback(undefined, { server: aggregateOperation.server, session, response }); + }); + } + + /** Execute the explain for the cursor */ + explain(): Promise; + explain(callback: Callback): void; + explain(verbosity: ExplainVerbosityLike): Promise; + explain( + verbosity?: ExplainVerbosityLike | Callback, + callback?: Callback + ): Promise | void { + if (typeof verbosity === 'function') (callback = verbosity), (verbosity = true); + if (verbosity == null) verbosity = true; + + return executeOperation( + this.topology, + new AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + explain: verbosity + }), + callback + ); + } + + /** Add a group stage to the aggregation pipeline */ + group($group: Document): AggregationCursor; + group($group: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $group }); + return this; + } + + /** Add a limit stage to the aggregation pipeline */ + limit($limit: number): this { + assertUninitialized(this); + this[kPipeline].push({ $limit }); + return this; + } + + /** Add a match stage to the aggregation pipeline */ + match($match: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $match }); + return this; + } + + /** Add an out stage to the aggregation pipeline */ + out($out: { db: string; coll: string } | string): this { + assertUninitialized(this); + this[kPipeline].push({ $out }); + return this; + } + + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.aggregate().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project($project: Document): AggregationCursor { + assertUninitialized(this); + this[kPipeline].push({ $project }); + return this as unknown as AggregationCursor; + } + + /** Add a lookup stage to the aggregation pipeline */ + lookup($lookup: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $lookup }); + return this; + } + + /** Add a redact stage to the aggregation pipeline */ + redact($redact: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $redact }); + return this; + } + + /** Add a skip stage to the aggregation pipeline */ + skip($skip: number): this { + assertUninitialized(this); + this[kPipeline].push({ $skip }); + return this; + } + + /** Add a sort stage to the aggregation pipeline */ + sort($sort: Sort): this { + assertUninitialized(this); + this[kPipeline].push({ $sort }); + return this; + } + + /** Add a unwind stage to the aggregation pipeline */ + unwind($unwind: Document | string): this { + assertUninitialized(this); + this[kPipeline].push({ $unwind }); + return this; + } + + // deprecated methods + /** @deprecated Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $geoNear }); + return this; + } +} diff --git a/node_modules/mongodb/src/cursor/find_cursor.ts b/node_modules/mongodb/src/cursor/find_cursor.ts new file mode 100644 index 0000000..2c9a04d --- /dev/null +++ b/node_modules/mongodb/src/cursor/find_cursor.ts @@ -0,0 +1,464 @@ +import type { Document } from '../bson'; +import { MongoInvalidArgumentError, MongoTailableCursorError } from '../error'; +import type { ExplainVerbosityLike } from '../explain'; +import { CountOperation, CountOptions } from '../operations/count'; +import { executeOperation, ExecutionResult } from '../operations/execute_operation'; +import { FindOperation, FindOptions } from '../operations/find'; +import { mergeOptions } from '../utils'; +import type { Hint } from '../operations/operation'; +import type { CollationOptions } from '../operations/command'; +import type { Topology } from '../sdam/topology'; +import type { ClientSession } from '../sessions'; +import { formatSort, Sort, SortDirection } from '../sort'; +import type { Callback, MongoDBNamespace } from '../utils'; +import { AbstractCursor, assertUninitialized } from './abstract_cursor'; + +/** @internal */ +const kFilter = Symbol('filter'); +/** @internal */ +const kNumReturned = Symbol('numReturned'); +/** @internal */ +const kBuiltOptions = Symbol('builtOptions'); + +/** @public Flags allowed for cursor */ +export const FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +] as const; + +/** @public */ +export class FindCursor extends AbstractCursor { + /** @internal */ + [kFilter]: Document; + /** @internal */ + [kNumReturned]?: number; + /** @internal */ + [kBuiltOptions]: FindOptions; + + /** @internal */ + constructor( + topology: Topology, + namespace: MongoDBNamespace, + filter: Document | undefined, + options: FindOptions = {} + ) { + super(topology, namespace, options); + + this[kFilter] = filter || {}; + this[kBuiltOptions] = options; + + if (options.sort != null) { + this[kBuiltOptions].sort = formatSort(options.sort); + } + } + + clone(): FindCursor { + const clonedOptions = mergeOptions({}, this[kBuiltOptions]); + delete clonedOptions.session; + return new FindCursor(this.topology, this.namespace, this[kFilter], { + ...clonedOptions + }); + } + + map(transform: (doc: TSchema) => T): FindCursor { + return super.map(transform) as FindCursor; + } + + /** @internal */ + _initialize(session: ClientSession | undefined, callback: Callback): void { + const findOperation = new FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + session + }); + + executeOperation(this.topology, findOperation, (err, response) => { + if (err || response == null) return callback(err); + + // TODO: We only need this for legacy queries that do not support `limit`, maybe + // the value should only be saved in those cases. + if (response.cursor) { + this[kNumReturned] = response.cursor.firstBatch.length; + } else { + this[kNumReturned] = response.documents ? response.documents.length : 0; + } + + // TODO: NODE-2882 + callback(undefined, { server: findOperation.server, session, response }); + }); + } + + /** @internal */ + _getMore(batchSize: number, callback: Callback): void { + // NOTE: this is to support client provided limits in pre-command servers + const numReturned = this[kNumReturned]; + if (numReturned) { + const limit = this[kBuiltOptions].limit; + batchSize = + limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize; + + if (batchSize <= 0) { + return this.close(callback); + } + } + + super._getMore(batchSize, (err, response) => { + if (err) return callback(err); + + // TODO: wrap this in some logic to prevent it from happening if we don't need this support + if (response) { + this[kNumReturned] = this[kNumReturned] + response.cursor.nextBatch.length; + } + + callback(undefined, response); + }); + } + + /** Get the count of documents for this cursor */ + count(): Promise; + count(callback: Callback): void; + count(options: CountOptions): Promise; + count(options: CountOptions, callback: Callback): void; + count( + options?: CountOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'boolean') { + throw new MongoInvalidArgumentError('Invalid first parameter to count'); + } + + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return executeOperation( + this.topology, + new CountOperation(this.namespace, this[kFilter], { + ...this[kBuiltOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + ...options + }), + callback + ); + } + + /** Execute the explain for the cursor */ + explain(): Promise; + explain(callback: Callback): void; + explain(verbosity?: ExplainVerbosityLike): Promise; + explain( + verbosity?: ExplainVerbosityLike | Callback, + callback?: Callback + ): Promise | void { + if (typeof verbosity === 'function') (callback = verbosity), (verbosity = true); + if (verbosity == null) verbosity = true; + + return executeOperation( + this.topology, + new FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + explain: verbosity + }), + callback + ); + } + + /** Set the cursor query */ + filter(filter: Document): this { + assertUninitialized(this); + this[kFilter] = filter; + return this; + } + + /** + * Set the cursor hint + * + * @param hint - If specified, then the query system will only consider plans using the hinted index. + */ + hint(hint: Hint): this { + assertUninitialized(this); + this[kBuiltOptions].hint = hint; + return this; + } + + /** + * Set the cursor min + * + * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + */ + min(min: Document): this { + assertUninitialized(this); + this[kBuiltOptions].min = min; + return this; + } + + /** + * Set the cursor max + * + * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + */ + max(max: Document): this { + assertUninitialized(this); + this[kBuiltOptions].max = max; + return this; + } + + /** + * Set the cursor returnKey. + * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. + * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * + * @param value - the returnKey value. + */ + returnKey(value: boolean): this { + assertUninitialized(this); + this[kBuiltOptions].returnKey = value; + return this; + } + + /** + * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. + * + * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + */ + showRecordId(value: boolean): this { + assertUninitialized(this); + this[kBuiltOptions].showRecordId = value; + return this; + } + + /** + * Add a query modifier to the cursor query + * + * @param name - The query modifier (must start with $, such as $orderby etc) + * @param value - The modifier value. + */ + addQueryModifier(name: string, value: string | boolean | number | Document): this { + assertUninitialized(this); + if (name[0] !== '$') { + throw new MongoInvalidArgumentError(`${name} is not a valid query modifier`); + } + + // Strip of the $ + const field = name.substr(1); + + // NOTE: consider some TS magic for this + switch (field) { + case 'comment': + this[kBuiltOptions].comment = value as string | Document; + break; + + case 'explain': + this[kBuiltOptions].explain = value as boolean; + break; + + case 'hint': + this[kBuiltOptions].hint = value as string | Document; + break; + + case 'max': + this[kBuiltOptions].max = value as Document; + break; + + case 'maxTimeMS': + this[kBuiltOptions].maxTimeMS = value as number; + break; + + case 'min': + this[kBuiltOptions].min = value as Document; + break; + + case 'orderby': + this[kBuiltOptions].sort = formatSort(value as string | Document); + break; + + case 'query': + this[kFilter] = value as Document; + break; + + case 'returnKey': + this[kBuiltOptions].returnKey = value as boolean; + break; + + case 'showDiskLoc': + this[kBuiltOptions].showRecordId = value as boolean; + break; + + default: + throw new MongoInvalidArgumentError(`Invalid query modifier: ${name}`); + } + + return this; + } + + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * + * @param value - The comment attached to this query. + */ + comment(value: string): this { + assertUninitialized(this); + this[kBuiltOptions].comment = value; + return this; + } + + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * + * @param value - Number of milliseconds to wait before aborting the tailed query. + */ + maxAwaitTimeMS(value: number): this { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Argument for maxAwaitTimeMS must be a number'); + } + + this[kBuiltOptions].maxAwaitTimeMS = value; + return this; + } + + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + + this[kBuiltOptions].maxTimeMS = value; + return this; + } + + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic + * {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: FindCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.find().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project(value: Document): FindCursor { + assertUninitialized(this); + this[kBuiltOptions].projection = value; + return this as unknown as FindCursor; + } + + /** + * Sets the sort order of the cursor query. + * + * @param sort - The key or keys set for the sort. + * @param direction - The direction of the sorting (1 or -1). + */ + sort(sort: Sort | string, direction?: SortDirection): this { + assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support sorting'); + } + + this[kBuiltOptions].sort = formatSort(sort, direction); + return this; + } + + /** + * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) + * + * @remarks + * {@link https://docs.mongodb.com/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} + */ + allowDiskUse(): this { + assertUninitialized(this); + if (!this[kBuiltOptions].sort) { + throw new MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification'); + } + this[kBuiltOptions].allowDiskUse = true; + return this; + } + + /** + * Set the collation options for the cursor. + * + * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + */ + collation(value: CollationOptions): this { + assertUninitialized(this); + this[kBuiltOptions].collation = value; + return this; + } + + /** + * Set the limit for the cursor. + * + * @param value - The limit for the cursor query. + */ + limit(value: number): this { + assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support limit'); + } + + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Operation "limit" requires an integer'); + } + + this[kBuiltOptions].limit = value; + return this; + } + + /** + * Set the skip for the cursor. + * + * @param value - The skip for the cursor query. + */ + skip(value: number): this { + assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support skip'); + } + + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Operation "skip" requires an integer'); + } + + this[kBuiltOptions].skip = value; + return this; + } +} diff --git a/node_modules/mongodb/src/db.ts b/node_modules/mongodb/src/db.ts new file mode 100644 index 0000000..2629cff --- /dev/null +++ b/node_modules/mongodb/src/db.ts @@ -0,0 +1,756 @@ +import { + Callback, + resolveOptions, + filterOptions, + MongoDBNamespace, + getTopology, + DEFAULT_PK_FACTORY +} from './utils'; +import { AggregationCursor } from './cursor/aggregation_cursor'; +import { Document, BSONSerializeOptions, resolveBSONOptions } from './bson'; +import { ReadPreference, ReadPreferenceLike } from './read_preference'; +import { MongoAPIError, MongoInvalidArgumentError } from './error'; +import { Collection, CollectionOptions } from './collection'; +import { ChangeStream, ChangeStreamOptions } from './change_stream'; +import * as CONSTANTS from './constants'; +import { WriteConcern, WriteConcernOptions } from './write_concern'; +import { ReadConcern } from './read_concern'; +import { Logger, LoggerOptions } from './logger'; +import type { AggregateOptions } from './operations/aggregate'; +import { AddUserOperation, AddUserOptions } from './operations/add_user'; +import { CollectionsOperation } from './operations/collections'; +import { DbStatsOperation, DbStatsOptions } from './operations/stats'; +import { RunCommandOperation, RunCommandOptions } from './operations/run_command'; +import { CreateCollectionOperation, CreateCollectionOptions } from './operations/create_collection'; +import { + CreateIndexOperation, + IndexInformationOperation, + CreateIndexesOptions, + IndexSpecification +} from './operations/indexes'; +import { + DropCollectionOperation, + DropDatabaseOperation, + DropDatabaseOptions, + DropCollectionOptions +} from './operations/drop'; +import { + CollectionInfo, + ListCollectionsCursor, + ListCollectionsOptions +} from './operations/list_collections'; +import { ProfilingLevelOperation, ProfilingLevelOptions } from './operations/profiling_level'; +import { RemoveUserOperation, RemoveUserOptions } from './operations/remove_user'; +import { RenameOperation, RenameOptions } from './operations/rename'; +import { + SetProfilingLevelOperation, + SetProfilingLevelOptions, + ProfilingLevel +} from './operations/set_profiling_level'; +import { executeOperation } from './operations/execute_operation'; +import type { IndexInformationOptions } from './operations/common_functions'; +import type { MongoClient, PkFactory } from './mongo_client'; +import { Admin } from './admin'; +import type { TODO_NODE_3286 } from './mongo_types'; + +// Allowed parameters +const DB_OPTIONS_ALLOW_LIST = [ + 'writeConcern', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'authSource', + 'ignoreUndefined', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'loggerLevel', + 'logger', + 'promoteBuffers', + 'promoteLongs', + 'bsonRegExp', + 'promoteValues', + 'compression', + 'retryWrites' +]; + +/** @internal */ +export interface DbPrivate { + client: MongoClient; + options?: DbOptions; + logger: Logger; + readPreference?: ReadPreference; + pkFactory: PkFactory; + readConcern?: ReadConcern; + bsonOptions: BSONSerializeOptions; + writeConcern?: WriteConcern; + namespace: MongoDBNamespace; +} + +/** @public */ +export interface DbOptions extends BSONSerializeOptions, WriteConcernOptions, LoggerOptions { + /** If the database authentication is dependent on another databaseName. */ + authSource?: string; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; + /** A primary key factory object for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcern; + /** Should retry failed writes */ + retryWrites?: boolean; +} + +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```js + * const { MongoClient } = require('mongodb'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); + * }); + * ``` + */ +export class Db { + /** @internal */ + s: DbPrivate; + + public static SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; + public static SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; + public static SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; + public static SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; + public static SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; + public static SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; + + /** + * Creates a new Db instance + * + * @param client - The MongoClient for the database. + * @param databaseName - The name of the database this instance represents. + * @param options - Optional settings for Db construction + */ + constructor(client: MongoClient, databaseName: string, options?: DbOptions) { + options = options ?? {}; + + // Filter the options + options = filterOptions(options, DB_OPTIONS_ALLOW_LIST); + + // Ensure we have a valid db name + validateDatabaseName(databaseName); + + // Internal state of the db object + this.s = { + // Client + client, + // Options + options, + // Logger instance + logger: new Logger('Db', options), + // Unpack read preference + readPreference: ReadPreference.fromOptions(options), + // Merge bson options + bsonOptions: resolveBSONOptions(options, client), + // Set up the primary key factory or fallback to ObjectId + pkFactory: options?.pkFactory ?? DEFAULT_PK_FACTORY, + // ReadConcern + readConcern: ReadConcern.fromOptions(options), + writeConcern: WriteConcern.fromOptions(options), + // Namespace + namespace: new MongoDBNamespace(databaseName) + }; + } + + get databaseName(): string { + return this.s.namespace.db; + } + + // Options + get options(): DbOptions | undefined { + return this.s.options; + } + + // slaveOk specified + get slaveOk(): boolean { + return this.s.readPreference?.preference !== 'primary' || false; + } + + get readConcern(): ReadConcern | undefined { + return this.s.readConcern; + } + + /** + * The current readPreference of the Db. If not explicitly defined for + * this Db, will be inherited from the parent MongoClient + */ + get readPreference(): ReadPreference { + if (this.s.readPreference == null) { + return this.s.client.readPreference; + } + + return this.s.readPreference; + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + // get the write Concern + get writeConcern(): WriteConcern | undefined { + return this.s.writeConcern; + } + + get namespace(): string { + return this.s.namespace.toString(); + } + + /** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @param name - The name of the collection to create + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + createCollection(name: string): Promise>; + createCollection( + name: string, + callback: Callback> + ): void; + createCollection( + name: string, + options: CreateCollectionOptions + ): Promise>; + createCollection( + name: string, + options: CreateCollectionOptions, + callback: Callback> + ): void; + createCollection( + name: string, + options?: CreateCollectionOptions | Callback, + callback?: Callback + ): Promise> | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new CreateCollectionOperation(this, name, resolveOptions(this, options)) as TODO_NODE_3286, + callback + ) as TODO_NODE_3286; + } + + /** + * Execute a command + * + * @remarks + * This command does not inherit options from the MongoClient. + * + * @param command - The command to run + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + command(command: Document): Promise; + command(command: Document, callback: Callback): void; + command(command: Document, options: RunCommandOptions): Promise; + command(command: Document, options: RunCommandOptions, callback: Callback): void; + command( + command: Document, + options?: RunCommandOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + // Intentionally, we do not inherit options from parent for this operation. + return executeOperation( + getTopology(this), + new RunCommandOperation(this, command, options ?? {}), + callback + ); + } + + /** + * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6 + * + * @param pipeline - An array of aggregation stages to be executed + * @param options - Optional settings for the command + */ + aggregate( + pipeline: Document[] = [], + options?: AggregateOptions + ): AggregationCursor { + if (arguments.length > 2) { + throw new MongoInvalidArgumentError('Method "db.aggregate()" accepts at most two arguments'); + } + if (typeof pipeline === 'function') { + throw new MongoInvalidArgumentError('Argument "pipeline" must not be function'); + } + if (typeof options === 'function') { + throw new MongoInvalidArgumentError('Argument "options" must not be function'); + } + + return new AggregationCursor( + getTopology(this), + this.s.namespace, + pipeline, + resolveOptions(this, options) + ); + } + + /** Return the Admin db instance */ + admin(): Admin { + return new Admin(this); + } + + /** + * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. + * + * @param name - the collection name we wish to access. + * @returns return the new Collection instance + */ + collection( + name: string, + options: CollectionOptions = {} + ): Collection { + if (typeof options === 'function') { + throw new MongoInvalidArgumentError('The callback form of this helper has been removed.'); + } + const finalOptions = resolveOptions(this, options); + return new Collection(this, name, finalOptions); + } + + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + stats(): Promise; + stats(callback: Callback): void; + stats(options: DbStatsOptions): Promise; + stats(options: DbStatsOptions, callback: Callback): void; + stats( + options?: DbStatsOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + return executeOperation( + getTopology(this), + new DbStatsOperation(this, resolveOptions(this, options)), + callback + ); + } + + /** + * List all collections of this database with optional filter + * + * @param filter - Query to filter collections by + * @param options - Optional settings for the command + */ + listCollections( + filter: Document, + options: Exclude & { nameOnly: true } + ): ListCollectionsCursor>; + listCollections( + filter: Document, + options: Exclude & { nameOnly: false } + ): ListCollectionsCursor; + listCollections< + T extends Pick | CollectionInfo = + | Pick + | CollectionInfo + >(filter?: Document, options?: ListCollectionsOptions): ListCollectionsCursor; + listCollections< + T extends Pick | CollectionInfo = + | Pick + | CollectionInfo + >(filter: Document = {}, options: ListCollectionsOptions = {}): ListCollectionsCursor { + return new ListCollectionsCursor(this, filter, resolveOptions(this, options)); + } + + /** + * Rename a collection. + * + * @remarks + * This operation does not inherit options from the MongoClient. + * + * @param fromCollection - Name of current collection to rename + * @param toCollection - New name of of the collection + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + renameCollection( + fromCollection: string, + toCollection: string + ): Promise>; + renameCollection( + fromCollection: string, + toCollection: string, + callback: Callback> + ): void; + renameCollection( + fromCollection: string, + toCollection: string, + options: RenameOptions + ): Promise>; + renameCollection( + fromCollection: string, + toCollection: string, + options: RenameOptions, + callback: Callback> + ): void; + renameCollection( + fromCollection: string, + toCollection: string, + options?: RenameOptions | Callback>, + callback?: Callback> + ): Promise> | void { + if (typeof options === 'function') (callback = options), (options = {}); + + // Intentionally, we do not inherit options from parent for this operation. + options = { ...options, readPreference: ReadPreference.PRIMARY }; + + // Add return new collection + options.new_collection = true; + + return executeOperation( + getTopology(this), + new RenameOperation( + this.collection(fromCollection) as TODO_NODE_3286, + toCollection, + options + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param name - Name of collection to drop + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropCollection(name: string): Promise; + dropCollection(name: string, callback: Callback): void; + dropCollection(name: string, options: DropCollectionOptions): Promise; + dropCollection(name: string, options: DropCollectionOptions, callback: Callback): void; + dropCollection( + name: string, + options?: DropCollectionOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new DropCollectionOperation(this, name, resolveOptions(this, options)), + callback + ); + } + + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropDatabase(): Promise; + dropDatabase(callback: Callback): void; + dropDatabase(options: DropDatabaseOptions): Promise; + dropDatabase(options: DropDatabaseOptions, callback: Callback): void; + dropDatabase( + options?: DropDatabaseOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new DropDatabaseOperation(this, resolveOptions(this, options)), + callback + ); + } + + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + collections(): Promise; + collections(callback: Callback): void; + collections(options: ListCollectionsOptions): Promise; + collections(options: ListCollectionsOptions, callback: Callback): void; + collections( + options?: ListCollectionsOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new CollectionsOperation(this, resolveOptions(this, options)), + callback + ); + } + + /** + * Creates an index on the db and collection. + * + * @param name - Name of the collection to create the index on. + * @param indexSpec - Specify the field to index, or an index specification + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + createIndex(name: string, indexSpec: IndexSpecification): Promise; + createIndex(name: string, indexSpec: IndexSpecification, callback?: Callback): void; + createIndex( + name: string, + indexSpec: IndexSpecification, + options: CreateIndexesOptions + ): Promise; + createIndex( + name: string, + indexSpec: IndexSpecification, + options: CreateIndexesOptions, + callback: Callback + ): void; + createIndex( + name: string, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new CreateIndexOperation(this, name, indexSpec, resolveOptions(this, options)), + callback + ); + } + + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param password - An optional password for the new user + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + addUser(username: string): Promise; + addUser(username: string, callback: Callback): void; + addUser(username: string, password: string): Promise; + addUser(username: string, password: string, callback: Callback): void; + addUser(username: string, options: AddUserOptions): Promise; + addUser(username: string, options: AddUserOptions, callback: Callback): void; + addUser(username: string, password: string, options: AddUserOptions): Promise; + addUser( + username: string, + password: string, + options: AddUserOptions, + callback: Callback + ): void; + addUser( + username: string, + password?: string | AddUserOptions | Callback, + options?: AddUserOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof password === 'function') { + (callback = password), (password = undefined), (options = {}); + } else if (typeof password !== 'string') { + if (typeof options === 'function') { + (callback = options), (options = password), (password = undefined); + } else { + (options = password), (callback = undefined), (password = undefined); + } + } else { + if (typeof options === 'function') (callback = options), (options = {}); + } + + return executeOperation( + getTopology(this), + new AddUserOperation(this, username, password, resolveOptions(this, options)), + callback + ); + } + + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + removeUser(username: string): Promise; + removeUser(username: string, callback: Callback): void; + removeUser(username: string, options: RemoveUserOptions): Promise; + removeUser(username: string, options: RemoveUserOptions, callback: Callback): void; + removeUser( + username: string, + options?: RemoveUserOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new RemoveUserOperation(this, username, resolveOptions(this, options)), + callback + ); + } + + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + setProfilingLevel(level: ProfilingLevel): Promise; + setProfilingLevel(level: ProfilingLevel, callback: Callback): void; + setProfilingLevel( + level: ProfilingLevel, + options: SetProfilingLevelOptions + ): Promise; + setProfilingLevel( + level: ProfilingLevel, + options: SetProfilingLevelOptions, + callback: Callback + ): void; + setProfilingLevel( + level: ProfilingLevel, + options?: SetProfilingLevelOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new SetProfilingLevelOperation(this, level, resolveOptions(this, options)), + callback + ); + } + + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + profilingLevel(): Promise; + profilingLevel(callback: Callback): void; + profilingLevel(options: ProfilingLevelOptions): Promise; + profilingLevel(options: ProfilingLevelOptions, callback: Callback): void; + profilingLevel( + options?: ProfilingLevelOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new ProfilingLevelOperation(this, resolveOptions(this, options)), + callback + ); + } + + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexInformation(name: string): Promise; + indexInformation(name: string, callback: Callback): void; + indexInformation(name: string, options: IndexInformationOptions): Promise; + indexInformation( + name: string, + options: IndexInformationOptions, + callback: Callback + ): void; + indexInformation( + name: string, + options?: IndexInformationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + getTopology(this), + new IndexInformationOperation(this, name, resolveOptions(this, options)), + callback + ); + } + + /** + * Unref all sockets + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref(): void { + getTopology(this).unref(); + } + + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this database. Will ignore all + * changes to system collections. + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch( + pipeline: Document[] = [], + options: ChangeStreamOptions = {} + ): ChangeStream { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, resolveOptions(this, options)); + } + + /** Return the db logger */ + getLogger(): Logger { + return this.s.logger; + } + + get logger(): Logger { + return this.s.logger; + } +} + +// TODO(NODE-3484): Refactor into MongoDBNamespace +// Validate the database name +function validateDatabaseName(databaseName: string) { + if (typeof databaseName !== 'string') + throw new MongoInvalidArgumentError('Database name must be a string'); + if (databaseName.length === 0) + throw new MongoInvalidArgumentError('Database name cannot be the empty string'); + if (databaseName === '$external') return; + + const invalidChars = [' ', '.', '$', '/', '\\']; + for (let i = 0; i < invalidChars.length; i++) { + if (databaseName.indexOf(invalidChars[i]) !== -1) + throw new MongoAPIError(`database names cannot contain the character '${invalidChars[i]}'`); + } +} diff --git a/node_modules/mongodb/src/deps.ts b/node_modules/mongodb/src/deps.ts new file mode 100644 index 0000000..35bd4eb --- /dev/null +++ b/node_modules/mongodb/src/deps.ts @@ -0,0 +1,275 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +import { MongoMissingDependencyError } from './error'; +import type { MongoClient } from './mongo_client'; +import type { deserialize, Document, serialize } from './bson'; +import { Callback, parsePackageVersion } from './utils'; + +export const PKG_VERSION = Symbol('kPkgVersion'); + +function makeErrorModule(error: any) { + const props = error ? { kModuleError: error } : {}; + return new Proxy(props, { + get: (_: any, key: any) => { + if (key === 'kModuleError') { + return error; + } + throw error; + }, + set: () => { + throw error; + } + }); +} + +export let Kerberos: typeof import('kerberos') | { kModuleError: MongoMissingDependencyError } = + makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `kerberos` not found. Please install it to enable kerberos authentication' + ) + ); + +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + Kerberos = require('kerberos'); +} catch {} // eslint-disable-line + +export interface KerberosClient { + step: (challenge: string, callback?: Callback) => Promise | void; + wrap: ( + challenge: string, + options?: { user: string }, + callback?: Callback + ) => Promise | void; + unwrap: (challenge: string, callback?: Callback) => Promise | void; +} + +type SnappyLib = { + [PKG_VERSION]: { major: number; minor: number; patch: number }; + + /** + * - Snappy 6.x takes a callback and returns void + * - Snappy 7.x returns a promise + * + * In order to support both we must check the return value of the function + * @param buf - Buffer to be compressed + * @param callback - ONLY USED IN SNAPPY 6.x + */ + compress(buf: Buffer): Promise; + compress(buf: Buffer, callback: (error?: Error, buffer?: Buffer) => void): Promise | void; + compress( + buf: Buffer, + callback?: (error?: Error, buffer?: Buffer) => void + ): Promise | void; + + /** + * - Snappy 6.x takes a callback and returns void + * - Snappy 7.x returns a promise + * + * In order to support both we must check the return value of the function + * @param buf - Buffer to be compressed + * @param callback - ONLY USED IN SNAPPY 6.x + */ + uncompress(buf: Buffer, opt: { asBuffer: true }): Promise; + uncompress( + buf: Buffer, + opt: { asBuffer: true }, + callback: (error?: Error, buffer?: Buffer) => void + ): Promise | void; + uncompress( + buf: Buffer, + opt: { asBuffer: true }, + callback?: (error?: Error, buffer?: Buffer) => void + ): Promise | void; +}; + +export let Snappy: SnappyLib | { kModuleError: MongoMissingDependencyError } = makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `snappy` not found. Please install it to enable snappy compression' + ) +); + +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + Snappy = require('snappy'); + try { + (Snappy as any)[PKG_VERSION] = parsePackageVersion(require('snappy/package.json')); + } catch {} // eslint-disable-line +} catch {} // eslint-disable-line + +export let saslprep: typeof import('saslprep') | { kModuleError: MongoMissingDependencyError } = + makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `saslprep` not found.' + + ' Please install it to enable Stringprep Profile for User Names and Passwords' + ) + ); + +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + saslprep = require('saslprep'); +} catch {} // eslint-disable-line + +interface AWS4 { + /** + * Created these inline types to better assert future usage of this API + * @param options - options for request + * @param credentials - AWS credential details, sessionToken should be omitted entirely if its false-y + */ + sign( + options: { + path: '/'; + body: string; + host: string; + method: 'POST'; + headers: { + 'Content-Type': 'application/x-www-form-urlencoded'; + 'Content-Length': number; + 'X-MongoDB-Server-Nonce': string; + 'X-MongoDB-GS2-CB-Flag': 'n'; + }; + service: string; + region: string; + }, + credentials: + | { + accessKeyId: string; + secretAccessKey: string; + sessionToken: string; + } + | { + accessKeyId: string; + secretAccessKey: string; + } + | undefined + ): { + headers: { + Authorization: string; + 'X-Amz-Date': string; + }; + }; +} + +export let aws4: AWS4 | { kModuleError: MongoMissingDependencyError } = makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `aws4` not found. Please install it to enable AWS authentication' + ) +); + +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + aws4 = require('aws4'); +} catch {} // eslint-disable-line + +/** @public */ +export const AutoEncryptionLoggerLevel = Object.freeze({ + FatalError: 0, + Error: 1, + Warning: 2, + Info: 3, + Trace: 4 +} as const); + +/** @public */ +export type AutoEncryptionLoggerLevel = + typeof AutoEncryptionLoggerLevel[keyof typeof AutoEncryptionLoggerLevel]; + +/** @public */ +export interface AutoEncryptionOptions { + /** @internal */ + bson?: { serialize: typeof serialize; deserialize: typeof deserialize }; + /** @internal client for metadata lookups */ + metadataClient?: MongoClient; + /** A `MongoClient` used to fetch keys from a key vault */ + keyVaultClient?: MongoClient; + /** The namespace where keys are stored in the key vault */ + keyVaultNamespace?: string; + /** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */ + kmsProviders?: { + /** Configuration options for using 'aws' as your KMS provider */ + aws?: { + /** The access key used for the AWS KMS provider */ + accessKeyId: string; + /** The secret access key used for the AWS KMS provider */ + secretAccessKey: string; + /** + * An optional AWS session token that will be used as the + * X-Amz-Security-Token header for AWS requests. + */ + sessionToken?: string; + }; + /** Configuration options for using 'local' as your KMS provider */ + local?: { + /** + * The master key used to encrypt/decrypt data keys. + * A 96-byte long Buffer or base64 encoded string. + */ + key: Buffer | string; + }; + /** Configuration options for using 'azure' as your KMS provider */ + azure?: { + /** The tenant ID identifies the organization for the account */ + tenantId: string; + /** The client ID to authenticate a registered application */ + clientId: string; + /** The client secret to authenticate a registered application */ + clientSecret: string; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * This is optional, and only needed if customer is using a non-commercial Azure instance + * (e.g. a government or China account, which use different URLs). + * Defaults to "login.microsoftonline.com" + */ + identityPlatformEndpoint?: string | undefined; + }; + /** Configuration options for using 'gcp' as your KMS provider */ + gcp?: { + /** The service account email to authenticate */ + email: string; + /** A PKCS#8 encrypted key. This can either be a base64 string or a binary representation */ + privateKey: string | Buffer; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * Defaults to "oauth2.googleapis.com" + */ + endpoint?: string | undefined; + }; + }; + /** + * A map of namespaces to a local JSON schema for encryption + * + * **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server. + * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted. + * Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption. + * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. + */ + schemaMap?: Document; + /** Allows the user to bypass auto encryption, maintaining implicit decryption */ + bypassAutoEncryption?: boolean; + options?: { + /** An optional hook to catch logging messages from the underlying encryption engine */ + logger?: (level: AutoEncryptionLoggerLevel, message: string) => void; + }; + extraOptions?: { + /** + * A local process the driver communicates with to determine how to encrypt values in a command. + * Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise + */ + mongocryptdURI?: string; + /** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */ + mongocryptdBypassSpawn?: boolean; + /** The path to the mongocryptd executable on the system */ + mongocryptdSpawnPath?: string; + /** Command line arguments to use when auto-spawning a mongocryptd */ + mongocryptdSpawnArgs?: string[]; + }; +} + +/** @public */ +export interface AutoEncrypter { + // eslint-disable-next-line @typescript-eslint/no-misused-new + new (client: MongoClient, options: AutoEncryptionOptions): AutoEncrypter; + init(cb: Callback): void; + teardown(force: boolean, callback: Callback): void; + encrypt(ns: string, cmd: Document, options: any, callback: Callback): void; + decrypt(cmd: Document, options: any, callback: Callback): void; +} diff --git a/node_modules/mongodb/src/encrypter.ts b/node_modules/mongodb/src/encrypter.ts new file mode 100644 index 0000000..18cd7a1 --- /dev/null +++ b/node_modules/mongodb/src/encrypter.ts @@ -0,0 +1,119 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +import { MongoClient, MongoClientOptions } from './mongo_client'; +import type { AutoEncrypter, AutoEncryptionOptions } from './deps'; +import { MongoInvalidArgumentError, MongoMissingDependencyError } from './error'; +import { deserialize, serialize } from './bson'; +import type { Callback } from './utils'; +import { MONGO_CLIENT_EVENTS } from './operations/connect'; + +let AutoEncrypterClass: AutoEncrypter; + +/** @internal */ +const kInternalClient = Symbol('internalClient'); + +/** @internal */ +export interface EncrypterOptions { + autoEncryption: AutoEncryptionOptions; + maxPoolSize?: number; +} + +/** @internal */ +export class Encrypter { + [kInternalClient]: MongoClient; + bypassAutoEncryption: boolean; + needsConnecting: boolean; + autoEncrypter: AutoEncrypter; + + constructor(client: MongoClient, uri: string, options: MongoClientOptions) { + if (typeof options.autoEncryption !== 'object') { + throw new MongoInvalidArgumentError('Option "autoEncryption" must be specified'); + } + + this.bypassAutoEncryption = !!options.autoEncryption.bypassAutoEncryption; + this.needsConnecting = false; + + if (options.maxPoolSize === 0 && options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = client; + } else if (options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = this.getInternalClient(client, uri, options); + } + + if (this.bypassAutoEncryption) { + options.autoEncryption.metadataClient = undefined; + } else if (options.maxPoolSize === 0) { + options.autoEncryption.metadataClient = client; + } else { + options.autoEncryption.metadataClient = this.getInternalClient(client, uri, options); + } + + options.autoEncryption.bson = Object.create(null); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + options.autoEncryption.bson!.serialize = serialize; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + options.autoEncryption.bson!.deserialize = deserialize; + + this.autoEncrypter = new AutoEncrypterClass(client, options.autoEncryption); + } + + getInternalClient(client: MongoClient, uri: string, options: MongoClientOptions): MongoClient { + if (!this[kInternalClient]) { + const clonedOptions: MongoClientOptions = {}; + + for (const key of Object.keys(options)) { + if (['autoEncryption', 'minPoolSize', 'servers', 'caseTranslate', 'dbName'].includes(key)) + continue; + Reflect.set(clonedOptions, key, Reflect.get(options, key)); + } + + clonedOptions.minPoolSize = 0; + + this[kInternalClient] = new MongoClient(uri, clonedOptions); + + for (const eventName of MONGO_CLIENT_EVENTS) { + for (const listener of client.listeners(eventName)) { + this[kInternalClient].on(eventName, listener); + } + } + + client.on('newListener', (eventName, listener) => { + this[kInternalClient].on(eventName, listener); + }); + + this.needsConnecting = true; + } + return this[kInternalClient]; + } + + connectInternalClient(callback: Callback): void { + if (this.needsConnecting) { + this.needsConnecting = false; + return this[kInternalClient].connect(callback); + } + + return callback(); + } + + close(client: MongoClient, force: boolean, callback: Callback): void { + this.autoEncrypter.teardown(!!force, e => { + if (this[kInternalClient] && client !== this[kInternalClient]) { + return this[kInternalClient].close(force, callback); + } + callback(e); + }); + } + + static checkForMongoCrypt(): void { + let mongodbClientEncryption = undefined; + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + mongodbClientEncryption = require('mongodb-client-encryption'); + } catch (err) { + throw new MongoMissingDependencyError( + 'Auto-encryption requested, but the module is not installed. ' + + 'Please add `mongodb-client-encryption` as a dependency of your project' + ); + } + + AutoEncrypterClass = mongodbClientEncryption.extension(require('../lib/index')).AutoEncrypter; + } +} diff --git a/node_modules/mongodb/src/error.ts b/node_modules/mongodb/src/error.ts new file mode 100644 index 0000000..fb64d5c --- /dev/null +++ b/node_modules/mongodb/src/error.ts @@ -0,0 +1,813 @@ +import type { TopologyVersion } from './sdam/server_description'; +import type { Document } from './bson'; +import type { TopologyDescription } from './sdam/topology_description'; + +/** @public */ +export type AnyError = MongoError | Error; + +/** @internal */ +const kErrorLabels = Symbol('errorLabels'); + +/** @internal MongoDB Error Codes */ +export const MONGODB_ERROR_CODES = Object.freeze({ + HostUnreachable: 6, + HostNotFound: 7, + NetworkTimeout: 89, + ShutdownInProgress: 91, + PrimarySteppedDown: 189, + ExceededTimeLimit: 262, + SocketException: 9001, + NotMaster: 10107, + InterruptedAtShutdown: 11600, + InterruptedDueToReplStateChange: 11602, + NotMasterNoSlaveOk: 13435, + NotMasterOrSecondary: 13436, + StaleShardVersion: 63, + StaleEpoch: 150, + StaleConfig: 13388, + RetryChangeStream: 234, + FailedToSatisfyReadPreference: 133, + CursorNotFound: 43, + LegacyNotPrimary: 10058, + WriteConcernFailed: 64, + NamespaceNotFound: 26, + IllegalOperation: 20, + MaxTimeMSExpired: 50, + UnknownReplWriteConcern: 79, + UnsatisfiableWriteConcern: 100 +} as const); + +// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error +export const GET_MORE_RESUMABLE_CODES = new Set([ + MONGODB_ERROR_CODES.HostUnreachable, + MONGODB_ERROR_CODES.HostNotFound, + MONGODB_ERROR_CODES.NetworkTimeout, + MONGODB_ERROR_CODES.ShutdownInProgress, + MONGODB_ERROR_CODES.PrimarySteppedDown, + MONGODB_ERROR_CODES.ExceededTimeLimit, + MONGODB_ERROR_CODES.SocketException, + MONGODB_ERROR_CODES.NotMaster, + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + MONGODB_ERROR_CODES.NotMasterNoSlaveOk, + MONGODB_ERROR_CODES.NotMasterOrSecondary, + MONGODB_ERROR_CODES.StaleShardVersion, + MONGODB_ERROR_CODES.StaleEpoch, + MONGODB_ERROR_CODES.StaleConfig, + MONGODB_ERROR_CODES.RetryChangeStream, + MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, + MONGODB_ERROR_CODES.CursorNotFound +]); + +/** @public */ +export interface ErrorDescription extends Document { + message?: string; + errmsg?: string; + $err?: string; + errorLabels?: string[]; + errInfo?: Document; +} + +/** + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error, it uses the constructor with a string argument + */ +export class MongoError extends Error { + /** @internal */ + [kErrorLabels]: Set; + /** + * This is a number in MongoServerError and a string in MongoDriverError + * @privateRemarks + * Define the type override on the subclasses when we can use the override keyword + */ + code?: number | string; + topologyVersion?: TopologyVersion; + + constructor(message: string | Error) { + if (message instanceof Error) { + super(message.message); + } else { + super(message); + } + } + + get name(): string { + return 'MongoError'; + } + + /** Legacy name for server error responses */ + get errmsg(): string { + return this.message; + } + + /** + * Checks the error to see if it has an error label + * + * @param label - The error label to check for + * @returns returns true if the error has the provided error label + */ + hasErrorLabel(label: string): boolean { + if (this[kErrorLabels] == null) { + return false; + } + + return this[kErrorLabels].has(label); + } + + addErrorLabel(label: string): void { + if (this[kErrorLabels] == null) { + this[kErrorLabels] = new Set(); + } + + this[kErrorLabels].add(label); + } + + get errorLabels(): string[] { + return this[kErrorLabels] ? Array.from(this[kErrorLabels]) : []; + } +} + +/** + * An error coming from the mongo server + * + * @public + * @category Error + */ +export class MongoServerError extends MongoError { + codeName?: string; + writeConcernError?: Document; + errInfo?: Document; + ok?: number; + [key: string]: any; + + constructor(message: ErrorDescription) { + super(message.message || message.errmsg || message.$err || 'n/a'); + if (message.errorLabels) { + this[kErrorLabels] = new Set(message.errorLabels); + } + + for (const name in message) { + if (name !== 'errorLabels' && name !== 'errmsg' && name !== 'message') + this[name] = message[name]; + } + } + + get name(): string { + return 'MongoServerError'; + } +} + +/** + * An error generated by the driver + * + * @public + * @category Error + */ +export class MongoDriverError extends MongoError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoDriverError'; + } +} + +/** + * An error generated when the driver API is used incorrectly + * + * @privateRemarks + * Should **never** be directly instantiated + * + * @public + * @category Error + */ + +export class MongoAPIError extends MongoDriverError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoAPIError'; + } +} + +/** + * An error generated when the driver encounters unexpected input + * or reaches an unexpected/invalid internal state + * + * @privateRemarks + * Should **never** be directly instantiated. + * + * @public + * @category Error + */ +export class MongoRuntimeError extends MongoDriverError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoRuntimeError'; + } +} + +/** + * An error generated when a batch command is reexecuted after one of the commands in the batch + * has failed + * + * @public + * @category Error + */ +export class MongoBatchReExecutionError extends MongoAPIError { + constructor(message = 'This batch has already been executed, create new batch to execute') { + super(message); + } + + get name(): string { + return 'MongoBatchReExecutionError'; + } +} + +/** + * An error generated when the driver fails to decompress + * data received from the server. + * + * @public + * @category Error + */ +export class MongoDecompressionError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoDecompressionError'; + } +} + +/** + * An error thrown when the user attempts to operate on a database or collection through a MongoClient + * that has not yet successfully called the "connect" method + * + * @public + * @category Error + */ +export class MongoNotConnectedError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoNotConnectedError'; + } +} + +/** + * An error generated when the user makes a mistake in the usage of transactions. + * (e.g. attempting to commit a transaction with a readPreference other than primary) + * + * @public + * @category Error + */ +export class MongoTransactionError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoTransactionError'; + } +} + +/** + * An error generated when the user attempts to operate + * on a session that has expired or has been closed. + * + * @public + * @category Error + */ +export class MongoExpiredSessionError extends MongoAPIError { + constructor(message = 'Cannot use a session that has ended') { + super(message); + } + + get name(): string { + return 'MongoExpiredSessionError'; + } +} + +/** + * A error generated when the user attempts to authenticate + * via Kerberos, but fails to connect to the Kerberos client. + * + * @public + * @category Error + */ +export class MongoKerberosError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoKerberosError'; + } +} + +/** + * An error generated when a ChangeStream operation fails to execute. + * + * @public + * @category Error + */ +export class MongoChangeStreamError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoChangeStreamError'; + } +} + +/** + * An error thrown when the user calls a function or method not supported on a tailable cursor + * + * @public + * @category Error + */ +export class MongoTailableCursorError extends MongoAPIError { + constructor(message = 'Tailable cursor does not support this operation') { + super(message); + } + + get name(): string { + return 'MongoTailableCursorError'; + } +} + +/** An error generated when a GridFSStream operation fails to execute. + * + * @public + * @category Error + */ +export class MongoGridFSStreamError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoGridFSStreamError'; + } +} + +/** + * An error generated when a malformed or invalid chunk is + * encountered when reading from a GridFSStream. + * + * @public + * @category Error + */ +export class MongoGridFSChunkError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoGridFSChunkError'; + } +} + +/** + * An error thrown when the user attempts to add options to a cursor that has already been + * initialized + * + * @public + * @category Error + */ +export class MongoCursorInUseError extends MongoAPIError { + constructor(message = 'Cursor is already initialized') { + super(message); + } + + get name(): string { + return 'MongoCursorInUseError'; + } +} + +/** + * An error generated when an attempt is made to operate + * on a closed/closing server. + * + * @public + * @category Error + */ +export class MongoServerClosedError extends MongoAPIError { + constructor(message = 'Server is closed') { + super(message); + } + + get name(): string { + return 'MongoServerClosedError'; + } +} + +/** + * An error thrown when an attempt is made to read from a cursor that has been exhausted + * + * @public + * @category Error + */ +export class MongoCursorExhaustedError extends MongoAPIError { + constructor(message?: string) { + super(message || 'Cursor is exhausted'); + } + + get name(): string { + return 'MongoCursorExhaustedError'; + } +} + +/** + * An error generated when an attempt is made to operate on a + * dropped, or otherwise unavailable, database. + * + * @public + * @category Error + */ +export class MongoTopologyClosedError extends MongoAPIError { + constructor(message = 'Topology is closed') { + super(message); + } + + get name(): string { + return 'MongoTopologyClosedError'; + } +} + +/** @internal */ +const kBeforeHandshake = Symbol('beforeHandshake'); +export function isNetworkErrorBeforeHandshake(err: MongoNetworkError): boolean { + return err[kBeforeHandshake] === true; +} + +/** @public */ +export interface MongoNetworkErrorOptions { + /** Indicates the timeout happened before a connection handshake completed */ + beforeHandshake: boolean; +} + +/** + * An error indicating an issue with the network, including TCP errors and timeouts. + * @public + * @category Error + */ +export class MongoNetworkError extends MongoError { + /** @internal */ + [kBeforeHandshake]?: boolean; + + constructor(message: string | Error, options?: MongoNetworkErrorOptions) { + super(message); + + if (options && typeof options.beforeHandshake === 'boolean') { + this[kBeforeHandshake] = options.beforeHandshake; + } + } + + get name(): string { + return 'MongoNetworkError'; + } +} + +/** + * An error indicating a network timeout occurred + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error with an instanceof check + */ +export class MongoNetworkTimeoutError extends MongoNetworkError { + constructor(message: string, options?: MongoNetworkErrorOptions) { + super(message, options); + } + + get name(): string { + return 'MongoNetworkTimeoutError'; + } +} + +/** + * An error used when attempting to parse a value (like a connection string) + * @public + * @category Error + */ +export class MongoParseError extends MongoDriverError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoParseError'; + } +} + +/** + * An error generated when the user supplies malformed or unexpected arguments + * or when a required argument or field is not provided. + * + * + * @public + * @category Error + */ +export class MongoInvalidArgumentError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoInvalidArgumentError'; + } +} + +/** + * An error generated when a feature that is not enabled or allowed for the current server + * configuration is used + * + * + * @public + * @category Error + */ +export class MongoCompatibilityError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoCompatibilityError'; + } +} + +/** + * An error generated when the user fails to provide authentication credentials before attempting + * to connect to a mongo server instance. + * + * + * @public + * @category Error + */ +export class MongoMissingCredentialsError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoMissingCredentialsError'; + } +} + +/** + * An error generated when a required module or dependency is not present in the local environment + * + * @public + * @category Error + */ +export class MongoMissingDependencyError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + get name(): string { + return 'MongoMissingDependencyError'; + } +} +/** + * An error signifying a general system issue + * @public + * @category Error + */ +export class MongoSystemError extends MongoError { + /** An optional reason context, such as an error saved during flow of monitoring and selecting servers */ + reason?: TopologyDescription; + + constructor(message: string, reason: TopologyDescription) { + if (reason && reason.error) { + super(reason.error.message || reason.error); + } else { + super(message); + } + + if (reason) { + this.reason = reason; + } + } + + get name(): string { + return 'MongoSystemError'; + } +} + +/** + * An error signifying a client-side server selection error + * @public + * @category Error + */ +export class MongoServerSelectionError extends MongoSystemError { + constructor(message: string, reason: TopologyDescription) { + super(message, reason); + } + + get name(): string { + return 'MongoServerSelectionError'; + } +} + +function makeWriteConcernResultObject(input: any) { + const output = Object.assign({}, input); + + if (output.ok === 0) { + output.ok = 1; + delete output.errmsg; + delete output.code; + delete output.codeName; + } + + return output; +} + +/** + * An error thrown when the server reports a writeConcernError + * @public + * @category Error + */ +export class MongoWriteConcernError extends MongoServerError { + /** The result document (provided if ok: 1) */ + result?: Document; + errInfo?: Document; + + constructor(message: ErrorDescription, result?: Document) { + if (result && Array.isArray(result.errorLabels)) { + message.errorLabels = result.errorLabels; + } + + super(message); + this.errInfo = message.errInfo; + + if (result != null) { + this.result = makeWriteConcernResultObject(result); + } + } + + get name(): string { + return 'MongoWriteConcernError'; + } +} + +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_ERROR_CODES = new Set([ + MONGODB_ERROR_CODES.HostUnreachable, + MONGODB_ERROR_CODES.HostNotFound, + MONGODB_ERROR_CODES.NetworkTimeout, + MONGODB_ERROR_CODES.ShutdownInProgress, + MONGODB_ERROR_CODES.PrimarySteppedDown, + MONGODB_ERROR_CODES.SocketException, + MONGODB_ERROR_CODES.NotMaster, + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + MONGODB_ERROR_CODES.NotMasterNoSlaveOk, + MONGODB_ERROR_CODES.NotMasterOrSecondary +]); + +const RETRYABLE_WRITE_ERROR_CODES = new Set([ + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + MONGODB_ERROR_CODES.NotMaster, + MONGODB_ERROR_CODES.NotMasterNoSlaveOk, + MONGODB_ERROR_CODES.NotMasterOrSecondary, + MONGODB_ERROR_CODES.PrimarySteppedDown, + MONGODB_ERROR_CODES.ShutdownInProgress, + MONGODB_ERROR_CODES.HostNotFound, + MONGODB_ERROR_CODES.HostUnreachable, + MONGODB_ERROR_CODES.NetworkTimeout, + MONGODB_ERROR_CODES.SocketException, + MONGODB_ERROR_CODES.ExceededTimeLimit +]); + +export function isRetryableWriteError(error: MongoError): boolean { + if (error instanceof MongoWriteConcernError) { + return RETRYABLE_WRITE_ERROR_CODES.has(error.result?.code ?? error.code ?? 0); + } + return typeof error.code === 'number' && RETRYABLE_WRITE_ERROR_CODES.has(error.code); +} + +/** Determines whether an error is something the driver should attempt to retry */ +export function isRetryableError(error: MongoError): boolean { + return ( + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + (typeof error.code === 'number' && RETRYABLE_ERROR_CODES.has(error.code!)) || + error instanceof MongoNetworkError || + !!error.message.match(/not master/) || + !!error.message.match(/node is recovering/) + ); +} + +const SDAM_RECOVERING_CODES = new Set([ + MONGODB_ERROR_CODES.ShutdownInProgress, + MONGODB_ERROR_CODES.PrimarySteppedDown, + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + MONGODB_ERROR_CODES.NotMasterOrSecondary +]); + +const SDAM_NOTMASTER_CODES = new Set([ + MONGODB_ERROR_CODES.NotMaster, + MONGODB_ERROR_CODES.NotMasterNoSlaveOk, + MONGODB_ERROR_CODES.LegacyNotPrimary +]); + +const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.ShutdownInProgress +]); + +function isRecoveringError(err: MongoError) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_RECOVERING_CODES.has(err.code); + } + + return /not master or secondary/.test(err.message) || /node is recovering/.test(err.message); +} + +function isNotMasterError(err: MongoError) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_NOTMASTER_CODES.has(err.code); + } + + if (isRecoveringError(err)) { + return false; + } + + return /not master/.test(err.message); +} + +export function isNodeShuttingDownError(err: MongoError): boolean { + return !!(typeof err.code === 'number' && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code)); +} + +/** + * Determines whether SDAM can recover from a given error. If it cannot + * then the pool will be cleared, and server state will completely reset + * locally. + * + * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering + */ +export function isSDAMUnrecoverableError(error: MongoError): boolean { + // NOTE: null check is here for a strictly pre-CMAP world, a timeout or + // close event are considered unrecoverable + if (error instanceof MongoParseError || error == null) { + return true; + } + + return isRecoveringError(error) || isNotMasterError(error); +} + +export function isNetworkTimeoutError(err: MongoError): err is MongoNetworkError { + return !!(err instanceof MongoNetworkError && err.message.match(/timed out/)); +} + +// From spec@https://github.com/mongodb/specifications/blob/7a2e93d85935ee4b1046a8d2ad3514c657dc74fa/source/change-streams/change-streams.rst#resumable-error: +// +// An error is considered resumable if it meets any of the following criteria: +// - any error encountered which is not a server error (e.g. a timeout error or network error) +// - any server error response from a getMore command excluding those containing the error label +// NonRetryableChangeStreamError and those containing the following error codes: +// - Interrupted: 11601 +// - CappedPositionLost: 136 +// - CursorKilled: 237 +// +// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors. + +export function isResumableError(error?: MongoError, wireVersion?: number): boolean { + if (error instanceof MongoNetworkError) { + return true; + } + + if (wireVersion != null && wireVersion >= 9) { + // DRIVERS-1308: For 4.4 drivers running against 4.4 servers, drivers will add a special case to treat the CursorNotFound error code as resumable + if (error && error instanceof MongoError && error.code === 43) { + return true; + } + return error instanceof MongoError && error.hasErrorLabel('ResumableChangeStreamError'); + } + + if (error && typeof error.code === 'number') { + return GET_MORE_RESUMABLE_CODES.has(error.code); + } + return false; +} diff --git a/node_modules/mongodb/src/explain.ts b/node_modules/mongodb/src/explain.ts new file mode 100644 index 0000000..0d08e69 --- /dev/null +++ b/node_modules/mongodb/src/explain.ts @@ -0,0 +1,52 @@ +import { MongoInvalidArgumentError } from './error'; + +/** @public */ +export const ExplainVerbosity = Object.freeze({ + queryPlanner: 'queryPlanner', + queryPlannerExtended: 'queryPlannerExtended', + executionStats: 'executionStats', + allPlansExecution: 'allPlansExecution' +} as const); + +/** @public */ +export type ExplainVerbosity = string; + +/** + * For backwards compatibility, true is interpreted as "allPlansExecution" + * and false as "queryPlanner". Prior to server version 3.6, aggregate() + * ignores the verbosity parameter and executes in "queryPlanner". + * @public + */ +export type ExplainVerbosityLike = ExplainVerbosity | boolean; + +/** @public */ +export interface ExplainOptions { + /** Specifies the verbosity mode for the explain output. */ + explain?: ExplainVerbosityLike; +} + +/** @internal */ +export class Explain { + verbosity: ExplainVerbosity; + + constructor(verbosity: ExplainVerbosityLike) { + if (typeof verbosity === 'boolean') { + this.verbosity = verbosity + ? ExplainVerbosity.allPlansExecution + : ExplainVerbosity.queryPlanner; + } else { + this.verbosity = verbosity; + } + } + + static fromOptions(options?: ExplainOptions): Explain | undefined { + if (options?.explain == null) return; + + const explain = options.explain; + if (typeof explain === 'boolean' || typeof explain === 'string') { + return new Explain(explain); + } + + throw new MongoInvalidArgumentError('Field "explain" must be a string or a boolean'); + } +} diff --git a/node_modules/mongodb/src/gridfs/download.ts b/node_modules/mongodb/src/gridfs/download.ts new file mode 100644 index 0000000..7e2925b --- /dev/null +++ b/node_modules/mongodb/src/gridfs/download.ts @@ -0,0 +1,454 @@ +import { Readable } from 'stream'; +import { + MongoRuntimeError, + MongoGridFSChunkError, + MongoGridFSStreamError, + MongoInvalidArgumentError +} from '../error'; +import type { Document } from '../bson'; +import type { FindOptions } from '../operations/find'; +import type { Sort } from '../sort'; +import type { Callback } from '../utils'; +import type { Collection } from '../collection'; +import type { ReadPreference } from '../read_preference'; +import type { GridFSChunk } from './upload'; +import type { FindCursor } from '../cursor/find_cursor'; +import type { ObjectId } from 'bson'; + +/** @public */ +export interface GridFSBucketReadStreamOptions { + sort?: Sort; + skip?: number; + /** 0-based offset in bytes to start streaming from */ + start?: number; + /** 0-based offset in bytes to stop streaming before */ + end?: number; +} + +/** @public */ +export interface GridFSBucketReadStreamOptionsWithRevision extends GridFSBucketReadStreamOptions { + /** The revision number relative to the oldest file with the given filename. 0 + * gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the + * newest. */ + revision?: number; +} + +/** @public */ +export interface GridFSFile { + _id: ObjectId; + length: number; + chunkSize: number; + filename: string; + contentType?: string; + aliases?: string[]; + metadata?: Document; + uploadDate: Date; +} + +/** @internal */ +export interface GridFSBucketReadStreamPrivate { + bytesRead: number; + bytesToTrim: number; + bytesToSkip: number; + chunks: Collection; + cursor?: FindCursor; + expected: number; + files: Collection; + filter: Document; + init: boolean; + expectedEnd: number; + file?: GridFSFile; + options: { + sort?: Sort; + skip?: number; + start: number; + end: number; + }; + readPreference?: ReadPreference; +} + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * @public + */ +export class GridFSBucketReadStream extends Readable implements NodeJS.ReadableStream { + /** @internal */ + s: GridFSBucketReadStreamPrivate; + + /** + * An error occurred + * @event + */ + static readonly ERROR = 'error' as const; + /** + * Fires when the stream loaded the file document corresponding to the provided id. + * @event + */ + static readonly FILE = 'file' as const; + /** + * Emitted when a chunk of data is available to be consumed. + * @event + */ + static readonly DATA = 'data' as const; + /** + * Fired when the stream is exhausted (no more data events). + * @event + */ + static readonly END = 'end' as const; + /** + * Fired when the stream is exhausted and the underlying cursor is killed + * @event + */ + static readonly CLOSE = 'close' as const; + + /** @internal + * @param chunks - Handle for chunks collection + * @param files - Handle for files collection + * @param readPreference - The read preference to use + * @param filter - The filter to use to find the file document + */ + constructor( + chunks: Collection, + files: Collection, + readPreference: ReadPreference | undefined, + filter: Document, + options?: GridFSBucketReadStreamOptions + ) { + super(); + this.s = { + bytesToTrim: 0, + bytesToSkip: 0, + bytesRead: 0, + chunks, + expected: 0, + files, + filter, + init: false, + expectedEnd: 0, + options: { + start: 0, + end: 0, + ...options + }, + readPreference + }; + } + + /** + * Reads from the cursor and pushes to the stream. + * Private Impl, do not call directly + * @internal + */ + _read(): void { + if (this.destroyed) return; + waitForFile(this, () => doRead(this)); + } + + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param start - 0-based offset in bytes to start streaming from + */ + start(start = 0): this { + throwIfInitialized(this); + this.s.options.start = start; + return this; + } + + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param end - Offset in bytes to stop reading at + */ + end(end = 0): this { + throwIfInitialized(this); + this.s.options.end = end; + return this; + } + + /** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @param callback - called when the cursor is successfully closed or an error occurred. + */ + abort(callback?: Callback): void { + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + this.s.cursor.close(error => { + this.emit(GridFSBucketReadStream.CLOSE); + callback && callback(error); + }); + } else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + this.emit(GridFSBucketReadStream.CLOSE); + } + callback && callback(); + } + } +} + +function throwIfInitialized(stream: GridFSBucketReadStream): void { + if (stream.s.init) { + throw new MongoGridFSStreamError('Options cannot be changed after the stream is initialized'); + } +} + +function doRead(stream: GridFSBucketReadStream): void { + if (stream.destroyed) return; + if (!stream.s.cursor) return; + if (!stream.s.file) return; + + stream.s.cursor.next((error, doc) => { + if (stream.destroyed) { + return; + } + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + if (!doc) { + stream.push(null); + + process.nextTick(() => { + if (!stream.s.cursor) return; + stream.s.cursor.close(error => { + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + + stream.emit(GridFSBucketReadStream.CLOSE); + }); + }); + + return; + } + + if (!stream.s.file) return; + + const bytesRemaining = stream.s.file.length - stream.s.bytesRead; + const expectedN = stream.s.expected++; + const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining); + if (doc.n > expectedN) { + return stream.emit( + GridFSBucketReadStream.ERROR, + new MongoGridFSChunkError( + `ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}` + ) + ); + } + + if (doc.n < expectedN) { + return stream.emit( + GridFSBucketReadStream.ERROR, + new MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`) + ); + } + + let buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + + if (buf.byteLength !== expectedLength) { + if (bytesRemaining <= 0) { + return stream.emit( + GridFSBucketReadStream.ERROR, + new MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}`) + ); + } + + return stream.emit( + GridFSBucketReadStream.ERROR, + new MongoGridFSChunkError( + `ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}` + ) + ); + } + + stream.s.bytesRead += buf.byteLength; + + if (buf.byteLength === 0) { + return stream.push(null); + } + + let sliceStart = null; + let sliceEnd = null; + + if (stream.s.bytesToSkip != null) { + sliceStart = stream.s.bytesToSkip; + stream.s.bytesToSkip = 0; + } + + const atEndOfStream = expectedN === stream.s.expectedEnd - 1; + const bytesLeftToRead = stream.s.options.end - stream.s.bytesToSkip; + if (atEndOfStream && stream.s.bytesToTrim != null) { + sliceEnd = stream.s.file.chunkSize - stream.s.bytesToTrim; + } else if (stream.s.options.end && bytesLeftToRead < doc.data.byteLength) { + sliceEnd = bytesLeftToRead; + } + + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.byteLength); + } + + stream.push(buf); + }); +} + +function init(stream: GridFSBucketReadStream): void { + const findOneOptions: FindOptions = {}; + if (stream.s.readPreference) { + findOneOptions.readPreference = stream.s.readPreference; + } + if (stream.s.options && stream.s.options.sort) { + findOneOptions.sort = stream.s.options.sort; + } + if (stream.s.options && stream.s.options.skip) { + findOneOptions.skip = stream.s.options.skip; + } + + stream.s.files.findOne(stream.s.filter, findOneOptions, (error, doc) => { + if (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + + if (!doc) { + const identifier = stream.s.filter._id + ? stream.s.filter._id.toString() + : stream.s.filter.filename; + const errmsg = `FileNotFound: file ${identifier} was not found`; + // TODO(NODE-3483) + const err = new MongoRuntimeError(errmsg); + err.code = 'ENOENT'; // TODO: NODE-3338 set property as part of constructor + return stream.emit(GridFSBucketReadStream.ERROR, err); + } + + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + stream.push(null); + return; + } + + if (stream.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + stream.emit(GridFSBucketReadStream.CLOSE); + return; + } + + try { + stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options); + } catch (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + + const filter: Document = { files_id: doc._id }; + + // Currently (MongoDB 3.4.4) skip function does not support the index, + // it needs to retrieve all the documents first and then skip them. (CS-25811) + // As work around we use $gte on the "n" field. + if (stream.s.options && stream.s.options.start != null) { + const skip = Math.floor(stream.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; + } + } + stream.s.cursor = stream.s.chunks.find(filter).sort({ n: 1 }); + + if (stream.s.readPreference) { + stream.s.cursor.withReadPreference(stream.s.readPreference); + } + + stream.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + stream.s.file = doc as GridFSFile; + + try { + stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options); + } catch (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + + stream.emit(GridFSBucketReadStream.FILE, doc); + }); +} + +function waitForFile(stream: GridFSBucketReadStream, callback: Callback): void { + if (stream.s.file) { + return callback(); + } + + if (!stream.s.init) { + init(stream); + stream.s.init = true; + } + + stream.once('file', () => { + callback(); + }); +} + +function handleStartOption( + stream: GridFSBucketReadStream, + doc: Document, + options: GridFSBucketReadStreamOptions +): number { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new MongoInvalidArgumentError( + `Stream start (${options.start}) must not be more than the length of the file (${doc.length})` + ); + } + if (options.start < 0) { + throw new MongoInvalidArgumentError(`Stream start (${options.start}) must not be negative`); + } + if (options.end != null && options.end < options.start) { + throw new MongoInvalidArgumentError( + `Stream start (${options.start}) must not be greater than stream end (${options.end})` + ); + } + + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + + return options.start - stream.s.bytesRead; + } + throw new MongoInvalidArgumentError('Start option must be defined'); +} + +function handleEndOption( + stream: GridFSBucketReadStream, + doc: Document, + cursor: FindCursor, + options: GridFSBucketReadStreamOptions +) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new MongoInvalidArgumentError( + `Stream end (${options.end}) must not be more than the length of the file (${doc.length})` + ); + } + if (options.start == null || options.start < 0) { + throw new MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`); + } + + const start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; + + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + + return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; + } + throw new MongoInvalidArgumentError('End option must be defined'); +} diff --git a/node_modules/mongodb/src/gridfs/index.ts b/node_modules/mongodb/src/gridfs/index.ts new file mode 100644 index 0000000..f2e6fb5 --- /dev/null +++ b/node_modules/mongodb/src/gridfs/index.ts @@ -0,0 +1,274 @@ +import { MongoRuntimeError } from '../error'; +import { + GridFSBucketReadStream, + GridFSBucketReadStreamOptions, + GridFSBucketReadStreamOptionsWithRevision, + GridFSFile +} from './download'; +import { GridFSBucketWriteStream, GridFSBucketWriteStreamOptions, GridFSChunk } from './upload'; +import { executeLegacyOperation, Callback, getTopology } from '../utils'; +import { WriteConcernOptions, WriteConcern } from '../write_concern'; +import type { ObjectId } from '../bson'; +import type { Db } from '../db'; +import type { ReadPreference } from '../read_preference'; +import type { Collection } from '../collection'; +import type { FindOptions } from './../operations/find'; +import type { Sort } from '../sort'; +import type { Logger } from '../logger'; +import type { FindCursor } from '../cursor/find_cursor'; +import { Filter, TypedEventEmitter } from '../mongo_types'; + +const DEFAULT_GRIDFS_BUCKET_OPTIONS: { + bucketName: string; + chunkSizeBytes: number; +} = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; + +/** @public */ +export interface GridFSBucketOptions extends WriteConcernOptions { + /** The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. */ + bucketName?: string; + /** Number of bytes stored in each chunk. Defaults to 255KB */ + chunkSizeBytes?: number; + /** Read preference to be passed to read operations */ + readPreference?: ReadPreference; +} + +/** @internal */ +export interface GridFSBucketPrivate { + db: Db; + options: { + bucketName: string; + chunkSizeBytes: number; + readPreference?: ReadPreference; + writeConcern: WriteConcern | undefined; + }; + _chunksCollection: Collection; + _filesCollection: Collection; + checkedIndexes: boolean; + calledOpenUploadStream: boolean; +} + +/** @public */ +export type GridFSBucketEvents = { + index(): void; +}; + +/** + * Constructor for a streaming GridFS interface + * @public + */ +export class GridFSBucket extends TypedEventEmitter { + /** @internal */ + s: GridFSBucketPrivate; + + /** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * @event + */ + static readonly INDEX = 'index' as const; + + constructor(db: Db, options?: GridFSBucketOptions) { + super(); + this.setMaxListeners(0); + const privateOptions = { + ...DEFAULT_GRIDFS_BUCKET_OPTIONS, + ...options, + writeConcern: WriteConcern.fromOptions(options) + }; + this.s = { + db, + options: privateOptions, + _chunksCollection: db.collection(privateOptions.bucketName + '.chunks'), + _filesCollection: db.collection(privateOptions.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false + }; + } + + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + + openUploadStream( + filename: string, + options?: GridFSBucketWriteStreamOptions + ): GridFSBucketWriteStream { + return new GridFSBucketWriteStream(this, filename, options); + } + + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + */ + openUploadStreamWithId( + id: ObjectId, + filename: string, + options?: GridFSBucketWriteStreamOptions + ): GridFSBucketWriteStream { + return new GridFSBucketWriteStream(this, filename, { ...options, id }); + } + + /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ + openDownloadStream( + id: ObjectId, + options?: GridFSBucketReadStreamOptions + ): GridFSBucketReadStream { + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + { _id: id }, + options + ); + } + + /** + * Deletes a file with the given id + * + * @param id - The id of the file doc + */ + delete(id: ObjectId): Promise; + delete(id: ObjectId, callback: Callback): void; + delete(id: ObjectId, callback?: Callback): Promise | void { + return executeLegacyOperation(getTopology(this.s.db), _delete, [this, id, callback], { + skipSessions: true + }); + } + + /** Convenience wrapper around find on the files collection */ + find(filter?: Filter, options?: FindOptions): FindCursor { + filter ??= {}; + options = options ?? {}; + return this.s._filesCollection.find(filter, options); + } + + /** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + */ + openDownloadStreamByName( + filename: string, + options?: GridFSBucketReadStreamOptionsWithRevision + ): GridFSBucketReadStream { + let sort: Sort = { uploadDate: -1 }; + let skip = undefined; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } else { + skip = -options.revision - 1; + } + } + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + { filename }, + { ...options, sort, skip } + ); + } + + /** + * Renames the file with the given _id to the given string + * + * @param id - the id of the file to rename + * @param filename - new name for the file + */ + rename(id: ObjectId, filename: string): Promise; + rename(id: ObjectId, filename: string, callback: Callback): void; + rename(id: ObjectId, filename: string, callback?: Callback): Promise | void { + return executeLegacyOperation(getTopology(this.s.db), _rename, [this, id, filename, callback], { + skipSessions: true + }); + } + + /** Removes this bucket's files collection, followed by its chunks collection. */ + drop(): Promise; + drop(callback: Callback): void; + drop(callback?: Callback): Promise | void { + return executeLegacyOperation(getTopology(this.s.db), _drop, [this, callback], { + skipSessions: true + }); + } + + /** Get the Db scoped logger. */ + getLogger(): Logger { + return this.s.db.s.logger; + } +} + +function _delete(bucket: GridFSBucket, id: ObjectId, callback: Callback): void { + return bucket.s._filesCollection.deleteOne({ _id: id }, (error, res) => { + if (error) { + return callback(error); + } + + return bucket.s._chunksCollection.deleteMany({ files_id: id }, error => { + if (error) { + return callback(error); + } + + // Delete orphaned chunks before returning FileNotFound + if (!res?.deletedCount) { + // TODO(NODE-3483): Replace with more appropriate error + // Consider creating new error MongoGridFSFileNotFoundError + return callback(new MongoRuntimeError(`File not found for id ${id}`)); + } + + return callback(); + }); + }); +} + +function _rename( + bucket: GridFSBucket, + id: ObjectId, + filename: string, + callback: Callback +): void { + const filter = { _id: id }; + const update = { $set: { filename } }; + return bucket.s._filesCollection.updateOne(filter, update, (error?, res?) => { + if (error) { + return callback(error); + } + + if (!res?.matchedCount) { + return callback(new MongoRuntimeError(`File with id ${id} not found`)); + } + + return callback(); + }); +} + +function _drop(bucket: GridFSBucket, callback: Callback): void { + return bucket.s._filesCollection.drop((error?: Error) => { + if (error) { + return callback(error); + } + return bucket.s._chunksCollection.drop((error?: Error) => { + if (error) { + return callback(error); + } + + return callback(); + }); + }); +} diff --git a/node_modules/mongodb/src/gridfs/upload.ts b/node_modules/mongodb/src/gridfs/upload.ts new file mode 100644 index 0000000..da81299 --- /dev/null +++ b/node_modules/mongodb/src/gridfs/upload.ts @@ -0,0 +1,563 @@ +import { Writable } from 'stream'; +import type { Document } from '../bson'; +import { ObjectId } from '../bson'; +import type { Collection } from '../collection'; +import { AnyError, MONGODB_ERROR_CODES, MongoError, MongoAPIError } from '../error'; +import { Callback, maybePromise } from '../utils'; +import type { WriteConcernOptions } from '../write_concern'; +import { WriteConcern } from './../write_concern'; +import type { GridFSFile } from './download'; +import type { GridFSBucket } from './index'; + +/** @public */ +export interface GridFSChunk { + _id: ObjectId; + files_id: ObjectId; + n: number; + data: Buffer | Uint8Array; +} + +/** @public */ +export interface GridFSBucketWriteStreamOptions extends WriteConcernOptions { + /** Overwrite this bucket's chunkSizeBytes for this file */ + chunkSizeBytes?: number; + /** Custom file id for the GridFS file. */ + id?: ObjectId; + /** Object to store in the file document's `metadata` field */ + metadata?: Document; + /** String to store in the file document's `contentType` field */ + contentType?: string; + /** Array of strings to store in the file document's `aliases` field */ + aliases?: string[]; +} + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * @public + */ +export class GridFSBucketWriteStream extends Writable implements NodeJS.WritableStream { + bucket: GridFSBucket; + chunks: Collection; + filename: string; + files: Collection; + options: GridFSBucketWriteStreamOptions; + done: boolean; + id: ObjectId; + chunkSizeBytes: number; + bufToStore: Buffer; + length: number; + n: number; + pos: number; + state: { + streamEnd: boolean; + outstandingRequests: number; + errored: boolean; + aborted: boolean; + }; + writeConcern?: WriteConcern; + + /** @event */ + static readonly CLOSE = 'close'; + /** @event */ + static readonly ERROR = 'error'; + /** + * `end()` was called and the write stream successfully wrote the file metadata and all the chunks to MongoDB. + * @event + */ + static readonly FINISH = 'finish'; + + /** @internal + * @param bucket - Handle for this stream's corresponding bucket + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + constructor(bucket: GridFSBucket, filename: string, options?: GridFSBucketWriteStreamOptions) { + super(); + + options = options ?? {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + this.writeConcern = WriteConcern.fromOptions(options) || bucket.s.options.writeConcern; + // Signals the write is all done + this.done = false; + + this.id = options.id ? options.id : new ObjectId(); + // properly inherit the default chunksize from parent + this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false + }; + + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + + checkIndexes(this, () => { + this.bucket.s.checkedIndexes = true; + this.bucket.emit('index'); + }); + } + } + + /** + * Write a buffer to the stream. + * + * @param chunk - Buffer to write + * @param encodingOrCallback - Optional encoding for the buffer + * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @returns False if this write required flushing a chunk to MongoDB. True otherwise. + */ + write(chunk: Buffer | string): boolean; + write(chunk: Buffer | string, callback: Callback): boolean; + write(chunk: Buffer | string, encoding: BufferEncoding | undefined): boolean; + write( + chunk: Buffer | string, + encoding: BufferEncoding | undefined, + callback: Callback + ): boolean; + write( + chunk: Buffer | string, + encodingOrCallback?: Callback | BufferEncoding, + callback?: Callback + ): boolean { + const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback; + callback = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback; + return waitForIndexes(this, () => doWrite(this, chunk, encoding, callback)); + } + + // TODO(NODE-3405): Refactor this with maybePromise and MongoStreamClosedError + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + * + * @param callback - called when chunks are successfully removed or error occurred + */ + abort(): Promise; + abort(callback: Callback): void; + abort(callback?: Callback): Promise | void { + return maybePromise(callback, callback => { + if (this.state.streamEnd) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + return callback(new MongoAPIError('Cannot abort a stream that has already completed')); + } + + if (this.state.aborted) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + return callback(new MongoAPIError('Cannot call abort() on a stream twice')); + } + + this.state.aborted = true; + this.chunks.deleteMany({ files_id: this.id }, error => callback(error)); + }); + } + + /** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @param chunk - Buffer to write + * @param encoding - Optional encoding for the buffer + * @param callback - Function to call when all files and chunks have been persisted to MongoDB + */ + end(): void; + end(chunk: Buffer): void; + end(callback: Callback): void; + end(chunk: Buffer, callback: Callback): void; + end(chunk: Buffer, encoding: BufferEncoding): void; + end( + chunk: Buffer, + encoding: BufferEncoding | undefined, + callback: Callback + ): void; + end( + chunkOrCallback?: Buffer | Callback, + encodingOrCallback?: BufferEncoding | Callback, + callback?: Callback + ): void { + const chunk = typeof chunkOrCallback === 'function' ? undefined : chunkOrCallback; + const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback; + callback = + typeof chunkOrCallback === 'function' + ? chunkOrCallback + : typeof encodingOrCallback === 'function' + ? encodingOrCallback + : callback; + + if (checkAborted(this, callback)) return; + + this.state.streamEnd = true; + + if (callback) { + this.once(GridFSBucketWriteStream.FINISH, (result: GridFSFile) => { + if (callback) callback(undefined, result); + }); + } + + if (!chunk) { + waitForIndexes(this, () => !!writeRemnant(this)); + return; + } + + this.write(chunk, encoding, () => { + writeRemnant(this); + }); + } +} + +function __handleError( + stream: GridFSBucketWriteStream, + error: AnyError, + callback?: Callback +): void { + if (stream.state.errored) { + return; + } + stream.state.errored = true; + if (callback) { + return callback(error); + } + stream.emit(GridFSBucketWriteStream.ERROR, error); +} + +function createChunkDoc(filesId: ObjectId, n: number, data: Buffer): GridFSChunk { + return { + _id: new ObjectId(), + files_id: filesId, + n, + data + }; +} + +function checkChunksIndex(stream: GridFSBucketWriteStream, callback: Callback): void { + stream.chunks.listIndexes().toArray((error?: AnyError, indexes?: Document[]) => { + let index: { files_id: number; n: number }; + if (error) { + // Collection doesn't exist so create index + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + index = { files_id: 1, n: 1 }; + stream.chunks.createIndex(index, { background: false, unique: true }, error => { + if (error) { + return callback(error); + } + + callback(); + }); + return; + } + return callback(error); + } + + let hasChunksIndex = false; + if (indexes) { + indexes.forEach((index: Document) => { + if (index.key) { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + } + + if (hasChunksIndex) { + callback(); + } else { + index = { files_id: 1, n: 1 }; + const writeConcernOptions = getWriteOptions(stream); + + stream.chunks.createIndex( + index, + { + ...writeConcernOptions, + background: true, + unique: true + }, + callback + ); + } + }); +} + +function checkDone(stream: GridFSBucketWriteStream, callback?: Callback): boolean { + if (stream.done) return true; + if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) { + // Set done so we do not trigger duplicate createFilesDoc + stream.done = true; + // Create a new files doc + const filesDoc = createFilesDoc( + stream.id, + stream.length, + stream.chunkSizeBytes, + stream.filename, + stream.options.contentType, + stream.options.aliases, + stream.options.metadata + ); + + if (checkAborted(stream, callback)) { + return false; + } + + stream.files.insertOne(filesDoc, getWriteOptions(stream), (error?: AnyError) => { + if (error) { + return __handleError(stream, error, callback); + } + stream.emit(GridFSBucketWriteStream.FINISH, filesDoc); + stream.emit(GridFSBucketWriteStream.CLOSE); + }); + + return true; + } + + return false; +} + +function checkIndexes(stream: GridFSBucketWriteStream, callback: Callback): void { + stream.files.findOne({}, { projection: { _id: 1 } }, (error, doc) => { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + + stream.files.listIndexes().toArray((error?: AnyError, indexes?: Document) => { + let index: { filename: number; uploadDate: number }; + if (error) { + // Collection doesn't exist so create index + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + index = { filename: 1, uploadDate: 1 }; + stream.files.createIndex(index, { background: false }, (error?: AnyError) => { + if (error) { + return callback(error); + } + + checkChunksIndex(stream, callback); + }); + return; + } + return callback(error); + } + + let hasFileIndex = false; + if (indexes) { + indexes.forEach((index: Document) => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + } + + if (hasFileIndex) { + checkChunksIndex(stream, callback); + } else { + index = { filename: 1, uploadDate: 1 }; + + const writeConcernOptions = getWriteOptions(stream); + + stream.files.createIndex( + index, + { + ...writeConcernOptions, + background: false + }, + (error?: AnyError) => { + if (error) { + return callback(error); + } + + checkChunksIndex(stream, callback); + } + ); + } + }); + }); +} + +function createFilesDoc( + _id: ObjectId, + length: number, + chunkSize: number, + filename: string, + contentType?: string, + aliases?: string[], + metadata?: Document +): GridFSFile { + const ret: GridFSFile = { + _id, + length, + chunkSize, + uploadDate: new Date(), + filename + }; + + if (contentType) { + ret.contentType = contentType; + } + + if (aliases) { + ret.aliases = aliases; + } + + if (metadata) { + ret.metadata = metadata; + } + + return ret; +} + +function doWrite( + stream: GridFSBucketWriteStream, + chunk: Buffer | string, + encoding?: BufferEncoding, + callback?: Callback +): boolean { + if (checkAborted(stream, callback)) { + return false; + } + + const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + + stream.length += inputBuf.length; + + // Input is small enough to fit in our buffer + if (stream.pos + inputBuf.length < stream.chunkSizeBytes) { + inputBuf.copy(stream.bufToStore, stream.pos); + stream.pos += inputBuf.length; + + callback && callback(); + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + let inputBufRemaining = inputBuf.length; + let spaceRemaining: number = stream.chunkSizeBytes - stream.pos; + let numToCopy = Math.min(spaceRemaining, inputBuf.length); + let outstandingRequests = 0; + while (inputBufRemaining > 0) { + const inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy); + stream.pos += numToCopy; + spaceRemaining -= numToCopy; + let doc: GridFSChunk; + if (spaceRemaining === 0) { + doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore)); + ++stream.state.outstandingRequests; + ++outstandingRequests; + + if (checkAborted(stream, callback)) { + return false; + } + + stream.chunks.insertOne(doc, getWriteOptions(stream), (error?: AnyError) => { + if (error) { + return __handleError(stream, error); + } + --stream.state.outstandingRequests; + --outstandingRequests; + + if (!outstandingRequests) { + stream.emit('drain', doc); + callback && callback(); + checkDone(stream); + } + }); + + spaceRemaining = stream.chunkSizeBytes; + stream.pos = 0; + ++stream.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} + +function getWriteOptions(stream: GridFSBucketWriteStream): WriteConcernOptions { + const obj: WriteConcernOptions = {}; + if (stream.writeConcern) { + obj.writeConcern = { + w: stream.writeConcern.w, + wtimeout: stream.writeConcern.wtimeout, + j: stream.writeConcern.j + }; + } + return obj; +} + +function waitForIndexes( + stream: GridFSBucketWriteStream, + callback: (res: boolean) => boolean +): boolean { + if (stream.bucket.s.checkedIndexes) { + return callback(false); + } + + stream.bucket.once('index', () => { + callback(true); + }); + + return true; +} + +function writeRemnant(stream: GridFSBucketWriteStream, callback?: Callback): boolean { + // Buffer is empty, so don't bother to insert + if (stream.pos === 0) { + return checkDone(stream, callback); + } + + ++stream.state.outstandingRequests; + + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + const remnant = Buffer.alloc(stream.pos); + stream.bufToStore.copy(remnant, 0, 0, stream.pos); + const doc = createChunkDoc(stream.id, stream.n, remnant); + + // If the stream was aborted, do not write remnant + if (checkAborted(stream, callback)) { + return false; + } + + stream.chunks.insertOne(doc, getWriteOptions(stream), (error?: AnyError) => { + if (error) { + return __handleError(stream, error); + } + --stream.state.outstandingRequests; + checkDone(stream); + }); + return true; +} + +function checkAborted(stream: GridFSBucketWriteStream, callback?: Callback): boolean { + if (stream.state.aborted) { + if (typeof callback === 'function') { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosedError + callback(new MongoAPIError('Stream has been aborted')); + } + return true; + } + return false; +} diff --git a/node_modules/mongodb/src/index.ts b/node_modules/mongodb/src/index.ts new file mode 100644 index 0000000..4a80f64 --- /dev/null +++ b/node_modules/mongodb/src/index.ts @@ -0,0 +1,435 @@ +import { AbstractCursor } from './cursor/abstract_cursor'; +import { AggregationCursor } from './cursor/aggregation_cursor'; +import { FindCursor } from './cursor/find_cursor'; +import { ListIndexesCursor } from './operations/indexes'; +import { ListCollectionsCursor } from './operations/list_collections'; +import { PromiseProvider } from './promise_provider'; +import { Admin } from './admin'; +import { MongoClient } from './mongo_client'; +import { Db } from './db'; +import { Collection } from './collection'; +import { Logger } from './logger'; +import { GridFSBucket } from './gridfs'; +import { CancellationToken } from './mongo_types'; + +export { + Binary, + Code, + DBRef, + Double, + Int32, + Long, + MinKey, + MaxKey, + ObjectId, + Timestamp, + Decimal128, + BSONRegExp, + BSONSymbol, + Map +} from './bson'; + +import { ObjectId } from 'bson'; +/** + * @public + * @deprecated Please use `ObjectId` + */ +export const ObjectID = ObjectId; + +export { + MongoError, + MongoServerError, + MongoDriverError, + MongoAPIError, + MongoCompatibilityError, + MongoInvalidArgumentError, + MongoMissingCredentialsError, + MongoMissingDependencyError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoSystemError, + MongoServerSelectionError, + MongoParseError, + MongoWriteConcernError, + MongoRuntimeError, + MongoChangeStreamError, + MongoGridFSStreamError, + MongoGridFSChunkError, + MongoDecompressionError, + MongoBatchReExecutionError, + MongoCursorExhaustedError, + MongoCursorInUseError, + MongoNotConnectedError, + MongoExpiredSessionError, + MongoTransactionError, + MongoKerberosError, + MongoServerClosedError, + MongoTopologyClosedError +} from './error'; +export { MongoBulkWriteError, BulkWriteOptions, AnyBulkWriteOperation } from './bulk/common'; +export { + // Utils + PromiseProvider as Promise, + // Actual driver classes exported + Admin, + MongoClient, + Db, + Collection, + Logger, + AbstractCursor, + AggregationCursor, + FindCursor, + ListIndexesCursor, + ListCollectionsCursor, + GridFSBucket, + CancellationToken +}; + +// enums +export { ProfilingLevel } from './operations/set_profiling_level'; +export { ServerType, TopologyType } from './sdam/common'; +export { LoggerLevel } from './logger'; +export { AutoEncryptionLoggerLevel } from './deps'; +export { BatchType } from './bulk/common'; +export { AuthMechanism } from './cmap/auth/defaultAuthProviders'; +export { CURSOR_FLAGS } from './cursor/abstract_cursor'; +export { Compressor } from './cmap/wire_protocol/compression'; +export { ReturnDocument } from './operations/find_and_modify'; +export { ExplainVerbosity } from './explain'; +export { ReadConcernLevel } from './read_concern'; +export { ReadPreferenceMode } from './read_preference'; +export { ServerApiVersion } from './mongo_client'; +export { BSONType } from './mongo_types'; + +// Helper classes +export { WriteConcern } from './write_concern'; +export { ReadConcern } from './read_concern'; +export { ReadPreference } from './read_preference'; + +// events +export { + CommandStartedEvent, + CommandSucceededEvent, + CommandFailedEvent +} from './cmap/command_monitoring_events'; +export { + ConnectionCheckOutFailedEvent, + ConnectionCheckOutStartedEvent, + ConnectionCheckedInEvent, + ConnectionCheckedOutEvent, + ConnectionClosedEvent, + ConnectionCreatedEvent, + ConnectionPoolClearedEvent, + ConnectionPoolClosedEvent, + ConnectionPoolCreatedEvent, + ConnectionPoolMonitoringEvent, + ConnectionReadyEvent +} from './cmap/connection_pool_events'; +export { + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent, + ServerHeartbeatFailedEvent, + ServerClosedEvent, + ServerDescriptionChangedEvent, + ServerOpeningEvent, + TopologyClosedEvent, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent +} from './sdam/events'; +export { SrvPollingEvent } from './sdam/srv_polling'; + +// type only exports below, these are removed from emitted JS +export type { AdminPrivate } from './admin'; +export type { Document, BSONSerializeOptions } from './bson'; +export type { + InsertOneModel, + ReplaceOneModel, + UpdateOneModel, + UpdateManyModel, + DeleteOneModel, + DeleteManyModel, + BulkResult, + BulkWriteResult, + WriteError, + WriteConcernError, + BulkWriteOperationError +} from './bulk/common'; +export type { + ChangeStream, + ChangeStreamDocument, + UpdateDescription, + ChangeStreamEvents, + ChangeStreamOptions, + ChangeStreamCursor, + ResumeToken, + PipeOptions, + ChangeStreamCursorOptions, + OperationTime, + ResumeOptions +} from './change_stream'; +export type { + MongoCredentials, + AuthMechanismProperties, + MongoCredentialsOptions +} from './cmap/auth/mongo_credentials'; +export type { + WriteProtocolMessageType, + Query, + GetMore, + Msg, + KillCursor, + OpGetMoreOptions, + OpQueryOptions +} from './cmap/commands'; +export type { Stream, LEGAL_TLS_SOCKET_OPTIONS, LEGAL_TCP_SOCKET_OPTIONS } from './cmap/connect'; +export type { + Connection, + ConnectionOptions, + DestroyOptions, + CommandOptions, + QueryOptions, + GetMoreOptions, + ConnectionEvents +} from './cmap/connection'; +export type { ConnectionPoolMetrics } from './cmap/metrics'; +export type { + CloseOptions, + ConnectionPoolOptions, + WaitQueueMember, + WithConnectionCallback, + ConnectionPool, + ConnectionPoolEvents +} from './cmap/connection_pool'; +export type { + OperationDescription, + MessageStream, + MessageStreamOptions +} from './cmap/message_stream'; +export type { StreamDescription, StreamDescriptionOptions } from './cmap/stream_description'; +export type { CompressorName } from './cmap/wire_protocol/compression'; +export type { CollectionPrivate, CollectionOptions, ModifyResult } from './collection'; +export type { AggregationCursorOptions } from './cursor/aggregation_cursor'; +export type { + CursorCloseOptions, + CursorStreamOptions, + AbstractCursorOptions, + AbstractCursorEvents, + CursorFlag +} from './cursor/abstract_cursor'; +export type { DbPrivate, DbOptions } from './db'; +export type { AutoEncryptionOptions, AutoEncrypter } from './deps'; +export type { AnyError, ErrorDescription, MongoNetworkErrorOptions } from './error'; +export type { Explain, ExplainOptions, ExplainVerbosityLike } from './explain'; +export type { + GridFSBucketReadStream, + GridFSBucketReadStreamOptions, + GridFSBucketReadStreamOptionsWithRevision, + GridFSBucketReadStreamPrivate, + GridFSFile +} from './gridfs/download'; +export type { GridFSBucketOptions, GridFSBucketPrivate, GridFSBucketEvents } from './gridfs/index'; +export type { + GridFSBucketWriteStreamOptions, + GridFSBucketWriteStream, + GridFSChunk +} from './gridfs/upload'; +export type { LoggerOptions, LoggerFunction } from './logger'; +export type { + MongoClientEvents, + MongoClientPrivate, + MongoClientOptions, + WithSessionCallback, + PkFactory, + Auth, + DriverInfo, + MongoOptions, + ServerApi, + SupportedNodeConnectionOptions, + SupportedTLSConnectionOptions, + SupportedTLSSocketOptions, + SupportedSocketOptions +} from './mongo_client'; +export type { + TypedEventEmitter, + EventsDescription, + CommonEvents, + GenericListener +} from './mongo_types'; +export type { AddUserOptions, RoleSpecification } from './operations/add_user'; +export type { + AggregateOptions, + AggregateOperation, + DB_AGGREGATE_COLLECTION +} from './operations/aggregate'; +export type { MONGO_CLIENT_EVENTS } from './operations/connect'; +export type { + CommandOperationOptions, + OperationParent, + CommandOperation, + CollationOptions +} from './operations/command'; +export type { IndexInformationOptions } from './operations/common_functions'; +export type { CountOptions } from './operations/count'; +export type { CountDocumentsOptions } from './operations/count_documents'; +export type { + CreateCollectionOptions, + TimeSeriesCollectionOptions +} from './operations/create_collection'; +export type { DeleteOptions, DeleteResult, DeleteStatement } from './operations/delete'; +export type { DistinctOptions } from './operations/distinct'; +export type { DropCollectionOptions, DropDatabaseOptions } from './operations/drop'; +export type { EstimatedDocumentCountOptions } from './operations/estimated_document_count'; +export type { EvalOptions } from './operations/eval'; +export type { FindOptions } from './operations/find'; +export type { Sort, SortDirection, SortDirectionForCmd, SortForCmd } from './sort'; +export type { + FindOneAndDeleteOptions, + FindOneAndReplaceOptions, + FindOneAndUpdateOptions +} from './operations/find_and_modify'; +export type { + IndexSpecification, + CreateIndexesOptions, + IndexDescription, + DropIndexesOptions, + ListIndexesOptions, + IndexDirection +} from './operations/indexes'; +export type { InsertOneResult, InsertOneOptions, InsertManyResult } from './operations/insert'; +export type { ListCollectionsOptions, CollectionInfo } from './operations/list_collections'; +export type { ListDatabasesResult, ListDatabasesOptions } from './operations/list_databases'; +export type { + MapFunction, + ReduceFunction, + MapReduceOptions, + FinalizeFunction +} from './operations/map_reduce'; +export type { Hint, OperationOptions, AbstractOperation } from './operations/operation'; +export type { ProfilingLevelOptions } from './operations/profiling_level'; +export type { RemoveUserOptions } from './operations/remove_user'; +export type { RenameOptions } from './operations/rename'; +export type { RunCommandOptions } from './operations/run_command'; +export type { SetProfilingLevelOptions } from './operations/set_profiling_level'; +export type { + CollStatsOptions, + DbStatsOptions, + CollStats, + WiredTigerData +} from './operations/stats'; +export type { + UpdateResult, + UpdateOptions, + ReplaceOptions, + UpdateStatement +} from './operations/update'; +export type { ValidateCollectionOptions } from './operations/validate_collection'; +export type { ReadConcernLike } from './read_concern'; +export type { + ReadPreferenceLike, + ReadPreferenceOptions, + ReadPreferenceLikeOptions, + ReadPreferenceFromOptions, + HedgeOptions +} from './read_preference'; +export type { ClusterTime, TimerQueue } from './sdam/common'; +export type { + Monitor, + MonitorEvents, + MonitorPrivate, + MonitorOptions, + RTTPinger, + RTTPingerOptions +} from './sdam/monitor'; +export type { Server, ServerEvents, ServerPrivate, ServerOptions } from './sdam/server'; +export type { + TopologyVersion, + TagSet, + ServerDescription, + ServerDescriptionOptions +} from './sdam/server_description'; +export type { ServerSelector } from './sdam/server_selection'; +export type { SrvPoller, SrvPollerEvents, SrvPollerOptions } from './sdam/srv_polling'; +export type { + Topology, + TopologyEvents, + TopologyPrivate, + ServerSelectionRequest, + TopologyOptions, + ServerCapabilities, + ConnectOptions, + SelectServerOptions, + ServerSelectionCallback +} from './sdam/topology'; +export type { TopologyDescription, TopologyDescriptionOptions } from './sdam/topology_description'; +export type { + ClientSession, + ClientSessionEvents, + ClientSessionOptions, + EndSessionOptions, + ServerSessionPool, + ServerSession, + ServerSessionId, + WithTransactionCallback +} from './sessions'; +export type { TransactionOptions, Transaction, TxnState } from './transactions'; +export type { + Callback, + ClientMetadata, + ClientMetadataOptions, + MongoDBNamespace, + InterruptibleAsyncInterval, + BufferPool, + HostAddress, + EventEmitterWithState +} from './utils'; +export type { W, WriteConcernOptions, WriteConcernSettings } from './write_concern'; +export type { ExecutionResult } from './operations/execute_operation'; +export type { InternalAbstractCursorOptions } from './cursor/abstract_cursor'; +export type { + BulkOperationBase, + BulkOperationPrivate, + FindOperators, + Batch, + WriteConcernErrorData +} from './bulk/common'; +export type { OrderedBulkOperation } from './bulk/ordered'; +export type { UnorderedBulkOperation } from './bulk/unordered'; +export type { Encrypter, EncrypterOptions } from './encrypter'; +export type { + EnhancedOmit, + WithId, + OptionalId, + WithoutId, + UpdateFilter, + Filter, + Projection, + InferIdType, + ProjectionOperators, + Flatten, + SchemaMember, + Condition, + RootFilterOperators, + AlternativeType, + FilterOperators, + BSONTypeAlias, + BitwiseFilter, + RegExpOrString, + OnlyFieldsOfType, + NumericType, + IntegerType, + MatchKeysAndValues, + SetFields, + PullOperator, + PushOperator, + PullAllOperator, + AcceptedFields, + NotAcceptedFields, + AddToSetOperators, + ArrayOperator, + FilterOperations, + KeysOfAType, + KeysOfOtherType, + IsAny, + OneOrMore +} from './mongo_types'; +export type { serialize, deserialize } from './bson'; diff --git a/node_modules/mongodb/src/logger.ts b/node_modules/mongodb/src/logger.ts new file mode 100644 index 0000000..e515402 --- /dev/null +++ b/node_modules/mongodb/src/logger.ts @@ -0,0 +1,264 @@ +import { format } from 'util'; +import { enumToString } from './utils'; +import { MongoInvalidArgumentError } from './error'; + +// Filters for classes +const classFilters: any = {}; +let filteredClasses: any = {}; +let level: LoggerLevel; + +// Save the process id +const pid = process.pid; + +// current logger +// eslint-disable-next-line no-console +let currentLogger: LoggerFunction = console.warn; + +/** @public */ +export const LoggerLevel = Object.freeze({ + ERROR: 'error', + WARN: 'warn', + INFO: 'info', + DEBUG: 'debug', + error: 'error', + warn: 'warn', + info: 'info', + debug: 'debug' +} as const); + +/** @public */ +export type LoggerLevel = typeof LoggerLevel[keyof typeof LoggerLevel]; + +/** @public */ +export type LoggerFunction = (message?: any, ...optionalParams: any[]) => void; + +/** @public */ +export interface LoggerOptions { + logger?: LoggerFunction; + loggerLevel?: LoggerLevel; +} + +/** + * @public + */ +export class Logger { + className: string; + + /** + * Creates a new Logger instance + * + * @param className - The Class name associated with the logging instance + * @param options - Optional logging settings + */ + constructor(className: string, options?: LoggerOptions) { + options = options ?? {}; + + // Current reference + this.className = className; + + // Current logger + if (!(options.logger instanceof Logger) && typeof options.logger === 'function') { + currentLogger = options.logger; + } + + // Set level of logging, default is error + if (options.loggerLevel) { + level = options.loggerLevel || LoggerLevel.ERROR; + } + + // Add all class names + if (filteredClasses[this.className] == null) { + classFilters[this.className] = true; + } + } + + /** + * Log a message at the debug level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + debug(message: string, object?: unknown): void { + if ( + this.isDebug() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + const dateTime = new Date().getTime(); + const msg = format('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); + const state = { + type: LoggerLevel.DEBUG, + message, + className: this.className, + pid, + date: dateTime + } as any; + + if (object) state.meta = object; + currentLogger(msg, state); + } + } + + /** + * Log a message at the warn level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + warn(message: string, object?: unknown): void { + if ( + this.isWarn() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + const dateTime = new Date().getTime(); + const msg = format('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); + const state = { + type: LoggerLevel.WARN, + message, + className: this.className, + pid, + date: dateTime + } as any; + + if (object) state.meta = object; + currentLogger(msg, state); + } + } + + /** + * Log a message at the info level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + info(message: string, object?: unknown): void { + if ( + this.isInfo() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + const dateTime = new Date().getTime(); + const msg = format('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); + const state = { + type: LoggerLevel.INFO, + message, + className: this.className, + pid, + date: dateTime + } as any; + + if (object) state.meta = object; + currentLogger(msg, state); + } + } + + /** + * Log a message at the error level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + error(message: string, object?: unknown): void { + if ( + this.isError() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + const dateTime = new Date().getTime(); + const msg = format('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); + const state = { + type: LoggerLevel.ERROR, + message, + className: this.className, + pid, + date: dateTime + } as any; + + if (object) state.meta = object; + currentLogger(msg, state); + } + } + + /** Is the logger set at info level */ + isInfo(): boolean { + return level === LoggerLevel.INFO || level === LoggerLevel.DEBUG; + } + + /** Is the logger set at error level */ + isError(): boolean { + return level === LoggerLevel.ERROR || level === LoggerLevel.INFO || level === LoggerLevel.DEBUG; + } + + /** Is the logger set at error level */ + isWarn(): boolean { + return ( + level === LoggerLevel.ERROR || + level === LoggerLevel.WARN || + level === LoggerLevel.INFO || + level === LoggerLevel.DEBUG + ); + } + + /** Is the logger set at debug level */ + isDebug(): boolean { + return level === LoggerLevel.DEBUG; + } + + /** Resets the logger to default settings, error and no filtered classes */ + static reset(): void { + level = LoggerLevel.ERROR; + filteredClasses = {}; + } + + /** Get the current logger function */ + static currentLogger(): LoggerFunction { + return currentLogger; + } + + /** + * Set the current logger function + * + * @param logger - Custom logging function + */ + static setCurrentLogger(logger: LoggerFunction): void { + if (typeof logger !== 'function') { + throw new MongoInvalidArgumentError('Current logger must be a function'); + } + + currentLogger = logger; + } + + /** + * Filter log messages for a particular class + * + * @param type - The type of filter (currently only class) + * @param values - The filters to apply + */ + static filter(type: string, values: string[]): void { + if (type === 'class' && Array.isArray(values)) { + filteredClasses = {}; + values.forEach(x => (filteredClasses[x] = true)); + } + } + + /** + * Set the current log level + * + * @param newLevel - Set current log level (debug, warn, info, error) + */ + static setLevel(newLevel: LoggerLevel): void { + if ( + newLevel !== LoggerLevel.INFO && + newLevel !== LoggerLevel.ERROR && + newLevel !== LoggerLevel.DEBUG && + newLevel !== LoggerLevel.WARN + ) { + throw new MongoInvalidArgumentError( + `Argument "newLevel" should be one of ${enumToString(LoggerLevel)}` + ); + } + + level = newLevel; + } +} diff --git a/node_modules/mongodb/src/mongo_client.ts b/node_modules/mongodb/src/mongo_client.ts new file mode 100644 index 0000000..b57563f --- /dev/null +++ b/node_modules/mongodb/src/mongo_client.ts @@ -0,0 +1,699 @@ +import { Db, DbOptions } from './db'; +import { ChangeStream, ChangeStreamOptions } from './change_stream'; +import type { ReadPreference, ReadPreferenceMode } from './read_preference'; +import { + AnyError, + MongoRuntimeError, + MongoInvalidArgumentError, + MongoNotConnectedError +} from './error'; +import type { W, WriteConcern } from './write_concern'; +import { + maybePromise, + MongoDBNamespace, + Callback, + resolveOptions, + ClientMetadata, + ns, + HostAddress +} from './utils'; +import { connect, MONGO_CLIENT_EVENTS } from './operations/connect'; +import { PromiseProvider } from './promise_provider'; +import type { Logger, LoggerLevel } from './logger'; +import type { ReadConcern, ReadConcernLevel, ReadConcernLike } from './read_concern'; +import { BSONSerializeOptions, Document, resolveBSONOptions } from './bson'; +import type { AutoEncrypter, AutoEncryptionOptions } from './deps'; +import type { AuthMechanism } from './cmap/auth/defaultAuthProviders'; +import type { Topology, TopologyEvents } from './sdam/topology'; +import type { ClientSession, ClientSessionOptions } from './sessions'; +import type { TagSet } from './sdam/server_description'; +import type { AuthMechanismProperties, MongoCredentials } from './cmap/auth/mongo_credentials'; +import { parseOptions } from './connection_string'; +import type { CompressorName } from './cmap/wire_protocol/compression'; +import type { TLSSocketOptions, ConnectionOptions as TLSConnectionOptions } from 'tls'; +import type { TcpNetConnectOpts } from 'net'; +import type { SrvPoller } from './sdam/srv_polling'; +import type { Connection } from './cmap/connection'; +import type { LEGAL_TLS_SOCKET_OPTIONS, LEGAL_TCP_SOCKET_OPTIONS } from './cmap/connect'; +import type { Encrypter } from './encrypter'; +import { TypedEventEmitter } from './mongo_types'; + +/** @public */ +export const ServerApiVersion = Object.freeze({ + v1: '1' +} as const); + +/** @public */ +export type ServerApiVersion = typeof ServerApiVersion[keyof typeof ServerApiVersion]; + +/** @public */ +export interface ServerApi { + version: ServerApiVersion; + strict?: boolean; + deprecationErrors?: boolean; +} + +/** @public */ +export interface DriverInfo { + name?: string; + version?: string; + platform?: string; +} + +/** @public */ +export interface Auth { + /** The username for auth */ + username?: string; + /** The password for auth */ + password?: string; +} + +/** @public */ +export interface PkFactory { + createPk(): any; // TODO: when js-bson is typed, function should return some BSON type +} + +type CleanUpHandlerFunction = (err?: AnyError, result?: any, opts?: any) => Promise; + +/** @public */ +export type SupportedTLSConnectionOptions = Pick< + TLSConnectionOptions, + Extract +>; + +/** @public */ +export type SupportedTLSSocketOptions = Pick< + TLSSocketOptions, + Extract +>; + +/** @public */ +export type SupportedSocketOptions = Pick< + TcpNetConnectOpts, + typeof LEGAL_TCP_SOCKET_OPTIONS[number] +>; + +/** @public */ +export type SupportedNodeConnectionOptions = SupportedTLSConnectionOptions & + SupportedTLSSocketOptions & + SupportedSocketOptions; + +/** + * Describes all possible URI query options for the mongo client + * @public + * @see https://docs.mongodb.com/manual/reference/connection-string + */ +export interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeConnectionOptions { + /** Specifies the name of the replica set, if the mongod is a member of a replica set. */ + replicaSet?: string; + /** Enables or disables TLS/SSL for the connection. */ + tls?: boolean; + /** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */ + ssl?: boolean; + /** Specifies the location of a local TLS Certificate */ + tlsCertificateFile?: string; + /** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key or only the client's TLS/SSL key when tlsCertificateFile is used to provide the certificate. */ + tlsCertificateKeyFile?: string; + /** Specifies the password to de-crypt the tlsCertificateKeyFile. */ + tlsCertificateKeyFilePassword?: string; + /** Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance. */ + tlsCAFile?: string; + /** Bypasses validation of the certificates presented by the mongod/mongos instance */ + tlsAllowInvalidCertificates?: boolean; + /** Disables hostname validation of the certificate presented by the mongod/mongos instance. */ + tlsAllowInvalidHostnames?: boolean; + /** Disables various certificate validations. */ + tlsInsecure?: boolean; + /** The time in milliseconds to attempt a connection before timing out. */ + connectTimeoutMS?: number; + /** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */ + socketTimeoutMS?: number; + /** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */ + compressors?: CompressorName[] | string; + /** An integer that specifies the compression level if using zlib for network compression. */ + zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined; + /** The maximum number of connections in the connection pool. */ + maxPoolSize?: number; + /** The minimum number of connections in the connection pool. */ + minPoolSize?: number; + /** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */ + maxIdleTimeMS?: number; + /** The maximum time in milliseconds that a thread can wait for a connection to become available. */ + waitQueueTimeoutMS?: number; + /** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The level of isolation */ + readConcernLevel?: ReadConcernLevel; + /** Specifies the read preferences for this connection */ + readPreference?: ReadPreferenceMode | ReadPreference; + /** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */ + maxStalenessSeconds?: number; + /** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */ + readPreferenceTags?: TagSet[]; + /** The auth settings for when connection to server. */ + auth?: Auth; + /** Specify the database name associated with the user’s credentials. */ + authSource?: string; + /** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */ + authMechanism?: AuthMechanism; + /** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */ + authMechanismProperties?: AuthMechanismProperties; + /** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */ + localThresholdMS?: number; + /** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */ + serverSelectionTimeoutMS?: number; + /** heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one. */ + heartbeatFrequencyMS?: number; + /** Sets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort. */ + minHeartbeatFrequencyMS?: number; + /** The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections */ + appName?: string; + /** Enables retryable reads. */ + retryReads?: boolean; + /** Enable retryable writes. */ + retryWrites?: boolean; + /** Allow a driver to force a Single topology type with a connection string containing one host */ + directConnection?: boolean; + /** Instruct the driver it is connecting to a load balancer fronting a mongos like service */ + loadBalanced?: boolean; + + /** The write concern w value */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + + /** Validate mongod server certificate against Certificate Authority */ + sslValidate?: boolean; + /** SSL Certificate file path. */ + sslCA?: string; + /** SSL Certificate file path. */ + sslCert?: string; + /** SSL Key file file path. */ + sslKey?: string; + /** SSL Certificate pass phrase. */ + sslPass?: string; + /** SSL Certificate revocation list file path. */ + sslCRL?: string; + /** TCP Connection no delay */ + noDelay?: boolean; + /** TCP Connection keep alive enabled */ + keepAlive?: boolean; + /** The number of milliseconds to wait before initiating keepAlive on the TCP socket */ + keepAliveInitialDelay?: number; + /** Force server to assign `_id` values instead of driver */ + forceServerObjectId?: boolean; + /** Return document results as raw BSON buffers */ + raw?: boolean; + /** A primary key factory function for generation of custom `_id` keys */ + pkFactory?: PkFactory; + /** A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible */ + promiseLibrary?: any; + /** The logging level */ + loggerLevel?: LoggerLevel; + /** Custom logger object */ + logger?: Logger; + /** Enable command monitoring for this client */ + monitorCommands?: boolean; + /** Server API version */ + serverApi?: ServerApi | ServerApiVersion; + /** + * Optionally enable client side auto encryption + * + * @remarks + * Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error + * (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts. + * + * Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://docs.mongodb.com/manual/reference/command/listCollections/#dbcmd.listCollections). + * + * If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true: + * - AutoEncryptionOptions.keyVaultClient is not passed. + * - AutoEncryptionOptions.bypassAutomaticEncryption is false. + * + * If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted. + */ + autoEncryption?: AutoEncryptionOptions; + /** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */ + driverInfo?: DriverInfo; + + /** @internal */ + srvPoller?: SrvPoller; + /** @internal */ + connectionType?: typeof Connection; +} + +/** @public */ +export type WithSessionCallback = (session: ClientSession) => Promise | void; + +/** @internal */ +export interface MongoClientPrivate { + url: string; + sessions: Set; + bsonOptions: BSONSerializeOptions; + namespace: MongoDBNamespace; + readonly options?: MongoOptions; + readonly readConcern?: ReadConcern; + readonly writeConcern?: WriteConcern; + readonly readPreference: ReadPreference; + readonly logger: Logger; +} + +/** @public */ +export type MongoClientEvents = Pick & { + // In previous versions the open event emitted a topology, in an effort to no longer + // expose internals but continue to expose this useful event API, it now emits a mongoClient + open(mongoClient: MongoClient): void; +}; + +/** @internal */ +const kOptions = Symbol('options'); + +/** + * The **MongoClient** class is a class that allows for making Connections to MongoDB. + * @public + * + * @remarks + * The programmatically provided options take precedent over the URI options. + * + * @example + * ```js + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + * + * @example + * ```js + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + */ +export class MongoClient extends TypedEventEmitter { + /** @internal */ + s: MongoClientPrivate; + /** @internal */ + topology?: Topology; + + /** + * The consolidate, parsed, transformed and merged options. + * @internal + */ + [kOptions]: MongoOptions; + + constructor(url: string, options?: MongoClientOptions) { + super(); + + this[kOptions] = parseOptions(url, this, options); + + // eslint-disable-next-line @typescript-eslint/no-this-alias + const client = this; + + // The internal state + this.s = { + url, + sessions: new Set(), + bsonOptions: resolveBSONOptions(this[kOptions]), + namespace: ns('admin'), + + get options() { + return client[kOptions]; + }, + get readConcern() { + return client[kOptions].readConcern; + }, + get writeConcern() { + return client[kOptions].writeConcern; + }, + get readPreference() { + return client[kOptions].readPreference; + }, + get logger() { + return client[kOptions].logger; + } + }; + } + + get options(): Readonly { + return Object.freeze({ ...this[kOptions] }); + } + + get serverApi(): Readonly { + return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi }); + } + /** + * Intended for APM use only + * @internal + */ + get monitorCommands(): boolean { + return this[kOptions].monitorCommands; + } + set monitorCommands(value: boolean) { + this[kOptions].monitorCommands = value; + } + + get autoEncrypter(): AutoEncrypter | undefined { + return this[kOptions].autoEncrypter; + } + + get readConcern(): ReadConcern | undefined { + return this.s.readConcern; + } + + get writeConcern(): WriteConcern | undefined { + return this.s.writeConcern; + } + + get readPreference(): ReadPreference { + return this.s.readPreference; + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + get logger(): Logger { + return this.s.logger; + } + + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + connect(): Promise; + connect(callback: Callback): void; + connect(callback?: Callback): Promise | void { + if (callback && typeof callback !== 'function') { + throw new MongoInvalidArgumentError('Method `connect` only accepts a callback'); + } + + return maybePromise(callback, cb => { + connect(this, this[kOptions], err => { + if (err) return cb(err); + cb(undefined, this); + }); + }); + } + + /** + * Close the db and its underlying connections + * + * @param force - Force close, emitting no events + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + close(): Promise; + close(callback: Callback): void; + close(force: boolean): Promise; + close(force: boolean, callback: Callback): void; + close( + forceOrCallback?: boolean | Callback, + callback?: Callback + ): Promise | void { + if (typeof forceOrCallback === 'function') { + callback = forceOrCallback; + } + + const force = typeof forceOrCallback === 'boolean' ? forceOrCallback : false; + + return maybePromise(callback, callback => { + if (this.topology == null) { + return callback(); + } + + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + + topology.close({ force }, error => { + if (error) return callback(error); + const { encrypter } = this[kOptions]; + if (encrypter) { + return encrypter.close(this, force, error => { + callback(error); + }); + } + callback(); + }); + }); + } + + /** + * Create a new Db instance sharing the current socket connections. + * + * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. + * @param options - Optional settings for Db construction + */ + db(dbName?: string, options?: DbOptions): Db { + options = options ?? {}; + + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.options.dbName; + } + + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this[kOptions], options); + + // Return the db object + const db = new Db(this, dbName, finalOptions); + + // Return the database + return db; + } + + /** + * Connect to MongoDB using a url + * + * @remarks + * The programmatically provided options take precedent over the URI options. + * + * @see https://docs.mongodb.org/manual/reference/connection-string/ + */ + static connect(url: string): Promise; + static connect(url: string, callback: Callback): void; + static connect(url: string, options: MongoClientOptions): Promise; + static connect(url: string, options: MongoClientOptions, callback: Callback): void; + static connect( + url: string, + options?: MongoClientOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + try { + // Create client + const mongoClient = new MongoClient(url, options); + // Execute the connect method + if (callback) { + return mongoClient.connect(callback); + } else { + return mongoClient.connect(); + } + } catch (error) { + if (callback) return callback(error); + else return PromiseProvider.get().reject(error); + } + } + + /** Starts a new session on the server */ + startSession(): ClientSession; + startSession(options: ClientSessionOptions): ClientSession; + startSession(options?: ClientSessionOptions): ClientSession { + options = Object.assign({ explicit: true }, options); + if (!this.topology) { + throw new MongoNotConnectedError('MongoClient must be connected to start a session'); + } + + return this.topology.startSession(options, this.s.options); + } + + /** + * Runs a given operation with an implicitly created session. The lifetime of the session + * will be handled without the need for user interaction. + * + * NOTE: presently the operation MUST return a Promise (either explicit or implicitly as an async function) + * + * @param options - Optional settings for the command + * @param callback - An callback to execute with an implicitly created session + */ + withSession(callback: WithSessionCallback): Promise; + withSession(options: ClientSessionOptions, callback: WithSessionCallback): Promise; + withSession( + optionsOrOperation?: ClientSessionOptions | WithSessionCallback, + callback?: WithSessionCallback + ): Promise { + let options: ClientSessionOptions = optionsOrOperation as ClientSessionOptions; + if (typeof optionsOrOperation === 'function') { + callback = optionsOrOperation as WithSessionCallback; + options = { owner: Symbol() }; + } + + if (callback == null) { + throw new MongoInvalidArgumentError('Missing required callback parameter'); + } + + const session = this.startSession(options); + const Promise = PromiseProvider.get(); + + let cleanupHandler: CleanUpHandlerFunction = ((err, result, opts) => { + // prevent multiple calls to cleanupHandler + cleanupHandler = () => { + // TODO(NODE-3483) + throw new MongoRuntimeError('cleanupHandler was called too many times'); + }; + + opts = Object.assign({ throw: true }, opts); + session.endSession(); + + if (err) { + if (opts.throw) throw err; + return Promise.reject(err); + } + }) as CleanUpHandlerFunction; + + try { + const result = callback(session); + return Promise.resolve(result).then( + result => cleanupHandler(undefined, result, undefined), + err => cleanupHandler(err, null, { throw: true }) + ); + } catch (err) { + return cleanupHandler(err, null, { throw: false }) as Promise; + } + } + + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this cluster. Will ignore all + * changes to system collections, as well as the local, admin, and config databases. + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + */ + watch( + pipeline: Document[] = [], + options: ChangeStreamOptions = {} + ): ChangeStream { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, resolveOptions(this, options)); + } + + /** Return the mongo client logger */ + getLogger(): Logger { + return this.s.logger; + } +} + +/** + * Mongo Client Options + * @public + */ +export interface MongoOptions + extends Required< + Pick< + MongoClientOptions, + | 'autoEncryption' + | 'connectTimeoutMS' + | 'directConnection' + | 'driverInfo' + | 'forceServerObjectId' + | 'minHeartbeatFrequencyMS' + | 'heartbeatFrequencyMS' + | 'keepAlive' + | 'keepAliveInitialDelay' + | 'localThresholdMS' + | 'logger' + | 'maxIdleTimeMS' + | 'maxPoolSize' + | 'minPoolSize' + | 'monitorCommands' + | 'noDelay' + | 'pkFactory' + | 'promiseLibrary' + | 'raw' + | 'replicaSet' + | 'retryReads' + | 'retryWrites' + | 'serverSelectionTimeoutMS' + | 'socketTimeoutMS' + | 'tlsAllowInvalidCertificates' + | 'tlsAllowInvalidHostnames' + | 'tlsInsecure' + | 'waitQueueTimeoutMS' + | 'zlibCompressionLevel' + > + >, + SupportedNodeConnectionOptions { + hosts: HostAddress[]; + srvHost?: string; + credentials?: MongoCredentials; + readPreference: ReadPreference; + readConcern: ReadConcern; + loadBalanced: boolean; + serverApi: ServerApi; + compressors: CompressorName[]; + writeConcern: WriteConcern; + dbName: string; + metadata: ClientMetadata; + autoEncrypter?: AutoEncrypter; + /** @internal */ + connectionType?: typeof Connection; + + /** @internal */ + encrypter: Encrypter; + /** @internal */ + userSpecifiedAuthSource: boolean; + /** @internal */ + userSpecifiedReplicaSet: boolean; + + /** + * # NOTE ABOUT TLS Options + * + * If set TLS enabled, equivalent to setting the ssl option. + * + * ### Additional options: + * + * | nodejs option | MongoDB equivalent | type | + * |:---------------------|--------------------------------------------------------- |:---------------------------------------| + * | `ca` | `sslCA`, `tlsCAFile` | `string \| Buffer \| Buffer[]` | + * | `crl` | `sslCRL` | `string \| Buffer \| Buffer[]` | + * | `cert` | `sslCert`, `tlsCertificateFile`, `tlsCertificateKeyFile` | `string \| Buffer \| Buffer[]` | + * | `key` | `sslKey`, `tlsCertificateKeyFile` | `string \| Buffer \| KeyObject[]` | + * | `passphrase` | `sslPass`, `tlsCertificateKeyFilePassword` | `string` | + * | `rejectUnauthorized` | `sslValidate` | `boolean` | + * + */ + tls: boolean; + + /** + * Turn these options into a reusable connection URI + */ + toURI(): string; +} diff --git a/node_modules/mongodb/src/mongo_types.ts b/node_modules/mongodb/src/mongo_types.ts new file mode 100644 index 0000000..d4107e1 --- /dev/null +++ b/node_modules/mongodb/src/mongo_types.ts @@ -0,0 +1,427 @@ +import type { + Binary, + Document, + ObjectId, + BSONRegExp, + Timestamp, + Decimal128, + Double, + Int32, + Long +} from './bson'; +import { EventEmitter } from 'events'; +import type { Sort } from './sort'; + +/** @internal */ +export type TODO_NODE_3286 = any; + +/** Given an object shaped type, return the type of the _id field or default to ObjectId @public */ +export type InferIdType = TSchema extends { _id: infer IdType } // user has defined a type for _id + ? // eslint-disable-next-line @typescript-eslint/ban-types + {} extends IdType // TODO(NODE-3285): Improve type readability + ? // eslint-disable-next-line @typescript-eslint/ban-types + Exclude + : unknown extends IdType + ? ObjectId + : IdType + : ObjectId; // user has not defined _id on schema + +/** Add an _id field to an object shaped type @public */ +export type WithId = EnhancedOmit & { _id: InferIdType }; + +/** + * Add an optional _id field to an object shaped type + * @public + * + * @privateRemarks + * `ObjectId extends TSchema['_id']` is a confusing ordering at first glance. Rather than ask + * `TSchema['_id'] extends ObjectId` which translated to "Is the _id property ObjectId?" + * we instead ask "Does ObjectId look like (have the same shape) as the _id?" + */ +export type OptionalId = ObjectId extends TSchema['_id'] // a Schema with ObjectId _id type or "any" or "indexed type" provided + ? EnhancedOmit & { _id?: InferIdType } // a Schema provided but _id type is not ObjectId + : WithId; // TODO(NODE-3285): Improve type readability + +/** TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions @public */ +export type EnhancedOmit = string extends keyof TRecordOrUnion + ? TRecordOrUnion // TRecordOrUnion has indexed type e.g. { _id: string; [k: string]: any; } or it is "any" + : TRecordOrUnion extends any + ? Pick> // discriminated unions + : never; + +/** Remove the _id field from an object shaped type @public */ +export type WithoutId = Omit; + +/** A MongoDB filter can be some portion of the schema or a set of operators @public */ +export type Filter = { + [P in keyof TSchema]?: Condition; +} & + RootFilterOperators; + +/** @public */ +export type Condition = AlternativeType | FilterOperators>; + +/** + * It is possible to search using alternative types in mongodb e.g. + * string types can be searched using a regex in mongo + * array types can be searched using their element type + * @public + */ +export type AlternativeType = T extends ReadonlyArray + ? T | RegExpOrString + : RegExpOrString; + +/** @public */ +export type RegExpOrString = T extends string ? BSONRegExp | RegExp | T : T; + +/** @public */ +export interface RootFilterOperators extends Document { + $and?: Filter[]; + $nor?: Filter[]; + $or?: Filter[]; + $text?: { + $search: string; + $language?: string; + $caseSensitive?: boolean; + $diacriticSensitive?: boolean; + }; + $where?: string | ((this: TSchema) => boolean); + $comment?: string | Document; +} + +/** @public */ +export interface FilterOperators extends Document { + // Comparison + $eq?: TValue; + $gt?: TValue; + $gte?: TValue; + $in?: ReadonlyArray; + $lt?: TValue; + $lte?: TValue; + $ne?: TValue; + $nin?: ReadonlyArray; + // Logical + $not?: TValue extends string ? FilterOperators | RegExp : FilterOperators; + // Element + /** + * When `true`, `$exists` matches the documents that contain the field, + * including documents where the field value is null. + */ + $exists?: boolean; + $type?: BSONType | BSONTypeAlias; + // Evaluation + $expr?: Record; + $jsonSchema?: Record; + $mod?: TValue extends number ? [number, number] : never; + $regex?: TValue extends string ? RegExp | BSONRegExp | string : never; + $options?: TValue extends string ? string : never; + // Geospatial + $geoIntersects?: { $geometry: Document }; + $geoWithin?: Document; + $near?: Document; + $nearSphere?: Document; + $maxDistance?: number; + // Array + $all?: ReadonlyArray; + $elemMatch?: Document; + $size?: TValue extends ReadonlyArray ? number : never; + // Bitwise + $bitsAllClear?: BitwiseFilter; + $bitsAllSet?: BitwiseFilter; + $bitsAnyClear?: BitwiseFilter; + $bitsAnySet?: BitwiseFilter; + $rand?: Record; +} + +/** @public */ +export type BitwiseFilter = + | number /** numeric bit mask */ + | Binary /** BinData bit mask */ + | ReadonlyArray; /** `[ , , ... ]` */ + +/** @public */ +export const BSONType = Object.freeze({ + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: -1, + maxKey: 127 +} as const); + +/** @public */ +export type BSONType = typeof BSONType[keyof typeof BSONType]; +/** @public */ +export type BSONTypeAlias = keyof typeof BSONType; + +/** + * @public + * Projection is flexible to permit the wide array of aggregation operators + * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export type Projection = Document; + +/** + * @public + * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further + */ +export type ProjectionOperators = Document; + +/** @public */ +export type IsAny = true extends false & Type + ? ResultIfAny + : ResultIfNotAny; + +/** @public */ +export type Flatten = Type extends ReadonlyArray ? Item : Type; + +/** @public */ +export type SchemaMember = { [P in keyof T]?: V } | { [key: string]: V }; + +/** @public */ +export type IntegerType = number | Int32 | Long; + +/** @public */ +export type NumericType = IntegerType | Decimal128 | Double; + +/** @public */ +export type FilterOperations = T extends Record + ? { [key in keyof T]?: FilterOperators } + : FilterOperators; + +/** @public */ +export type KeysOfAType = { + [key in keyof TSchema]: NonNullable extends Type ? key : never; +}[keyof TSchema]; + +/** @public */ +export type KeysOfOtherType = { + [key in keyof TSchema]: NonNullable extends Type ? never : key; +}[keyof TSchema]; + +/** @public */ +export type AcceptedFields = { + readonly [key in KeysOfAType]?: AssignableType; +}; + +/** It avoids using fields with not acceptable types @public */ +export type NotAcceptedFields = { + readonly [key in KeysOfOtherType]?: never; +}; + +/** @public */ +export type OnlyFieldsOfType = IsAny< + TSchema[keyof TSchema], + Record, + AcceptedFields & + NotAcceptedFields & + Record +>; + +/** @public */ +export type MatchKeysAndValues = Readonly> & Record; + +/** @public */ +export type AddToSetOperators = { + $each?: Array>; +}; + +/** @public */ +export type ArrayOperator = { + $each?: Array>; + $slice?: number; + $position?: number; + $sort?: Sort; +}; + +/** @public */ +export type SetFields = ({ + readonly [key in KeysOfAType | undefined>]?: + | OptionalId> + | AddToSetOperators>>>; +} & + NotAcceptedFields | undefined>) & { + readonly [key: string]: AddToSetOperators | any; +}; + +/** @public */ +export type PushOperator = ({ + readonly [key in KeysOfAType>]?: + | Flatten + | ArrayOperator>>; +} & + NotAcceptedFields>) & { + readonly [key: string]: ArrayOperator | any; +}; + +/** @public */ +export type PullOperator = ({ + readonly [key in KeysOfAType>]?: + | Partial> + | FilterOperations>; +} & + NotAcceptedFields>) & { + readonly [key: string]: FilterOperators | any; +}; + +/** @public */ +export type PullAllOperator = ({ + readonly [key in KeysOfAType>]?: TSchema[key]; +} & + NotAcceptedFields>) & { + readonly [key: string]: ReadonlyArray; +}; + +/** @public */ +export type UpdateFilter = { + $currentDate?: OnlyFieldsOfType< + TSchema, + Date | Timestamp, + true | { $type: 'date' | 'timestamp' } + >; + $inc?: OnlyFieldsOfType; + $min?: MatchKeysAndValues; + $max?: MatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: MatchKeysAndValues; + $setOnInsert?: MatchKeysAndValues; + $unset?: OnlyFieldsOfType; + $addToSet?: SetFields; + $pop?: OnlyFieldsOfType, 1 | -1>; + $pull?: PullOperator; + $push?: PushOperator; + $pullAll?: PullAllOperator; + $bit?: OnlyFieldsOfType< + TSchema, + NumericType | undefined, + { and: IntegerType } | { or: IntegerType } | { xor: IntegerType } + >; +} & Document; + +/** @public */ +export type Nullable = AnyType | null | undefined; + +/** @public */ +export type OneOrMore = T | ReadonlyArray; + +/** @public */ +export type GenericListener = (...args: any[]) => void; + +/** + * Event description type + * @public + */ +export type EventsDescription = Record; + +/** @public */ +export type CommonEvents = 'newListener' | 'removeListener'; + +/** + * Typescript type safe event emitter + * @public + */ +export declare interface TypedEventEmitter extends EventEmitter { + addListener(event: EventKey, listener: Events[EventKey]): this; + addListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + addListener(event: string | symbol, listener: GenericListener): this; + + on(event: EventKey, listener: Events[EventKey]): this; + on( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + on(event: string | symbol, listener: GenericListener): this; + + once(event: EventKey, listener: Events[EventKey]): this; + once( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + once(event: string | symbol, listener: GenericListener): this; + + removeListener(event: EventKey, listener: Events[EventKey]): this; + removeListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + removeListener(event: string | symbol, listener: GenericListener): this; + + off(event: EventKey, listener: Events[EventKey]): this; + off( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + off(event: string | symbol, listener: GenericListener): this; + + removeAllListeners( + event?: EventKey | CommonEvents | symbol | string + ): this; + + listeners( + event: EventKey | CommonEvents | symbol | string + ): Events[EventKey][]; + + rawListeners( + event: EventKey | CommonEvents | symbol | string + ): Events[EventKey][]; + + emit( + event: EventKey | symbol, + ...args: Parameters + ): boolean; + + listenerCount( + type: EventKey | CommonEvents | symbol | string + ): number; + + prependListener(event: EventKey, listener: Events[EventKey]): this; + prependListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + prependListener(event: string | symbol, listener: GenericListener): this; + + prependOnceListener( + event: EventKey, + listener: Events[EventKey] + ): this; + prependOnceListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + prependOnceListener(event: string | symbol, listener: GenericListener): this; + + eventNames(): string[]; + getMaxListeners(): number; + setMaxListeners(n: number): this; +} + +/** + * Typescript type safe event emitter + * @public + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export class TypedEventEmitter extends EventEmitter {} + +/** @public */ +export class CancellationToken extends TypedEventEmitter<{ cancel(): void }> {} diff --git a/node_modules/mongodb/src/operations/add_user.ts b/node_modules/mongodb/src/operations/add_user.ts new file mode 100644 index 0000000..4dd56ac --- /dev/null +++ b/node_modules/mongodb/src/operations/add_user.ts @@ -0,0 +1,106 @@ +import * as crypto from 'crypto'; +import { Aspect, defineAspects } from './operation'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { MongoInvalidArgumentError } from '../error'; +import { Callback, emitWarningOnce, getTopology } from '../utils'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Db } from '../db'; +import type { ClientSession } from '../sessions'; + +/** @public */ +export interface RoleSpecification { + /** + * A role grants privileges to perform sets of actions on defined resources. + * A given role applies to the database on which it is defined and can grant access down to a collection level of granularity. + */ + role: string; + /** The database this user's role should effect. */ + db: string; +} + +/** @public */ +export interface AddUserOptions extends CommandOperationOptions { + /** @deprecated Please use db.command('createUser', ...) instead for this option */ + digestPassword?: null; + /** Roles associated with the created user */ + roles?: string | string[] | RoleSpecification | RoleSpecification[]; + /** Custom data associated with the user (only Mongodb 2.6 or higher) */ + customData?: Document; +} + +/** @internal */ +export class AddUserOperation extends CommandOperation { + options: AddUserOptions; + db: Db; + username: string; + password?: string; + + constructor(db: Db, username: string, password: string | undefined, options?: AddUserOptions) { + super(db, options); + + this.db = db; + this.username = username; + this.password = password; + this.options = options ?? {}; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const db = this.db; + const username = this.username; + const password = this.password; + const options = this.options; + + // Error out if digestPassword set + if (options.digestPassword != null) { + return callback( + new MongoInvalidArgumentError( + 'Option "digestPassword" not supported via addUser, use db.command(...) instead' + ) + ); + } + + let roles; + if (!options.roles || (Array.isArray(options.roles) && options.roles.length === 0)) { + emitWarningOnce( + 'Creating a user without roles is deprecated. Defaults to "root" if db is "admin" or "dbOwner" otherwise' + ); + if (db.databaseName.toLowerCase() === 'admin') { + roles = ['root']; + } else { + roles = ['dbOwner']; + } + } else { + roles = Array.isArray(options.roles) ? options.roles : [options.roles]; + } + + const digestPassword = getTopology(db).lastIsMaster().maxWireVersion >= 7; + + let userPassword = password; + + if (!digestPassword) { + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(`${username}:mongo:${password}`); + userPassword = md5.digest('hex'); + } + + // Build the command to execute + const command: Document = { + createUser: username, + customData: options.customData || {}, + roles: roles, + digestPassword + }; + + // No password + if (typeof password === 'string') { + command.pwd = userPassword; + } + + super.executeCommand(server, session, command, callback); + } +} + +defineAspects(AddUserOperation, [Aspect.WRITE_OPERATION]); diff --git a/node_modules/mongodb/src/operations/aggregate.ts b/node_modules/mongodb/src/operations/aggregate.ts new file mode 100644 index 0000000..0685400 --- /dev/null +++ b/node_modules/mongodb/src/operations/aggregate.ts @@ -0,0 +1,135 @@ +import { CommandOperation, CommandOperationOptions, CollationOptions } from './command'; +import { ReadPreference } from '../read_preference'; +import { MongoInvalidArgumentError } from '../error'; +import { maxWireVersion, MongoDBNamespace } from '../utils'; +import { Aspect, defineAspects, Hint } from './operation'; +import type { Callback } from '../utils'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; + +/** @internal */ +export const DB_AGGREGATE_COLLECTION = 1 as const; +const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8 as const; + +/** @public */ +export interface AggregateOptions extends CommandOperationOptions { + /** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */ + allowDiskUse?: boolean; + /** The number of documents to return per batch. See [aggregation documentation](https://docs.mongodb.com/manual/reference/command/aggregate). */ + batchSize?: number; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */ + cursor?: Document; + /** specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */ + maxAwaitTimeMS?: number; + /** Specify collation. */ + collation?: CollationOptions; + /** Add an index selection hint to an aggregation command */ + hint?: Hint; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + out?: string; +} + +/** @internal */ +export class AggregateOperation extends CommandOperation { + options: AggregateOptions; + target: string | typeof DB_AGGREGATE_COLLECTION; + pipeline: Document[]; + hasWriteStage: boolean; + + constructor(ns: MongoDBNamespace, pipeline: Document[], options?: AggregateOptions) { + super(undefined, { ...options, dbName: ns.db }); + + this.options = options ?? {}; + + // Covers when ns.collection is null, undefined or the empty string, use DB_AGGREGATE_COLLECTION + this.target = ns.collection || DB_AGGREGATE_COLLECTION; + + this.pipeline = pipeline; + + // determine if we have a write stage, override read preference if so + this.hasWriteStage = false; + if (typeof options?.out === 'string') { + this.pipeline = this.pipeline.concat({ $out: options.out }); + this.hasWriteStage = true; + } else if (pipeline.length > 0) { + const finalStage = pipeline[pipeline.length - 1]; + if (finalStage.$out || finalStage.$merge) { + this.hasWriteStage = true; + } + } + + if (this.hasWriteStage) { + this.readPreference = ReadPreference.primary; + } + + if (this.explain && this.writeConcern) { + throw new MongoInvalidArgumentError( + 'Option "explain" cannot be used on an aggregate call with writeConcern' + ); + } + + if (options?.cursor != null && typeof options.cursor !== 'object') { + throw new MongoInvalidArgumentError('Cursor options must be an object'); + } + } + + get canRetryRead(): boolean { + return !this.hasWriteStage; + } + + addToPipeline(stage: Document): void { + this.pipeline.push(stage); + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const options: AggregateOptions = this.options; + const serverWireVersion = maxWireVersion(server); + const command: Document = { aggregate: this.target, pipeline: this.pipeline }; + + if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { + this.readConcern = undefined; + } + + if (serverWireVersion >= 5) { + if (this.hasWriteStage && this.writeConcern) { + Object.assign(command, { writeConcern: this.writeConcern }); + } + } + + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + if (typeof options.allowDiskUse === 'boolean') { + command.allowDiskUse = options.allowDiskUse; + } + + if (options.hint) { + command.hint = options.hint; + } + + if (options.let) { + command.let = options.let; + } + + command.cursor = options.cursor || {}; + if (options.batchSize && !this.hasWriteStage) { + command.cursor.batchSize = options.batchSize; + } + + super.executeCommand(server, session, command, callback); + } +} + +defineAspects(AggregateOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXPLAINABLE, + Aspect.CURSOR_CREATING +]); diff --git a/node_modules/mongodb/src/operations/bulk_write.ts b/node_modules/mongodb/src/operations/bulk_write.ts new file mode 100644 index 0000000..8ab1f91 --- /dev/null +++ b/node_modules/mongodb/src/operations/bulk_write.ts @@ -0,0 +1,63 @@ +import { Aspect, defineAspects, AbstractOperation } from './operation'; +import type { Callback } from '../utils'; +import type { Collection } from '../collection'; +import type { + BulkOperationBase, + BulkWriteResult, + BulkWriteOptions, + AnyBulkWriteOperation +} from '../bulk/common'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; + +/** @internal */ +export class BulkWriteOperation extends AbstractOperation { + options: BulkWriteOptions; + collection: Collection; + operations: AnyBulkWriteOperation[]; + + constructor( + collection: Collection, + operations: AnyBulkWriteOperation[], + options: BulkWriteOptions + ) { + super(options); + this.options = options; + this.collection = collection; + this.operations = operations; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const coll = this.collection; + const operations = this.operations; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + + // Create the bulk operation + const bulk: BulkOperationBase = + options.ordered === false + ? coll.initializeUnorderedBulkOp(options) + : coll.initializeOrderedBulkOp(options); + + // for each op go through and add to the bulk + try { + for (let i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); + } + } catch (err) { + return callback(err); + } + + // Execute the bulk + bulk.execute({ ...options, session }, (err, r) => { + // We have connection level error + if (!r && err) { + return callback(err); + } + + // Return the results + callback(undefined, r); + }); + } +} + +defineAspects(BulkWriteOperation, [Aspect.WRITE_OPERATION]); diff --git a/node_modules/mongodb/src/operations/collections.ts b/node_modules/mongodb/src/operations/collections.ts new file mode 100644 index 0000000..fbdf417 --- /dev/null +++ b/node_modules/mongodb/src/operations/collections.ts @@ -0,0 +1,44 @@ +import { AbstractOperation, OperationOptions } from './operation'; +import { Collection } from '../collection'; +import type { Callback } from '../utils'; +import type { Db } from '../db'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; + +export interface CollectionsOptions extends OperationOptions { + nameOnly?: boolean; +} + +/** @internal */ +export class CollectionsOperation extends AbstractOperation { + options: CollectionsOptions; + db: Db; + + constructor(db: Db, options: CollectionsOptions) { + super(options); + this.options = options; + this.db = db; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const db = this.db; + + // Let's get the collection names + db.listCollections( + {}, + { ...this.options, nameOnly: true, readPreference: this.readPreference, session } + ).toArray((err, documents) => { + if (err || !documents) return callback(err); + // Filter collections removing any illegal ones + documents = documents.filter(doc => doc.name.indexOf('$') === -1); + + // Return the collection objects + callback( + undefined, + documents.map(d => { + return new Collection(db, d.name, db.s.options); + }) + ); + }); + } +} diff --git a/node_modules/mongodb/src/operations/command.ts b/node_modules/mongodb/src/operations/command.ts new file mode 100644 index 0000000..70ae413 --- /dev/null +++ b/node_modules/mongodb/src/operations/command.ts @@ -0,0 +1,171 @@ +import { Aspect, AbstractOperation, OperationOptions } from './operation'; +import { ReadConcern } from '../read_concern'; +import { WriteConcern, WriteConcernOptions } from '../write_concern'; +import { maxWireVersion, MongoDBNamespace, Callback, decorateWithExplain } from '../utils'; +import type { ReadPreference } from '../read_preference'; +import { ClientSession, commandSupportsReadConcern } from '../sessions'; +import { MongoInvalidArgumentError, MongoCompatibilityError } from '../error'; +import type { Logger } from '../logger'; +import type { Server } from '../sdam/server'; +import type { BSONSerializeOptions, Document } from '../bson'; +import type { ReadConcernLike } from './../read_concern'; +import { Explain, ExplainOptions } from '../explain'; + +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; + +/** @public */ +export interface CollationOptions { + locale: string; + caseLevel?: boolean; + caseFirst?: string; + strength?: number; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + normalization?: boolean; +} + +/** @public */ +export interface CommandOperationOptions + extends OperationOptions, + WriteConcernOptions, + ExplainOptions { + /** @deprecated This option does nothing */ + fullResponse?: boolean; + /** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** Collation */ + collation?: CollationOptions; + maxTimeMS?: number; + /** A user-provided comment to attach to this command */ + comment?: string | Document; + /** Should retry failed writes */ + retryWrites?: boolean; + + // Admin command overrides. + dbName?: string; + authdb?: string; + noResponse?: boolean; +} + +/** @internal */ +export interface OperationParent { + s: { namespace: MongoDBNamespace }; + readConcern?: ReadConcern; + writeConcern?: WriteConcern; + readPreference?: ReadPreference; + logger?: Logger; + bsonOptions?: BSONSerializeOptions; +} + +/** @internal */ +export abstract class CommandOperation extends AbstractOperation { + options: CommandOperationOptions; + ns: MongoDBNamespace; + readConcern?: ReadConcern; + writeConcern?: WriteConcern; + explain?: Explain; + logger?: Logger; + + constructor(parent?: OperationParent, options?: CommandOperationOptions) { + super(options); + this.options = options ?? {}; + + // NOTE: this was explicitly added for the add/remove user operations, it's likely + // something we'd want to reconsider. Perhaps those commands can use `Admin` + // as a parent? + const dbNameOverride = options?.dbName || options?.authdb; + if (dbNameOverride) { + this.ns = new MongoDBNamespace(dbNameOverride, '$cmd'); + } else { + this.ns = parent + ? parent.s.namespace.withCollection('$cmd') + : new MongoDBNamespace('admin', '$cmd'); + } + + this.readConcern = ReadConcern.fromOptions(options); + this.writeConcern = WriteConcern.fromOptions(options); + + // TODO(NODE-2056): make logger another "inheritable" property + if (parent && parent.logger) { + this.logger = parent.logger; + } + + if (this.hasAspect(Aspect.EXPLAINABLE)) { + this.explain = Explain.fromOptions(options); + } else if (options?.explain != null) { + throw new MongoInvalidArgumentError(`Option "explain" is not supported on this command`); + } + } + + get canRetryWrite(): boolean { + if (this.hasAspect(Aspect.EXPLAINABLE)) { + return this.explain == null; + } + return true; + } + + abstract execute(server: Server, session: ClientSession, callback: Callback): void; + + executeCommand(server: Server, session: ClientSession, cmd: Document, callback: Callback): void { + // TODO: consider making this a non-enumerable property + this.server = server; + + const options = { + ...this.options, + ...this.bsonOptions, + readPreference: this.readPreference, + session + }; + + const serverWireVersion = maxWireVersion(server); + const inTransaction = this.session && this.session.inTransaction(); + + if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) { + Object.assign(cmd, { readConcern: this.readConcern }); + } + + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback( + new MongoCompatibilityError( + `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation` + ) + ); + return; + } + + if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION) && !inTransaction) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + + if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + if ( + options.collation && + typeof options.collation === 'object' && + !this.hasAspect(Aspect.SKIP_COLLATION) + ) { + Object.assign(cmd, { collation: options.collation }); + } + } + + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + if (typeof options.comment === 'string') { + cmd.comment = options.comment; + } + + if (this.hasAspect(Aspect.EXPLAINABLE) && this.explain) { + if (serverWireVersion < 6 && cmd.aggregate) { + // Prior to 3.6, with aggregate, verbosity is ignored, and we must pass in "explain: true" + cmd.explain = true; + } else { + cmd = decorateWithExplain(cmd, this.explain); + } + } + + server.command(this.ns, cmd, options, callback); + } +} diff --git a/node_modules/mongodb/src/operations/common_functions.ts b/node_modules/mongodb/src/operations/common_functions.ts new file mode 100644 index 0000000..f056f32 --- /dev/null +++ b/node_modules/mongodb/src/operations/common_functions.ts @@ -0,0 +1,95 @@ +import { MongoTopologyClosedError } from '../error'; +import { Callback, getTopology } from '../utils'; +import type { Document } from '../bson'; +import type { Db } from '../db'; +import type { ClientSession } from '../sessions'; +import type { ReadPreference } from '../read_preference'; +import type { Collection } from '../collection'; + +/** @public */ +export interface IndexInformationOptions { + full?: boolean; + readPreference?: ReadPreference; + session?: ClientSession; +} +/** + * Retrieves this collections index info. + * + * @param db - The Db instance on which to retrieve the index info. + * @param name - The name of the collection. + */ +export function indexInformation(db: Db, name: string, callback: Callback): void; +export function indexInformation( + db: Db, + name: string, + options: IndexInformationOptions, + callback?: Callback +): void; +export function indexInformation( + db: Db, + name: string, + _optionsOrCallback: IndexInformationOptions | Callback, + _callback?: Callback +): void { + let options = _optionsOrCallback as IndexInformationOptions; + let callback = _callback as Callback; + if ('function' === typeof _optionsOrCallback) { + callback = _optionsOrCallback as Callback; + options = {}; + } + // If we specified full information + const full = options.full == null ? false : options.full; + + // Did the user destroy the topology + if (getTopology(db).isDestroyed()) return callback(new MongoTopologyClosedError()); + // Process all the results from the index command and collection + function processResults(indexes: any) { + // Contains all the information + const info: any = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (const name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + db.collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) return callback(err); + if (!Array.isArray(indexes)) return callback(undefined, []); + if (full) return callback(undefined, indexes); + callback(undefined, processResults(indexes)); + }); +} + +export function prepareDocs( + coll: Collection, + docs: Document[], + options: { forceServerObjectId?: boolean } +): Document[] { + const forceServerObjectId = + typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : coll.s.db.options?.forceServerObjectId; + + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docs; + } + + return docs.map(doc => { + if (doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); + } + + return doc; + }); +} diff --git a/node_modules/mongodb/src/operations/connect.ts b/node_modules/mongodb/src/operations/connect.ts new file mode 100644 index 0000000..7a12411 --- /dev/null +++ b/node_modules/mongodb/src/operations/connect.ts @@ -0,0 +1,116 @@ +import { MongoRuntimeError, MongoInvalidArgumentError } from '../error'; +import { Topology, TOPOLOGY_EVENTS } from '../sdam/topology'; +import { resolveSRVRecord } from '../connection_string'; +import type { Callback } from '../utils'; +import type { MongoClient, MongoOptions } from '../mongo_client'; +import { CMAP_EVENTS } from '../cmap/connection_pool'; +import { APM_EVENTS } from '../cmap/connection'; +import { HEARTBEAT_EVENTS } from '../sdam/server'; + +/** @public */ +export const MONGO_CLIENT_EVENTS = [ + ...CMAP_EVENTS, + ...APM_EVENTS, + ...TOPOLOGY_EVENTS, + ...HEARTBEAT_EVENTS +] as const; + +export function connect( + mongoClient: MongoClient, + options: MongoOptions, + callback: Callback +): void { + if (!callback) { + throw new MongoInvalidArgumentError('Callback function must be provided'); + } + + // If a connection already been established, we can terminate early + if (mongoClient.topology && mongoClient.topology.isConnected()) { + return callback(undefined, mongoClient); + } + + const logger = mongoClient.logger; + const connectCallback: Callback = err => { + const warningMessage = + 'seed list contains no mongos proxies, replicaset connections requires ' + + 'the parameter replicaSet to be supplied in the URI or options object, ' + + 'mongodb://server:port/db?replicaSet=name'; + if (err && err.message === 'no mongos proxies found in seed list') { + if (logger.isWarn()) { + logger.warn(warningMessage); + } + + // Return a more specific error message for MongoClient.connect + // TODO(NODE-3483) + return callback(new MongoRuntimeError(warningMessage)); + } + + callback(err, mongoClient); + }; + + if (typeof options.srvHost === 'string') { + return resolveSRVRecord(options, (err, hosts) => { + if (err || !hosts) return callback(err); + for (const [index, host] of hosts.entries()) { + options.hosts[index] = host; + } + + return createTopology(mongoClient, options, connectCallback); + }); + } + + return createTopology(mongoClient, options, connectCallback); +} + +function createTopology( + mongoClient: MongoClient, + options: MongoOptions, + callback: Callback +) { + // Create the topology + const topology = new Topology(options.hosts, options); + // Events can be emitted before initialization is complete so we have to + // save the reference to the topology on the client ASAP if the event handlers need to access it + mongoClient.topology = topology; + + topology.once(Topology.OPEN, () => mongoClient.emit('open', mongoClient)); + + for (const event of MONGO_CLIENT_EVENTS) { + topology.on(event, (...args: any[]) => mongoClient.emit(event, ...(args as any))); + } + + // initialize CSFLE if requested + if (mongoClient.autoEncrypter) { + mongoClient.autoEncrypter.init(err => { + if (err) { + return callback(err); + } + + topology.connect(options, err => { + if (err) { + topology.close({ force: true }); + return callback(err); + } + + options.encrypter.connectInternalClient(error => { + if (error) return callback(error); + + callback(undefined, topology); + }); + }); + }); + + return; + } + + // otherwise connect normally + topology.connect(options, err => { + if (err) { + topology.close({ force: true }); + return callback(err); + } + + callback(undefined, topology); + return; + }); +} diff --git a/node_modules/mongodb/src/operations/count.ts b/node_modules/mongodb/src/operations/count.ts new file mode 100644 index 0000000..34f4156 --- /dev/null +++ b/node_modules/mongodb/src/operations/count.ts @@ -0,0 +1,64 @@ +import { Aspect, defineAspects } from './operation'; +import { CommandOperation, CommandOperationOptions } from './command'; +import type { Callback, MongoDBNamespace } from '../utils'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Collection } from '../collection'; +import type { ClientSession } from '../sessions'; + +/** @public */ +export interface CountOptions extends CommandOperationOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** An index name hint for the query. */ + hint?: string | Document; +} + +/** @internal */ +export class CountOperation extends CommandOperation { + options: CountOptions; + collectionName?: string; + query: Document; + + constructor(namespace: MongoDBNamespace, filter: Document, options: CountOptions) { + super({ s: { namespace: namespace } } as unknown as Collection, options); + + this.options = options; + this.collectionName = namespace.collection; + this.query = filter; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const options = this.options; + const cmd: Document = { + count: this.collectionName, + query: this.query + }; + + if (typeof options.limit === 'number') { + cmd.limit = options.limit; + } + + if (typeof options.skip === 'number') { + cmd.skip = options.skip; + } + + if (options.hint != null) { + cmd.hint = options.hint; + } + + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + super.executeCommand(server, session, cmd, (err, result) => { + callback(err, result ? result.n : 0); + }); + } +} + +defineAspects(CountOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE]); diff --git a/node_modules/mongodb/src/operations/count_documents.ts b/node_modules/mongodb/src/operations/count_documents.ts new file mode 100644 index 0000000..d7e8c3e --- /dev/null +++ b/node_modules/mongodb/src/operations/count_documents.ts @@ -0,0 +1,53 @@ +import { AggregateOperation, AggregateOptions } from './aggregate'; +import type { Callback } from '../utils'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Collection } from '../collection'; +import type { ClientSession } from '../sessions'; + +/** @public */ +export interface CountDocumentsOptions extends AggregateOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; +} + +/** @internal */ +export class CountDocumentsOperation extends AggregateOperation { + constructor(collection: Collection, query: Document, options: CountDocumentsOptions) { + const pipeline = []; + pipeline.push({ $match: query }); + + if (typeof options.skip === 'number') { + pipeline.push({ $skip: options.skip }); + } + + if (typeof options.limit === 'number') { + pipeline.push({ $limit: options.limit }); + } + + pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); + + super(collection.s.namespace, pipeline, options); + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + super.execute(server, session, (err, result) => { + if (err || !result) { + callback(err); + return; + } + + // NOTE: We're avoiding creating a cursor here to reduce the callstack. + const response = result as unknown as Document; + if (response.cursor == null || response.cursor.firstBatch == null) { + callback(undefined, 0); + return; + } + + const docs = response.cursor.firstBatch; + callback(undefined, docs.length ? docs[0].n : 0); + }); + } +} diff --git a/node_modules/mongodb/src/operations/create_collection.ts b/node_modules/mongodb/src/operations/create_collection.ts new file mode 100644 index 0000000..86291c6 --- /dev/null +++ b/node_modules/mongodb/src/operations/create_collection.ts @@ -0,0 +1,122 @@ +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; +import { Collection } from '../collection'; +import type { Callback } from '../utils'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Db } from '../db'; +import type { PkFactory } from '../mongo_client'; +import type { ClientSession } from '../sessions'; + +const ILLEGAL_COMMAND_FIELDS = new Set([ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'pkFactory', + 'raw', + 'readPreference', + 'session', + 'readConcern', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined' +]); + +/** @public + * Configuration options for timeseries collections + * @see https://docs.mongodb.com/manual/core/timeseries-collections/ + */ +export interface TimeSeriesCollectionOptions extends Document { + timeField: string; + metaField?: string; + granularity?: string; +} + +/** @public */ +export interface CreateCollectionOptions extends CommandOperationOptions { + /** Returns an error if the collection does not exist */ + strict?: boolean; + /** Create a capped collection */ + capped?: boolean; + /** @deprecated Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 */ + autoIndexId?: boolean; + /** The size of the capped collection in bytes */ + size?: number; + /** The maximum number of documents in the capped collection */ + max?: number; + /** Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag */ + flags?: number; + /** Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher */ + storageEngine?: Document; + /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher */ + validator?: Document; + /** Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher */ + validationLevel?: string; + /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher */ + validationAction?: string; + /** Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher */ + indexOptionDefaults?: Document; + /** The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher */ + viewOn?: string; + /** An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher */ + pipeline?: Document[]; + /** A primary key factory function for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** A document specifying configuration options for timeseries collections. */ + timeseries?: TimeSeriesCollectionOptions; + /** The number of seconds after which a document in a timeseries collection expires. */ + expireAfterSeconds?: number; +} + +/** @internal */ +export class CreateCollectionOperation extends CommandOperation { + options: CreateCollectionOptions; + db: Db; + name: string; + + constructor(db: Db, name: string, options: CreateCollectionOptions = {}) { + super(db, options); + + this.options = options; + this.db = db; + this.name = name; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const db = this.db; + const name = this.name; + const options = this.options; + + const done: Callback = err => { + if (err) { + return callback(err); + } + + callback(undefined, new Collection(db, name, options)); + }; + + const cmd: Document = { create: name }; + for (const n in options) { + if ( + (options as any)[n] != null && + typeof (options as any)[n] !== 'function' && + !ILLEGAL_COMMAND_FIELDS.has(n) + ) { + cmd[n] = (options as any)[n]; + } + } + + // otherwise just execute the command + super.executeCommand(server, session, cmd, done); + } +} + +defineAspects(CreateCollectionOperation, [Aspect.WRITE_OPERATION]); diff --git a/node_modules/mongodb/src/operations/delete.ts b/node_modules/mongodb/src/operations/delete.ts new file mode 100644 index 0000000..c8c15b7 --- /dev/null +++ b/node_modules/mongodb/src/operations/delete.ts @@ -0,0 +1,188 @@ +import { defineAspects, Aspect, Hint } from './operation'; +import { CommandOperation, CommandOperationOptions, CollationOptions } from './command'; +import { Callback, maxWireVersion, MongoDBNamespace, collationNotSupported } from '../utils'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Collection } from '../collection'; +import type { ClientSession } from '../sessions'; +import { MongoServerError, MongoCompatibilityError } from '../error'; +import type { WriteConcernOptions } from '../write_concern'; + +/** @public */ +export interface DeleteOptions extends CommandOperationOptions, WriteConcernOptions { + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** A user-provided comment to attach to this command */ + comment?: string | Document; + /** Specifies the collation to use for the operation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + + /** @deprecated use `removeOne` or `removeMany` to implicitly specify the limit */ + single?: boolean; +} + +/** @public */ +export interface DeleteResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined. */ + acknowledged: boolean; + /** The number of documents that were deleted */ + deletedCount: number; +} + +/** @public */ +export interface DeleteStatement { + /** The query that matches documents to delete. */ + q: Document; + /** The number of matching documents to delete. */ + limit: number; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; + /** A user-provided comment to attach to this command */ + comment?: string | Document; +} + +/** @internal */ +export class DeleteOperation extends CommandOperation { + options: DeleteOptions; + statements: DeleteStatement[]; + + constructor(ns: MongoDBNamespace, statements: DeleteStatement[], options: DeleteOptions) { + super(undefined, options); + this.options = options; + this.ns = ns; + this.statements = statements; + } + + get canRetryWrite(): boolean { + if (super.canRetryWrite === false) { + return false; + } + + return this.statements.every(op => (op.limit != null ? op.limit > 0 : true)); + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command: Document = { + delete: this.ns.collection, + deletes: this.statements, + ordered + }; + + if (options.let) { + command.let = options.let; + } + + if (options.explain != null && maxWireVersion(server) < 3) { + return callback + ? callback( + new MongoCompatibilityError(`Server ${server.name} does not support explain on delete`) + ) + : undefined; + } + + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite || maxWireVersion(server) < 5) { + if (this.statements.find((o: Document) => o.hint)) { + callback(new MongoCompatibilityError(`Servers < 3.4 do not support hint on delete`)); + return; + } + } + + const statementWithCollation = this.statements.find(statement => !!statement.collation); + if (statementWithCollation && collationNotSupported(server, statementWithCollation)) { + callback(new MongoCompatibilityError(`Server ${server.name} does not support collation`)); + return; + } + + super.executeCommand(server, session, command, callback); + } +} + +export class DeleteOneOperation extends DeleteOperation { + constructor(collection: Collection, filter: Document, options: DeleteOptions) { + super(collection.s.namespace, [makeDeleteStatement(filter, { ...options, limit: 1 })], options); + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + super.execute(server, session, (err, res) => { + if (err || res == null) return callback(err); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0])); + if (this.explain) return callback(undefined, res); + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + deletedCount: res.n + }); + }); + } +} + +export class DeleteManyOperation extends DeleteOperation { + constructor(collection: Collection, filter: Document, options: DeleteOptions) { + super(collection.s.namespace, [makeDeleteStatement(filter, options)], options); + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + super.execute(server, session, (err, res) => { + if (err || res == null) return callback(err); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0])); + if (this.explain) return callback(undefined, res); + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + deletedCount: res.n + }); + }); + } +} + +export function makeDeleteStatement( + filter: Document, + options: DeleteOptions & { limit?: number } +): DeleteStatement { + const op: DeleteStatement = { + q: filter, + limit: typeof options.limit === 'number' ? options.limit : 0 + }; + + if (options.single === true) { + op.limit = 1; + } + + if (options.collation) { + op.collation = options.collation; + } + + if (options.hint) { + op.hint = options.hint; + } + + if (options.comment) { + op.comment = options.comment; + } + + return op; +} + +defineAspects(DeleteOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION]); +defineAspects(DeleteOneOperation, [ + Aspect.RETRYABLE, + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); +defineAspects(DeleteManyOperation, [ + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); diff --git a/node_modules/mongodb/src/operations/distinct.ts b/node_modules/mongodb/src/operations/distinct.ts new file mode 100644 index 0000000..5524b2b --- /dev/null +++ b/node_modules/mongodb/src/operations/distinct.ts @@ -0,0 +1,88 @@ +import { Aspect, defineAspects } from './operation'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { decorateWithCollation, decorateWithReadConcern, Callback, maxWireVersion } from '../utils'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Collection } from '../collection'; +import { MongoCompatibilityError } from '../error'; +import type { ClientSession } from '../sessions'; + +/** @public */ +export type DistinctOptions = CommandOperationOptions; + +/** + * Return a list of distinct values for the given key across a collection. + * @internal + */ +export class DistinctOperation extends CommandOperation { + options: DistinctOptions; + collection: Collection; + /** Field of the document to find distinct values for. */ + key: string; + /** The query for filtering the set of documents to which we apply the distinct filter. */ + query: Document; + + /** + * Construct a Distinct operation. + * + * @param collection - Collection instance. + * @param key - Field of the document to find distinct values for. + * @param query - The query for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings. See Collection.prototype.distinct for a list of options. + */ + constructor(collection: Collection, key: string, query: Document, options?: DistinctOptions) { + super(collection, options); + + this.options = options ?? {}; + this.collection = collection; + this.key = key; + this.query = query; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const coll = this.collection; + const key = this.key; + const query = this.query; + const options = this.options; + + // Distinct command + const cmd: Document = { + distinct: coll.collectionName, + key: key, + query: query + }; + + // Add maxTimeMS if defined + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, coll, options); + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return callback(err); + } + + if (this.explain && maxWireVersion(server) < 4) { + callback( + new MongoCompatibilityError(`Server ${server.name} does not support explain on distinct`) + ); + return; + } + + super.executeCommand(server, session, cmd, (err, result) => { + if (err) { + callback(err); + return; + } + + callback(undefined, this.explain ? result : result.values); + }); + } +} + +defineAspects(DistinctOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE, Aspect.EXPLAINABLE]); diff --git a/node_modules/mongodb/src/operations/drop.ts b/node_modules/mongodb/src/operations/drop.ts new file mode 100644 index 0000000..f8a3757 --- /dev/null +++ b/node_modules/mongodb/src/operations/drop.ts @@ -0,0 +1,52 @@ +import { Aspect, defineAspects } from './operation'; +import { CommandOperation, CommandOperationOptions } from './command'; +import type { Callback } from '../utils'; +import type { Server } from '../sdam/server'; +import type { Db } from '../db'; +import type { ClientSession } from '../sessions'; + +/** @public */ +export type DropCollectionOptions = CommandOperationOptions; + +/** @internal */ +export class DropCollectionOperation extends CommandOperation { + options: DropCollectionOptions; + name: string; + + constructor(db: Db, name: string, options: DropCollectionOptions) { + super(db, options); + this.options = options; + this.name = name; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + super.executeCommand(server, session, { drop: this.name }, (err, result) => { + if (err) return callback(err); + if (result.ok) return callback(undefined, true); + callback(undefined, false); + }); + } +} + +/** @public */ +export type DropDatabaseOptions = CommandOperationOptions; + +/** @internal */ +export class DropDatabaseOperation extends CommandOperation { + options: DropDatabaseOptions; + + constructor(db: Db, options: DropDatabaseOptions) { + super(db, options); + this.options = options; + } + execute(server: Server, session: ClientSession, callback: Callback): void { + super.executeCommand(server, session, { dropDatabase: 1 }, (err, result) => { + if (err) return callback(err); + if (result.ok) return callback(undefined, true); + callback(undefined, false); + }); + } +} + +defineAspects(DropCollectionOperation, [Aspect.WRITE_OPERATION]); +defineAspects(DropDatabaseOperation, [Aspect.WRITE_OPERATION]); diff --git a/node_modules/mongodb/src/operations/estimated_document_count.ts b/node_modules/mongodb/src/operations/estimated_document_count.ts new file mode 100644 index 0000000..90261cb --- /dev/null +++ b/node_modules/mongodb/src/operations/estimated_document_count.ts @@ -0,0 +1,75 @@ +import { Aspect, defineAspects } from './operation'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Callback, maxWireVersion } from '../utils'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Collection } from '../collection'; +import type { ClientSession } from '../sessions'; +import type { MongoServerError } from '../error'; + +/** @public */ +export interface EstimatedDocumentCountOptions extends CommandOperationOptions { + /** + * The maximum amount of time to allow the operation to run. + * + * This option is sent only if the caller explicitly provides a value. The default is to not send a value. + */ + maxTimeMS?: number; +} + +/** @internal */ +export class EstimatedDocumentCountOperation extends CommandOperation { + options: EstimatedDocumentCountOptions; + collectionName: string; + + constructor(collection: Collection, options: EstimatedDocumentCountOptions = {}) { + super(collection, options); + this.options = options; + this.collectionName = collection.collectionName; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + if (maxWireVersion(server) < 12) { + return this.executeLegacy(server, session, callback); + } + const pipeline = [{ $collStats: { count: {} } }, { $group: { _id: 1, n: { $sum: '$count' } } }]; + + const cmd: Document = { aggregate: this.collectionName, pipeline, cursor: {} }; + + if (typeof this.options.maxTimeMS === 'number') { + cmd.maxTimeMS = this.options.maxTimeMS; + } + + super.executeCommand(server, session, cmd, (err, response) => { + if (err && (err as MongoServerError).code !== 26) { + callback(err); + return; + } + + callback(undefined, response?.cursor?.firstBatch[0]?.n || 0); + }); + } + + executeLegacy(server: Server, session: ClientSession, callback: Callback): void { + const cmd: Document = { count: this.collectionName }; + + if (typeof this.options.maxTimeMS === 'number') { + cmd.maxTimeMS = this.options.maxTimeMS; + } + + super.executeCommand(server, session, cmd, (err, response) => { + if (err) { + callback(err); + return; + } + + callback(undefined, response.n || 0); + }); + } +} + +defineAspects(EstimatedDocumentCountOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.CURSOR_CREATING +]); diff --git a/node_modules/mongodb/src/operations/eval.ts b/node_modules/mongodb/src/operations/eval.ts new file mode 100644 index 0000000..3974912 --- /dev/null +++ b/node_modules/mongodb/src/operations/eval.ts @@ -0,0 +1,78 @@ +import { CommandOperation, CommandOperationOptions } from './command'; +import { Code, Document } from '../bson'; +import { ReadPreference } from '../read_preference'; +import { MongoServerError } from '../error'; +import type { Callback } from '../utils'; +import type { Server } from '../sdam/server'; +import type { Db } from '../db'; +import type { Collection } from '../collection'; +import type { ClientSession } from '../sessions'; + +/** @public */ +export interface EvalOptions extends CommandOperationOptions { + nolock?: boolean; +} + +/** @internal */ +export class EvalOperation extends CommandOperation { + options: EvalOptions; + code: Code; + parameters?: Document | Document[]; + + constructor( + db: Db | Collection, + code: Code, + parameters?: Document | Document[], + options?: EvalOptions + ) { + super(db, options); + + this.options = options ?? {}; + this.code = code; + this.parameters = parameters; + // force primary read preference + Object.defineProperty(this, 'readPreference', { + value: ReadPreference.primary, + configurable: false, + writable: false + }); + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + let finalCode = this.code; + let finalParameters: Document[] = []; + + // If not a code object translate to one + if (!(finalCode && (finalCode as unknown as { _bsontype: string })._bsontype === 'Code')) { + finalCode = new Code(finalCode as never); + } + + // Ensure the parameters are correct + if (this.parameters != null && typeof this.parameters !== 'function') { + finalParameters = Array.isArray(this.parameters) ? this.parameters : [this.parameters]; + } + + // Create execution selector + const cmd: Document = { $eval: finalCode, args: finalParameters }; + + // Check if the nolock parameter is passed in + if (this.options.nolock) { + cmd.nolock = this.options.nolock; + } + + // Execute the command + super.executeCommand(server, session, cmd, (err, result) => { + if (err) return callback(err); + if (result && result.ok === 1) { + return callback(undefined, result.retval); + } + + if (result) { + callback(new MongoServerError({ message: `eval failed: ${result.errmsg}` })); + return; + } + + callback(err, result); + }); + } +} diff --git a/node_modules/mongodb/src/operations/execute_operation.ts b/node_modules/mongodb/src/operations/execute_operation.ts new file mode 100644 index 0000000..7809783 --- /dev/null +++ b/node_modules/mongodb/src/operations/execute_operation.ts @@ -0,0 +1,269 @@ +import { ReadPreference } from '../read_preference'; +import { + MongoError, + isRetryableError, + MONGODB_ERROR_CODES, + MongoRuntimeError, + MongoNetworkError, + MongoCompatibilityError, + MongoServerError, + MongoExpiredSessionError, + MongoTransactionError +} from '../error'; +import { Aspect, AbstractOperation } from './operation'; +import { maxWireVersion, maybePromise, Callback } from '../utils'; +import type { Server } from '../sdam/server'; +import type { Topology } from '../sdam/topology'; +import type { ClientSession } from '../sessions'; +import type { Document } from '../bson'; +import { supportsRetryableWrites } from '../utils'; + +const MMAPv1_RETRY_WRITES_ERROR_CODE = MONGODB_ERROR_CODES.IllegalOperation; +const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = + 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; + +type ResultTypeFromOperation = TOperation extends AbstractOperation + ? K + : never; + +/** @internal */ +export interface ExecutionResult { + /** The server selected for the operation */ + server: Server; + /** The session used for this operation, may be implicitly created */ + session?: ClientSession; + /** The raw server response for the operation */ + response: Document; +} + +/** + * Executes the given operation with provided arguments. + * @internal + * + * @remarks + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @param topology - The topology to execute this operation on + * @param operation - The operation to execute + * @param callback - The command result callback + */ +export function executeOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>(topology: Topology, operation: T): Promise; +export function executeOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>(topology: Topology, operation: T, callback: Callback): void; +export function executeOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>(topology: Topology, operation: T, callback?: Callback): Promise | void; +export function executeOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>(topology: Topology, operation: T, callback?: Callback): Promise | void { + if (!(operation instanceof AbstractOperation)) { + // TODO(NODE-3483) + throw new MongoRuntimeError('This method requires a valid operation instance'); + } + + return maybePromise(callback, cb => { + if (topology.shouldCheckForSessionSupport()) { + return topology.selectServer(ReadPreference.primaryPreferred, err => { + if (err) return cb(err); + + executeOperation(topology, operation, cb); + }); + } + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session: ClientSession | undefined = operation.session; + let owner: symbol | undefined; + if (topology.hasSessionSupport()) { + if (session == null) { + owner = Symbol(); + session = topology.startSession({ owner, explicit: false }); + } else if (session.hasEnded) { + return cb(new MongoExpiredSessionError('Use of expired sessions is not permitted')); + } else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + return cb(new MongoCompatibilityError('Snapshot reads require MongoDB 5.0 or later')); + } + } else if (session) { + // If the user passed an explicit session and we are still, after server selection, + // trying to run against a topology that doesn't support sessions we error out. + return cb(new MongoCompatibilityError('Current topology does not support sessions')); + } + + try { + executeWithServerSelection(topology, session, operation, (err, result) => { + if (session && session.owner && session.owner === owner) { + return session.endSession(err2 => cb(err2 || err, result)); + } + + cb(err, result); + }); + } catch (e) { + if (session && session.owner && session.owner === owner) { + session.endSession(); + } + + throw e; + } + }); +} + +function supportsRetryableReads(server: Server) { + return maxWireVersion(server) >= 6; +} + +function executeWithServerSelection( + topology: Topology, + session: ClientSession, + operation: AbstractOperation, + callback: Callback +) { + const readPreference = operation.readPreference || ReadPreference.primary; + const inTransaction = session && session.inTransaction(); + + if (inTransaction && !readPreference.equals(ReadPreference.primary)) { + callback( + new MongoTransactionError( + `Read preference in a transaction must be primary, not: ${readPreference.mode}` + ) + ); + + return; + } + + if ( + session && + session.isPinned && + session.transaction.isCommitted && + !operation.bypassPinningCheck + ) { + session.unpin(); + } + + const serverSelectionOptions = { session }; + function callbackWithRetry(err?: any, result?: any) { + if (err == null) { + return callback(undefined, result); + } + + const hasReadAspect = operation.hasAspect(Aspect.READ_OPERATION); + const hasWriteAspect = operation.hasAspect(Aspect.WRITE_OPERATION); + const itShouldRetryWrite = shouldRetryWrite(err); + + if ((hasReadAspect && !isRetryableError(err)) || (hasWriteAspect && !itShouldRetryWrite)) { + return callback(err); + } + + if ( + hasWriteAspect && + itShouldRetryWrite && + err.code === MMAPv1_RETRY_WRITES_ERROR_CODE && + err.errmsg.match(/Transaction numbers/) + ) { + callback( + new MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError: err + }) + ); + + return; + } + + // select a new server, and attempt to retry the operation + topology.selectServer(readPreference, serverSelectionOptions, (e?: any, server?: any) => { + if ( + e || + (operation.hasAspect(Aspect.READ_OPERATION) && !supportsRetryableReads(server)) || + (operation.hasAspect(Aspect.WRITE_OPERATION) && !supportsRetryableWrites(server)) + ) { + callback(e); + return; + } + + // If we have a cursor and the initial command fails with a network error, + // we can retry it on another connection. So we need to check it back in, clear the + // pool for the service id, and retry again. + if ( + err && + err instanceof MongoNetworkError && + server.loadBalanced && + session && + session.isPinned && + !session.inTransaction() && + operation.hasAspect(Aspect.CURSOR_CREATING) + ) { + session.unpin({ force: true, forceClear: true }); + } + + operation.execute(server, session, callback); + }); + } + + if ( + readPreference && + !readPreference.equals(ReadPreference.primary) && + session && + session.inTransaction() + ) { + callback( + new MongoTransactionError( + `Read preference in a transaction must be primary, not: ${readPreference.mode}` + ) + ); + + return; + } + + // select a server, and execute the operation against it + topology.selectServer(readPreference, serverSelectionOptions, (err?: any, server?: any) => { + if (err) { + callback(err); + return; + } + + if (session && operation.hasAspect(Aspect.RETRYABLE)) { + const willRetryRead = + topology.s.options.retryReads !== false && + !inTransaction && + supportsRetryableReads(server) && + operation.canRetryRead; + + const willRetryWrite = + topology.s.options.retryWrites === true && + !inTransaction && + supportsRetryableWrites(server) && + operation.canRetryWrite; + + const hasReadAspect = operation.hasAspect(Aspect.READ_OPERATION); + const hasWriteAspect = operation.hasAspect(Aspect.WRITE_OPERATION); + + if ((hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite)) { + if (hasWriteAspect && willRetryWrite) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + + operation.execute(server, session, callbackWithRetry); + return; + } + } + + operation.execute(server, session, callback); + }); +} + +function shouldRetryWrite(err: any) { + return err instanceof MongoError && err.hasErrorLabel('RetryableWriteError'); +} diff --git a/node_modules/mongodb/src/operations/find.ts b/node_modules/mongodb/src/operations/find.ts new file mode 100644 index 0000000..f832eea --- /dev/null +++ b/node_modules/mongodb/src/operations/find.ts @@ -0,0 +1,355 @@ +import { Aspect, defineAspects, Hint } from './operation'; +import { + maxWireVersion, + MongoDBNamespace, + Callback, + normalizeHintField, + decorateWithExplain +} from '../utils'; +import { MongoInvalidArgumentError, MongoCompatibilityError } from '../error'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Collection } from '../collection'; +import { CommandOperation, CommandOperationOptions, CollationOptions } from './command'; +import { Sort, formatSort } from '../sort'; +import { isSharded } from '../cmap/wire_protocol/shared'; +import { ReadConcern } from '../read_concern'; +import type { ClientSession } from '../sessions'; + +/** + * @public + * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export interface FindOptions extends CommandOperationOptions { + /** Sets the limit of documents returned in the query. */ + limit?: number; + /** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */ + sort?: Sort; + /** The fields to return in the query. Object of fields to either include or exclude (one of, not both), `{'a':1, 'b': 1}` **or** `{'a': 0, 'b': 0}` */ + projection?: Document; + /** Set to skip N documents ahead in your query (useful for pagination). */ + skip?: number; + /** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */ + hint?: Hint; + /** Specify if the cursor can timeout. */ + timeout?: boolean; + /** Specify if the cursor is tailable. */ + tailable?: boolean; + /** Specify if the cursor is a a tailable-await cursor. Requires `tailable` to be true */ + awaitData?: boolean; + /** Set the batchSize for the getMoreCommand when iterating over the query results. */ + batchSize?: number; + /** If true, returns only the index keys in the resulting documents. */ + returnKey?: boolean; + /** The inclusive lower bound for a specific index */ + min?: Document; + /** The exclusive upper bound for a specific index */ + max?: Document; + /** You can put a $comment field on a query to make looking in the profiler logs simpler. */ + comment?: string | Document; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true */ + maxAwaitTimeMS?: number; + /** The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. */ + noCursorTimeout?: boolean; + /** Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */ + collation?: CollationOptions; + /** Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) */ + allowDiskUse?: boolean; + /** Determines whether to close the cursor after the first batch. Defaults to false. */ + singleBatch?: boolean; + /** For queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable. */ + allowPartialResults?: boolean; + /** Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents. */ + showRecordId?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; + +/** @internal */ +export class FindOperation extends CommandOperation { + options: FindOptions; + filter: Document; + + constructor( + collection: Collection | undefined, + ns: MongoDBNamespace, + filter: Document = {}, + options: FindOptions = {} + ) { + super(collection, options); + + this.options = options; + this.ns = ns; + + if (typeof filter !== 'object' || Array.isArray(filter)) { + throw new MongoInvalidArgumentError('Query filter must be a plain object or ObjectId'); + } + + // If the filter is a buffer, validate that is a valid BSON document + if (Buffer.isBuffer(filter)) { + const objectSize = filter[0] | (filter[1] << 8) | (filter[2] << 16) | (filter[3] << 24); + if (objectSize !== filter.length) { + throw new MongoInvalidArgumentError( + `Query filter raw message size does not match message header size [${filter.length}] != [${objectSize}]` + ); + } + } + + // special case passing in an ObjectId as a filter + this.filter = filter != null && filter._bsontype === 'ObjectID' ? { _id: filter } : filter; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + this.server = server; + + const serverWireVersion = maxWireVersion(server); + const options = this.options; + if (options.allowDiskUse != null && serverWireVersion < 4) { + callback( + new MongoCompatibilityError('Option "allowDiskUse" is not supported on MongoDB < 3.2') + ); + return; + } + + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback( + new MongoCompatibilityError( + `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation` + ) + ); + + return; + } + + if (serverWireVersion < 4) { + if (this.readConcern && this.readConcern.level !== 'local') { + callback( + new MongoCompatibilityError( + `Server find command does not support a readConcern level of ${this.readConcern.level}` + ) + ); + + return; + } + + const findCommand = makeLegacyFindCommand(this.ns, this.filter, options); + if (isSharded(server) && this.readPreference) { + findCommand.$readPreference = this.readPreference.toJSON(); + } + + server.query( + this.ns, + findCommand, + { + ...this.options, + ...this.bsonOptions, + documentsReturnedIn: 'firstBatch', + readPreference: this.readPreference + }, + callback + ); + + return; + } + + let findCommand = makeFindCommand(this.ns, this.filter, options); + if (this.explain) { + findCommand = decorateWithExplain(findCommand, this.explain); + } + + server.command( + this.ns, + findCommand, + { + ...this.options, + ...this.bsonOptions, + documentsReturnedIn: 'firstBatch', + session + }, + callback + ); + } +} + +function makeFindCommand(ns: MongoDBNamespace, filter: Document, options: FindOptions): Document { + const findCommand: Document = { + find: ns.collection, + filter + }; + + if (options.sort) { + findCommand.sort = formatSort(options.sort); + } + + if (options.projection) { + let projection = options.projection; + if (projection && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; + } + + findCommand.projection = projection; + } + + if (options.hint) { + findCommand.hint = normalizeHintField(options.hint); + } + + if (typeof options.skip === 'number') { + findCommand.skip = options.skip; + } + + if (typeof options.limit === 'number') { + if (options.limit < 0) { + findCommand.limit = -options.limit; + findCommand.singleBatch = true; + } else { + findCommand.limit = options.limit; + } + } + + if (typeof options.batchSize === 'number') { + if (options.batchSize < 0) { + if ( + options.limit && + options.limit !== 0 && + Math.abs(options.batchSize) < Math.abs(options.limit) + ) { + findCommand.limit = -options.batchSize; + } + + findCommand.singleBatch = true; + } else { + findCommand.batchSize = options.batchSize; + } + } + + if (typeof options.singleBatch === 'boolean') { + findCommand.singleBatch = options.singleBatch; + } + + if (options.comment) { + findCommand.comment = options.comment; + } + + if (typeof options.maxTimeMS === 'number') { + findCommand.maxTimeMS = options.maxTimeMS; + } + + const readConcern = ReadConcern.fromOptions(options); + if (readConcern) { + findCommand.readConcern = readConcern.toJSON(); + } + + if (options.max) { + findCommand.max = options.max; + } + + if (options.min) { + findCommand.min = options.min; + } + + if (typeof options.returnKey === 'boolean') { + findCommand.returnKey = options.returnKey; + } + + if (typeof options.showRecordId === 'boolean') { + findCommand.showRecordId = options.showRecordId; + } + + if (typeof options.tailable === 'boolean') { + findCommand.tailable = options.tailable; + } + + if (typeof options.timeout === 'boolean') { + findCommand.noCursorTimeout = !options.timeout; + } else if (typeof options.noCursorTimeout === 'boolean') { + findCommand.noCursorTimeout = options.noCursorTimeout; + } + + if (typeof options.awaitData === 'boolean') { + findCommand.awaitData = options.awaitData; + } + + if (typeof options.allowPartialResults === 'boolean') { + findCommand.allowPartialResults = options.allowPartialResults; + } + + if (options.collation) { + findCommand.collation = options.collation; + } + + if (typeof options.allowDiskUse === 'boolean') { + findCommand.allowDiskUse = options.allowDiskUse; + } + + if (options.let) { + findCommand.let = options.let; + } + + return findCommand; +} + +function makeLegacyFindCommand( + ns: MongoDBNamespace, + filter: Document, + options: FindOptions +): Document { + const findCommand: Document = { + $query: filter + }; + + if (options.sort) { + findCommand.$orderby = formatSort(options.sort); + } + + if (options.hint) { + findCommand.$hint = normalizeHintField(options.hint); + } + + if (typeof options.returnKey === 'boolean') { + findCommand.$returnKey = options.returnKey; + } + + if (options.max) { + findCommand.$max = options.max; + } + + if (options.min) { + findCommand.$min = options.min; + } + + if (typeof options.showRecordId === 'boolean') { + findCommand.$showDiskLoc = options.showRecordId; + } + + if (options.comment) { + findCommand.$comment = options.comment; + } + + if (typeof options.maxTimeMS === 'number') { + findCommand.$maxTimeMS = options.maxTimeMS; + } + + if (options.explain != null) { + findCommand.$explain = true; + } + + return findCommand; +} + +defineAspects(FindOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXPLAINABLE, + Aspect.CURSOR_CREATING +]); diff --git a/node_modules/mongodb/src/operations/find_and_modify.ts b/node_modules/mongodb/src/operations/find_and_modify.ts new file mode 100644 index 0000000..eb04588 --- /dev/null +++ b/node_modules/mongodb/src/operations/find_and_modify.ts @@ -0,0 +1,276 @@ +import { ReadPreference } from '../read_preference'; +import { maxWireVersion, decorateWithCollation, hasAtomicOperators, Callback } from '../utils'; +import { MongoInvalidArgumentError, MongoCompatibilityError } from '../error'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { defineAspects, Aspect } from './operation'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Collection } from '../collection'; +import { Sort, SortForCmd, formatSort } from '../sort'; +import type { ClientSession } from '../sessions'; +import type { WriteConcern, WriteConcernSettings } from '../write_concern'; + +/** @public */ +export const ReturnDocument = Object.freeze({ + BEFORE: 'before', + AFTER: 'after' +} as const); + +/** @public */ +export type ReturnDocument = typeof ReturnDocument[keyof typeof ReturnDocument]; + +/** @public */ +export interface FindOneAndDeleteOptions extends CommandOperationOptions { + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export interface FindOneAndReplaceOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export interface FindOneAndUpdateOptions extends CommandOperationOptions { + /** Optional list of array filters referenced in filtered positional operators */ + arrayFilters?: Document[]; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @internal */ +interface FindAndModifyCmdBase { + remove: boolean; + new: boolean; + upsert: boolean; + update?: Document; + sort?: SortForCmd; + fields?: Document; + bypassDocumentValidation?: boolean; + arrayFilters?: Document[]; + maxTimeMS?: number; + let?: Document; + writeConcern?: WriteConcern | WriteConcernSettings; +} + +function configureFindAndModifyCmdBaseUpdateOpts( + cmdBase: FindAndModifyCmdBase, + options: FindOneAndReplaceOptions | FindOneAndUpdateOptions +): FindAndModifyCmdBase { + cmdBase.new = options.returnDocument === ReturnDocument.AFTER; + cmdBase.upsert = options.upsert === true; + + if (options.bypassDocumentValidation === true) { + cmdBase.bypassDocumentValidation = options.bypassDocumentValidation; + } + return cmdBase; +} + +/** @internal */ +class FindAndModifyOperation extends CommandOperation { + options: FindOneAndReplaceOptions | FindOneAndUpdateOptions | FindOneAndDeleteOptions; + cmdBase: FindAndModifyCmdBase; + collection: Collection; + query: Document; + doc?: Document; + + constructor( + collection: Collection, + query: Document, + options: FindOneAndReplaceOptions | FindOneAndUpdateOptions | FindOneAndDeleteOptions + ) { + super(collection, options); + this.options = options ?? {}; + this.cmdBase = { + remove: false, + new: false, + upsert: false + }; + + const sort = formatSort(options.sort); + if (sort) { + this.cmdBase.sort = sort; + } + + if (options.projection) { + this.cmdBase.fields = options.projection; + } + + if (options.maxTimeMS) { + this.cmdBase.maxTimeMS = options.maxTimeMS; + } + + // Decorate the findAndModify command with the write Concern + if (options.writeConcern) { + this.cmdBase.writeConcern = options.writeConcern; + } + + if (options.let) { + this.cmdBase.let = options.let; + } + + // force primary read preference + this.readPreference = ReadPreference.primary; + + this.collection = collection; + this.query = query; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const coll = this.collection; + const query = this.query; + const options = { ...this.options, ...this.bsonOptions }; + + // Create findAndModify command object + const cmd: Document = { + findAndModify: coll.collectionName, + query: query, + ...this.cmdBase + }; + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return callback(err); + } + + if (options.hint) { + // TODO: once this method becomes a CommandOperation we will have the server + // in place to check. + const unacknowledgedWrite = this.writeConcern?.w === 0; + if (unacknowledgedWrite || maxWireVersion(server) < 8) { + callback( + new MongoCompatibilityError( + 'The current topology does not support a hint on findAndModify commands' + ) + ); + + return; + } + + cmd.hint = options.hint; + } + + if (this.explain && maxWireVersion(server) < 4) { + callback( + new MongoCompatibilityError( + `Server ${server.name} does not support explain on findAndModify` + ) + ); + return; + } + + // Execute the command + super.executeCommand(server, session, cmd, (err, result) => { + if (err) return callback(err); + return callback(undefined, result); + }); + } +} + +/** @internal */ +export class FindOneAndDeleteOperation extends FindAndModifyOperation { + constructor(collection: Collection, filter: Document, options: FindOneAndDeleteOptions) { + // Basic validation + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Argument "filter" must be an object'); + } + + super(collection, filter, options); + this.cmdBase.remove = true; + } +} + +/** @internal */ +export class FindOneAndReplaceOperation extends FindAndModifyOperation { + constructor( + collection: Collection, + filter: Document, + replacement: Document, + options: FindOneAndReplaceOptions + ) { + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Argument "filter" must be an object'); + } + + if (replacement == null || typeof replacement !== 'object') { + throw new MongoInvalidArgumentError('Argument "replacement" must be an object'); + } + + if (hasAtomicOperators(replacement)) { + throw new MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + + super(collection, filter, options); + this.cmdBase.update = replacement; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + } +} + +/** @internal */ +export class FindOneAndUpdateOperation extends FindAndModifyOperation { + constructor( + collection: Collection, + filter: Document, + update: Document, + options: FindOneAndUpdateOptions + ) { + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Argument "filter" must be an object'); + } + + if (update == null || typeof update !== 'object') { + throw new MongoInvalidArgumentError('Argument "update" must be an object'); + } + + if (!hasAtomicOperators(update)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + + super(collection, filter, options); + this.cmdBase.update = update; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + + if (options.arrayFilters) { + this.cmdBase.arrayFilters = options.arrayFilters; + } + } +} + +defineAspects(FindAndModifyOperation, [ + Aspect.WRITE_OPERATION, + Aspect.RETRYABLE, + Aspect.EXPLAINABLE +]); diff --git a/node_modules/mongodb/src/operations/indexes.ts b/node_modules/mongodb/src/operations/indexes.ts new file mode 100644 index 0000000..91b479f --- /dev/null +++ b/node_modules/mongodb/src/operations/indexes.ts @@ -0,0 +1,525 @@ +import { indexInformation, IndexInformationOptions } from './common_functions'; +import { AbstractOperation, Aspect, defineAspects } from './operation'; +import { MONGODB_ERROR_CODES, MongoServerError, MongoCompatibilityError } from '../error'; +import { + maxWireVersion, + parseIndexOptions, + MongoDBNamespace, + Callback, + getTopology +} from '../utils'; +import { + CommandOperation, + CommandOperationOptions, + OperationParent, + CollationOptions +} from './command'; +import { ReadPreference } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Db } from '../db'; +import { AbstractCursor } from '../cursor/abstract_cursor'; +import type { ClientSession } from '../sessions'; +import { executeOperation, ExecutionResult } from './execute_operation'; +import type { OneOrMore } from '../mongo_types'; + +const LIST_INDEXES_WIRE_VERSION = 3; +const VALID_INDEX_OPTIONS = new Set([ + 'background', + 'unique', + 'name', + 'partialFilterExpression', + 'sparse', + 'hidden', + 'expireAfterSeconds', + 'storageEngine', + 'collation', + 'version', + + // text indexes + 'weights', + 'default_language', + 'language_override', + 'textIndexVersion', + + // 2d-sphere indexes + '2dsphereIndexVersion', + + // 2d indexes + 'bits', + 'min', + 'max', + + // geoHaystack Indexes + 'bucketSize', + + // wildcard indexes + 'wildcardProjection' +]); + +/** @public */ +export type IndexDirection = -1 | 1 | '2d' | '2dsphere' | 'text' | 'geoHaystack' | number; + +/** @public */ +export type IndexSpecification = OneOrMore< + | string + | [string, IndexDirection] + | { [key: string]: IndexDirection } + | [string, IndexDirection][] + | { [key: string]: IndexDirection }[] +>; + +/** @public */ +export interface IndexDescription + extends Pick< + CreateIndexesOptions, + | 'background' + | 'unique' + | 'partialFilterExpression' + | 'sparse' + | 'hidden' + | 'expireAfterSeconds' + | 'storageEngine' + | 'version' + | 'weights' + | 'default_language' + | 'language_override' + | 'textIndexVersion' + | '2dsphereIndexVersion' + | 'bits' + | 'min' + | 'max' + | 'bucketSize' + | 'wildcardProjection' + > { + collation?: CollationOptions; + name?: string; + key: Document; +} + +/** @public */ +export interface CreateIndexesOptions extends CommandOperationOptions { + /** Creates the index in the background, yielding whenever possible. */ + background?: boolean; + /** Creates an unique index. */ + unique?: boolean; + /** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */ + name?: string; + /** Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */ + partialFilterExpression?: Document; + /** Creates a sparse index. */ + sparse?: boolean; + /** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */ + expireAfterSeconds?: number; + /** Allows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher) */ + storageEngine?: Document; + /** (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. */ + commitQuorum?: number | string; + /** Specifies the index version number, either 0 or 1. */ + version?: number; + // text indexes + weights?: Document; + default_language?: string; + language_override?: string; + textIndexVersion?: number; + // 2d-sphere indexes + '2dsphereIndexVersion'?: number; + // 2d indexes + bits?: number; + /** For geospatial indexes set the lower bound for the co-ordinates. */ + min?: number; + /** For geospatial indexes set the high bound for the co-ordinates. */ + max?: number; + // geoHaystack Indexes + bucketSize?: number; + // wildcard indexes + wildcardProjection?: Document; + /** Specifies that the index should exist on the target collection but should not be used by the query planner when executing operations. (MongoDB 4.4 or higher) */ + hidden?: boolean; +} + +function makeIndexSpec(indexSpec: IndexSpecification, options: any): IndexDescription { + const indexParameters = parseIndexOptions(indexSpec); + + // Generate the index name + const name = typeof options.name === 'string' ? options.name : indexParameters.name; + + // Set up the index + const finalIndexSpec: Document = { name, key: indexParameters.fieldHash }; + + // merge valid index options into the index spec + for (const optionName in options) { + if (VALID_INDEX_OPTIONS.has(optionName)) { + finalIndexSpec[optionName] = options[optionName]; + } + } + + return finalIndexSpec as IndexDescription; +} + +/** @internal */ +export class IndexesOperation extends AbstractOperation { + options: IndexInformationOptions; + collection: Collection; + + constructor(collection: Collection, options: IndexInformationOptions) { + super(options); + this.options = options; + this.collection = collection; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const coll = this.collection; + const options = this.options; + + indexInformation( + coll.s.db, + coll.collectionName, + { full: true, ...options, readPreference: this.readPreference, session }, + callback + ); + } +} + +/** @internal */ +export class CreateIndexesOperation< + T extends string | string[] = string[] +> extends CommandOperation { + options: CreateIndexesOptions; + collectionName: string; + indexes: IndexDescription[]; + + constructor( + parent: OperationParent, + collectionName: string, + indexes: IndexDescription[], + options?: CreateIndexesOptions + ) { + super(parent, options); + + this.options = options ?? {}; + this.collectionName = collectionName; + + this.indexes = indexes; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const options = this.options; + const indexes = this.indexes; + + const serverWireVersion = maxWireVersion(server); + + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexes.length; i++) { + // Did the user pass in a collation, check if our write server supports it + if (indexes[i].collation && serverWireVersion < 5) { + callback( + new MongoCompatibilityError( + `Server ${server.name}, which reports wire version ${serverWireVersion}, ` + + 'does not support collation' + ) + ); + return; + } + + if (indexes[i].name == null) { + const keys = []; + + for (const name in indexes[i].key) { + keys.push(`${name}_${indexes[i].key[name]}`); + } + + // Set the name + indexes[i].name = keys.join('_'); + } + } + + const cmd: Document = { createIndexes: this.collectionName, indexes }; + + if (options.commitQuorum != null) { + if (serverWireVersion < 9) { + callback( + new MongoCompatibilityError( + 'Option `commitQuorum` for `createIndexes` not supported on servers < 4.4' + ) + ); + return; + } + cmd.commitQuorum = options.commitQuorum; + } + + // collation is set on each index, it should not be defined at the root + this.options.collation = undefined; + + super.executeCommand(server, session, cmd, err => { + if (err) { + callback(err); + return; + } + + const indexNames = indexes.map(index => index.name || ''); + callback(undefined, indexNames as T); + }); + } +} + +/** @internal */ +export class CreateIndexOperation extends CreateIndexesOperation { + constructor( + parent: OperationParent, + collectionName: string, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ) { + // createIndex can be called with a variety of styles: + // coll.createIndex('a'); + // coll.createIndex({ a: 1 }); + // coll.createIndex([['a', 1]]); + // createIndexes is always called with an array of index spec objects + + super(parent, collectionName, [makeIndexSpec(indexSpec, options)], options); + } + execute(server: Server, session: ClientSession, callback: Callback): void { + super.execute(server, session, (err, indexNames) => { + if (err || !indexNames) return callback(err); + return callback(undefined, indexNames[0]); + }); + } +} + +/** @internal */ +export class EnsureIndexOperation extends CreateIndexOperation { + db: Db; + collectionName: string; + + constructor( + db: Db, + collectionName: string, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ) { + super(db, collectionName, indexSpec, options); + + this.readPreference = ReadPreference.primary; + this.db = db; + this.collectionName = collectionName; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const indexName = this.indexes[0].name; + const cursor = this.db.collection(this.collectionName).listIndexes({ session }); + cursor.toArray((err, indexes) => { + /// ignore "NamespaceNotFound" errors + if (err && (err as MongoServerError).code !== MONGODB_ERROR_CODES.NamespaceNotFound) { + return callback(err); + } + + if (indexes) { + indexes = Array.isArray(indexes) ? indexes : [indexes]; + if (indexes.some(index => index.name === indexName)) { + callback(undefined, indexName); + return; + } + } + + super.execute(server, session, callback); + }); + } +} + +/** @public */ +export type DropIndexesOptions = CommandOperationOptions; + +/** @internal */ +export class DropIndexOperation extends CommandOperation { + options: DropIndexesOptions; + collection: Collection; + indexName: string; + + constructor(collection: Collection, indexName: string, options?: DropIndexesOptions) { + super(collection, options); + + this.options = options ?? {}; + this.collection = collection; + this.indexName = indexName; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const cmd = { dropIndexes: this.collection.collectionName, index: this.indexName }; + super.executeCommand(server, session, cmd, callback); + } +} + +/** @internal */ +export class DropIndexesOperation extends DropIndexOperation { + constructor(collection: Collection, options: DropIndexesOptions) { + super(collection, '*', options); + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + super.execute(server, session, err => { + if (err) return callback(err, false); + callback(undefined, true); + }); + } +} + +/** @public */ +export interface ListIndexesOptions extends CommandOperationOptions { + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** @internal */ +export class ListIndexesOperation extends CommandOperation { + options: ListIndexesOptions; + collectionNamespace: MongoDBNamespace; + + constructor(collection: Collection, options?: ListIndexesOptions) { + super(collection, options); + + this.options = options ?? {}; + this.collectionNamespace = collection.s.namespace; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const serverWireVersion = maxWireVersion(server); + if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) { + const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes'); + const collectionNS = this.collectionNamespace.toString(); + + server.query( + systemIndexesNS, + { query: { ns: collectionNS } }, + { ...this.options, readPreference: this.readPreference }, + callback + ); + return; + } + + const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; + super.executeCommand( + server, + session, + { listIndexes: this.collectionNamespace.collection, cursor }, + callback + ); + } +} + +/** @public */ +export class ListIndexesCursor extends AbstractCursor { + parent: Collection; + options?: ListIndexesOptions; + + constructor(collection: Collection, options?: ListIndexesOptions) { + super(getTopology(collection), collection.s.namespace, options); + this.parent = collection; + this.options = options; + } + + clone(): ListIndexesCursor { + return new ListIndexesCursor(this.parent, { + ...this.options, + ...this.cursorOptions + }); + } + + /** @internal */ + _initialize(session: ClientSession | undefined, callback: Callback): void { + const operation = new ListIndexesOperation(this.parent, { + ...this.cursorOptions, + ...this.options, + session + }); + + executeOperation(getTopology(this.parent), operation, (err, response) => { + if (err || response == null) return callback(err); + + // TODO: NODE-2882 + callback(undefined, { server: operation.server, session, response }); + }); + } +} + +/** @internal */ +export class IndexExistsOperation extends AbstractOperation { + options: IndexInformationOptions; + collection: Collection; + indexes: string | string[]; + + constructor( + collection: Collection, + indexes: string | string[], + options: IndexInformationOptions + ) { + super(options); + this.options = options; + this.collection = collection; + this.indexes = indexes; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const coll = this.collection; + const indexes = this.indexes; + + indexInformation( + coll.s.db, + coll.collectionName, + { ...this.options, readPreference: this.readPreference, session }, + (err, indexInformation) => { + // If we have an error return + if (err != null) return callback(err); + // Let's check for the index names + if (!Array.isArray(indexes)) return callback(undefined, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return callback(undefined, false); + } + } + + // All keys found return true + return callback(undefined, true); + } + ); + } +} + +/** @internal */ +export class IndexInformationOperation extends AbstractOperation { + options: IndexInformationOptions; + db: Db; + name: string; + + constructor(db: Db, name: string, options?: IndexInformationOptions) { + super(options); + this.options = options ?? {}; + this.db = db; + this.name = name; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const db = this.db; + const name = this.name; + + indexInformation( + db, + name, + { ...this.options, readPreference: this.readPreference, session }, + callback + ); + } +} + +defineAspects(ListIndexesOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.CURSOR_CREATING +]); +defineAspects(CreateIndexesOperation, [Aspect.WRITE_OPERATION]); +defineAspects(CreateIndexOperation, [Aspect.WRITE_OPERATION]); +defineAspects(EnsureIndexOperation, [Aspect.WRITE_OPERATION]); +defineAspects(DropIndexOperation, [Aspect.WRITE_OPERATION]); +defineAspects(DropIndexesOperation, [Aspect.WRITE_OPERATION]); diff --git a/node_modules/mongodb/src/operations/insert.ts b/node_modules/mongodb/src/operations/insert.ts new file mode 100644 index 0000000..10af5ce --- /dev/null +++ b/node_modules/mongodb/src/operations/insert.ts @@ -0,0 +1,137 @@ +import { MongoServerError, MongoInvalidArgumentError } from '../error'; +import { defineAspects, Aspect, AbstractOperation } from './operation'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { prepareDocs } from './common_functions'; +import type { Callback, MongoDBNamespace } from '../utils'; +import type { Server } from '../sdam/server'; +import type { Collection } from '../collection'; +import type { Document } from '../bson'; +import type { BulkWriteOptions } from '../bulk/common'; +import { WriteConcern } from '../write_concern'; +import type { ClientSession } from '../sessions'; +import { BulkWriteOperation } from './bulk_write'; +import type { InferIdType } from '../mongo_types'; + +/** @internal */ +export class InsertOperation extends CommandOperation { + options: BulkWriteOptions; + documents: Document[]; + + constructor(ns: MongoDBNamespace, documents: Document[], options: BulkWriteOptions) { + super(undefined, options); + this.options = { ...options, checkKeys: options.checkKeys ?? false }; + this.ns = ns; + this.documents = documents; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command: Document = { + insert: this.ns.collection, + documents: this.documents, + ordered + }; + + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + if (options.comment != null) { + command.comment = options.comment; + } + + super.executeCommand(server, session, command, callback); + } +} + +/** @public */ +export interface InsertOneOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; +} + +/** @public */ +export interface InsertOneResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The identifier that was inserted. If the server generated the identifier, this value will be null as the driver does not have access to that data */ + insertedId: InferIdType; +} + +export class InsertOneOperation extends InsertOperation { + constructor(collection: Collection, doc: Document, options: InsertOneOptions) { + super(collection.s.namespace, prepareDocs(collection, [doc], options), options); + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + super.execute(server, session, (err, res) => { + if (err || res == null) return callback(err); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) { + // This should be a WriteError but we can't change it now because of error hierarchy + return callback(new MongoServerError(res.writeErrors[0])); + } + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + insertedId: this.documents[0]._id + }); + }); + } +} + +/** @public */ +export interface InsertManyResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of inserted documents for this operations */ + insertedCount: number; + /** Map of the index of the inserted document to the id of the inserted document */ + insertedIds: { [key: number]: InferIdType }; +} + +/** @internal */ +export class InsertManyOperation extends AbstractOperation { + options: BulkWriteOptions; + collection: Collection; + docs: Document[]; + + constructor(collection: Collection, docs: Document[], options: BulkWriteOptions) { + super(options); + + if (!Array.isArray(docs)) { + throw new MongoInvalidArgumentError('Argument "docs" must be an array of documents'); + } + + this.options = options; + this.collection = collection; + this.docs = docs; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const coll = this.collection; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + const writeConcern = WriteConcern.fromOptions(options); + const bulkWriteOperation = new BulkWriteOperation( + coll, + prepareDocs(coll, this.docs, options).map(document => ({ insertOne: { document } })), + options + ); + + bulkWriteOperation.execute(server, session, (err, res) => { + if (err || res == null) return callback(err); + callback(undefined, { + acknowledged: writeConcern?.w !== 0 ?? true, + insertedCount: res.insertedCount, + insertedIds: res.insertedIds + }); + }); + } +} + +defineAspects(InsertOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION]); +defineAspects(InsertOneOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION]); +defineAspects(InsertManyOperation, [Aspect.WRITE_OPERATION]); diff --git a/node_modules/mongodb/src/operations/is_capped.ts b/node_modules/mongodb/src/operations/is_capped.ts new file mode 100644 index 0000000..4adc5f5 --- /dev/null +++ b/node_modules/mongodb/src/operations/is_capped.ts @@ -0,0 +1,38 @@ +import type { Callback } from '../utils'; +import type { Collection } from '../collection'; +import { OperationOptions, AbstractOperation } from './operation'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { MongoAPIError } from '../error'; + +/** @internal */ +export class IsCappedOperation extends AbstractOperation { + options: OperationOptions; + collection: Collection; + + constructor(collection: Collection, options: OperationOptions) { + super(options); + this.options = options; + this.collection = collection; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const coll = this.collection; + + coll.s.db + .listCollections( + { name: coll.collectionName }, + { ...this.options, nameOnly: false, readPreference: this.readPreference, session } + ) + .toArray((err, collections) => { + if (err || !collections) return callback(err); + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new MongoAPIError(`collection ${coll.namespace} not found`)); + } + + const collOptions = collections[0].options; + callback(undefined, !!(collOptions && collOptions.capped)); + }); + } +} diff --git a/node_modules/mongodb/src/operations/list_collections.ts b/node_modules/mongodb/src/operations/list_collections.ts new file mode 100644 index 0000000..4ba93ea --- /dev/null +++ b/node_modules/mongodb/src/operations/list_collections.ts @@ -0,0 +1,161 @@ +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; +import { maxWireVersion, Callback, getTopology, MongoDBNamespace } from '../utils'; +import * as CONSTANTS from '../constants'; +import type { Binary, Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Db } from '../db'; +import { AbstractCursor } from '../cursor/abstract_cursor'; +import type { ClientSession } from '../sessions'; +import { executeOperation, ExecutionResult } from './execute_operation'; + +const LIST_COLLECTIONS_WIRE_VERSION = 3; + +/** @public */ +export interface ListCollectionsOptions extends CommandOperationOptions { + /** Since 4.0: If true, will only return the collection name in the response, and will omit additional info */ + nameOnly?: boolean; + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** @internal */ +export class ListCollectionsOperation extends CommandOperation { + options: ListCollectionsOptions; + db: Db; + filter: Document; + nameOnly: boolean; + batchSize?: number; + + constructor(db: Db, filter: Document, options?: ListCollectionsOptions) { + super(db, options); + + this.options = options ?? {}; + this.db = db; + this.filter = filter; + this.nameOnly = !!this.options.nameOnly; + + if (typeof this.options.batchSize === 'number') { + this.batchSize = this.options.batchSize; + } + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + if (maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) { + let filter = this.filter; + const databaseName = this.db.s.namespace.db; + + // If we have legacy mode and have not provided a full db name filter it + if (typeof filter.name === 'string' && !new RegExp(`^${databaseName}\\.`).test(filter.name)) { + filter = Object.assign({}, filter); + filter.name = this.db.s.namespace.withCollection(filter.name).toString(); + } + + // No filter, filter by current database + if (filter == null) { + filter = { name: `/${databaseName}/` }; + } + + // Rewrite the filter to use $and to filter out indexes + if (filter.name) { + filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; + } else { + filter = { name: /^((?!\$).)*$/ }; + } + + const documentTransform = (doc: Document) => { + const matching = `${databaseName}.`; + const index = doc.name.indexOf(matching); + // Remove database name if available + if (doc.name && index === 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + }; + + server.query( + new MongoDBNamespace(databaseName, CONSTANTS.SYSTEM_NAMESPACE_COLLECTION), + { query: filter }, + { batchSize: this.batchSize || 1000, readPreference: this.readPreference }, + (err, result) => { + if (result && result.documents && Array.isArray(result.documents)) { + result.documents = result.documents.map(documentTransform); + } + + callback(err, result); + } + ); + + return; + } + + const command = { + listCollections: 1, + filter: this.filter, + cursor: this.batchSize ? { batchSize: this.batchSize } : {}, + nameOnly: this.nameOnly + }; + + return super.executeCommand(server, session, command, callback); + } +} + +/** @public */ +export interface CollectionInfo extends Document { + name: string; + type?: string; + options?: Document; + info?: { + readOnly?: false; + uuid?: Binary; + }; + idIndex?: Document; +} + +/** @public */ +export class ListCollectionsCursor< + T extends Pick | CollectionInfo = + | Pick + | CollectionInfo +> extends AbstractCursor { + parent: Db; + filter: Document; + options?: ListCollectionsOptions; + + constructor(db: Db, filter: Document, options?: ListCollectionsOptions) { + super(getTopology(db), db.s.namespace, options); + this.parent = db; + this.filter = filter; + this.options = options; + } + + clone(): ListCollectionsCursor { + return new ListCollectionsCursor(this.parent, this.filter, { + ...this.options, + ...this.cursorOptions + }); + } + + /** @internal */ + _initialize(session: ClientSession | undefined, callback: Callback): void { + const operation = new ListCollectionsOperation(this.parent, this.filter, { + ...this.cursorOptions, + ...this.options, + session + }); + + executeOperation(getTopology(this.parent), operation, (err, response) => { + if (err || response == null) return callback(err); + + // TODO: NODE-2882 + callback(undefined, { server: operation.server, session, response }); + }); + } +} + +defineAspects(ListCollectionsOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.CURSOR_CREATING +]); diff --git a/node_modules/mongodb/src/operations/list_databases.ts b/node_modules/mongodb/src/operations/list_databases.ts new file mode 100644 index 0000000..d138e35 --- /dev/null +++ b/node_modules/mongodb/src/operations/list_databases.ts @@ -0,0 +1,50 @@ +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; +import { MongoDBNamespace, Callback } from '../utils'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Db } from '../db'; +import type { ClientSession } from '../sessions'; + +/** @public */ +export type ListDatabasesResult = string[] | Document[]; + +/** @public */ +export interface ListDatabasesOptions extends CommandOperationOptions { + /** A query predicate that determines which databases are listed */ + filter?: Document; + /** A flag to indicate whether the command should return just the database names, or return both database names and size information */ + nameOnly?: boolean; + /** A flag that determines which databases are returned based on the user privileges when access control is enabled */ + authorizedDatabases?: boolean; +} + +/** @internal */ +export class ListDatabasesOperation extends CommandOperation { + options: ListDatabasesOptions; + + constructor(db: Db, options?: ListDatabasesOptions) { + super(db, options); + this.options = options ?? {}; + this.ns = new MongoDBNamespace('admin', '$cmd'); + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const cmd: Document = { listDatabases: 1 }; + if (this.options.nameOnly) { + cmd.nameOnly = Number(cmd.nameOnly); + } + + if (this.options.filter) { + cmd.filter = this.options.filter; + } + + if (typeof this.options.authorizedDatabases === 'boolean') { + cmd.authorizedDatabases = this.options.authorizedDatabases; + } + + super.executeCommand(server, session, cmd, callback); + } +} + +defineAspects(ListDatabasesOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE]); diff --git a/node_modules/mongodb/src/operations/map_reduce.ts b/node_modules/mongodb/src/operations/map_reduce.ts new file mode 100644 index 0000000..3e84aeb --- /dev/null +++ b/node_modules/mongodb/src/operations/map_reduce.ts @@ -0,0 +1,248 @@ +import { Code, Document } from '../bson'; +import { + applyWriteConcern, + decorateWithCollation, + decorateWithReadConcern, + isObject, + Callback, + maxWireVersion +} from '../utils'; +import { ReadPreference, ReadPreferenceMode } from '../read_preference'; +import { CommandOperation, CommandOperationOptions } from './command'; +import type { Server } from '../sdam/server'; +import type { Collection } from '../collection'; +import type { Sort } from '../sort'; +import { MongoServerError, MongoCompatibilityError } from '../error'; +import type { ObjectId } from '../bson'; +import { Aspect, defineAspects } from './operation'; +import type { ClientSession } from '../sessions'; +import { Db } from '../db'; + +const exclusionList = [ + 'explain', + 'readPreference', + 'readConcern', + 'session', + 'bypassDocumentValidation', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined', + 'scope' // this option is reformatted thus exclude the original +]; + +/** @public */ +export type MapFunction = (this: TSchema) => void; +/** @public */ +export type ReduceFunction = (key: TKey, values: TValue[]) => TValue; +/** @public */ +export type FinalizeFunction = ( + key: TKey, + reducedValue: TValue +) => TValue; + +/** @public */ +export interface MapReduceOptions + extends CommandOperationOptions { + /** Sets the output target for the map reduce job. */ + out?: 'inline' | { inline: 1 } | { replace: string } | { merge: string } | { reduce: string }; + /** Query filter object. */ + query?: Document; + /** Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. */ + sort?: Sort; + /** Number of objects to return from collection. */ + limit?: number; + /** Keep temporary data. */ + keeptemp?: boolean; + /** Finalize function. */ + finalize?: FinalizeFunction | string; + /** Can pass in variables that can be access from map/reduce/finalize. */ + scope?: Document; + /** It is possible to make the execution stay in JS. Provided in MongoDB \> 2.0.X. */ + jsMode?: boolean; + /** Provide statistics on job execution time. */ + verbose?: boolean; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; +} + +interface MapReduceStats { + processtime?: number; + counts?: number; + timing?: number; +} + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * @internal + */ +export class MapReduceOperation extends CommandOperation { + options: MapReduceOptions; + collection: Collection; + /** The mapping function. */ + map: MapFunction | string; + /** The reduce function. */ + reduce: ReduceFunction | string; + + /** + * Constructs a MapReduce operation. + * + * @param collection - Collection instance. + * @param map - The mapping function. + * @param reduce - The reduce function. + * @param options - Optional settings. See Collection.prototype.mapReduce for a list of options. + */ + constructor( + collection: Collection, + map: MapFunction | string, + reduce: ReduceFunction | string, + options?: MapReduceOptions + ) { + super(collection, options); + + this.options = options ?? {}; + this.collection = collection; + this.map = map; + this.reduce = reduce; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const coll = this.collection; + const map = this.map; + const reduce = this.reduce; + let options = this.options; + + const mapCommandHash: Document = { + mapReduce: coll.collectionName, + map: map, + reduce: reduce + }; + + if (options.scope) { + mapCommandHash.scope = processScope(options.scope); + } + + // Add any other options passed in + for (const n in options) { + // Only include if not in exclusion list + if (exclusionList.indexOf(n) === -1) { + mapCommandHash[n] = (options as any)[n]; + } + } + + options = Object.assign({}, options); + + // If we have a read preference and inline is not set as output fail hard + if ( + this.readPreference.mode === ReadPreferenceMode.primary && + options.out && + (options.out as any).inline !== 1 && + options.out !== 'inline' + ) { + // Force readPreference to primary + options.readPreference = ReadPreference.primary; + // Decorate command with writeConcern if supported + applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); + } else { + decorateWithReadConcern(mapCommandHash, coll, options); + } + + // Is bypassDocumentValidation specified + if (options.bypassDocumentValidation === true) { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Have we specified collation + try { + decorateWithCollation(mapCommandHash, coll, options); + } catch (err) { + return callback(err); + } + + if (this.explain && maxWireVersion(server) < 9) { + callback( + new MongoCompatibilityError(`Server ${server.name} does not support explain on mapReduce`) + ); + return; + } + + // Execute command + super.executeCommand(server, session, mapCommandHash, (err, result) => { + if (err) return callback(err); + // Check if we have an error + if (1 !== result.ok || result.err || result.errmsg) { + return callback(new MongoServerError(result)); + } + + // If an explain option was executed, don't process the server results + if (this.explain) return callback(undefined, result); + + // Create statistics value + const stats: MapReduceStats = {}; + if (result.timeMillis) stats['processtime'] = result.timeMillis; + if (result.counts) stats['counts'] = result.counts; + if (result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if (result.results) { + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return callback(undefined, result.results); + } + + return callback(undefined, { results: result.results, stats: stats }); + } + + // The returned collection + let collection = null; + + // If we have an object it's a different db + if (result.result != null && typeof result.result === 'object') { + const doc = result.result; + // Return a collection from another db + collection = new Db(coll.s.db.s.client, doc.db, coll.s.db.s.options).collection( + doc.collection + ); + } else { + // Create a collection object that wraps the result collection + collection = coll.s.db.collection(result.result); + } + + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return callback(err, collection); + } + + // Return stats as third set of values + callback(err, { collection, stats }); + }); + } +} + +/** Functions that are passed as scope args must be converted to Code instances. */ +function processScope(scope: Document | ObjectId) { + if (!isObject(scope) || (scope as any)._bsontype === 'ObjectID') { + return scope; + } + + const newScope: Document = {}; + + for (const key of Object.keys(scope)) { + if ('function' === typeof (scope as Document)[key]) { + newScope[key] = new Code(String((scope as Document)[key])); + } else if ((scope as Document)[key]._bsontype === 'Code') { + newScope[key] = (scope as Document)[key]; + } else { + newScope[key] = processScope((scope as Document)[key]); + } + } + + return newScope; +} + +defineAspects(MapReduceOperation, [Aspect.EXPLAINABLE]); diff --git a/node_modules/mongodb/src/operations/operation.ts b/node_modules/mongodb/src/operations/operation.ts new file mode 100644 index 0000000..c503b81 --- /dev/null +++ b/node_modules/mongodb/src/operations/operation.ts @@ -0,0 +1,116 @@ +import { ReadPreference, ReadPreferenceLike } from '../read_preference'; +import type { ClientSession } from '../sessions'; +import { Document, BSONSerializeOptions, resolveBSONOptions } from '../bson'; +import type { MongoDBNamespace, Callback } from '../utils'; +import type { Server } from '../sdam/server'; + +export const Aspect = { + READ_OPERATION: Symbol('READ_OPERATION'), + WRITE_OPERATION: Symbol('WRITE_OPERATION'), + RETRYABLE: Symbol('RETRYABLE'), + EXPLAINABLE: Symbol('EXPLAINABLE'), + SKIP_COLLATION: Symbol('SKIP_COLLATION'), + CURSOR_CREATING: Symbol('CURSOR_CREATING') +} as const; + +/** @public */ +export type Hint = string | Document; + +export interface OperationConstructor extends Function { + aspects?: Set; +} + +/** @public */ +export interface OperationOptions extends BSONSerializeOptions { + /** Specify ClientSession for this command */ + session?: ClientSession; + willRetryWrites?: boolean; + + /** The preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest). */ + readPreference?: ReadPreferenceLike; + + /** @internal Hints to `executeOperation` that this operation should not unpin on an ended transaction */ + bypassPinningCheck?: boolean; +} + +/** @internal */ +const kSession = Symbol('session'); + +/** + * This class acts as a parent class for any operation and is responsible for setting this.options, + * as well as setting and getting a session. + * Additionally, this class implements `hasAspect`, which determines whether an operation has + * a specific aspect. + * @internal + */ +export abstract class AbstractOperation { + ns!: MongoDBNamespace; + cmd!: Document; + readPreference: ReadPreference; + server!: Server; + bypassPinningCheck: boolean; + + // BSON serialization options + bsonOptions?: BSONSerializeOptions; + + // TODO: Each operation defines its own options, there should be better typing here + options: Document; + + [kSession]: ClientSession; + + constructor(options: OperationOptions = {}) { + this.readPreference = this.hasAspect(Aspect.WRITE_OPERATION) + ? ReadPreference.primary + : ReadPreference.fromOptions(options) ?? ReadPreference.primary; + + // Pull the BSON serialize options from the already-resolved options + this.bsonOptions = resolveBSONOptions(options); + + if (options.session) { + this[kSession] = options.session; + } + + this.options = options; + this.bypassPinningCheck = !!options.bypassPinningCheck; + } + + abstract execute(server: Server, session: ClientSession, callback: Callback): void; + + hasAspect(aspect: symbol): boolean { + const ctor = this.constructor as OperationConstructor; + if (ctor.aspects == null) { + return false; + } + + return ctor.aspects.has(aspect); + } + + get session(): ClientSession { + return this[kSession]; + } + + get canRetryRead(): boolean { + return true; + } + + get canRetryWrite(): boolean { + return true; + } +} + +export function defineAspects( + operation: OperationConstructor, + aspects: symbol | symbol[] | Set +): Set { + if (!Array.isArray(aspects) && !(aspects instanceof Set)) { + aspects = [aspects]; + } + + aspects = new Set(aspects); + Object.defineProperty(operation, 'aspects', { + value: aspects, + writable: false + }); + + return aspects; +} diff --git a/node_modules/mongodb/src/operations/options_operation.ts b/node_modules/mongodb/src/operations/options_operation.ts new file mode 100644 index 0000000..0d1dee1 --- /dev/null +++ b/node_modules/mongodb/src/operations/options_operation.ts @@ -0,0 +1,38 @@ +import { AbstractOperation, OperationOptions } from './operation'; +import { MongoAPIError } from '../error'; +import type { Callback } from '../utils'; +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; + +/** @internal */ +export class OptionsOperation extends AbstractOperation { + options: OperationOptions; + collection: Collection; + + constructor(collection: Collection, options: OperationOptions) { + super(options); + this.options = options; + this.collection = collection; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const coll = this.collection; + + coll.s.db + .listCollections( + { name: coll.collectionName }, + { ...this.options, nameOnly: false, readPreference: this.readPreference, session } + ) + .toArray((err, collections) => { + if (err || !collections) return callback(err); + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new MongoAPIError(`collection ${coll.namespace} not found`)); + } + + callback(err, collections[0].options); + }); + } +} diff --git a/node_modules/mongodb/src/operations/profiling_level.ts b/node_modules/mongodb/src/operations/profiling_level.ts new file mode 100644 index 0000000..2c28da5 --- /dev/null +++ b/node_modules/mongodb/src/operations/profiling_level.ts @@ -0,0 +1,35 @@ +import { CommandOperation, CommandOperationOptions } from './command'; +import type { Callback } from '../utils'; +import type { Server } from '../sdam/server'; +import type { Db } from '../db'; +import type { ClientSession } from '../sessions'; +import { MongoRuntimeError } from '../error'; + +/** @public */ +export type ProfilingLevelOptions = CommandOperationOptions; + +/** @internal */ +export class ProfilingLevelOperation extends CommandOperation { + options: ProfilingLevelOptions; + + constructor(db: Db, options: ProfilingLevelOptions) { + super(db, options); + this.options = options; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + super.executeCommand(server, session, { profile: -1 }, (err, doc) => { + if (err == null && doc.ok === 1) { + const was = doc.was; + if (was === 0) return callback(undefined, 'off'); + if (was === 1) return callback(undefined, 'slow_only'); + if (was === 2) return callback(undefined, 'all'); + // TODO(NODE-3483) + return callback(new MongoRuntimeError(`Illegal profiling level value ${was}`)); + } else { + // TODO(NODE-3483): Consider MongoUnexpectedServerResponseError + err != null ? callback(err) : callback(new MongoRuntimeError('Error with profile command')); + } + }); + } +} diff --git a/node_modules/mongodb/src/operations/remove_user.ts b/node_modules/mongodb/src/operations/remove_user.ts new file mode 100644 index 0000000..073b6eb --- /dev/null +++ b/node_modules/mongodb/src/operations/remove_user.ts @@ -0,0 +1,29 @@ +import { Aspect, defineAspects } from './operation'; +import { CommandOperation, CommandOperationOptions } from './command'; +import type { Callback } from '../utils'; +import type { Server } from '../sdam/server'; +import type { Db } from '../db'; +import type { ClientSession } from '../sessions'; + +/** @public */ +export type RemoveUserOptions = CommandOperationOptions; + +/** @internal */ +export class RemoveUserOperation extends CommandOperation { + options: RemoveUserOptions; + username: string; + + constructor(db: Db, username: string, options: RemoveUserOptions) { + super(db, options); + this.options = options; + this.username = username; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + super.executeCommand(server, session, { dropUser: this.username }, err => { + callback(err, err ? false : true); + }); + } +} + +defineAspects(RemoveUserOperation, [Aspect.WRITE_OPERATION]); diff --git a/node_modules/mongodb/src/operations/rename.ts b/node_modules/mongodb/src/operations/rename.ts new file mode 100644 index 0000000..47d03a2 --- /dev/null +++ b/node_modules/mongodb/src/operations/rename.ts @@ -0,0 +1,63 @@ +import { checkCollectionName, Callback } from '../utils'; +import { RunAdminCommandOperation } from './run_command'; +import { defineAspects, Aspect } from './operation'; +import type { Server } from '../sdam/server'; +import { Collection } from '../collection'; +import type { CommandOperationOptions } from './command'; +import { MongoServerError } from '../error'; +import type { ClientSession } from '../sessions'; +import type { Document } from 'bson'; + +/** @public */ +export interface RenameOptions extends CommandOperationOptions { + /** Drop the target name collection if it previously exists. */ + dropTarget?: boolean; + /** Unclear */ + new_collection?: boolean; +} + +/** @internal */ +export class RenameOperation extends RunAdminCommandOperation { + options: RenameOptions; + collection: Collection; + newName: string; + + constructor(collection: Collection, newName: string, options: RenameOptions) { + // Check the collection name + checkCollectionName(newName); + + // Build the command + const renameCollection = collection.namespace; + const toCollection = collection.s.namespace.withCollection(newName).toString(); + const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; + const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; + + super(collection, cmd, options); + this.options = options; + this.collection = collection; + this.newName = newName; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const coll = this.collection; + + super.execute(server, session, (err, doc) => { + if (err) return callback(err); + // We have an error + if (doc.errmsg) { + return callback(new MongoServerError(doc)); + } + + let newColl: Collection; + try { + newColl = new Collection(coll.s.db, this.newName, coll.s.options); + } catch (err) { + return callback(err); + } + + return callback(undefined, newColl); + }); + } +} + +defineAspects(RenameOperation, [Aspect.WRITE_OPERATION]); diff --git a/node_modules/mongodb/src/operations/run_command.ts b/node_modules/mongodb/src/operations/run_command.ts new file mode 100644 index 0000000..e9cabb9 --- /dev/null +++ b/node_modules/mongodb/src/operations/run_command.ts @@ -0,0 +1,32 @@ +import { CommandOperation, CommandOperationOptions, OperationParent } from './command'; +import { MongoDBNamespace, Callback } from '../utils'; +import type { Server } from '../sdam/server'; +import type { Document } from '../bson'; +import type { ClientSession } from '../sessions'; + +/** @public */ +export type RunCommandOptions = CommandOperationOptions; + +/** @internal */ +export class RunCommandOperation extends CommandOperation { + options: RunCommandOptions; + command: Document; + + constructor(parent: OperationParent | undefined, command: Document, options?: RunCommandOptions) { + super(parent, options); + this.options = options ?? {}; + this.command = command; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const command = this.command; + this.executeCommand(server, session, command, callback); + } +} + +export class RunAdminCommandOperation extends RunCommandOperation { + constructor(parent: OperationParent | undefined, command: Document, options?: RunCommandOptions) { + super(parent, command, options); + this.ns = new MongoDBNamespace('admin'); + } +} diff --git a/node_modules/mongodb/src/operations/set_profiling_level.ts b/node_modules/mongodb/src/operations/set_profiling_level.ts new file mode 100644 index 0000000..db3a2e0 --- /dev/null +++ b/node_modules/mongodb/src/operations/set_profiling_level.ts @@ -0,0 +1,69 @@ +import { CommandOperation, CommandOperationOptions } from './command'; +import type { Callback } from '../utils'; +import { enumToString } from '../utils'; +import type { Server } from '../sdam/server'; +import type { Db } from '../db'; +import type { ClientSession } from '../sessions'; +import { MongoRuntimeError, MongoInvalidArgumentError } from '../error'; +const levelValues = new Set(['off', 'slow_only', 'all']); + +/** @public */ +export const ProfilingLevel = Object.freeze({ + off: 'off', + slowOnly: 'slow_only', + all: 'all' +} as const); + +/** @public */ +export type ProfilingLevel = typeof ProfilingLevel[keyof typeof ProfilingLevel]; + +/** @public */ +export type SetProfilingLevelOptions = CommandOperationOptions; + +/** @internal */ +export class SetProfilingLevelOperation extends CommandOperation { + options: SetProfilingLevelOptions; + level: ProfilingLevel; + profile: 0 | 1 | 2; + + constructor(db: Db, level: ProfilingLevel, options: SetProfilingLevelOptions) { + super(db, options); + this.options = options; + switch (level) { + case ProfilingLevel.off: + this.profile = 0; + break; + case ProfilingLevel.slowOnly: + this.profile = 1; + break; + case ProfilingLevel.all: + this.profile = 2; + break; + default: + this.profile = 0; + break; + } + + this.level = level; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const level = this.level; + + if (!levelValues.has(level)) { + return callback( + new MongoInvalidArgumentError( + `Profiling level must be one of "${enumToString(ProfilingLevel)}"` + ) + ); + } + + // TODO(NODE-3483): Determine error to put here + super.executeCommand(server, session, { profile: this.profile }, (err, doc) => { + if (err == null && doc.ok === 1) return callback(undefined, level); + return err != null + ? callback(err) + : callback(new MongoRuntimeError('Error with profile command')); + }); + } +} diff --git a/node_modules/mongodb/src/operations/stats.ts b/node_modules/mongodb/src/operations/stats.ts new file mode 100644 index 0000000..98de407 --- /dev/null +++ b/node_modules/mongodb/src/operations/stats.ts @@ -0,0 +1,263 @@ +import { Aspect, defineAspects } from './operation'; +import { CommandOperation, CommandOperationOptions } from './command'; +import type { Callback } from '../utils'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Collection } from '../collection'; +import type { Db } from '../db'; +import type { ClientSession } from '../sessions'; + +/** @public */ +export interface CollStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} + +/** + * Get all the collection statistics. + * @internal + */ +export class CollStatsOperation extends CommandOperation { + options: CollStatsOptions; + collectionName: string; + + /** + * Construct a Stats operation. + * + * @param collection - Collection instance + * @param options - Optional settings. See Collection.prototype.stats for a list of options. + */ + constructor(collection: Collection, options?: CollStatsOptions) { + super(collection, options); + this.options = options ?? {}; + this.collectionName = collection.collectionName; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const command: Document = { collStats: this.collectionName }; + if (this.options.scale != null) { + command.scale = this.options.scale; + } + + super.executeCommand(server, session, command, callback); + } +} + +/** @public */ +export interface DbStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} + +/** @internal */ +export class DbStatsOperation extends CommandOperation { + options: DbStatsOptions; + + constructor(db: Db, options: DbStatsOptions) { + super(db, options); + this.options = options; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const command: Document = { dbStats: true }; + if (this.options.scale != null) { + command.scale = this.options.scale; + } + + super.executeCommand(server, session, command, callback); + } +} + +/** + * @public + * @see https://docs.mongodb.org/manual/reference/command/collStats/ + */ +export interface CollStats extends Document { + /** Namespace */ + ns: string; + /** Number of documents */ + count: number; + /** Collection size in bytes */ + size: number; + /** Average object size in bytes */ + avgObjSize: number; + /** (Pre)allocated space for the collection in bytes */ + storageSize: number; + /** Number of extents (contiguously allocated chunks of datafile space) */ + numExtents: number; + /** Number of indexes */ + nindexes: number; + /** Size of the most recently created extent in bytes */ + lastExtentSize: number; + /** Padding can speed up updates if documents grow */ + paddingFactor: number; + /** A number that indicates the user-set flags on the collection. userFlags only appears when using the mmapv1 storage engine */ + userFlags?: number; + /** Total index size in bytes */ + totalIndexSize: number; + /** Size of specific indexes in bytes */ + indexSizes: { + _id_: number; + [index: string]: number; + }; + /** `true` if the collection is capped */ + capped: boolean; + /** The maximum number of documents that may be present in a capped collection */ + max: number; + /** The maximum size of a capped collection */ + maxSize: number; + /** This document contains data reported directly by the WiredTiger engine and other data for internal diagnostic use */ + wiredTiger?: WiredTigerData; + /** The fields in this document are the names of the indexes, while the values themselves are documents that contain statistics for the index provided by the storage engine */ + indexDetails?: any; + ok: number; + + /** The amount of storage available for reuse. The scale argument affects this value. */ + freeStorageSize?: number; + /** An array that contains the names of the indexes that are currently being built on the collection */ + indexBuilds?: number; + /** The sum of the storageSize and totalIndexSize. The scale argument affects this value */ + totalSize: number; + /** The scale value used by the command. */ + scaleFactor: number; +} + +/** @public */ +export interface WiredTigerData extends Document { + LSM: { + 'bloom filter false positives': number; + 'bloom filter hits': number; + 'bloom filter misses': number; + 'bloom filter pages evicted from cache': number; + 'bloom filter pages read into cache': number; + 'bloom filters in the LSM tree': number; + 'chunks in the LSM tree': number; + 'highest merge generation in the LSM tree': number; + 'queries that could have benefited from a Bloom filter that did not exist': number; + 'sleep for LSM checkpoint throttle': number; + 'sleep for LSM merge throttle': number; + 'total size of bloom filters': number; + } & Document; + 'block-manager': { + 'allocations requiring file extension': number; + 'blocks allocated': number; + 'blocks freed': number; + 'checkpoint size': number; + 'file allocation unit size': number; + 'file bytes available for reuse': number; + 'file magic number': number; + 'file major version number': number; + 'file size in bytes': number; + 'minor version number': number; + }; + btree: { + 'btree checkpoint generation': number; + 'column-store fixed-size leaf pages': number; + 'column-store internal pages': number; + 'column-store variable-size RLE encoded values': number; + 'column-store variable-size deleted values': number; + 'column-store variable-size leaf pages': number; + 'fixed-record size': number; + 'maximum internal page key size': number; + 'maximum internal page size': number; + 'maximum leaf page key size': number; + 'maximum leaf page size': number; + 'maximum leaf page value size': number; + 'maximum tree depth': number; + 'number of key/value pairs': number; + 'overflow pages': number; + 'pages rewritten by compaction': number; + 'row-store internal pages': number; + 'row-store leaf pages': number; + } & Document; + cache: { + 'bytes currently in the cache': number; + 'bytes read into cache': number; + 'bytes written from cache': number; + 'checkpoint blocked page eviction': number; + 'data source pages selected for eviction unable to be evicted': number; + 'hazard pointer blocked page eviction': number; + 'in-memory page passed criteria to be split': number; + 'in-memory page splits': number; + 'internal pages evicted': number; + 'internal pages split during eviction': number; + 'leaf pages split during eviction': number; + 'modified pages evicted': number; + 'overflow pages read into cache': number; + 'overflow values cached in memory': number; + 'page split during eviction deepened the tree': number; + 'page written requiring lookaside records': number; + 'pages read into cache': number; + 'pages read into cache requiring lookaside entries': number; + 'pages requested from the cache': number; + 'pages written from cache': number; + 'pages written requiring in-memory restoration': number; + 'tracked dirty bytes in the cache': number; + 'unmodified pages evicted': number; + } & Document; + cache_walk: { + 'Average difference between current eviction generation when the page was last considered': number; + 'Average on-disk page image size seen': number; + 'Clean pages currently in cache': number; + 'Current eviction generation': number; + 'Dirty pages currently in cache': number; + 'Entries in the root page': number; + 'Internal pages currently in cache': number; + 'Leaf pages currently in cache': number; + 'Maximum difference between current eviction generation when the page was last considered': number; + 'Maximum page size seen': number; + 'Minimum on-disk page image size seen': number; + 'On-disk page image sizes smaller than a single allocation unit': number; + 'Pages created in memory and never written': number; + 'Pages currently queued for eviction': number; + 'Pages that could not be queued for eviction': number; + 'Refs skipped during cache traversal': number; + 'Size of the root page': number; + 'Total number of pages currently in cache': number; + } & Document; + compression: { + 'compressed pages read': number; + 'compressed pages written': number; + 'page written failed to compress': number; + 'page written was too small to compress': number; + 'raw compression call failed, additional data available': number; + 'raw compression call failed, no additional data available': number; + 'raw compression call succeeded': number; + } & Document; + cursor: { + 'bulk-loaded cursor-insert calls': number; + 'create calls': number; + 'cursor-insert key and value bytes inserted': number; + 'cursor-remove key bytes removed': number; + 'cursor-update value bytes updated': number; + 'insert calls': number; + 'next calls': number; + 'prev calls': number; + 'remove calls': number; + 'reset calls': number; + 'restarted searches': number; + 'search calls': number; + 'search near calls': number; + 'truncate calls': number; + 'update calls': number; + }; + reconciliation: { + 'dictionary matches': number; + 'fast-path pages deleted': number; + 'internal page key bytes discarded using suffix compression': number; + 'internal page multi-block writes': number; + 'internal-page overflow keys': number; + 'leaf page key bytes discarded using prefix compression': number; + 'leaf page multi-block writes': number; + 'leaf-page overflow keys': number; + 'maximum blocks required for a page': number; + 'overflow values written': number; + 'page checksum matches': number; + 'page reconciliation calls': number; + 'page reconciliation calls for eviction': number; + 'pages deleted': number; + } & Document; +} + +defineAspects(CollStatsOperation, [Aspect.READ_OPERATION]); +defineAspects(DbStatsOperation, [Aspect.READ_OPERATION]); diff --git a/node_modules/mongodb/src/operations/update.ts b/node_modules/mongodb/src/operations/update.ts new file mode 100644 index 0000000..fa69973 --- /dev/null +++ b/node_modules/mongodb/src/operations/update.ts @@ -0,0 +1,322 @@ +import { defineAspects, Aspect, Hint } from './operation'; +import { + hasAtomicOperators, + MongoDBNamespace, + Callback, + collationNotSupported, + maxWireVersion +} from '../utils'; +import { CommandOperation, CommandOperationOptions, CollationOptions } from './command'; +import type { Server } from '../sdam/server'; +import type { Collection } from '../collection'; +import type { ObjectId, Document } from '../bson'; +import type { ClientSession } from '../sessions'; +import { MongoServerError, MongoInvalidArgumentError, MongoCompatibilityError } from '../error'; + +/** @public */ +export interface UpdateOptions extends CommandOperationOptions { + /** A set of filters specifying to which array elements an update should apply */ + arrayFilters?: Document[]; + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export interface UpdateResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of documents that matched the filter */ + matchedCount: number; + /** The number of documents that were modified */ + modifiedCount: number; + /** The number of documents that were upserted */ + upsertedCount: number; + /** The identifier of the inserted document if an upsert took place */ + upsertedId: ObjectId; +} + +/** @public */ +export interface UpdateStatement { + /** The query that matches documents to update. */ + q: Document; + /** The modifications to apply. */ + u: Document | Document[]; + /** If true, perform an insert if no documents match the query. */ + upsert?: boolean; + /** If true, updates all documents that meet the query criteria. */ + multi?: boolean; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** An array of filter documents that determines which array elements to modify for an update operation on an array field. */ + arrayFilters?: Document[]; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; +} + +/** @internal */ +export class UpdateOperation extends CommandOperation { + options: UpdateOptions & { ordered?: boolean }; + statements: UpdateStatement[]; + + constructor( + ns: MongoDBNamespace, + statements: UpdateStatement[], + options: UpdateOptions & { ordered?: boolean } + ) { + super(undefined, options); + this.options = options; + this.ns = ns; + + this.statements = statements; + } + + get canRetryWrite(): boolean { + if (super.canRetryWrite === false) { + return false; + } + + return this.statements.every(op => op.multi == null || op.multi === false); + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command: Document = { + update: this.ns.collection, + updates: this.statements, + ordered + }; + + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + if (options.let) { + command.let = options.let; + } + + const statementWithCollation = this.statements.find(statement => !!statement.collation); + if ( + collationNotSupported(server, options) || + (statementWithCollation && collationNotSupported(server, statementWithCollation)) + ) { + callback(new MongoCompatibilityError(`Server ${server.name} does not support collation`)); + return; + } + + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite || maxWireVersion(server) < 5) { + if (this.statements.find((o: Document) => o.hint)) { + callback(new MongoCompatibilityError(`Servers < 3.4 do not support hint on update`)); + return; + } + } + + if (this.explain && maxWireVersion(server) < 3) { + callback( + new MongoCompatibilityError(`Server ${server.name} does not support explain on update`) + ); + return; + } + + if (this.statements.some(statement => !!statement.arrayFilters) && maxWireVersion(server) < 6) { + callback( + new MongoCompatibilityError('Option "arrayFilters" is only supported on MongoDB 3.6+') + ); + return; + } + + super.executeCommand(server, session, command, callback); + } +} + +/** @internal */ +export class UpdateOneOperation extends UpdateOperation { + constructor(collection: Collection, filter: Document, update: Document, options: UpdateOptions) { + super( + collection.s.namespace, + [makeUpdateStatement(filter, update, { ...options, multi: false })], + options + ); + + if (!hasAtomicOperators(update)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + + execute( + server: Server, + session: ClientSession, + callback: Callback + ): void { + super.execute(server, session, (err, res) => { + if (err || !res) return callback(err); + if (this.explain != null) return callback(undefined, res); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0])); + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: + Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} + +/** @internal */ +export class UpdateManyOperation extends UpdateOperation { + constructor(collection: Collection, filter: Document, update: Document, options: UpdateOptions) { + super( + collection.s.namespace, + [makeUpdateStatement(filter, update, { ...options, multi: true })], + options + ); + + if (!hasAtomicOperators(update)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + + execute( + server: Server, + session: ClientSession, + callback: Callback + ): void { + super.execute(server, session, (err, res) => { + if (err || !res) return callback(err); + if (this.explain != null) return callback(undefined, res); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0])); + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: + Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} + +/** @public */ +export interface ReplaceOptions extends CommandOperationOptions { + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; +} + +/** @internal */ +export class ReplaceOneOperation extends UpdateOperation { + constructor( + collection: Collection, + filter: Document, + replacement: Document, + options: ReplaceOptions + ) { + super( + collection.s.namespace, + [makeUpdateStatement(filter, replacement, { ...options, multi: false })], + options + ); + + if (hasAtomicOperators(replacement)) { + throw new MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + } + + execute( + server: Server, + session: ClientSession, + callback: Callback + ): void { + super.execute(server, session, (err, res) => { + if (err || !res) return callback(err); + if (this.explain != null) return callback(undefined, res); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0])); + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: + Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} + +export function makeUpdateStatement( + filter: Document, + update: Document, + options: UpdateOptions & { multi?: boolean } +): UpdateStatement { + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Selector must be a valid JavaScript object'); + } + + if (update == null || typeof update !== 'object') { + throw new MongoInvalidArgumentError('Document must be a valid JavaScript object'); + } + + const op: UpdateStatement = { q: filter, u: update }; + if (typeof options.upsert === 'boolean') { + op.upsert = options.upsert; + } + + if (options.multi) { + op.multi = options.multi; + } + + if (options.hint) { + op.hint = options.hint; + } + + if (options.arrayFilters) { + op.arrayFilters = options.arrayFilters; + } + + if (options.collation) { + op.collation = options.collation; + } + + return op; +} + +defineAspects(UpdateOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION, Aspect.SKIP_COLLATION]); +defineAspects(UpdateOneOperation, [ + Aspect.RETRYABLE, + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); +defineAspects(UpdateManyOperation, [ + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); +defineAspects(ReplaceOneOperation, [ + Aspect.RETRYABLE, + Aspect.WRITE_OPERATION, + Aspect.SKIP_COLLATION +]); diff --git a/node_modules/mongodb/src/operations/validate_collection.ts b/node_modules/mongodb/src/operations/validate_collection.ts new file mode 100644 index 0000000..ce3a681 --- /dev/null +++ b/node_modules/mongodb/src/operations/validate_collection.ts @@ -0,0 +1,55 @@ +import { CommandOperation, CommandOperationOptions } from './command'; +import type { Callback } from '../utils'; +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { Admin } from '../admin'; +import type { ClientSession } from '../sessions'; +import { MongoRuntimeError } from '../error'; + +/** @public */ +export interface ValidateCollectionOptions extends CommandOperationOptions { + /** Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) */ + background?: boolean; +} + +/** @internal */ +export class ValidateCollectionOperation extends CommandOperation { + options: ValidateCollectionOptions; + collectionName: string; + command: Document; + + constructor(admin: Admin, collectionName: string, options: ValidateCollectionOptions) { + // Decorate command with extra options + const command: Document = { validate: collectionName }; + const keys = Object.keys(options); + for (let i = 0; i < keys.length; i++) { + if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== 'session') { + command[keys[i]] = (options as Document)[keys[i]]; + } + } + + super(admin.s.db, options); + this.options = options; + this.command = command; + this.collectionName = collectionName; + } + + execute(server: Server, session: ClientSession, callback: Callback): void { + const collectionName = this.collectionName; + + super.executeCommand(server, session, this.command, (err, doc) => { + if (err != null) return callback(err); + + // TODO(NODE-3483): Replace these with MongoUnexpectedServerResponseError + if (doc.ok === 0) return callback(new MongoRuntimeError('Error with validate command')); + if (doc.result != null && typeof doc.result !== 'string') + return callback(new MongoRuntimeError('Error with validation data')); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new MongoRuntimeError(`Invalid collection ${collectionName}`)); + if (doc.valid != null && !doc.valid) + return callback(new MongoRuntimeError(`Invalid collection ${collectionName}`)); + + return callback(undefined, doc); + }); + } +} diff --git a/node_modules/mongodb/src/promise_provider.ts b/node_modules/mongodb/src/promise_provider.ts new file mode 100644 index 0000000..a6aeb54 --- /dev/null +++ b/node_modules/mongodb/src/promise_provider.ts @@ -0,0 +1,41 @@ +import { MongoInvalidArgumentError } from './error'; + +/** @internal */ +const kPromise = Symbol('promise'); + +interface PromiseStore { + [kPromise]?: PromiseConstructor; +} + +const store: PromiseStore = { + [kPromise]: undefined +}; + +/** + * Global promise store allowing user-provided promises + * @public + */ +export class PromiseProvider { + /** Validates the passed in promise library */ + static validate(lib: unknown): lib is PromiseConstructor { + if (typeof lib !== 'function') + throw new MongoInvalidArgumentError(`Promise must be a function, got ${lib}`); + return !!lib; + } + + /** Sets the promise library */ + static set(lib: PromiseConstructor): void { + if (!PromiseProvider.validate(lib)) { + // validate + return; + } + store[kPromise] = lib; + } + + /** Get the stored promise library, or resolves passed in */ + static get(): PromiseConstructor { + return store[kPromise] as PromiseConstructor; + } +} + +PromiseProvider.set(global.Promise); diff --git a/node_modules/mongodb/src/read_concern.ts b/node_modules/mongodb/src/read_concern.ts new file mode 100644 index 0000000..195d6c8 --- /dev/null +++ b/node_modules/mongodb/src/read_concern.ts @@ -0,0 +1,87 @@ +import type { Document } from './bson'; + +/** @public */ +export const ReadConcernLevel = Object.freeze({ + local: 'local', + majority: 'majority', + linearizable: 'linearizable', + available: 'available', + snapshot: 'snapshot' +} as const); + +/** @public */ +export type ReadConcernLevel = typeof ReadConcernLevel[keyof typeof ReadConcernLevel]; + +/** @public */ +export type ReadConcernLike = ReadConcern | { level: ReadConcernLevel } | ReadConcernLevel; + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @public + * + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html + */ +export class ReadConcern { + level: ReadConcernLevel | string; + + /** Constructs a ReadConcern from the read concern level.*/ + constructor(level: ReadConcernLevel) { + /** + * A spec test exists that allows level to be any string. + * "invalid readConcern with out stage" + * @see ./test/spec/crud/v2/aggregate-out-readConcern.json + * @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#unknown-levels-and-additional-options-for-string-based-readconcerns + */ + this.level = ReadConcernLevel[level] ?? level; + } + + /** + * Construct a ReadConcern given an options object. + * + * @param options - The options object from which to extract the write concern. + */ + static fromOptions(options?: { + readConcern?: ReadConcernLike; + level?: ReadConcernLevel; + }): ReadConcern | undefined { + if (options == null) { + return; + } + + if (options.readConcern) { + const { readConcern } = options; + if (readConcern instanceof ReadConcern) { + return readConcern; + } else if (typeof readConcern === 'string') { + return new ReadConcern(readConcern); + } else if ('level' in readConcern && readConcern.level) { + return new ReadConcern(readConcern.level); + } + } + + if (options.level) { + return new ReadConcern(options.level); + } + } + + static get MAJORITY(): 'majority' { + return ReadConcernLevel.majority; + } + + static get AVAILABLE(): 'available' { + return ReadConcernLevel.available; + } + + static get LINEARIZABLE(): 'linearizable' { + return ReadConcernLevel.linearizable; + } + + static get SNAPSHOT(): 'snapshot' { + return ReadConcernLevel.snapshot; + } + + toJSON(): Document { + return { level: this.level }; + } +} diff --git a/node_modules/mongodb/src/read_preference.ts b/node_modules/mongodb/src/read_preference.ts new file mode 100644 index 0000000..d0ffd6e --- /dev/null +++ b/node_modules/mongodb/src/read_preference.ts @@ -0,0 +1,264 @@ +import type { TagSet } from './sdam/server_description'; +import type { Document } from './bson'; +import type { ClientSession } from './sessions'; +import { MongoInvalidArgumentError } from './error'; + +/** @public */ +export type ReadPreferenceLike = ReadPreference | ReadPreferenceMode; + +/** @public */ +export const ReadPreferenceMode = Object.freeze({ + primary: 'primary', + primaryPreferred: 'primaryPreferred', + secondary: 'secondary', + secondaryPreferred: 'secondaryPreferred', + nearest: 'nearest' +} as const); + +/** @public */ +export type ReadPreferenceMode = typeof ReadPreferenceMode[keyof typeof ReadPreferenceMode]; + +/** @public */ +export interface HedgeOptions { + /** Explicitly enable or disable hedged reads. */ + enabled?: boolean; +} + +/** @public */ +export interface ReadPreferenceOptions { + /** Max secondary read staleness in seconds, Minimum value is 90 seconds.*/ + maxStalenessSeconds?: number; + /** Server mode in which the same query is dispatched in parallel to multiple replica set members. */ + hedge?: HedgeOptions; +} + +/** @public */ +export interface ReadPreferenceLikeOptions extends ReadPreferenceOptions { + readPreference?: + | ReadPreferenceLike + | { + mode?: ReadPreferenceMode; + preference?: ReadPreferenceMode; + tags?: TagSet[]; + maxStalenessSeconds?: number; + }; +} + +/** @public */ +export interface ReadPreferenceFromOptions extends ReadPreferenceLikeOptions { + session?: ClientSession; + readPreferenceTags?: TagSet[]; + hedge?: HedgeOptions; +} + +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @public + * + * @see https://docs.mongodb.com/manual/core/read-preference/ + */ +export class ReadPreference { + mode: ReadPreferenceMode; + tags?: TagSet[]; + hedge?: HedgeOptions; + maxStalenessSeconds?: number; + minWireVersion?: number; + + public static PRIMARY = ReadPreferenceMode.primary; + public static PRIMARY_PREFERRED = ReadPreferenceMode.primaryPreferred; + public static SECONDARY = ReadPreferenceMode.secondary; + public static SECONDARY_PREFERRED = ReadPreferenceMode.secondaryPreferred; + public static NEAREST = ReadPreferenceMode.nearest; + + public static primary = new ReadPreference(ReadPreferenceMode.primary); + public static primaryPreferred = new ReadPreference(ReadPreferenceMode.primaryPreferred); + public static secondary = new ReadPreference(ReadPreferenceMode.secondary); + public static secondaryPreferred = new ReadPreference(ReadPreferenceMode.secondaryPreferred); + public static nearest = new ReadPreference(ReadPreferenceMode.nearest); + + /** + * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. + * @param options - Additional read preference options + */ + constructor(mode: ReadPreferenceMode, tags?: TagSet[], options?: ReadPreferenceOptions) { + if (!ReadPreference.isValid(mode)) { + throw new MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`); + } + if (options == null && typeof tags === 'object' && !Array.isArray(tags)) { + options = tags; + tags = undefined; + } else if (tags && !Array.isArray(tags)) { + throw new MongoInvalidArgumentError('ReadPreference tags must be an array'); + } + + this.mode = mode; + this.tags = tags; + this.hedge = options?.hedge; + this.maxStalenessSeconds = undefined; + this.minWireVersion = undefined; + + options = options ?? {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new MongoInvalidArgumentError('maxStalenessSeconds must be a positive integer'); + } + + this.maxStalenessSeconds = options.maxStalenessSeconds; + + // NOTE: The minimum required wire version is 5 for this read preference. If the existing + // topology has a lower value then a MongoError will be thrown during server selection. + this.minWireVersion = 5; + } + + if (this.mode === ReadPreference.PRIMARY) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new MongoInvalidArgumentError('Primary read preference cannot be combined with tags'); + } + + if (this.maxStalenessSeconds) { + throw new MongoInvalidArgumentError( + 'Primary read preference cannot be combined with maxStalenessSeconds' + ); + } + + if (this.hedge) { + throw new MongoInvalidArgumentError( + 'Primary read preference cannot be combined with hedge' + ); + } + } + } + + // Support the deprecated `preference` property introduced in the porcelain layer + get preference(): ReadPreferenceMode { + return this.mode; + } + + static fromString(mode: string): ReadPreference { + return new ReadPreference(mode as ReadPreferenceMode); + } + + /** + * Construct a ReadPreference given an options object. + * + * @param options - The options object from which to extract the read preference. + */ + static fromOptions(options?: ReadPreferenceFromOptions): ReadPreference | undefined { + if (!options) return; + const readPreference = + options.readPreference ?? options.session?.transaction.options.readPreference; + const readPreferenceTags = options.readPreferenceTags; + + if (readPreference == null) { + return; + } + + if (typeof readPreference === 'string') { + return new ReadPreference(readPreference as ReadPreferenceMode, readPreferenceTags); + } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + return new ReadPreference( + mode as ReadPreferenceMode, + readPreference.tags ?? readPreferenceTags, + { + maxStalenessSeconds: readPreference.maxStalenessSeconds, + hedge: options.hedge + } + ); + } + } + + if (readPreferenceTags) { + readPreference.tags = readPreferenceTags; + } + + return readPreference as ReadPreference; + } + + /** + * Replaces options.readPreference with a ReadPreference instance + */ + static translate(options: ReadPreferenceLikeOptions): ReadPreferenceLikeOptions { + if (options.readPreference == null) return options; + const r = options.readPreference; + + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r as ReadPreferenceMode); + } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode as ReadPreferenceMode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } else if (!(r instanceof ReadPreference)) { + throw new MongoInvalidArgumentError(`Invalid read preference: ${r}`); + } + + return options; + } + + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + static isValid(mode: string): boolean { + const VALID_MODES = new Set([ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + null + ]); + + return VALID_MODES.has(mode as ReadPreferenceMode); + } + + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + isValid(mode?: string): boolean { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); + } + + /** + * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire + * + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ + slaveOk(): boolean { + const NEEDS_SLAVEOK = new Set([ + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST + ]); + + return NEEDS_SLAVEOK.has(this.mode); + } + + /** + * Check if the two ReadPreferences are equivalent + * + * @param readPreference - The read preference with which to check equality + */ + equals(readPreference: ReadPreference): boolean { + return readPreference.mode === this.mode; + } + + /** Return JSON representation */ + toJSON(): Document { + const readPreference = { mode: this.mode } as Document; + if (Array.isArray(this.tags)) readPreference.tags = this.tags; + if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + if (this.hedge) readPreference.hedge = this.hedge; + return readPreference; + } +} diff --git a/node_modules/mongodb/src/sdam/common.ts b/node_modules/mongodb/src/sdam/common.ts new file mode 100644 index 0000000..673573b --- /dev/null +++ b/node_modules/mongodb/src/sdam/common.ts @@ -0,0 +1,83 @@ +import type { Timestamp, Binary, Long } from '../bson'; +import type { Topology } from './topology'; +import type { ClientSession } from '../sessions'; + +// shared state names +export const STATE_CLOSING = 'closing'; +export const STATE_CLOSED = 'closed'; +export const STATE_CONNECTING = 'connecting'; +export const STATE_CONNECTED = 'connected'; + +/** + * An enumeration of topology types we know about + * @public + */ +export const TopologyType = Object.freeze({ + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown', + LoadBalanced: 'LoadBalanced' +} as const); + +/** @public */ +export type TopologyType = typeof TopologyType[keyof typeof TopologyType]; + +/** + * An enumeration of server types we know about + * @public + */ +export const ServerType = Object.freeze({ + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown', + LoadBalancer: 'LoadBalancer' +} as const); + +/** @public */ +export type ServerType = typeof ServerType[keyof typeof ServerType]; + +/** @internal */ +export type TimerQueue = Set; + +/** @internal */ +export function drainTimerQueue(queue: TimerQueue): void { + queue.forEach(clearTimeout); + queue.clear(); +} + +/** @internal */ +export function clearAndRemoveTimerFrom(timer: NodeJS.Timeout, timers: TimerQueue): boolean { + clearTimeout(timer); + return timers.delete(timer); +} + +/** @public */ +export interface ClusterTime { + clusterTime: Timestamp; + signature: { + hash: Binary; + keyId: Long; + }; +} + +/** Shared function to determine clusterTime for a given topology or session */ +export function _advanceClusterTime( + entity: Topology | ClientSession, + $clusterTime: ClusterTime +): void { + if (entity.clusterTime == null) { + entity.clusterTime = $clusterTime; + } else { + if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) { + entity.clusterTime = $clusterTime; + } + } +} diff --git a/node_modules/mongodb/src/sdam/events.ts b/node_modules/mongodb/src/sdam/events.ts new file mode 100644 index 0000000..ff8c460 --- /dev/null +++ b/node_modules/mongodb/src/sdam/events.ts @@ -0,0 +1,182 @@ +import type { ServerDescription } from './server_description'; +import type { TopologyDescription } from './topology_description'; +import type { Document } from '../bson'; + +/** + * Emitted when server description changes, but does NOT include changes to the RTT. + * @public + * @category Event + */ +export class ServerDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /** The previous server description */ + previousDescription: ServerDescription; + /** The new server description */ + newDescription: ServerDescription; + + /** @internal */ + constructor( + topologyId: number, + address: string, + previousDescription: ServerDescription, + newDescription: ServerDescription + ) { + this.topologyId = topologyId; + this.address = address; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} + +/** + * Emitted when server is initialized. + * @public + * @category Event + */ +export class ServerOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + + /** @internal */ + constructor(topologyId: number, address: string) { + this.topologyId = topologyId; + this.address = address; + } +} + +/** + * Emitted when server is closed. + * @public + * @category Event + */ +export class ServerClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + + /** @internal */ + constructor(topologyId: number, address: string) { + this.topologyId = topologyId; + this.address = address; + } +} + +/** + * Emitted when topology description changes. + * @public + * @category Event + */ +export class TopologyDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The old topology description */ + previousDescription: TopologyDescription; + /** The new topology description */ + newDescription: TopologyDescription; + + /** @internal */ + constructor( + topologyId: number, + previousDescription: TopologyDescription, + newDescription: TopologyDescription + ) { + this.topologyId = topologyId; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} + +/** + * Emitted when topology is initialized. + * @public + * @category Event + */ +export class TopologyOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + + /** @internal */ + constructor(topologyId: number) { + this.topologyId = topologyId; + } +} + +/** + * Emitted when topology is closed. + * @public + * @category Event + */ +export class TopologyClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + + /** @internal */ + constructor(topologyId: number) { + this.topologyId = topologyId; + } +} + +/** + * Emitted when the server monitor’s ismaster command is started - immediately before + * the ismaster command is serialized into raw BSON and written to the socket. + * + * @public + * @category Event + */ +export class ServerHeartbeatStartedEvent { + /** The connection id for the command */ + connectionId: string; + + /** @internal */ + constructor(connectionId: string) { + this.connectionId = connectionId; + } +} + +/** + * Emitted when the server monitor’s ismaster succeeds. + * @public + * @category Event + */ +export class ServerHeartbeatSucceededEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command reply */ + reply: Document; + + /** @internal */ + constructor(connectionId: string, duration: number, reply: Document) { + this.connectionId = connectionId; + this.duration = duration; + this.reply = reply; + } +} + +/** + * Emitted when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. + * @public + * @category Event + */ +export class ServerHeartbeatFailedEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command failure */ + failure: Error; + + /** @internal */ + constructor(connectionId: string, duration: number, failure: Error) { + this.connectionId = connectionId; + this.duration = duration; + this.failure = failure; + } +} diff --git a/node_modules/mongodb/src/sdam/monitor.ts b/node_modules/mongodb/src/sdam/monitor.ts new file mode 100644 index 0000000..aad9807 --- /dev/null +++ b/node_modules/mongodb/src/sdam/monitor.ts @@ -0,0 +1,465 @@ +import { ServerType, STATE_CLOSED, STATE_CLOSING } from './common'; +import { + now, + makeStateMachine, + calculateDurationInMs, + makeInterruptibleAsyncInterval, + ns, + EventEmitterWithState +} from '../utils'; +import { connect } from '../cmap/connect'; +import { Connection, ConnectionOptions } from '../cmap/connection'; +import { MongoNetworkError, AnyError } from '../error'; +import { Long, Document } from '../bson'; +import { + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent, + ServerHeartbeatFailedEvent +} from './events'; + +import { Server } from './server'; +import type { InterruptibleAsyncInterval, Callback } from '../utils'; +import type { TopologyVersion } from './server_description'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; + +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kMonitorId = Symbol('monitorId'); +/** @internal */ +const kConnection = Symbol('connection'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kRTTPinger = Symbol('rttPinger'); +/** @internal */ +const kRoundTripTime = Symbol('roundTripTime'); + +const STATE_IDLE = 'idle'; +const STATE_MONITORING = 'monitoring'; +const stateTransition = makeStateMachine({ + [STATE_CLOSING]: [STATE_CLOSING, STATE_IDLE, STATE_CLOSED], + [STATE_CLOSED]: [STATE_CLOSED, STATE_MONITORING], + [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, STATE_CLOSING], + [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, STATE_CLOSING] +}); + +const INVALID_REQUEST_CHECK_STATES = new Set([STATE_CLOSING, STATE_CLOSED, STATE_MONITORING]); +function isInCloseState(monitor: Monitor) { + return monitor.s.state === STATE_CLOSED || monitor.s.state === STATE_CLOSING; +} + +/** @internal */ +export interface MonitorPrivate { + state: string; +} + +/** @public */ +export interface MonitorOptions + extends Omit { + connectTimeoutMS: number; + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; +} + +/** @public */ +export type MonitorEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + resetServer(error?: Error): void; + resetConnectionPool(): void; + close(): void; +} & EventEmitterWithState; + +/** @internal */ +export class Monitor extends TypedEventEmitter { + /** @internal */ + s: MonitorPrivate; + address: string; + options: Readonly< + Pick + >; + connectOptions: ConnectionOptions; + [kServer]: Server; + [kConnection]?: Connection; + [kCancellationToken]: CancellationToken; + /** @internal */ + [kMonitorId]?: InterruptibleAsyncInterval; + [kRTTPinger]?: RTTPinger; + + constructor(server: Server, options: MonitorOptions) { + super(); + + this[kServer] = server; + this[kConnection] = undefined; + this[kCancellationToken] = new CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kMonitorId] = undefined; + this.s = { + state: STATE_CLOSED + }; + + this.address = server.description.address; + this.options = Object.freeze({ + connectTimeoutMS: options.connectTimeoutMS ?? 10000, + heartbeatFrequencyMS: options.heartbeatFrequencyMS ?? 10000, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS ?? 500 + }); + + const cancellationToken = this[kCancellationToken]; + // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration + const connectOptions = Object.assign( + { + id: '' as const, + generation: server.s.pool.generation, + connectionType: Connection, + cancellationToken, + hostAddress: server.description.hostAddress + }, + options, + // force BSON serialization options + { + raw: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: true + } + ); + + // ensure no authentication is used for monitoring + delete connectOptions.credentials; + if (connectOptions.autoEncrypter) { + delete connectOptions.autoEncrypter; + } + + this.connectOptions = Object.freeze(connectOptions); + } + + connect(): void { + if (this.s.state !== STATE_CLOSED) { + return; + } + + // start + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = makeInterruptibleAsyncInterval(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS, + immediate: true + }); + } + + requestCheck(): void { + if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { + return; + } + + this[kMonitorId]?.wake(); + } + + reset(): void { + const topologyVersion = this[kServer].description.topologyVersion; + if (isInCloseState(this) || topologyVersion == null) { + return; + } + + stateTransition(this, STATE_CLOSING); + resetMonitorState(this); + + // restart monitor + stateTransition(this, STATE_IDLE); + + // restart monitoring + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = makeInterruptibleAsyncInterval(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS + }); + } + + close(): void { + if (isInCloseState(this)) { + return; + } + + stateTransition(this, STATE_CLOSING); + resetMonitorState(this); + + // close monitor + this.emit('close'); + stateTransition(this, STATE_CLOSED); + } +} + +function resetMonitorState(monitor: Monitor) { + monitor[kMonitorId]?.stop(); + monitor[kMonitorId] = undefined; + + monitor[kRTTPinger]?.close(); + monitor[kRTTPinger] = undefined; + + monitor[kCancellationToken].emit('cancel'); + + monitor[kConnection]?.destroy({ force: true }); + monitor[kConnection] = undefined; +} + +function checkServer(monitor: Monitor, callback: Callback) { + let start = now(); + monitor.emit(Server.SERVER_HEARTBEAT_STARTED, new ServerHeartbeatStartedEvent(monitor.address)); + + function failureHandler(err: AnyError) { + monitor[kConnection]?.destroy({ force: true }); + monitor[kConnection] = undefined; + + monitor.emit( + Server.SERVER_HEARTBEAT_FAILED, + new ServerHeartbeatFailedEvent(monitor.address, calculateDurationInMs(start), err) + ); + + monitor.emit('resetServer', err); + monitor.emit('resetConnectionPool'); + callback(err); + } + + const connection = monitor[kConnection]; + if (connection && !connection.closed) { + const { serverApi, helloOk } = connection; + const connectTimeoutMS = monitor.options.connectTimeoutMS; + const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS; + const topologyVersion = monitor[kServer].description.topologyVersion; + const isAwaitable = topologyVersion != null; + + const cmd = { + [serverApi?.version || helloOk ? 'hello' : 'ismaster']: true, + ...(isAwaitable && topologyVersion + ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } + : {}) + }; + + const options = isAwaitable + ? { + socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0, + exhaustAllowed: true + } + : { socketTimeoutMS: connectTimeoutMS }; + + if (isAwaitable && monitor[kRTTPinger] == null) { + monitor[kRTTPinger] = new RTTPinger( + monitor[kCancellationToken], + Object.assign( + { heartbeatFrequencyMS: monitor.options.heartbeatFrequencyMS }, + monitor.connectOptions + ) + ); + } + + connection.command(ns('admin.$cmd'), cmd, options, (err, isMaster) => { + if (err) { + failureHandler(err); + return; + } + if ('isWritablePrimary' in isMaster) { + // Provide pre-hello-style response document. + isMaster.ismaster = isMaster.isWritablePrimary; + } + + const rttPinger = monitor[kRTTPinger]; + const duration = + isAwaitable && rttPinger ? rttPinger.roundTripTime : calculateDurationInMs(start); + + monitor.emit( + Server.SERVER_HEARTBEAT_SUCCEEDED, + new ServerHeartbeatSucceededEvent(monitor.address, duration, isMaster) + ); + + // if we are using the streaming protocol then we immediately issue another `started` + // event, otherwise the "check" is complete and return to the main monitor loop + if (isAwaitable && isMaster.topologyVersion) { + monitor.emit( + Server.SERVER_HEARTBEAT_STARTED, + new ServerHeartbeatStartedEvent(monitor.address) + ); + start = now(); + } else { + monitor[kRTTPinger]?.close(); + monitor[kRTTPinger] = undefined; + + callback(undefined, isMaster); + } + }); + + return; + } + + // connecting does an implicit `ismaster` + connect(monitor.connectOptions, (err, conn) => { + if (err) { + monitor[kConnection] = undefined; + + // we already reset the connection pool on network errors in all cases + if (!(err instanceof MongoNetworkError)) { + monitor.emit('resetConnectionPool'); + } + + failureHandler(err); + return; + } + + if (conn) { + if (isInCloseState(monitor)) { + conn.destroy({ force: true }); + return; + } + + monitor[kConnection] = conn; + monitor.emit( + Server.SERVER_HEARTBEAT_SUCCEEDED, + new ServerHeartbeatSucceededEvent( + monitor.address, + calculateDurationInMs(start), + conn.ismaster + ) + ); + + callback(undefined, conn.ismaster); + } + }); +} + +function monitorServer(monitor: Monitor) { + return (callback: Callback) => { + stateTransition(monitor, STATE_MONITORING); + function done() { + if (!isInCloseState(monitor)) { + stateTransition(monitor, STATE_IDLE); + } + + callback(); + } + + checkServer(monitor, (err, isMaster) => { + if (err) { + // otherwise an error occurred on initial discovery, also bail + if (monitor[kServer].description.type === ServerType.Unknown) { + monitor.emit('resetServer', err); + return done(); + } + } + + // if the check indicates streaming is supported, immediately reschedule monitoring + if (isMaster && isMaster.topologyVersion) { + setTimeout(() => { + if (!isInCloseState(monitor)) { + monitor[kMonitorId]?.wake(); + } + }, 0); + } + + done(); + }); + }; +} + +function makeTopologyVersion(tv: TopologyVersion) { + return { + processId: tv.processId, + // tests mock counter as just number, but in a real situation counter should always be a Long + counter: Long.isLong(tv.counter) ? tv.counter : Long.fromNumber(tv.counter) + }; +} + +/** @internal */ +export interface RTTPingerOptions extends ConnectionOptions { + heartbeatFrequencyMS: number; +} + +/** @internal */ +export class RTTPinger { + /** @internal */ + [kConnection]?: Connection; + /** @internal */ + [kCancellationToken]: CancellationToken; + /** @internal */ + [kRoundTripTime]: number; + /** @internal */ + [kMonitorId]: NodeJS.Timeout; + closed: boolean; + + constructor(cancellationToken: CancellationToken, options: RTTPingerOptions) { + this[kConnection] = undefined; + this[kCancellationToken] = cancellationToken; + this[kRoundTripTime] = 0; + this.closed = false; + + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + this[kMonitorId] = setTimeout(() => measureRoundTripTime(this, options), heartbeatFrequencyMS); + } + + get roundTripTime(): number { + return this[kRoundTripTime]; + } + + close(): void { + this.closed = true; + clearTimeout(this[kMonitorId]); + + this[kConnection]?.destroy({ force: true }); + this[kConnection] = undefined; + } +} + +function measureRoundTripTime(rttPinger: RTTPinger, options: RTTPingerOptions) { + const start = now(); + options.cancellationToken = rttPinger[kCancellationToken]; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + + if (rttPinger.closed) { + return; + } + + function measureAndReschedule(conn?: Connection) { + if (rttPinger.closed) { + conn?.destroy({ force: true }); + return; + } + + if (rttPinger[kConnection] == null) { + rttPinger[kConnection] = conn; + } + + rttPinger[kRoundTripTime] = calculateDurationInMs(start); + rttPinger[kMonitorId] = setTimeout( + () => measureRoundTripTime(rttPinger, options), + heartbeatFrequencyMS + ); + } + + const connection = rttPinger[kConnection]; + if (connection == null) { + connect(options, (err, conn) => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + + measureAndReschedule(conn); + }); + + return; + } + + connection.command(ns('admin.$cmd'), { ismaster: 1 }, undefined, err => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + + measureAndReschedule(); + }); +} diff --git a/node_modules/mongodb/src/sdam/server.ts b/node_modules/mongodb/src/sdam/server.ts new file mode 100644 index 0000000..e3f1fb4 --- /dev/null +++ b/node_modules/mongodb/src/sdam/server.ts @@ -0,0 +1,602 @@ +import { Logger } from '../logger'; +import { + ConnectionPool, + ConnectionPoolOptions, + CMAP_EVENTS, + ConnectionPoolEvents +} from '../cmap/connection_pool'; +import { ServerDescription, compareTopologyVersion } from './server_description'; +import { Monitor, MonitorOptions } from './monitor'; +import { isTransactionCommand } from '../transactions'; +import { + collationNotSupported, + makeStateMachine, + maxWireVersion, + Callback, + CallbackWithType, + MongoDBNamespace, + EventEmitterWithState +} from '../utils'; +import { + STATE_CLOSED, + STATE_CLOSING, + STATE_CONNECTING, + STATE_CONNECTED, + ClusterTime, + TopologyType +} from './common'; +import { + MongoError, + MongoNetworkError, + MongoNetworkTimeoutError, + isSDAMUnrecoverableError, + isRetryableWriteError, + isNodeShuttingDownError, + isNetworkErrorBeforeHandshake, + MongoCompatibilityError, + MongoInvalidArgumentError, + MongoServerClosedError +} from '../error'; +import { + Connection, + DestroyOptions, + QueryOptions, + GetMoreOptions, + CommandOptions, + APM_EVENTS +} from '../cmap/connection'; +import type { Topology } from './topology'; +import type { + ServerHeartbeatFailedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent +} from './events'; +import type { ClientSession } from '../sessions'; +import type { Document, Long } from '../bson'; +import type { AutoEncrypter } from '../deps'; +import type { ServerApi } from '../mongo_client'; +import { TypedEventEmitter } from '../mongo_types'; +import { supportsRetryableWrites } from '../utils'; + +const stateTransition = makeStateMachine({ + [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], + [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], + [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], + [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] +}); + +/** @internal */ +const kMonitor = Symbol('monitor'); + +/** @public */ +export type ServerOptions = Omit & + MonitorOptions; + +/** @internal */ +export interface ServerPrivate { + /** The server description for this server */ + description: ServerDescription; + /** A copy of the options used to construct this instance */ + options: ServerOptions; + /** A logger instance */ + logger: Logger; + /** The current state of the Server */ + state: string; + /** The topology this server is a part of */ + topology: Topology; + /** A connection pool for this server */ + pool: ConnectionPool; + /** MongoDB server API version */ + serverApi?: ServerApi; +} + +/** @public */ +export type ServerEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + /** Top level MongoClient doesn't emit this so it is marked: @internal */ + connect(server: Server): void; + descriptionReceived(description: ServerDescription): void; + closed(): void; + ended(): void; +} & ConnectionPoolEvents & + EventEmitterWithState; + +/** @internal */ +export class Server extends TypedEventEmitter { + /** @internal */ + s: ServerPrivate; + serverApi?: ServerApi; + clusterTime?: ClusterTime; + ismaster?: Document; + [kMonitor]: Monitor; + + /** @event */ + static readonly SERVER_HEARTBEAT_STARTED = 'serverHeartbeatStarted' as const; + /** @event */ + static readonly SERVER_HEARTBEAT_SUCCEEDED = 'serverHeartbeatSucceeded' as const; + /** @event */ + static readonly SERVER_HEARTBEAT_FAILED = 'serverHeartbeatFailed' as const; + /** @event */ + static readonly CONNECT = 'connect' as const; + /** @event */ + static readonly DESCRIPTION_RECEIVED = 'descriptionReceived' as const; + /** @event */ + static readonly CLOSED = 'closed' as const; + /** @event */ + static readonly ENDED = 'ended' as const; + + /** + * Create a server + */ + constructor(topology: Topology, description: ServerDescription, options: ServerOptions) { + super(); + + this.serverApi = options.serverApi; + + const poolOptions = { hostAddress: description.hostAddress, ...options }; + + this.s = { + description, + options, + logger: new Logger('Server'), + state: STATE_CLOSED, + topology, + pool: new ConnectionPool(poolOptions) + }; + + for (const event of [...CMAP_EVENTS, ...APM_EVENTS]) { + this.s.pool.on(event, (e: any) => this.emit(event, e)); + } + + this.s.pool.on(Connection.CLUSTER_TIME_RECEIVED, (clusterTime: ClusterTime) => { + this.clusterTime = clusterTime; + }); + + // monitoring is disabled in load balancing mode + if (this.loadBalanced) return; + + // create the monitor + this[kMonitor] = new Monitor(this, this.s.options); + + for (const event of HEARTBEAT_EVENTS) { + this[kMonitor].on(event, (e: any) => this.emit(event, e)); + } + + this[kMonitor].on('resetConnectionPool', () => { + this.s.pool.clear(); + }); + + this[kMonitor].on('resetServer', (error: MongoError) => markServerUnknown(this, error)); + this[kMonitor].on(Server.SERVER_HEARTBEAT_SUCCEEDED, (event: ServerHeartbeatSucceededEvent) => { + this.emit( + Server.DESCRIPTION_RECEIVED, + new ServerDescription(this.description.hostAddress, event.reply, { + roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration) + }) + ); + + if (this.s.state === STATE_CONNECTING) { + stateTransition(this, STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + }); + } + + get description(): ServerDescription { + return this.s.description; + } + + get name(): string { + return this.s.description.address; + } + + get autoEncrypter(): AutoEncrypter | undefined { + if (this.s.options && this.s.options.autoEncrypter) { + return this.s.options.autoEncrypter; + } + } + + get loadBalanced(): boolean { + return this.s.topology.description.type === TopologyType.LoadBalanced; + } + + /** + * Initiate server connect + */ + connect(): void { + if (this.s.state !== STATE_CLOSED) { + return; + } + + stateTransition(this, STATE_CONNECTING); + + // If in load balancer mode we automatically set the server to + // a load balancer. It never transitions out of this state and + // has no monitor. + if (!this.loadBalanced) { + this[kMonitor].connect(); + } else { + stateTransition(this, STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + } + + /** Destroy the server connection */ + destroy(options?: DestroyOptions, callback?: Callback): void { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { force: false }, options); + + if (this.s.state === STATE_CLOSED) { + if (typeof callback === 'function') { + callback(); + } + + return; + } + + stateTransition(this, STATE_CLOSING); + + if (!this.loadBalanced) { + this[kMonitor].close(); + } + + this.s.pool.close(options, err => { + stateTransition(this, STATE_CLOSED); + this.emit('closed'); + if (typeof callback === 'function') { + callback(err); + } + }); + } + + /** + * Immediately schedule monitoring of this server. If there already an attempt being made + * this will be a no-op. + */ + requestCheck(): void { + if (!this.loadBalanced) { + this[kMonitor].requestCheck(); + } + } + + /** + * Execute a command + * @internal + */ + command(ns: MongoDBNamespace, cmd: Document, callback: Callback): void; + /** @internal */ + command( + ns: MongoDBNamespace, + cmd: Document, + options: CommandOptions, + callback: Callback + ): void; + command( + ns: MongoDBNamespace, + cmd: Document, + options?: CommandOptions | Callback, + callback?: Callback + ): void { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options ?? {}); + } + + if (callback == null) { + throw new MongoInvalidArgumentError('Callback must be provided'); + } + + if (ns.db == null || typeof ns === 'string') { + throw new MongoInvalidArgumentError('Namespace must not be a string'); + } + + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + callback(new MongoServerClosedError()); + return; + } + + // Clone the options + const finalOptions = Object.assign({}, options, { wireProtocolCommand: false }); + + // error if collation not supported + if (collationNotSupported(this, cmd)) { + callback(new MongoCompatibilityError(`Server ${this.name} does not support collation`)); + return; + } + + const session = finalOptions.session; + const conn = session?.pinnedConnection; + + // NOTE: This is a hack! We can't retrieve the connections used for executing an operation + // (and prevent them from being checked back in) at the point of operation execution. + // This should be considered as part of the work for NODE-2882 + if (this.loadBalanced && session && conn == null && isPinnableCommand(cmd, session)) { + this.s.pool.checkOut((err, checkedOut) => { + if (err || checkedOut == null) { + if (callback) return callback(err); + return; + } + + session.pin(checkedOut); + this.command(ns, cmd, finalOptions, callback as Callback); + }); + + return; + } + + this.s.pool.withConnection( + conn, + (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, err); + return cb(err); + } + + conn.command( + ns, + cmd, + finalOptions, + makeOperationHandler(this, conn, cmd, finalOptions, cb) as Callback + ); + }, + callback + ); + } + + /** + * Execute a query against the server + * @internal + */ + query(ns: MongoDBNamespace, cmd: Document, options: QueryOptions, callback: Callback): void { + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + callback(new MongoServerClosedError()); + return; + } + + this.s.pool.withConnection( + undefined, + (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, err); + return cb(err); + } + + conn.query( + ns, + cmd, + options, + makeOperationHandler(this, conn, cmd, options, cb) as Callback + ); + }, + callback + ); + } + + /** + * Execute a `getMore` against the server + * @internal + */ + getMore( + ns: MongoDBNamespace, + cursorId: Long, + options: GetMoreOptions, + callback: Callback + ): void { + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + callback(new MongoServerClosedError()); + return; + } + + this.s.pool.withConnection( + options.session?.pinnedConnection, + (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, err); + return cb(err); + } + + conn.getMore( + ns, + cursorId, + options, + makeOperationHandler(this, conn, {}, options, cb) as Callback + ); + }, + callback + ); + } + + /** + * Execute a `killCursors` command against the server + * @internal + */ + killCursors( + ns: MongoDBNamespace, + cursorIds: Long[], + options: CommandOptions, + callback?: Callback + ): void { + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + if (typeof callback === 'function') { + callback(new MongoServerClosedError()); + } + + return; + } + + this.s.pool.withConnection( + options.session?.pinnedConnection, + (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, err); + return cb(err); + } + + conn.killCursors( + ns, + cursorIds, + options, + makeOperationHandler(this, conn, {}, undefined, cb) as Callback + ); + }, + callback + ); + } +} + +export const HEARTBEAT_EVENTS = [ + Server.SERVER_HEARTBEAT_STARTED, + Server.SERVER_HEARTBEAT_SUCCEEDED, + Server.SERVER_HEARTBEAT_FAILED +]; + +Object.defineProperty(Server.prototype, 'clusterTime', { + get() { + return this.s.topology.clusterTime; + }, + set(clusterTime: ClusterTime) { + this.s.topology.clusterTime = clusterTime; + } +}); + +function calculateRoundTripTime(oldRtt: number, duration: number): number { + if (oldRtt === -1) { + return duration; + } + + const alpha = 0.2; + return alpha * duration + (1 - alpha) * oldRtt; +} + +function markServerUnknown(server: Server, error?: MongoError) { + // Load balancer servers can never be marked unknown. + if (server.loadBalanced) { + return; + } + + if (error instanceof MongoNetworkError && !(error instanceof MongoNetworkTimeoutError)) { + server[kMonitor].reset(); + } + + server.emit( + Server.DESCRIPTION_RECEIVED, + new ServerDescription(server.description.hostAddress, undefined, { + error, + topologyVersion: + error && error.topologyVersion ? error.topologyVersion : server.description.topologyVersion + }) + ); +} + +function isPinnableCommand(cmd: Document, session?: ClientSession): boolean { + if (session) { + return ( + session.inTransaction() || + 'aggregate' in cmd || + 'find' in cmd || + 'getMore' in cmd || + 'listCollections' in cmd || + 'listIndexes' in cmd + ); + } + + return false; +} + +function connectionIsStale(pool: ConnectionPool, connection: Connection) { + if (connection.serviceId) { + return ( + connection.generation !== pool.serviceGenerations.get(connection.serviceId.toHexString()) + ); + } + + return connection.generation !== pool.generation; +} + +function shouldHandleStateChangeError(server: Server, err: MongoError) { + const etv = err.topologyVersion; + const stv = server.description.topologyVersion; + return compareTopologyVersion(stv, etv) < 0; +} + +function inActiveTransaction(session: ClientSession | undefined, cmd: Document) { + return session && session.inTransaction() && !isTransactionCommand(cmd); +} + +/** this checks the retryWrites option passed down from the client options, it + * does not check if the server supports retryable writes */ +function isRetryableWritesEnabled(topology: Topology) { + return topology.s.options.retryWrites !== false; +} + +function makeOperationHandler( + server: Server, + connection: Connection, + cmd: Document, + options: CommandOptions | GetMoreOptions | undefined, + callback: Callback +): CallbackWithType { + const session = options?.session; + return function handleOperationResult(err, result) { + if (err && !connectionIsStale(server.s.pool, connection)) { + if (err instanceof MongoNetworkError) { + if (session && !session.hasEnded && session.serverSession) { + session.serverSession.isDirty = true; + } + + // inActiveTransaction check handles commit and abort. + if (inActiveTransaction(session, cmd) && !err.hasErrorLabel('TransientTransactionError')) { + err.addErrorLabel('TransientTransactionError'); + } + + if ( + (isRetryableWritesEnabled(server.s.topology) || isTransactionCommand(cmd)) && + supportsRetryableWrites(server) && + !inActiveTransaction(session, cmd) + ) { + err.addErrorLabel('RetryableWriteError'); + } + + if (!(err instanceof MongoNetworkTimeoutError) || isNetworkErrorBeforeHandshake(err)) { + // In load balanced mode we never mark the server as unknown and always + // clear for the specific service id. + + server.s.pool.clear(connection.serviceId); + if (!server.loadBalanced) { + markServerUnknown(server, err); + } + } + } else { + // if pre-4.4 server, then add error label if its a retryable write error + if ( + (isRetryableWritesEnabled(server.s.topology) || isTransactionCommand(cmd)) && + maxWireVersion(server) < 9 && + isRetryableWriteError(err) && + !inActiveTransaction(session, cmd) + ) { + err.addErrorLabel('RetryableWriteError'); + } + + if (isSDAMUnrecoverableError(err)) { + if (shouldHandleStateChangeError(server, err)) { + if (maxWireVersion(server) <= 7 || isNodeShuttingDownError(err)) { + server.s.pool.clear(connection.serviceId); + } + + if (!server.loadBalanced) { + markServerUnknown(server, err); + process.nextTick(() => server.requestCheck()); + } + } + } + } + + if (session && session.isPinned && err.hasErrorLabel('TransientTransactionError')) { + session.unpin({ force: true }); + } + } + + callback(err, result); + }; +} diff --git a/node_modules/mongodb/src/sdam/server_description.ts b/node_modules/mongodb/src/sdam/server_description.ts new file mode 100644 index 0000000..bd907b2 --- /dev/null +++ b/node_modules/mongodb/src/sdam/server_description.ts @@ -0,0 +1,279 @@ +import { arrayStrictEqual, errorStrictEqual, now, HostAddress } from '../utils'; +import { ServerType } from './common'; +import { ObjectId, Long, Document } from '../bson'; +import type { ClusterTime } from './common'; +import type { MongoError } from '../error'; + +const WRITABLE_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.Standalone, + ServerType.Mongos, + ServerType.LoadBalancer +]); + +const DATA_BEARING_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.RSSecondary, + ServerType.Mongos, + ServerType.Standalone, + ServerType.LoadBalancer +]); + +/** @public */ +export interface TopologyVersion { + processId: ObjectId; + counter: Long; +} + +/** @public */ +export type TagSet = { [key: string]: string }; + +/** @internal */ +export interface ServerDescriptionOptions { + /** An Error used for better reporting debugging */ + error?: MongoError; + + /** The round trip time to ping this server (in ms) */ + roundTripTime?: number; + + /** The topologyVersion */ + topologyVersion?: TopologyVersion; + + /** If the client is in load balancing mode. */ + loadBalanced?: boolean; +} + +/** + * The client's view of a single server, based on the most recent ismaster outcome. + * + * Internal type, not meant to be directly instantiated + * @public + */ +export class ServerDescription { + private _hostAddress: HostAddress; + address: string; + type: ServerType; + hosts: string[]; + passives: string[]; + arbiters: string[]; + tags: TagSet; + + error?: MongoError; + topologyVersion?: TopologyVersion; + minWireVersion: number; + maxWireVersion: number; + roundTripTime: number; + lastUpdateTime: number; + lastWriteDate: number; + + me?: string; + primary?: string; + setName?: string; + setVersion?: number; + electionId?: ObjectId; + logicalSessionTimeoutMinutes?: number; + + // NOTE: does this belong here? It seems we should gossip the cluster time at the CMAP level + $clusterTime?: ClusterTime; + + /** + * Create a ServerDescription + * @internal + * + * @param address - The address of the server + * @param ismaster - An optional ismaster response for this server + */ + constructor( + address: HostAddress | string, + ismaster?: Document, + options?: ServerDescriptionOptions + ) { + if (typeof address === 'string') { + this._hostAddress = new HostAddress(address); + this.address = this._hostAddress.toString(); + } else { + this._hostAddress = address; + this.address = this._hostAddress.toString(); + } + this.type = parseServerType(ismaster, options); + this.hosts = ismaster?.hosts?.map((host: string) => host.toLowerCase()) ?? []; + this.passives = ismaster?.passives?.map((host: string) => host.toLowerCase()) ?? []; + this.arbiters = ismaster?.arbiters?.map((host: string) => host.toLowerCase()) ?? []; + this.tags = ismaster?.tags ?? {}; + this.minWireVersion = ismaster?.minWireVersion ?? 0; + this.maxWireVersion = ismaster?.maxWireVersion ?? 0; + this.roundTripTime = options?.roundTripTime ?? -1; + this.lastUpdateTime = now(); + this.lastWriteDate = ismaster?.lastWrite?.lastWriteDate ?? 0; + + if (options?.topologyVersion) { + this.topologyVersion = options.topologyVersion; + } else if (ismaster?.topologyVersion) { + this.topologyVersion = ismaster.topologyVersion; + } + + if (options?.error) { + this.error = options.error; + } + + if (ismaster?.primary) { + this.primary = ismaster.primary; + } + + if (ismaster?.me) { + this.me = ismaster.me.toLowerCase(); + } + + if (ismaster?.setName) { + this.setName = ismaster.setName; + } + + if (ismaster?.setVersion) { + this.setVersion = ismaster.setVersion; + } + + if (ismaster?.electionId) { + this.electionId = ismaster.electionId; + } + + if (ismaster?.logicalSessionTimeoutMinutes) { + this.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; + } + + if (ismaster?.$clusterTime) { + this.$clusterTime = ismaster.$clusterTime; + } + } + + get hostAddress(): HostAddress { + if (this._hostAddress) return this._hostAddress; + else return new HostAddress(this.address); + } + + get allHosts(): string[] { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + + /** Is this server available for reads*/ + get isReadable(): boolean { + return this.type === ServerType.RSSecondary || this.isWritable; + } + + /** Is this server data bearing */ + get isDataBearing(): boolean { + return DATA_BEARING_SERVER_TYPES.has(this.type); + } + + /** Is this server available for writes */ + get isWritable(): boolean { + return WRITABLE_SERVER_TYPES.has(this.type); + } + + get host(): string { + const chopLength = `:${this.port}`.length; + return this.address.slice(0, -chopLength); + } + + get port(): number { + const port = this.address.split(':').pop(); + return port ? Number.parseInt(port, 10) : 27017; + } + + /** + * Determines if another `ServerDescription` is equal to this one per the rules defined + * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} + */ + equals(other: ServerDescription): boolean { + const topologyVersionsEqual = + this.topologyVersion === other.topologyVersion || + compareTopologyVersion(this.topologyVersion, other.topologyVersion) === 0; + + const electionIdsEqual: boolean = + this.electionId && other.electionId + ? other.electionId && this.electionId.equals(other.electionId) + : this.electionId === other.electionId; + + return ( + other != null && + errorStrictEqual(this.error, other.error) && + this.type === other.type && + this.minWireVersion === other.minWireVersion && + arrayStrictEqual(this.hosts, other.hosts) && + tagsStrictEqual(this.tags, other.tags) && + this.setName === other.setName && + this.setVersion === other.setVersion && + electionIdsEqual && + this.primary === other.primary && + this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && + topologyVersionsEqual + ); + } +} + +// Parses an `ismaster` message and determines the server type +export function parseServerType( + ismaster?: Document, + options?: ServerDescriptionOptions +): ServerType { + if (options?.loadBalanced) { + return ServerType.LoadBalancer; + } + + if (!ismaster || !ismaster.ok) { + return ServerType.Unknown; + } + + if (ismaster.isreplicaset) { + return ServerType.RSGhost; + } + + if (ismaster.msg && ismaster.msg === 'isdbgrid') { + return ServerType.Mongos; + } + + if (ismaster.setName) { + if (ismaster.hidden) { + return ServerType.RSOther; + } else if (ismaster.ismaster || ismaster.isWritablePrimary) { + return ServerType.RSPrimary; + } else if (ismaster.secondary) { + return ServerType.RSSecondary; + } else if (ismaster.arbiterOnly) { + return ServerType.RSArbiter; + } else { + return ServerType.RSOther; + } + } + + return ServerType.Standalone; +} + +function tagsStrictEqual(tags: TagSet, tags2: TagSet): boolean { + const tagsKeys = Object.keys(tags); + const tags2Keys = Object.keys(tags2); + + return ( + tagsKeys.length === tags2Keys.length && + tagsKeys.every((key: string) => tags2[key] === tags[key]) + ); +} + +/** + * Compares two topology versions. + * + * @returns A negative number if `lhs` is older than `rhs`; positive if `lhs` is newer than `rhs`; 0 if they are equivalent. + */ +export function compareTopologyVersion(lhs?: TopologyVersion, rhs?: TopologyVersion): number { + if (lhs == null || rhs == null) { + return -1; + } + + if (lhs.processId.equals(rhs.processId)) { + // tests mock counter as just number, but in a real situation counter should always be a Long + const lhsCounter = Long.isLong(lhs.counter) ? lhs.counter : Long.fromNumber(lhs.counter); + const rhsCounter = Long.isLong(rhs.counter) ? lhs.counter : Long.fromNumber(rhs.counter); + return lhsCounter.compare(rhsCounter); + } + + return -1; +} diff --git a/node_modules/mongodb/src/sdam/server_selection.ts b/node_modules/mongodb/src/sdam/server_selection.ts new file mode 100644 index 0000000..390da96 --- /dev/null +++ b/node_modules/mongodb/src/sdam/server_selection.ts @@ -0,0 +1,281 @@ +import { ServerType, TopologyType } from './common'; +import { ReadPreference } from '../read_preference'; +import { MongoCompatibilityError, MongoInvalidArgumentError } from '../error'; +import type { TopologyDescription } from './topology_description'; +import type { ServerDescription, TagSet } from './server_description'; + +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; + +/** @public */ +export type ServerSelector = ( + topologyDescription: TopologyDescription, + servers: ServerDescription[] +) => ServerDescription[]; + +/** + * Returns a server selector that selects for writable servers + */ +export function writableServerSelector(): ServerSelector { + return ( + topologyDescription: TopologyDescription, + servers: ServerDescription[] + ): ServerDescription[] => + latencyWindowReducer( + topologyDescription, + servers.filter((s: ServerDescription) => s.isWritable) + ); +} + +/** + * Reduces the passed in array of servers by the rules of the "Max Staleness" specification + * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst + * + * @param readPreference - The read preference providing max staleness guidance + * @param topologyDescription - The topology description + * @param servers - The list of server descriptions to be reduced + * @returns The list of servers that satisfy the requirements of max staleness + */ +function maxStalenessReducer( + readPreference: ReadPreference, + topologyDescription: TopologyDescription, + servers: ServerDescription[] +): ServerDescription[] { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; + } + + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = + (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw new MongoInvalidArgumentError( + `Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds` + ); + } + + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new MongoInvalidArgumentError( + `Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` + ); + } + + if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { + const primary: ServerDescription = Array.from(topologyDescription.servers.values()).filter( + primaryFilter + )[0]; + + return servers.reduce((result: ServerDescription[], server: ServerDescription) => { + const stalenessMS = + server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + + return result; + }, []); + } + + if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { + if (servers.length === 0) { + return servers; + } + + const sMax = servers.reduce((max: ServerDescription, s: ServerDescription) => + s.lastWriteDate > max.lastWriteDate ? s : max + ); + + return servers.reduce((result: ServerDescription[], server: ServerDescription) => { + const stalenessMS = + sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + + return result; + }, []); + } + + return servers; +} + +/** + * Determines whether a server's tags match a given set of tags + * + * @param tagSet - The requested tag set to match + * @param serverTags - The server's tags + */ +function tagSetMatch(tagSet: TagSet, serverTags: TagSet) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } + } + + return true; +} + +/** + * Reduces a set of server descriptions based on tags requested by the read preference + * + * @param readPreference - The read preference providing the requested tags + * @param servers - The list of server descriptions to reduce + * @returns The list of servers matching the requested tags + */ +function tagSetReducer( + readPreference: ReadPreference, + servers: ServerDescription[] +): ServerDescription[] { + if ( + readPreference.tags == null || + (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) + ) { + return servers; + } + + for (let i = 0; i < readPreference.tags.length; ++i) { + const tagSet = readPreference.tags[i]; + const serversMatchingTagset = servers.reduce( + (matched: ServerDescription[], server: ServerDescription) => { + if (tagSetMatch(tagSet, server.tags)) matched.push(server); + return matched; + }, + [] + ); + + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } + } + + return []; +} + +/** + * Reduces a list of servers to ensure they fall within an acceptable latency window. This is + * further specified in the "Server Selection" specification, found here: + * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst + * + * @param topologyDescription - The topology description + * @param servers - The list of servers to reduce + * @returns The servers which fall within an acceptable latency window + */ +function latencyWindowReducer( + topologyDescription: TopologyDescription, + servers: ServerDescription[] +): ServerDescription[] { + const low = servers.reduce( + (min: number, server: ServerDescription) => + min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min), + -1 + ); + + const high = low + topologyDescription.localThresholdMS; + return servers.reduce((result: ServerDescription[], server: ServerDescription) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); + return result; + }, []); +} + +// filters +function primaryFilter(server: ServerDescription): boolean { + return server.type === ServerType.RSPrimary; +} + +function secondaryFilter(server: ServerDescription): boolean { + return server.type === ServerType.RSSecondary; +} + +function nearestFilter(server: ServerDescription): boolean { + return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; +} + +function knownFilter(server: ServerDescription): boolean { + return server.type !== ServerType.Unknown; +} + +function loadBalancerFilter(server: ServerDescription): boolean { + return server.type === ServerType.LoadBalancer; +} + +/** + * Returns a function which selects servers based on a provided read preference + * + * @param readPreference - The read preference to select with + */ +export function readPreferenceServerSelector(readPreference: ReadPreference): ServerSelector { + if (!readPreference.isValid()) { + throw new MongoInvalidArgumentError('Invalid read preference specified'); + } + + return ( + topologyDescription: TopologyDescription, + servers: ServerDescription[] + ): ServerDescription[] => { + const commonWireVersion = topologyDescription.commonWireVersion; + if ( + commonWireVersion && + readPreference.minWireVersion && + readPreference.minWireVersion > commonWireVersion + ) { + throw new MongoCompatibilityError( + `Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'` + ); + } + + if (topologyDescription.type === TopologyType.LoadBalanced) { + return servers.filter(loadBalancerFilter); + } + + if (topologyDescription.type === TopologyType.Unknown) { + return []; + } + + if ( + topologyDescription.type === TopologyType.Single || + topologyDescription.type === TopologyType.Sharded + ) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); + } + + const mode = readPreference.mode; + if (mode === ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); + } + + if (mode === ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } + } + + const filter = mode === ReadPreference.NEAREST ? nearestFilter : secondaryFilter; + const selectedServers = latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)) + ) + ); + + if (mode === ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { + return servers.filter(primaryFilter); + } + + return selectedServers; + }; +} diff --git a/node_modules/mongodb/src/sdam/srv_polling.ts b/node_modules/mongodb/src/sdam/srv_polling.ts new file mode 100644 index 0000000..119bcc5 --- /dev/null +++ b/node_modules/mongodb/src/sdam/srv_polling.ts @@ -0,0 +1,162 @@ +import * as dns from 'dns'; +import { Logger, LoggerOptions } from '../logger'; +import { HostAddress } from '../utils'; +import { TypedEventEmitter } from '../mongo_types'; +import { MongoRuntimeError } from '../error'; + +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param srvAddress - The address to check against a domain + * @param parentDomain - The domain to check the provided address against + * @returns Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress: string, parentDomain: string): boolean { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +/** + * @internal + * @category Event + */ +export class SrvPollingEvent { + srvRecords: dns.SrvRecord[]; + constructor(srvRecords: dns.SrvRecord[]) { + this.srvRecords = srvRecords; + } + + addresses(): Map { + return new Map( + this.srvRecords.map(record => { + const host = new HostAddress(`${record.name}:${record.port}`); + return [host.toString(), host]; + }) + ); + } +} + +/** @internal */ +export interface SrvPollerOptions extends LoggerOptions { + srvHost: string; + heartbeatFrequencyMS: number; +} + +/** @internal */ +export type SrvPollerEvents = { + srvRecordDiscovery(event: SrvPollingEvent): void; +}; + +/** @internal */ +export class SrvPoller extends TypedEventEmitter { + srvHost: string; + rescanSrvIntervalMS: number; + heartbeatFrequencyMS: number; + logger: Logger; + haMode: boolean; + generation: number; + _timeout?: NodeJS.Timeout; + + /** @event */ + static readonly SRV_RECORD_DISCOVERY = 'srvRecordDiscovery' as const; + + constructor(options: SrvPollerOptions) { + super(); + + if (!options || !options.srvHost) { + throw new MongoRuntimeError('Options for SrvPoller must exist and include srvHost'); + } + + this.srvHost = options.srvHost; + this.rescanSrvIntervalMS = 60000; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + this.logger = new Logger('srvPoller', options); + + this.haMode = false; + this.generation = 0; + + this._timeout = undefined; + } + + get srvAddress(): string { + return `_mongodb._tcp.${this.srvHost}`; + } + + get intervalMS(): number { + return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; + } + + start(): void { + if (!this._timeout) { + this.schedule(); + } + } + + stop(): void { + if (this._timeout) { + clearTimeout(this._timeout); + this.generation += 1; + this._timeout = undefined; + } + } + + schedule(): void { + if (this._timeout) { + clearTimeout(this._timeout); + } + + this._timeout = setTimeout(() => this._poll(), this.intervalMS); + } + + success(srvRecords: dns.SrvRecord[]): void { + this.haMode = false; + this.schedule(); + this.emit(SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords)); + } + + failure(message: string, obj?: NodeJS.ErrnoException): void { + this.logger.warn(message, obj); + this.haMode = true; + this.schedule(); + } + + parentDomainMismatch(srvRecord: dns.SrvRecord): void { + this.logger.warn( + `parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, + srvRecord + ); + } + + _poll(): void { + const generation = this.generation; + dns.resolveSrv(this.srvAddress, (err, srvRecords) => { + if (generation !== this.generation) { + return; + } + + if (err) { + this.failure('DNS error', err); + return; + } + + const finalAddresses: dns.SrvRecord[] = []; + srvRecords.forEach((record: dns.SrvRecord) => { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } else { + this.parentDomainMismatch(record); + } + }); + + if (!finalAddresses.length) { + this.failure('No valid addresses found at host'); + return; + } + + this.success(finalAddresses); + }); + } +} diff --git a/node_modules/mongodb/src/sdam/topology.ts b/node_modules/mongodb/src/sdam/topology.ts new file mode 100644 index 0000000..67f81db --- /dev/null +++ b/node_modules/mongodb/src/sdam/topology.ts @@ -0,0 +1,1109 @@ +import Denque = require('denque'); +import { ReadPreference, ReadPreferenceLike } from '../read_preference'; +import { compareTopologyVersion, ServerDescription } from './server_description'; +import { TopologyDescription } from './topology_description'; +import { Server, ServerEvents, ServerOptions } from './server'; +import { + ClientSession, + ServerSessionPool, + ServerSessionId, + ClientSessionOptions +} from '../sessions'; +import { SrvPoller, SrvPollingEvent } from './srv_polling'; +import { CMAP_EVENTS, ConnectionPoolEvents } from '../cmap/connection_pool'; +import { + MongoServerSelectionError, + MongoCompatibilityError, + MongoDriverError, + MongoTopologyClosedError, + MongoRuntimeError +} from '../error'; +import { readPreferenceServerSelector, ServerSelector } from './server_selection'; +import { + makeStateMachine, + eachAsync, + ClientMetadata, + Callback, + HostAddress, + ns, + emitWarning, + EventEmitterWithState +} from '../utils'; +import { + TopologyType, + ServerType, + ClusterTime, + TimerQueue, + _advanceClusterTime, + drainTimerQueue, + clearAndRemoveTimerFrom, + STATE_CLOSED, + STATE_CLOSING, + STATE_CONNECTING, + STATE_CONNECTED +} from './common'; +import { + ServerOpeningEvent, + ServerClosedEvent, + ServerDescriptionChangedEvent, + TopologyOpeningEvent, + TopologyClosedEvent, + TopologyDescriptionChangedEvent +} from './events'; +import type { Document, BSONSerializeOptions } from '../bson'; +import type { MongoCredentials } from '../cmap/auth/mongo_credentials'; +import type { Transaction } from '../transactions'; +import type { CloseOptions } from '../cmap/connection_pool'; +import { DestroyOptions, Connection, ConnectionEvents } from '../cmap/connection'; +import type { MongoOptions, ServerApi } from '../mongo_client'; +import { DEFAULT_OPTIONS } from '../connection_string'; +import { serialize, deserialize } from '../bson'; +import { TypedEventEmitter } from '../mongo_types'; + +// Global state +let globalTopologyCounter = 0; + +// events that we relay to the `Topology` +const SERVER_RELAY_EVENTS = [ + Server.SERVER_HEARTBEAT_STARTED, + Server.SERVER_HEARTBEAT_SUCCEEDED, + Server.SERVER_HEARTBEAT_FAILED, + Connection.COMMAND_STARTED, + Connection.COMMAND_SUCCEEDED, + Connection.COMMAND_FAILED, + ...CMAP_EVENTS +]; + +// all events we listen to from `Server` instances +const LOCAL_SERVER_EVENTS = [ + Server.CONNECT, + Server.DESCRIPTION_RECEIVED, + Server.CLOSED, + Server.ENDED +]; + +const stateTransition = makeStateMachine({ + [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], + [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], + [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], + [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] +}); + +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); + +/** @internal */ +export type ServerSelectionCallback = Callback; + +/** @internal */ +export interface ServerSelectionRequest { + serverSelector: ServerSelector; + transaction?: Transaction; + callback: ServerSelectionCallback; + timer?: NodeJS.Timeout; + [kCancelled]?: boolean; +} + +/** @internal */ +export interface TopologyPrivate { + /** the id of this topology */ + id: number; + /** passed in options */ + options: TopologyOptions; + /** initial seedlist of servers to connect to */ + seedlist: HostAddress[]; + /** initial state */ + state: string; + /** the topology description */ + description: TopologyDescription; + serverSelectionTimeoutMS: number; + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; + /** A map of server instances to normalized addresses */ + servers: Map; + /** Server Session Pool */ + sessionPool: ServerSessionPool; + /** Active client sessions */ + sessions: Set; + credentials?: MongoCredentials; + clusterTime?: ClusterTime; + /** timers created for the initial connect to a server */ + connectionTimers: TimerQueue; + + /** related to srv polling */ + srvPoller?: SrvPoller; + detectShardedTopology: (event: TopologyDescriptionChangedEvent) => void; + detectSrvRecords: (event: SrvPollingEvent) => void; +} + +/** @public */ +export interface TopologyOptions extends BSONSerializeOptions, ServerOptions { + hosts: HostAddress[]; + retryWrites: boolean; + retryReads: boolean; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS: number; + /** The name of the replica set to connect to */ + replicaSet?: string; + srvHost?: string; + /** @internal */ + srvPoller?: SrvPoller; + /** Indicates that a client should directly connect to a node without attempting to discover its topology type */ + directConnection: boolean; + loadBalanced: boolean; + metadata: ClientMetadata; + /** MongoDB server API version */ + serverApi?: ServerApi; +} + +/** @public */ +export interface ConnectOptions { + readPreference?: ReadPreference; +} + +/** @public */ +export interface SelectServerOptions { + readPreference?: ReadPreferenceLike; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS?: number; + session?: ClientSession; +} + +/** @public */ +export type TopologyEvents = { + /** Top level MongoClient doesn't emit this so it is marked: @internal */ + connect(topology: Topology): void; + serverOpening(event: ServerOpeningEvent): void; + serverClosed(event: ServerClosedEvent): void; + serverDescriptionChanged(event: ServerDescriptionChangedEvent): void; + topologyClosed(event: TopologyClosedEvent): void; + topologyOpening(event: TopologyOpeningEvent): void; + topologyDescriptionChanged(event: TopologyDescriptionChangedEvent): void; + error(error: Error): void; + /** TODO(NODE-3273) - remove error @internal */ + open(error: undefined, topology: Topology): void; + close(): void; + timeout(): void; +} & Omit & + ConnectionPoolEvents & + ConnectionEvents & + EventEmitterWithState; +/** + * A container of server instances representing a connection to a MongoDB topology. + * @internal + */ +export class Topology extends TypedEventEmitter { + /** @internal */ + s: TopologyPrivate; + /** @internal */ + [kWaitQueue]: Denque; + /** @internal */ + ismaster?: Document; + /** @internal */ + _type?: string; + + /** @event */ + static readonly SERVER_OPENING = 'serverOpening' as const; + /** @event */ + static readonly SERVER_CLOSED = 'serverClosed' as const; + /** @event */ + static readonly SERVER_DESCRIPTION_CHANGED = 'serverDescriptionChanged' as const; + /** @event */ + static readonly TOPOLOGY_OPENING = 'topologyOpening' as const; + /** @event */ + static readonly TOPOLOGY_CLOSED = 'topologyClosed' as const; + /** @event */ + static readonly TOPOLOGY_DESCRIPTION_CHANGED = 'topologyDescriptionChanged' as const; + /** @event */ + static readonly ERROR = 'error' as const; + /** @event */ + static readonly OPEN = 'open' as const; + /** @event */ + static readonly CONNECT = 'connect' as const; + /** @event */ + static readonly CLOSE = 'close' as const; + /** @event */ + static readonly TIMEOUT = 'timeout' as const; + + /** + * @internal + * + * @privateRemarks + * mongodb-client-encryption's class ClientEncryption falls back to finding the bson lib + * defined on client.topology.bson, in order to maintain compatibility with any version + * of mongodb-client-encryption we keep a reference to serialize and deserialize here. + */ + bson: { serialize: typeof serialize; deserialize: typeof deserialize }; + + /** + * @param seedlist - a list of HostAddress instances to connect to + */ + constructor(seeds: string | string[] | HostAddress | HostAddress[], options: TopologyOptions) { + super(); + + // Legacy CSFLE support + this.bson = Object.create(null); + this.bson.serialize = serialize; + this.bson.deserialize = deserialize; + + // Options should only be undefined in tests, MongoClient will always have defined options + options = options ?? { + hosts: [HostAddress.fromString('localhost:27017')], + retryReads: DEFAULT_OPTIONS.get('retryReads'), + retryWrites: DEFAULT_OPTIONS.get('retryWrites'), + serverSelectionTimeoutMS: DEFAULT_OPTIONS.get('serverSelectionTimeoutMS'), + directConnection: DEFAULT_OPTIONS.get('directConnection'), + loadBalanced: DEFAULT_OPTIONS.get('loadBalanced'), + metadata: DEFAULT_OPTIONS.get('metadata'), + monitorCommands: DEFAULT_OPTIONS.get('monitorCommands'), + tls: DEFAULT_OPTIONS.get('tls'), + maxPoolSize: DEFAULT_OPTIONS.get('maxPoolSize'), + minPoolSize: DEFAULT_OPTIONS.get('minPoolSize'), + waitQueueTimeoutMS: DEFAULT_OPTIONS.get('waitQueueTimeoutMS'), + connectionType: DEFAULT_OPTIONS.get('connectionType'), + connectTimeoutMS: DEFAULT_OPTIONS.get('connectTimeoutMS'), + maxIdleTimeMS: DEFAULT_OPTIONS.get('maxIdleTimeMS'), + heartbeatFrequencyMS: DEFAULT_OPTIONS.get('heartbeatFrequencyMS'), + minHeartbeatFrequencyMS: DEFAULT_OPTIONS.get('minHeartbeatFrequencyMS') + }; + + if (typeof seeds === 'string') { + seeds = [HostAddress.fromString(seeds)]; + } else if (!Array.isArray(seeds)) { + seeds = [seeds]; + } + + const seedlist: HostAddress[] = []; + for (const seed of seeds) { + if (typeof seed === 'string') { + seedlist.push(HostAddress.fromString(seed)); + } else if (seed instanceof HostAddress) { + seedlist.push(seed); + } else { + // FIXME(NODE-3483): May need to be a MongoParseError + throw new MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(seed)}`); + } + } + + const topologyType = topologyTypeFromOptions(options); + const topologyId = globalTopologyCounter++; + + const serverDescriptions = new Map(); + for (const hostAddress of seedlist) { + serverDescriptions.set(hostAddress.toString(), new ServerDescription(hostAddress)); + } + + this[kWaitQueue] = new Denque(); + this.s = { + // the id of this topology + id: topologyId, + // passed in options + options, + // initial seedlist of servers to connect to + seedlist, + // initial state + state: STATE_CLOSED, + // the topology description + description: new TopologyDescription( + topologyType, + serverDescriptions, + options.replicaSet, + undefined, + undefined, + undefined, + options + ), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, + // a map of server instances to normalized addresses + servers: new Map(), + // Server Session Pool + sessionPool: new ServerSessionPool(this), + // Active client sessions + sessions: new Set(), + credentials: options?.credentials, + clusterTime: undefined, + + // timer management + connectionTimers: new Set(), + + detectShardedTopology: ev => this.detectShardedTopology(ev), + detectSrvRecords: ev => this.detectSrvRecords(ev) + }; + + if (options.srvHost && !options.loadBalanced) { + this.s.srvPoller = + options.srvPoller ?? + new SrvPoller({ + heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, + srvHost: options.srvHost + }); + + this.on(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + } + } + + private detectShardedTopology(event: TopologyDescriptionChangedEvent) { + const previousType = event.previousDescription.type; + const newType = event.newDescription.type; + + const transitionToSharded = + previousType !== TopologyType.Sharded && newType === TopologyType.Sharded; + const srvListeners = this.s.srvPoller?.listeners(SrvPoller.SRV_RECORD_DISCOVERY); + const listeningToSrvPolling = !!srvListeners?.includes(this.s.detectSrvRecords); + + if (transitionToSharded && !listeningToSrvPolling) { + this.s.srvPoller?.on(SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + this.s.srvPoller?.start(); + } + } + + private detectSrvRecords(ev: SrvPollingEvent) { + const previousTopologyDescription = this.s.description; + this.s.description = this.s.description.updateFromSrvPollingEvent(ev); + if (this.s.description === previousTopologyDescription) { + // Nothing changed, so return + return; + } + + updateServers(this); + + this.emit( + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + new TopologyDescriptionChangedEvent( + this.s.id, + previousTopologyDescription, + this.s.description + ) + ); + } + + /** + * @returns A `TopologyDescription` for this topology + */ + get description(): TopologyDescription { + return this.s.description; + } + + get loadBalanced(): boolean { + return this.s.options.loadBalanced; + } + + get capabilities(): ServerCapabilities { + return new ServerCapabilities(this.lastIsMaster()); + } + + /** Initiate server connect */ + connect(options?: ConnectOptions, callback?: Callback): void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + if (this.s.state === STATE_CONNECTED) { + if (typeof callback === 'function') { + callback(); + } + + return; + } + + stateTransition(this, STATE_CONNECTING); + + // emit SDAM monitoring events + this.emit(Topology.TOPOLOGY_OPENING, new TopologyOpeningEvent(this.s.id)); + + // emit an event for the topology change + this.emit( + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + new TopologyDescriptionChangedEvent( + this.s.id, + new TopologyDescription(TopologyType.Unknown), // initial is always Unknown + this.s.description + ) + ); + + // connect all known servers, then attempt server selection to connect + const serverDescriptions = Array.from(this.s.description.servers.values()); + connectServers(this, serverDescriptions); + + // In load balancer mode we need to fake a server description getting + // emitted from the monitor, since the monitor doesn't exist. + if (this.s.options.loadBalanced) { + for (const description of serverDescriptions) { + const newDescription = new ServerDescription(description.hostAddress, undefined, { + loadBalanced: this.s.options.loadBalanced + }); + this.serverUpdateHandler(newDescription); + } + } + + const readPreference = options.readPreference ?? ReadPreference.primary; + this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { + if (err) { + this.close(); + + typeof callback === 'function' ? callback(err) : this.emit(Topology.ERROR, err); + return; + } + + // TODO: NODE-2471 + if (server && this.s.credentials) { + server.command(ns('admin.$cmd'), { ping: 1 }, err => { + if (err) { + typeof callback === 'function' ? callback(err) : this.emit(Topology.ERROR, err); + return; + } + + stateTransition(this, STATE_CONNECTED); + // TODO(NODE-3273) - remove err + this.emit(Topology.OPEN, err, this); + this.emit(Topology.CONNECT, this); + + if (typeof callback === 'function') callback(undefined, this); + }); + + return; + } + + stateTransition(this, STATE_CONNECTED); + // TODO(NODE-3273) - remove err + this.emit(Topology.OPEN, err, this); + this.emit(Topology.CONNECT, this); + + if (typeof callback === 'function') callback(undefined, this); + }); + } + + /** Close this topology */ + close(options?: CloseOptions, callback?: Callback): void { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + if (typeof options === 'boolean') { + options = { force: options }; + } + + options = options ?? {}; + if (this.s.state === STATE_CLOSED || this.s.state === STATE_CLOSING) { + if (typeof callback === 'function') { + callback(); + } + + return; + } + + stateTransition(this, STATE_CLOSING); + + drainWaitQueue(this[kWaitQueue], new MongoTopologyClosedError()); + drainTimerQueue(this.s.connectionTimers); + + if (this.s.srvPoller) { + this.s.srvPoller.stop(); + this.s.srvPoller.removeListener(SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + } + + this.removeListener(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + + eachAsync( + Array.from(this.s.sessions.values()), + (session, cb) => session.endSession(cb), + () => { + this.s.sessionPool.endAllPooledSessions(() => { + eachAsync( + Array.from(this.s.servers.values()), + (server, cb) => destroyServer(server, this, options, cb), + err => { + this.s.servers.clear(); + + // emit an event for close + this.emit(Topology.TOPOLOGY_CLOSED, new TopologyClosedEvent(this.s.id)); + + stateTransition(this, STATE_CLOSED); + + if (typeof callback === 'function') { + callback(err); + } + } + ); + }); + } + ); + } + + /** + * Selects a server according to the selection predicate provided + * + * @param selector - An optional selector to select servers by, defaults to a random selection within a latency window + * @param options - Optional settings related to server selection + * @param callback - The callback used to indicate success or failure + * @returns An instance of a `Server` meeting the criteria of the predicate provided + */ + selectServer(options: SelectServerOptions, callback: Callback): void; + selectServer( + selector: string | ReadPreference | ServerSelector, + callback: Callback + ): void; + selectServer( + selector: string | ReadPreference | ServerSelector, + options: SelectServerOptions, + callback: Callback + ): void; + selectServer( + selector: string | ReadPreference | ServerSelector | SelectServerOptions, + _options?: SelectServerOptions | Callback, + _callback?: Callback + ): void { + let options = _options as SelectServerOptions; + const callback = (_callback ?? _options) as Callback; + if (typeof options === 'function') { + options = {}; + } + + let serverSelector; + if (typeof selector !== 'function') { + if (typeof selector === 'string') { + serverSelector = readPreferenceServerSelector(ReadPreference.fromString(selector)); + } else { + let readPreference; + if (selector instanceof ReadPreference) { + readPreference = selector; + } else { + ReadPreference.translate(options); + readPreference = options.readPreference || ReadPreference.primary; + } + + serverSelector = readPreferenceServerSelector(readPreference as ReadPreference); + } + } else { + serverSelector = selector; + } + + options = Object.assign( + {}, + { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, + options + ); + + const isSharded = this.description.type === TopologyType.Sharded; + const session = options.session; + const transaction = session && session.transaction; + + if (isSharded && transaction && transaction.server) { + callback(undefined, transaction.server); + return; + } + + const waitQueueMember: ServerSelectionRequest = { + serverSelector, + transaction, + callback + }; + + const serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; + if (serverSelectionTimeoutMS) { + waitQueueMember.timer = setTimeout(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + const timeoutError = new MongoServerSelectionError( + `Server selection timed out after ${serverSelectionTimeoutMS} ms`, + this.description + ); + + waitQueueMember.callback(timeoutError); + }, serverSelectionTimeoutMS); + } + + this[kWaitQueue].push(waitQueueMember); + processWaitQueue(this); + } + + // Sessions related methods + + /** + * @returns Whether the topology should initiate selection to determine session support + */ + shouldCheckForSessionSupport(): boolean { + if (this.description.type === TopologyType.Single) { + return !this.description.hasKnownServers; + } + + return !this.description.hasDataBearingServers; + } + + /** + * @returns Whether sessions are supported on the current topology + */ + hasSessionSupport(): boolean { + return this.loadBalanced || this.description.logicalSessionTimeoutMinutes != null; + } + + /** Start a logical session */ + startSession(options: ClientSessionOptions, clientOptions?: MongoOptions): ClientSession { + const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); + session.once('ended', () => { + this.s.sessions.delete(session); + }); + + this.s.sessions.add(session); + return session; + } + + /** Send endSessions command(s) with the given session ids */ + endSessions(sessions: ServerSessionId[], callback?: Callback): void { + if (!Array.isArray(sessions)) { + sessions = [sessions]; + } + + this.selectServer( + readPreferenceServerSelector(ReadPreference.primaryPreferred), + (err, server) => { + if (err || !server) { + if (typeof callback === 'function') callback(err); + return; + } + + server.command( + ns('admin.$cmd'), + { endSessions: sessions }, + { noResponse: true }, + (err, result) => { + if (typeof callback === 'function') callback(err, result); + } + ); + } + ); + } + + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param serverDescription - The server to update in the internal list of server descriptions + */ + serverUpdateHandler(serverDescription: ServerDescription): void { + if (!this.s.description.hasServer(serverDescription.address)) { + return; + } + + // ignore this server update if its from an outdated topologyVersion + if (isStaleServerDescription(this.s.description, serverDescription)) { + return; + } + + // these will be used for monitoring events later + const previousTopologyDescription = this.s.description; + const previousServerDescription = this.s.description.servers.get(serverDescription.address); + if (!previousServerDescription) { + return; + } + + // Driver Sessions Spec: "Whenever a driver receives a cluster time from + // a server it MUST compare it to the current highest seen cluster time + // for the deployment. If the new cluster time is higher than the + // highest seen cluster time it MUST become the new highest seen cluster + // time. Two cluster times are compared using only the BsonTimestamp + // value of the clusterTime embedded field." + const clusterTime = serverDescription.$clusterTime; + if (clusterTime) { + _advanceClusterTime(this, clusterTime); + } + + // If we already know all the information contained in this updated description, then + // we don't need to emit SDAM events, but still need to update the description, in order + // to keep client-tracked attributes like last update time and round trip time up to date + const equalDescriptions = + previousServerDescription && previousServerDescription.equals(serverDescription); + + // first update the TopologyDescription + this.s.description = this.s.description.update(serverDescription); + if (this.s.description.compatibilityError) { + this.emit(Topology.ERROR, new MongoCompatibilityError(this.s.description.compatibilityError)); + return; + } + + // emit monitoring events for this change + if (!equalDescriptions) { + const newDescription = this.s.description.servers.get(serverDescription.address); + if (newDescription) { + this.emit( + Topology.SERVER_DESCRIPTION_CHANGED, + new ServerDescriptionChangedEvent( + this.s.id, + serverDescription.address, + previousServerDescription, + newDescription + ) + ); + } + } + + // update server list from updated descriptions + updateServers(this, serverDescription); + + // attempt to resolve any outstanding server selection attempts + if (this[kWaitQueue].length > 0) { + processWaitQueue(this); + } + + if (!equalDescriptions) { + this.emit( + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + new TopologyDescriptionChangedEvent( + this.s.id, + previousTopologyDescription, + this.s.description + ) + ); + } + } + + auth(credentials?: MongoCredentials, callback?: Callback): void { + if (typeof credentials === 'function') (callback = credentials), (credentials = undefined); + if (typeof callback === 'function') callback(undefined, true); + } + + get clientMetadata(): ClientMetadata { + return this.s.options.metadata; + } + + isConnected(): boolean { + return this.s.state === STATE_CONNECTED; + } + + isDestroyed(): boolean { + return this.s.state === STATE_CLOSED; + } + + /** + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref(): void { + emitWarning('`unref` is a noop and will be removed in the next major version'); + } + + // NOTE: There are many places in code where we explicitly check the last isMaster + // to do feature support detection. This should be done any other way, but for + // now we will just return the first isMaster seen, which should suffice. + lastIsMaster(): Document { + const serverDescriptions = Array.from(this.description.servers.values()); + if (serverDescriptions.length === 0) return {}; + const sd = serverDescriptions.filter( + (sd: ServerDescription) => sd.type !== ServerType.Unknown + )[0]; + + const result = sd || { maxWireVersion: this.description.commonWireVersion }; + return result; + } + + get logicalSessionTimeoutMinutes(): number | undefined { + return this.description.logicalSessionTimeoutMinutes; + } + + get clusterTime(): ClusterTime | undefined { + return this.s.clusterTime; + } + + set clusterTime(clusterTime: ClusterTime | undefined) { + this.s.clusterTime = clusterTime; + } +} + +/** @public */ +export const TOPOLOGY_EVENTS = [ + Topology.SERVER_OPENING, + Topology.SERVER_CLOSED, + Topology.SERVER_DESCRIPTION_CHANGED, + Topology.TOPOLOGY_OPENING, + Topology.TOPOLOGY_CLOSED, + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + Topology.ERROR, + Topology.TIMEOUT, + Topology.CLOSE +]; + +/** Destroys a server, and removes all event listeners from the instance */ +function destroyServer( + server: Server, + topology: Topology, + options?: DestroyOptions, + callback?: Callback +) { + options = options ?? {}; + for (const event of LOCAL_SERVER_EVENTS) { + server.removeAllListeners(event); + } + + server.destroy(options, () => { + topology.emit( + Topology.SERVER_CLOSED, + new ServerClosedEvent(topology.s.id, server.description.address) + ); + + for (const event of SERVER_RELAY_EVENTS) { + server.removeAllListeners(event); + } + if (typeof callback === 'function') { + callback(); + } + }); +} + +/** Predicts the TopologyType from options */ +function topologyTypeFromOptions(options?: TopologyOptions) { + if (options?.directConnection) { + return TopologyType.Single; + } + + if (options?.replicaSet) { + return TopologyType.ReplicaSetNoPrimary; + } + + if (options?.loadBalanced) { + return TopologyType.LoadBalanced; + } + + return TopologyType.Unknown; +} + +function randomSelection(array: ServerDescription[]): ServerDescription { + return array[Math.floor(Math.random() * array.length)]; +} + +/** + * Creates new server instances and attempts to connect them + * + * @param topology - The topology that this server belongs to + * @param serverDescription - The description for the server to initialize and connect to + * @param connectDelay - Time to wait before attempting initial connection + */ +function createAndConnectServer( + topology: Topology, + serverDescription: ServerDescription, + connectDelay?: number +) { + topology.emit( + Topology.SERVER_OPENING, + new ServerOpeningEvent(topology.s.id, serverDescription.address) + ); + + const server = new Server(topology, serverDescription, topology.s.options); + for (const event of SERVER_RELAY_EVENTS) { + server.on(event, (e: any) => topology.emit(event, e)); + } + + server.on(Server.DESCRIPTION_RECEIVED, description => topology.serverUpdateHandler(description)); + + if (connectDelay) { + const connectTimer = setTimeout(() => { + clearAndRemoveTimerFrom(connectTimer, topology.s.connectionTimers); + server.connect(); + }, connectDelay); + + topology.s.connectionTimers.add(connectTimer); + return server; + } + + server.connect(); + return server; +} + +/** + * Create `Server` instances for all initially known servers, connect them, and assign + * them to the passed in `Topology`. + * + * @param topology - The topology responsible for the servers + * @param serverDescriptions - A list of server descriptions to connect + */ +function connectServers(topology: Topology, serverDescriptions: ServerDescription[]) { + topology.s.servers = serverDescriptions.reduce( + (servers: Map, serverDescription: ServerDescription) => { + const server = createAndConnectServer(topology, serverDescription); + servers.set(serverDescription.address, server); + return servers; + }, + new Map() + ); +} + +/** + * @param topology - Topology to update. + * @param incomingServerDescription - New server description. + */ +function updateServers(topology: Topology, incomingServerDescription?: ServerDescription) { + // update the internal server's description + if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { + const server = topology.s.servers.get(incomingServerDescription.address); + if (server) { + server.s.description = incomingServerDescription; + } + } + + // add new servers for all descriptions we currently don't know about locally + for (const serverDescription of topology.description.servers.values()) { + if (!topology.s.servers.has(serverDescription.address)) { + const server = createAndConnectServer(topology, serverDescription); + topology.s.servers.set(serverDescription.address, server); + } + } + + // for all servers no longer known, remove their descriptions and destroy their instances + for (const entry of topology.s.servers) { + const serverAddress = entry[0]; + if (topology.description.hasServer(serverAddress)) { + continue; + } + + if (!topology.s.servers.has(serverAddress)) { + continue; + } + + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + + // prepare server for garbage collection + if (server) { + destroyServer(server, topology); + } + } +} + +function drainWaitQueue(queue: Denque, err?: MongoDriverError) { + while (queue.length) { + const waitQueueMember = queue.shift(); + if (!waitQueueMember) { + continue; + } + + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + + if (!waitQueueMember[kCancelled]) { + waitQueueMember.callback(err); + } + } +} + +function processWaitQueue(topology: Topology) { + if (topology.s.state === STATE_CLOSED) { + drainWaitQueue(topology[kWaitQueue], new MongoTopologyClosedError()); + return; + } + + const isSharded = topology.description.type === TopologyType.Sharded; + const serverDescriptions = Array.from(topology.description.servers.values()); + const membersToProcess = topology[kWaitQueue].length; + for (let i = 0; i < membersToProcess; ++i) { + const waitQueueMember = topology[kWaitQueue].shift(); + if (!waitQueueMember) { + continue; + } + + if (waitQueueMember[kCancelled]) { + continue; + } + + let selectedDescriptions; + try { + const serverSelector = waitQueueMember.serverSelector; + selectedDescriptions = serverSelector + ? serverSelector(topology.description, serverDescriptions) + : serverDescriptions; + } catch (e) { + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + + waitQueueMember.callback(e); + continue; + } + + if (selectedDescriptions.length === 0) { + topology[kWaitQueue].push(waitQueueMember); + continue; + } + + const selectedServerDescription = randomSelection(selectedDescriptions); + const selectedServer = topology.s.servers.get(selectedServerDescription.address); + const transaction = waitQueueMember.transaction; + if (isSharded && transaction && transaction.isActive && selectedServer) { + transaction.pinServer(selectedServer); + } + + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + + waitQueueMember.callback(undefined, selectedServer); + } + + if (topology[kWaitQueue].length > 0) { + // ensure all server monitors attempt monitoring soon + for (const [, server] of topology.s.servers) { + process.nextTick(function scheduleServerCheck() { + return server.requestCheck(); + }); + } + } +} + +function isStaleServerDescription( + topologyDescription: TopologyDescription, + incomingServerDescription: ServerDescription +) { + const currentServerDescription = topologyDescription.servers.get( + incomingServerDescription.address + ); + const currentTopologyVersion = currentServerDescription?.topologyVersion; + return ( + compareTopologyVersion(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0 + ); +} + +/** @public */ +export class ServerCapabilities { + maxWireVersion: number; + minWireVersion: number; + + constructor(ismaster: Document) { + this.minWireVersion = ismaster.minWireVersion || 0; + this.maxWireVersion = ismaster.maxWireVersion || 0; + } + + get hasAggregationCursor(): boolean { + return this.maxWireVersion >= 1; + } + + get hasWriteCommands(): boolean { + return this.maxWireVersion >= 2; + } + get hasTextSearch(): boolean { + return this.minWireVersion >= 0; + } + + get hasAuthCommands(): boolean { + return this.maxWireVersion >= 1; + } + + get hasListCollectionsCommand(): boolean { + return this.maxWireVersion >= 3; + } + + get hasListIndexesCommand(): boolean { + return this.maxWireVersion >= 3; + } + + get supportsSnapshotReads(): boolean { + return this.maxWireVersion >= 13; + } + + get commandsTakeWriteConcern(): boolean { + return this.maxWireVersion >= 5; + } + + get commandsTakeCollation(): boolean { + return this.maxWireVersion >= 5; + } +} diff --git a/node_modules/mongodb/src/sdam/topology_description.ts b/node_modules/mongodb/src/sdam/topology_description.ts new file mode 100644 index 0000000..60ad5e6 --- /dev/null +++ b/node_modules/mongodb/src/sdam/topology_description.ts @@ -0,0 +1,487 @@ +import { ServerDescription } from './server_description'; +import * as WIRE_CONSTANTS from '../cmap/wire_protocol/constants'; +import { TopologyType, ServerType } from './common'; +import type { ObjectId, Document } from '../bson'; +import type { SrvPollingEvent } from './srv_polling'; +import { MongoError, MongoRuntimeError } from '../error'; + +// constants related to compatibility checks +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; + +const MONGOS_OR_UNKNOWN = new Set([ServerType.Mongos, ServerType.Unknown]); +const MONGOS_OR_STANDALONE = new Set([ServerType.Mongos, ServerType.Standalone]); +const NON_PRIMARY_RS_MEMBERS = new Set([ + ServerType.RSSecondary, + ServerType.RSArbiter, + ServerType.RSOther +]); + +/** @public */ +export interface TopologyDescriptionOptions { + heartbeatFrequencyMS?: number; + localThresholdMS?: number; +} + +/** + * Representation of a deployment of servers + * @public + */ +export class TopologyDescription { + type: TopologyType; + setName?: string; + maxSetVersion?: number; + maxElectionId?: ObjectId; + servers: Map; + stale: boolean; + compatible: boolean; + compatibilityError?: string; + logicalSessionTimeoutMinutes?: number; + heartbeatFrequencyMS: number; + localThresholdMS: number; + commonWireVersion?: number; + + /** + * Create a TopologyDescription + */ + constructor( + topologyType: TopologyType, + serverDescriptions?: Map, + setName?: string, + maxSetVersion?: number, + maxElectionId?: ObjectId, + commonWireVersion?: number, + options?: TopologyDescriptionOptions + ) { + options = options ?? {}; + + // TODO: consider assigning all these values to a temporary value `s` which + // we use `Object.freeze` on, ensuring the internal state of this type + // is immutable. + this.type = topologyType ?? TopologyType.Unknown; + this.servers = serverDescriptions ?? new Map(); + this.stale = false; + this.compatible = true; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 0; + this.localThresholdMS = options.localThresholdMS ?? 0; + + if (setName) { + this.setName = setName; + } + + if (maxSetVersion) { + this.maxSetVersion = maxSetVersion; + } + + if (maxElectionId) { + this.maxElectionId = maxElectionId; + } + + if (commonWireVersion) { + this.commonWireVersion = commonWireVersion; + } + + // determine server compatibility + for (const serverDescription of this.servers.values()) { + // Load balancer mode is always compatible. + if ( + serverDescription.type === ServerType.Unknown || + serverDescription.type === ServerType.LoadBalancer + ) { + continue; + } + + if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + } + + if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; + break; + } + } + + // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set + // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes + // value among ServerDescriptions of all data-bearing server types. If any have a null + // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be + // set to null. + this.logicalSessionTimeoutMinutes = undefined; + for (const [, server] of this.servers) { + if (server.isReadable) { + if (server.logicalSessionTimeoutMinutes == null) { + // If any of the servers have a null logicalSessionsTimeout, then the whole topology does + this.logicalSessionTimeoutMinutes = undefined; + break; + } + + if (this.logicalSessionTimeoutMinutes == null) { + // First server with a non null logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes; + continue; + } + + // Always select the smaller of the: + // current server logicalSessionsTimeout and the topologies logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = Math.min( + this.logicalSessionTimeoutMinutes, + server.logicalSessionTimeoutMinutes + ); + } + } + } + + /** + * Returns a new TopologyDescription based on the SrvPollingEvent + * @internal + */ + updateFromSrvPollingEvent(ev: SrvPollingEvent): TopologyDescription { + const newAddresses = ev.addresses(); + const serverDescriptions = new Map(this.servers); + for (const address of this.servers.keys()) { + if (newAddresses.has(address)) { + newAddresses.delete(address); + } else { + serverDescriptions.delete(address); + } + } + + if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) { + return this; + } + + for (const [address, host] of newAddresses) { + serverDescriptions.set(address, new ServerDescription(host)); + } + + return new TopologyDescription( + this.type, + serverDescriptions, + this.setName, + this.maxSetVersion, + this.maxElectionId, + this.commonWireVersion, + { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS } + ); + } + + /** + * Returns a copy of this description updated with a given ServerDescription + * @internal + */ + update(serverDescription: ServerDescription): TopologyDescription { + const address = serverDescription.address; + + // potentially mutated values + let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this; + + if (serverDescription.setName && setName && serverDescription.setName !== setName) { + serverDescription = new ServerDescription(address, undefined); + } + + const serverType = serverDescription.type; + const serverDescriptions = new Map(this.servers); + + // update common wire version + if (serverDescription.maxWireVersion !== 0) { + if (commonWireVersion == null) { + commonWireVersion = serverDescription.maxWireVersion; + } else { + commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); + } + } + + // update the actual server description + serverDescriptions.set(address, serverDescription); + + if (topologyType === TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription( + TopologyType.Single, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS } + ); + } + + if (topologyType === TopologyType.Unknown) { + if (serverType === ServerType.Standalone && this.servers.size !== 1) { + serverDescriptions.delete(address); + } else { + topologyType = topologyTypeForServerType(serverType); + } + } + + if (topologyType === TopologyType.Sharded) { + if (!MONGOS_OR_UNKNOWN.has(serverType)) { + serverDescriptions.delete(address); + } + } + + if (topologyType === TopologyType.ReplicaSetNoPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + } + + if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + serverDescription, + setName, + maxSetVersion, + maxElectionId + ); + + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName); + topologyType = result[0]; + setName = result[1]; + } + } + + if (topologyType === TopologyType.ReplicaSetWithPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } else if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + serverDescription, + setName, + maxSetVersion, + maxElectionId + ); + + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + topologyType = updateRsWithPrimaryFromMember( + serverDescriptions, + serverDescription, + setName + ); + } else { + topologyType = checkHasPrimary(serverDescriptions); + } + } + + return new TopologyDescription( + topologyType, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS } + ); + } + + get error(): MongoError | undefined { + const descriptionsWithError = Array.from(this.servers.values()).filter( + (sd: ServerDescription) => sd.error + ); + + if (descriptionsWithError.length > 0) { + return descriptionsWithError[0].error; + } + } + + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers(): boolean { + return Array.from(this.servers.values()).some( + (sd: ServerDescription) => sd.type !== ServerType.Unknown + ); + } + + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers(): boolean { + return Array.from(this.servers.values()).some((sd: ServerDescription) => sd.isDataBearing); + } + + /** + * Determines if the topology has a definition for the provided address + * @internal + */ + hasServer(address: string): boolean { + return this.servers.has(address); + } +} + +function topologyTypeForServerType(serverType: ServerType): TopologyType { + switch (serverType) { + case ServerType.Standalone: + return TopologyType.Single; + case ServerType.Mongos: + return TopologyType.Sharded; + case ServerType.RSPrimary: + return TopologyType.ReplicaSetWithPrimary; + case ServerType.RSOther: + case ServerType.RSSecondary: + return TopologyType.ReplicaSetNoPrimary; + default: + return TopologyType.Unknown; + } +} + +// TODO: improve these docs when ObjectId is properly typed +function compareObjectId(oid1: Document, oid2: Document): number { + if (oid1 == null) { + return -1; + } + + if (oid2 == null) { + return 1; + } + + if (oid1.id instanceof Buffer && oid2.id instanceof Buffer) { + const oid1Buffer = oid1.id; + const oid2Buffer = oid2.id; + return oid1Buffer.compare(oid2Buffer); + } + + const oid1String = oid1.toString(); + const oid2String = oid2.toString(); + return oid1String.localeCompare(oid2String); +} + +function updateRsFromPrimary( + serverDescriptions: Map, + serverDescription: ServerDescription, + setName?: string, + maxSetVersion?: number, + maxElectionId?: ObjectId +): [TopologyType, string?, number?, ObjectId?] { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + + const electionId = serverDescription.electionId ? serverDescription.electionId : null; + if (serverDescription.setVersion && electionId) { + if (maxSetVersion && maxElectionId) { + if ( + maxSetVersion > serverDescription.setVersion || + compareObjectId(maxElectionId, electionId) > 0 + ) { + // this primary is stale, we must remove it + serverDescriptions.set( + serverDescription.address, + new ServerDescription(serverDescription.address) + ); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + + maxElectionId = serverDescription.electionId; + } + + if ( + serverDescription.setVersion != null && + (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) + ) { + maxSetVersion = serverDescription.setVersion; + } + + // We've heard from the primary. Is it the same primary as before? + for (const [address, server] of serverDescriptions) { + if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new ServerDescription(server.address)); + + // There can only be one primary + break; + } + } + + // Discover new hosts from this primary's response. + serverDescription.allHosts.forEach((address: string) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + // Remove hosts not in the response. + const currentAddresses = Array.from(serverDescriptions.keys()); + const responseAddresses = serverDescription.allHosts; + currentAddresses + .filter((addr: string) => responseAddresses.indexOf(addr) === -1) + .forEach((address: string) => { + serverDescriptions.delete(address); + }); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; +} + +function updateRsWithPrimaryFromMember( + serverDescriptions: Map, + serverDescription: ServerDescription, + setName?: string +): TopologyType { + if (setName == null) { + // TODO(NODE-3483): should be an appropriate runtime error + throw new MongoRuntimeError('Argument "setName" is required if connected to a replica set'); + } + + if ( + setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me) + ) { + serverDescriptions.delete(serverDescription.address); + } + + return checkHasPrimary(serverDescriptions); +} + +function updateRsNoPrimaryFromMember( + serverDescriptions: Map, + serverDescription: ServerDescription, + setName?: string +): [TopologyType, string?] { + const topologyType = TopologyType.ReplicaSetNoPrimary; + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [topologyType, setName]; + } + + serverDescription.allHosts.forEach((address: string) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + + return [topologyType, setName]; +} + +function checkHasPrimary(serverDescriptions: Map): TopologyType { + for (const serverDescription of serverDescriptions.values()) { + if (serverDescription.type === ServerType.RSPrimary) { + return TopologyType.ReplicaSetWithPrimary; + } + } + + return TopologyType.ReplicaSetNoPrimary; +} diff --git a/node_modules/mongodb/src/sessions.ts b/node_modules/mongodb/src/sessions.ts new file mode 100644 index 0000000..ec865f1 --- /dev/null +++ b/node_modules/mongodb/src/sessions.ts @@ -0,0 +1,1058 @@ +import { PromiseProvider } from './promise_provider'; +import { Binary, Long, Timestamp, Document } from './bson'; +import { ReadPreference } from './read_preference'; +import { isTransactionCommand, TxnState, Transaction, TransactionOptions } from './transactions'; +import { _advanceClusterTime, ClusterTime, TopologyType } from './sdam/common'; +import { isSharded } from './cmap/wire_protocol/shared'; +import { + MongoError, + MongoInvalidArgumentError, + isRetryableError, + MongoCompatibilityError, + MongoNetworkError, + MongoWriteConcernError, + MONGODB_ERROR_CODES, + MongoServerError, + MongoDriverError, + MongoAPIError, + AnyError, + MongoExpiredSessionError, + MongoTransactionError, + MongoRuntimeError +} from './error'; +import { + now, + calculateDurationInMs, + Callback, + isPromiseLike, + uuidV4, + maxWireVersion, + maybePromise +} from './utils'; +import type { Topology } from './sdam/topology'; +import type { MongoOptions } from './mongo_client'; +import { executeOperation } from './operations/execute_operation'; +import { RunAdminCommandOperation } from './operations/run_command'; +import type { AbstractCursor } from './cursor/abstract_cursor'; +import type { CommandOptions } from './cmap/connection'; +import { Connection } from './cmap/connection'; +import { ConnectionPoolMetrics } from './cmap/metrics'; +import type { WriteConcern } from './write_concern'; +import { TypedEventEmitter } from './mongo_types'; +import { ReadConcernLevel } from './read_concern'; + +const minWireVersionForShardedTransactions = 8; + +function assertAlive(session: ClientSession, callback?: Callback): boolean { + if (session.serverSession == null) { + const error = new MongoExpiredSessionError(); + if (typeof callback === 'function') { + callback(error); + return false; + } + + throw error; + } + + return true; +} + +/** @public */ +export interface ClientSessionOptions { + /** Whether causal consistency should be enabled on this session */ + causalConsistency?: boolean; + /** Whether all read operations should be read from the same snapshot for this session (NOTE: not compatible with `causalConsistency=true`) */ + snapshot?: boolean; + /** The default TransactionOptions to use for transactions started on this session. */ + defaultTransactionOptions?: TransactionOptions; + + /** @internal */ + owner?: symbol | AbstractCursor; + /** @internal */ + explicit?: boolean; + /** @internal */ + initialClusterTime?: ClusterTime; +} + +/** @public */ +export type WithTransactionCallback = (session: ClientSession) => Promise; + +/** @public */ +export type ClientSessionEvents = { + ended(session: ClientSession): void; +}; + +/** @internal */ +const kServerSession = Symbol('serverSession'); +/** @internal */ +const kSnapshotTime = Symbol('snapshotTime'); +/** @internal */ +const kSnapshotEnabled = Symbol('snapshotEnabled'); +/** @internal */ +const kPinnedConnection = Symbol('pinnedConnection'); + +/** @public */ +export interface EndSessionOptions { + /** + * An optional error which caused the call to end this session + * @internal + */ + error?: AnyError; + force?: boolean; + forceClear?: boolean; +} + +/** + * A class representing a client session on the server + * + * NOTE: not meant to be instantiated directly. + * @public + */ +export class ClientSession extends TypedEventEmitter { + /** @internal */ + topology: Topology; + /** @internal */ + sessionPool: ServerSessionPool; + hasEnded: boolean; + clientOptions?: MongoOptions; + supports: { causalConsistency: boolean }; + clusterTime?: ClusterTime; + operationTime?: Timestamp; + explicit: boolean; + /** @internal */ + owner?: symbol | AbstractCursor; + defaultTransactionOptions: TransactionOptions; + transaction: Transaction; + /** @internal */ + [kServerSession]?: ServerSession; + /** @internal */ + [kSnapshotTime]?: Timestamp; + /** @internal */ + [kSnapshotEnabled] = false; + /** @internal */ + [kPinnedConnection]?: Connection; + + /** + * Create a client session. + * @internal + * @param topology - The current client's topology (Internal Class) + * @param sessionPool - The server session pool (Internal Class) + * @param options - Optional settings + * @param clientOptions - Optional settings provided when creating a MongoClient + */ + constructor( + topology: Topology, + sessionPool: ServerSessionPool, + options: ClientSessionOptions, + clientOptions?: MongoOptions + ) { + super(); + + if (topology == null) { + // TODO(NODE-3483) + throw new MongoRuntimeError('ClientSession requires a topology'); + } + + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + // TODO(NODE-3483) + throw new MongoRuntimeError('ClientSession requires a ServerSessionPool'); + } + + options = options ?? {}; + + if (options.snapshot === true) { + this[kSnapshotEnabled] = true; + if (options.causalConsistency === true) { + throw new MongoInvalidArgumentError( + 'Properties "causalConsistency" and "snapshot" are mutually exclusive' + ); + } + } + + this.topology = topology; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.clientOptions = clientOptions; + this[kServerSession] = undefined; + + this.supports = { + causalConsistency: options.snapshot !== true && options.causalConsistency !== false + }; + + this.clusterTime = options.initialClusterTime; + + this.operationTime = undefined; + this.explicit = !!options.explicit; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new Transaction(); + } + + /** The server id associated with this session */ + get id(): ServerSessionId | undefined { + return this.serverSession?.id; + } + + get serverSession(): ServerSession { + if (this[kServerSession] == null) { + this[kServerSession] = this.sessionPool.acquire(); + } + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return this[kServerSession]!; + } + + /** Whether or not this session is configured for snapshot reads */ + get snapshotEnabled(): boolean { + return this[kSnapshotEnabled]; + } + + get loadBalanced(): boolean { + return this.topology.description.type === TopologyType.LoadBalanced; + } + + /** @internal */ + get pinnedConnection(): Connection | undefined { + return this[kPinnedConnection]; + } + + /** @internal */ + pin(conn: Connection): void { + if (this[kPinnedConnection]) { + throw TypeError('Cannot pin multiple connections to the same session'); + } + + this[kPinnedConnection] = conn; + conn.emit( + Connection.PINNED, + this.inTransaction() ? ConnectionPoolMetrics.TXN : ConnectionPoolMetrics.CURSOR + ); + } + + /** @internal */ + unpin(options?: { force?: boolean; forceClear?: boolean; error?: AnyError }): void { + if (this.loadBalanced) { + return maybeClearPinnedConnection(this, options); + } + + this.transaction.unpinServer(); + } + + get isPinned(): boolean { + return this.loadBalanced ? !!this[kPinnedConnection] : this.transaction.isPinned; + } + + /** + * Ends this session on the server + * + * @param options - Optional settings. Currently reserved for future use + * @param callback - Optional callback for completion of this operation + */ + endSession(): Promise; + endSession(callback: Callback): void; + endSession(options: EndSessionOptions): Promise; + endSession(options: EndSessionOptions, callback: Callback): void; + endSession( + options?: EndSessionOptions | Callback, + callback?: Callback + ): void | Promise { + if (typeof options === 'function') (callback = options), (options = {}); + const finalOptions = { force: true, ...options }; + + return maybePromise(callback, done => { + if (this.hasEnded) { + maybeClearPinnedConnection(this, finalOptions); + return done(); + } + + const completeEndSession = () => { + maybeClearPinnedConnection(this, finalOptions); + + // release the server session back to the pool + this.sessionPool.release(this.serverSession); + this[kServerSession] = undefined; + + // mark the session as ended, and emit a signal + this.hasEnded = true; + this.emit('ended', this); + + // spec indicates that we should ignore all errors for `endSessions` + done(); + }; + + if (this.serverSession && this.inTransaction()) { + this.abortTransaction(err => { + if (err) return done(err); + completeEndSession(); + }); + + return; + } + + completeEndSession(); + }); + } + + /** + * Advances the operationTime for a ClientSession. + * + * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime: Timestamp): void { + if (this.operationTime == null) { + this.operationTime = operationTime; + return; + } + + if (operationTime.greaterThan(this.operationTime)) { + this.operationTime = operationTime; + } + } + + /** + * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession + * + * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature + */ + advanceClusterTime(clusterTime: ClusterTime): void { + if (!clusterTime || typeof clusterTime !== 'object') { + throw new MongoInvalidArgumentError('input cluster time must be an object'); + } + if (!clusterTime.clusterTime || clusterTime.clusterTime._bsontype !== 'Timestamp') { + throw new MongoInvalidArgumentError( + 'input cluster time "clusterTime" property must be a valid BSON Timestamp' + ); + } + if ( + !clusterTime.signature || + clusterTime.signature.hash?._bsontype !== 'Binary' || + (typeof clusterTime.signature.keyId !== 'number' && + clusterTime.signature.keyId?._bsontype !== 'Long') // apparently we decode the key to number? + ) { + throw new MongoInvalidArgumentError( + 'input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId' + ); + } + + _advanceClusterTime(this, clusterTime); + } + + /** + * Used to determine if this session equals another + * + * @param session - The session to compare to + */ + equals(session: ClientSession): boolean { + if (!(session instanceof ClientSession)) { + return false; + } + + if (this.id == null || session.id == null) { + return false; + } + + return this.id.id.buffer.equals(session.id.id.buffer); + } + + /** Increment the transaction number on the internal ServerSession */ + incrementTransactionNumber(): void { + if (this.serverSession) { + this.serverSession.txnNumber = + typeof this.serverSession.txnNumber === 'number' ? this.serverSession.txnNumber + 1 : 0; + } + } + + /** @returns whether this session is currently in a transaction or not */ + inTransaction(): boolean { + return this.transaction.isActive; + } + + /** + * Starts a new transaction with the given options. + * + * @param options - Options for the transaction + */ + startTransaction(options?: TransactionOptions): void { + if (this[kSnapshotEnabled]) { + throw new MongoCompatibilityError('Transactions are not allowed with snapshot sessions'); + } + + assertAlive(this); + if (this.inTransaction()) { + throw new MongoTransactionError('Transaction already in progress'); + } + + if (this.isPinned && this.transaction.isCommitted) { + this.unpin(); + } + + const topologyMaxWireVersion = maxWireVersion(this.topology); + if ( + isSharded(this.topology) && + topologyMaxWireVersion != null && + topologyMaxWireVersion < minWireVersionForShardedTransactions + ) { + throw new MongoCompatibilityError( + 'Transactions are not supported on sharded clusters in MongoDB < 4.2.' + ); + } + + // increment txnNumber + this.incrementTransactionNumber(); + // create transaction state + this.transaction = new Transaction({ + readConcern: + options?.readConcern ?? + this.defaultTransactionOptions.readConcern ?? + this.clientOptions?.readConcern, + writeConcern: + options?.writeConcern ?? + this.defaultTransactionOptions.writeConcern ?? + this.clientOptions?.writeConcern, + readPreference: + options?.readPreference ?? + this.defaultTransactionOptions.readPreference ?? + this.clientOptions?.readPreference, + maxCommitTimeMS: options?.maxCommitTimeMS ?? this.defaultTransactionOptions.maxCommitTimeMS + }); + + this.transaction.transition(TxnState.STARTING_TRANSACTION); + } + + /** + * Commits the currently active transaction in this session. + * + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + commitTransaction(): Promise; + commitTransaction(callback: Callback): void; + commitTransaction(callback?: Callback): Promise | void { + return maybePromise(callback, cb => endTransaction(this, 'commitTransaction', cb)); + } + + /** + * Aborts the currently active transaction in this session. + * + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + abortTransaction(): Promise; + abortTransaction(callback: Callback): void; + abortTransaction(callback?: Callback): Promise | void { + return maybePromise(callback, cb => endTransaction(this, 'abortTransaction', cb)); + } + + /** + * This is here to ensure that ClientSession is never serialized to BSON. + */ + toBSON(): never { + throw new MongoRuntimeError('ClientSession cannot be serialized to BSON.'); + } + + /** + * Runs a provided lambda within a transaction, retrying either the commit operation + * or entire transaction as needed (and when the error permits) to better ensure that + * the transaction can complete successfully. + * + * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not + * return a Promise will result in undefined behavior. + * + * @param fn - A lambda to run within a transaction + * @param options - Optional settings for the transaction + */ + withTransaction( + fn: WithTransactionCallback, + options?: TransactionOptions + ): ReturnType { + const startTime = now(); + return attemptTransaction(this, startTime, fn, options); + } +} + +const MAX_WITH_TRANSACTION_TIMEOUT = 120000; +const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ + 'CannotSatisfyWriteConcern', + 'UnknownReplWriteConcern', + 'UnsatisfiableWriteConcern' +]); + +function hasNotTimedOut(startTime: number, max: number) { + return calculateDurationInMs(startTime) < max; +} + +function isUnknownTransactionCommitResult(err: MongoError) { + const isNonDeterministicWriteConcernError = + err instanceof MongoServerError && + err.codeName && + NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName); + + return ( + isMaxTimeMSExpiredError(err) || + (!isNonDeterministicWriteConcernError && + err.code !== MONGODB_ERROR_CODES.UnsatisfiableWriteConcern && + err.code !== MONGODB_ERROR_CODES.UnknownReplWriteConcern) + ); +} + +export function maybeClearPinnedConnection( + session: ClientSession, + options?: EndSessionOptions +): void { + // unpin a connection if it has been pinned + const conn = session[kPinnedConnection]; + const error = options?.error; + + if ( + session.inTransaction() && + error && + error instanceof MongoError && + error.hasErrorLabel('TransientTransactionError') + ) { + return; + } + + // NOTE: the spec talks about what to do on a network error only, but the tests seem to + // to validate that we don't unpin on _all_ errors? + if (conn) { + const servers = Array.from(session.topology.s.servers.values()); + const loadBalancer = servers[0]; + + if (options?.error == null || options?.force) { + loadBalancer.s.pool.checkIn(conn); + conn.emit( + Connection.UNPINNED, + session.transaction.state !== TxnState.NO_TRANSACTION + ? ConnectionPoolMetrics.TXN + : ConnectionPoolMetrics.CURSOR + ); + + if (options?.forceClear) { + loadBalancer.s.pool.clear(conn.serviceId); + } + } + + session[kPinnedConnection] = undefined; + } +} + +function isMaxTimeMSExpiredError(err: MongoError) { + if (err == null || !(err instanceof MongoServerError)) { + return false; + } + + return ( + err.code === MONGODB_ERROR_CODES.MaxTimeMSExpired || + (err.writeConcernError && err.writeConcernError.code === MONGODB_ERROR_CODES.MaxTimeMSExpired) + ); +} + +function attemptTransactionCommit( + session: ClientSession, + startTime: number, + fn: WithTransactionCallback, + options?: TransactionOptions +): Promise { + return session.commitTransaction().catch((err: MongoError) => { + if ( + err instanceof MongoError && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && + !isMaxTimeMSExpiredError(err) + ) { + if (err.hasErrorLabel('UnknownTransactionCommitResult')) { + return attemptTransactionCommit(session, startTime, fn, options); + } + + if (err.hasErrorLabel('TransientTransactionError')) { + return attemptTransaction(session, startTime, fn, options); + } + } + + throw err; + }); +} + +const USER_EXPLICIT_TXN_END_STATES = new Set([ + TxnState.NO_TRANSACTION, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_ABORTED +]); + +function userExplicitlyEndedTransaction(session: ClientSession) { + return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); +} + +function attemptTransaction( + session: ClientSession, + startTime: number, + fn: WithTransactionCallback, + options?: TransactionOptions +): Promise { + const Promise = PromiseProvider.get(); + session.startTransaction(options); + + let promise; + try { + promise = fn(session); + } catch (err) { + promise = Promise.reject(err); + } + + if (!isPromiseLike(promise)) { + session.abortTransaction(); + throw new MongoInvalidArgumentError( + 'Function provided to `withTransaction` must return a Promise' + ); + } + + return promise.then( + () => { + if (userExplicitlyEndedTransaction(session)) { + return; + } + + return attemptTransactionCommit(session, startTime, fn, options); + }, + err => { + function maybeRetryOrThrow(err: MongoError): Promise { + if ( + err instanceof MongoError && + err.hasErrorLabel('TransientTransactionError') && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) + ) { + return attemptTransaction(session, startTime, fn, options); + } + + if (isMaxTimeMSExpiredError(err)) { + err.addErrorLabel('UnknownTransactionCommitResult'); + } + + throw err; + } + + if (session.transaction.isActive) { + return session.abortTransaction().then(() => maybeRetryOrThrow(err)); + } + + return maybeRetryOrThrow(err); + } + ); +} + +function endTransaction(session: ClientSession, commandName: string, callback: Callback) { + if (!assertAlive(session, callback)) { + // checking result in case callback was called + return; + } + + // handle any initial problematic cases + const txnState = session.transaction.state; + + if (txnState === TxnState.NO_TRANSACTION) { + callback(new MongoTransactionError('No transaction started')); + return; + } + + if (commandName === 'commitTransaction') { + if ( + txnState === TxnState.STARTING_TRANSACTION || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback( + new MongoTransactionError('Cannot call commitTransaction after calling abortTransaction') + ); + return; + } + } else { + if (txnState === TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + callback(); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoTransactionError('Cannot call abortTransaction twice')); + return; + } + + if ( + txnState === TxnState.TRANSACTION_COMMITTED || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + callback( + new MongoTransactionError('Cannot call abortTransaction after calling commitTransaction') + ); + return; + } + } + + // construct and send the command + const command: Document = { [commandName]: 1 }; + + // apply a writeConcern if specified + let writeConcern; + if (session.transaction.options.writeConcern) { + writeConcern = Object.assign({}, session.transaction.options.writeConcern); + } else if (session.clientOptions && session.clientOptions.writeConcern) { + writeConcern = { w: session.clientOptions.writeConcern.w }; + } + + if (txnState === TxnState.TRANSACTION_COMMITTED) { + writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); + } + + if (writeConcern) { + Object.assign(command, { writeConcern }); + } + + if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { + Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); + } + + function commandHandler(e?: MongoError, r?: Document) { + if (commandName !== 'commitTransaction') { + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + if (session.loadBalanced) { + maybeClearPinnedConnection(session, { force: false }); + } + + // The spec indicates that we should ignore all errors on `abortTransaction` + return callback(); + } + + session.transaction.transition(TxnState.TRANSACTION_COMMITTED); + if (e) { + if ( + e instanceof MongoNetworkError || + e instanceof MongoWriteConcernError || + isRetryableError(e) || + isMaxTimeMSExpiredError(e) + ) { + if (isUnknownTransactionCommitResult(e)) { + e.addErrorLabel('UnknownTransactionCommitResult'); + + // per txns spec, must unpin session in this case + session.unpin({ error: e }); + } + } else if (e.hasErrorLabel('TransientTransactionError')) { + session.unpin({ error: e }); + } + } + + callback(e, r); + } + + // Assumption here that commandName is "commitTransaction" or "abortTransaction" + if (session.transaction.recoveryToken) { + command.recoveryToken = session.transaction.recoveryToken; + } + + // send the command + executeOperation( + session.topology, + new RunAdminCommandOperation(undefined, command, { + session, + readPreference: ReadPreference.primary, + bypassPinningCheck: true + }), + (err, reply) => { + if (command.abortTransaction) { + // always unpin on abort regardless of command outcome + session.unpin(); + } + + if (err && isRetryableError(err as MongoError)) { + // SPEC-1185: apply majority write concern when retrying commitTransaction + if (command.commitTransaction) { + // per txns spec, must unpin session in this case + session.unpin({ force: true }); + + command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { + w: 'majority' + }); + } + + return executeOperation( + session.topology, + new RunAdminCommandOperation(undefined, command, { + session, + readPreference: ReadPreference.primary, + bypassPinningCheck: true + }), + (_err, _reply) => commandHandler(_err as MongoError, _reply) + ); + } + + commandHandler(err as MongoError, reply); + } + ); +} + +/** @public */ +export type ServerSessionId = { id: Binary }; + +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @public + */ +export class ServerSession { + id: ServerSessionId; + lastUse: number; + txnNumber: number; + isDirty: boolean; + + /** @internal */ + constructor() { + this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; + this.lastUse = now(); + this.txnNumber = 0; + this.isDirty = false; + } + + /** + * Determines if the server session has timed out. + * + * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" + */ + hasTimedOut(sessionTimeoutMinutes: number): boolean { + // Take the difference of the lastUse timestamp and now, which will result in a value in + // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` + const idleTimeMinutes = Math.round( + ((calculateDurationInMs(this.lastUse) % 86400000) % 3600000) / 60000 + ); + + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } +} + +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @internal + */ +export class ServerSessionPool { + topology: Topology; + sessions: ServerSession[]; + + constructor(topology: Topology) { + if (topology == null) { + throw new MongoRuntimeError('ServerSessionPool requires a topology'); + } + + this.topology = topology; + this.sessions = []; + } + + /** Ends all sessions in the session pool */ + endAllPooledSessions(callback?: Callback): void { + if (this.sessions.length) { + this.topology.endSessions( + this.sessions.map((session: ServerSession) => session.id), + () => { + this.sessions = []; + if (typeof callback === 'function') { + callback(); + } + } + ); + + return; + } + + if (typeof callback === 'function') { + callback(); + } + } + + /** + * Acquire a Server Session from the pool. + * Iterates through each session in the pool, removing any stale sessions + * along the way. The first non-stale session found is removed from the + * pool and returned. If no non-stale session is found, a new ServerSession is created. + */ + acquire(): ServerSession { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes || 10; + + while (this.sessions.length) { + const session = this.sessions.shift(); + if (session && (this.topology.loadBalanced || !session.hasTimedOut(sessionTimeoutMinutes))) { + return session; + } + } + + return new ServerSession(); + } + + /** + * Release a session to the session pool + * Adds the session back to the session pool if the session has not timed out yet. + * This method also removes any stale sessions from the pool. + * + * @param session - The session to release to the pool + */ + release(session: ServerSession): void { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + + if (this.topology.loadBalanced && !sessionTimeoutMinutes) { + this.sessions.unshift(session); + } + + if (!sessionTimeoutMinutes) { + return; + } + + while (this.sessions.length) { + const pooledSession = this.sessions[this.sessions.length - 1]; + if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.pop(); + } else { + break; + } + } + + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + if (session.isDirty) { + return; + } + + // otherwise, readd this session to the session pool + this.sessions.unshift(session); + } + } +} + +// TODO: this should be codified in command construction +// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern +export function commandSupportsReadConcern(command: Document, options?: Document): boolean { + if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) { + return true; + } + + if ( + command.mapReduce && + options && + options.out && + (options.out.inline === 1 || options.out === 'inline') + ) { + return true; + } + + return false; +} + +/** + * Optionally decorate a command with sessions specific keys + * + * @param session - the session tracking transaction state + * @param command - the command to decorate + * @param options - Optional settings passed to calling operation + */ +export function applySession( + session: ClientSession, + command: Document, + options?: CommandOptions +): MongoDriverError | undefined { + // TODO: merge this with `assertAlive`, did not want to throw a try/catch here + if (session.hasEnded) { + return new MongoExpiredSessionError(); + } + + const serverSession = session.serverSession; + if (serverSession == null) { + return new MongoRuntimeError('Unable to acquire server session'); + } + + // SPEC-1019: silently ignore explicit session with unacknowledged write for backwards compatibility + // FIXME: NODE-2781, this check for write concern shouldn't be happening here, but instead during command construction + if (options && options.writeConcern && (options.writeConcern as WriteConcern).w === 0) { + if (session && session.explicit) { + return new MongoAPIError('Cannot have explicit session with unacknowledged writes'); + } + return; + } + + // mark the last use of this session, and apply the `lsid` + serverSession.lastUse = now(); + command.lsid = serverSession.id; + + // first apply non-transaction-specific sessions data + const inTransaction = session.inTransaction() || isTransactionCommand(command); + const isRetryableWrite = options?.willRetryWrite || false; + + if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { + command.txnNumber = Long.fromNumber(serverSession.txnNumber); + } + + if (!inTransaction) { + if (session.transaction.state !== TxnState.NO_TRANSACTION) { + session.transaction.transition(TxnState.NO_TRANSACTION); + } + + if ( + session.supports.causalConsistency && + session.operationTime && + commandSupportsReadConcern(command, options) + ) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } else if (session[kSnapshotEnabled]) { + command.readConcern = command.readConcern || { level: ReadConcernLevel.snapshot }; + if (session[kSnapshotTime] != null) { + Object.assign(command.readConcern, { atClusterTime: session[kSnapshotTime] }); + } + } + + return; + } + + // now attempt to apply transaction-specific sessions data + + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + + if (session.transaction.state === TxnState.STARTING_TRANSACTION) { + session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + + const readConcern = + session.transaction.options.readConcern || session?.clientOptions?.readConcern; + if (readConcern) { + command.readConcern = readConcern; + } + + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + } +} + +export function updateSessionFromResponse(session: ClientSession, document: Document): void { + if (document.$clusterTime) { + _advanceClusterTime(session, document.$clusterTime); + } + + if (document.operationTime && session && session.supports.causalConsistency) { + session.advanceOperationTime(document.operationTime); + } + + if (document.recoveryToken && session && session.inTransaction()) { + session.transaction._recoveryToken = document.recoveryToken; + } + + if (session?.[kSnapshotEnabled] && session[kSnapshotTime] == null) { + // find and aggregate commands return atClusterTime on the cursor + // distinct includes it in the response body + const atClusterTime = document.cursor?.atClusterTime || document.atClusterTime; + if (atClusterTime) { + session[kSnapshotTime] = atClusterTime; + } + } +} diff --git a/node_modules/mongodb/src/sort.ts b/node_modules/mongodb/src/sort.ts new file mode 100644 index 0000000..6b766b5 --- /dev/null +++ b/node_modules/mongodb/src/sort.ts @@ -0,0 +1,132 @@ +import { MongoInvalidArgumentError } from './error'; + +/** @public */ +export type SortDirection = + | 1 + | -1 + | 'asc' + | 'desc' + | 'ascending' + | 'descending' + | { $meta: string }; + +/** @public */ +export type Sort = + | string + | Exclude + | string[] + | { [key: string]: SortDirection } + | Map + | [string, SortDirection][] + | [string, SortDirection]; + +/** Below stricter types were created for sort that correspond with type that the cmd takes */ + +/** @internal */ +export type SortDirectionForCmd = 1 | -1 | { $meta: string }; + +/** @internal */ +export type SortForCmd = Map; + +/** @internal */ +type SortPairForCmd = [string, SortDirectionForCmd]; + +/** @internal */ +function prepareDirection(direction: any = 1): SortDirectionForCmd { + const value = `${direction}`.toLowerCase(); + if (isMeta(direction)) return direction; + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`); + } +} + +/** @internal */ +function isMeta(t: SortDirection): t is { $meta: string } { + return typeof t === 'object' && t != null && '$meta' in t && typeof t.$meta === 'string'; +} + +/** @internal */ +function isPair(t: Sort): t is [string, SortDirection] { + if (Array.isArray(t) && t.length === 2) { + try { + prepareDirection(t[1]); + return true; + } catch (e) { + return false; + } + } + return false; +} + +function isDeep(t: Sort): t is [string, SortDirection][] { + return Array.isArray(t) && Array.isArray(t[0]); +} + +function isMap(t: Sort): t is Map { + return t instanceof Map && t.size > 0; +} + +/** @internal */ +function pairToMap(v: [string, SortDirection]): SortForCmd { + return new Map([[`${v[0]}`, prepareDirection([v[1]])]]); +} + +/** @internal */ +function deepToMap(t: [string, SortDirection][]): SortForCmd { + const sortEntries: SortPairForCmd[] = t.map(([k, v]) => [`${k}`, prepareDirection(v)]); + return new Map(sortEntries); +} + +/** @internal */ +function stringsToMap(t: string[]): SortForCmd { + const sortEntries: SortPairForCmd[] = t.map(key => [`${key}`, 1]); + return new Map(sortEntries); +} + +/** @internal */ +function objectToMap(t: { [key: string]: SortDirection }): SortForCmd { + const sortEntries: SortPairForCmd[] = Object.entries(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} + +/** @internal */ +function mapToMap(t: Map): SortForCmd { + const sortEntries: SortPairForCmd[] = Array.from(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} + +/** converts a Sort type into a type that is valid for the server (SortForCmd) */ +export function formatSort( + sort: Sort | undefined, + direction?: SortDirection +): SortForCmd | undefined { + if (sort == null) return undefined; + if (typeof sort === 'string') return new Map([[sort, prepareDirection(direction)]]); + if (typeof sort !== 'object') { + throw new MongoInvalidArgumentError( + `Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object` + ); + } + if (!Array.isArray(sort)) { + return isMap(sort) ? mapToMap(sort) : Object.keys(sort).length ? objectToMap(sort) : undefined; + } + if (!sort.length) return undefined; + if (isDeep(sort)) return deepToMap(sort); + if (isPair(sort)) return pairToMap(sort); + return stringsToMap(sort); +} diff --git a/node_modules/mongodb/src/transactions.ts b/node_modules/mongodb/src/transactions.ts new file mode 100644 index 0000000..1b73ae3 --- /dev/null +++ b/node_modules/mongodb/src/transactions.ts @@ -0,0 +1,187 @@ +import { ReadPreference } from './read_preference'; +import { MongoRuntimeError, MongoTransactionError } from './error'; +import { ReadConcern } from './read_concern'; +import { WriteConcern } from './write_concern'; +import type { Server } from './sdam/server'; +import type { CommandOperationOptions } from './operations/command'; +import type { Document } from './bson'; + +/** @internal */ +export const TxnState = Object.freeze({ + NO_TRANSACTION: 'NO_TRANSACTION', + STARTING_TRANSACTION: 'STARTING_TRANSACTION', + TRANSACTION_IN_PROGRESS: 'TRANSACTION_IN_PROGRESS', + TRANSACTION_COMMITTED: 'TRANSACTION_COMMITTED', + TRANSACTION_COMMITTED_EMPTY: 'TRANSACTION_COMMITTED_EMPTY', + TRANSACTION_ABORTED: 'TRANSACTION_ABORTED' +} as const); + +/** @internal */ +export type TxnState = typeof TxnState[keyof typeof TxnState]; + +const stateMachine: { [state in TxnState]: TxnState[] } = { + [TxnState.NO_TRANSACTION]: [TxnState.NO_TRANSACTION, TxnState.STARTING_TRANSACTION], + [TxnState.STARTING_TRANSACTION]: [ + TxnState.TRANSACTION_IN_PROGRESS, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.TRANSACTION_ABORTED + ], + [TxnState.TRANSACTION_IN_PROGRESS]: [ + TxnState.TRANSACTION_IN_PROGRESS, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_ABORTED + ], + [TxnState.TRANSACTION_COMMITTED]: [ + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.STARTING_TRANSACTION, + TxnState.NO_TRANSACTION + ], + [TxnState.TRANSACTION_ABORTED]: [TxnState.STARTING_TRANSACTION, TxnState.NO_TRANSACTION], + [TxnState.TRANSACTION_COMMITTED_EMPTY]: [ + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.NO_TRANSACTION + ] +}; + +const ACTIVE_STATES: Set = new Set([ + TxnState.STARTING_TRANSACTION, + TxnState.TRANSACTION_IN_PROGRESS +]); + +const COMMITTED_STATES: Set = new Set([ + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.TRANSACTION_ABORTED +]); + +/** + * Configuration options for a transaction. + * @public + */ +export interface TransactionOptions extends CommandOperationOptions { + // TODO(NODE-3344): These options use the proper class forms of these settings, it should accept the basic enum values too + /** A default read concern for commands in this transaction */ + readConcern?: ReadConcern; + /** A default writeConcern for commands in this transaction */ + writeConcern?: WriteConcern; + /** A default read preference for commands in this transaction */ + readPreference?: ReadPreference; + + maxCommitTimeMS?: number; +} + +/** + * @public + * A class maintaining state related to a server transaction. Internal Only + */ +export class Transaction { + /** @internal */ + state: TxnState; + options: TransactionOptions; + /** @internal */ + _pinnedServer?: Server; + /** @internal */ + _recoveryToken?: Document; + + /** Create a transaction @internal */ + constructor(options?: TransactionOptions) { + options = options ?? {}; + this.state = TxnState.NO_TRANSACTION; + this.options = {}; + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + if (writeConcern.w === 0) { + throw new MongoTransactionError('Transactions do not support unacknowledged write concern'); + } + + this.options.writeConcern = writeConcern; + } + + if (options.readConcern) { + this.options.readConcern = ReadConcern.fromOptions(options); + } + + if (options.readPreference) { + this.options.readPreference = ReadPreference.fromOptions(options); + } + + if (options.maxCommitTimeMS) { + this.options.maxTimeMS = options.maxCommitTimeMS; + } + + // TODO: This isn't technically necessary + this._pinnedServer = undefined; + this._recoveryToken = undefined; + } + + /** @internal */ + get server(): Server | undefined { + return this._pinnedServer; + } + + get recoveryToken(): Document | undefined { + return this._recoveryToken; + } + + get isPinned(): boolean { + return !!this.server; + } + + /** @returns Whether the transaction has started */ + get isStarting(): boolean { + return this.state === TxnState.STARTING_TRANSACTION; + } + + /** + * @returns Whether this session is presently in a transaction + */ + get isActive(): boolean { + return ACTIVE_STATES.has(this.state); + } + + get isCommitted(): boolean { + return COMMITTED_STATES.has(this.state); + } + /** + * Transition the transaction in the state machine + * @internal + * @param nextState - The new state to transition to + */ + transition(nextState: TxnState): void { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.includes(nextState)) { + this.state = nextState; + if ( + this.state === TxnState.NO_TRANSACTION || + this.state === TxnState.STARTING_TRANSACTION || + this.state === TxnState.TRANSACTION_ABORTED + ) { + this.unpinServer(); + } + return; + } + + throw new MongoRuntimeError( + `Attempted illegal state transition from [${this.state}] to [${nextState}]` + ); + } + + /** @internal */ + pinServer(server: Server): void { + if (this.isActive) { + this._pinnedServer = server; + } + } + + /** @internal */ + unpinServer(): void { + this._pinnedServer = undefined; + } +} + +export function isTransactionCommand(command: Document): boolean { + return !!(command.commitTransaction || command.abortTransaction); +} diff --git a/node_modules/mongodb/src/utils.ts b/node_modules/mongodb/src/utils.ts new file mode 100644 index 0000000..db681d1 --- /dev/null +++ b/node_modules/mongodb/src/utils.ts @@ -0,0 +1,1440 @@ +import * as os from 'os'; +import * as crypto from 'crypto'; +import { PromiseProvider } from './promise_provider'; +import { + AnyError, + MongoParseError, + MongoRuntimeError, + MongoCompatibilityError, + MongoNotConnectedError, + MongoInvalidArgumentError, + MongoExpiredSessionError +} from './error'; +import { WriteConcern, WriteConcernOptions, W } from './write_concern'; +import type { Server } from './sdam/server'; +import type { Topology } from './sdam/topology'; +import { ServerType } from './sdam/common'; +import type { Db } from './db'; +import type { Collection } from './collection'; +import type { OperationOptions, Hint } from './operations/operation'; +import type { ClientSession } from './sessions'; +import { ReadConcern } from './read_concern'; +import type { Connection } from './cmap/connection'; +import { Document, ObjectId, resolveBSONOptions } from './bson'; +import type { IndexSpecification, IndexDirection } from './operations/indexes'; +import type { Explain } from './explain'; +import type { MongoClient } from './mongo_client'; +import type { CommandOperationOptions, OperationParent } from './operations/command'; +import { ReadPreference } from './read_preference'; +import { URL } from 'url'; +import { MAX_SUPPORTED_WIRE_VERSION } from './cmap/wire_protocol/constants'; + +/** + * MongoDB Driver style callback + * @public + */ +export type Callback = (error?: AnyError, result?: T) => void; +/** @public */ +export type CallbackWithType = (error?: E, result?: T0) => void; + +export const MAX_JS_INT = Number.MAX_SAFE_INTEGER + 1; + +export type AnyOptions = Document; + +/** + * Add a readonly enumerable property. + * @internal + */ +export function getSingleProperty( + obj: AnyOptions, + name: string | number | symbol, + value: unknown +): void { + Object.defineProperty(obj, name, { + enumerable: true, + get() { + return value; + } + }); +} + +/** + * Throws if collectionName is not a valid mongodb collection namespace. + * @internal + */ +export function checkCollectionName(collectionName: string): void { + if ('string' !== typeof collectionName) { + throw new MongoInvalidArgumentError('Collection name must be a String'); + } + + if (!collectionName || collectionName.indexOf('..') !== -1) { + throw new MongoInvalidArgumentError('Collection names cannot be empty'); + } + + if ( + collectionName.indexOf('$') !== -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null + ) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new MongoInvalidArgumentError("Collection names must not contain '$'"); + } + + if (collectionName.match(/^\.|\.$/) != null) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new MongoInvalidArgumentError("Collection names must not start or end with '.'"); + } + + // Validate that we are not passing 0x00 in the collection name + if (collectionName.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new MongoInvalidArgumentError('Collection names cannot contain a null character'); + } +} + +/** + * Ensure Hint field is in a shape we expect: + * - object of index names mapping to 1 or -1 + * - just an index name + * @internal + */ +export function normalizeHintField(hint?: Hint): Hint | undefined { + let finalHint = undefined; + + if (typeof hint === 'string') { + finalHint = hint; + } else if (Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(param => { + finalHint[param] = 1; + }); + } else if (hint != null && typeof hint === 'object') { + finalHint = {} as Document; + for (const name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +} + +interface IndexOptions { + name: string; + keys?: string[]; + fieldHash: Document; +} + +/** + * Create an index specifier based on + * @internal + */ +export function parseIndexOptions(indexSpec: IndexSpecification): IndexOptions { + const fieldHash: { [key: string]: IndexDirection } = {}; + const indexes = []; + let keys; + + // Get all the fields accordingly + if ('string' === typeof indexSpec) { + // 'type' + indexes.push(indexSpec + '_' + 1); + fieldHash[indexSpec] = 1; + } else if (Array.isArray(indexSpec)) { + indexSpec.forEach((f: any) => { + if ('string' === typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } else if (Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } else if (isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(k => { + indexes.push(k + '_' + (f as AnyOptions)[k]); + fieldHash[k] = (f as AnyOptions)[k]; + }); + } else { + // undefined (ignore) + } + }); + } else if (isObject(indexSpec)) { + // {location:'2d', type:1} + keys = Object.keys(indexSpec); + Object.entries(indexSpec).forEach(([key, value]) => { + indexes.push(key + '_' + value); + fieldHash[key] = value; + }); + } + + return { + name: indexes.join('_'), + keys: keys, + fieldHash: fieldHash + }; +} + +/** + * Checks if arg is an Object: + * - **NOTE**: the check is based on the `[Symbol.toStringTag]() === 'Object'` + * @internal + */ +// eslint-disable-next-line @typescript-eslint/ban-types +export function isObject(arg: unknown): arg is object { + return '[object Object]' === Object.prototype.toString.call(arg); +} + +/** @internal */ +export function decorateCommand(command: Document, options: Document, exclude: string[]): Document { + for (const name in options) { + if (!exclude.includes(name)) { + command[name] = options[name]; + } + } + + return command; +} + +/** @internal */ +export function mergeOptions(target: T, source: S): T & S { + return { ...target, ...source }; +} + +/** @internal */ +export function filterOptions(options: AnyOptions, names: string[]): AnyOptions { + const filterOptions: AnyOptions = {}; + + for (const name in options) { + if (names.includes(name)) { + filterOptions[name] = options[name]; + } + } + + // Filtered options + return filterOptions; +} + +/** + * Executes the given operation with provided arguments. + * + * @remarks + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @internal + * + * @param topology - The topology to execute this operation on + * @param operation - The operation to execute + * @param args - Arguments to apply the provided operation + * @param options - Options that modify the behavior of the method + */ +export function executeLegacyOperation( + topology: Topology, + operation: (...args: any[]) => void | Promise, + args: any[], + options?: AnyOptions +): void | Promise { + const Promise = PromiseProvider.get(); + + if (!Array.isArray(args)) { + // TODO(NODE-3483) + throw new MongoRuntimeError('This method requires an array of arguments to apply'); + } + + options = options ?? {}; + + let callback = args[args.length - 1]; + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session: ClientSession; + let opOptions: any; + let owner: any; + if (!options.skipSessions && topology.hasSessionSupport()) { + opOptions = args[args.length - 2]; + if (opOptions == null || opOptions.session == null) { + owner = Symbol(); + session = topology.startSession({ owner }); + const optionsIndex = args.length - 2; + args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); + } else if (opOptions.session && opOptions.session.hasEnded) { + throw new MongoExpiredSessionError(); + } + } + + function makeExecuteCallback( + resolve: (value?: Document) => void, + reject: (reason?: AnyError) => void + ) { + return function (err?: AnyError, result?: any) { + if (session && session.owner === owner && !options?.returnsCursor) { + session.endSession(() => { + delete opOptions.session; + if (err) return reject(err); + resolve(result); + }); + } else { + if (err) return reject(err); + resolve(result); + } + }; + } + + // Execute using callback + if (typeof callback === 'function') { + callback = args.pop(); + const handler = makeExecuteCallback( + result => callback(undefined, result), + err => callback(err, null) + ); + args.push(handler); + + try { + return operation(...args); + } catch (e) { + handler(e); + throw e; + } + } + + // Return a Promise + if (args[args.length - 1] != null) { + // TODO(NODE-3483) + throw new MongoRuntimeError('Final argument to `executeLegacyOperation` must be a callback'); + } + + return new Promise((resolve, reject) => { + const handler = makeExecuteCallback(resolve, reject); + args[args.length - 1] = handler; + + try { + return operation(...args); + } catch (e) { + handler(e); + } + }); +} + +interface HasRetryableWrites { + retryWrites?: boolean; +} +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * @internal + * + * @param target - The target command to which we will apply retryWrites. + * @param db - The database from which we can inherit a retryWrites value. + */ +export function applyRetryableWrites(target: T, db?: Db): T { + if (db && db.s.options?.retryWrites) { + target.retryWrites = true; + } + + return target; +} + +interface HasWriteConcern { + writeConcern?: WriteConcernOptions | WriteConcern | W; +} +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * @internal + * + * @param target - the target command we will be applying the write concern to + * @param sources - sources where we can inherit default write concerns from + * @param options - optional settings passed into a command for write concern overrides + */ +export function applyWriteConcern( + target: T, + sources: { db?: Db; collection?: Collection }, + options?: OperationOptions & WriteConcernOptions +): T { + options = options ?? {}; + const db = sources.db; + const coll = sources.collection; + + if (options.session && options.session.inTransaction()) { + // writeConcern is not allowed within a multi-statement transaction + if (target.writeConcern) { + delete target.writeConcern; + } + + return target; + } + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + return Object.assign(target, { writeConcern }); + } + + if (coll && coll.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); + } + + if (db && db.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); + } + + return target; +} + +/** + * Checks if a given value is a Promise + * + * @typeParam T - The result type of maybePromise + * @param maybePromise - An object that could be a promise + * @returns true if the provided value is a Promise + */ +export function isPromiseLike( + maybePromise?: PromiseLike | void +): maybePromise is Promise { + return !!maybePromise && typeof maybePromise.then === 'function'; +} + +/** + * Applies collation to a given command. + * @internal + * + * @param command - the command on which to apply collation + * @param target - target of command + * @param options - options containing collation settings + */ +export function decorateWithCollation( + command: Document, + target: MongoClient | Db | Collection, + options: AnyOptions +): void { + const capabilities = getTopology(target).capabilities; + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; + } else { + throw new MongoCompatibilityError(`Current topology does not support collation`); + } + } +} + +/** + * Applies a read concern to a given command. + * @internal + * + * @param command - the command on which to apply the read concern + * @param coll - the parent collection of the operation calling this method + */ +export function decorateWithReadConcern( + command: Document, + coll: { s: { readConcern?: ReadConcern } }, + options?: OperationOptions +): void { + if (options && options.session && options.session.inTransaction()) { + return; + } + const readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern: readConcern }); + } +} + +/** + * Applies an explain to a given command. + * @internal + * + * @param command - the command on which to apply the explain + * @param options - the options containing the explain verbosity + */ +export function decorateWithExplain(command: Document, explain: Explain): Document { + if (command.explain) { + return command; + } + + return { explain: command, verbosity: explain.verbosity }; +} + +/** + * A helper function to get the topology from a given provider. Throws + * if the topology cannot be found. + * @internal + */ +export function getTopology(provider: MongoClient | Db | Collection): Topology { + if (`topology` in provider && provider.topology) { + return provider.topology; + } else if ('client' in provider.s && provider.s.client.topology) { + return provider.s.client.topology; + } else if ('db' in provider.s && provider.s.db.s.client.topology) { + return provider.s.db.s.client.topology; + } + + throw new MongoNotConnectedError('MongoClient must be connected to perform this operation'); +} + +/** + * Default message handler for generating deprecation warnings. + * @internal + * + * @param name - function name + * @param option - option name + * @returns warning message + */ +export function defaultMsgHandler(name: string, option: string): string { + return `${name} option [${option}] is deprecated and will be removed in a later version.`; +} + +export interface DeprecateOptionsConfig { + /** function name */ + name: string; + /** options to deprecate */ + deprecatedOptions: string[]; + /** index of options object in function arguments array */ + optionsIndex: number; + /** optional custom message handler to generate warnings */ + msgHandler?(name: string, option: string): string; +} + +/** + * Deprecates a given function's options. + * @internal + * + * @param this - the bound class if this is a method + * @param config - configuration for deprecation + * @param fn - the target function of deprecation + * @returns modified function that warns once per deprecated option, and executes original function + */ +export function deprecateOptions( + this: unknown, + config: DeprecateOptionsConfig, + fn: (...args: any[]) => any +): any { + if ((process as any).noDeprecation === true) { + return fn; + } + + const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; + + const optionsWarned = new Set(); + function deprecated(this: any, ...args: any[]) { + const options = args[config.optionsIndex] as AnyOptions; + + // ensure options is a valid, non-empty object, otherwise short-circuit + if (!isObject(options) || Object.keys(options).length === 0) { + return fn.bind(this)(...args); // call the function, no change + } + + // interrupt the function call with a warning + for (const deprecatedOption of config.deprecatedOptions) { + if (deprecatedOption in options && !optionsWarned.has(deprecatedOption)) { + optionsWarned.add(deprecatedOption); + const msg = msgHandler(config.name, deprecatedOption); + emitWarning(msg); + if (this && 'getLogger' in this) { + const logger = this.getLogger(); + if (logger) { + logger.warn(msg); + } + } + } + } + + return fn.bind(this)(...args); + } + + // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 + // The wrapper will keep the same prototype as fn to maintain prototype chain + Object.setPrototypeOf(deprecated, fn); + if (fn.prototype) { + // Setting this (rather than using Object.setPrototype, as above) ensures + // that calling the unwrapped constructor gives an instanceof the wrapped + // constructor. + deprecated.prototype = fn.prototype; + } + + return deprecated; +} + +/** @internal */ +export function ns(ns: string): MongoDBNamespace { + return MongoDBNamespace.fromString(ns); +} + +/** @public */ +export class MongoDBNamespace { + db: string; + collection?: string; + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(db: string, collection?: string) { + this.db = db; + this.collection = collection; + } + + toString(): string { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + + withCollection(collection: string): MongoDBNamespace { + return new MongoDBNamespace(this.db, collection); + } + + static fromString(namespace?: string): MongoDBNamespace { + if (!namespace) { + // TODO(NODE-3483): Replace with MongoNamespaceError + throw new MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); + } + + const [db, ...collection] = namespace.split('.'); + return new MongoDBNamespace(db, collection.join('.')); + } +} + +/** @internal */ +export function* makeCounter(seed = 0): Generator { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} + +/** + * Helper function for either accepting a callback, or returning a promise + * @internal + * + * @param callback - The last function argument in exposed method, controls if a Promise is returned + * @param wrapper - A function that wraps the callback + * @returns Returns void if a callback is supplied, else returns a Promise. + */ +export function maybePromise( + callback: Callback | undefined, + wrapper: (fn: Callback) => void +): Promise | void { + const Promise = PromiseProvider.get(); + let result: Promise | void; + if (typeof callback !== 'function') { + result = new Promise((resolve, reject) => { + callback = (err, res) => { + if (err) return reject(err); + resolve(res); + }; + }); + } + + wrapper((err, res) => { + if (err != null) { + try { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + callback!(err); + } catch (error) { + process.nextTick(() => { + throw error; + }); + } + + return; + } + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + callback!(err, res); + }); + + return result; +} + +/** @internal */ +export function databaseNamespace(ns: string): string { + return ns.split('.')[0]; +} + +/** @internal */ +export function collectionNamespace(ns: string): string { + return ns.split('.').slice(1).join('.'); +} + +/** + * Synchronously Generate a UUIDv4 + * @internal + */ +export function uuidV4(): Buffer { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +} + +/** + * A helper function for determining `maxWireVersion` between legacy and new topology instances + * @internal + */ +export function maxWireVersion(topologyOrServer?: Connection | Topology | Server): number { + if (topologyOrServer) { + if (topologyOrServer.loadBalanced) { + // Since we do not have a monitor, we assume the load balanced server is always + // pointed at the latest mongodb version. There is a risk that for on-prem + // deployments that don't upgrade immediately that this could alert to the + // application that a feature is avaiable that is actually not. + return MAX_SUPPORTED_WIRE_VERSION; + } + if (topologyOrServer.ismaster) { + return topologyOrServer.ismaster.maxWireVersion; + } + + if ('lastIsMaster' in topologyOrServer && typeof topologyOrServer.lastIsMaster === 'function') { + const lastIsMaster = topologyOrServer.lastIsMaster(); + if (lastIsMaster) { + return lastIsMaster.maxWireVersion; + } + } + + if ( + topologyOrServer.description && + 'maxWireVersion' in topologyOrServer.description && + topologyOrServer.description.maxWireVersion != null + ) { + return topologyOrServer.description.maxWireVersion; + } + } + + return 0; +} + +/** + * Checks that collation is supported by server. + * @internal + * + * @param server - to check against + * @param cmd - object where collation may be specified + */ +export function collationNotSupported(server: Server, cmd: Document): boolean { + return cmd && cmd.collation && maxWireVersion(server) < 5; +} + +/** + * Applies the function `eachFn` to each item in `arr`, in parallel. + * @internal + * + * @param arr - An array of items to asynchronously iterate over + * @param eachFn - A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. + * @param callback - The callback called after every item has been iterated + */ +export function eachAsync( + arr: T[], + eachFn: (item: T, callback: (err?: AnyError) => void) => void, + callback: Callback +): void { + arr = arr || []; + + let idx = 0; + let awaiting = 0; + for (idx = 0; idx < arr.length; ++idx) { + awaiting++; + eachFn(arr[idx], eachCallback); + } + + if (awaiting === 0) { + callback(); + return; + } + + function eachCallback(err?: AnyError) { + awaiting--; + if (err) { + callback(err); + return; + } + + if (idx === arr.length && awaiting <= 0) { + callback(); + } + } +} + +/** @internal */ +export function eachAsyncSeries( + arr: T[], + eachFn: (item: T, callback: (err?: AnyError) => void) => void, + callback: Callback +): void { + arr = arr || []; + + let idx = 0; + let awaiting = arr.length; + if (awaiting === 0) { + callback(); + return; + } + + function eachCallback(err?: AnyError) { + idx++; + awaiting--; + if (err) { + callback(err); + return; + } + + if (idx === arr.length && awaiting <= 0) { + callback(); + return; + } + + eachFn(arr[idx], eachCallback); + } + + eachFn(arr[idx], eachCallback); +} + +/** @internal */ +export function arrayStrictEqual(arr: unknown[], arr2: unknown[]): boolean { + if (!Array.isArray(arr) || !Array.isArray(arr2)) { + return false; + } + + return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); +} + +/** @internal */ +export function errorStrictEqual(lhs?: AnyError, rhs?: AnyError): boolean { + if (lhs === rhs) { + return true; + } + + if (!lhs || !rhs) { + return lhs === rhs; + } + + if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { + return false; + } + + if (lhs.constructor.name !== rhs.constructor.name) { + return false; + } + + if (lhs.message !== rhs.message) { + return false; + } + + return true; +} + +interface StateTable { + [key: string]: string[]; +} +interface ObjectWithState { + s: { state: string }; + emit(event: 'stateChanged', state: string, newState: string): void; +} +interface StateTransitionFunction { + (target: ObjectWithState, newState: string): void; +} + +/** @public */ +export type EventEmitterWithState = { + /** @internal */ + stateChanged(previous: string, current: string): void; +}; + +/** @internal */ +export function makeStateMachine(stateTable: StateTable): StateTransitionFunction { + return function stateTransition(target, newState) { + const legalStates = stateTable[target.s.state]; + if (legalStates && legalStates.indexOf(newState) < 0) { + throw new MongoRuntimeError( + `illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]` + ); + } + + target.emit('stateChanged', target.s.state, newState); + target.s.state = newState; + }; +} + +/** @public */ +export interface ClientMetadata { + driver: { + name: string; + version: string; + }; + os: { + type: string; + name: NodeJS.Platform; + architecture: string; + version: string; + }; + platform: string; + version?: string; + application?: { + name: string; + }; +} + +/** @public */ +export interface ClientMetadataOptions { + driverInfo?: { + name?: string; + version?: string; + platform?: string; + }; + appName?: string; +} + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const NODE_DRIVER_VERSION = require('../package.json').version; + +export function makeClientMetadata(options?: ClientMetadataOptions): ClientMetadata { + options = options ?? {}; + + const metadata: ClientMetadata = { + driver: { + name: 'nodejs', + version: NODE_DRIVER_VERSION + }, + os: { + type: os.type(), + name: process.platform, + architecture: process.arch, + version: os.release() + }, + platform: `Node.js ${process.version}, ${os.endianness()} (unified)` + }; + + // support optionally provided wrapping driver info + if (options.driverInfo) { + if (options.driverInfo.name) { + metadata.driver.name = `${metadata.driver.name}|${options.driverInfo.name}`; + } + + if (options.driverInfo.version) { + metadata.version = `${metadata.driver.version}|${options.driverInfo.version}`; + } + + if (options.driverInfo.platform) { + metadata.platform = `${metadata.platform}|${options.driverInfo.platform}`; + } + } + + if (options.appName) { + // MongoDB requires the appName not exceed a byte length of 128 + const buffer = Buffer.from(options.appName); + metadata.application = { + name: buffer.byteLength > 128 ? buffer.slice(0, 128).toString('utf8') : options.appName + }; + } + + return metadata; +} + +/** @internal */ +export function now(): number { + const hrtime = process.hrtime(); + return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1000000); +} + +/** @internal */ +export function calculateDurationInMs(started: number): number { + if (typeof started !== 'number') { + throw new MongoInvalidArgumentError('Numeric value required to calculate duration'); + } + + const elapsed = now() - started; + return elapsed < 0 ? 0 : elapsed; +} + +export interface InterruptibleAsyncIntervalOptions { + /** The interval to execute a method on */ + interval: number; + /** A minimum interval that must elapse before the method is called */ + minInterval: number; + /** Whether the method should be called immediately when the interval is started */ + immediate: boolean; + + /** + * Only used for testing unreliable timer environments + * @internal + */ + clock: () => number; +} + +/** @internal */ +export interface InterruptibleAsyncInterval { + wake(): void; + stop(): void; +} + +/** + * Creates an interval timer which is able to be woken up sooner than + * the interval. The timer will also debounce multiple calls to wake + * ensuring that the function is only ever called once within a minimum + * interval window. + * @internal + * + * @param fn - An async function to run on an interval, must accept a `callback` as its only parameter + */ +export function makeInterruptibleAsyncInterval( + fn: (callback: Callback) => void, + options?: Partial +): InterruptibleAsyncInterval { + let timerId: NodeJS.Timeout | undefined; + let lastCallTime: number; + let lastWakeTime: number; + let stopped = false; + + options = options ?? {}; + const interval = options.interval || 1000; + const minInterval = options.minInterval || 500; + const immediate = typeof options.immediate === 'boolean' ? options.immediate : false; + const clock = typeof options.clock === 'function' ? options.clock : now; + + function wake() { + const currentTime = clock(); + const timeSinceLastWake = currentTime - lastWakeTime; + const timeSinceLastCall = currentTime - lastCallTime; + const timeUntilNextCall = interval - timeSinceLastCall; + lastWakeTime = currentTime; + + // For the streaming protocol: there is nothing obviously stopping this + // interval from being woken up again while we are waiting "infinitely" + // for `fn` to be called again`. Since the function effectively + // never completes, the `timeUntilNextCall` will continue to grow + // negatively unbounded, so it will never trigger a reschedule here. + + // debounce multiple calls to wake within the `minInterval` + if (timeSinceLastWake < minInterval) { + return; + } + + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeUntilNextCall > minInterval) { + reschedule(minInterval); + } + + // This is possible in virtualized environments like AWS Lambda where our + // clock is unreliable. In these cases the timer is "running" but never + // actually completes, so we want to execute immediately and then attempt + // to reschedule. + if (timeUntilNextCall < 0) { + executeAndReschedule(); + } + } + + function stop() { + stopped = true; + if (timerId) { + clearTimeout(timerId); + timerId = undefined; + } + + lastCallTime = 0; + lastWakeTime = 0; + } + + function reschedule(ms?: number) { + if (stopped) return; + if (timerId) { + clearTimeout(timerId); + } + + timerId = setTimeout(executeAndReschedule, ms || interval); + } + + function executeAndReschedule() { + lastWakeTime = 0; + lastCallTime = clock(); + + fn(err => { + if (err) throw err; + reschedule(interval); + }); + } + + if (immediate) { + executeAndReschedule(); + } else { + lastCallTime = clock(); + reschedule(undefined); + } + + return { wake, stop }; +} + +/** @internal */ +export function hasAtomicOperators(doc: Document | Document[]): boolean { + if (Array.isArray(doc)) { + for (const document of doc) { + if (hasAtomicOperators(document)) { + return true; + } + } + return false; + } + + const keys = Object.keys(doc); + return keys.length > 0 && keys[0][0] === '$'; +} + +/** + * Merge inherited properties from parent into options, prioritizing values from options, + * then values from parent. + * @internal + */ +export function resolveOptions( + parent: OperationParent | undefined, + options?: T +): T { + const result: T = Object.assign({}, options, resolveBSONOptions(options, parent)); + + // Users cannot pass a readConcern/writeConcern to operations in a transaction + const session = options?.session; + if (!session?.inTransaction()) { + const readConcern = ReadConcern.fromOptions(options) ?? parent?.readConcern; + if (readConcern) { + result.readConcern = readConcern; + } + + const writeConcern = WriteConcern.fromOptions(options) ?? parent?.writeConcern; + if (writeConcern) { + result.writeConcern = writeConcern; + } + } + + const readPreference = ReadPreference.fromOptions(options) ?? parent?.readPreference; + if (readPreference) { + result.readPreference = readPreference; + } + + return result; +} + +export function isSuperset(set: Set | any[], subset: Set | any[]): boolean { + set = Array.isArray(set) ? new Set(set) : set; + subset = Array.isArray(subset) ? new Set(subset) : subset; + for (const elem of subset) { + if (!set.has(elem)) { + return false; + } + } + return true; +} + +export function setDifference(setA: Iterable, setB: Iterable): Set { + const difference = new Set(setA); + for (const elem of setB) { + difference.delete(elem); + } + return difference; +} + +export function isRecord( + value: unknown, + requiredKeys: T +): value is Record; +export function isRecord(value: unknown): value is Record; +export function isRecord( + value: unknown, + requiredKeys: string[] | undefined = undefined +): value is Record { + const toString = Object.prototype.toString; + const hasOwnProperty = Object.prototype.hasOwnProperty; + const isObject = (v: unknown) => toString.call(v) === '[object Object]'; + if (!isObject(value)) { + return false; + } + + const ctor = (value as any).constructor; + if (ctor && ctor.prototype) { + if (!isObject(ctor.prototype)) { + return false; + } + + // Check to see if some method exists from the Object exists + if (!hasOwnProperty.call(ctor.prototype, 'isPrototypeOf')) { + return false; + } + } + + if (requiredKeys) { + const keys = Object.keys(value as Record); + return isSuperset(keys, requiredKeys); + } + + return true; +} + +/** + * Make a deep copy of an object + * + * NOTE: This is not meant to be the perfect implementation of a deep copy, + * but instead something that is good enough for the purposes of + * command monitoring. + */ +export function deepCopy(value: T): T { + if (value == null) { + return value; + } else if (Array.isArray(value)) { + return value.map(item => deepCopy(item)) as T; + } else if (isRecord(value)) { + const res = {} as any; + for (const key in value) { + res[key] = deepCopy(value[key]); + } + return res; + } + + const ctor = (value as any).constructor; + if (ctor) { + switch (ctor.name.toLowerCase()) { + case 'date': + return new ctor(Number(value)); + case 'map': + return new Map(value as any) as T; + case 'set': + return new Set(value as any) as T; + case 'buffer': + return Buffer.from(value as Buffer) as T; + } + } + + return value; +} + +/** @internal */ +const kBuffers = Symbol('buffers'); +/** @internal */ +const kLength = Symbol('length'); + +/** + * A pool of Buffers which allow you to read them as if they were one + * @internal + */ +export class BufferPool { + [kBuffers]: Buffer[]; + [kLength]: number; + + constructor() { + this[kBuffers] = []; + this[kLength] = 0; + } + + get length(): number { + return this[kLength]; + } + + /** Adds a buffer to the internal buffer pool list */ + append(buffer: Buffer): void { + this[kBuffers].push(buffer); + this[kLength] += buffer.length; + } + + /** Returns the requested number of bytes without consuming them */ + peek(size: number): Buffer { + return this.read(size, false); + } + + /** Reads the requested number of bytes, optionally consuming them */ + read(size: number, consume = true): Buffer { + if (typeof size !== 'number' || size < 0) { + throw new MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + } + + if (size > this[kLength]) { + return Buffer.alloc(0); + } + + let result: Buffer; + + // read the whole buffer + if (size === this.length) { + result = Buffer.concat(this[kBuffers]); + + if (consume) { + this[kBuffers] = []; + this[kLength] = 0; + } + } + + // size is within first buffer, no need to concat + else if (size <= this[kBuffers][0].length) { + result = this[kBuffers][0].slice(0, size); + if (consume) { + this[kBuffers][0] = this[kBuffers][0].slice(size); + this[kLength] -= size; + } + } + + // size is beyond first buffer, need to track and copy + else { + result = Buffer.allocUnsafe(size); + + let idx; + let offset = 0; + let bytesToCopy = size; + for (idx = 0; idx < this[kBuffers].length; ++idx) { + let bytesCopied; + if (bytesToCopy > this[kBuffers][idx].length) { + bytesCopied = this[kBuffers][idx].copy(result, offset, 0); + offset += bytesCopied; + } else { + bytesCopied = this[kBuffers][idx].copy(result, offset, 0, bytesToCopy); + if (consume) { + this[kBuffers][idx] = this[kBuffers][idx].slice(bytesCopied); + } + offset += bytesCopied; + break; + } + + bytesToCopy -= bytesCopied; + } + + // compact the internal buffer array + if (consume) { + this[kBuffers] = this[kBuffers].slice(idx); + this[kLength] -= size; + } + } + + return result; + } +} + +/** @public */ +export class HostAddress { + host; + port; + // Driver only works with unix socket path to connect + // SDAM operates only on tcp addresses + socketPath; + isIPv6; + + constructor(hostString: string) { + const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts + const { hostname, port } = new URL(`mongodb://${escapedHost}`); + + if (hostname.endsWith('.sock')) { + // heuristically determine if we're working with a domain socket + this.socketPath = decodeURIComponent(hostname); + } else if (typeof hostname === 'string') { + this.isIPv6 = false; + + let normalized = decodeURIComponent(hostname).toLowerCase(); + if (normalized.startsWith('[') && normalized.endsWith(']')) { + this.isIPv6 = true; + normalized = normalized.substring(1, hostname.length - 1); + } + + this.host = normalized.toLowerCase(); + + if (typeof port === 'number') { + this.port = port; + } else if (typeof port === 'string' && port !== '') { + this.port = Number.parseInt(port, 10); + } else { + this.port = 27017; + } + + if (this.port === 0) { + throw new MongoParseError('Invalid port (zero) with hostname'); + } + } else { + throw new MongoInvalidArgumentError('Either socketPath or host must be defined.'); + } + Object.freeze(this); + } + + /** + * @param ipv6Brackets - optionally request ipv6 bracket notation required for connection strings + */ + toString(ipv6Brackets = false): string { + if (typeof this.host === 'string') { + if (this.isIPv6 && ipv6Brackets) { + return `[${this.host}]:${this.port}`; + } + return `${this.host}:${this.port}`; + } + return `${this.socketPath}`; + } + + static fromString(s: string): HostAddress { + return new HostAddress(s); + } +} + +export const DEFAULT_PK_FACTORY = { + // We prefer not to rely on ObjectId having a createPk method + createPk(): ObjectId { + return new ObjectId(); + } +}; + +/** + * When the driver used emitWarning the code will be equal to this. + * @public + * + * @example + * ```js + * process.on('warning', (warning) => { + * if (warning.code === MONGODB_WARNING_CODE) console.error('Ah an important warning! :)') + * }) + * ``` + */ +export const MONGODB_WARNING_CODE = 'MONGODB DRIVER' as const; + +/** @internal */ +export function emitWarning(message: string): void { + return process.emitWarning(message, { code: MONGODB_WARNING_CODE } as any); +} + +const emittedWarnings = new Set(); +/** + * Will emit a warning once for the duration of the application. + * Uses the message to identify if it has already been emitted + * so using string interpolation can cause multiple emits + * @internal + */ +export function emitWarningOnce(message: string): void { + if (!emittedWarnings.has(message)) { + emittedWarnings.add(message); + return emitWarning(message); + } +} + +/** + * Takes a JS object and joins the values into a string separated by ', ' + */ +export function enumToString(en: Record): string { + return Object.values(en).join(', '); +} + +/** + * Determine if a server supports retryable writes. + * + * @internal + */ +export function supportsRetryableWrites(server: Server): boolean { + return ( + !!server.loadBalanced || + (server.description.maxWireVersion >= 6 && + !!server.description.logicalSessionTimeoutMinutes && + server.description.type !== ServerType.Standalone) + ); +} + +export function parsePackageVersion({ version }: { version: string }): { + major: number; + minor: number; + patch: number; +} { + const [major, minor, patch] = version.split('.').map((n: string) => Number.parseInt(n, 10)); + return { major, minor, patch }; +} diff --git a/node_modules/mongodb/src/write_concern.ts b/node_modules/mongodb/src/write_concern.ts new file mode 100644 index 0000000..ebc77eb --- /dev/null +++ b/node_modules/mongodb/src/write_concern.ts @@ -0,0 +1,114 @@ +/** @public */ +export type W = number | 'majority'; + +/** @public */ +export interface WriteConcernOptions { + /** Write Concern as an object */ + writeConcern?: WriteConcern | WriteConcernSettings; +} + +/** @public */ +export interface WriteConcernSettings { + /** The write concern */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + + // legacy options + /** The journal write concern */ + j?: boolean; + /** The write concern timeout */ + wtimeout?: number; + /** The file sync write concern */ + fsync?: boolean | 1; +} + +export const WRITE_CONCERN_KEYS = ['w', 'wtimeout', 'j', 'journal', 'fsync']; + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @public + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ +export class WriteConcern { + /** request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. */ + w?: W; + /** specify a time limit to prevent write operations from blocking indefinitely */ + wtimeout?: number; + /** request acknowledgment that the write operation has been written to the on-disk journal */ + j?: boolean; + /** equivalent to the j option */ + fsync?: boolean | 1; + + /** + * Constructs a WriteConcern from the write concern properties. + * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. + * @param wtimeout - specify a time limit to prevent write operations from blocking indefinitely + * @param j - request acknowledgment that the write operation has been written to the on-disk journal + * @param fsync - equivalent to the j option + */ + constructor(w?: W, wtimeout?: number, j?: boolean, fsync?: boolean | 1) { + if (w != null) { + if (!Number.isNaN(Number(w))) { + this.w = Number(w); + } else { + this.w = w; + } + } + if (wtimeout != null) { + this.wtimeout = wtimeout; + } + if (j != null) { + this.j = j; + } + if (fsync != null) { + this.fsync = fsync; + } + } + + /** Construct a WriteConcern given an options object. */ + static fromOptions( + options?: WriteConcernOptions | WriteConcern | W, + inherit?: WriteConcernOptions | WriteConcern + ): WriteConcern | undefined { + if (options == null) return undefined; + inherit = inherit ?? {}; + let opts: WriteConcernSettings | WriteConcern | undefined; + if (typeof options === 'string' || typeof options === 'number') { + opts = { w: options }; + } else if (options instanceof WriteConcern) { + opts = options; + } else { + opts = options.writeConcern; + } + const parentOpts: WriteConcern | WriteConcernSettings | undefined = + inherit instanceof WriteConcern ? inherit : inherit.writeConcern; + + const { + w = undefined, + wtimeout = undefined, + j = undefined, + fsync = undefined, + journal = undefined, + wtimeoutMS = undefined + } = { + ...parentOpts, + ...opts + }; + if ( + w != null || + wtimeout != null || + wtimeoutMS != null || + j != null || + journal != null || + fsync != null + ) { + return new WriteConcern(w, wtimeout ?? wtimeoutMS, j ?? journal, fsync); + } + return undefined; + } +} diff --git a/node_modules/mongoose/LICENSE.md b/node_modules/mongoose/LICENSE.md new file mode 100644 index 0000000..54b4a4c --- /dev/null +++ b/node_modules/mongoose/LICENSE.md @@ -0,0 +1,22 @@ +# MIT License + +Copyright (c) 2010-2013 LearnBoost +Copyright (c) 2013-2021 Automattic + +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/mongoose/README.md b/node_modules/mongoose/README.md new file mode 100644 index 0000000..90a788d --- /dev/null +++ b/node_modules/mongoose/README.md @@ -0,0 +1,366 @@ +# Mongoose + +Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks. + +[![Slack Status](http://slack.mongoosejs.io/badge.svg)](http://slack.mongoosejs.io) +[![Build Status](https://github.com/Automattic/mongoose/workflows/Test/badge.svg)](https://github.com/Automattic/mongoose) +[![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose) + +[![npm](https://nodei.co/npm/mongoose.png)](https://www.npmjs.com/package/mongoose) + +## Documentation + +The official documentation website is [mongoosejs.com](http://mongoosejs.com/). + +Mongoose 6.0.0 was released on August 24, 2021. You can find more details on [backwards breaking changes in 6.0.0 on our docs site](https://mongoosejs.com/docs/migrating_to_6.html). + +## Support + + - [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose) + - [Bug Reports](https://github.com/Automattic/mongoose/issues/) + - [Mongoose Slack Channel](http://slack.mongoosejs.io/) + - [Help Forum](http://groups.google.com/group/mongoose-orm) + - [MongoDB Support](https://docs.mongodb.org/manual/support/) + +## Plugins + +Check out the [plugins search site](http://plugins.mongoosejs.io/) to see hundreds of related modules from the community. Next, learn how to write your own plugin from the [docs](http://mongoosejs.com/docs/plugins.html) or [this blog post](http://thecodebarbarian.com/2015/03/06/guide-to-mongoose-plugins). + +## Contributors + +Pull requests are always welcome! Please base pull requests against the `master` +branch and follow the [contributing guide](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md). + +If your pull requests makes documentation changes, please do **not** +modify any `.html` files. The `.html` files are compiled code, so please make +your changes in `docs/*.pug`, `lib/*.js`, or `test/docs/*.js`. + +View all 400+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors). + +## Installation + +First install [Node.js](http://nodejs.org/) and [MongoDB](https://www.mongodb.org/downloads). Then: + +```sh +$ npm install mongoose +``` + +## Importing + +```javascript +// Using Node.js `require()` +const mongoose = require('mongoose'); + +// Using ES6 imports +import mongoose from 'mongoose'; +``` + +## Mongoose for Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of mongoose 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-mongoose?utm_source=npm-mongoose&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +## Overview + +### Connecting to MongoDB + +First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`. + +Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`. + +```js +await mongoose.connect('mongodb://localhost/my_database'); +``` + +Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`. + +**Note:** _If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed._ + +**Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc. + +### Defining a Model + +Models are defined through the `Schema` interface. + +```js +const Schema = mongoose.Schema; +const ObjectId = Schema.ObjectId; + +const BlogPost = new Schema({ + author: ObjectId, + title: String, + body: String, +  date: Date +}); +``` + +Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of: + +* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync) +* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default) +* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get) +* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set) +* [Indexes](http://mongoosejs.com/docs/guide.html#indexes) +* [Middleware](http://mongoosejs.com/docs/middleware.html) +* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition +* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition +* [Plugins](http://mongoosejs.com/docs/plugins.html) +* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html) + +The following example shows some of these features: + +```js +const Comment = new Schema({ + name: { type: String, default: 'hahaha' }, + age: { type: Number, min: 18, index: true }, + bio: { type: String, match: /[a-z]/ }, + date: { type: Date, default: Date.now }, + buff: Buffer +}); + +// a setter +Comment.path('name').set(function (v) { + return capitalize(v); +}); + +// middleware +Comment.pre('save', function (next) { + notify(this.get('email')); + next(); +}); +``` + +Take a look at the example in [`examples/schema/schema.js`](https://github.com/Automattic/mongoose/blob/master/examples/schema/schema.js) for an end-to-end example of a typical setup. + +### Accessing a Model + +Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function + +```js +const MyModel = mongoose.model('ModelName'); +``` + +Or just do it all at once + +```js +const MyModel = mongoose.model('ModelName', mySchema); +``` + +The first argument is the _singular_ name of the collection your model is for. **Mongoose automatically looks for the _plural_ version of your model name.** For example, if you use + +```js +const MyModel = mongoose.model('Ticket', mySchema); +``` + +Then Mongoose will create the model for your __tickets__ collection, not your __ticket__ collection. + +Once we have our model, we can then instantiate it, and save it: + +```js +const instance = new MyModel(); +instance.my.key = 'hello'; +instance.save(function (err) { + // +}); +``` + +Or we can find documents from the same collection + +```js +MyModel.find({}, function (err, docs) { + // docs.forEach +}); +``` + +You can also `findOne`, `findById`, `update`, etc. + +```js +const instance = await MyModel.findOne({ ... }); +console.log(instance.my.key); // 'hello' +``` + +For more details check out [the docs](http://mongoosejs.com/docs/queries.html). + +**Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created: + +```js +const conn = mongoose.createConnection('your connection string'); +const MyModel = conn.model('ModelName', schema); +const m = new MyModel; +m.save(); // works +``` + +vs + +```js +const conn = mongoose.createConnection('your connection string'); +const MyModel = mongoose.model('ModelName', schema); +const m = new MyModel; +m.save(); // does not work b/c the default connection object was never connected +``` + +### Embedded Documents + +In the first example snippet, we defined a key in the Schema that looks like: + +``` +comments: [Comment] +``` + +Where `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as: + +```js +// retrieve my model +const BlogPost = mongoose.model('BlogPost'); + +// create a blog post +const post = new BlogPost(); + +// create a comment +post.comments.push({ title: 'My comment' }); + +post.save(function (err) { + if (!err) console.log('Success!'); +}); +``` + +The same goes for removing them: + +```js +BlogPost.findById(myId, function (err, post) { + if (!err) { + post.comments[0].remove(); + post.save(function (err) { + // do something + }); + } +}); +``` + +Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the `save()` error callback, so error handling is a snap! + + +### Middleware + +See the [docs](http://mongoosejs.com/docs/middleware.html) page. + +#### Intercepting and mutating method arguments + +You can intercept method arguments via middleware. + +For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value: + +```js +schema.pre('set', function (next, path, val, typel) { + // `this` is the current Document + this.emit('set', path, val); + + // Pass control to the next pre + next(); +}); +``` + +Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`: + +```js +.pre(method, function firstPre (next, methodArg1, methodArg2) { + // Mutate methodArg1 + next("altered-" + methodArg1.toString(), methodArg2); +}); + +// pre declaration is chainable +.pre(method, function secondPre (next, methodArg1, methodArg2) { + console.log(methodArg1); + // => 'altered-originalValOfMethodArg1' + + console.log(methodArg2); + // => 'originalValOfMethodArg2' + + // Passing no arguments to `next` automatically passes along the current argument values + // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)` + // and also equivalent to, with the example method arg + // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')` + next(); +}); +``` + +#### Schema gotcha + +`type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation: + +```js +new Schema({ + broken: { type: Boolean }, + asset: { + name: String, + type: String // uh oh, it broke. asset will be interpreted as String + } +}); + +new Schema({ + works: { type: Boolean }, + asset: { + name: String, + type: { type: String } // works. asset is an object with a type property + } +}); +``` + +### Driver Access + +Mongoose is built on top of the [official MongoDB Node.js driver](https://github.com/mongodb/node-mongodb-native). Each mongoose model keeps a reference to a [native MongoDB driver collection](http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html). The collection object can be accessed using `YourModel.collection`. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one +notable exception that `YourModel.collection` still buffers +commands. As such, `YourModel.collection.find()` will **not** +return a cursor. + +## API Docs + +Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](https://github.com/tj/dox) +and [acquit](https://github.com/vkarpov15/acquit). + +## Related Projects + +#### MongoDB Runners + +- [run-rs](https://www.npmjs.com/package/run-rs) +- [mongodb-memory-server](https://www.npmjs.com/package/mongodb-memory-server) +- [mongodb-topology-manager](https://www.npmjs.com/package/mongodb-topology-manager) + +#### Unofficial CLIs + +- [mongoosejs-cli](https://www.npmjs.com/package/mongoosejs-cli) + +#### Data Seeding + +- [dookie](https://www.npmjs.com/package/dookie) +- [seedgoose](https://www.npmjs.com/package/seedgoose) +- [mongoose-data-seed](https://www.npmjs.com/package/mongoose-data-seed) + +#### Express Session Stores + +- [connect-mongodb-session](https://www.npmjs.com/package/connect-mongodb-session) +- [connect-mongo](https://www.npmjs.com/package/connect-mongo) + +## License + +Copyright (c) 2010 LearnBoost <dev@learnboost.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/mongoose/SECURITY.md b/node_modules/mongoose/SECURITY.md new file mode 100644 index 0000000..41b89d8 --- /dev/null +++ b/node_modules/mongoose/SECURITY.md @@ -0,0 +1 @@ +Please follow the instructions on [Tidelift's security page](https://tidelift.com/docs/security) to report a security issue. diff --git a/node_modules/mongoose/browser.js b/node_modules/mongoose/browser.js new file mode 100644 index 0000000..4cf8228 --- /dev/null +++ b/node_modules/mongoose/browser.js @@ -0,0 +1,8 @@ +/** + * Export lib/mongoose + * + */ + +'use strict'; + +module.exports = require('./lib/browser'); diff --git a/node_modules/mongoose/build-browser.js b/node_modules/mongoose/build-browser.js new file mode 100644 index 0000000..6f4aa16 --- /dev/null +++ b/node_modules/mongoose/build-browser.js @@ -0,0 +1,18 @@ +'use strict'; + +const config = require('./webpack.config.js'); +const webpack = require('webpack'); + +const compiler = webpack(config); + +console.log('Starting browser build...'); +compiler.run((err, stats) => { + if (err) { + console.err(stats.toString()); + console.err('Browser build unsuccessful.'); + process.exit(1); + } + console.log(stats.toString()); + console.log('Browser build successful.'); + process.exit(0); +}); diff --git a/node_modules/mongoose/dist/browser.umd.js b/node_modules/mongoose/dist/browser.umd.js new file mode 100644 index 0000000..6d8b2a1 --- /dev/null +++ b/node_modules/mongoose/dist/browser.umd.js @@ -0,0 +1,1665 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.mongoose=e():t.mongoose=e()}("undefined"!=typeof self?self:this,(function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=96)}([function(t,e,r){"use strict";e.arrayAtomicsBackupSymbol=Symbol("mongoose#Array#atomicsBackup"),e.arrayAtomicsSymbol=Symbol("mongoose#Array#_atomics"),e.arrayParentSymbol=Symbol("mongoose#Array#_parent"),e.arrayPathSymbol=Symbol("mongoose#Array#_path"),e.arraySchemaSymbol=Symbol("mongoose#Array#_schema"),e.documentArrayParent=Symbol("mongoose:documentArrayParent"),e.documentIsSelected=Symbol("mongoose#Document#isSelected"),e.documentIsModified=Symbol("mongoose#Document#isModified"),e.documentModifiedPaths=Symbol("mongoose#Document#modifiedPaths"),e.documentSchemaSymbol=Symbol("mongoose#Document#schema"),e.getSymbol=Symbol("mongoose#Document#get"),e.modelSymbol=Symbol("mongoose#Model"),e.objectIdSymbol=Symbol("mongoose#ObjectId"),e.populateModelSymbol=Symbol("mongoose.PopulateOptions#Model"),e.schemaTypeSymbol=Symbol("mongoose#schemaType"),e.sessionNewDocuments=Symbol("mongoose:ClientSession#newDocuments"),e.scopeSymbol=Symbol("mongoose#Document#scope"),e.validatorErrorSymbol=Symbol("mongoose:validatorError")},function(t,e,r){"use strict";(function(t,n){ +/*! + * Module dependencies. + */ +function o(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return i(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return i(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0,o=function(){};return{s:o,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0;f--)if(u[f]!==c[f])return!1;for(var p=0,h=u;p0)return t[t.length-1]},e.clone=y, +/*! + * ignore + */ +e.promiseOrCallback=b, +/*! + * ignore + */ +e.omit=function(t,e){if(null==e)return Object.assign({},t);Array.isArray(e)||(e=[e]);var r,n=Object.assign({},t),i=o(e);try{for(i.s();!(r=i.n()).done;){delete n[r.value]}}catch(t){i.e(t)}finally{i.f()}return n}, +/*! + * Shallow copies defaults into options. + * + * @param {Object} defaults + * @param {Object} options + * @return {Object} the merged object + * @api private + */ +e.options=function(t,e){var r,n=Object.keys(t),o=n.length;for(e=e||{};o--;)(r=n[o])in e||(e[r]=t[r]);return e}, +/*! + * Generates a random string + * + * @api private + */ +e.random=function(){return Math.random().toString().substr(3)}, +/*! + * Merges `from` into `to` without overwriting existing properties. + * + * @param {Object} to + * @param {Object} from + * @api private + */ +e.merge=function t(r,n,o,i){o=o||{};var s,a=Object.keys(n),u=0,c=a.length;n[S]&&(r[S]=n[S]),i=i||"";for(var l=o.omitNested||{};u [1,2,3,4] + * + * @param {Array} arr + * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsy value, the item will not be included in the results. + * @return {Array} + * @private + */ +e.array.flatten=function t(e,r,n){return n||(n=[]),e.forEach((function(e){Array.isArray(e)?t(e,r,n):r&&!r(e)||n.push(e)})),n}; +/*! + * ignore + */ +var E=Object.prototype.hasOwnProperty;e.hasUserDefinedProperty=function(t,r){if(null==t)return!1;if(Array.isArray(r)){var n,i=o(r);try{for(i.s();!(n=i.n()).done;){var a=n.value;if(e.hasUserDefinedProperty(t,a))return!0}}catch(t){i.e(t)}finally{i.f()}return!1}if(E.call(t,r))return!0;if("object"===s(t)&&r in t){var u=t[r];return u!==Object.prototype[r]&&u!==Array.prototype[r]}return!1}; +/*! + * ignore + */ +var j=Math.pow(2,32)-1;e.isArrayIndex=function(t){return"number"==typeof t?t>=0&&t<=j:"string"==typeof t&&(!!/^\d+$/.test(t)&&((t=+t)>=0&&t<=j))}, +/*! + * Removes duplicate values from an array + * + * [1, 2, 3, 3, 5] => [1, 2, 3, 5] + * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ] + * => [ObjectId("550988ba0c19d57f697dc45e")] + * + * @param {Array} arr + * @return {Array} + * @private + */ +e.array.unique=function(t){var e,r=new Set,n=new Set,i=[],s=o(t);try{for(s.s();!(e=s.n()).done;){var a=e.value;if("number"==typeof a||"string"==typeof a||null==a){if(r.has(a))continue;i.push(a),r.add(a)}else if(a instanceof p){if(n.has(a.toString()))continue;i.push(a),n.add(a.toString())}else i.push(a)}}catch(t){s.e(t)}finally{s.f()}return i}, +/*! + * Determines if two buffers are equal. + * + * @param {Buffer} a + * @param {Object} b + */ +e.buffer={},e.buffer.areEqual=function(e,r){if(!t.isBuffer(e))return!1;if(!t.isBuffer(r))return!1;if(e.length!==r.length)return!1;for(var n=0,o=e.length;n + * @license MIT + */ +var n=r(98),o=r(99),i=r(100);function s(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(t,e){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|t}function y(t,e){if(u.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return L(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return U(t).length;default:if(n)return L(t).length;e=(""+e).toLowerCase(),n=!0}}function d(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return x(this,e,r);case"utf8":case"utf-8":return E(this,e,r);case"ascii":return j(this,e,r);case"latin1":case"binary":return P(this,e,r);case"base64":return $(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function _(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function v(t,e,r,n,o){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(o)return-1;r=t.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof e&&(e=u.from(e,n)),u.isBuffer(e))return 0===e.length?-1:m(t,e,r,n,o);if("number"==typeof e)return e&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):m(t,[e],r,n,o);throw new TypeError("val must be string, number or Buffer")}function m(t,e,r,n,o){var i,s=1,a=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,u/=2,r/=2}function c(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(o){var l=-1;for(i=r;ia&&(r=a-u),i=r;i>=0;i--){for(var f=!0,p=0;po&&(n=o):n=o;var i=e.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var s=0;s>8,o=r%256,i.push(o),i.push(n);return i}(e,t.length-r),t,r,n)}function $(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function E(t,e,r){r=Math.min(t.length,r);for(var n=[],o=e;o239?4:c>223?3:c>191?2:1;if(o+f<=r)switch(f){case 1:c<128&&(l=c);break;case 2:128==(192&(i=t[o+1]))&&(u=(31&c)<<6|63&i)>127&&(l=u);break;case 3:i=t[o+1],s=t[o+2],128==(192&i)&&128==(192&s)&&(u=(15&c)<<12|(63&i)<<6|63&s)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:i=t[o+1],s=t[o+2],a=t[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(u=(15&c)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(l=u)}null===l?(l=65533,f=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),o+=f}return function(t){var e=t.length;if(e<=4096)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),""},u.prototype.compare=function(t,e,r,n,o){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),e<0||r>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&e>=r)return 0;if(n>=o)return-1;if(e>=r)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),a=Math.min(i,s),c=this.slice(n,o),l=t.slice(e,r),f=0;fo)&&(r=o),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return g(this,t,e,r);case"utf8":case"utf-8":return b(this,t,e,r);case"ascii":return w(this,t,e,r);case"latin1":case"binary":return O(this,t,e,r);case"base64":return S(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,e,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function j(t,e,r){var n="";r=Math.min(t.length,r);for(var o=e;on)&&(r=n);for(var o="",i=e;ir)throw new RangeError("Trying to access beyond buffer length")}function k(t,e,r,n,o,i){if(!u.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||et.length)throw new RangeError("Index out of range")}function B(t,e,r,n){e<0&&(e=65535+e+1);for(var o=0,i=Math.min(t.length-r,2);o>>8*(n?o:1-o)}function C(t,e,r,n){e<0&&(e=4294967295+e+1);for(var o=0,i=Math.min(t.length-r,4);o>>8*(n?o:3-o)&255}function R(t,e,r,n,o,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function D(t,e,r,n,i){return i||R(t,0,r,4),o.write(t,e,r,n,23,4),r+4}function M(t,e,r,n,i){return i||R(t,0,r,8),o.write(t,e,r,n,52,8),r+8}u.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(o*=256);)n+=this[t+--e]*o;return n},u.prototype.readUInt8=function(t,e){return e||N(t,1,this.length),this[t]},u.prototype.readUInt16LE=function(t,e){return e||N(t,2,this.length),this[t]|this[t+1]<<8},u.prototype.readUInt16BE=function(t,e){return e||N(t,2,this.length),this[t]<<8|this[t+1]},u.prototype.readUInt32LE=function(t,e){return e||N(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},u.prototype.readUInt32BE=function(t,e){return e||N(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},u.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||N(t,e,this.length);for(var n=this[t],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*e)),n},u.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||N(t,e,this.length);for(var n=e,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*e)),i},u.prototype.readInt8=function(t,e){return e||N(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},u.prototype.readInt16LE=function(t,e){e||N(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(t,e){e||N(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(t,e){return e||N(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},u.prototype.readInt32BE=function(t,e){return e||N(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},u.prototype.readFloatLE=function(t,e){return e||N(t,4,this.length),o.read(this,t,!0,23,4)},u.prototype.readFloatBE=function(t,e){return e||N(t,4,this.length),o.read(this,t,!1,23,4)},u.prototype.readDoubleLE=function(t,e){return e||N(t,8,this.length),o.read(this,t,!0,52,8)},u.prototype.readDoubleBE=function(t,e){return e||N(t,8,this.length),o.read(this,t,!1,52,8)},u.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||k(this,t,e,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[e]=255&t;++i=0&&(i*=256);)this[e+o]=t/i&255;return e+r},u.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||k(this,t,e,1,255,0),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},u.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||k(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):B(this,t,e,!0),e+2},u.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||k(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):B(this,t,e,!1),e+2},u.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||k(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):C(this,t,e,!0),e+4},u.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||k(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):C(this,t,e,!1),e+4},u.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);k(this,t,e,r,o-1,-o)}var i=0,s=1,a=0;for(this[e]=255&t;++i>0)-a&255;return e+r},u.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);k(this,t,e,r,o-1,-o)}var i=r-1,s=1,a=0;for(this[e+i]=255&t;--i>=0&&(s*=256);)t<0&&0===a&&0!==this[e+i+1]&&(a=1),this[e+i]=(t/s>>0)-a&255;return e+r},u.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||k(this,t,e,1,127,-128),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},u.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||k(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):B(this,t,e,!0),e+2},u.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||k(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):B(this,t,e,!1),e+2},u.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||k(this,t,e,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):C(this,t,e,!0),e+4},u.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||k(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):C(this,t,e,!1),e+4},u.prototype.writeFloatLE=function(t,e,r){return D(this,t,e,!0,r)},u.prototype.writeFloatBE=function(t,e,r){return D(this,t,e,!1,r)},u.prototype.writeDoubleLE=function(t,e,r){return M(this,t,e,!0,r)},u.prototype.writeDoubleBE=function(t,e,r){return M(this,t,e,!1,r)},u.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--o)t[o+e]=this[o+r];else if(i<1e3||!u.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function U(t){return n.toByteArray(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(I,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function V(t,e,r,n){for(var o=0;o=e.length||o>=t.length);++o)e[o+r]=t[o];return o}}).call(this,r(10))},function(t,e,r){"use strict"; +/*! + * Simplified lodash.get to work around the annoying null quirk. See: + * https://github.com/lodash/lodash/issues/3659 + */function n(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return o(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0,i=function(){};return{s:i,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=o)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}})),a=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),d(r)?n.showHidden=r:r&&e._extend(n,r),g(n.showHidden)&&(n.showHidden=!1),g(n.depth)&&(n.depth=2),g(n.colors)&&(n.colors=!1),g(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=c),f(n,t,n.depth)}function c(t,e){var r=u.styles[e];return r?"["+u.colors[r][0]+"m"+t+"["+u.colors[r][1]+"m":t}function l(t,e){return t}function f(t,r,n){if(t.customInspect&&r&&A(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var o=r.inspect(n,t);return m(o)||(o=f(t,o,n)),o}var i=function(t,e){if(g(e))return t.stylize("undefined","undefined");if(m(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(v(e))return t.stylize(""+e,"number");if(d(e))return t.stylize(""+e,"boolean");if(_(e))return t.stylize("null","null")}(t,r);if(i)return i;var s=Object.keys(r),a=function(t){var e={};return t.forEach((function(t,r){e[t]=!0})),e}(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(r)),S(r)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return p(r);if(0===s.length){if(A(r)){var u=r.name?": "+r.name:"";return t.stylize("[Function"+u+"]","special")}if(b(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(O(r))return t.stylize(Date.prototype.toString.call(r),"date");if(S(r))return p(r)}var c,l="",w=!1,$=["{","}"];(y(r)&&(w=!0,$=["[","]"]),A(r))&&(l=" [Function"+(r.name?": "+r.name:"")+"]");return b(r)&&(l=" "+RegExp.prototype.toString.call(r)),O(r)&&(l=" "+Date.prototype.toUTCString.call(r)),S(r)&&(l=" "+p(r)),0!==s.length||w&&0!=r.length?n<0?b(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special"):(t.seen.push(r),c=w?function(t,e,r,n,o){for(var i=[],s=0,a=e.length;s=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1}),0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(c,l,$)):$[0]+l+$[1]}function p(t){return"["+Error.prototype.toString.call(t)+"]"}function h(t,e,r,n,o,i){var s,a,u;if((u=Object.getOwnPropertyDescriptor(e,o)||{value:e[o]}).get?a=u.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):u.set&&(a=t.stylize("[Setter]","special")),x(n,o)||(s="["+o+"]"),a||(t.seen.indexOf(u.value)<0?(a=_(r)?f(t,u.value,null):f(t,u.value,r-1)).indexOf("\n")>-1&&(a=i?a.split("\n").map((function(t){return" "+t})).join("\n").substr(2):"\n"+a.split("\n").map((function(t){return" "+t})).join("\n")):a=t.stylize("[Circular]","special")),g(s)){if(i&&o.match(/^\d+$/))return a;(s=JSON.stringify(""+o)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+a}function y(t){return Array.isArray(t)}function d(t){return"boolean"==typeof t}function _(t){return null===t}function v(t){return"number"==typeof t}function m(t){return"string"==typeof t}function g(t){return void 0===t}function b(t){return w(t)&&"[object RegExp]"===$(t)}function w(t){return"object"===n(t)&&null!==t}function O(t){return w(t)&&"[object Date]"===$(t)}function S(t){return w(t)&&("[object Error]"===$(t)||t instanceof Error)}function A(t){return"function"==typeof t}function $(t){return Object.prototype.toString.call(t)}function E(t){return t<10?"0"+t.toString(10):t.toString(10)}e.debuglog=function(r){if(g(s)&&(s=t.env.NODE_DEBUG||""),r=r.toUpperCase(),!a[r])if(new RegExp("\\b"+r+"\\b","i").test(s)){var n=t.pid;a[r]=function(){var t=e.format.apply(e,arguments);console.error("%s %d: %s",r,n,t)}}else a[r]=function(){};return a[r]},e.inspect=u,u.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},u.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.isArray=y,e.isBoolean=d,e.isNull=_,e.isNullOrUndefined=function(t){return null==t},e.isNumber=v,e.isString=m,e.isSymbol=function(t){return"symbol"===n(t)},e.isUndefined=g,e.isRegExp=b,e.isObject=w,e.isDate=O,e.isError=S,e.isFunction=A,e.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"===n(t)||void 0===t},e.isBuffer=r(103);var j=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function P(){var t=new Date,e=[E(t.getHours()),E(t.getMinutes()),E(t.getSeconds())].join(":");return[t.getDate(),j[t.getMonth()],e].join(" ")}function x(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.log=function(){console.log("%s - %s",P(),e.format.apply(e,arguments))},e.inherits=r(104),e._extend=function(t,e){if(!e||!w(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t};var T="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function N(t,e){if(!t){var r=new Error("Promise was rejected with a falsy value");r.reason=t,t=r}return e(t)}e.promisify=function(t){if("function"!=typeof t)throw new TypeError('The "original" argument must be of type Function');if(T&&t[T]){var e;if("function"!=typeof(e=t[T]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(e,T,{value:e,enumerable:!1,writable:!1,configurable:!0}),e}function e(){for(var e,r,n=new Promise((function(t,n){e=t,r=n})),o=[],i=0;i1&&(this.defaultValue=y.args(arguments)),this.defaultValue},b.prototype.index=function(t){return this._index=t,y.expires(this._index),this},b.prototype.unique=function(t){if(!1===this._index){if(!t)return;throw new Error('Path "'+this.path+'" may not have `index` set to false and `unique` set to true')}return this.options.hasOwnProperty("index")||!1!==t?(null==this._index||!0===this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.unique=t,this):this},b.prototype.text=function(t){if(!1===this._index){if(!t)return;throw new Error('Path "'+this.path+'" may not have `index` set to false and `text` set to true')}return this.options.hasOwnProperty("index")||!1!==t?(null===this._index||void 0===this._index||"boolean"==typeof this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.text=t,this):this},b.prototype.sparse=function(t){if(!1===this._index){if(!t)return;throw new Error('Path "'+this.path+'" may not have `index` set to false and `sparse` set to true')}return this.options.hasOwnProperty("index")||!1!==t?(null==this._index||"boolean"==typeof this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.sparse=t,this):this},b.prototype.immutable=function(t){return this.$immutable=t,l(this),this},b.prototype.transform=function(t){return this.options.transform=t,this},b.prototype.set=function(t){if("function"!=typeof t)throw new TypeError("A setter must be a function.");return this.setters.push(t),this},b.prototype.get=function(t){if("function"!=typeof t)throw new TypeError("A getter must be a function.");return this.getters.push(t),this},b.prototype.validate=function(t,e,r){var n,s,a,u;if("function"==typeof t||t&&"RegExp"===y.getFunctionName(t.constructor))return"function"==typeof e?(n={validator:t,message:e}).type=r||"user defined":e instanceof Object&&!r?((n=y.clone(e)).message||(n.message=n.msg),n.validator=t,n.type=n.type||"user defined"):(null==e&&(e=i.messages.general.default),r||(r="user defined"),n={message:e,type:r,validator:t}),this.validators.push(n),this;for(s=0,a=arguments.length;s0&&null==t)return this.validators=this.validators.filter((function(t){return t.validator!==this.requiredValidator}),this),this.isRequired=!1,delete this.originalRequiredValue,this;if("object"===o(t)&&(e=(r=t).message||e,t=t.isRequired),!1===t)return this.validators=this.validators.filter((function(t){return t.validator!==this.requiredValidator}),this),this.isRequired=!1,delete this.originalRequiredValue,this;var n=this;this.isRequired=!0,this.requiredValidator=function(e){var r=c(this,"$__.cachedRequired");if(null!=r&&!this.$__isSelected(n.path)&&!this[_](n.path))return!0;if(null!=r&&n.path in r){var o=!r[n.path]||n.checkRequired(e,this);return delete r[n.path],o}return"function"==typeof t&&!t.apply(this)||n.checkRequired(e,this)},this.originalRequiredValue=t,"string"==typeof t&&(e=t,t=void 0);var s=e||i.messages.general.required;return this.validators.unshift(Object.assign({},r,{validator:this.requiredValidator,message:s,type:"required"})),this},b.prototype.ref=function(t){return this.options.ref=t,this},b.prototype.getDefault=function(t,e){var r;if(null!=(r="function"==typeof this.defaultValue?this.defaultValue===Date.now||this.defaultValue===Array||"objectid"===this.defaultValue.name.toLowerCase()?this.defaultValue.call(t):this.defaultValue.call(t,t):this.defaultValue)){"object"!==o(r)||this.options&&this.options.shared||(r=y.clone(r));var n=this.applySetters(r,t,e);return n&&n.$isSingleNested&&(n.$__parent=t),n}return r}, +/*! + * Applies setters without casting + * + * @api private + */ +b.prototype._applySetters=function(t,e,r,n){var o=t;if(r)return o;for(var i=this.setters,s=i.length-1;s>=0;s--)o=i[s].call(e,o,n,this);return o}, +/*! + * ignore + */ +b.prototype._castNullish=function(t){return t},b.prototype.applySetters=function(t,e,r,n,o){var i=this._applySetters(t,e,r,n,o);return null==i?this._castNullish(i):i=this.cast(i,e,r,n,o)},b.prototype.applyGetters=function(t,e){var r=t,n=this.getters,o=n.length;if(0===o)return r;for(var i=0;i0&&"required"===this.validators[0].type))return null;i=[this.validators[0]]}var s=null;return i.forEach((function(i){if(!s&&null!=i&&"object"===o(i)){var u,c=i.validator,l=y.clone(i);if(l.path=r&&r.path?r.path:n,l.value=t,!f(c))if(c instanceof RegExp)a(c.test(t),l);else if("function"==typeof c){try{u=l.propsParameter?c.call(e,t,l):c.call(e,t)}catch(t){u=!1,l.reason=t}null!=u&&"function"==typeof u.then||a(u,l)}}})),s;function a(t,e){if(!s&&void 0!==t&&!t){var r=e.ErrorConstructor||g;(s=new r(e))[d]=!0}}},b._isRef=function(t,e,r,o){var i=o&&t.options&&(t.options.ref||t.options.refPath);if(!i&&r&&null!=r.$__){var s=r.$__fullPath(t.path,!0),a=r.ownerDocument?r.ownerDocument():r;i=null!=s&&a.$populated(s)||r.$populated(t.path)}return!!i&&(null==e||(!(n.isBuffer(e)||"Binary"===e._bsontype||!y.isObject(e))||o))}, +/*! + * ignore + */ +b.prototype._castRef=function(t,e,r){if(null==t)return t;if(null!=t.$__)return t.$__.wasPopulated=!0,t;if(n.isBuffer(t)||!y.isObject(t)){if(r)return t;throw new m(this.instance,t,this.path,null,this)}var o=e.$__fullPath(this.path,!0),i=(e.ownerDocument?e.ownerDocument():e).$populated(o,!0),s=t;return e.$__.populated&&e.$__.populated[o]&&e.$__.populated[o].options&&e.$__.populated[o].options.options&&e.$__.populated[o].options.options.lean||((s=new i.options[v](t)).$__.wasPopulated=!0),s},b.prototype.$conditionalHandlers={$all:function(t){var e=this;return Array.isArray(t)?t.map((function(t){return e.castForQuery(t)})):[this.castForQuery(t)]},$eq:w,$in:O,$ne:w,$nin:O,$exists:a,$type:u}, +/*! + * Wraps `castForQuery` to handle context + */ +b.prototype.castForQueryWrapper=function(t){if(this.$$context=t.context,"$conditional"in t){var e=this.castForQuery(t.$conditional,t.val);return this.$$context=null,e}if(t.$skipQueryCastForUpdate||t.$applySetters){var r=this._castForQuery(t.val);return this.$$context=null,r}var n=this.castForQuery(t.val);return this.$$context=null,n},b.prototype.castForQuery=function(t,e){var r;if(2===arguments.length){if(!(r=this.$conditionalHandlers[t]))throw new Error("Can't use "+t);return r.call(this,e)}return e=t,this._castForQuery(e)}, +/*! + * Internal switch for runSetters + * + * @api private + */ +b.prototype._castForQuery=function(t){return this.applySetters(t,this.$$context)},b.checkRequired=function(t){return arguments.length>0&&(this._checkRequired=t),this._checkRequired},b.prototype.checkRequired=function(t){return null!=t}, +/*! + * ignore + */ +b.prototype.clone=function(){var t=Object.assign({},this.options),e=new this.constructor(this.path,t,this.instance);return e.validators=this.validators.slice(),void 0!==this.requiredValidator&&(e.requiredValidator=this.requiredValidator),void 0!==this.defaultValue&&(e.defaultValue=this.defaultValue),void 0!==this.$immutable&&void 0===this.options.immutable&&(e.$immutable=this.$immutable,l(e)),void 0!==this._index&&(e._index=this._index),void 0!==this.selected&&(e.selected=this.selected),void 0!==this.isRequired&&(e.isRequired=this.isRequired),void 0!==this.originalRequiredValue&&(e.originalRequiredValue=this.originalRequiredValue),e.getters=this.getters.slice(),e.setters=this.setters.slice(),e}, +/*! + * Module exports. + */ +t.exports=e=b,e.CastError=m,e.ValidatorError=g}).call(this,r(2).Buffer)},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function o(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return i(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return i(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0,o=function(){};return{s:o,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0?".":"")+tt[b],it||(this.$set(st,{}),this.$__isSelected(st)||this.unmarkModified(st),it=this.$__getValue(st));if(tt.length<=1)ot=t;else{for(b=0;b0&&null!=e[0]&&null!=e[0].$__&&null!=e[0].$__.populated){for(var mt=Object.keys(e[0].$__.populated),gt=function(){var r=wt[bt];a.$populated(t+"."+r,e.map((function(t){return t.$populated(r)})),e[0].$__.populated[r].options)},bt=0,wt=mt;bt0){var r=this.$get(t);return null==r||"object"===s(r)&&(L.isPOJO(r)?ut(r):0===Object.keys(r.toObject(e)).length)}return 0===Object.keys(this.toObject(e)).length},nt.prototype.modifiedPaths=function(t){t=t||{};var e=Object.keys(this.$__.activePaths.states.modify),r=this;return e.reduce((function(e,n){var i=n.split(".");if(e=e.concat(i.reduce((function(t,e,r){return t.concat(i.slice(0,r).concat(e).join("."))}),[]).filter((function(t){return-1===e.indexOf(t)}))),!t.includeChildren)return e;var a=r.$get(n);if(null!=a&&"object"===s(a))if(a._doc&&(a=a._doc),Array.isArray(a)){for(var u=a.length,c=0;c0){"function"==typeof r[r.length-1]&&(t=r.pop());var n,i=L.populate.apply(null,r),s=o(i);try{for(s.s();!(n=s.n()).done;){var a=n.value;e[a.path]=a}}catch(t){s.e(t)}finally{s.f()}}var u=L.object.vals(e),c=this.constructor;if(this.$__isNested){c=this.$__[Z].constructor;var l=this.$__.nestedPath;u.forEach((function(t){t.path=l+"."+t.path}))}if(null!=this.$session()){var f=this.$session();u.forEach((function(t){null!=t.options?"session"in t.options||(t.options.session=f):t.options={session:f}}))}return u.forEach((function(t){t._localModel=c})),c.populate(this,u,t)},nt.prototype.$getPopulatedDocs=function(){var t=[];null!=this.$__.populated&&(t=t.concat(Object.keys(this.$__.populated)));var e,r=[],n=o(t);try{for(n.s();!(e=n.n()).done;){var i=e.value,s=this.$get(i);Array.isArray(s)?r=r.concat(s):s instanceof nt&&r.push(s)}}catch(t){n.e(t)}finally{n.f()}return r},nt.prototype.populated=function(t,e,r){if(null==e||!0===e){if(!this.$__.populated)return;if("string"!=typeof t)return;var n=t.endsWith(".$*")?t.replace(/\.\$\*$/,""):t,o=this.$__.populated[n];return o?!0===e?o:o.value:void 0}this.$__.populated||(this.$__.populated={}),this.$__.populated[t]={value:e,options:r};for(var i=t.split("."),s=0;s1)for(var r=1;r0){var a=y(e),f=d(e),p=_(i),h=v(null,t,a,r,p,f);(s=c.call(this,h)).init(t,e,r,n,i)}else s=c.call(this,v());return u(s)}return e=l,(r=[{key:"toJSON",value:function(){return{stringValue:this.stringValue,valueType:this.valueType,kind:this.kind,value:this.value,path:this.path,reason:this.reason,name:this.name,message:this.message}} +/*! + * ignore + */},{key:"init",value:function(t,e,r,n,o){this.stringValue=y(e),this.messageFormat=_(o),this.kind=t,this.value=e,this.path=r,this.reason=n,this.valueType=d(e)} +/*! + * ignore + * @param {Readonly} other + */},{key:"copy",value:function(t){this.messageFormat=t.messageFormat,this.stringValue=t.stringValue,this.kind=t.kind,this.value=t.value,this.path=t.path,this.reason=t.reason,this.message=t.message,this.valueType=t.valueType} +/*! + * ignore + */},{key:"setModel",value:function(t){this.model=t,this.message=v(t,this.kind,this.stringValue,this.path,this.messageFormat,this.valueType)}}])&&i(e.prototype,r),n&&i(e,n),l}(l);function y(t){var e=p.inspect(t);return(e=e.replace(/^'|'$/g,'"')).startsWith('"')||(e='"'+e+'"'),e}function d(t){if(null==t)return""+t;var e=n(t);return"object"!==e||"function"!=typeof t.constructor?e:t.constructor.name}function _(t){var e=f(t,"options.cast",null);if("string"==typeof e)return e} +/*! + * ignore + */function v(t,e,r,n,o,i){if(null!=o){var s=o.replace("{KIND}",e).replace("{VALUE}",r).replace("{PATH}",n);return null!=t&&(s=s.replace("{MODEL}",t.modelName)),s}var a="Cast to "+e+" failed for value "+r+(i?" (type "+i+")":"")+' at path "'+n+'"';return null!=t&&(a+=' for model "'+t.modelName+'"'),a} +/*! + * exports + */Object.defineProperty(h.prototype,"name",{value:"CastError"}),t.exports=h},function(t,e,r){"use strict"; +/*! + * ignore + */function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function s(t){var e="function"==typeof Map?new Map:void 0;return(s=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,n)}function n(){return a(t,arguments,l(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),c(n,t)})(t)}function a(t,e,r){return(a=u()?Reflect.construct:function(t,e,r){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(t,n));return r&&c(o,r.prototype),o}).apply(null,arguments)}function u(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function c(t,e){return(c=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function l(t){return(l=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var f=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&c(t,e)}(s,t);var e,r,n=(e=s,r=u(),function(){var t,n=l(e);if(r){var o=l(this).constructor;t=Reflect.construct(n,arguments,o)}else t=n.apply(this,arguments);return i(this,t)});function s(){return o(this,s),n.apply(this,arguments)}return s}(s(Error));Object.defineProperty(f.prototype,"name",{value:"MongooseError"}),t.exports=f},function(t,e,r){"use strict"; +/*! + * ignore + */var n=null;t.exports.get=function(){return n},t.exports.set=function(t){n=t}},function(t,e,r){"use strict";(function(e){function r(t,r){return new e(t,r)}t.exports={normalizedFunctionString:function(t){return t.toString().replace(/function *\(/,"function (")},allocBuffer:"function"==typeof e.alloc?function(){return e.alloc.apply(e,arguments)}:r,toBuffer:"function"==typeof e.from?function(){return e.from.apply(e,arguments)}:r}}).call(this,r(2).Buffer)},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}var o=r(57),i=r(163),s=r(7),a=r(0).arrayAtomicsSymbol,u=r(0).arrayAtomicsBackupSymbol,c=r(0).arrayParentSymbol,l=r(0).arrayPathSymbol,f=r(0).arraySchemaSymbol,p=Array.prototype.push;function h(t,e,r){var n=this.__array;if(r)return n[t]=e,n;var o=i._cast.call(this,e,t);return n[t]=o,i._markModified.call(this,t),n} +/*! + * Module exports. + */t.exports=function(t,e,r){var y,d=[],_=(n(y={},a,{}),n(y,u,void 0),n(y,l,e),n(y,f,void 0),n(y,c,void 0),y);if(Array.isArray(t)&&(t[l]===e&&t[c]===r&&(_[a]=Object.assign({},t[a])),t.forEach((function(t){p.call(d,t)}))),_[l]=e,r&&r instanceof s)for(_[c]=r,_[f]=r.schema.path(e);null!=_[f]&&_[f].$isMongooseArray&&!_[f].$isMongooseDocumentArray;)_[f]=_[f].casterConstructor;var v=new Proxy(d,{get:function(t,e){return"isMongooseArray"===e||"isMongooseArrayProxy"===e||"isMongooseDocumentArray"===e||"isMongooseDocumentArrayProxy"===e||("__array"===e?d:"set"===e?h:_.hasOwnProperty(e)?_[e]:i.hasOwnProperty(e)?i[e]:o.hasOwnProperty(e)?o[e]:d[e])},set:function(t,e,r){return"string"==typeof e&&/^\d+$/.test(e)?h.call(v,e,r):_.hasOwnProperty(e)?_[e]=r:d[e]=r,!0}});return v}},function(t,e,r){"use strict";function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var o,i="object"===("undefined"==typeof Reflect?"undefined":n(Reflect))?Reflect:null,s=i&&"function"==typeof i.apply?i.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)};o=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:function(t){return Object.getOwnPropertyNames(t)};var a=Number.isNaN||function(t){return t!=t};function u(){u.init.call(this)}t.exports=u,t.exports.once=function(t,e){return new Promise((function(r,n){function o(r){t.removeListener(e,i),n(r)}function i(){"function"==typeof t.removeListener&&t.removeListener("error",o),r([].slice.call(arguments))}m(t,e,i,{once:!0}),"error"!==e&&function(t,e,r){"function"==typeof t.on&&m(t,"error",e,r)}(t,o,{once:!0})}))},u.EventEmitter=u,u.prototype._events=void 0,u.prototype._eventsCount=0,u.prototype._maxListeners=void 0;var c=10;function l(t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+n(t))}function f(t){return void 0===t._maxListeners?u.defaultMaxListeners:t._maxListeners}function p(t,e,r,n){var o,i,s,a;if(l(r),void 0===(i=t._events)?(i=t._events=Object.create(null),t._eventsCount=0):(void 0!==i.newListener&&(t.emit("newListener",e,r.listener?r.listener:r),i=t._events),s=i[e]),void 0===s)s=i[e]=r,++t._eventsCount;else if("function"==typeof s?s=i[e]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),(o=f(t))>0&&s.length>o&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=s.length,a=u,console&&console.warn&&console.warn(a)}return t}function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function y(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},o=h.bind(n);return o.listener=r,n.wrapFn=o,o}function d(t,e,r){var n=t._events;if(void 0===n)return[];var o=n[e];return void 0===o?[]:"function"==typeof o?r?[o.listener||o]:[o]:r?function(t){for(var e=new Array(t.length),r=0;r0&&(i=e[0]),i instanceof Error)throw i;var a=new Error("Unhandled error."+(i?" ("+i.message+")":""));throw a.context=i,a}var u=o[t];if(void 0===u)return!1;if("function"==typeof u)s(u,this,e);else{var c=u.length,l=v(u,c);for(r=0;r=0;i--)if(r[i]===e||r[i].listener===e){s=r[i].listener,o=i;break}if(o<0)return this;0===o?r.shift():function(t,e){for(;e+1=0;n--)this.removeListener(t,e[n]);return this},u.prototype.listeners=function(t){return d(this,t,!0)},u.prototype.rawListeners=function(t){return d(this,t,!1)},u.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):_.call(t,e)},u.prototype.listenerCount=_,u.prototype.eventNames=function(){return this._eventsCount>0?o(this._events):[]}},function(t,e,r){"use strict";t.exports=r(15).get().Decimal128},function(t,e,r){"use strict";(function(e){ +/*! + * Determines if `arg` is an object. + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @api private + * @return {Boolean} + */ +t.exports=function(t){return!!e.isBuffer(t)||"[object Object]"===Object.prototype.toString.call(t)}}).call(this,r(2).Buffer)},function(t,e,r){"use strict";(function(e){function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var o=r(119); +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */function i(t,e){if(t===e)return 0;for(var r=t.length,n=e.length,o=0,i=Math.min(r,n);o=0;u--)if(l[u]!==f[u])return!1;for(u=l.length-1;u>=0;u--)if(s=l[u],!b(t[s],e[s],r,n))return!1;return!0}(t,e,r,o))}return r?t===e:t==e}function w(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function O(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function S(t,e,r,n){var o;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),o=function(t){var e;try{t()}catch(t){e=t}return e}(e),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),t&&!o&&m(o,r,"Missing expected exception"+n);var i="string"==typeof n,s=!t&&o&&!r;if((!t&&a.isError(o)&&i&&O(o,r)||s)&&m(o,r,"Got unwanted exception"+n),t&&o&&r&&!O(o,r)||!t&&o)throw o}h.AssertionError=function(t){this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=function(t){return _(v(t.actual),128)+" "+t.operator+" "+_(v(t.expected),128)}(this),this.generatedMessage=!0);var e=t.stackStartFunction||m;if(Error.captureStackTrace)Error.captureStackTrace(this,e);else{var r=new Error;if(r.stack){var n=r.stack,o=d(e),i=n.indexOf("\n"+o);if(i>=0){var s=n.indexOf("\n",i+1);n=n.substring(s+1)}this.stack=n}}},a.inherits(h.AssertionError,Error),h.fail=m,h.ok=g,h.equal=function(t,e,r){t!=e&&m(t,e,r,"==",h.equal)},h.notEqual=function(t,e,r){t==e&&m(t,e,r,"!=",h.notEqual)},h.deepEqual=function(t,e,r){b(t,e,!1)||m(t,e,r,"deepEqual",h.deepEqual)},h.deepStrictEqual=function(t,e,r){b(t,e,!0)||m(t,e,r,"deepStrictEqual",h.deepStrictEqual)},h.notDeepEqual=function(t,e,r){b(t,e,!1)&&m(t,e,r,"notDeepEqual",h.notDeepEqual)},h.notDeepStrictEqual=function t(e,r,n){b(e,r,!0)&&m(e,r,n,"notDeepStrictEqual",t)},h.strictEqual=function(t,e,r){t!==e&&m(t,e,r,"===",h.strictEqual)},h.notStrictEqual=function(t,e,r){t===e&&m(t,e,r,"!==",h.notStrictEqual)},h.throws=function(t,e,r){S(!0,t,e,r)},h.doesNotThrow=function(t,e,r){S(!1,t,e,r)},h.ifError=function(t){if(t)throw t},h.strict=o((function t(e,r){e||m(e,!0,r,"==",t)}),h,{equal:h.strictEqual,deepEqual:h.deepStrictEqual,notEqual:h.notStrictEqual,notDeepEqual:h.notDeepStrictEqual}),h.strict.strict=h.strict;var A=Object.keys||function(t){var e=[];for(var r in t)u.call(t,r)&&e.push(r);return e}}).call(this,r(10))},function(t,e,r){"use strict"; +/*! + * If `val` is an object, returns constructor name, if possible. Otherwise returns undefined. + */t.exports=function(t){if(null!=t&&"function"==typeof t.constructor)return t.constructor.name}},function(t,e,r){"use strict"; +/*! + * ignore + */e.internalToObjectOptions={transform:!1,virtuals:!1,getters:!1,_skipDepopulateTopLevel:!0,depopulate:!0,flattenDecimals:!1,useProjection:!1}},function(t,e){function r(t,e){if(!(this instanceof r))return new r(t,e);this._bsontype="Long",this.low_=0|t,this.high_=0|e}r.prototype.toInt=function(){return this.low_},r.prototype.toNumber=function(){return this.high_*r.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},r.prototype.toBigInt=function(){return BigInt(this.toString())},r.prototype.toJSON=function(){return this.toString()},r.prototype.toString=function(t){var e=t||10;if(e<2||36=0?this.low_:r.TWO_PWR_32_DBL_+this.low_},r.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(r.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var t=0!==this.high_?this.high_:this.low_,e=31;e>0&&0==(t&1<0},r.prototype.greaterThanOrEqual=function(t){return this.compare(t)>=0},r.prototype.compare=function(t){if(this.equals(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&r?1:this.subtract(t).isNegative()?-1:1},r.prototype.negate=function(){return this.equals(r.MIN_VALUE)?r.MIN_VALUE:this.not().add(r.ONE)},r.prototype.add=function(t){var e=this.high_>>>16,n=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=0,l=0,f=0,p=0;return f+=(p+=i+(65535&t.low_))>>>16,p&=65535,l+=(f+=o+u)>>>16,f&=65535,c+=(l+=n+a)>>>16,l&=65535,c+=e+s,c&=65535,r.fromBits(f<<16|p,c<<16|l)},r.prototype.subtract=function(t){return this.add(t.negate())},r.prototype.multiply=function(t){if(this.isZero())return r.ZERO;if(t.isZero())return r.ZERO;if(this.equals(r.MIN_VALUE))return t.isOdd()?r.MIN_VALUE:r.ZERO;if(t.equals(r.MIN_VALUE))return this.isOdd()?r.MIN_VALUE:r.ZERO;if(this.isNegative())return t.isNegative()?this.negate().multiply(t.negate()):this.negate().multiply(t).negate();if(t.isNegative())return this.multiply(t.negate()).negate();if(this.lessThan(r.TWO_PWR_24_)&&t.lessThan(r.TWO_PWR_24_))return r.fromNumber(this.toNumber()*t.toNumber());var e=this.high_>>>16,n=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=65535&t.low_,l=0,f=0,p=0,h=0;return p+=(h+=i*c)>>>16,h&=65535,f+=(p+=o*c)>>>16,p&=65535,f+=(p+=i*u)>>>16,p&=65535,l+=(f+=n*c)>>>16,f&=65535,l+=(f+=o*u)>>>16,f&=65535,l+=(f+=i*a)>>>16,f&=65535,l+=e*c+n*u+o*a+i*s,l&=65535,r.fromBits(p<<16|h,l<<16|f)},r.prototype.div=function(t){if(t.isZero())throw Error("division by zero");if(this.isZero())return r.ZERO;if(this.equals(r.MIN_VALUE)){if(t.equals(r.ONE)||t.equals(r.NEG_ONE))return r.MIN_VALUE;if(t.equals(r.MIN_VALUE))return r.ONE;var e=this.shiftRight(1).div(t).shiftLeft(1);if(e.equals(r.ZERO))return t.isNegative()?r.ONE:r.NEG_ONE;var n=this.subtract(t.multiply(e));return e.add(n.div(t))}if(t.equals(r.MIN_VALUE))return r.ZERO;if(this.isNegative())return t.isNegative()?this.negate().div(t.negate()):this.negate().div(t).negate();if(t.isNegative())return this.div(t.negate()).negate();var o=r.ZERO;for(n=this;n.greaterThanOrEqual(t);){e=Math.max(1,Math.floor(n.toNumber()/t.toNumber()));for(var i=Math.ceil(Math.log(e)/Math.LN2),s=i<=48?1:Math.pow(2,i-48),a=r.fromNumber(e),u=a.multiply(t);u.isNegative()||u.greaterThan(n);)e-=s,u=(a=r.fromNumber(e)).multiply(t);a.isZero()&&(a=r.ONE),o=o.add(a),n=n.subtract(u)}return o},r.prototype.modulo=function(t){return this.subtract(this.div(t).multiply(t))},r.prototype.not=function(){return r.fromBits(~this.low_,~this.high_)},r.prototype.and=function(t){return r.fromBits(this.low_&t.low_,this.high_&t.high_)},r.prototype.or=function(t){return r.fromBits(this.low_|t.low_,this.high_|t.high_)},r.prototype.xor=function(t){return r.fromBits(this.low_^t.low_,this.high_^t.high_)},r.prototype.shiftLeft=function(t){if(0===(t&=63))return this;var e=this.low_;if(t<32){var n=this.high_;return r.fromBits(e<>>32-t)}return r.fromBits(0,e<>>t|e<<32-t,e>>t)}return r.fromBits(e>>t-32,e>=0?0:-1)},r.prototype.shiftRightUnsigned=function(t){if(0===(t&=63))return this;var e=this.high_;if(t<32){var n=this.low_;return r.fromBits(n>>>t|e<<32-t,e>>>t)}return 32===t?r.fromBits(e,0):r.fromBits(e>>>t-32,0)},r.fromInt=function(t){if(-128<=t&&t<128){var e=r.INT_CACHE_[t];if(e)return e}var n=new r(0|t,t<0?-1:0);return-128<=t&&t<128&&(r.INT_CACHE_[t]=n),n},r.fromNumber=function(t){return isNaN(t)||!isFinite(t)?r.ZERO:t<=-r.TWO_PWR_63_DBL_?r.MIN_VALUE:t+1>=r.TWO_PWR_63_DBL_?r.MAX_VALUE:t<0?r.fromNumber(-t).negate():new r(t%r.TWO_PWR_32_DBL_|0,t/r.TWO_PWR_32_DBL_|0)},r.fromBigInt=function(t){return r.fromString(t.toString(10),10)},r.fromBits=function(t,e){return new r(t,e)},r.fromString=function(t,e){if(0===t.length)throw Error("number format error: empty string");var n=e||10;if(n<2||36=0)throw Error('number format error: interior "-" character: '+t);for(var o=r.fromNumber(Math.pow(n,8)),i=r.ZERO,s=0;s=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var e=null;if(e="string"==typeof t?t.charCodeAt(0):null!=t.length?t[0]:t,this.buffer.length>this.position)this.buffer[this.position++]=e;else if(void 0!==n&&n.isBuffer(this.buffer)){var r=o.allocBuffer(i.BUFFER_SIZE+this.buffer.length);this.buffer.copy(r,0,0,this.buffer.length),this.buffer=r,this.buffer[this.position++]=e}else{r=null,r="[object Uint8Array]"===Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(i.BUFFER_SIZE+this.buffer.length)):new Array(i.BUFFER_SIZE+this.buffer.length);for(var s=0;sthis.position?e+t.length:this.position;else if(void 0!==n&&"string"==typeof t&&n.isBuffer(this.buffer))this.buffer.write(t,e,"binary"),this.position=e+t.length>this.position?e+t.length:this.position;else if("[object Uint8Array]"===Object.prototype.toString.call(t)||"[object Array]"===Object.prototype.toString.call(t)&&"string"!=typeof t){for(i=0;ithis.position?e:this.position}else if("string"==typeof t){for(i=0;ithis.position?e:this.position}},i.prototype.read=function(t,e){if(e=e&&e>0?e:this.position,this.buffer.slice)return this.buffer.slice(t,t+e);for(var r="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(e)):new Array(e),n=0;n0&&!e[i]&&(e[i]=!0,r.emit("error",e));try{t(e)}catch(e){return o((function(){throw e}))}}})):new(s=s||n.get())((function(t,n){e((function(e,o){return null!=e?(null!=r&&null!=r.listeners&&r.listeners("error").length>0&&!e[i]&&(e[i]=!0,r.emit("error",e)),n(e)):arguments.length>2?t(Array.prototype.slice.call(arguments,1)):void t(o)}))}))}},function(t,e,r){"use strict";var n=["find","findOne","update","updateMany","updateOne","replaceOne","remove","count","distinct","findAndModify","aggregate","findStream","deleteOne","deleteMany"];function o(){}for(var i=0,s=n.length;i=0?this.low_:r.TWO_PWR_32_DBL_+this.low_},r.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(r.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var t=0!==this.high_?this.high_:this.low_,e=31;e>0&&0==(t&1<0},r.prototype.greaterThanOrEqual=function(t){return this.compare(t)>=0},r.prototype.compare=function(t){if(this.equals(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&r?1:this.subtract(t).isNegative()?-1:1},r.prototype.negate=function(){return this.equals(r.MIN_VALUE)?r.MIN_VALUE:this.not().add(r.ONE)},r.prototype.add=function(t){var e=this.high_>>>16,n=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=0,l=0,f=0,p=0;return f+=(p+=i+(65535&t.low_))>>>16,p&=65535,l+=(f+=o+u)>>>16,f&=65535,c+=(l+=n+a)>>>16,l&=65535,c+=e+s,c&=65535,r.fromBits(f<<16|p,c<<16|l)},r.prototype.subtract=function(t){return this.add(t.negate())},r.prototype.multiply=function(t){if(this.isZero())return r.ZERO;if(t.isZero())return r.ZERO;if(this.equals(r.MIN_VALUE))return t.isOdd()?r.MIN_VALUE:r.ZERO;if(t.equals(r.MIN_VALUE))return this.isOdd()?r.MIN_VALUE:r.ZERO;if(this.isNegative())return t.isNegative()?this.negate().multiply(t.negate()):this.negate().multiply(t).negate();if(t.isNegative())return this.multiply(t.negate()).negate();if(this.lessThan(r.TWO_PWR_24_)&&t.lessThan(r.TWO_PWR_24_))return r.fromNumber(this.toNumber()*t.toNumber());var e=this.high_>>>16,n=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=65535&t.low_,l=0,f=0,p=0,h=0;return p+=(h+=i*c)>>>16,h&=65535,f+=(p+=o*c)>>>16,p&=65535,f+=(p+=i*u)>>>16,p&=65535,l+=(f+=n*c)>>>16,f&=65535,l+=(f+=o*u)>>>16,f&=65535,l+=(f+=i*a)>>>16,f&=65535,l+=e*c+n*u+o*a+i*s,l&=65535,r.fromBits(p<<16|h,l<<16|f)},r.prototype.div=function(t){if(t.isZero())throw Error("division by zero");if(this.isZero())return r.ZERO;if(this.equals(r.MIN_VALUE)){if(t.equals(r.ONE)||t.equals(r.NEG_ONE))return r.MIN_VALUE;if(t.equals(r.MIN_VALUE))return r.ONE;var e=this.shiftRight(1).div(t).shiftLeft(1);if(e.equals(r.ZERO))return t.isNegative()?r.ONE:r.NEG_ONE;var n=this.subtract(t.multiply(e));return e.add(n.div(t))}if(t.equals(r.MIN_VALUE))return r.ZERO;if(this.isNegative())return t.isNegative()?this.negate().div(t.negate()):this.negate().div(t).negate();if(t.isNegative())return this.div(t.negate()).negate();var o=r.ZERO;for(n=this;n.greaterThanOrEqual(t);){e=Math.max(1,Math.floor(n.toNumber()/t.toNumber()));for(var i=Math.ceil(Math.log(e)/Math.LN2),s=i<=48?1:Math.pow(2,i-48),a=r.fromNumber(e),u=a.multiply(t);u.isNegative()||u.greaterThan(n);)e-=s,u=(a=r.fromNumber(e)).multiply(t);a.isZero()&&(a=r.ONE),o=o.add(a),n=n.subtract(u)}return o},r.prototype.modulo=function(t){return this.subtract(this.div(t).multiply(t))},r.prototype.not=function(){return r.fromBits(~this.low_,~this.high_)},r.prototype.and=function(t){return r.fromBits(this.low_&t.low_,this.high_&t.high_)},r.prototype.or=function(t){return r.fromBits(this.low_|t.low_,this.high_|t.high_)},r.prototype.xor=function(t){return r.fromBits(this.low_^t.low_,this.high_^t.high_)},r.prototype.shiftLeft=function(t){if(0===(t&=63))return this;var e=this.low_;if(t<32){var n=this.high_;return r.fromBits(e<>>32-t)}return r.fromBits(0,e<>>t|e<<32-t,e>>t)}return r.fromBits(e>>t-32,e>=0?0:-1)},r.prototype.shiftRightUnsigned=function(t){if(0===(t&=63))return this;var e=this.high_;if(t<32){var n=this.low_;return r.fromBits(n>>>t|e<<32-t,e>>>t)}return 32===t?r.fromBits(e,0):r.fromBits(e>>>t-32,0)},r.fromInt=function(t){if(-128<=t&&t<128){var e=r.INT_CACHE_[t];if(e)return e}var n=new r(0|t,t<0?-1:0);return-128<=t&&t<128&&(r.INT_CACHE_[t]=n),n},r.fromNumber=function(t){return isNaN(t)||!isFinite(t)?r.ZERO:t<=-r.TWO_PWR_63_DBL_?r.MIN_VALUE:t+1>=r.TWO_PWR_63_DBL_?r.MAX_VALUE:t<0?r.fromNumber(-t).negate():new r(t%r.TWO_PWR_32_DBL_|0,t/r.TWO_PWR_32_DBL_|0)},r.fromBits=function(t,e){return new r(t,e)},r.fromString=function(t,e){if(0===t.length)throw Error("number format error: empty string");var n=e||10;if(n<2||36=0)throw Error('number format error: interior "-" character: '+t);for(var o=r.fromNumber(Math.pow(n,8)),i=r.ZERO,s=0;s>8&255,o[1]=t>>16&255,o[0]=t>>24&255,o[6]=255&s,o[5]=s>>8&255,o[4]=s>>16&255,o[8]=255&e,o[7]=e>>8&255,o[11]=255&r,o[10]=r>>8&255,o[9]=r>>16&255,o},c.prototype.toString=function(t){return this.id&&this.id.copy?this.id.toString("string"==typeof t?t:"hex"):this.toHexString()},c.prototype[o]=c.prototype.toString,c.prototype.toJSON=function(){return this.toHexString()},c.prototype.equals=function(t){return t instanceof c?this.toString()===t.toString():"string"==typeof t&&c.isValid(t)&&12===t.length&&this.id instanceof h?t===this.id.toString("binary"):"string"==typeof t&&c.isValid(t)&&24===t.length?t.toLowerCase()===this.toHexString():"string"==typeof t&&c.isValid(t)&&12===t.length?t===this.id:!(null==t||!(t instanceof c||t.toHexString))&&t.toHexString()===this.toHexString()},c.prototype.getTimestamp=function(){var t=new Date,e=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return t.setTime(1e3*Math.floor(e)),t},c.index=~~(16777215*Math.random()),c.createPk=function(){return new c},c.createFromTime=function(t){var e=i.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);return e[3]=255&t,e[2]=t>>8&255,e[1]=t>>16&255,e[0]=t>>24&255,new c(e)};var p=[];for(f=0;f<10;)p[48+f]=f++;for(;f<16;)p[55+f]=p[87+f]=f++;var h=e,y=function(t){return t.toString("hex")};c.createFromHexString=function(t){if(void 0===t||null!=t&&24!==t.length)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(u)return new c(i.toBuffer(t,"hex"));for(var e=new h(12),r=0,n=0;n<24;)e[r++]=p[t.charCodeAt(n++)]<<4|p[t.charCodeAt(n++)];return new c(e)},c.isValid=function(t){return null!=t&&("number"==typeof t||("string"==typeof t?12===t.length||24===t.length&&a.test(t):t instanceof c||(t instanceof h||"function"==typeof t.toHexString&&(t.id instanceof h||"string"==typeof t.id)&&(12===t.id.length||24===t.id.length&&a.test(t.id)))))},Object.defineProperty(c.prototype,"generationTime",{enumerable:!0,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(t){this.id[3]=255&t,this.id[2]=t>>8&255,this.id[1]=t>>16&255,this.id[0]=t>>24&255}}),t.exports=c,t.exports.ObjectID=c,t.exports.ObjectId=c}).call(this,r(2).Buffer,r(11))},function(t,e){function r(t,e){if(!(this instanceof r))return new r;this._bsontype="BSONRegExp",this.pattern=t||"",this.options=e||"";for(var n=0;n=7e3)throw new Error(t+" not a valid Decimal128 string");var k=t.match(o),B=t.match(i),C=t.match(s);if(!k&&!B&&!C||0===t.length)throw new Error(t+" not a valid Decimal128 string");if(k&&k[4]&&void 0===k[2])throw new Error(t+" not a valid Decimal128 string");if("+"!==t[N]&&"-"!==t[N]||(r="-"===t[N++]),!h(t[N])&&"."!==t[N]){if("i"===t[N]||"I"===t[N])return new d(p.toBuffer(r?c:l));if("N"===t[N])return new d(p.toBuffer(u))}for(;h(t[N])||"."===t[N];)if("."!==t[N])S<34&&("0"!==t[N]||_)&&(_||(w=m),_=!0,O[A++]=parseInt(t[N],10),S+=1),_&&(g+=1),y&&(b+=1),m+=1,N+=1;else{if(y)return new d(p.toBuffer(u));y=!0,N+=1}if(y&&!m)throw new Error(t+" not a valid Decimal128 string");if("e"===t[N]||"E"===t[N]){var R=t.substr(++N).match(f);if(!R||!R[2])return new d(p.toBuffer(u));j=parseInt(R[0],10),N+=R[0].length}if(t[N])return new d(p.toBuffer(u));if($=0,S){if(E=S-1,v=g,0!==j&&1!==v)for(;"0"===t[w+v-1];)v-=1}else $=0,E=0,O[0]=0,g=1,S=1,v=0;for(j<=b&&b-j>16384?j=-6176:j-=b;j>6111;){if((E+=1)-$>34){var D=O.join("");if(D.match(/^0+$/)){j=6111;break}return new d(p.toBuffer(r?c:l))}j-=1}for(;j<-6176||S=5&&(F=1,5===I))for(F=O[E]%2==1,P=w+E+2;P=0&&++O[L]>9;L--)if(O[L]=0,0===L){if(!(j<6111))return new d(p.toBuffer(r?c:l));j+=1,O[L]=1}}if(x=n.fromNumber(0),T=n.fromNumber(0),0===v)x=n.fromNumber(0),T=n.fromNumber(0);else if(E-$<17)for(L=$,T=n.fromNumber(O[L++]),x=new n(0,0);L<=E;L++)T=(T=T.multiply(n.fromNumber(10))).add(n.fromNumber(O[L]));else{for(L=$,x=n.fromNumber(O[L++]);L<=E-17;L++)x=(x=x.multiply(n.fromNumber(10))).add(n.fromNumber(O[L]));for(T=n.fromNumber(O[L++]);L<=E;L++)T=(T=T.multiply(n.fromNumber(10))).add(n.fromNumber(O[L]))}var U,V,q,W,H=function(t,e){if(!t&&!e)return{high:n.fromNumber(0),low:n.fromNumber(0)};var r=t.shiftRightUnsigned(32),o=new n(t.getLowBits(),0),i=e.shiftRightUnsigned(32),s=new n(e.getLowBits(),0),a=r.multiply(i),u=r.multiply(s),c=o.multiply(i),l=o.multiply(s);return a=a.add(u.shiftRightUnsigned(32)),u=new n(u.getLowBits(),0).add(c).add(l.shiftRightUnsigned(32)),{high:a=a.add(u.shiftRightUnsigned(32)),low:l=u.shiftLeft(32).add(new n(l.getLowBits(),0))}}(x,n.fromString("100000000000000000"));H.low=H.low.add(T),U=H.low,V=T,q=U.high_>>>0,W=V.high_>>>0,(q>>0>>0)&&(H.high=H.high.add(n.fromNumber(1))),e=j+a;var Y={low:n.fromNumber(0),high:n.fromNumber(0)};H.high.shiftRightUnsigned(49).and(n.fromNumber(1)).equals(n.fromNumber)?(Y.high=Y.high.or(n.fromNumber(3).shiftLeft(61)),Y.high=Y.high.or(n.fromNumber(e).and(n.fromNumber(16383).shiftLeft(47))),Y.high=Y.high.or(H.high.and(n.fromNumber(0x7fffffffffff)))):(Y.high=Y.high.or(n.fromNumber(16383&e).shiftLeft(49)),Y.high=Y.high.or(H.high.and(n.fromNumber(562949953421311)))),Y.low=H.low,r&&(Y.high=Y.high.or(n.fromString("9223372036854775808")));var K=p.allocBuffer(16);return N=0,K[N++]=255&Y.low.low_,K[N++]=Y.low.low_>>8&255,K[N++]=Y.low.low_>>16&255,K[N++]=Y.low.low_>>24&255,K[N++]=255&Y.low.high_,K[N++]=Y.low.high_>>8&255,K[N++]=Y.low.high_>>16&255,K[N++]=Y.low.high_>>24&255,K[N++]=255&Y.high.low_,K[N++]=Y.high.low_>>8&255,K[N++]=Y.high.low_>>16&255,K[N++]=Y.high.low_>>24&255,K[N++]=255&Y.high.high_,K[N++]=Y.high.high_>>8&255,K[N++]=Y.high.high_>>16&255,K[N++]=Y.high.high_>>24&255,new d(K)};a=6176,d.prototype.toString=function(){for(var t,e,r,o,i,s,u=0,c=new Array(36),l=0;l>26&31)>>3==3){if(30===i)return b.join("")+"Infinity";if(31===i)return"NaN";s=t>>15&16383,h=8+(t>>14&1)}else h=t>>14&7,s=t>>17&16383;if(f=s-a,g.parts[0]=(16383&t)+((15&h)<<14),g.parts[1]=e,g.parts[2]=r,g.parts[3]=o,0===g.parts[0]&&0===g.parts[1]&&0===g.parts[2]&&0===g.parts[3])m=!0;else for(_=3;_>=0;_--){var O=0,S=y(g);if(g=S.quotient,O=S.rem.low_)for(d=8;d>=0;d--)c[9*_+d]=O%10,O=Math.floor(O/10)}if(m)u=1,c[v]=0;else for(u=36,l=0;!c[v];)l++,u-=1,v+=1;if((p=u-1+f)>=34||p<=-7||f>0){for(b.push(c[v++]),(u-=1)&&b.push("."),l=0;l0?b.push("+"+p):b.push(p)}else if(f>=0)for(l=0;l0)for(l=0;l=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,s=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return s=t.done,t},e:function(t){u=!0,i=t},f:function(){try{s||null==r.return||r.return()}finally{if(u)throw i}}}}function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0){e&&(this.nested[e.substr(0,e.length-1)]=!0);var u=new N(a),c=Object.assign({},t[o],{type:u});this.path(e+o,c)}else e&&(this.nested[e.substr(0,e.length-1)]=!0),this.path(e+o,t[o])}else e&&(this.nested[e.substr(0,e.length-1)]=!0),this.path(e+o,t[o])}}return function(t,e){var r,n=s(e=e||Object.keys(t.paths));try{for(n.s();!(r=n.n()).done;){var o=r.value,i=v(t.paths[o],"options");if(null!=i){var a=t.paths[o].path,u=i.alias;if(u){if("string"!=typeof u)throw new Error("Invalid value for alias option on "+a+", got "+u);t.aliases[u]=a,t.virtual(u).get(function(t){return function(){return"function"==typeof this.get?this.get(t):this[t]}}(a)).set(function(t){return function(e){return this.$set(t,e)}}(a))}}}}catch(t){n.e(t)}finally{n.f()}}(this,Object.keys(t).map((function(t){return e?e+t:t}))),this},N.reserved=Object.create(null),N.prototype.reserved=N.reserved;var k=N.reserved; +/*! + * ignore + */ +function B(t){return/\.\d+/.test(t)?t.replace(/\.\d+\./g,".$.").replace(/\.\d+$/,".$"):t} +/*! + * ignore + */function C(t,e){if(0===t.mapPaths.length)return null;var r,n=s(t.mapPaths);try{for(n.s();!(r=n.n()).done;){var o=r.value.path;if(new RegExp("^"+o.replace(/\.\$\*/g,"\\.[^.]+")+"$").test(e))return t.paths[o]}}catch(t){n.e(t)}finally{n.f()}return null} +/*! + * ignore. Deprecated re: #6405 + */ +function R(t,e){var r=e.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean);if(r.length<2)return t.paths.hasOwnProperty(r[0])?t.paths[r[0]]:"adhocOrUndefined";var n=t.path(r[0]),o=!1;if(!n)return"adhocOrUndefined";for(var i=r.length-1,s=1;s0?".":"")+_,h[_]||(this.nested[y]=!0,h[_]={}),"object"!==i(h[_])){var v="Cannot set nested path `"+t+"`. Parent path `"+y+"` already set to type "+h[_].name+".";throw new Error(v)}h=h[_]}}catch(t){d.e(t)}finally{d.f()}h[f]=$.clone(e),this.paths[t]=this.interpretAsType(t,e,this.options);var m=this.paths[t];if(m.$isSchemaMap){var g=t+".$*";this.paths[g]=m.$__schemaType,this.mapPaths.push(this.paths[g])}if(m.$isSingleNested){for(var b=0,w=Object.keys(m.schema.paths);b0&&!$.hasUserDefinedProperty(n.of,t.options.typeKey);a=u?o({},t.options.typeKey,new N(n.of)):$.isPOJO(n.of)?Object.assign({},n.of):o({},t.options.typeKey,n.of),$.hasUserDefinedProperty(n,"ref")&&(a.ref=n.ref)}e.$__schemaType=t.interpretAsType(s,a,i)}(this,v,t,e,r),v},N.prototype.eachPath=function(t){for(var e=Object.keys(this.paths),r=e.length,n=0;n0?t+"."+e[r]:e[r],this.paths.hasOwnProperty(t)&&this.paths[t]instanceof u.Mixed)return this.paths[t];return null},N.prototype.setupTimestamp=function(t){return A(this,t)},N.prototype.queue=function(t,e){return this.callQueue.push([t,e]),this},N.prototype.pre=function(t){if(t instanceof RegExp){var e,r=Array.prototype.slice.call(arguments,1),n=s(x);try{for(n.s();!(e=n.n()).done;){var o=e.value;t.test(o)&&this.pre.apply(this,[o].concat(r))}}catch(t){n.e(t)}finally{n.f()}return this}if(Array.isArray(t)){var i,a=Array.prototype.slice.call(arguments,1),u=s(t);try{for(u.s();!(i=u.n()).done;){var c=i.value;this.pre.apply(this,[c].concat(a))}}catch(t){u.e(t)}finally{u.f()}return this}return this.s.hooks.pre.apply(this.s.hooks,arguments),this},N.prototype.post=function(t){if(t instanceof RegExp){var e,r=Array.prototype.slice.call(arguments,1),n=s(x);try{for(n.s();!(e=n.n()).done;){var o=e.value;t.test(o)&&this.post.apply(this,[o].concat(r))}}catch(t){n.e(t)}finally{n.f()}return this}if(Array.isArray(t)){var i,a=Array.prototype.slice.call(arguments,1),u=s(t);try{for(u.s();!(i=u.n()).done;){var c=i.value;this.post.apply(this,[c].concat(a))}}catch(t){u.e(t)}finally{u.f()}return this}return this.s.hooks.post.apply(this.s.hooks,arguments),this},N.prototype.plugin=function(t,e){if("function"!=typeof t)throw new Error('First param to `schema.plugin()` must be a function, got "'+i(t)+'"');if(e&&e.deduplicate){var r,n=s(this.plugins);try{for(n.s();!(r=n.n()).done;){if(r.value.fn===t)return this}}catch(t){n.e(t)}finally{n.f()}}return this.plugins.push({fn:t,opts:e}),t(this,e),this},N.prototype.method=function(t,e,r){if("string"!=typeof t)for(var n in t)this.methods[n]=t[n],this.methodOptions[n]=$.clone(r);else this.methods[t]=e,this.methodOptions[t]=$.clone(r);return this},N.prototype.static=function(t,e){if("string"!=typeof t)for(var r in t)this.statics[r]=t[r];else this.statics[t]=e;return this},N.prototype.index=function(t,e){return t||(t={}),e||(e={}),e.expires&&$.expires(e),this._indexes.push([t,e]),this},N.prototype.set=function(t,e,r){if(1===arguments.length)return this.options[t];switch(t){case"read":this.options[t]=S(e,r),this._userProvidedOptions[t]=this.options[t];break;case"timestamps":this.setupTimestamp(e),this.options[t]=e,this._userProvidedOptions[t]=this.options[t];break;case"_id":this.options[t]=e,this._userProvidedOptions[t]=this.options[t],e&&!this.paths._id?_(this):!e&&null!=this.paths._id&&this.paths._id.auto&&this.remove("_id");break;default:this.options[t]=e,this._userProvidedOptions[t]=this.options[t]}return this},N.prototype.get=function(t){return this.options[t]};var D="2d 2dsphere hashed text".split(" "); +/*! + * ignore + */ +function M(t,e){var r,n=e.split("."),o=n.pop(),i=t.tree,a=s(n);try{for(a.s();!(r=a.n()).done;){i=i[r.value]}}catch(t){a.e(t)}finally{a.f()}delete i[o]} +/*! + * ignore + */ +function I(t){return t.startsWith("$[")&&t.endsWith("]")} +/*! + * Called by `compile()` _right before_ compiling. Good for making any changes to + * the schema that should respect options set by plugins, like `id` + */Object.defineProperty(N,"indexTypes",{get:function(){return D},set:function(){throw new Error("Cannot overwrite Schema.indexTypes")}}),N.prototype.indexes=function(){return g(this)},N.prototype.virtual=function(t,e){if(t instanceof d||"VirtualType"===m(t))return this.virtual(t.path,t.options);if(e=new y(e),$.hasUserDefinedProperty(e,["ref","refPath"])){if(null==e.localField)throw new Error("Reference virtuals require `localField` option");if(null==e.foreignField)throw new Error("Reference virtuals require `foreignField` option");this.pre("init",(function(r){if(O.has(t,r)){var n=O.get(t,r);this.$$populatedVirtuals||(this.$$populatedVirtuals={}),e.justOne||e.count?this.$$populatedVirtuals[t]=Array.isArray(n)?n[0]:n:this.$$populatedVirtuals[t]=Array.isArray(n)?n:null==n?[]:[n],O.unset(t,r)}}));var r=this.virtual(t);r.options=e,r.set((function(r){this.$$populatedVirtuals||(this.$$populatedVirtuals={}),e.justOne||e.count?(this.$$populatedVirtuals[t]=Array.isArray(r)?r[0]:r,"object"!==i(this.$$populatedVirtuals[t])&&(this.$$populatedVirtuals[t]=e.count?r:null)):(this.$$populatedVirtuals[t]=Array.isArray(r)?r:null==r?[]:[r],this.$$populatedVirtuals[t]=this.$$populatedVirtuals[t].filter((function(t){return t&&"object"===i(t)})))})),"function"==typeof e.get&&r.get(e.get);for(var n=t.split("."),o=n[0],s=0;s=e.length?o:s+1>=e.length?o.$__schemaType:t(e.slice(s+1),o.$__schemaType.schema)}return o.$fullPath=r.join("."),o}}(n,this)}, +/*! + * ignore + */ +N.prototype._getPathType=function(t){if(this.path(t))return"real";return function t(e,r){for(var n,o,i=e.length+1;i--;){if(o=e.slice(0,i).join("."),n=r.path(o))return n.caster?n.caster instanceof u.Mixed?{schema:n,pathType:"mixed"}:i!==e.length&&n.schema?"$"===e[i]||I(e[i])?i===e.length-1?{schema:n,pathType:"nested"}:t(e.slice(i+1),n.schema):t(e.slice(i),n.schema):{schema:n,pathType:n.$isSingleNested?"nested":"array"}:{schema:n,pathType:"real"};if(i===e.length&&r.nested[o])return{schema:r,pathType:"nested"}}return{schema:n||r,pathType:"undefined"}}(t.split("."),this)},N.prototype._preCompile=function(){b(this)}, +/*! + * Module exports. + */ +t.exports=e=N,N.Types=u=r(55), +/*! + * ignore + */ +e.ObjectId=u.ObjectId}).call(this,r(2).Buffer)},function(t,e,r){"use strict";function n(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return o(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0,i=function(){};return{s:i,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0||this.setters.length>0)){var t="$"+this.path;this.getters.push((function(){return this[t]})),this.setters.push((function(e){this[t]=e}))}}, +/*! + * ignore + */ +s.prototype.clone=function(){var t=new s(this.options,this.path);return t.getters=[].concat(this.getters),t.setters=[].concat(this.setters),t},s.prototype.get=function(t){return this.getters.push(t),this},s.prototype.set=function(t){return this.setters.push(t),this},s.prototype.applyGetters=function(t,e){i.hasUserDefinedProperty(this.options,["ref","refPath"])&&e.$$populatedVirtuals&&e.$$populatedVirtuals.hasOwnProperty(this.path)&&(t=e.$$populatedVirtuals[this.path]);var r,o=t,s=n(this.getters);try{for(s.s();!(r=s.n()).done;){o=r.value.call(e,o,this,e)}}catch(t){s.e(t)}finally{s.f()}return o},s.prototype.applySetters=function(t,e){var r,o=t,i=n(this.setters);try{for(i.s();!(r=i.n()).done;){o=r.value.call(e,o,this,e)}}catch(t){i.e(t)}finally{i.f()}return o}, +/*! + * exports + */ +t.exports=s},function(t,e,r){"use strict"; +/*! + * Module exports. + */e.String=r(153),e.Number=r(81),e.Boolean=r(157),e.DocumentArray=r(158),e.Subdocument=r(165),e.Array=r(56),e.Buffer=r(167),e.Date=r(169),e.ObjectId=r(172),e.Mixed=r(27),e.Decimal128=e.Decimal=r(174),e.Map=r(176),e.Oid=e.ObjectId,e.Object=e.Mixed,e.Bool=e.Boolean,e.ObjectID=e.ObjectId},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return o(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0,i=function(){};return{s:i,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0){var s=y(t);if(s.min===s.max&&s.max=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0?t:r)}return this},_registerAtomic:function(t,e){if(!this[m]){if("$set"===t)return this[h]={$set:e},c(this[y],this[d]),this._markModified(),this;var r,n=this[h];if("$pop"===t&&!("$pop"in n)){var o=this;this[y].once("save",(function(){o._popped=o._shifted=null}))}if(n.$set||Object.keys(n).length&&!(t in n))return this[h]={$set:this},this;if("$pullAll"===t||"$addToSet"===t)n[t]||(n[t]=[]),n[t]=n[t].concat(e);else if("$pullDocs"===t){var i=n.$pull||(n.$pull={});e[0]instanceof s?(r=i.$or||(i.$or=[]),Array.prototype.push.apply(r,e.map((function(t){return t.toObject({transform:!1,virtuals:!1})})))):(r=i._id||(i._id={$in:[]})).$in=r.$in.concat(e)}else"$push"===t?(n.$push=n.$push||{$each:[]},null!=e&&p.hasUserDefinedProperty(e,"$each")?n.$push=e:n.$push.$each=n.$push.$each.concat(e)):n[t]=e;return this}},addToSet:function(){w(this,arguments);var t=[].map.call(arguments,this._mapCast,this);t=this[_].applySetters(t,this[y]);var e=[],r="";t[0]instanceof s?r="doc":t[0]instanceof Date&&(r="date");var n=t.isMongooseArrayProxy?t.__array:this,o=this.isMongooseArrayProxy?this.__array:this;return n.forEach((function(t){var n,i=+t;switch(r){case"doc":n=this.some((function(e){return e.equals(t)}));break;case"date":n=this.some((function(t){return+t===i}));break;default:n=~this.indexOf(t)}n||(o.push(t),this._registerAtomic("$addToSet",t),this._markModified(),[].push.call(e,t))}),this),e},hasAtomics:function(){return p.isPOJO(this[h])?Object.keys(this[h]).length:0},includes:function(t,e){return-1!==this.indexOf(t,e)},indexOf:function(t,e){t instanceof u&&(t=t.toString()),e=null==e?0:e;for(var r=this.length,n=e;n0&&this._registerAtomic("$set",this),this},push:function(){var t=arguments,e=t,r=null!=t[0]&&p.hasUserDefinedProperty(t[0],"$each"),n=this.isMongooseArrayProxy?this.__array:this;if(r&&(e=t[0],t=t[0].$each),null==this[_])return g.apply(this,t);w(this,t);var o,i=this[y];t=[].map.call(t,this._mapCast,this),t=this[_].applySetters(t,i,void 0,void 0,{skipDocumentArrayCast:!0});var s=this[h];if(r){if(e.$each=t,l(s,"$push.$each.length",0)>0&&s.$push.$position!=e.$position)throw new a("Cannot call `Array#push()` multiple times with different `$position`");null!=e.$position?([].splice.apply(n,[e.$position,0].concat(t)),o=this.length):o=[].push.apply(n,t)}else{if(l(s,"$push.$each.length",0)>0&&null!=s.$push.$position)throw new a("Cannot call `Array#push()` multiple times with different `$position`");e=t,o=[].push.apply(n,t)}return this._registerAtomic("$push",e),this._markModified(),o},remove:function(){return this.pull.apply(this,arguments)},set:function(t,e,r){var n=this.__array;if(r)return n[t]=e,this;var o=b._cast.call(this,e,t);return n[t]=o,b._markModified.call(this,t),this},shift:function(){var t=this.isMongooseArrayProxy?this.__array:this,e=[].shift.call(t);return this._registerAtomic("$set",this),this._markModified(),e},sort:function(){var t=this.isMongooseArrayProxy?this.__array:this,e=[].sort.apply(t,arguments);return this._registerAtomic("$set",this),e},splice:function(){var t,e=this.isMongooseArrayProxy?this.__array:this;if(w(this,Array.prototype.slice.call(arguments,2)),arguments.length){var r;if(null==this[_])r=arguments;else{r=[];for(var n=0;n0&& +/*! + * ignore + */ +function(t,e){if(!e)return!1;var r,o=n(t);try{for(o.s();!(r=o.n()).done;){var s=r.value;if(null==s)return!1;var a=s.constructor;if(!(s instanceof i)||a.modelName!==e&&a.baseModelName!==e)return!1}}catch(t){o.e(t)}finally{o.f()}return!0}(e,a)&&t[y].$populated(t[d],[],(r={},o=v,s=e[0].constructor,o in r?Object.defineProperty(r,o,{value:s,enumerable:!0,configurable:!0,writable:!0}):r[o]=s,r))}for(var O=function(){var t=A[S];if(null==Array.prototype[t])return"continue";b[t]=function(){var e=this.isMongooseArrayProxy?this.__array:this,r=[].concat(e);return r[t].apply(r,arguments)}},S=0,A=["filter","flat","flatMap","map","slice"];Si;)n[o-i]=t[o];return n}},function(t,e){function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var n=Object.prototype.toString;t.exports=function(t){if("object"!=r(e=t)||"[object RegExp]"!=n.call(e))throw new TypeError("Not a RegExp");var e,o=[];t.global&&o.push("g"),t.multiline&&o.push("m"),t.ignoreCase&&o.push("i"),t.dotAll&&o.push("s"),t.unicode&&o.push("u"),t.sticky&&o.push("y");var i=new RegExp(t.source,o.join(""));return"number"==typeof t.lastIndex&&(i.lastIndex=t.lastIndex),i}},function(t,e,r){"use strict";t.exports=function(t){return t.name?t.name:(t.toString().trim().match(/^function\s*([^\s(]+)/)||[])[1]}},function(t,e,r){"use strict";var n=r(3); +/*! + * Get the bson type, if it exists + */t.exports=function(t,e){return n(t,"_bsontype",void 0)===e}},function(t,e,r){"use strict";function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var o=Symbol("mongoose#trustedSymbol");e.trustedSymbol=o,e.trusted=function(t){return null==t||"object"!==n(t)||(t[o]=!0),t}},function(t,e,r){"use strict";(function(e){ +/*! + * ignore + */ +var n=r(21),o=r(120),i={_promise:null,get:function(){return i._promise},set:function(t){n.ok("function"==typeof t,"mongoose.Promise must be a function, got ".concat(t)),i._promise=t,o.Promise=t}}; +/*! + * Use native promises by default + */ +i.set(e.Promise),t.exports=i}).call(this,r(10))},function(t,e,r){"use strict";(function(t,n){ +/*! + * Module dependencies. + */ +function o(t){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var i=r(122).Buffer,s=r(64),a=["__proto__","constructor","prototype"],u=e.clone=function t(r,n){if(null==r)return r;if(Array.isArray(r))return e.cloneArray(r,n);if(r.constructor){if(/ObjectI[dD]$/.test(r.constructor.name))return"function"==typeof r.clone?r.clone():new r.constructor(r.id);if("ReadPreference"===r.constructor.name)return new r.constructor(r.mode,t(r.tags,n));if("Binary"==r._bsontype&&r.buffer&&r.value)return"function"==typeof r.clone?r.clone():new r.constructor(r.value(!0),r.sub_type);if("Date"===r.constructor.name||"Function"===r.constructor.name)return new r.constructor(+r);if("RegExp"===r.constructor.name)return s(r);if("Buffer"===r.constructor.name)return e.cloneBuffer(r)}return l(r)?e.cloneObject(r,n):r.valueOf?r.valueOf():void 0}; +/*! + * ignore + */ +e.cloneObject=function(t,e){for(var r,n,o=e&&e.minimize,i={},s=0,c=Object.keys(t);s1)throw new Error("Adding properties is not supported");function e(){}return e.prototype=t,new e},e.inherits=function(t,r){t.prototype=e.create(r.prototype),t.prototype.constructor=t};var f=e.soon="function"==typeof t?t:n.nextTick;e.cloneBuffer=function(t){var e=i.alloc(t.length);return t.copy(e,0,0,t.length),e},e.isArgumentsObject=function(t){return"[object Arguments]"===Object.prototype.toString.call(t)}}).call(this,r(70).setImmediate,r(11))},function(t,e,r){(function(t){var n=void 0!==t&&t||"undefined"!=typeof self&&self||window,o=Function.prototype.apply;function i(t,e){this._id=t,this._clearFn=e}e.setTimeout=function(){return new i(o.call(setTimeout,n,arguments),clearTimeout)},e.setInterval=function(){return new i(o.call(setInterval,n,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},i.prototype.unref=i.prototype.ref=function(){},i.prototype.close=function(){this._clearFn.call(n,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout((function(){t._onTimeout&&t._onTimeout()}),e))},r(121),e.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||this&&this.setImmediate,e.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||this&&this.clearImmediate}).call(this,r(10))},function(t,e,r){"use strict";(function(t,r,n,o){function i(t){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}e.isNode=void 0!==t&&"object"==i(r)&&"object"==(void 0===n?"undefined":i(n))&&"function"==typeof o&&t.argv,e.isMongo=!e.isNode&&"function"==typeof printjson&&"function"==typeof ObjectId&&"function"==typeof rs&&"function"==typeof sh,e.isBrowser=!e.isNode&&!e.isMongo&&"undefined"!=typeof window,e.type=e.isNode?"node":e.isMongo?"mongo":e.isBrowser?"browser":"unknown"}).call(this,r(11),r(127)(t),r(10),r(2).Buffer)},function(t,e,r){"use strict";t.exports=function(t,e,r){for(var n={},o=0,i=Object.keys(e.tree);o=t},message:r,type:"min",min:t})}return this},l.prototype.max=function(t,e){if(this.maxValidator&&(this.validators=this.validators.filter((function(t){return t.validator!==this.maxValidator}),this)),null!=t){var r=e||n.messages.Number.max;r=r.replace(/{MAX}/,t),this.validators.push({validator:this.maxValidator=function(e){return null==e||e<=t},message:r,type:"max",max:t})}return this},l.prototype.enum=function(t,e){if(this.enumValidator&&(this.validators=this.validators.filter((function(t){return t.validator!==this.enumValidator}),this)),!Array.isArray(t)){var r=u.isPOJO(t)&&null!=t.values;r?(e=t.message,t=t.values):"number"==typeof t&&(t=Array.prototype.slice.call(arguments),e=null),u.isPOJO(t)&&(t=Object.values(t)),e=e||n.messages.Number.enum}return e=null==e?n.messages.Number.enum:e,this.enumValidator=function(e){return null==e||-1!==t.indexOf(e)},this.validators.push({validator:this.enumValidator,message:e,type:"enum",enumValues:t}),this},l.prototype.cast=function(t,e,r){if(i._isRef(this,t,e,r))return"number"==typeof t?t:this._castRef(t,e,r);var n,o=t&&void 0!==t._id?t._id:t;n="function"==typeof this._castFunction?this._castFunction:"function"==typeof this.constructor.cast?this.constructor.cast():l.cast();try{return n(o)}catch(t){throw new c("Number",o,this.path,t,this)}},l.prototype.$conditionalHandlers=u.options(i.prototype.$conditionalHandlers,{$bitsAllClear:a,$bitsAnyClear:a,$bitsAllSet:a,$bitsAnySet:a,$gt:f,$gte:f,$lt:f,$lte:f,$mod:function(t){var e=this;return Array.isArray(t)?t.map((function(t){return e.cast(t)})):[this.cast(t)]}}),l.prototype.castForQuery=function(t,e){var r;if(2===arguments.length){if(!(r=this.$conditionalHandlers[t]))throw new c("number",e,this.path,null,this);return r.call(this,e)}return e=this._castForQuery(t)}, +/*! + * Module exports. + */ +t.exports=l},function(t,e,r){"use strict";(function(e){ +/*! + * Module requirements. + */ +var n=r(13); +/*! + * ignore + */ +/*! + * ignore + */ +function o(t,e){var r=Number(e);if(isNaN(r))throw new n("number",e,t);return r}t.exports=function(t){var r=this;return Array.isArray(t)?t.map((function(t){return o(r.path,t)})):e.isBuffer(t)?t:o(r.path,t)}}).call(this,r(2).Buffer)},function(t,e,r){"use strict";var n=r(84); +/*! +* returns discriminator by discriminatorMapping.value +* +* @param {Schema} schema +* @param {string} value +*/t.exports=function(t,e){if(null==t||null==t.discriminators)return null;for(var r=0,o=Object.keys(t.discriminators);r0&&this._markModified(),t},copy:function(t){var r=e.prototype.copy.apply(this,arguments);return t&&t.isMongooseBuffer&&t._markModified(),r}}, +/*! + * Compile other Buffer methods marking this buffer as modified. + */ +"writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 writeFloat writeDouble fill utf8Write binaryWrite asciiWrite set writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE writeInt16LE writeInt16BE writeInt32LE writeInt32BE writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE".split(" ").forEach((function(t){e.prototype[t]&&(i.mixin[t]=function(){var r=e.prototype[t].apply(this,arguments);return this._markModified(),r})})),i.mixin.toObject=function(t){var r="number"==typeof t?t:this._subtype||0;return new n(e.from(this),r)},i.mixin.$toObject=i.mixin.toObject,i.mixin.toBSON=function(){return new n(this,this._subtype||0)},i.mixin.equals=function(t){if(!e.isBuffer(t))return!1;if(this.length!==t.length)return!1;for(var r=0;r=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0?s-4:s;for(r=0;r>16&255,u[l++]=e>>8&255,u[l++]=255&e;2===a&&(e=o[t.charCodeAt(r)]<<2|o[t.charCodeAt(r+1)]>>4,u[l++]=255&e);1===a&&(e=o[t.charCodeAt(r)]<<10|o[t.charCodeAt(r+1)]<<4|o[t.charCodeAt(r+2)]>>2,u[l++]=e>>8&255,u[l++]=255&e);return u},e.fromByteArray=function(t){for(var e,r=t.length,o=r%3,i=[],s=0,a=r-o;sa?a:s+16383));1===o?(e=t[r-1],i.push(n[e>>2]+n[e<<4&63]+"==")):2===o&&(e=(t[r-2]<<8)+t[r-1],i.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return i.join("")};for(var n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function l(t,e,r){for(var o,i,s=[],a=e;a>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},function(t,e){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +e.read=function(t,e,r,n,o){var i,s,a=8*o-n-1,u=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,h=t[e+f];for(f+=p,i=h&(1<<-l)-1,h>>=-l,l+=a;l>0;i=256*i+t[e+f],f+=p,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=n;l>0;s=256*s+t[e+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===u)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,n),i-=c}return(h?-1:1)*s*Math.pow(2,i-n)},e.write=function(t,e,r,n,o,i){var s,a,u,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,y=n?1:-1,d=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=l):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+f>=1?p/u:p*Math.pow(2,1-f))*u>=2&&(s++,u/=2),s+f>=l?(a=0,s=l):s+f>=1?(a=(e*u-1)*Math.pow(2,o),s+=f):(a=e*Math.pow(2,f-1)*Math.pow(2,o),s=0));o>=8;t[r+h]=255&a,h+=y,a/=256,o-=8);for(s=s<0;t[r+h]=255&s,h+=y,s/=256,c-=8);t[r+h-y]|=128*d}},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e,r){"use strict"; +/*! + * Module exports. + */e.Binary=r(102),e.Collection=function(){throw new Error("Cannot create a collection from browser library")},e.getConnection=function(){return function(){throw new Error("Cannot create a connection from browser library")}},e.Decimal128=r(109),e.ObjectId=r(110),e.ReadPreference=r(111)},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */var n=r(38).Binary; +/*! + * Module exports. + */t.exports=n},function(t,e){function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}t.exports=function(t){return t&&"object"===r(t)&&"function"==typeof t.copy&&"function"==typeof t.fill&&"function"==typeof t.readUInt8}},function(t,e){"function"==typeof Object.create?t.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},function(module,exports,__webpack_require__){"use strict";var Long=__webpack_require__(24).Long,Double=__webpack_require__(39).Double,Timestamp=__webpack_require__(40).Timestamp,ObjectID=__webpack_require__(41).ObjectID,_Symbol=__webpack_require__(43).Symbol,Code=__webpack_require__(44).Code,MinKey=__webpack_require__(46).MinKey,MaxKey=__webpack_require__(47).MaxKey,Decimal128=__webpack_require__(45),Int32=__webpack_require__(62),DBRef=__webpack_require__(48).DBRef,BSONRegExp=__webpack_require__(42).BSONRegExp,Binary=__webpack_require__(29).Binary,utils=__webpack_require__(16),deserialize=function(t,e,r){var n=(e=null==e?{}:e)&&e.index?e.index:0,o=t[n]|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24;if(o<5||t.lengtht.length)throw new Error("corrupt bson message");if(0!==t[n+o-1])throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return deserializeObject(t,n,e,r)},deserializeObject=function t(e,r,n,o){var i=null!=n.evalFunctions&&n.evalFunctions,s=null!=n.cacheFunctions&&n.cacheFunctions,a=null!=n.cacheFunctionsCrc32&&n.cacheFunctionsCrc32;if(!a)var u=null;var c=null==n.fieldsAsRaw?null:n.fieldsAsRaw,l=null!=n.raw&&n.raw,f="boolean"==typeof n.bsonRegExp&&n.bsonRegExp,p=null!=n.promoteBuffers&&n.promoteBuffers,h=null==n.promoteLongs||n.promoteLongs,y=null==n.promoteValues||n.promoteValues,d=r;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var _=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;if(_<5||_>e.length)throw new Error("corrupt bson message");for(var v=o?[]:{},m=0;;){var g=e[r++];if(0===g)break;for(var b=r;0!==e[b]&&b=e.length)throw new Error("Bad BSON Document: illegal CString");var w=o?m++:e.toString("utf8",r,b);if(r=b+1,g===BSON.BSON_DATA_STRING){var O=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;if(O<=0||O>e.length-r||0!==e[r+O-1])throw new Error("bad string length in bson");v[w]=e.toString("utf8",r,r+O-1),r+=O}else if(g===BSON.BSON_DATA_OID){var S=utils.allocBuffer(12);e.copy(S,0,r,r+12),v[w]=new ObjectID(S),r+=12}else if(g===BSON.BSON_DATA_INT&&!1===y)v[w]=new Int32(e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24);else if(g===BSON.BSON_DATA_INT)v[w]=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;else if(g===BSON.BSON_DATA_NUMBER&&!1===y)v[w]=new Double(e.readDoubleLE(r)),r+=8;else if(g===BSON.BSON_DATA_NUMBER)v[w]=e.readDoubleLE(r),r+=8;else if(g===BSON.BSON_DATA_DATE){var A=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24,$=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;v[w]=new Date(new Long(A,$).toNumber())}else if(g===BSON.BSON_DATA_BOOLEAN){if(0!==e[r]&&1!==e[r])throw new Error("illegal boolean type value");v[w]=1===e[r++]}else if(g===BSON.BSON_DATA_OBJECT){var E=r,j=e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24;if(j<=0||j>e.length-r)throw new Error("bad embedded document length in bson");v[w]=l?e.slice(r,r+j):t(e,E,n,!1),r+=j}else if(g===BSON.BSON_DATA_ARRAY){E=r;var P=n,x=r+(j=e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24);if(c&&c[w]){for(var T in P={},n)P[T]=n[T];P.raw=!0}if(v[w]=t(e,E,P,!0),0!==e[(r+=j)-1])throw new Error("invalid array terminator byte");if(r!==x)throw new Error("corrupted array bson")}else if(g===BSON.BSON_DATA_UNDEFINED)v[w]=void 0;else if(g===BSON.BSON_DATA_NULL)v[w]=null;else if(g===BSON.BSON_DATA_LONG){A=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24,$=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;var N=new Long(A,$);v[w]=h&&!0===y&&N.lessThanOrEqual(JS_INT_MAX_LONG)&&N.greaterThanOrEqual(JS_INT_MIN_LONG)?N.toNumber():N}else if(g===BSON.BSON_DATA_DECIMAL128){var k=utils.allocBuffer(16);e.copy(k,0,r,r+16),r+=16;var B=new Decimal128(k);v[w]=B.toObject?B.toObject():B}else if(g===BSON.BSON_DATA_BINARY){var C=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24,R=C,D=e[r++];if(C<0)throw new Error("Negative binary type element size found");if(C>e.length)throw new Error("Binary type size larger than document size");if(null!=e.slice){if(D===Binary.SUBTYPE_BYTE_ARRAY){if((C=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24)<0)throw new Error("Negative binary type element size found for subtype 0x02");if(C>R-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(CR-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(C=e.length)throw new Error("Bad BSON Document: illegal CString");var I=e.toString("utf8",r,b);for(b=r=b+1;0!==e[b]&&b=e.length)throw new Error("Bad BSON Document: illegal CString");var F=e.toString("utf8",r,b);r=b+1;var L=new Array(F.length);for(b=0;b=e.length)throw new Error("Bad BSON Document: illegal CString");for(I=e.toString("utf8",r,b),b=r=b+1;0!==e[b]&&b=e.length)throw new Error("Bad BSON Document: illegal CString");F=e.toString("utf8",r,b),r=b+1,v[w]=new BSONRegExp(I,F)}else if(g===BSON.BSON_DATA_SYMBOL){if((O=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24)<=0||O>e.length-r||0!==e[r+O-1])throw new Error("bad string length in bson");v[w]=new _Symbol(e.toString("utf8",r,r+O-1)),r+=O}else if(g===BSON.BSON_DATA_TIMESTAMP)A=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24,$=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24,v[w]=new Timestamp(A,$);else if(g===BSON.BSON_DATA_MIN_KEY)v[w]=new MinKey;else if(g===BSON.BSON_DATA_MAX_KEY)v[w]=new MaxKey;else if(g===BSON.BSON_DATA_CODE){if((O=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24)<=0||O>e.length-r||0!==e[r+O-1])throw new Error("bad string length in bson");var U=e.toString("utf8",r,r+O-1);if(i)if(s){var V=a?u(U):U;v[w]=isolateEvalWithHash(functionCache,V,U,v)}else v[w]=isolateEval(U);else v[w]=new Code(U);r+=O}else if(g===BSON.BSON_DATA_CODE_W_SCOPE){var q=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;if(q<13)throw new Error("code_w_scope total size shorter minimum expected length");if((O=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24)<=0||O>e.length-r||0!==e[r+O-1])throw new Error("bad string length in bson");U=e.toString("utf8",r,r+O-1),E=r+=O,j=e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24;var W=t(e,E,n,!1);if(r+=j,q<8+j+O)throw new Error("code_w_scope total size is to short, truncating scope");if(q>8+j+O)throw new Error("code_w_scope total size is to long, clips outer document");i?(s?(V=a?u(U):U,v[w]=isolateEvalWithHash(functionCache,V,U,v)):v[w]=isolateEval(U),v[w].scope=W):v[w]=new Code(U,W)}else{if(g!==BSON.BSON_DATA_DBPOINTER)throw new Error("Detected unknown BSON type "+g.toString(16)+' for fieldname "'+w+'", are you using the latest BSON parser');if((O=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24)<=0||O>e.length-r||0!==e[r+O-1])throw new Error("bad string length in bson");var H=e.toString("utf8",r,r+O-1);r+=O;var Y=utils.allocBuffer(12);e.copy(Y,0,r,r+12),S=new ObjectID(Y),r+=12;var K=H.split("."),z=K.shift(),Q=K.join(".");v[w]=new DBRef(Q,S,z)}}if(_!==r-d){if(o)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}return null!=v.$id&&(v=new DBRef(v.$ref,v.$id,v.$db)),v},isolateEvalWithHash=function isolateEvalWithHash(functionCache,hash,functionString,object){var value=null;return null==functionCache[hash]&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},isolateEval=function isolateEval(functionString){var value=null;return eval("value = "+functionString),value},BSON={},functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1,BSON.BSON_DATA_STRING=2,BSON.BSON_DATA_OBJECT=3,BSON.BSON_DATA_ARRAY=4,BSON.BSON_DATA_BINARY=5,BSON.BSON_DATA_UNDEFINED=6,BSON.BSON_DATA_OID=7,BSON.BSON_DATA_BOOLEAN=8,BSON.BSON_DATA_DATE=9,BSON.BSON_DATA_NULL=10,BSON.BSON_DATA_REGEXP=11,BSON.BSON_DATA_DBPOINTER=12,BSON.BSON_DATA_CODE=13,BSON.BSON_DATA_SYMBOL=14,BSON.BSON_DATA_CODE_W_SCOPE=15,BSON.BSON_DATA_INT=16,BSON.BSON_DATA_TIMESTAMP=17,BSON.BSON_DATA_LONG=18,BSON.BSON_DATA_DECIMAL128=19,BSON.BSON_DATA_MIN_KEY=255,BSON.BSON_DATA_MAX_KEY=127,BSON.BSON_BINARY_SUBTYPE_DEFAULT=0,BSON.BSON_BINARY_SUBTYPE_FUNCTION=1,BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,BSON.BSON_BINARY_SUBTYPE_UUID=3,BSON.BSON_BINARY_SUBTYPE_MD5=4,BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128,BSON.BSON_INT32_MAX=2147483647,BSON.BSON_INT32_MIN=-2147483648,BSON.BSON_INT64_MAX=Math.pow(2,63)-1,BSON.BSON_INT64_MIN=-Math.pow(2,63),BSON.JS_INT_MAX=9007199254740992,BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},function(t,e,r){"use strict";(function(e){function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var o=r(107).writeIEEE754,i=r(24).Long,s=r(61),a=r(29).Binary,u=r(16).normalizedFunctionString,c=/\x00/,l=["$db","$ref","$id","$clusterTime"],f=function(t){return"object"===n(t)&&"[object Date]"===Object.prototype.toString.call(t)},p=function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},h=function(t,e,r,n,o){t[n++]=C.BSON_DATA_STRING;var i=o?t.write(e,n,"ascii"):t.write(e,n,"utf8");t[(n=n+i+1)-1]=0;var s=t.write(r,n+4,"utf8");return t[n+3]=s+1>>24&255,t[n+2]=s+1>>16&255,t[n+1]=s+1>>8&255,t[n]=s+1&255,n=n+4+s,t[n++]=0,n},y=function(t,e,r,n,s){if(Math.floor(r)===r&&r>=C.JS_INT_MIN&&r<=C.JS_INT_MAX)if(r>=C.BSON_INT32_MIN&&r<=C.BSON_INT32_MAX){t[n++]=C.BSON_DATA_INT;var a=s?t.write(e,n,"ascii"):t.write(e,n,"utf8");n+=a,t[n++]=0,t[n++]=255&r,t[n++]=r>>8&255,t[n++]=r>>16&255,t[n++]=r>>24&255}else if(r>=C.JS_INT_MIN&&r<=C.JS_INT_MAX)t[n++]=C.BSON_DATA_NUMBER,n+=a=s?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,o(t,r,n,"little",52,8),n+=8;else{t[n++]=C.BSON_DATA_LONG,n+=a=s?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var u=i.fromNumber(r),c=u.getLowBits(),l=u.getHighBits();t[n++]=255&c,t[n++]=c>>8&255,t[n++]=c>>16&255,t[n++]=c>>24&255,t[n++]=255&l,t[n++]=l>>8&255,t[n++]=l>>16&255,t[n++]=l>>24&255}else t[n++]=C.BSON_DATA_NUMBER,n+=a=s?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,o(t,r,n,"little",52,8),n+=8;return n},d=function(t,e,r,n,o){return t[n++]=C.BSON_DATA_NULL,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,n},_=function(t,e,r,n,o){return t[n++]=C.BSON_DATA_BOOLEAN,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,t[n++]=r?1:0,n},v=function(t,e,r,n,o){t[n++]=C.BSON_DATA_DATE,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var s=i.fromNumber(r.getTime()),a=s.getLowBits(),u=s.getHighBits();return t[n++]=255&a,t[n++]=a>>8&255,t[n++]=a>>16&255,t[n++]=a>>24&255,t[n++]=255&u,t[n++]=u>>8&255,t[n++]=u>>16&255,t[n++]=u>>24&255,n},m=function(t,e,r,n,o){if(t[n++]=C.BSON_DATA_REGEXP,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,r.source&&null!=r.source.match(c))throw Error("value "+r.source+" must not contain null bytes");return n+=t.write(r.source,n,"utf8"),t[n++]=0,r.global&&(t[n++]=115),r.ignoreCase&&(t[n++]=105),r.multiline&&(t[n++]=109),t[n++]=0,n},g=function(t,e,r,n,o){if(t[n++]=C.BSON_DATA_REGEXP,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,null!=r.pattern.match(c))throw Error("pattern "+r.pattern+" must not contain null bytes");return n+=t.write(r.pattern,n,"utf8"),t[n++]=0,n+=t.write(r.options.split("").sort().join(""),n,"utf8"),t[n++]=0,n},b=function(t,e,r,n,o){return null===r?t[n++]=C.BSON_DATA_NULL:"MinKey"===r._bsontype?t[n++]=C.BSON_DATA_MIN_KEY:t[n++]=C.BSON_DATA_MAX_KEY,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,n},w=function(t,e,r,n,o){if(t[n++]=C.BSON_DATA_OID,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,"string"==typeof r.id)t.write(r.id,n,"binary");else{if(!r.id||!r.id.copy)throw new Error("object ["+JSON.stringify(r)+"] is not a valid ObjectId");r.id.copy(t,n,0,12)}return n+12},O=function(t,e,r,n,o){t[n++]=C.BSON_DATA_BINARY,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var i=r.length;return t[n++]=255&i,t[n++]=i>>8&255,t[n++]=i>>16&255,t[n++]=i>>24&255,t[n++]=C.BSON_BINARY_SUBTYPE_DEFAULT,r.copy(t,n,0,i),n+=i},S=function(t,e,r,n,o,i,s,a,u,c){for(var l=0;l>8&255,t[n++]=i>>16&255,t[n++]=i>>24&255,t[n++]=255&s,t[n++]=s>>8&255,t[n++]=s>>16&255,t[n++]=s>>24&255,n},E=function(t,e,r,n,o){return t[n++]=C.BSON_DATA_INT,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,t[n++]=255&r,t[n++]=r>>8&255,t[n++]=r>>16&255,t[n++]=r>>24&255,n},j=function(t,e,r,n,i){return t[n++]=C.BSON_DATA_NUMBER,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,o(t,r,n,"little",52,8),n+=8},P=function(t,e,r,n,o,i,s){t[n++]=C.BSON_DATA_CODE,n+=s?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var a=u(r),c=t.write(a,n+4,"utf8")+1;return t[n]=255&c,t[n+1]=c>>8&255,t[n+2]=c>>16&255,t[n+3]=c>>24&255,n=n+4+c-1,t[n++]=0,n},x=function(t,e,r,o,i,s,a,u,c){if(r.scope&&"object"===n(r.scope)){t[o++]=C.BSON_DATA_CODE_W_SCOPE;var l=c?t.write(e,o,"ascii"):t.write(e,o,"utf8");o+=l,t[o++]=0;var f=o,p="string"==typeof r.code?r.code:r.code.toString();o+=4;var h=t.write(p,o+4,"utf8")+1;t[o]=255&h,t[o+1]=h>>8&255,t[o+2]=h>>16&255,t[o+3]=h>>24&255,t[o+4+h-1]=0,o=o+h+4;var y=B(t,r.scope,i,o,s+1,a,u);o=y-1;var d=y-f;t[f++]=255&d,t[f++]=d>>8&255,t[f++]=d>>16&255,t[f++]=d>>24&255,t[o++]=0}else{t[o++]=C.BSON_DATA_CODE,o+=l=c?t.write(e,o,"ascii"):t.write(e,o,"utf8"),t[o++]=0,p=r.code.toString();var _=t.write(p,o+4,"utf8")+1;t[o]=255&_,t[o+1]=_>>8&255,t[o+2]=_>>16&255,t[o+3]=_>>24&255,o=o+4+_-1,t[o++]=0}return o},T=function(t,e,r,n,o){t[n++]=C.BSON_DATA_BINARY,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var i=r.value(!0),s=r.position;return r.sub_type===a.SUBTYPE_BYTE_ARRAY&&(s+=4),t[n++]=255&s,t[n++]=s>>8&255,t[n++]=s>>16&255,t[n++]=s>>24&255,t[n++]=r.sub_type,r.sub_type===a.SUBTYPE_BYTE_ARRAY&&(s-=4,t[n++]=255&s,t[n++]=s>>8&255,t[n++]=s>>16&255,t[n++]=s>>24&255),i.copy(t,n,0,r.position),n+=r.position},N=function(t,e,r,n,o){t[n++]=C.BSON_DATA_SYMBOL,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var i=t.write(r.value,n+4,"utf8")+1;return t[n]=255&i,t[n+1]=i>>8&255,t[n+2]=i>>16&255,t[n+3]=i>>24&255,n=n+4+i-1,t[n++]=0,n},k=function(t,e,r,n,o,i,s){t[n++]=C.BSON_DATA_OBJECT,n+=s?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var a,u=n,c=(a=null!=r.db?B(t,{$ref:r.namespace,$id:r.oid,$db:r.db},!1,n,o+1,i):B(t,{$ref:r.namespace,$id:r.oid},!1,n,o+1,i))-u;return t[u++]=255&c,t[u++]=c>>8&255,t[u++]=c>>16&255,t[u++]=c>>24&255,a},B=function(t,r,o,i,a,u,B,C){i=i||0,(C=C||[]).push(r);var R=i+4;if(Array.isArray(r))for(var D=0;D>8&255,t[i++]=q>>16&255,t[i++]=q>>24&255,R},C={BSON_DATA_NUMBER:1,BSON_DATA_STRING:2,BSON_DATA_OBJECT:3,BSON_DATA_ARRAY:4,BSON_DATA_BINARY:5,BSON_DATA_UNDEFINED:6,BSON_DATA_OID:7,BSON_DATA_BOOLEAN:8,BSON_DATA_DATE:9,BSON_DATA_NULL:10,BSON_DATA_REGEXP:11,BSON_DATA_CODE:13,BSON_DATA_SYMBOL:14,BSON_DATA_CODE_W_SCOPE:15,BSON_DATA_INT:16,BSON_DATA_TIMESTAMP:17,BSON_DATA_LONG:18,BSON_DATA_DECIMAL128:19,BSON_DATA_MIN_KEY:255,BSON_DATA_MAX_KEY:127,BSON_BINARY_SUBTYPE_DEFAULT:0,BSON_BINARY_SUBTYPE_FUNCTION:1,BSON_BINARY_SUBTYPE_BYTE_ARRAY:2,BSON_BINARY_SUBTYPE_UUID:3,BSON_BINARY_SUBTYPE_MD5:4,BSON_BINARY_SUBTYPE_USER_DEFINED:128,BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648};C.BSON_INT64_MAX=Math.pow(2,63)-1,C.BSON_INT64_MIN=-Math.pow(2,63),C.JS_INT_MAX=9007199254740992,C.JS_INT_MIN=-9007199254740992,t.exports=B}).call(this,r(2).Buffer)},function(t,e){e.readIEEE754=function(t,e,r,n,o){var i,s,a="big"===r,u=8*o-n-1,c=(1<>1,f=-7,p=a?0:o-1,h=a?1:-1,y=t[e+p];for(p+=h,i=y&(1<<-f)-1,y>>=-f,f+=u;f>0;i=256*i+t[e+p],p+=h,f-=8);for(s=i&(1<<-f)-1,i>>=-f,f+=n;f>0;s=256*s+t[e+p],p+=h,f-=8);if(0===i)i=1-l;else{if(i===c)return s?NaN:1/0*(y?-1:1);s+=Math.pow(2,n),i-=l}return(y?-1:1)*s*Math.pow(2,i-n)},e.writeIEEE754=function(t,e,r,n,o,i){var s,a,u,c="big"===n,l=8*i-o-1,f=(1<>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,y=c?i-1:0,d=c?-1:1,_=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+p>=1?h/u:h*Math.pow(2,1-p))*u>=2&&(s++,u/=2),s+p>=f?(a=0,s=f):s+p>=1?(a=(e*u-1)*Math.pow(2,o),s+=p):(a=e*Math.pow(2,p-1)*Math.pow(2,o),s=0));o>=8;t[r+y]=255&a,y+=d,a/=256,o-=8);for(s=s<0;t[r+y]=255&s,y+=d,s/=256,l-=8);t[r+y-d]|=128*_}},function(t,e,r){"use strict";(function(e){function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var o=r(24).Long,i=r(39).Double,s=r(40).Timestamp,a=r(41).ObjectID,u=r(43).Symbol,c=r(42).BSONRegExp,l=r(44).Code,f=r(45),p=r(46).MinKey,h=r(47).MaxKey,y=r(48).DBRef,d=r(29).Binary,_=r(16).normalizedFunctionString,v=function(t,e,r){var n=5;if(Array.isArray(t))for(var o=0;o=g.JS_INT_MIN&&r<=g.JS_INT_MAX&&r>=g.BSON_INT32_MIN&&r<=g.BSON_INT32_MAX?(null!=t?e.byteLength(t,"utf8")+1:0)+5:(null!=t?e.byteLength(t,"utf8")+1:0)+9;case"undefined":return b||!w?(null!=t?e.byteLength(t,"utf8")+1:0)+1:0;case"boolean":return(null!=t?e.byteLength(t,"utf8")+1:0)+2;case"object":if(null==r||r instanceof p||r instanceof h||"MinKey"===r._bsontype||"MaxKey"===r._bsontype)return(null!=t?e.byteLength(t,"utf8")+1:0)+1;if(r instanceof a||"ObjectID"===r._bsontype||"ObjectId"===r._bsontype)return(null!=t?e.byteLength(t,"utf8")+1:0)+13;if(r instanceof Date||"object"===n(S=r)&&"[object Date]"===Object.prototype.toString.call(S))return(null!=t?e.byteLength(t,"utf8")+1:0)+9;if(void 0!==e&&e.isBuffer(r))return(null!=t?e.byteLength(t,"utf8")+1:0)+6+r.length;if(r instanceof o||r instanceof i||r instanceof s||"Long"===r._bsontype||"Double"===r._bsontype||"Timestamp"===r._bsontype)return(null!=t?e.byteLength(t,"utf8")+1:0)+9;if(r instanceof f||"Decimal128"===r._bsontype)return(null!=t?e.byteLength(t,"utf8")+1:0)+17;if(r instanceof l||"Code"===r._bsontype)return null!=r.scope&&Object.keys(r.scope).length>0?(null!=t?e.byteLength(t,"utf8")+1:0)+1+4+4+e.byteLength(r.code.toString(),"utf8")+1+v(r.scope,m,w):(null!=t?e.byteLength(t,"utf8")+1:0)+1+4+e.byteLength(r.code.toString(),"utf8")+1;if(r instanceof d||"Binary"===r._bsontype)return r.sub_type===d.SUBTYPE_BYTE_ARRAY?(null!=t?e.byteLength(t,"utf8")+1:0)+(r.position+1+4+1+4):(null!=t?e.byteLength(t,"utf8")+1:0)+(r.position+1+4+1);if(r instanceof u||"Symbol"===r._bsontype)return(null!=t?e.byteLength(t,"utf8")+1:0)+e.byteLength(r.value,"utf8")+4+1+1;if(r instanceof y||"DBRef"===r._bsontype){var O={$ref:r.namespace,$id:r.oid};return null!=r.db&&(O.$db=r.db),(null!=t?e.byteLength(t,"utf8")+1:0)+1+v(O,m,w)}return r instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(r)?(null!=t?e.byteLength(t,"utf8")+1:0)+1+e.byteLength(r.source,"utf8")+1+(r.global?1:0)+(r.ignoreCase?1:0)+(r.multiline?1:0)+1:r instanceof c||"BSONRegExp"===r._bsontype?(null!=t?e.byteLength(t,"utf8")+1:0)+1+e.byteLength(r.pattern,"utf8")+1+e.byteLength(r.options,"utf8")+1:(null!=t?e.byteLength(t,"utf8")+1:0)+v(r,m,w)+1;case"function":if(r instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(r)||"[object RegExp]"===String.call(r))return(null!=t?e.byteLength(t,"utf8")+1:0)+1+e.byteLength(r.source,"utf8")+1+(r.global?1:0)+(r.ignoreCase?1:0)+(r.multiline?1:0)+1;if(m&&null!=r.scope&&Object.keys(r.scope).length>0)return(null!=t?e.byteLength(t,"utf8")+1:0)+1+4+4+e.byteLength(_(r),"utf8")+1+v(r.scope,m,w);if(m)return(null!=t?e.byteLength(t,"utf8")+1:0)+1+4+e.byteLength(_(r),"utf8")+1}var S;return 0}var g={BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648,JS_INT_MAX:9007199254740992,JS_INT_MIN:-9007199254740992};t.exports=v}).call(this,r(2).Buffer)},function(t,e,r){"use strict"; +/*! + * ignore + */t.exports=r(38).Decimal128},function(t,e,r){"use strict"; +/*! + * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId + * @constructor NodeMongoDbObjectId + * @see ObjectId + */var n=r(38).ObjectID; +/*! + * Getter for convenience with populate, see gh-6115 + */Object.defineProperty(n.prototype,"_id",{enumerable:!1,configurable:!0,get:function(){return this}}), +/*! + * ignore + */ +t.exports=n},function(t,e,r){"use strict"; +/*! + * ignore + */t.exports=function(){}},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */var n=r(7),o=r(189),i=!1;t.exports=function(){return i?o:n}, +/*! + * ignore + */ +t.exports.setBrowser=function(t){i=t}},function(t,e,r){"use strict"; +/*! + * Dependencies + */var n=r(114).ctor("require","modify","init","default","ignore");function o(){this.activePaths=new n,this.ownerDocument=void 0,this.fullPath=void 0}t.exports=o,o.prototype.strictMode=void 0,o.prototype.selected=void 0,o.prototype.shardval=void 0,o.prototype.saveError=void 0,o.prototype.validationError=void 0,o.prototype.adhocPaths=void 0,o.prototype.removing=void 0,o.prototype.inserting=void 0,o.prototype.saving=void 0,o.prototype.version=void 0,o.prototype._id=void 0,o.prototype.populate=void 0,o.prototype.populated=void 0,o.prototype.wasPopulated=!1,o.prototype.scope=void 0,o.prototype.session=null,o.prototype.pathsToScopes=null,o.prototype.cachedRequired=null},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */var n=r(1),o=t.exports=function(){}; +/*! + * StateMachine represents a minimal `interface` for the + * constructors it builds via StateMachine.ctor(...). + * + * @api private + */ +/*! + * StateMachine.ctor('state1', 'state2', ...) + * A factory method for subclassing StateMachine. + * The arguments are a list of states. For each state, + * the constructor's prototype gets state transition + * methods named after each state. These transition methods + * place their path argument into the given state. + * + * @param {String} state + * @param {String} [state] + * @return {Function} subclass constructor + * @private + */ +o.ctor=function(){var t=n.args(arguments),e=function(){o.apply(this,arguments),this.paths={},this.states={},this.stateNames=t;for(var e,r=t.length;r--;)e=t[r],this.states[e]={}};return e.prototype=new o,t.forEach((function(t){e.prototype[t]=function(e){this._changeState(e,t)}})),e}, +/*! + * This function is wrapped by the state change functions: + * + * - `require(path)` + * - `modify(path)` + * - `init(path)` + * + * @api private + */ +o.prototype._changeState=function(t,e){var r=this.states[this.paths[t]];r&&delete r[t],this.paths[t]=e,this.states[e][t]=!0}, +/*! + * ignore + */ +o.prototype.clear=function(t){for(var e,r=Object.keys(this.states[t]),n=r.length;n--;)e=r[n],delete this.states[t][e],delete this.paths[e]}, +/*! + * Checks to see if at least one path is in the states passed in via `arguments` + * e.g., this.some('required', 'inited') + * + * @param {String} state that we want to check for. + * @private + */ +o.prototype.some=function(){var t=this,e=arguments.length?arguments:this.stateNames;return Array.prototype.some.call(e,(function(e){return Object.keys(t.states[e]).length}))}, +/*! + * This function builds the functions that get assigned to `forEach` and `map`, + * since both of those methods share a lot of the same logic. + * + * @param {String} iterMethod is either 'forEach' or 'map' + * @return {Function} + * @api private + */ +o.prototype._iter=function(t){return function(){var e=arguments.length,r=n.args(arguments,0,e-1),o=arguments[e-1];r.length||(r=this.stateNames);var i=this,s=r.reduce((function(t,e){return t.concat(Object.keys(i.states[e]))}),[]);return s[t]((function(t,e,r){return o(t,e,r)}))}}, +/*! + * Iterates over the paths that belong to one of the parameter states. + * + * The function profile can look like: + * this.forEach(state1, fn); // iterates over all paths in state1 + * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 + * this.forEach(fn); // iterates over all paths in all states + * + * @param {String} [state] + * @param {String} [state] + * @param {Function} callback + * @private + */ +o.prototype.forEach=function(){return this.forEach=this._iter("forEach"),this.forEach.apply(this,arguments)}, +/*! + * Maps over the paths that belong to one of the parameter states. + * + * The function profile can look like: + * this.forEach(state1, fn); // iterates over all paths in state1 + * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 + * this.forEach(fn); // iterates over all paths in all states + * + * @param {String} [state] + * @param {String} [state] + * @param {Function} callback + * @return {Array} + * @private + */ +o.prototype.map=function(){return this.map=this._iter("map"),this.map.apply(this,arguments)}},function(t,e){function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var n=1e3,o=6e4,i=60*o,s=24*i;function a(t,e,r,n){var o=e>=1.5*r;return Math.round(t/r)+" "+n+(o?"s":"")}t.exports=function(t,e){e=e||{};var u=r(t);if("string"===u&&t.length>0)return function(t){if((t=String(t)).length>100)return;var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!e)return;var r=parseFloat(e[1]);switch((e[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return r*s;case"hours":case"hour":case"hrs":case"hr":case"h":return r*i;case"minutes":case"minute":case"mins":case"min":case"m":return r*o;case"seconds":case"second":case"secs":case"sec":case"s":return r*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(t);if("number"===u&&isFinite(t))return e.long?function(t){var e=Math.abs(t);if(e>=s)return a(t,e,s,"day");if(e>=i)return a(t,e,i,"hour");if(e>=o)return a(t,e,o,"minute");if(e>=n)return a(t,e,n,"second");return t+" ms"}(t):function(t){var e=Math.abs(t);if(e>=s)return Math.round(t/s)+"d";if(e>=i)return Math.round(t/i)+"h";if(e>=o)return Math.round(t/o)+"m";if(e>=n)return Math.round(t/n)+"s";return t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,r){function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var o=r(117),i=["__proto__","constructor","prototype"]; +/*! + * Returns the value passed to it. + */ +function s(t){return t}e.get=function(t,r,i,a){var u;"function"==typeof i&&(i.length<2?(a=i,i=void 0):(u=i,i=void 0)),a||(a=s);var c="string"==typeof t?o(t):t;if(!Array.isArray(c))throw new TypeError("Invalid `path`. Must be either string or array");for(var l,f=r,p=0;p");t.sort.set(r,n)}))} +/*! + * limit, skip, maxScan, batchSize, comment + * + * Sets these associated options. + * + * query.comment('feed query'); + */ +/*! + * Internal helper for update, updateMany, updateOne + */ +function d(t,e,r,n,o,i,s){return t.op=e,c.canMerge(r)&&t.merge(r),n&&t._mergeUpdate(n),a.isObject(o)&&t.setOptions(o),i||s?!t._update||!t.options.overwrite&&0===a.keys(t._update).length?(s&&a.soon(s.bind(null,null,0)),t):(o=t._optionsForExec(),s||(o.safe=!1),r=t._conditions,n=t._updateForExec(),u("update",t._collection.collectionName,r,n,o),s=t._wrapCallback(e,s,{conditions:r,doc:n,options:o}),t._collection[e](r,n,o,a.tick(s)),t):t}["limit","skip","maxScan","batchSize","comment"].forEach((function(t){c.prototype[t]=function(e){return this._validate(t),this.options[t]=e,this}})),c.prototype.maxTime=c.prototype.maxTimeMS=function(t){return this._validate("maxTime"),this.options.maxTimeMS=t,this},c.prototype.snapshot=function(){return this._validate("snapshot"),this.options.snapshot=!arguments.length||!!arguments[0],this},c.prototype.hint=function(){if(0===arguments.length)return this;this._validate("hint");var t=arguments[0];if(a.isObject(t)){var e=this.options.hint||(this.options.hint={});for(var r in t)e[r]=t[r];return this}if("string"==typeof t)return this.options.hint=t,this;throw new TypeError("Invalid hint. "+t)},c.prototype.j=function(t){return this.options.j=t,this},c.prototype.slaveOk=function(t){return this.options.slaveOk=!arguments.length||!!t,this},c.prototype.read=c.prototype.setReadPreference=function(t){return arguments.length>1&&!c.prototype.read.deprecationWarningIssued&&(console.error("Deprecation warning: 'tags' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead."),c.prototype.read.deprecationWarningIssued=!0),this.options.readPreference=a.readPref(t),this},c.prototype.readConcern=c.prototype.r=function(t){return this.options.readConcern=a.readConcern(t),this},c.prototype.tailable=function(){return this._validate("tailable"),this.options.tailable=!arguments.length||!!arguments[0],this},c.prototype.writeConcern=c.prototype.w=function(t){return"object"===n(t)?(void 0!==t.j&&(this.options.j=t.j),void 0!==t.w&&(this.options.w=t.w),void 0!==t.wtimeout&&(this.options.wtimeout=t.wtimeout)):this.options.w="m"===t?"majority":t,this},c.prototype.wtimeout=c.prototype.wTimeout=function(t){return this.options.wtimeout=t,this},c.prototype.merge=function(t){if(!t)return this;if(!c.canMerge(t))throw new TypeError("Invalid argument. Expected instanceof mquery or plain object");return t instanceof c?(t._conditions&&a.merge(this._conditions,t._conditions),t._fields&&(this._fields||(this._fields={}),a.merge(this._fields,t._fields)),t.options&&(this.options||(this.options={}),a.merge(this.options,t.options)),t._update&&(this._update||(this._update={}),a.mergeClone(this._update,t._update)),t._distinct&&(this._distinct=t._distinct),this):(a.merge(this._conditions,t),this)},c.prototype.find=function(t,e){if(this.op="find","function"==typeof t?(e=t,t=void 0):c.canMerge(t)&&this.merge(t),!e)return this;var r=this._conditions,n=this._optionsForExec();return this.$useProjection?n.projection=this._fieldsForExec():n.fields=this._fieldsForExec(),u("find",this._collection.collectionName,r,n),e=this._wrapCallback("find",e,{conditions:r,options:n}),this._collection.find(r,n,a.tick(e)),this},c.prototype.cursor=function(t){if(this.op){if("find"!==this.op)throw new TypeError(".cursor only support .find method")}else this.find(t);var e=this._conditions,r=this._optionsForExec();return this.$useProjection?r.projection=this._fieldsForExec():r.fields=this._fieldsForExec(),u("findCursor",this._collection.collectionName,e,r),this._collection.findCursor(e,r)},c.prototype.findOne=function(t,e){if(this.op="findOne","function"==typeof t?(e=t,t=void 0):c.canMerge(t)&&this.merge(t),!e)return this;var r=this._conditions,n=this._optionsForExec();return this.$useProjection?n.projection=this._fieldsForExec():n.fields=this._fieldsForExec(),u("findOne",this._collection.collectionName,r,n),e=this._wrapCallback("findOne",e,{conditions:r,options:n}),this._collection.findOne(r,n,a.tick(e)),this},c.prototype.count=function(t,e){if(this.op="count",this._validate(),"function"==typeof t?(e=t,t=void 0):c.canMerge(t)&&this.merge(t),!e)return this;var r=this._conditions,n=this._optionsForExec();return u("count",this._collection.collectionName,r,n),e=this._wrapCallback("count",e,{conditions:r,options:n}),this._collection.count(r,n,a.tick(e)),this},c.prototype.distinct=function(t,e,r){if(this.op="distinct",this._validate(),!r){switch(n(e)){case"function":r=e,"string"==typeof t&&(e=t,t=void 0);break;case"undefined":case"string":break;default:throw new TypeError("Invalid `field` argument. Must be string or function")}switch(n(t)){case"function":r=t,t=e=void 0;break;case"string":e=t,t=void 0}}if("string"==typeof e&&(this._distinct=e),c.canMerge(t)&&this.merge(t),!r)return this;if(!this._distinct)throw new Error("No value for `distinct` has been declared");var o=this._conditions,i=this._optionsForExec();return u("distinct",this._collection.collectionName,o,i),r=this._wrapCallback("distinct",r,{conditions:o,options:i}),this._collection.distinct(this._distinct,o,i,a.tick(r)),this},c.prototype.update=function(t,e,r,o){var i;switch(arguments.length){case 3:"function"==typeof r&&(o=r,r=void 0);break;case 2:"function"==typeof e&&(o=e,e=t,t=void 0);break;case 1:switch(n(t)){case"function":o=t,t=r=e=void 0;break;case"boolean":i=t,t=void 0;break;default:e=t,t=r=void 0}}return d(this,"update",t,e,r,i,o)},c.prototype.updateMany=function(t,e,r,o){var i;switch(arguments.length){case 3:"function"==typeof r&&(o=r,r=void 0);break;case 2:"function"==typeof e&&(o=e,e=t,t=void 0);break;case 1:switch(n(t)){case"function":o=t,t=r=e=void 0;break;case"boolean":i=t,t=void 0;break;default:e=t,t=r=void 0}}return d(this,"updateMany",t,e,r,i,o)},c.prototype.updateOne=function(t,e,r,o){var i;switch(arguments.length){case 3:"function"==typeof r&&(o=r,r=void 0);break;case 2:"function"==typeof e&&(o=e,e=t,t=void 0);break;case 1:switch(n(t)){case"function":o=t,t=r=e=void 0;break;case"boolean":i=t,t=void 0;break;default:e=t,t=r=void 0}}return d(this,"updateOne",t,e,r,i,o)},c.prototype.replaceOne=function(t,e,r,o){var i;switch(arguments.length){case 3:"function"==typeof r&&(o=r,r=void 0);break;case 2:"function"==typeof e&&(o=e,e=t,t=void 0);break;case 1:switch(n(t)){case"function":o=t,t=r=e=void 0;break;case"boolean":i=t,t=void 0;break;default:e=t,t=r=void 0}}return this.setOptions({overwrite:!0}),d(this,"replaceOne",t,e,r,i,o)},c.prototype.remove=function(t,e){var r;if(this.op="remove","function"==typeof t?(e=t,t=void 0):c.canMerge(t)?this.merge(t):!0===t&&(r=t,t=void 0),!r&&!e)return this;var n=this._optionsForExec();e||(n.safe=!1);var o=this._conditions;return u("remove",this._collection.collectionName,o,n),e=this._wrapCallback("remove",e,{conditions:o,options:n}),this._collection.remove(o,n,a.tick(e)),this},c.prototype.deleteOne=function(t,e){var r;if(this.op="deleteOne","function"==typeof t?(e=t,t=void 0):c.canMerge(t)?this.merge(t):!0===t&&(r=t,t=void 0),!r&&!e)return this;var n=this._optionsForExec();e||(n.safe=!1),delete n.justOne;var o=this._conditions;return u("deleteOne",this._collection.collectionName,o,n),e=this._wrapCallback("deleteOne",e,{conditions:o,options:n}),this._collection.deleteOne(o,n,a.tick(e)),this},c.prototype.deleteMany=function(t,e){var r;if(this.op="deleteMany","function"==typeof t?(e=t,t=void 0):c.canMerge(t)?this.merge(t):!0===t&&(r=t,t=void 0),!r&&!e)return this;var n=this._optionsForExec();e||(n.safe=!1),delete n.justOne;var o=this._conditions;return u("deleteOne",this._collection.collectionName,o,n),e=this._wrapCallback("deleteOne",e,{conditions:o,options:n}),this._collection.deleteMany(o,n,a.tick(e)),this},c.prototype.findOneAndUpdate=function(t,e,r,n){switch(this.op="findOneAndUpdate",this._validate(),arguments.length){case 3:"function"==typeof r&&(n=r,r={});break;case 2:"function"==typeof e&&(n=e,e=t,t=void 0),r=void 0;break;case 1:"function"==typeof t?(n=t,t=r=e=void 0):(e=t,t=r=void 0)}return c.canMerge(t)&&this.merge(t),e&&this._mergeUpdate(e),r&&this.setOptions(r),n?this._findAndModify("update",n):this},c.prototype.findOneAndRemove=c.prototype.findOneAndDelete=function(t,e,r){return this.op="findOneAndRemove",this._validate(),"function"==typeof e?(r=e,e=void 0):"function"==typeof t&&(r=t,t=void 0),c.canMerge(t)&&this.merge(t),e&&this.setOptions(e),r?this._findAndModify("remove",r):this},c.prototype._findAndModify=function(t,e){i.equal("function",n(e));var r,o=this._optionsForExec();if("remove"==t)o.remove=!0;else if("new"in o||(o.new=!0),"upsert"in o||(o.upsert=!1),!(r=this._updateForExec())){if(!o.upsert)return this.findOne(e);r={$set:{}}}null!=this._fieldsForExec()&&(this.$useProjection?o.projection=this._fieldsForExec():o.fields=this._fieldsForExec());var s=this._conditions;return u("findAndModify",this._collection.collectionName,s,r,o),e=this._wrapCallback("findAndModify",e,{conditions:s,doc:r,options:o}),this._collection.findAndModify(s,r,o,a.tick(e)),this},c.prototype._wrapCallback=function(t,e,r){var n=this._traceFunction||c.traceFunction;if(n){r.collectionName=this._collection.collectionName;var o=n&&n.call(null,t,r,this),i=(new Date).getTime();return function(t,r){if(o){var n=(new Date).getTime()-i;o.call(null,t,r,n)}e&&e.apply(null,arguments)}}return e},c.prototype.setTraceFunction=function(t){return this._traceFunction=t,this},c.prototype.exec=function(t,e){switch(n(t)){case"function":e=t,t=null;break;case"string":this.op=t}i.ok(this.op,"Missing query type: (find, update, etc)"),"update"!=this.op&&"remove"!=this.op||e||(e=!0);var r=this;if("function"!=typeof e)return new c.Promise((function(t,e){r[r.op]((function(r,n){r?e(r):t(n),t=e=null}))}));this[this.op](e)},c.prototype.thunk=function(){var t=this;return function(e){t.exec(e)}},c.prototype.then=function(t,e){var r=this;return new c.Promise((function(t,e){r.exec((function(r,n){r?e(r):t(n),t=e=null}))})).then(t,e)},c.prototype.stream=function(t){if("find"!=this.op)throw new Error("stream() is only available for find");var e=this._conditions,r=this._optionsForExec();return this.$useProjection?r.projection=this._fieldsForExec():r.fields=this._fieldsForExec(),u("stream",this._collection.collectionName,e,r,t),this._collection.findStream(e,r,t)},c.prototype.selected=function(){return!!(this._fields&&Object.keys(this._fields).length>0)},c.prototype.selectedInclusively=function(){if(!this._fields)return!1;var t=Object.keys(this._fields);if(0===t.length)return!1;for(var e=0;e=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(t){}}(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.formatters.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}},e.enable(i())}).call(this,r(11))},function(t,e,r){function n(t){var r;function n(){if(n.enabled){var t=n,o=+new Date,i=o-(r||o);t.diff=i,t.prev=r,t.curr=o,r=o;for(var s=new Array(arguments.length),a=0;a0)return function(t){if((t=String(t)).length>100)return;var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(!e)return;var r=parseFloat(e[1]);switch((e[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"days":case"day":case"d":return r*s;case"hours":case"hour":case"hrs":case"hr":case"h":return r*i;case"minutes":case"minute":case"mins":case"min":case"m":return r*o;case"seconds":case"second":case"secs":case"sec":case"s":return r*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(t);if("number"===c&&!1===isNaN(t))return e.long?a(u=t,s,"day")||a(u,i,"hour")||a(u,o,"minute")||a(u,n,"second")||u+" ms":function(t){if(t>=s)return Math.round(t/s)+"d";if(t>=i)return Math.round(t/i)+"h";if(t>=o)return Math.round(t/o)+"m";if(t>=n)return Math.round(t/n)+"s";return t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,r){"use strict";var n=e;n.distinct=function(t){return t._fields&&Object.keys(t._fields).length>0?"field selection and slice":(Object.keys(n.distinct).every((function(r){return!t.options[r]||(e=r,!1)})),e);var e},n.distinct.select=n.distinct.slice=n.distinct.sort=n.distinct.limit=n.distinct.skip=n.distinct.batchSize=n.distinct.comment=n.distinct.maxScan=n.distinct.snapshot=n.distinct.hint=n.distinct.tailable=!0,n.findOneAndUpdate=n.findOneAndRemove=function(t){var e;return Object.keys(n.findOneAndUpdate).every((function(r){return!t.options[r]||(e=r,!1)})),e},n.findOneAndUpdate.limit=n.findOneAndUpdate.skip=n.findOneAndUpdate.batchSize=n.findOneAndUpdate.maxScan=n.findOneAndUpdate.snapshot=n.findOneAndUpdate.hint=n.findOneAndUpdate.tailable=n.findOneAndUpdate.comment=!0,n.count=function(t){return t._fields&&Object.keys(t._fields).length>0?"field selection and slice":(Object.keys(n.count).every((function(r){return!t.options[r]||(e=r,!1)})),e);var e},n.count.slice=n.count.batchSize=n.count.comment=n.count.maxScan=n.count.snapshot=n.count.tailable=!0},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,r){"use strict";var n=r(71);if("unknown"==n.type)throw new Error("Unknown environment");t.exports=n.isNode?r(129):(n.isMongo,r(32))},function(t,e,r){"use strict";var n=r(32);function o(t){this.collection=t,this.collectionName=t.collectionName}r(69).inherits(o,n),o.prototype.find=function(t,e,r){this.collection.find(t,e,(function(t,e){if(t)return r(t);try{e.toArray(r)}catch(t){r(t)}}))},o.prototype.findOne=function(t,e,r){this.collection.findOne(t,e,r)},o.prototype.count=function(t,e,r){this.collection.count(t,e,r)},o.prototype.distinct=function(t,e,r,n){this.collection.distinct(t,e,r,n)},o.prototype.update=function(t,e,r,n){this.collection.update(t,e,r,n)},o.prototype.updateMany=function(t,e,r,n){this.collection.updateMany(t,e,r,n)},o.prototype.updateOne=function(t,e,r,n){this.collection.updateOne(t,e,r,n)},o.prototype.replaceOne=function(t,e,r,n){this.collection.replaceOne(t,e,r,n)},o.prototype.deleteOne=function(t,e,r){this.collection.deleteOne(t,e,r)},o.prototype.deleteMany=function(t,e,r){this.collection.deleteMany(t,e,r)},o.prototype.remove=function(t,e,r){this.collection.remove(t,e,r)},o.prototype.findAndModify=function(t,e,r,n){var o=Array.isArray(r.sort)?r.sort:[];this.collection.findAndModify(t,o,e,r,n)},o.prototype.findStream=function(t,e,r){return this.collection.find(t,e).stream(r)},o.prototype.findCursor=function(t,e){return this.collection.find(t,e)},t.exports=o},function(t,e,r){(function(r,n,o){var i,s,a,u;function c(t){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)} +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2017 Petka Antonov + * + * 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. + * + */u=function(){var t,e,i;return function t(e,r,n){function o(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=r[s]={exports:{}};e[s][0].call(l.exports,(function(t){var r=e[s][1][t];return o(r||t)}),l,l.exports,t,e,r,n)}return r[s].exports}for(var i="function"==typeof _dereq_&&_dereq_,s=0;s0;){var e=t.shift();if("function"==typeof e){var r=t.shift(),n=t.shift();e.call(r,n)}else e._settlePromises()}},u.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},u.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},u.prototype._reset=function(){this._isTickUsed=!1},e.exports=u,e.exports.firstLineError=o},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var o=!1,i=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(i,i,null,this,t)},a=function(t,e){0==(50397184&this._bitField)&&this._resolveCallback(e.target)},u=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(i){o||(o=!0,t.prototype._propagateFrom=n.propagateFromFunction(),t.prototype._boundValue=n.boundValueFunction());var c=r(i),l=new t(e);l._propagateFrom(this,1);var f=this._target();if(l._setBoundTo(c),c instanceof t){var p={promiseRejectionQueued:!1,promise:l,target:f,bindingPromise:c};f._then(e,s,void 0,l,p),c._then(a,u,void 0,l,p),l._setOnCancel(c)}else l._resolveCallback(f);return l},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152==(2097152&this._bitField)},t.bind=function(e,r){return t.resolve(r).bind(e)}}},{}],4:[function(t,e,r){"use strict";var n;"undefined"!=typeof Promise&&(n=Promise);var o=t("./promise")();o.noConflict=function(){try{Promise===o&&(Promise=n)}catch(t){}return o},e.exports=o},{"./promise":22}],5:[function(t,e,r){"use strict";var n=Object.create;if(n){var o=n(null),i=n(null);o[" size"]=i[" size"]=0}e.exports=function(e){var r=t("./util"),n=r.canEvaluate;function o(t){return function(t,n){var o;if(null!=t&&(o=t[n]),"function"!=typeof o){var i="Object "+r.classString(t)+" has no method '"+r.toString(n)+"'";throw new e.TypeError(i)}return o}(t,this.pop()).apply(t,this)}function i(t){return t[this]}function s(t){var e=+this;return e<0&&(e=Math.max(0,e+t.length)),t[e]}r.isIdentifier,e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(o,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e;if("number"==typeof t)e=s;else if(n){var r=(void 0)(t);e=null!==r?r:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,r){"use strict";e.exports=function(e,r,n,o){var i=t("./util"),s=i.tryCatch,a=i.errorObj,u=e._async;e.prototype.break=e.prototype.cancel=function(){if(!o.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var r=t._cancellationParent;if(null==r||!r._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=r}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),u.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(i.isArray(t))for(var r=0;r=0)return r[t]}return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},n.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,r.push(this._trace))},n.prototype._popContext=function(){if(void 0!==this._trace){var t=r.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},n.CapturedTrace=null,n.create=function(){if(e)return new n},n.deactivateLongStackTraces=function(){},n.activateLongStackTraces=function(){var r=t.prototype._pushContext,i=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,u=t.prototype._promiseCreated;n.deactivateLongStackTraces=function(){t.prototype._pushContext=r,t.prototype._popContext=i,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=u,e=!1},e=!0,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,t._peekContext=t.prototype._peekContext=o,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},n}},{}],9:[function(t,e,n){"use strict";e.exports=function(e,n){var o,i,s,a=e._getDomain,u=e._async,l=t("./errors").Warning,f=t("./util"),p=f.canAttachTrace,h=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,y=/\((?:timers\.js):\d+:\d+\)/,d=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,_=null,v=null,m=!1,g=!(0==f.env("BLUEBIRD_DEBUG")),b=!(0==f.env("BLUEBIRD_WARNINGS")||!g&&!f.env("BLUEBIRD_WARNINGS")),w=!(0==f.env("BLUEBIRD_LONG_STACK_TRACES")||!g&&!f.env("BLUEBIRD_LONG_STACK_TRACES")),O=0!=f.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(b||!!f.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){if(0==(524288&this._bitField)){this._setRejectionIsUnhandled();var t=this;setTimeout((function(){t._notifyUnhandledRejection()}),1)}},e.prototype._notifyUnhandledRejectionIsHandled=function(){W("rejectionHandled",o,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!=(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),W("unhandledRejection",i,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,r){return L(t,e,r||this)},e.onPossiblyUnhandledRejection=function(t){var e=a();i="function"==typeof t?null===e?t:f.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=a();o="function"==typeof t?null===e?t:f.domainBind(e,t):void 0};var S=function(){};e.longStackTraces=function(){if(u.haveItemsQueued()&&!X.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!X.longStackTraces&&Y()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;X.longStackTraces=!0,S=function(){if(u.haveItemsQueued()&&!X.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,n.deactivateLongStackTraces(),u.enableTrampoline(),X.longStackTraces=!1},e.prototype._captureStackTrace=I,e.prototype._attachExtraTrace=F,n.activateLongStackTraces(),u.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return X.longStackTraces&&Y()};var A=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return f.global.dispatchEvent(t),function(t,e){var r=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!f.global.dispatchEvent(r)}}return"function"==typeof Event?(t=new Event("CustomEvent"),f.global.dispatchEvent(t),function(t,e){var r=new Event(t.toLowerCase(),{cancelable:!0});return r.detail=e,!f.global.dispatchEvent(r)}):((t=document.createEvent("CustomEvent")).initCustomEvent("testingtheevent",!1,!0,{}),f.global.dispatchEvent(t),function(t,e){var r=document.createEvent("CustomEvent");return r.initCustomEvent(t.toLowerCase(),!1,!0,e),!f.global.dispatchEvent(r)})}catch(t){}return function(){return!1}}(),$=f.isNode?function(){return r.emit.apply(r,arguments)}:f.global?function(t){var e="on"+t.toLowerCase(),r=f.global[e];return!!r&&(r.apply(f.global,[].slice.call(arguments,1)),!0)}:function(){return!1};function E(t,e){return{promise:e}}var j={promiseCreated:E,promiseFulfilled:E,promiseRejected:E,promiseResolved:E,promiseCancelled:E,promiseChained:function(t,e,r){return{promise:e,child:r}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,r){return{reason:e,promise:r}},rejectionHandled:E},P=function(t){var e=!1;try{e=$.apply(null,arguments)}catch(t){u.throwLater(t),e=!0}var r=!1;try{r=A(t,j[t].apply(null,arguments))}catch(t){u.throwLater(t),r=!0}return r||e};function x(){return!1}function T(t,e,r){var n=this;try{t(e,r,(function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+f.toString(t));n._attachCancellationCallback(t)}))}catch(t){return t}}function N(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?f.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function k(){return this._onCancelField}function B(t){this._onCancelField=t}function C(){this._cancellationParent=void 0,this._onCancelField=void 0}function R(t,e){if(0!=(1&e)){this._cancellationParent=t;var r=t._branchesRemainingToCancel;void 0===r&&(r=0),t._branchesRemainingToCancel=r+1}0!=(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}e.config=function(t){if("longStackTraces"in(t=Object(t))&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&S()),"warnings"in t){var r=t.warnings;X.warnings=!!r,O=X.warnings,f.isObject(r)&&"wForgottenReturn"in r&&(O=!!r.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!X.cancellation){if(u.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=C,e.prototype._propagateFrom=R,e.prototype._onCancel=k,e.prototype._setOnCancel=B,e.prototype._attachCancellationCallback=N,e.prototype._execute=T,D=R,X.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!X.monitoring?(X.monitoring=!0,e.prototype._fireEvent=P):!t.monitoring&&X.monitoring&&(X.monitoring=!1,e.prototype._fireEvent=x)),e},e.prototype._fireEvent=x,e.prototype._execute=function(t,e,r){try{t(e,r)}catch(t){return t}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var D=function(t,e){0!=(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)};function M(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function I(){this._trace=new J(this._peekContext())}function F(t,e){if(p(t)){var r=this._trace;if(void 0!==r&&e&&(r=r._parent),void 0!==r)r.attachExtraTrace(t);else if(!t.__stackCleaned__){var n=V(t);f.notEnumerableProp(t,"stack",n.message+"\n"+n.stack.join("\n")),f.notEnumerableProp(t,"__stackCleaned__",!0)}}}function L(t,r,n){if(X.warnings){var o,i=new l(t);if(r)n._attachExtraTrace(i);else if(X.longStackTraces&&(o=e._peekContext()))o.attachExtraTrace(i);else{var s=V(i);i.stack=s.message+"\n"+s.stack.join("\n")}P("warning",i)||q(i,"",!0)}}function U(t){for(var e=[],r=0;r0?function(t){for(var e=t.stack.replace(/\s+$/g,"").split("\n"),r=0;r0&&"SyntaxError"!=t.name&&(e=e.slice(r)),e}(t):[" (No stack trace)"],{message:r,stack:"SyntaxError"==t.name?e:U(e)}}function q(t,e,r){if("undefined"!=typeof console){var n;if(f.isObject(t)){var o=t.stack;n=e+v(o,t)}else n=e+String(t);"function"==typeof s?s(n,r):"function"!=typeof console.log&&"object"!==c(console.log)||console.log(n)}}function W(t,e,r,n){var o=!1;try{"function"==typeof e&&(o=!0,"rejectionHandled"===t?e(n):e(r,n))}catch(t){u.throwLater(t)}"unhandledRejection"===t?P(t,r,n)||o||q(r,"Unhandled rejection "):P(t,n)}function H(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{if(e=t&&"function"==typeof t.toString?t.toString():f.toString(t),/\[object [a-zA-Z0-9$_]+\]/.test(e))try{e=JSON.stringify(t)}catch(t){}0===e.length&&(e="(empty array)")}return"(<"+function(t){return t.length<41?t:t.substr(0,38)+"..."}(e)+">, no stack trace)"}function Y(){return"function"==typeof G}var K=function(){return!1},z=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function Q(t){var e=t.match(z);if(e)return{fileName:e[1],line:parseInt(e[2],10)}}function J(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);G(this,J),e>32&&this.uncycle()}f.inherits(J,Error),n.CapturedTrace=J,J.prototype.uncycle=function(){var t=this._length;if(!(t<2)){for(var e=[],r={},n=0,o=this;void 0!==o;++n)e.push(o),o=o._parent;for(n=(t=this._length=n)-1;n>=0;--n){var i=e[n].stack;void 0===r[i]&&(r[i]=n)}for(n=0;n0&&(e[s-1]._parent=void 0,e[s-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var a=n>0?e[n-1]:this;s=0;--c)e[c]._length=u,u++;return}}}},J.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=V(t),r=e.message,n=[e.stack],o=this;void 0!==o;)n.push(U(o.stack.split("\n"))),o=o._parent;!function(t){for(var e=t[0],r=1;r=0;--a)if(n[a]===i){s=a;break}for(a=s;a>=0;--a){var u=n[a];if(e[o]!==u)break;e.pop(),o--}e=n}}(n),function(t){for(var e=0;e=0)return _=/@/,v=e,m=!0,function(t){t.stack=(new Error).stack};try{throw new Error}catch(t){n="stack"in t}return!("stack"in o)&&n&&"number"==typeof Error.stackTraceLimit?(_=t,v=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6}):(v=function(t,e){return"string"==typeof t?t:"object"!==c(e)&&"function"!=typeof e||void 0===e.name||void 0===e.message?H(e):e.toString()},null)}();"undefined"!=typeof console&&void 0!==console.warn&&(s=function(t){console.warn(t)},f.isNode&&r.stderr.isTTY?s=function(t,e){var r=e?"":"";console.warn(r+t+"\n")}:f.isNode||"string"!=typeof(new Error).stack||(s=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var X={warnings:b,longStackTraces:!1,cancellation:!1,monitoring:!1};return w&&e.longStackTraces(),{longStackTraces:function(){return X.longStackTraces},warnings:function(){return X.warnings},cancellation:function(){return X.cancellation},monitoring:function(){return X.monitoring},propagateFromFunction:function(){return D},boundValueFunction:function(){return M},checkForgottenReturns:function(t,e,r,n,o){if(void 0===t&&null!==e&&O){if(void 0!==o&&o._returnedNonUndefined())return;if(0==(65535&n._bitField))return;r&&(r+=" ");var i="",s="";if(e._trace){for(var a=e._trace.stack.split("\n"),u=U(a),c=u.length-1;c>=0;--c){var l=u[c];if(!y.test(l)){var f=l.match(d);f&&(i="at "+f[1]+":"+f[2]+":"+f[3]+" ");break}}if(u.length>0){var p=u[0];for(c=0;c0&&(s="\n"+a[c-1]);break}}}var h="a promise was created in a "+r+"handler "+i+"but was not returned from it, see http://goo.gl/rRqMUw"+s;n._warn(h,!0,e)}},setBounds:function(t,e){if(Y()){for(var r,n,o=t.stack.split("\n"),i=e.stack.split("\n"),s=-1,a=-1,u=0;u=a||(K=function(t){if(h.test(t))return!0;var e=Q(t);return!!(e&&e.fileName===r&&s<=e.line&&e.line<=a)})}},warn:L,deprecated:function(t,e){var r=t+" is deprecated and will be removed in a future version.";return e&&(r+=" Use "+e+" instead."),L(r)},CapturedTrace:J,fireDomEvent:A,fireGlobalEvent:$}}},{"./errors":12,"./util":36}],10:[function(t,e,r){"use strict";e.exports=function(t){function e(){return this.value}function r(){throw this.reason}t.prototype.return=t.prototype.thenReturn=function(r){return r instanceof t&&r.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:r},void 0)},t.prototype.throw=t.prototype.thenThrow=function(t){return this._then(r,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,r,void 0,{reason:t},void 0);var e=arguments[1],n=function(){throw e};return this.caught(t,n)},t.prototype.catchReturn=function(r){if(arguments.length<=1)return r instanceof t&&r.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:r},void 0);var n=arguments[1];n instanceof t&&n.suppressUnhandledRejections();var o=function(){return n};return this.caught(r,o)}}},{}],11:[function(t,e,r){"use strict";e.exports=function(t,e){var r=t.reduce,n=t.all;function o(){return n(this)}t.prototype.each=function(t){return r(this,t,e,0)._then(o,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return r(this,t,e,e)},t.each=function(t,n){return r(t,n,e,0)._then(o,void 0,void 0,t,void 0)},t.mapSeries=function(t,n){return r(t,n,e,e)}}},{}],12:[function(t,e,r){"use strict";var n,o,i=t("./es5"),s=i.freeze,a=t("./util"),u=a.inherits,c=a.notEnumerableProp;function l(t,e){function r(n){if(!(this instanceof r))return new r(n);c(this,"message","string"==typeof n?n:e),c(this,"name",t),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return u(r,Error),r}var f=l("Warning","warning"),p=l("CancellationError","cancellation error"),h=l("TimeoutError","timeout error"),y=l("AggregateError","aggregate error");try{n=TypeError,o=RangeError}catch(t){n=l("TypeError","type error"),o=l("RangeError","range error")}for(var d="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),_=0;_1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0)}function f(){return h.call(this,this.promise._target()._settledValue())}function p(t){if(!l(this,t))return s.e=t,s}function h(t){var o=this.promise,a=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?a.call(o._boundValue()):a.call(o._boundValue(),t);if(u===n)return u;if(void 0!==u){o._setReturnedNonUndefined();var h=r(u,o);if(h instanceof e){if(null!=this.cancelPromise){if(h._isCancelled()){var y=new i("late cancellation observer");return o._attachExtraTrace(y),s.e=y,s}h.isPending()&&h._attachCancellationCallback(new c(this))}return h._then(f,p,void 0,this,void 0)}}}return o.isRejected()?(l(this),s.e=t,s):(l(this),t)}return u.prototype.isFinallyHandler=function(){return 0===this.type},c.prototype._resultCancelled=function(){l(this.finallyHandler)},e.prototype._passThrough=function(t,e,r,n){return"function"!=typeof t?this.then():this._then(r,n,void 0,new u(this,e,t),void 0)},e.prototype.lastly=e.prototype.finally=function(t){return this._passThrough(t,0,h,h)},e.prototype.tap=function(t){return this._passThrough(t,1,h)},e.prototype.tapCatch=function(t){var r=arguments.length;if(1===r)return this._passThrough(t,1,void 0,h);var n,i=new Array(r-1),s=0;for(n=0;n0&&"function"==typeof arguments[e]&&(t=arguments[e]);var n=[].slice.call(arguments);t&&n.pop();var o=new r(n).promise();return void 0!==t?o.spread(t):o}}},{"./util":36}],18:[function(t,e,r){"use strict";e.exports=function(e,r,n,o,i,s){var a=e._getDomain,u=t("./util"),l=u.tryCatch,f=u.errorObj,p=e._async;function h(t,e,r,n){this.constructor$(t),this._promise._captureStackTrace();var o=a();this._callback=null===o?e:u.domainBind(o,e),this._preservedValues=n===i?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=[],p.invoke(this._asyncInit,this,void 0)}function y(t,r,o,i){if("function"!=typeof r)return n("expecting a function but got "+u.classString(r));var s=0;if(void 0!==o){if("object"!==c(o)||null===o)return e.reject(new TypeError("options argument must be an object but it is "+u.classString(o)));if("number"!=typeof o.concurrency)return e.reject(new TypeError("'concurrency' must be a number but it is "+u.classString(o.concurrency)));s=o.concurrency}return new h(t,r,s="number"==typeof s&&isFinite(s)&&s>=1?s:0,i).promise()}u.inherits(h,r),h.prototype._asyncInit=function(){this._init$(void 0,-2)},h.prototype._init=function(){},h.prototype._promiseFulfilled=function(t,r){var n=this._values,i=this.length(),a=this._preservedValues,u=this._limit;if(r<0){if(n[r=-1*r-1]=t,u>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(u>=1&&this._inFlight>=u)return n[r]=t,this._queue.push(r),!1;null!==a&&(a[r]=t);var c=this._promise,p=this._callback,h=c._boundValue();c._pushContext();var y=l(p).call(h,t,r,i),d=c._popContext();if(s.checkForgottenReturns(y,d,null!==a?"Promise.filter":"Promise.map",c),y===f)return this._reject(y.e),!0;var _=o(y,this._promise);if(_ instanceof e){var v=(_=_._target())._bitField;if(0==(50397184&v))return u>=1&&this._inFlight++,n[r]=_,_._proxy(this,-1*(r+1)),!1;if(0==(33554432&v))return 0!=(16777216&v)?(this._reject(_._reason()),!0):(this._cancel(),!0);y=_._value()}n[r]=y}return++this._totalResolved>=i&&(null!==a?this._filter(n,a):this._resolve(n),!0)},h.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlight1){i.deprecated("calling Promise.try with more than 1 argument");var c=arguments[1],l=arguments[2];n=s.isArray(c)?a(t).apply(l,c):a(t).call(l,c)}else n=a(t)();var f=u._popContext();return i.checkForgottenReturns(n,f,"Promise.try",u),u._resolveFromSyncValue(n),u},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,r){"use strict";var n=t("./util"),o=n.maybeWrapAsError,i=t("./errors").OperationalError,s=t("./es5"),a=/^(?:name|message|stack|cause)$/;function u(t){var e;if(function(t){return t instanceof Error&&s.getPrototypeOf(t)===Error.prototype}(t)){(e=new i(t)).name=t.name,e.message=t.message,e.stack=t.stack;for(var r=s.keys(t),o=0;o1){var r,n=new Array(e-1),o=0;for(r=0;r0&&"function"!=typeof t&&"function"!=typeof e){var r=".then() only accepts functions but was passed: "+c.classString(t);arguments.length>1&&(r+=", "+c.classString(e)),this._warn(r)}return this._then(t,e,void 0,void 0,void 0)},x.prototype.done=function(t,e){this._then(t,e,void 0,void 0,void 0)._setIsFinal()},x.prototype.spread=function(t){return"function"!=typeof t?i("expecting a function but got "+c.classString(t)):this.all()._then(t,void 0,void 0,v,void 0)},x.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},x.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new b(this).promise()},x.prototype.error=function(t){return this.caught(c.originatesFromRejection,t)},x.getNewLibraryCopy=e.exports,x.is=function(t){return t instanceof x},x.fromNode=x.fromCallback=function(t){var e=new x(_);e._captureStackTrace();var r=arguments.length>1&&!!Object(arguments[1]).multiArgs,n=P(t)(E(e,r));return n===j&&e._rejectCallback(n.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},x.all=function(t){return new b(t).promise()},x.cast=function(t){var e=g(t);return e instanceof x||((e=new x(_))._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},x.resolve=x.fulfilled=x.cast,x.reject=x.rejected=function(t){var e=new x(_);return e._captureStackTrace(),e._rejectCallback(t,!0),e},x.setScheduler=function(t){if("function"!=typeof t)throw new y("expecting a function but got "+c.classString(t));return p.setScheduler(t)},x.prototype._then=function(t,e,r,n,o){var i=void 0!==o,s=i?o:new x(_),u=this._target(),l=u._bitField;i||(s._propagateFrom(this,3),s._captureStackTrace(),void 0===n&&0!=(2097152&this._bitField)&&(n=0!=(50397184&l)?this._boundValue():u===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,s));var f=a();if(0!=(50397184&l)){var h,y,v=u._settlePromiseCtx;0!=(33554432&l)?(y=u._rejectionHandler0,h=t):0!=(16777216&l)?(y=u._fulfillmentHandler0,h=e,u._unsetRejectionIsUnhandled()):(v=u._settlePromiseLateCancellationObserver,y=new d("late cancellation observer"),u._attachExtraTrace(y),h=e),p.invoke(v,u,{handler:null===f?h:"function"==typeof h&&c.domainBind(f,h),promise:s,receiver:n,value:y})}else u._addCallbacks(t,e,s,n,f);return s},x.prototype._length=function(){return 65535&this._bitField},x.prototype._isFateSealed=function(){return 0!=(117506048&this._bitField)},x.prototype._isFollowing=function(){return 67108864==(67108864&this._bitField)},x.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},x.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},x.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},x.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},x.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},x.prototype._isFinal=function(){return(4194304&this._bitField)>0},x.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},x.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},x.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},x.prototype._setAsyncGuaranteed=function(){p.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},x.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];if(e!==u)return void 0===e&&this._isBound()?this._boundValue():e},x.prototype._promiseAt=function(t){return this[4*t-4+2]},x.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},x.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},x.prototype._boundValue=function(){},x.prototype._migrateCallback0=function(t){t._bitField;var e=t._fulfillmentHandler0,r=t._rejectionHandler0,n=t._promise0,o=t._receiverAt(0);void 0===o&&(o=u),this._addCallbacks(e,r,n,o,null)},x.prototype._migrateCallbackAt=function(t,e){var r=t._fulfillmentHandlerAt(e),n=t._rejectionHandlerAt(e),o=t._promiseAt(e),i=t._receiverAt(e);void 0===i&&(i=u),this._addCallbacks(r,n,o,i,null)},x.prototype._addCallbacks=function(t,e,r,n,o){var i=this._length();if(i>=65531&&(i=0,this._setLength(0)),0===i)this._promise0=r,this._receiver0=n,"function"==typeof t&&(this._fulfillmentHandler0=null===o?t:c.domainBind(o,t)),"function"==typeof e&&(this._rejectionHandler0=null===o?e:c.domainBind(o,e));else{var s=4*i-4;this[s+2]=r,this[s+3]=n,"function"==typeof t&&(this[s+0]=null===o?t:c.domainBind(o,t)),"function"==typeof e&&(this[s+1]=null===o?e:c.domainBind(o,e))}return this._setLength(i+1),i},x.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},x.prototype._resolveCallback=function(t,e){if(0==(117506048&this._bitField)){if(t===this)return this._rejectCallback(n(),!1);var r=g(t,this);if(!(r instanceof x))return this._fulfill(t);e&&this._propagateFrom(r,2);var o=r._target();if(o!==this){var i=o._bitField;if(0==(50397184&i)){var s=this._length();s>0&&o._migrateCallback0(this);for(var a=1;a>>16)){if(t===this){var r=n();return this._attachExtraTrace(r),this._reject(r)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!=(134217728&e)?this._settlePromises():p.settlePromises(this))}},x.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=t,this._isFinal())return p.fatalError(t,c.isNode);(65535&e)>0?p.settlePromises(this):this._ensurePossibleRejectionHandled()}},x.prototype._fulfillPromises=function(t,e){for(var r=1;r0){if(0!=(16842752&t)){var r=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,r,t),this._rejectPromises(e,r)}else{var n=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,n,t),this._fulfillPromises(e,n)}this._setLength(0)}this._clearCancellationData()},x.prototype._settledValue=function(){var t=this._bitField;return 0!=(33554432&t)?this._rejectionHandler0:0!=(16777216&t)?this._fulfillmentHandler0:void 0},x.defer=x.pending=function(){return S.deprecated("Promise.defer","new Promise"),{promise:new x(_),resolve:T,reject:N}},c.notEnumerableProp(x,"_makeSelfResolutionError",n),t("./method")(x,_,g,i,S),t("./bind")(x,_,g,S),t("./cancel")(x,b,i,S),t("./direct_resolve")(x),t("./synchronous_inspection")(x),t("./join")(x,b,g,_,p,a),x.Promise=x,x.version="3.5.1",t("./map.js")(x,b,i,g,_,S),t("./call_get.js")(x),t("./using.js")(x,i,g,O,_,S),t("./timers.js")(x,_,S),t("./generators.js")(x,i,_,g,s,S),t("./nodeify.js")(x),t("./promisify.js")(x,_),t("./props.js")(x,b,g,i),t("./race.js")(x,_,g,i),t("./reduce.js")(x,b,i,g,_,S),t("./settle.js")(x,b,S),t("./some.js")(x,b,i),t("./filter.js")(x,_),t("./each.js")(x,_),t("./any.js")(x),c.toFastProperties(x),c.toFastProperties(x.prototype),k({a:1}),k({b:2}),k({c:3}),k(1),k((function(){})),k(void 0),k(!1),k(new x(_)),S.setBounds(f.firstLineError,c.lastLineError),x}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(t,e,r){"use strict";e.exports=function(e,r,n,o,i){var s=t("./util");function a(t){var n=this._promise=new e(r);t instanceof e&&n._propagateFrom(t,3),n._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return s.isArray,s.inherits(a,i),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function t(r,i){var a=n(this._values,this._promise);if(a instanceof e){var u=(a=a._target())._bitField;if(this._values=a,0==(50397184&u))return this._promise._setAsyncGuaranteed(),a._then(t,this._reject,void 0,this,i);if(0==(33554432&u))return 0!=(16777216&u)?this._reject(a._reason()):this._cancel();a=a._value()}if(null!==(a=s.asArray(a)))0!==a.length?this._iterate(a):-5===i?this._resolveEmptyArray():this._resolve(function(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}(i));else{var c=o("expecting an array or an iterable object but got "+s.classString(a)).reason();this._promise._rejectCallback(c,!1)}},a.prototype._iterate=function(t){var r=this.getActualLength(t.length);this._length=r,this._values=this.shouldCopyValues()?new Array(r):this._values;for(var o=this._promise,i=!1,s=null,a=0;a=this._length&&(this._resolve(this._values),!0)},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var r=0;r=this._length){var r;if(this._isMap)r=function(t){for(var e=new i,r=t.length/2|0,n=0;n>1},e.prototype.props=function(){return f(this)},e.props=function(t){return f(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,r){"use strict";function n(t){this._capacity=t,this._length=0,this._front=0}n.prototype._willBeOverCapacity=function(t){return this._capacity=this._length&&(this._resolve(this._values),!0)},i.prototype._promiseFulfilled=function(t,e){var r=new o;return r._bitField=33554432,r._settledValueField=t,this._promiseResolved(e,r)},i.prototype._promiseRejected=function(t,e){var r=new o;return r._bitField=16777216,r._settledValueField=t,this._promiseResolved(e,r)},e.settle=function(t){return n.deprecated(".settle()",".reflect()"),new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,r){"use strict";e.exports=function(e,r,n){var o=t("./util"),i=t("./errors").RangeError,s=t("./errors").AggregateError,a=o.isArray,u={};function c(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function l(t,e){if((0|e)!==e||e<0)return n("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var r=new c(t),o=r.promise();return r.setHowMany(e),r.init(),o}o.inherits(c,r),c.prototype._init=function(){if(this._initialized)if(0!==this._howMany){this._init$(void 0,-5);var t=a(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}else this._resolve([])},c.prototype.init=function(){this._initialized=!0,this._init()},c.prototype.setUnwrap=function(){this._unwrap=!0},c.prototype.howMany=function(){return this._howMany},c.prototype.setHowMany=function(t){this._howMany=t},c.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},c.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},c.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(u),this._checkOutcome())},c.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new s,e=this.length();e0?this._reject(t):this._cancel(),!0}return!1},c.prototype._fulfilled=function(){return this._totalResolved},c.prototype._rejected=function(){return this._values.length-this.length()},c.prototype._addRejected=function(t){this._values.push(t)},c.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},c.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},c.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new i(e)},c.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return l(t,e)},e.prototype.some=function(t){return l(this,t)},e._SomePromiseArray=c}},{"./errors":12,"./util":36}],32:[function(t,e,r){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var r=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},n=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},o=e.prototype.isFulfilled=function(){return 0!=(33554432&this._bitField)},i=e.prototype.isRejected=function(){return 0!=(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0==(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!=(50331648&this._bitField)};e.prototype.isCancelled=function(){return 0!=(8454144&this._bitField)},t.prototype.__isCancelled=function(){return 65536==(65536&this._bitField)},t.prototype._isCancelled=function(){return this._target().__isCancelled()},t.prototype.isCancelled=function(){return 0!=(8454144&this._target()._bitField)},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return i.call(this._target())},t.prototype.isFulfilled=function(){return o.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return r.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),n.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,r){"use strict";e.exports=function(e,r){var n=t("./util"),o=n.errorObj,i=n.isObject,s={}.hasOwnProperty;return function(t,a){if(i(t)){if(t instanceof e)return t;var u=function(t){try{return function(t){return t.then}(t)}catch(t){return o.e=t,o}}(t);if(u===o){a&&a._pushContext();var c=e.reject(u.e);return a&&a._popContext(),c}if("function"==typeof u)return function(t){try{return s.call(t,"_promise0")}catch(t){return!1}}(t)?(c=new e(r),t._then(c._fulfill,c._reject,void 0,c,null),c):function(t,i,s){var a=new e(r),u=a;s&&s._pushContext(),a._captureStackTrace(),s&&s._popContext();var c=n.tryCatch(i).call(t,(function(t){a&&(a._resolveCallback(t),a=null)}),(function(t){a&&(a._rejectCallback(t,!1,!0),a=null)}));return a&&c===o&&(a._rejectCallback(c.e,!0,!0),a=null),u}(t,u,a)}return t}}},{"./util":36}],34:[function(t,e,r){"use strict";e.exports=function(e,r,n){var o=t("./util"),i=e.TimeoutError;function s(t){this.handle=t}s.prototype._resultCancelled=function(){clearTimeout(this.handle)};var a=function(t){return u(+this).thenReturn(t)},u=e.delay=function(t,o){var i,u;return void 0!==o?(i=e.resolve(o)._then(a,null,null,t,void 0),n.cancellation()&&o instanceof e&&i._setOnCancel(o)):(i=new e(r),u=setTimeout((function(){i._fulfill()}),+t),n.cancellation()&&i._setOnCancel(new s(u)),i._captureStackTrace()),i._setAsyncGuaranteed(),i};function c(t){return clearTimeout(this.handle),t}function l(t){throw clearTimeout(this.handle),t}e.prototype.delay=function(t){return u(t,this)},e.prototype.timeout=function(t,e){var r,a;t=+t;var u=new s(setTimeout((function(){r.isPending()&&function(t,e,r){var n;n="string"!=typeof e?e instanceof Error?e:new i("operation timed out"):new i(e),o.markAsOriginatingFromRejection(n),t._attachExtraTrace(n),t._reject(n),null!=r&&r.cancel()}(r,e,a)}),t));return n.cancellation()?(a=this.then(),(r=a._then(c,l,void 0,u,void 0))._setOnCancel(u)):r=this._then(c,l,void 0,u,void 0),r}}},{"./util":36}],35:[function(t,e,r){"use strict";e.exports=function(e,r,n,o,i,s){var a=t("./util"),u=t("./errors").TypeError,c=t("./util").inherits,l=a.errorObj,f=a.tryCatch,p={};function h(t){setTimeout((function(){throw t}),0)}function y(t,r){var o=0,s=t.length,a=new e(i);return function i(){if(o>=s)return a._fulfill();var u=function(t){var e=n(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}(t[o++]);if(u instanceof e&&u._isDisposable()){try{u=n(u._getDisposer().tryDispose(r),t.promise)}catch(t){return h(t)}if(u instanceof e)return u._then(i,h,null,null,null)}i()}(),a}function d(t,e,r){this._data=t,this._promise=e,this._context=r}function _(t,e,r){this.constructor$(t,e,r)}function v(t){return d.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function m(t){this.length=t,this.promise=null,this[t-1]=null}d.prototype.data=function(){return this._data},d.prototype.promise=function(){return this._promise},d.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():p},d.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=e!==p?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},d.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},c(_,d),_.prototype.doDispose=function(t,e){return this.data().call(t,t,e)},m.prototype._resultCancelled=function(){for(var t=this.length,r=0;r0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new _(t,this,o());throw new u}}},{"./errors":12,"./util":36}],36:[function(t,e,o){"use strict";var i=t("./es5"),s="undefined"==typeof navigator,a={e:{}},u,l="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==n?n:void 0!==this?this:null;function f(){try{var t=u;return u=null,t.apply(this,arguments)}catch(t){return a.e=t,a}}function p(t){return u=t,f}var h=function(t,e){var r={}.hasOwnProperty;function n(){for(var n in this.constructor=t,this.constructor$=e,e.prototype)r.call(e.prototype,n)&&"$"!==n.charAt(n.length-1)&&(this[n+"$"]=e.prototype[n])}return n.prototype=e.prototype,t.prototype=new n,t.prototype};function y(t){return null==t||!0===t||!1===t||"string"==typeof t||"number"==typeof t}function d(t){return"function"==typeof t||"object"===c(t)&&null!==t}function _(t){return y(t)?new Error(P(t)):t}function v(t,e){var r,n=t.length,o=new Array(n+1);for(r=0;r1,n=e.length>0&&!(1===e.length&&"constructor"===e[0]),o=O.test(t+"")&&i.names(t).length>0;if(r||n||o)return!0}return!1}catch(t){return!1}}function A(t){function e(){}e.prototype=t;for(var r=8;r--;)new e;return t}var $=/^[a-z$_][a-z$_0-9]*$/i;function E(t){return $.test(t)}function j(t,e,r){for(var n=new Array(t),o=0;o10||W[0]>0),q.isNode&&q.toFastProperties(r);try{throw new Error}catch(t){q.lastLineError=t}e.exports=q},{"./es5":13}]},{},[4])(4)},"object"==c(e)&&void 0!==t?t.exports=u():(s=[],void 0===(a="function"==typeof(i=u)?i.apply(e,s):i)||(t.exports=a)),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,r(11),r(10),r(70).setImmediate)},function(t,e,r){"use strict";var n=t.exports={};n.DocumentNotFoundError=null,n.general={},n.general.default="Validator failed for path `{PATH}` with value `{VALUE}`",n.general.required="Path `{PATH}` is required.",n.Number={},n.Number.min="Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).",n.Number.max="Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).",n.Number.enum="`{VALUE}` is not a valid enum value for path `{PATH}`.",n.Date={},n.Date.min="Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).",n.Date.max="Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).",n.String={},n.String.enum="`{VALUE}` is not a valid enum value for path `{PATH}`.",n.String.match="Path `{PATH}` is invalid ({VALUE}).",n.String.minlength="Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).",n.String.maxlength="Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH})."},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){return(o=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function i(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=a(t);if(e){var o=a(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return s(this,r)}}function s(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=r(4),c=r(5),l=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&o(t,e)}(r,t);var e=i(r); +/*! + * OverwriteModel Error constructor. + */function r(t,n,o,i){var s,a;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r);var l=u.messages;return a=null!=l.DocumentNotFoundError?"function"==typeof l.DocumentNotFoundError?l.DocumentNotFoundError(t,n):l.DocumentNotFoundError:'No document found for query "'+c.inspect(t)+'" on model "'+n+'"',(s=e.call(this,a)).result=i,s.numAffected=o,s.filter=t,s.query=t,s}return r}(u);Object.defineProperty(l.prototype,"name",{value:"DocumentNotFoundError"}), +/*! + * exports + */ +t.exports=l},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){return(o=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function i(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=a(t);if(e){var o=a(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return s(this,r)}}function s(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&o(t,e)}(r,t);var e=i(r);function r(t,n,o){var i;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r);var s=o.join(", ");return(i=e.call(this,'No matching document found for id "'+t._id+'" version '+n+' modifiedPaths "'+s+'"')).version=n,i.modifiedPaths=o,i}return r}(r(4));Object.defineProperty(u.prototype,"name",{value:"VersionError"}), +/*! + * exports + */ +t.exports=u},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){return(o=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function i(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=a(t);if(e){var o=a(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return s(this,r)}}function s(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&o(t,e)}(r,t);var e=i(r);function r(t){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r);return e.call(this,"Can't save() the same doc multiple times in parallel. Document: "+t._id)}return r}(r(4));Object.defineProperty(u.prototype,"name",{value:"ParallelSaveError"}), +/*! + * exports + */ +t.exports=u},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){return(o=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function i(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=a(t);if(e){var o=a(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return s(this,r)}}function s(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&o(t,e)}(r,t);var e=i(r); +/*! + * OverwriteModel Error constructor. + * @param {String} name + */function r(t){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r),e.call(this,"Cannot overwrite `"+t+"` model once compiled.")}return r}(r(4));Object.defineProperty(u.prototype,"name",{value:"OverwriteModelError"}), +/*! + * exports + */ +t.exports=u},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){return(o=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function i(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=a(t);if(e){var o=a(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return s(this,r)}}function s(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&o(t,e)}(r,t);var e=i(r); +/*! + * MissingSchema Error constructor. + * @param {String} name + */function r(t){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r);var n="Schema hasn't been registered for model \""+t+'".\nUse mongoose.model(name, schema)';return e.call(this,n)}return r}(r(4));Object.defineProperty(u.prototype,"name",{value:"MissingSchemaError"}), +/*! + * exports + */ +t.exports=u},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){return(o=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function i(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=a(t);if(e){var o=a(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return s(this,r)}}function s(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&o(t,e)}(r,t);var e=i(r); +/*! + * DivergentArrayError constructor. + * @param {Array} paths + */function r(t){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r);var n="For your own good, using `document.save()` to update an array which was selected using an $elemMatch projection OR populated using skip, limit, query conditions, or exclusion of the _id field when the operation results in a $pop or $set of the entire array is not supported. The following path(s) would have been modified unsafely:\n "+t.join("\n ")+"\nUse Model.update() to update these arrays instead.";return e.call(this,n)}return r}(r(4));Object.defineProperty(u.prototype,"name",{value:"DivergentArrayError"}), +/*! + * exports + */ +t.exports=u},function(t,e,r){"use strict";var n=r(33); +/*! + * ignore + */t.exports=function(t){var e,r;t.$immutable?(t.$immutableSetter=(e=t.path,r=t.options.immutable,function(t){if(null==this||null==this.$__)return t;if(this.isNew)return t;if(!("function"==typeof r?r.call(this,this):r))return t;var o=null!=this.$__.priorDoc?this.$__.priorDoc.$__getValue(e):this.$__getValue(e);if("throw"===this.$__.strictMode&&t!==o)throw new n(e,"Path `"+e+"` is immutable and strict mode is set to throw.",!0);return o}),t.set(t.$immutableSetter)):t.$immutableSetter&&(t.setters=t.setters.filter((function(e){return e!==t.$immutableSetter})),delete t.$immutableSetter)}},function(t,e,r){"use strict";var n=r(5).inspect;t.exports=function(t){if("function"==typeof t)return n(t).startsWith("[AsyncFunction:")}},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){return(o=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function i(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=a(t);if(e){var o=a(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return s(this,r)}}function s(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&o(t,e)}(r,t);var e=i(r);function r(t,n,o){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r),e.call(this,'Parameter "'+n+'" to '+o+"() must be an object, got "+t.toString())}return r}(r(4));Object.defineProperty(u.prototype,"name",{value:"ObjectParameterError"}),t.exports=u},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){return(o=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function i(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=a(t);if(e){var o=a(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return s(this,r)}}function s(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&o(t,e)}(r,t);var e=i(r);function r(t){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r);return e.call(this,"Can't validate() the same doc multiple times in parallel. Document: "+t._id)}return r}(r(14));Object.defineProperty(u.prototype,"name",{value:"ParallelValidateError"}), +/*! + * exports + */ +t.exports=u},function(t,e,r){"use strict";(function(e){function r(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return n(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return n(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var o=0,i=function(){};return{s:i,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function n(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=s)){var n=i[p];if(n.isAsync){var a=[l(v),l((function(t){if(t){if(y)return;return y=!0,o(t)}if(0==--h&&p>=s)return o(null)}))];u(n.fn,r,a,a[0])}else if(n.fn.length>0){a=[l(v)];for(var f=arguments.length>=2?arguments:[null].concat(d),_=1;_=s)return h>0?void 0:e.nextTick((function(){o(null)}));t()}}}};function v(t){if(t){if(y)return;return y=!0,o(t)}if(++p>=s)return h>0?void 0:o(null);_.apply(r,arguments)}_.apply(null,[null].concat(n))},i.prototype.execPreSync=function(t,e,r){for(var n=a(this._pres,t,[]),o=n.length,i=0;i=f)return i.call(null,h);t()}));u(e,r,[h].concat(y).concat([_]),_)}else{if(++p>=f)return i.call(null,h);t()}else{var v=l((function(e){return e?(h=e,t()):++p>=f?i.apply(null,[null].concat(n)):void t()}));if(e.length===o+2)return++p>=f?i.apply(null,[null].concat(n)):t();if(e.length===o+1)u(e,r,y.concat([v]),v);else{var m,g;try{g=e.apply(r,y)}catch(t){m=t,h=t}if(c(g))return g.then((function(){return v()}),(function(t){return v(t)}));if(++p>=f)return i.apply(null,[m].concat(n));t()}}};y()},i.prototype.execPostSync=function(t,e,r){for(var n=a(this._posts,t,[]),o=n.length,i=0;i0?n[n.length-1]:null,a=("function"==typeof i&&n.slice(0,n.length-1),this),u=(o=o||{}).checkForPromise;this.execPre(t,r,n,(function(c){if(c){for(var l=o.numCallbackParams||0,f=o.contextParameter?[r]:[],p=f.length;p=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0;--p){var h=t.path(f.slice(0,p).join("."));null!=h&&(h.$isMongooseDocumentArray||h.$isSingleNested)&&l.push({parentPath:e.split(".").slice(0,p).join("."),parentSchemaType:h})}if(Array.isArray(r[e])&&c.$isMongooseDocumentArray)!function(t,e,r){var n=e.schema.options.timestamps;if(n)for(var o=t.length,i=s(n,"createdAt"),u=s(n,"updatedAt"),c=0;c0){var y,d=n(l);try{for(d.s();!(y=d.n()).done;){var _=y.value,v=_.parentPath,m=_.parentSchemaType,g=m.schema.options.timestamps,b=s(g,"updatedAt");if(g&&null!=b)if(m.$isSingleNested)r[v+"."+b]=o;else if(m.$isMongooseDocumentArray){var w=e.substr(v.length+1);if(/^\d+$/.test(w)){r[v+"."+w][b]=o;continue}var O=w.indexOf(".");r[v+"."+(w=-1!==O?w.substr(0,O):w)+"."+b]=o}}}catch(t){d.e(t)}finally{d.f()}}else if(null!=c.schema&&c.schema!=t&&r[e]){var S=c.schema.options.timestamps,A=s(S,"createdAt"),$=s(S,"updatedAt");if(!S)return;null!=$&&(r[e][$]=o),null!=A&&(r[e][A]=o)}}}t.exports=a},function(t,e,r){"use strict";t.exports=function(t){return t.replace(/\.\$(\[[^\]]*\])?(?=\.)/g,".0").replace(/\.\$(\[[^\]]*\])?$/g,".0")}},function(t,e,r){"use strict"; +/*! + * ignore + */var n=r(3);t.exports= +/*! + * ignore + */ +function(t,e,r,o,i){var s=o,a=s,u=n(i,"overwrite",!1),c=n(i,"timestamps",!0);if(!c||null==s)return o;var l=null!=c&&!1===c.createdAt,f=null!=c&&!1===c.updatedAt;if(u)return o&&o.$set&&(o=o.$set,s.$set={},a=s.$set),f||!r||o[r]||(a[r]=t),l||!e||o[e]||(a[e]=t),s;if(o=o||{},Array.isArray(s))return s.push({$set:{updatedAt:t}}),s;if(s.$set=s.$set||{},!f&&r&&(!o.$currentDate||!o.$currentDate[r])){var p=!1;if(-1!==r.indexOf("."))for(var h=r.split("."),y=1;y=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&!t?this:this.set((function(t){return"string"!=typeof t&&(t=e.cast(t)),t?t.toLowerCase():t}))},f.prototype.uppercase=function(t){var e=this;return arguments.length>0&&!t?this:this.set((function(t){return"string"!=typeof t&&(t=e.cast(t)),t?t.toUpperCase():t}))},f.prototype.trim=function(t){var e=this;return arguments.length>0&&!t?this:this.set((function(t){return"string"!=typeof t&&(t=e.cast(t)),t?t.trim():t}))},f.prototype.minlength=function(t,e){if(this.minlengthValidator&&(this.validators=this.validators.filter((function(t){return t.validator!==this.minlengthValidator}),this)),null!=t){var r=e||s.messages.String.minlength;r=r.replace(/{MINLENGTH}/,t),this.validators.push({validator:this.minlengthValidator=function(e){return null===e||e.length>=t},message:r,type:"minlength",minlength:t})}return this},f.prototype.minLength=f.prototype.minlength,f.prototype.maxlength=function(t,e){if(this.maxlengthValidator&&(this.validators=this.validators.filter((function(t){return t.validator!==this.maxlengthValidator}),this)),null!=t){var r=e||s.messages.String.maxlength;r=r.replace(/{MAXLENGTH}/,t),this.validators.push({validator:this.maxlengthValidator=function(e){return null===e||e.length<=t},message:r,type:"maxlength",maxlength:t})}return this},f.prototype.maxLength=f.prototype.maxlength,f.prototype.match=function(t,e){var r=e||s.messages.String.match;return this.validators.push({validator:function(e){return!!t&&(t.lastIndex=0,null==e||""===e||t.test(e))},message:r,type:"regexp",regexp:t}),this},f.prototype.checkRequired=function(t,e){return i._isRef(this,t,e,!0)?!!t:("function"==typeof this.constructor.checkRequired?this.constructor.checkRequired():f.checkRequired())(t)},f.prototype.cast=function(t,e,r){if(i._isRef(this,t,e,r))return"string"==typeof t?t:this._castRef(t,e,r);var n;n="function"==typeof this._castFunction?this._castFunction:"function"==typeof this.constructor.cast?this.constructor.cast():f.cast();try{return n(t)}catch(e){throw new l("string",t,this.path,null,this)}};var h=c.options(i.prototype.$conditionalHandlers,{$all:function(t){var e=this;return Array.isArray(t)?t.map((function(t){return e.castForQuery(t)})):[this.castForQuery(t)]},$gt:p,$gte:p,$lt:p,$lte:p,$options:String,$regex:p,$not:p});Object.defineProperty(f.prototype,"$conditionalHandlers",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(h)}),f.prototype.castForQuery=function(t,e){var r;if(2===arguments.length){if(!(r=this.$conditionalHandlers[t]))throw new Error("Can't use "+t+" with String.");return r.call(this,e)}return e=t,"[object RegExp]"===Object.prototype.toString.call(e)?e:this._castForQuery(e)}, +/*! + * Module exports. + */ +t.exports=f},function(t,e,r){"use strict";function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=u(t);if(e){var o=u(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return a(this,r)}}function a(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var c=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}(r,t);var e=s(r);function r(){return o(this,r),e.apply(this,arguments)}return r}(r(8)),l=r(9);Object.defineProperty(c.prototype,"enum",l),Object.defineProperty(c.prototype,"match",l),Object.defineProperty(c.prototype,"lowercase",l),Object.defineProperty(c.prototype,"trim",l),Object.defineProperty(c.prototype,"uppercase",l),Object.defineProperty(c.prototype,"minLength",l),Object.defineProperty(c.prototype,"minlength",l),Object.defineProperty(c.prototype,"maxLength",l),Object.defineProperty(c.prototype,"maxlength",l),Object.defineProperty(c.prototype,"populate",l), +/*! + * ignore + */ +t.exports=c},function(t,e,r){"use strict";function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=u(t);if(e){var o=u(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return a(this,r)}}function a(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var c=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}(r,t);var e=s(r);function r(){return o(this,r),e.apply(this,arguments)}return r}(r(8)),l=r(9);Object.defineProperty(c.prototype,"min",l),Object.defineProperty(c.prototype,"max",l),Object.defineProperty(c.prototype,"enum",l),Object.defineProperty(c.prototype,"populate",l), +/*! + * ignore + */ +t.exports=c},function(t,e,r){"use strict";var n=r(21); +/*! + * Given a value, cast it to a number, or throw a `CastError` if the value + * cannot be casted. `null` and `undefined` are considered valid. + * + * @param {Any} value + * @param {String} [path] optional the path to set on the CastError + * @return {Boolean|null|undefined} + * @throws {Error} if `value` is not one of the allowed values + * @api private + */t.exports=function(t){return null==t?t:""===t?null:("string"!=typeof t&&"boolean"!=typeof t||(t=Number(t)),n.ok(!isNaN(t)),t instanceof Number?t.valueOf():"number"==typeof t?t:Array.isArray(t)||"function"!=typeof t.valueOf?t.toString&&!Array.isArray(t)&&t.toString()==Number(t)?Number(t):void n.ok(!1):Number(t.valueOf()))}},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */var n=r(13),o=r(6),i=r(52),s=r(1);function a(t,e){o.call(this,t,e,"Boolean")}a.schemaName="Boolean",a.defaultOptions={}, +/*! + * Inherits from SchemaType. + */ +a.prototype=Object.create(o.prototype),a.prototype.constructor=a, +/*! + * ignore + */ +a._cast=i,a.set=o.set,a.cast=function(t){return 0===arguments.length||(!1===t&&(t=this._defaultCaster),this._cast=t),this._cast}, +/*! + * ignore + */ +a._defaultCaster=function(t){if(null!=t&&"boolean"!=typeof t)throw new Error;return t}, +/*! + * ignore + */ +a._checkRequired=function(t){return!0===t||!1===t},a.checkRequired=o.checkRequired,a.prototype.checkRequired=function(t){return this.constructor._checkRequired(t)},Object.defineProperty(a,"convertToTrue",{get:function(){return i.convertToTrue},set:function(t){i.convertToTrue=t}}),Object.defineProperty(a,"convertToFalse",{get:function(){return i.convertToFalse},set:function(t){i.convertToFalse=t}}),a.prototype.cast=function(t){var e;e="function"==typeof this._castFunction?this._castFunction:"function"==typeof this.constructor.cast?this.constructor.cast():a.cast();try{return e(t)}catch(e){throw new n("Boolean",t,this.path,e,this)}},a.$conditionalHandlers=s.options(o.prototype.$conditionalHandlers,{}),a.prototype.castForQuery=function(t,e){var r;return 2===arguments.length?(r=a.$conditionalHandlers[t])?r.call(this,e):this._castForQuery(e):this._castForQuery(t)},a.prototype._castNullish=function(t){if(void 0===t&&null!=this.$$context&&null!=this.$$context._mongooseOptions&&this.$$context._mongooseOptions.omitUndefined)return t;var e="function"==typeof this.constructor.cast?this.constructor.cast():a.cast();return null==e?t:!(e.convertToFalse instanceof Set&&e.convertToFalse.has(t))&&(!!(e.convertToTrue instanceof Set&&e.convertToTrue.has(t))||t)}, +/*! + * Module exports. + */ +t.exports=a},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */var n,o,i=r(56),s=r(13),a=r(18).EventEmitter,u=r(164),c=r(6),l=r(93),f=r(3),p=r(94),h=r(5),y=r(1),d=r(95),_=r(0).arrayAtomicsSymbol,v=r(0).arrayPathSymbol,m=r(0).documentArrayParent;function g(t,e,r,n){null!=n&&null!=n._id?e=p(e,n):null!=r&&null!=r._id&&(e=p(e,r));var o=b(e,r);o.prototype.$basePath=t,i.call(this,t,o,r),this.schema=e,this.schemaOptions=n||{},this.$isMongooseDocumentArray=!0,this.Constructor=o,o.base=e.base;var s=this.defaultValue;"defaultValue"in this&&void 0===s||this.default((function(){var t=s.call(this);return Array.isArray(t)||(t=[t]),t}));var a=this;this.$embeddedSchemaType=new c(t+".$",{required:f(this,"schemaOptions.required",!1)}),this.$embeddedSchemaType.cast=function(t,e,r){return a.cast(t,e,r)[0]},this.$embeddedSchemaType.$isMongooseDocumentArrayElement=!0,this.$embeddedSchemaType.caster=this.Constructor,this.$embeddedSchemaType.schema=this.schema} +/*! + * Ignore + */ +function b(t,e,n){function i(){o.apply(this,arguments),this.$session(this.ownerDocument().$session())}o||(o=r(28)),t._preCompile();var s=null!=n?n.prototype:o.prototype;for(var u in i.prototype=Object.create(s),i.prototype.$__setSchema(t),i.schema=t,i.prototype.constructor=i,i.$isArraySubdocument=!0,i.events=new a,t.methods)i.prototype[u]=t.methods[u];for(var c in t.statics)i[c]=t.statics[c];for(var l in a.prototype)i[l]=a.prototype[l];return i.options=e,i} +/*! + * Scopes paths selected in a query to this array. + * Necessary for proper default application of subdocument values. + * + * @param {DocumentArrayPath} array - the array to scope `fields` paths + * @param {Object|undefined} fields - the root fields selected in the query + * @param {Boolean|undefined} init - if we are being created part of a query result + */ +function w(t,e,r){if(r&&e){for(var n,o,i,s=t.path+".",a=Object.keys(e),u=a.length,c={};u--;)if((o=a[u]).startsWith(s)){if("$"===(i=o.substring(s.length)))continue;i.startsWith("$.")&&(i=i.substr(2)),n||(n=!0),c[i]=e[o]}return n&&c||void 0}}g.schemaName="DocumentArray",g.options={castNonArrays:!0}, +/*! + * Inherits from ArrayType. + */ +g.prototype=Object.create(i.prototype),g.prototype.constructor=g,g.prototype.OptionsConstructor=u,g.prototype.discriminator=function(t,e,r){"function"==typeof t&&(t=y.getFunctionName(t)),r=r||{};var n=y.isPOJO(r)?r.value:r,o=f(r,"clone",!0);e.instanceOfSchema&&o&&(e=e.clone());var i=b(e=l(this.casterConstructor,t,e,n),null,this.casterConstructor);i.baseCasterConstructor=this.casterConstructor;try{Object.defineProperty(i,"name",{value:t})}catch(t){}return this.casterConstructor.discriminators[t]=i,this.casterConstructor.discriminators[t]},g.prototype.doValidate=function(t,e,i,s){n||(n=r(17));var a=this;try{c.prototype.doValidate.call(this,t,(function(r){if(r)return e(r);var u,c=t&&t.length;if(!c)return e();if(s&&s.updateValidator)return e();t.isMongooseDocumentArray||(t=new n(t,a.path,i));function l(t){null!=t&&(u=t),--c||e(u)}for(var f=0,p=c;fr.max&&(r.max=o.max),r.containsNonArrayItem=r.containsNonArrayItem||o.containsNonArrayItem}return r.min=r.min+1,r.max=r.max+1,r}},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return o(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0,i=function(){};return{s:i,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0?t:n)}return this}}; +/*! + * If this is a document array, each element may contain single + * populated paths, so we need to modify the top-level document's + * populated cache. See gh-8247, gh-8265. + */ +function v(t){var e=t[p];if(e&&null!=e.$__.populated){var r,o=n(Object.keys(e.$__.populated).filter((function(e){return e.startsWith(t[h]+".")})));try{var i=function(){var n=r.value,o=n.slice((t[h]+".").length);if(!Array.isArray(e.$__.populated[n].value))return"continue";e.$__.populated[n].value=t.map((function(t){return t.$populated(o)}))};for(o.s();!(r=o.n()).done;)i()}catch(t){o.e(t)}finally{o.f()}}}t.exports=_}).call(this,r(2).Buffer)},function(t,e,r){"use strict";function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=u(t);if(e){var o=u(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return a(this,r)}}function a(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var c=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}(r,t);var e=s(r);function r(){return o(this,r),e.apply(this,arguments)}return r}(r(8)),l=r(9);Object.defineProperty(c.prototype,"excludeIndexes",l),Object.defineProperty(c.prototype,"_id",l), +/*! + * ignore + */ +t.exports=c},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var o,i=r(13),s=r(18).EventEmitter,a=r(76),u=r(166),c=r(6),l=r(51),f=r(35).castToNumber,p=r(93),h=r(86),y=r(3),d=r(95),_=r(94),v=r(23).internalToObjectOptions,m=r(1);function g(t,e,r){t=_(t,r),this.caster=b(t),this.caster.path=e,this.caster.prototype.$basePath=e,this.schema=t,this.$isSingleNested=!0,c.call(this,e,r,"Embedded")} +/*! + * ignore + */ +/*! + * ignore + */ +function b(t,e){o||(o=r(58));var n=function(t,e,r){var n=this;this.$__parent=r,o.apply(this,arguments),this.$session(this.ownerDocument().$session()),r&&(r.$on("save",(function(){n.emit("save",n),n.constructor.emit("save",n)})),r.$on("isNew",(function(t){n.isNew=t,n.emit("isNew",t),n.constructor.emit("isNew",t)})))};t._preCompile();var i=null!=e?e.prototype:o.prototype;for(var a in(n.prototype=Object.create(i)).$__setSchema(t),n.prototype.constructor=n,n.schema=t,n.$isSingleNested=!0,n.events=new s,n.prototype.toBSON=function(){return this.toObject(v)},t.methods)n.prototype[a]=t.methods[a];for(var u in t.statics)n[u]=t.statics[u];for(var c in s.prototype)n[c]=s.prototype[c];return n} +/*! + * Special case for when users use a common location schema to represent + * locations for use with $geoWithin. + * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/ + * + * @param {Object} val + * @api private + */t.exports=g,g.prototype=Object.create(c.prototype),g.prototype.constructor=g,g.prototype.OptionsConstructor=u,g.prototype.$conditionalHandlers.$geoWithin=function(t){return{$geometry:this.castForQuery(t.$geometry)}}, +/*! + * ignore + */ +g.prototype.$conditionalHandlers.$near=g.prototype.$conditionalHandlers.$nearSphere=h.cast$near,g.prototype.$conditionalHandlers.$within=g.prototype.$conditionalHandlers.$geoWithin=h.cast$within,g.prototype.$conditionalHandlers.$geoIntersects=h.cast$geoIntersects,g.prototype.$conditionalHandlers.$minDistance=f,g.prototype.$conditionalHandlers.$maxDistance=f,g.prototype.$conditionalHandlers.$exists=l,g.prototype.cast=function(t,e,r,o,i){if(t&&t.$isSingleNested&&t.parent===e)return t;if(null!=t&&("object"!==n(t)||Array.isArray(t)))throw new a(this.path,t);var s,u=d(this.caster,t),c=y(e,"$__.selected",{}),l=this.path,f=Object.keys(c).reduce((function(t,e){return e.startsWith(l+".")&&(t[e.substr(l.length+1)]=c[e]),t}),{});return i=Object.assign({},i,{priorDoc:o}),r?((s=new u(void 0,f,e)).$init(t),s):0===Object.keys(t).length?new u({},f,e,void 0,i):new u(t,f,e,void 0,i)},g.prototype.castForQuery=function(t,e,r){var n;if(2===arguments.length){if(!(n=this.$conditionalHandlers[t]))throw new Error("Can't use "+t);return n.call(this,e)}if(null==(e=t))return e;this.options.runSetters&&(e=this._applySetters(e));var o=d(this.caster,e),s=null!=r&&null!=r.strict?r.strict:void 0;try{e=new o(e,s)}catch(t){if(!(t instanceof i))throw new i("Embedded",e,this.path,t,this);throw t}return e},g.prototype.doValidate=function(t,e,r,n){var o=d(this.caster,t);if(n&&n.skipSchemaValidators)return t instanceof o||(t=new o(t,null,r)),t.validate(e);c.prototype.doValidate.call(this,t,(function(r){return r?e(r):t?void t.validate(e):e(null)}),r,n)},g.prototype.doValidateSync=function(t,e,r){if(!r||!r.skipSchemaValidators){var n=c.prototype.doValidateSync.call(this,t,e);if(n)return n}if(t)return t.validateSync()},g.prototype.discriminator=function(t,e,r){r=r||{};var n=m.isPOJO(r)?r.value:r,o=y(r,"clone",!0);return e.instanceOfSchema&&o&&(e=e.clone()),e=p(this.caster,t,e,n),this.caster.discriminators[t]=b(e,this.caster),this.caster.discriminators[t]},g.defaultOptions={},g.set=c.set, +/*! + * ignore + */ +g.prototype.clone=function(){var t=Object.assign({},this.options),e=new this.constructor(this.schema,this.path,t);return e.validators=this.validators.slice(),void 0!==this.requiredValidator&&(e.requiredValidator=this.requiredValidator),e.caster.discriminators=Object.assign({},this.caster.discriminators),e}},function(t,e,r){"use strict";function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=u(t);if(e){var o=u(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return a(this,r)}}function a(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var c=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}(r,t);var e=s(r);function r(){return o(this,r),e.apply(this,arguments)}return r}(r(8)),l=r(9);Object.defineProperty(c.prototype,"_id",l),t.exports=c},function(t,e,r){"use strict";(function(e){ +/*! + * Module dependencies. + */ +function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var o=r(89),i=r(168),s=r(6),a=r(82),u=r(1),c=o.Binary,l=s.CastError;function f(t,e){s.call(this,t,e,"Buffer")} +/*! + * ignore + */ +function p(t){return this.castForQuery(t)}f.schemaName="Buffer",f.defaultOptions={}, +/*! + * Inherits from SchemaType. + */ +f.prototype=Object.create(s.prototype),f.prototype.constructor=f,f.prototype.OptionsConstructor=i, +/*! + * ignore + */ +f._checkRequired=function(t){return!(!t||!t.length)},f.set=s.set,f.checkRequired=s.checkRequired,f.prototype.checkRequired=function(t,e){return s._isRef(this,t,e,!0)?!!t:this.constructor._checkRequired(t)},f.prototype.cast=function(t,r,i){var a;if(s._isRef(this,t,r,i)){if(t&&t.isMongooseBuffer)return t;if(e.isBuffer(t))return t&&t.isMongooseBuffer||(t=new o(t,[this.path,r]),null!=this.options.subtype&&(t._subtype=this.options.subtype)),t;if(t instanceof c){if(a=new o(t.value(!0),[this.path,r]),"number"!=typeof t.sub_type)throw new l("Buffer",t,this.path,null,this);return a._subtype=t.sub_type,a}return this._castRef(t,r,i)}if(t&&t._id&&(t=t._id),t&&t.isMongooseBuffer)return t;if(e.isBuffer(t))return t&&t.isMongooseBuffer||(t=new o(t,[this.path,r]),null!=this.options.subtype&&(t._subtype=this.options.subtype)),t;if(t instanceof c){if(a=new o(t.value(!0),[this.path,r]),"number"!=typeof t.sub_type)throw new l("Buffer",t,this.path,null,this);return a._subtype=t.sub_type,a}if(null===t)return t;var u=n(t);if("string"===u||"number"===u||Array.isArray(t)||"object"===u&&"Buffer"===t.type&&Array.isArray(t.data))return"number"===u&&(t=[t]),a=new o(t,[this.path,r]),null!=this.options.subtype&&(a._subtype=this.options.subtype),a;throw new l("Buffer",t,this.path,null,this)},f.prototype.subtype=function(t){return this.options.subtype=t,this},f.prototype.$conditionalHandlers=u.options(s.prototype.$conditionalHandlers,{$bitsAllClear:a,$bitsAnyClear:a,$bitsAllSet:a,$bitsAnySet:a,$gt:p,$gte:p,$lt:p,$lte:p}),f.prototype.castForQuery=function(t,e){var r;if(2===arguments.length){if(!(r=this.$conditionalHandlers[t]))throw new Error("Can't use "+t+" with Buffer.");return r.call(this,e)}e=t;var n=this._castForQuery(e);return n?n.toObject({transform:!1,virtuals:!1}):n}, +/*! + * Module exports. + */ +t.exports=f}).call(this,r(2).Buffer)},function(t,e,r){"use strict";function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=u(t);if(e){var o=u(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return a(this,r)}}function a(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var c=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}(r,t);var e=s(r);function r(){return o(this,r),e.apply(this,arguments)}return r}(r(8)),l=r(9);Object.defineProperty(c.prototype,"subtype",l), +/*! + * ignore + */ +t.exports=c},function(t,e,r){"use strict"; +/*! + * Module requirements. + */var n=r(4),o=r(170),i=r(6),s=r(171),a=r(22),u=r(1),c=i.CastError;function l(t,e){i.call(this,t,e,"Date")} +/*! + * Date Query casting. + * + * @api private + */ +function f(t){return this.cast(t)}l.schemaName="Date",l.defaultOptions={}, +/*! + * Inherits from SchemaType. + */ +l.prototype=Object.create(i.prototype),l.prototype.constructor=l,l.prototype.OptionsConstructor=o, +/*! + * ignore + */ +l._cast=s,l.set=i.set,l.cast=function(t){return 0===arguments.length||(!1===t&&(t=this._defaultCaster),this._cast=t),this._cast}, +/*! + * ignore + */ +l._defaultCaster=function(t){if(null!=t&&!(t instanceof Date))throw new Error;return t},l.prototype.expires=function(t){return"Object"!==a(this._index)&&(this._index={}),this._index.expires=t,u.expires(this._index),this}, +/*! + * ignore + */ +l._checkRequired=function(t){return t instanceof Date},l.checkRequired=i.checkRequired,l.prototype.checkRequired=function(t,e){return i._isRef(this,t,e,!0)?!!t:("function"==typeof this.constructor.checkRequired?this.constructor.checkRequired():l.checkRequired())(t)},l.prototype.min=function(t,e){if(this.minValidator&&(this.validators=this.validators.filter((function(t){return t.validator!==this.minValidator}),this)),t){var r=e||n.messages.Date.min;"string"==typeof r&&(r=r.replace(/{MIN}/,t===Date.now?"Date.now()":t.toString()));var o=this;this.validators.push({validator:this.minValidator=function(e){var r=t;"function"==typeof t&&t!==Date.now&&(r=r.call(this));var n=r===Date.now?r():o.cast(r);return null===e||e.valueOf()>=n.valueOf()},message:r,type:"min",min:t})}return this},l.prototype.max=function(t,e){if(this.maxValidator&&(this.validators=this.validators.filter((function(t){return t.validator!==this.maxValidator}),this)),t){var r=e||n.messages.Date.max;"string"==typeof r&&(r=r.replace(/{MAX}/,t===Date.now?"Date.now()":t.toString()));var o=this;this.validators.push({validator:this.maxValidator=function(e){var r=t;"function"==typeof r&&r!==Date.now&&(r=r.call(this));var n=r===Date.now?r():o.cast(r);return null===e||e.valueOf()<=n.valueOf()},message:r,type:"max",max:t})}return this},l.prototype.cast=function(t){var e;e="function"==typeof this._castFunction?this._castFunction:"function"==typeof this.constructor.cast?this.constructor.cast():l.cast();try{return e(t)}catch(e){throw new c("date",t,this.path,e,this)}},l.prototype.$conditionalHandlers=u.options(i.prototype.$conditionalHandlers,{$gt:f,$gte:f,$lt:f,$lte:f}),l.prototype.castForQuery=function(t,e){if(2!==arguments.length)return this._castForQuery(t);var r=this.$conditionalHandlers[t];if(!r)throw new Error("Can't use "+t+" with Date.");return r.call(this,e)}, +/*! + * Module exports. + */ +t.exports=l},function(t,e,r){"use strict";function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=u(t);if(e){var o=u(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return a(this,r)}}function a(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var c=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}(r,t);var e=s(r);function r(){return o(this,r),e.apply(this,arguments)}return r}(r(8)),l=r(9);Object.defineProperty(c.prototype,"min",l),Object.defineProperty(c.prototype,"max",l),Object.defineProperty(c.prototype,"expires",l), +/*! + * ignore + */ +t.exports=c},function(t,e,r){"use strict";var n=r(21);t.exports=function(t){return null==t||""===t?null:t instanceof Date?(n.ok(!isNaN(t.valueOf())),t):(n.ok("boolean"!=typeof t),e=t instanceof Number||"number"==typeof t?new Date(t):"string"==typeof t&&!isNaN(Number(t))&&(Number(t)>=275761||Number(t)<-271820)?new Date(Number(t)):"function"==typeof t.valueOf?new Date(t.valueOf()):new Date(t),isNaN(e.valueOf())?void n.ok(!1):e);var e}},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */var n,o=r(173),i=r(6),s=r(90),a=r(22),u=r(12),c=r(1),l=i.CastError;function f(t,e){var r="string"==typeof t&&24===t.length&&/^[a-f0-9]+$/i.test(t),n=e&&e.suppressWarning;!r&&void 0!==t||n||c.warn("mongoose: To create a new ObjectId please try `Mongoose.Types.ObjectId` instead of using `Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if you're trying to create a hex char path in your schema."),i.call(this,t,e,"ObjectID")} +/*! + * ignore + */ +function p(t){return this.cast(t)} +/*! + * ignore + */ +function h(){return new u}function y(t){if(n||(n=r(7)),this instanceof n){if(void 0===t){var e=new u;return this.$__._id=e,e}this.$__._id=t}return t} +/*! + * Module exports. + */f.schemaName="ObjectId",f.defaultOptions={}, +/*! + * Inherits from SchemaType. + */ +f.prototype=Object.create(i.prototype),f.prototype.constructor=f,f.prototype.OptionsConstructor=o,f.get=i.get,f.set=i.set,f.prototype.auto=function(t){return t&&(this.default(h),this.set(y)),this}, +/*! + * ignore + */ +f._checkRequired=function(t){return t instanceof u}, +/*! + * ignore + */ +f._cast=s,f.cast=function(t){return 0===arguments.length||(!1===t&&(t=this._defaultCaster),this._cast=t),this._cast}, +/*! + * ignore + */ +f._defaultCaster=function(t){if(!(t instanceof u))throw new Error(t+" is not an instance of ObjectId");return t},f.checkRequired=i.checkRequired,f.prototype.checkRequired=function(t,e){return i._isRef(this,t,e,!0)?!!t:("function"==typeof this.constructor.checkRequired?this.constructor.checkRequired():f.checkRequired())(t)},f.prototype.cast=function(t,e,r){if(i._isRef(this,t,e,r))return t instanceof u?t:"objectid"===(a(t)||"").toLowerCase()?new u(t.toHexString()):this._castRef(t,e,r);var n;n="function"==typeof this._castFunction?this._castFunction:"function"==typeof this.constructor.cast?this.constructor.cast():f.cast();try{return n(t)}catch(e){throw new l("ObjectId",t,this.path,e,this)}},f.prototype.$conditionalHandlers=c.options(i.prototype.$conditionalHandlers,{$gt:p,$gte:p,$lt:p,$lte:p}),h.$runBeforeSetters=!0,t.exports=f},function(t,e,r){"use strict";function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var r,n=u(t);if(e){var o=u(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return a(this,r)}}function a(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var c=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}(r,t);var e=s(r);function r(){return o(this,r),e.apply(this,arguments)}return r}(r(8)),l=r(9);Object.defineProperty(c.prototype,"auto",l),Object.defineProperty(c.prototype,"populate",l), +/*! + * ignore + */ +t.exports=c},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */var n=r(6),o=n.CastError,i=r(19),s=r(175),a=r(1);function u(t,e){n.call(this,t,e,"Decimal128")} +/*! + * ignore + */ +function c(t){return this.cast(t)}u.schemaName="Decimal128",u.defaultOptions={}, +/*! + * Inherits from SchemaType. + */ +u.prototype=Object.create(n.prototype),u.prototype.constructor=u, +/*! + * ignore + */ +u._cast=s,u.set=n.set,u.cast=function(t){return 0===arguments.length||(!1===t&&(t=this._defaultCaster),this._cast=t),this._cast}, +/*! + * ignore + */ +u._defaultCaster=function(t){if(null!=t&&!(t instanceof i))throw new Error;return t}, +/*! + * ignore + */ +u._checkRequired=function(t){return t instanceof i},u.checkRequired=n.checkRequired,u.prototype.checkRequired=function(t,e){return n._isRef(this,t,e,!0)?!!t:("function"==typeof this.constructor.checkRequired?this.constructor.checkRequired():u.checkRequired())(t)},u.prototype.cast=function(t,e,r){if(n._isRef(this,t,e,r))return t instanceof i?t:this._castRef(t,e,r);var s;s="function"==typeof this._castFunction?this._castFunction:"function"==typeof this.constructor.cast?this.constructor.cast():u.cast();try{return s(t)}catch(e){throw new o("Decimal128",t,this.path,e,this)}},u.prototype.$conditionalHandlers=a.options(n.prototype.$conditionalHandlers,{$gt:c,$gte:c,$lt:c,$lte:c}), +/*! + * Module exports. + */ +t.exports=u},function(t,e,r){"use strict";(function(e){function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var o=r(19),i=r(21);t.exports=function(t){return null==t?t:"object"===n(t)&&"string"==typeof t.$numberDecimal?o.fromString(t.$numberDecimal):t instanceof o?t:"string"==typeof t?o.fromString(t):e.isBuffer(t)?new o(t):"number"==typeof t?o.fromString(String(t)):"function"==typeof t.valueOf&&"string"==typeof t.valueOf()?o.fromString(t.valueOf()):void i.ok(!1)}}).call(this,r(2).Buffer)},function(t,e,r){"use strict";(function(e){ +/*! + * ignore + */ +function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return i(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return i(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0,o=function(){};return{s:o,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0)&&!(e instanceof t)&&!(e instanceof i)&&!(e instanceof o)}e.flatten= +/*! + * ignore + */ +function e(r,n,o,i){var s;s=r&&a(r)&&!t.isBuffer(r)?Object.keys(r.toObject({transform:!1,virtuals:!1})):Object.keys(r||{});var c=s.length,l={};n=n?n+".":"";for(var f=0;f=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r1){o=new Set;var u,c=n(s);try{for(c.s();!(u=c.n()).done;){var l=u.value;a.has(l)&&o.add(l)}}catch(t){c.e(t)}finally{c.f()}var f,p=n(a);try{for(p.s();!(f=p.n()).done;){var h=f.value;o.has(h)||o.add(h)}}catch(t){p.e(t)}finally{p.f()}o=Array.from(o)}else o=Array.from(a);return o}},function(t,e,r){"use strict";var n=r(60); +/*! + * ignore + */t.exports=function(t){if(null==t)return null;var e=Object.keys(t),r=e.length,o=null;if(1===r&&"_id"===e[0])o=!t._id;else for(;r--;)if("_id"!==e[r]&&n(t[e[r]])){o=!t[e[r]];break}return o}},function(t,e,r){"use strict"; +/*! + * If populating a path within a document array, make sure each + * subdoc within the array knows its subpaths are populated. + * + * ####Example: + * const doc = await Article.findOne().populate('comments.author'); + * doc.comments[0].populated('author'); // Should be set + */function n(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return o(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0,i=function(){};return{s:i,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){u=!0,s=t},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r1&&!~i.indexOf(e)&&(t[e]=1));for(var c=e.split("."),l="",h=0;h0?".":"")+e[o],n.push(r);return n}},function(t,e,r){"use strict"; +/*! + * Module dependencies. + */var n=r(7),o=r(18).EventEmitter,i=r(4),s=r(53),a=r(12),u=i.ValidationError,c=r(79),l=r(20);function f(t,e,r,o,u){if(!(this instanceof f))return new f(t,e,r,o,u);if(l(e)&&!e.instanceOfSchema&&(e=new s(e)),e=this.schema||e,!this.schema&&e.options._id&&void 0===(t=t||{})._id&&(t._id=new a),!e)throw new i.MissingSchemaError;for(var p in this.$__setSchema(e),n.call(this,t,r,o,u),c(this,e,{decorateDoc:!0}),e.methods)this[p]=e.methods[p];for(var h in e.statics)this[h]=e.statics[h]} +/*! + * Inherit from the NodeJS document + */f.prototype=Object.create(n.prototype),f.prototype.constructor=f, +/*! + * ignore + */ +f.events=new o, +/*! + * Browser doc exposes the event emitter API + */ +f.$emitter=new o,["on","once","emit","listeners","removeListener","setMaxListeners","removeAllListeners","addListener"].forEach((function(t){f[t]=function(){return f.$emitter[t].apply(f.$emitter,arguments)}})), +/*! + * Module exports. + */ +f.ValidationError=u,t.exports=f}])})); \ No newline at end of file diff --git a/node_modules/mongoose/index.d.ts b/node_modules/mongoose/index.d.ts new file mode 100644 index 0000000..bbef149 --- /dev/null +++ b/node_modules/mongoose/index.d.ts @@ -0,0 +1,3098 @@ +declare module 'mongoose' { + import events = require('events'); + import mongodb = require('mongodb'); + import mongoose = require('mongoose'); + import stream = require('stream'); + + export enum ConnectionStates { + disconnected = 0, + connected = 1, + connecting = 2, + disconnecting = 3, + uninitialized = 99, + } + + class NativeDate extends global.Date {} + + /** The Mongoose Date [SchemaType](/docs/schematypes.html). */ + export type Date = Schema.Types.Date; + + /** + * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that should be + * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html). + * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128` + * instead. + */ + export type Decimal128 = Schema.Types.Decimal128; + + /** + * The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that Mongoose's change tracking, casting, + * and validation should ignore. + */ + export type Mixed = Schema.Types.Mixed; + + /** + * Mongoose constructor. The exports object of the `mongoose` module is an instance of this + * class. Most apps will only use this one instance. + */ + export const Mongoose: new (options?: MongooseOptions | null) => typeof mongoose; + + /** + * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that Mongoose should cast to numbers. + */ + export type Number = Schema.Types.Number; + + /** + * The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that should be + * [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/). + * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId` + * instead. + */ + export type ObjectId = Schema.Types.ObjectId; + + export let Promise: any; + export const PromiseProvider: any; + + /** The various Mongoose SchemaTypes. */ + export const SchemaTypes: typeof Schema.Types; + + /** Expose connection states for user-land */ + export const STATES: typeof ConnectionStates; + + /** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */ + export function connect(uri: string, options: ConnectOptions, callback: CallbackWithoutResult): void; + export function connect(uri: string, callback: CallbackWithoutResult): void; + export function connect(uri: string, options?: ConnectOptions): Promise; + + /** The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections). */ + export const connection: Connection; + + /** An array containing all connections associated with this Mongoose instance. */ + export const connections: Connection[]; + + /** + * Can be extended to explicitly type specific models. + */ + interface Models { + [modelName: string]: Model + } + + /** An array containing all models associated with this Mongoose instance. */ + export const models: Models; + /** Creates a Connection instance. */ + export function createConnection(uri: string, options?: ConnectOptions): Connection; + export function createConnection(): Connection; + export function createConnection(uri: string, options: ConnectOptions, callback: Callback): void; + + /** + * Removes the model named `name` from the default connection, if it exists. + * You can use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + */ + export function deleteModel(name: string | RegExp): typeof mongoose; + + export function disconnect(): Promise; + export function disconnect(cb: CallbackWithoutResult): void; + + /** Gets mongoose options */ + export function get(key: K): MongooseOptions[K]; + + /** + * Returns true if Mongoose can cast the given value to an ObjectId, or + * false otherwise. + */ + export function isValidObjectId(v: any): boolean; + + export function model(name: string, schema?: Schema | Schema, collection?: string, skipInit?: boolean): Model; + export function model( + name: string, + schema?: Schema, + collection?: string, + skipInit?: boolean + ): U; + + /** Returns an array of model names created on this instance of Mongoose. */ + export function modelNames(): Array; + + /** The node-mongodb-native driver Mongoose uses. */ + export const mongo: typeof mongodb; + + /** + * Mongoose uses this function to get the current time when setting + * [timestamps](/docs/guide.html#timestamps). You may stub out this function + * using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing. + */ + export function now(): NativeDate; + + /** Declares a global plugin executed on all Schemas. */ + export function plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): typeof mongoose; + + /** Getter/setter around function for pluralizing collection names. */ + export function pluralize(fn?: ((str: string) => string) | null): ((str: string) => string) | null; + + /** Sets mongoose options */ + export function set(key: K, value: MongooseOptions[K]): typeof mongoose; + + /** + * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) + * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), + * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). + */ + export function startSession(options?: mongodb.ClientSessionOptions): Promise; + export function startSession(options: mongodb.ClientSessionOptions, cb: Callback): void; + + /** The Mongoose version */ + export const version: string; + + export type CastError = Error.CastError; + + type Mongoose = typeof mongoose; + + interface MongooseOptions { + /** true by default. Set to false to skip applying global plugins to child schemas */ + applyPluginsToChildSchemas?: boolean; + + /** + * false by default. Set to true to apply global plugins to discriminator schemas. + * This typically isn't necessary because plugins are applied to the base schema and + * discriminators copy all middleware, methods, statics, and properties from the base schema. + */ + applyPluginsToDiscriminators?: boolean; + + /** + * Set to `true` to make Mongoose call` Model.createCollection()` automatically when you + * create a model with `mongoose.model()` or `conn.model()`. This is useful for testing + * transactions, change streams, and other features that require the collection to exist. + */ + autoCreate?: boolean; + + /** + * true by default. Set to false to disable automatic index creation + * for all models associated with this Mongoose instance. + */ + autoIndex?: boolean; + + /** enable/disable mongoose's buffering mechanism for all connections and models */ + bufferCommands?: boolean; + + bufferTimeoutMS?: number; + + /** false by default. Set to `true` to `clone()` all schemas before compiling into a model. */ + cloneSchemas?: boolean; + + /** + * If `true`, prints the operations mongoose sends to MongoDB to the console. + * If a writable stream is passed, it will log to that stream, without colorization. + * If a callback function is passed, it will receive the collection name, the method + * name, then all arguments passed to the method. For example, if you wanted to + * replicate the default logging, you could output from the callback + * `Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})`. + */ + debug?: + | boolean + | { color?: boolean; shell?: boolean } + | stream.Writable + | ((collectionName: string, methodName: string, ...methodArgs: any[]) => void); + + /** If set, attaches [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) to every query */ + maxTimeMS?: number; + + /** + * true by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that + * returns `this` for convenience with populate. Set this to false to remove the getter. + */ + objectIdGetter?: boolean; + + /** + * Set to `true` to default to overwriting models with the same name when calling + * `mongoose.model()`, as opposed to throwing an `OverwriteModelError`. + */ + overwriteModels?: boolean; + + /** + * If `false`, changes the default `returnOriginal` option to `findOneAndUpdate()`, + * `findByIdAndUpdate`, and `findOneAndReplace()` to false. This is equivalent to + * setting the `new` option to `true` for `findOneAndX()` calls by default. Read our + * `findOneAndUpdate()` [tutorial](https://mongoosejs.com/docs/tutorials/findoneandupdate.html) + * for more information. + */ + returnOriginal?: boolean; + + /** + * false by default. Set to true to enable [update validators]( + * https://mongoosejs.com/docs/validation.html#update-validators + * ) for all validators by default. + */ + runValidators?: boolean; + + sanitizeFilter?: boolean; + + sanitizeProjection?: boolean; + + /** + * true by default. Set to false to opt out of Mongoose adding all fields that you `populate()` + * to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one. + */ + selectPopulatedPaths?: boolean; + + setDefaultsOnInsert?: boolean; + + /** true by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas. */ + strict?: boolean | 'throw'; + + /** + * `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to + * `toJSON()`, for determining how Mongoose documents get serialized by `JSON.stringify()` + */ + toJSON?: ToObjectOptions; + + /** `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to `toObject()` */ + toObject?: ToObjectOptions; + } + + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface ClientSession extends mongodb.ClientSession { } + + interface ConnectOptions extends mongodb.MongoClientOptions { + /** Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. */ + bufferCommands?: boolean; + /** The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. */ + dbName?: string; + /** username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. */ + user?: string; + /** password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. */ + pass?: string; + /** Set to false to disable automatic index creation for all models associated with this connection. */ + autoIndex?: boolean; + /** Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. */ + autoCreate?: boolean; + } + + class Connection extends events.EventEmitter { + /** Returns a promise that resolves when this connection successfully connects to MongoDB */ + asPromise(): Promise; + + /** Closes the connection */ + close(callback: CallbackWithoutResult): void; + close(force: boolean, callback: CallbackWithoutResult): void; + close(force?: boolean): Promise; + + /** Retrieves a collection, creating it if not cached. */ + collection(name: string, options?: mongodb.CreateCollectionOptions): Collection; + + /** A hash of the collections associated with this connection */ + collections: { [index: string]: Collection }; + + /** A hash of the global options that are associated with this connection */ + config: any; + + /** The mongodb.Db instance, set when the connection is opened */ + db: mongodb.Db; + + /** + * Helper for `createCollection()`. Will explicitly create the given collection + * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/) + * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose. + */ + createCollection(name: string, options?: mongodb.CreateCollectionOptions): Promise; + createCollection(name: string, cb: Callback): void; + createCollection(name: string, options: mongodb.CreateCollectionOptions, cb?: Callback): Promise; + + /** + * Removes the model named `name` from this connection, if it exists. You can + * use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + */ + deleteModel(name: string): this; + + /** + * Helper for `dropCollection()`. Will delete the given collection, including + * all documents and indexes. + */ + dropCollection(collection: string): Promise; + dropCollection(collection: string, cb: CallbackWithoutResult): void; + + /** + * Helper for `dropDatabase()`. Deletes the given database, including all + * collections, documents, and indexes. + */ + dropDatabase(): Promise; + dropDatabase(cb: CallbackWithoutResult): void; + + /** Gets the value of the option `key`. Equivalent to `conn.options[key]` */ + get(key: string): any; + + /** + * Returns the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance + * that this connection uses to talk to MongoDB. + */ + getClient(): mongodb.MongoClient; + + /** + * The host name portion of the URI. If multiple hosts, such as a replica set, + * this will contain the first host name in the URI + */ + host: string; + + /** + * A number identifier for this connection. Used for debugging when + * you have [multiple connections](/docs/connections.html#multiple_connections). + */ + id: number; + + /** + * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing + * a map from model names to models. Contains all models that have been + * added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model). + */ + models: { [index: string]: Model }; + + /** Defines or retrieves a model. */ + model(name: string, schema?: Schema, collection?: string): Model; + model( + name: string, + schema?: Schema, + collection?: string, + skipInit?: boolean + ): U; + + /** Returns an array of model names created on this connection. */ + modelNames(): Array; + + /** The name of the database this connection points to. */ + name: string; + + /** Opens the connection with a URI using `MongoClient.connect()`. */ + openUri(uri: string, options?: ConnectOptions): Promise; + openUri(uri: string, callback: (err: CallbackError, conn?: Connection) => void): Connection; + openUri(uri: string, options: ConnectOptions, callback: (err: CallbackError, conn?: Connection) => void): Connection; + + /** The password specified in the URI */ + pass: string; + + /** + * The port portion of the URI. If multiple hosts, such as a replica set, + * this will contain the port from the first host name in the URI. + */ + port: number; + + /** Declares a plugin executed on all schemas you pass to `conn.model()` */ + plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): Connection; + + /** The plugins that will be applied to all models created on this connection. */ + plugins: Array; + + /** + * Connection ready state + * + * - 0 = disconnected + * - 1 = connected + * - 2 = connecting + * - 3 = disconnecting + */ + readyState: number; + + /** Sets the value of the option `key`. Equivalent to `conn.options[key] = val` */ + set(key: string, value: any): any; + + /** + * Set the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance + * that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to + * reuse it. + */ + setClient(client: mongodb.MongoClient): this; + + /** + * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) + * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), + * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). + */ + startSession(options?: mongodb.ClientSessionOptions): Promise; + startSession(options: mongodb.ClientSessionOptions, cb: Callback): void; + + /** + * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function + * in a transaction. Mongoose will commit the transaction if the + * async function executes successfully and attempt to retry if + * there was a retriable error. + */ + transaction(fn: (session: mongodb.ClientSession) => Promise): Promise; + + /** Switches to a different database using the same connection pool. */ + useDb(name: string, options?: { useCache?: boolean, noListener?: boolean }): Connection; + + /** The username specified in the URI */ + user: string; + + /** Watches the entire underlying database for changes. Similar to [`Model.watch()`](/docs/api/model.html#model_Model.watch). */ + watch(pipeline?: Array, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream; + } + + /* + * section collection.js + * http://mongoosejs.com/docs/api.html#collection-js + */ + interface CollectionBase extends mongodb.Collection { + /* + * Abstract methods. Some of these are already defined on the + * mongodb.Collection interface so they've been commented out. + */ + ensureIndex(...args: any[]): any; + findAndModify(...args: any[]): any; + getIndexes(...args: any[]): any; + + /** The collection name */ + collectionName: string; + /** The Connection instance */ + conn: Connection; + /** The collection name */ + name: string; + } + + /* + * section drivers/node-mongodb-native/collection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js + */ + let Collection: Collection; + interface Collection extends CollectionBase { + /** + * Collection constructor + * @param name name of the collection + * @param conn A MongooseConnection instance + * @param opts optional collection options + */ + // eslint-disable-next-line @typescript-eslint/no-misused-new + new(name: string, conn: Connection, opts?: any): Collection; + /** Formatter for debug print args */ + $format(arg: any): string; + /** Debug print helper */ + $print(name: any, i: any, args: any[]): void; + /** Retrieves information about this collections indexes. */ + getIndexes(): any; + } + + class Document { + constructor(doc?: any); + + /** This documents _id. */ + _id?: T; + + /** This documents __v. */ + __v?: any; + + /* Get all subdocs (by bfs) */ + $getAllSubdocs(): Document[]; + + /** Don't run validation on this path or persist changes to this path. */ + $ignore(path: string): void; + + /** Checks if a path is set to its default. */ + $isDefault(path: string): boolean; + + /** Getter/setter, determines whether the document was removed or not. */ + $isDeleted(val?: boolean): boolean; + + /** Returns an array of all populated documents associated with the query */ + $getPopulatedDocs(): Document[]; + + /** + * Returns true if the given path is nullish or only contains empty objects. + * Useful for determining whether this subdoc will get stripped out by the + * [minimize option](/docs/guide.html#minimize). + */ + $isEmpty(path: string): boolean; + + /** Checks if a path is invalid */ + $isValid(path: string): boolean; + + /** + * Empty object that you can use for storing properties on the document. This + * is handy for passing data to middleware without conflicting with Mongoose + * internals. + */ + $locals: Record; + + /** Marks a path as valid, removing existing validation errors. */ + $markValid(path: string): void; + + /** + * A string containing the current operation that Mongoose is executing + * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`. + */ + $op: string | null; + + /** + * Getter/setter around the session associated with this document. Used to + * automatically set `session` if you `save()` a doc that you got from a + * query with an associated session. + */ + $session(session?: mongodb.ClientSession | null): mongodb.ClientSession; + + /** Alias for `set()`, used internally to avoid conflicts */ + $set(path: string, val: any, options?: any): this; + $set(path: string, val: any, type: any, options?: any): this; + $set(value: any): this; + + /** Set this property to add additional query filters when Mongoose saves this document and `isNew` is false. */ + $where: Record; + + /** If this is a discriminator model, `baseModelName` is the name of the base model. */ + baseModelName?: string; + + /** Collection the model uses. */ + collection: Collection; + + /** Connection the model uses. */ + db: Connection; + + /** Removes this document from the db. */ + delete(options?: QueryOptions): QueryWithHelpers; + delete(options: QueryOptions, cb?: Callback): void; + delete(cb: Callback): void; + + /** Removes this document from the db. */ + deleteOne(options?: QueryOptions): QueryWithHelpers; + deleteOne(options: QueryOptions, cb?: Callback): void; + deleteOne(cb: Callback): void; + + /** + * Takes a populated field and returns it to its unpopulated state. If called with + * no arguments, then all populated fields are returned to their unpopulated state. + */ + depopulate(path?: string | string[]): this; + + /** + * Returns the list of paths that have been directly modified. A direct + * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`, + * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`. + */ + directModifiedPaths(): Array; + + /** + * Returns true if this document is equal to another document. + * + * Documents are considered equal when they have matching `_id`s, unless neither + * document has an `_id`, in which case this function falls back to using + * `deepEqual()`. + */ + equals(doc: Document): boolean; + + /** Hash containing current validation errors. */ + errors?: Error.ValidationError; + + /** Returns the value of a path. */ + get(path: string, type?: any, options?: any): any; + + /** + * Returns the changes that happened to the document + * in the format that will be sent to MongoDB. + */ + getChanges(): UpdateQuery; + + /** The string version of this documents _id. */ + id?: any; + + /** Signal that we desire an increment of this documents version. */ + increment(): this; + + /** + * Initializes the document without setters or marking anything modified. + * Called internally after a document is returned from mongodb. Normally, + * you do **not** need to call this function on your own. + */ + init(obj: any, opts?: any, cb?: Callback): this; + + /** Marks a path as invalid, causing validation to fail. */ + invalidate(path: string, errorMsg: string | NativeError, value?: any, kind?: string): NativeError | null; + + /** Returns true if `path` was directly set and modified, else false. */ + isDirectModified(path: string): boolean; + + /** Checks if `path` was explicitly selected. If no projection, always returns true. */ + isDirectSelected(path: string): boolean; + + /** Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since. */ + isInit(path: string): boolean; + + /** + * Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path + * in this document is modified. + */ + isModified(path?: string | Array): boolean; + + /** Boolean flag specifying if the document is new. */ + isNew: boolean; + + /** Checks if `path` was selected in the source query which initialized this document. */ + isSelected(path: string): boolean; + + /** Marks the path as having pending changes to write to the db. */ + markModified(path: string, scope?: any): void; + + /** Returns the list of paths that have been modified. */ + modifiedPaths(options?: { includeChildren?: boolean }): Array; + + /** The name of the model */ + modelName: string; + + /** + * Overwrite all values in this document with the values of `obj`, except + * for immutable properties. Behaves similarly to `set()`, except for it + * unsets all properties that aren't in `obj`. + */ + overwrite(obj: AnyObject): this; + + /** + * If this document is a subdocument or populated document, returns the + * document's parent. Returns undefined otherwise. + */ + $parent(): Document | undefined; + + /** Populates document references. */ + populate(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise; + populate(path: string | PopulateOptions | (string | PopulateOptions)[], callback: Callback): void; + populate(path: string, names: string): Promise; + populate(path: string, names: string, callback: Callback): void; + + /** Gets _id(s) used during population of the given `path`. If the path was not populated, returns `undefined`. */ + populated(path: string): any; + + /** Removes this document from the db. */ + remove(options?: QueryOptions): Promise; + remove(options?: QueryOptions, cb?: Callback): void; + + /** Sends a replaceOne command with this document `_id` as the query selector. */ + replaceOne(replacement?: AnyObject, options?: QueryOptions | null, callback?: Callback): Query; + replaceOne(replacement?: AnyObject, options?: QueryOptions | null, callback?: Callback): Query; + + /** Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation with just the modified paths if `isNew` is `false`. */ + save(options?: SaveOptions): Promise; + save(options?: SaveOptions, fn?: Callback): void; + save(fn?: Callback): void; + + /** The document's schema. */ + schema: Schema; + + /** Sets the value of a path, or many paths. */ + set(path: string, val: any, options?: any): this; + set(path: string, val: any, type: any, options?: any): this; + set(value: any): this; + + /** The return value of this method is used in calls to JSON.stringify(doc). */ + toJSON(options?: ToObjectOptions): LeanDocument; + toJSON(options?: ToObjectOptions): T; + + /** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */ + toObject(options?: ToObjectOptions): LeanDocument; + toObject(options?: ToObjectOptions): T; + + /** Clears the modified state on the specified path. */ + unmarkModified(path: string): void; + + /** Sends an update command with this document `_id` as the query selector. */ + update(update?: UpdateQuery | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): Query; + + /** Sends an updateOne command with this document `_id` as the query selector. */ + updateOne(update?: UpdateQuery | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): Query; + + /** Executes registered validation rules for this document. */ + validate(options:{ pathsToSkip?: pathsToSkip }): Promise; + validate(pathsToValidate?: pathsToValidate, options?: any): Promise; + validate(callback: CallbackWithoutResult): void; + validate(pathsToValidate: pathsToValidate, callback: CallbackWithoutResult): void; + validate(pathsToValidate: pathsToValidate, options: any, callback: CallbackWithoutResult): void; + + /** Executes registered validation rules (skipping asynchronous validators) for this document. */ + validateSync(options:{pathsToSkip?: pathsToSkip, [k:string]: any }): Error.ValidationError | null; + validateSync(pathsToValidate?: Array, options?: any): Error.ValidationError | null; + } + + /** A list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list. */ + type pathsToValidate = string[] | string; + /** A list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. */ + type pathsToSkip = string[] | string; + + interface AcceptsDiscriminator { + /** Adds a discriminator type. */ + discriminator(name: string | number, schema: Schema, value?: string | number | ObjectId): Model; + discriminator(name: string | number, schema: Schema, value?: string | number | ObjectId): U; + } + + type AnyKeys = { [P in keyof T]?: T[P] | any }; + interface AnyObject { [k: string]: any } + + type Require_id = T extends { _id?: any } ? (T & { _id: T['_id'] }) : (T & { _id: Types.ObjectId }); + type EnforceDocument = T extends Document ? Require_id : (Document & Require_id & TVirtuals & TMethods); + + interface IndexesDiff { + /** Indexes that would be created in mongodb. */ + toCreate: Array + /** Indexes that would be dropped in mongodb. */ + toDrop: Array + } + + export const Model: Model; + interface Model extends NodeJS.EventEmitter, AcceptsDiscriminator { + new(doc?: AnyKeys & AnyObject, fields?: any | null, options?: boolean | AnyObject): EnforceDocument; + + aggregate(pipeline?: any[], options?: Record): Aggregate>; + aggregate(pipeline: any[], cb: Function): Promise>; + aggregate(pipeline: any[], options: Record, cb: Function): Promise>; + + /** Base Mongoose instance the model uses. */ + base: typeof mongoose; + + /** + * If this is a discriminator model, `baseModelName` is the name of + * the base model. + */ + baseModelName: string | undefined; + + /** + * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`, + * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one + * command. This is faster than sending multiple independent operations (e.g. + * if you use `create()`) because with `bulkWrite()` there is only one network + * round trip to the MongoDB server. + */ + bulkWrite(writes: Array, options?: mongodb.BulkWriteOptions): Promise; + bulkWrite(writes: Array, options?: mongodb.BulkWriteOptions, cb?: Callback): void; + + /** + * Sends multiple `save()` calls in a single `bulkWrite()`. This is faster than + * sending multiple `save()` calls because with `bulkSave()` there is only one + * network round trip to the MongoDB server. + */ + bulkSave(documents: Array): Promise; + + /** Collection the model uses. */ + collection: Collection; + + /** Creates a `count` query: counts the number of documents that match `filter`. */ + count(callback?: Callback): QueryWithHelpers, TQueryHelpers, T>; + count(filter: FilterQuery, callback?: Callback): QueryWithHelpers, TQueryHelpers, T>; + + /** Creates a `countDocuments` query: counts the number of documents that match `filter`. */ + countDocuments(callback?: Callback): QueryWithHelpers, TQueryHelpers, T>; + countDocuments(filter: FilterQuery, callback?: Callback): QueryWithHelpers, TQueryHelpers, T>; + + /** Creates a new document or documents */ + create(docs: (AnyKeys | AnyObject)[], options?: SaveOptions): Promise[]>; + create(docs: (AnyKeys | AnyObject)[], callback: Callback[]>): void; + create(doc: AnyKeys | AnyObject): Promise>; + create(doc: AnyKeys | AnyObject, callback: Callback>): void; + create>(docs: DocContents[], options?: SaveOptions): Promise[]>; + create>(docs: DocContents[], callback: Callback[]>): void; + create>(doc: DocContents): Promise>; + create>(...docs: DocContents[]): Promise[]>; + create>(doc: DocContents, callback: Callback>): void; + + /** + * Create the collection for this model. By default, if no indexes are specified, + * mongoose will not create the collection for the model until any documents are + * created. Use this method to create the collection explicitly. + */ + createCollection(options?: mongodb.CreateCollectionOptions): Promise; + createCollection(options: mongodb.CreateCollectionOptions | null, callback: Callback): void; + + /** + * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex) + * function. + */ + createIndexes(callback?: CallbackWithoutResult): Promise; + createIndexes(options?: any, callback?: CallbackWithoutResult): Promise; + + /** Connection the model uses. */ + db: Connection; + + /** + * Deletes all of the documents that match `conditions` from the collection. + * Behaves like `remove()`, but deletes all documents that match `conditions` + * regardless of the `single` option. + */ + deleteMany(filter?: FilterQuery, options?: QueryOptions, callback?: CallbackWithoutResult): QueryWithHelpers, TQueryHelpers, T>; + deleteMany(filter: FilterQuery, callback: CallbackWithoutResult): QueryWithHelpers, TQueryHelpers, T>; + deleteMany(callback: CallbackWithoutResult): QueryWithHelpers, TQueryHelpers, T>; + + /** + * Deletes the first document that matches `conditions` from the collection. + * Behaves like `remove()`, but deletes at most one document regardless of the + * `single` option. + */ + deleteOne(filter?: FilterQuery, options?: QueryOptions, callback?: CallbackWithoutResult): QueryWithHelpers, TQueryHelpers, T>; + deleteOne(filter: FilterQuery, callback: CallbackWithoutResult): QueryWithHelpers, TQueryHelpers, T>; + deleteOne(callback: CallbackWithoutResult): QueryWithHelpers, TQueryHelpers, T>; + + /** + * Sends `createIndex` commands to mongo for each index declared in the schema. + * The `createIndex` commands are sent in series. + */ + ensureIndexes(callback?: CallbackWithoutResult): Promise; + ensureIndexes(options?: any, callback?: CallbackWithoutResult): Promise; + + /** + * Event emitter that reports any errors that occurred. Useful for global error + * handling. + */ + events: NodeJS.EventEmitter; + + /** + * Finds a single document by its _id field. `findById(id)` is almost* + * equivalent to `findOne({ _id: id })`. If you want to query by a document's + * `_id`, use `findById()` instead of `findOne()`. + */ + findById(id: any, projection?: any | null, options?: QueryOptions | null, callback?: Callback | null>): QueryWithHelpers | null, EnforceDocument, TQueryHelpers, T>; + + /** Finds one document. */ + findOne(filter?: FilterQuery, projection?: any | null, options?: QueryOptions | null, callback?: Callback | null>): QueryWithHelpers | null, EnforceDocument, TQueryHelpers, T>; + + /** + * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. + * The document returned has no paths marked as modified initially. + */ + hydrate(obj: any): EnforceDocument; + + /** + * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/), + * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off. + * Mongoose calls this function automatically when a model is created using + * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or + * [`connection.model()`](/docs/api.html#connection_Connection-model), so you + * don't need to call it. + */ + init(callback?: CallbackWithoutResult): Promise>; + + /** Inserts one or more new documents as a single `insertMany` call to the MongoDB server. */ + insertMany(docs: Array | AnyObject>, options: InsertManyOptions & { rawResult: true }): Promise; + insertMany(docs: Array | AnyObject>, options?: InsertManyOptions): Promise>>; + insertMany(doc: AnyKeys | AnyObject, options: InsertManyOptions & { rawResult: true }): Promise; + insertMany(doc: AnyKeys | AnyObject, options?: InsertManyOptions): Promise[]>; + insertMany(doc: AnyKeys | AnyObject, options?: InsertManyOptions, callback?: Callback[] | InsertManyResult>): void; + insertMany(docs: Array | AnyObject>, options?: InsertManyOptions, callback?: Callback> | InsertManyResult>): void; + + /** + * Lists the indexes currently defined in MongoDB. This may or may not be + * the same as the indexes defined in your schema depending on whether you + * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you + * build indexes manually. + */ + listIndexes(callback: Callback>): void; + listIndexes(): Promise>; + + /** The name of the model */ + modelName: string; + + /** Populates document references. */ + populate(docs: Array, options: PopulateOptions | Array | string, + callback?: Callback<(EnforceDocument)[]>): Promise>>; + populate(doc: any, options: PopulateOptions | Array | string, + callback?: Callback>): Promise>; + + /** + * Makes the indexes in MongoDB match the indexes defined in this model's + * schema. This function will drop any indexes that are not defined in + * the model's schema except the `_id` index, and build any indexes that + * are in your schema but not in MongoDB. + */ + syncIndexes(options?: Record): Promise>; + syncIndexes(options: Record | null, callback: Callback>): void; + + /** + * Does a dry-run of Model.syncIndexes(), meaning that + * the result of this function would be the result of + * Model.syncIndexes(). + */ + diffIndexes(options?: Record): Promise + diffIndexes(options: Record | null, callback: (err: CallbackError, diff: IndexesDiff) => void): void + + /** + * Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) + * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), + * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). + * */ + startSession(options?: mongodb.ClientSessionOptions, cb?: Callback): Promise; + + /** Casts and validates the given object against this model's schema, passing the given `context` to custom validators. */ + validate(callback?: CallbackWithoutResult): Promise; + validate(optional: any, callback?: CallbackWithoutResult): Promise; + validate(optional: any, pathsToValidate: string[], callback?: CallbackWithoutResult): Promise; + + /** Watches the underlying collection for changes using [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). */ + watch(pipeline?: Array>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream; + + /** Adds a `$where` clause to this query */ + $where(argument: string | Function): QueryWithHelpers>, EnforceDocument, TQueryHelpers, T>; + + /** Registered discriminators for this model. */ + discriminators: { [name: string]: Model } | undefined; + + /** Translate any aliases fields/conditions so the final query or document object is pure */ + translateAliases(raw: any): any; + + /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */ + distinct(field: string, filter?: FilterQuery, callback?: Callback): QueryWithHelpers, EnforceDocument, TQueryHelpers, T>; + + /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */ + estimatedDocumentCount(options?: QueryOptions, callback?: Callback): QueryWithHelpers, TQueryHelpers, T>; + + /** + * Returns true if at least one document exists in the database that matches + * the given `filter`, and false otherwise. + */ + exists(filter: FilterQuery): Promise; + exists(filter: FilterQuery, callback: Callback): void; + + /** Creates a `find` query: gets a list of documents that match `filter`. */ + find(callback?: Callback[]>): QueryWithHelpers>, EnforceDocument, TQueryHelpers, T>; + find(filter: FilterQuery, callback?: Callback): QueryWithHelpers>, EnforceDocument, TQueryHelpers, T>; + find(filter: FilterQuery, projection?: any | null, options?: QueryOptions | null, callback?: Callback[]>): QueryWithHelpers>, EnforceDocument, TQueryHelpers, T>; + + /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */ + findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: CallbackError, doc: EnforceDocument | null, res: any) => void): QueryWithHelpers | null, EnforceDocument, TQueryHelpers, T>; + + /** Creates a `findByIdAndRemove` query, filtering by the given `_id`. */ + findByIdAndRemove(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: CallbackError, doc: EnforceDocument | null, res: any) => void): QueryWithHelpers | null, EnforceDocument, TQueryHelpers, T>; + + /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */ + findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: any, res: any) => void): QueryWithHelpers>, EnforceDocument, TQueryHelpers, T>; + findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: EnforceDocument, res: any) => void): QueryWithHelpers, EnforceDocument, TQueryHelpers, T>; + findByIdAndUpdate(id?: mongodb.ObjectId | any, update?: UpdateQuery, options?: QueryOptions | null, callback?: (err: CallbackError, doc: EnforceDocument | null, res: any) => void): QueryWithHelpers | null, EnforceDocument, TQueryHelpers, T>; + findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery, callback: (err: CallbackError, doc: EnforceDocument | null, res: any) => void): QueryWithHelpers | null, EnforceDocument, TQueryHelpers, T>; + + /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */ + findOneAndDelete(filter?: FilterQuery, options?: QueryOptions | null, callback?: (err: CallbackError, doc: EnforceDocument | null, res: any) => void): QueryWithHelpers | null, EnforceDocument, TQueryHelpers, T>; + + /** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */ + findOneAndRemove(filter?: FilterQuery, options?: QueryOptions | null, callback?: (err: CallbackError, doc: EnforceDocument | null, res: any) => void): QueryWithHelpers | null, EnforceDocument, TQueryHelpers, T>; + + /** Creates a `findOneAndReplace` query: atomically finds the given document and replaces it with `replacement`. */ + findOneAndReplace(filter: FilterQuery, replacement: T | AnyObject, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: EnforceDocument, res: any) => void): QueryWithHelpers, EnforceDocument, TQueryHelpers, T>; + findOneAndReplace(filter?: FilterQuery, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: (err: CallbackError, doc: EnforceDocument | null, res: any) => void): QueryWithHelpers | null, EnforceDocument, TQueryHelpers, T>; + + /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */ + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: any, res: any) => void): QueryWithHelpers>, EnforceDocument, TQueryHelpers, T>; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: EnforceDocument, res: any) => void): QueryWithHelpers, EnforceDocument, TQueryHelpers, T>; + findOneAndUpdate(filter?: FilterQuery, update?: UpdateQuery, options?: QueryOptions | null, callback?: (err: CallbackError, doc: T | null, res: any) => void): QueryWithHelpers | null, EnforceDocument, TQueryHelpers, T>; + + geoSearch(filter?: FilterQuery, options?: GeoSearchOptions, callback?: Callback>>): QueryWithHelpers>, EnforceDocument, TQueryHelpers, T>; + + /** Executes a mapReduce command. */ + mapReduce( + o: MapReduceOptions, + callback?: Callback + ): Promise; + + remove(filter?: any, callback?: CallbackWithoutResult): QueryWithHelpers, TQueryHelpers, T>; + + /** Creates a `replaceOne` query: finds the first document that matches `filter` and replaces it with `replacement`. */ + replaceOne(filter?: FilterQuery, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers, TQueryHelpers, T>; + replaceOne(filter?: FilterQuery, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers, TQueryHelpers, T>; + + /** Schema the model uses. */ + schema: Schema; + + /** + * @deprecated use `updateOne` or `updateMany` instead. + * Creates a `update` query: updates one or many documents that match `filter` with `update`, based on the `multi` option. + */ + update(filter?: FilterQuery, update?: UpdateQuery | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers, TQueryHelpers, T>; + + /** Creates a `updateMany` query: updates all documents that match `filter` with `update`. */ + updateMany(filter?: FilterQuery, update?: UpdateQuery | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers, TQueryHelpers, T>; + + /** Creates a `updateOne` query: updates the first document that matches `filter` with `update`. */ + updateOne(filter?: FilterQuery, update?: UpdateQuery | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers, TQueryHelpers, T>; + + /** Creates a Query, applies the passed conditions, and returns the Query. */ + where(path: string, val?: any): QueryWithHelpers>, EnforceDocument, TQueryHelpers, T>; + where(obj: object): QueryWithHelpers>, EnforceDocument, TQueryHelpers, T>; + where(): QueryWithHelpers>, EnforceDocument, TQueryHelpers, T>; + } + + type UpdateWriteOpResult = mongodb.UpdateResult; + + interface QueryOptions { + arrayFilters?: { [key: string]: any }[]; + batchSize?: number; + collation?: mongodb.CollationOptions; + comment?: any; + context?: string; + explain?: any; + fields?: any | string; + hint?: any; + /** + * If truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. + */ + lean?: boolean | any; + limit?: number; + maxTimeMS?: number; + maxscan?: number; + multi?: boolean; + multipleCastError?: boolean; + /** + * By default, `findOneAndUpdate()` returns the document as it was **before** + * `update` was applied. If you set `new: true`, `findOneAndUpdate()` will + * instead give you the object after `update` was applied. + */ + new?: boolean; + overwrite?: boolean; + overwriteDiscriminatorKey?: boolean; + populate?: string | string[] | PopulateOptions | PopulateOptions[]; + projection?: any; + /** + * if true, returns the raw result from the MongoDB driver + */ + rawResult?: boolean; + readPreference?: string | mongodb.ReadPreferenceMode; + /** + * An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. + */ + returnOriginal?: boolean; + /** + * Another alias for the `new` option. `returnOriginal` is deprecated so this should be used. + */ + returnDocument?: string; + runValidators?: boolean; + /* Set to `true` to automatically sanitize potentially unsafe user-generated query projections */ + sanitizeProjection?: boolean; + /** + * Set to `true` to automatically sanitize potentially unsafe query filters by stripping out query selectors that + * aren't explicitly allowed using `mongoose.trusted()`. + */ + sanitizeFilter?: boolean; + /** The session associated with this query. */ + session?: mongodb.ClientSession; + setDefaultsOnInsert?: boolean; + skip?: number; + snapshot?: any; + sort?: any; + /** overwrites the schema's strict mode option */ + strict?: boolean | string; + /** + * equal to `strict` by default, may be `false`, `true`, or `'throw'`. Sets the default + * [strictQuery](https://mongoosejs.com/docs/guide.html#strictQuery) mode for schemas. + */ + strictQuery?: boolean | 'throw'; + tailable?: number; + /** + * If set to `false` and schema-level timestamps are enabled, + * skip timestamps for this update. Note that this allows you to overwrite + * timestamps. Does nothing if schema-level timestamps are not set. + */ + timestamps?: boolean; + upsert?: boolean; + writeConcern?: any; + + [other: string]: any; + } + + type MongooseQueryOptions = Pick; + + interface SaveOptions { + checkKeys?: boolean; + j?: boolean; + safe?: boolean | WriteConcern; + session?: ClientSession | null; + timestamps?: boolean; + validateBeforeSave?: boolean; + validateModifiedOnly?: boolean; + w?: number | string; + wtimeout?: number; + } + + interface WriteConcern { + j?: boolean; + w?: number | 'majority' | TagSet; + wtimeout?: number; + } + + interface TagSet { + [k: string]: string; + } + + interface InsertManyOptions { + limit?: number; + rawResult?: boolean; + ordered?: boolean; + lean?: boolean; + session?: mongodb.ClientSession; + populate?: string | string[] | PopulateOptions | PopulateOptions[]; + } + + interface InsertManyResult extends mongodb.InsertManyResult { + mongoose?: { validationErrors?: Array } + } + + interface MapReduceOptions { + map: Function | string; + reduce: (key: Key, vals: T[]) => Val; + /** query filter object. */ + query?: any; + /** sort input objects using this key */ + sort?: any; + /** max number of documents */ + limit?: number; + /** keep temporary data default: false */ + keeptemp?: boolean; + /** finalize function */ + finalize?: (key: Key, val: Val) => Val; + /** scope variables exposed to map/reduce/finalize during execution */ + scope?: any; + /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */ + jsMode?: boolean; + /** provide statistics on job execution time. default: false */ + verbose?: boolean; + readPreference?: string; + /** sets the output target for the map reduce job. default: {inline: 1} */ + out?: { + /** the results are returned in an array */ + inline?: number; + /** + * {replace: 'collectionName'} add the results to collectionName: the + * results replace the collection + */ + replace?: string; + /** + * {reduce: 'collectionName'} add the results to collectionName: if + * dups are detected, uses the reducer / finalize functions + */ + reduce?: string; + /** + * {merge: 'collectionName'} add the results to collectionName: if + * dups exist the new docs overwrite the old + */ + merge?: string; + }; + } + + interface GeoSearchOptions { + /** x,y point to search for */ + near: number[]; + /** the maximum distance from the point near that a result can be */ + maxDistance: number; + /** The maximum number of results to return */ + limit?: number; + /** return the raw object instead of the Mongoose Model */ + lean?: boolean; + } + + interface PopulateOptions { + /** space delimited path(s) to populate */ + path: string; + /** fields to select */ + select?: any; + /** query conditions to match */ + match?: any; + /** optional model to use for population */ + model?: string | Model; + /** optional query options like sort, limit, etc */ + options?: any; + /** deep populate */ + populate?: PopulateOptions | Array; + /** + * If true Mongoose will always set `path` to an array, if false Mongoose will + * always set `path` to a document. Inferred from schema by default. + */ + justOne?: boolean; + /** transform function to call on every populated doc */ + transform?: (doc: any, id: any) => any; + } + + interface ToObjectOptions { + /** apply all getters (path and virtual getters) */ + getters?: boolean; + /** apply virtual getters (can override getters option) */ + virtuals?: boolean | string[]; + /** if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. */ + aliases?: boolean; + /** remove empty objects (defaults to true) */ + minimize?: boolean; + /** if set, mongoose will call this function to allow you to transform the returned object */ + transform?: (doc: any, ret: any, options: any) => any; + /** if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. */ + depopulate?: boolean; + /** if false, exclude the version key (`__v` by default) from the output */ + versionKey?: boolean; + /** if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. */ + flattenMaps?: boolean; + /** If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. */ + useProjection?: boolean; + } + + type MongooseDocumentMiddleware = 'validate' | 'save' | 'remove' | 'updateOne' | 'deleteOne' | 'init'; + type MongooseQueryMiddleware = 'count' | 'deleteMany' | 'deleteOne' | 'distinct' | 'find' | 'findOne' | 'findOneAndDelete' | 'findOneAndRemove' | 'findOneAndUpdate' | 'remove' | 'update' | 'updateOne' | 'updateMany'; + + type SchemaPreOptions = { document?: boolean, query?: boolean }; + type SchemaPostOptions = { document?: boolean, query?: boolean }; + + type ExtractQueryHelpers = M extends Model ? TQueryHelpers : {}; + type ExtractVirtuals = M extends Model ? TVirtuals : {}; + + type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text'; + type IndexDefinition = Record; + + type PreMiddlewareFunction = (this: T, next: (err?: CallbackError) => void) => void | Promise; + type PreSaveMiddlewareFunction = (this: T, next: (err?: CallbackError) => void, opts: SaveOptions) => void | Promise; + type PostMiddlewareFunction = (this: ThisType, res: ResType, next: (err?: CallbackError) => void) => void | Promise; + type ErrorHandlingMiddlewareFunction = (this: ThisType, err: NativeError, res: ResType, next: (err?: CallbackError) => void) => void; + + class Schema, TInstanceMethods = {}> extends events.EventEmitter { + /** + * Create a new schema + */ + constructor(definition?: SchemaDefinition>, options?: SchemaOptions); + + /** Adds key path / schema type pairs to this schema. */ + add(obj: SchemaDefinition> | Schema, prefix?: string): this; + + /** + * Array of child schemas (from document arrays and single nested subdocs) + * and their corresponding compiled models. Each element of the array is + * an object with 2 properties: `schema` and `model`. + */ + childSchemas: { schema: Schema, model: any }[]; + + /** Returns a copy of this schema */ + clone(): Schema; + + /** Object containing discriminators defined on this schema */ + discriminators?: { [name: string]: Schema }; + + /** Iterates the schemas paths similar to Array#forEach. */ + eachPath(fn: (path: string, type: SchemaType) => void): this; + + /** Defines an index (most likely compound) for this schema. */ + index(fields: IndexDefinition, options?: IndexOptions): this; + + /** + * Returns a list of indexes that this schema declares, via `schema.index()` + * or by `index: true` in a path's options. + */ + indexes(): Array; + + /** Gets a schema option. */ + get(key: K): SchemaOptions[K]; + + /** + * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static), + * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions) + * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals), + * [statics](http://mongoosejs.com/docs/guide.html#statics), and + * [methods](http://mongoosejs.com/docs/guide.html#methods). + */ + loadClass(model: Function, onlyVirtuals?: boolean): this; + + /** Adds an instance method to documents constructed from Models compiled from this schema. */ + method(name: string, fn: (this: EnforceDocument>, ...args: any[]) => any, opts?: any): this; + method(obj: { [name: string]: (this: EnforceDocument>, ...args: any[]) => any }): this; + + /** Object of currently defined methods on this schema. */ + methods: { [name: string]: (this: EnforceDocument>, ...args: any[]) => any }; + + /** The original object passed to the schema constructor */ + obj: any; + + /** Gets/sets schema paths. */ + path(path: string): ResultType; + path(path: string, constructor: any): this; + + /** Lists all paths and their type in the schema. */ + paths: { + [key: string]: SchemaType; + } + + /** Returns the pathType of `path` for this schema. */ + pathType(path: string): string; + + /** Registers a plugin for this schema. */ + plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): this; + + /** Defines a post hook for the model. */ + post>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction): this; + post>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction): this; + post = Query>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: PostMiddlewareFunction): this; + post = Query>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction): this; + post = Aggregate>(method: 'aggregate' | RegExp, fn: PostMiddlewareFunction>): this; + post = Aggregate>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction>): this; + post(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction): this; + post(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction): this; + + post>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction): this; + post>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction): this; + post = Query>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: ErrorHandlingMiddlewareFunction): this; + post = Query>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction): this; + post = Aggregate>(method: 'aggregate' | RegExp, fn: ErrorHandlingMiddlewareFunction>): this; + post = Aggregate>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction>): this; + post(method: 'insertMany' | RegExp, fn: ErrorHandlingMiddlewareFunction): this; + post(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction): this; + + /** Defines a pre hook for the model. */ + pre>>(method: 'save', fn: PreSaveMiddlewareFunction): this; + pre>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PreMiddlewareFunction): this; + pre>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction): this; + pre = Query>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: PreMiddlewareFunction): this; + pre = Query>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction): this; + pre = Aggregate>(method: 'aggregate' | RegExp, fn: PreMiddlewareFunction): this; + pre = Aggregate>(method: 'aggregate' | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction): this; + pre(method: 'insertMany' | RegExp, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array) => void | Promise): this; + pre(method: 'insertMany' | RegExp, options: SchemaPreOptions, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array) => void | Promise): this; + + /** Object of currently defined query helpers on this schema. */ + query: { [name: string]: (this: QueryWithHelpers>, ...args: any[]) => any }; + + /** Adds a method call to the queue. */ + queue(name: string, args: any[]): this; + + /** Removes the given `path` (or [`paths`]). */ + remove(paths: string | Array): this; + + /** Returns an Array of path strings that are required by this schema. */ + requiredPaths(invalidate?: boolean): string[]; + + /** Sets a schema option. */ + set(key: K, value: SchemaOptions[K], _tags?: any): this; + + /** Adds static "class" methods to Models compiled from this schema. */ + static(name: string, fn: (this: M, ...args: any[]) => any): this; + static(obj: { [name: string]: (this: M, ...args: any[]) => any }): this; + + /** Object of currently defined statics on this schema. */ + statics: { [name: string]: (this: M, ...args: any[]) => any }; + + /** Creates a virtual type with the given name. */ + virtual(name: string, options?: VirtualTypeOptions): VirtualType; + + /** Object of currently defined virtuals on this schema */ + virtuals: any; + + /** Returns the virtual type with the given `name`. */ + virtualpath(name: string): VirtualType | null; + } + + type SchemaDefinitionWithBuiltInClass = T extends number + ? (typeof Number | 'number' | 'Number' | typeof Schema.Types.Number) + : T extends string + ? (typeof String | 'string' | 'String' | typeof Schema.Types.String) + : T extends boolean + ? (typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean) + : T extends NativeDate + ? (typeof NativeDate | 'date' | 'Date' | typeof Schema.Types.Date) + : (Function | string); + + type SchemaDefinitionProperty = SchemaDefinitionWithBuiltInClass | + SchemaTypeOptions | + typeof SchemaType | + Schema | + Schema[] | + SchemaTypeOptions[] | + Function[] | + SchemaDefinition | + SchemaDefinition[]; + + type SchemaDefinition = T extends undefined + ? { [path: string]: SchemaDefinitionProperty; } + : { [path in keyof T]?: SchemaDefinitionProperty; }; + + interface SchemaOptions { + /** + * By default, Mongoose's init() function creates all the indexes defined in your model's schema by + * calling Model.createIndexes() after you successfully connect to MongoDB. If you want to disable + * automatic index builds, you can set autoIndex to false. + */ + autoIndex?: boolean; + /** + * If set to `true`, Mongoose will call Model.createCollection() to create the underlying collection + * in MongoDB if autoCreate is set to true. Calling createCollection() sets the collection's default + * collation based on the collation option and establishes the collection as a capped collection if + * you set the capped schema option. + */ + autoCreate?: boolean; + /** + * By default, mongoose buffers commands when the connection goes down until the driver manages to reconnect. + * To disable buffering, set bufferCommands to false. + */ + bufferCommands?: boolean; + /** + * If bufferCommands is on, this option sets the maximum amount of time Mongoose buffering will wait before + * throwing an error. If not specified, Mongoose will use 10000 (10 seconds). + */ + bufferTimeoutMS?: number; + /** + * Mongoose supports MongoDBs capped collections. To specify the underlying MongoDB collection be capped, set + * the capped option to the maximum size of the collection in bytes. + */ + capped?: boolean | number | { size?: number; max?: number; autoIndexId?: boolean; }; + /** Sets a default collation for every query and aggregation. */ + collation?: mongodb.CollationOptions; + /** + * Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName + * method. This method pluralizes the name. Set this option if you need a different name for your collection. + */ + collection?: string; + /** + * When you define a [discriminator](/docs/discriminators.html), Mongoose adds a path to your + * schema that stores which discriminator a document is an instance of. By default, Mongoose + * adds an `__t` path, but you can set `discriminatorKey` to overwrite this default. + */ + discriminatorKey?: string; + /** defaults to false. */ + emitIndexErrors?: boolean; + excludeIndexes?: any; + /** + * Mongoose assigns each of your schemas an id virtual getter by default which returns the document's _id field + * cast to a string, or in the case of ObjectIds, its hexString. + */ + id?: boolean; + /** + * Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema + * constructor. The type assigned is an ObjectId to coincide with MongoDB's default behavior. If you + * don't want an _id added to your schema at all, you may disable it using this option. + */ + _id?: boolean; + /** + * Mongoose will, by default, "minimize" schemas by removing empty objects. This behavior can be + * overridden by setting minimize option to false. It will then store empty objects. + */ + minimize?: boolean; + /** + * Optimistic concurrency is a strategy to ensure the document you're updating didn't change between when you + * loaded it using find() or findOne(), and when you update it using save(). Set to `true` to enable + * optimistic concurrency. + */ + optimisticConcurrency?: boolean; + /** + * Allows setting query#read options at the schema level, providing us a way to apply default ReadPreferences + * to all queries derived from a model. + */ + read?: string; + /** Allows setting write concern at the schema level. */ + writeConcern?: WriteConcern; + /** defaults to true. */ + safe?: boolean | { w?: number | string; wtimeout?: number; j?: boolean }; + /** + * The shardKey option is used when we have a sharded MongoDB architecture. Each sharded collection is + * given a shard key which must be present in all insert/update operations. We just need to set this + * schema option to the same shard key and we'll be all set. + */ + shardKey?: Record; + /** + * The strict option, (enabled by default), ensures that values passed to our model constructor that were not + * specified in our schema do not get saved to the db. + */ + strict?: boolean | 'throw'; + /** + * equal to `strict` by default, may be `false`, `true`, or `'throw'`. Sets the default + * [strictQuery](https://mongoosejs.com/docs/guide.html#strictQuery) mode for schemas. + */ + strictQuery?: boolean | 'throw'; + /** Exactly the same as the toObject option but only applies when the document's toJSON method is called. */ + toJSON?: ToObjectOptions; + /** + * Documents have a toObject method which converts the mongoose document into a plain JavaScript object. + * This method accepts a few options. Instead of applying these options on a per-document basis, we may + * declare the options at the schema level and have them applied to all of the schema's documents by + * default. + */ + toObject?: ToObjectOptions; + /** + * By default, if you have an object with key 'type' in your schema, mongoose will interpret it as a + * type declaration. However, for applications like geoJSON, the 'type' property is important. If you want to + * control which key mongoose uses to find type declarations, set the 'typeKey' schema option. + */ + typeKey?: string; + + /** + * By default, documents are automatically validated before they are saved to the database. This is to + * prevent saving an invalid document. If you want to handle validation manually, and be able to save + * objects which don't pass validation, you can set validateBeforeSave to false. + */ + validateBeforeSave?: boolean; + /** + * The versionKey is a property set on each document when first created by Mongoose. This keys value + * contains the internal revision of the document. The versionKey option is a string that represents + * the path to use for versioning. The default is '__v'. + */ + versionKey?: string | boolean; + /** + * By default, Mongoose will automatically select() any populated paths for you, unless you explicitly exclude them. + */ + selectPopulatedPaths?: boolean; + /** + * skipVersioning allows excluding paths from versioning (i.e., the internal revision will not be + * incremented even if these paths are updated). DO NOT do this unless you know what you're doing. + * For subdocuments, include this on the parent document using the fully qualified path. + */ + skipVersioning?: any; + /** + * Validation errors in a single nested schema are reported + * both on the child and on the parent schema. + * Set storeSubdocValidationError to false on the child schema + * to make Mongoose only report the parent error. + */ + storeSubdocValidationError?: boolean; + /** + * The timestamps option tells mongoose to assign createdAt and updatedAt fields to your schema. The type + * assigned is Date. By default, the names of the fields are createdAt and updatedAt. Customize the + * field names by setting timestamps.createdAt and timestamps.updatedAt. + */ + timestamps?: boolean | SchemaTimestampsConfig; + } + + interface SchemaTimestampsConfig { + createdAt?: boolean | string; + updatedAt?: boolean | string; + currentTime?: () => (NativeDate | number); + } + + type Unpacked = T extends (infer U)[] ? + U : + T extends ReadonlyArray ? U : T; + + type AnyArray = T[] | ReadonlyArray; + + export class SchemaTypeOptions { + type?: + T extends string | number | boolean | NativeDate | Function ? SchemaDefinitionWithBuiltInClass : + T extends Schema ? T : + T extends object[] ? (AnyArray> | AnyArray>> | AnyArray>>) : + T extends string[] ? AnyArray> | AnyArray> : + T extends number[] ? AnyArray> | AnyArray> : + T extends boolean[] ? AnyArray> | AnyArray> : + T extends Function[] ? AnyArray> | AnyArray>> : + T | typeof SchemaType | Schema | SchemaDefinition; + + /** Defines a virtual with the given name that gets/sets this path. */ + alias?: string; + + /** Function or object describing how to validate this schematype. See [validation docs](https://mongoosejs.com/docs/validation.html). */ + validate?: RegExp | [RegExp, string] | Function | [Function, string] | ValidateOpts | ValidateOpts[]; + + /** Allows overriding casting logic for this individual path. If a string, the given string overwrites Mongoose's default cast error message. */ + cast?: string; + + /** + * If true, attach a required validator to this path, which ensures this path + * path cannot be set to a nullish value. If a function, Mongoose calls the + * function and only checks for nullish values if the function returns a truthy value. + */ + required?: boolean | (() => boolean) | [boolean, string] | [() => boolean, string]; + + /** + * The default value for this path. If a function, Mongoose executes the function + * and uses the return value as the default. + */ + default?: T | ((this: any, doc: any) => T); + + /** + * The model that `populate()` should use if populating this path. + */ + ref?: string | Model | ((this: any, doc: any) => string | Model); + + /** + * Whether to include or exclude this path by default when loading documents + * using `find()`, `findOne()`, etc. + */ + select?: boolean | number; + + /** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will + * build an index on this path when the model is compiled. + */ + index?: boolean | number | IndexOptions | '2d' | '2dsphere' | 'hashed' | 'text'; + + /** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose + * will build a unique index on this path when the + * model is compiled. [The `unique` option is **not** a validator](/docs/validation.html#the-unique-option-is-not-a-validator). + */ + unique?: boolean | number; + + /** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will + * disallow changes to this path once the document is saved to the database for the first time. Read more + * about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html). + */ + immutable?: boolean | ((this: any, doc: any) => boolean); + + /** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will + * build a sparse index on this path. + */ + sparse?: boolean | number; + + /** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose + * will build a text index on this path. + */ + text?: boolean | number | any; + + /** + * Define a transform function for this individual schema type. + * Only called when calling `toJSON()` or `toObject()`. + */ + transform?: (this: any, val: T) => any; + + /** defines a custom getter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */ + get?: (value: T, schematype?: this) => any; + + /** defines a custom setter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */ + set?: (value: T, schematype?: this) => any; + + /** array of allowed values for this path. Allowed for strings, numbers, and arrays of strings */ + enum?: Array | ReadonlyArray | { values: Array | ReadonlyArray, message?: string } | { [path: string]: string | number | null }; + + /** The default [subtype](http://bsonspec.org/spec.html) associated with this buffer when it is stored in MongoDB. Only allowed for buffer paths */ + subtype?: number + + /** The minimum value allowed for this path. Only allowed for numbers and dates. */ + min?: number | NativeDate | [number, string] | [NativeDate, string] | readonly [number, string] | readonly [NativeDate, string]; + + /** The maximum value allowed for this path. Only allowed for numbers and dates. */ + max?: number | NativeDate | [number, string] | [NativeDate, string] | readonly [number, string] | readonly [NativeDate, string]; + + /** Defines a TTL index on this path. Only allowed for dates. */ + expires?: string | number; + + /** If `true`, Mongoose will skip gathering indexes on subpaths. Only allowed for subdocuments and subdocument arrays. */ + excludeIndexes?: boolean; + + /** If set, overrides the child schema's `_id` option. Only allowed for subdocuments and subdocument arrays. */ + _id?: boolean; + + /** If set, specifies the type of this map's values. Mongoose will cast this map's values to the given type. */ + of?: Function | SchemaDefinitionProperty; + + /** If true, uses Mongoose's default `_id` settings. Only allowed for ObjectIds */ + auto?: boolean; + + /** Attaches a validator that succeeds if the data string matches the given regular expression, and fails otherwise. */ + match?: RegExp | [RegExp, string] | readonly [RegExp, string]; + + /** If truthy, Mongoose will add a custom setter that lowercases this string using JavaScript's built-in `String#toLowerCase()`. */ + lowercase?: boolean; + + /** If truthy, Mongoose will add a custom setter that removes leading and trailing whitespace using JavaScript's built-in `String#trim()`. */ + trim?: boolean; + + /** If truthy, Mongoose will add a custom setter that uppercases this string using JavaScript's built-in `String#toUpperCase()`. */ + uppercase?: boolean; + + /** If set, Mongoose will add a custom validator that ensures the given string's `length` is at least the given number. */ + minlength?: number | [number, string] | readonly [number, string]; + + /** If set, Mongoose will add a custom validator that ensures the given string's `length` is at most the given number. */ + maxlength?: number | [number, string] | readonly [number, string]; + + [other: string]: any; + } + + export type RefType = + | number + | string + | Buffer + | undefined + | mongoose.Types.ObjectId + | mongoose.Types.Buffer + | typeof mongoose.Schema.Types.Number + | typeof mongoose.Schema.Types.String + | typeof mongoose.Schema.Types.Buffer + | typeof mongoose.Schema.Types.ObjectId; + + /** + * Reference another Model + */ + export type PopulatedDoc< + PopulatedType, + RawId extends RefType = (PopulatedType extends { _id?: RefType; } ? NonNullable : mongoose.Types.ObjectId) | undefined + > = PopulatedType | RawId; + + interface IndexOptions extends mongodb.CreateIndexesOptions { + /** + * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax: + * + * @example + * ```js + * const schema = new Schema({ prop1: Date }); + * + * // expire in 24 hours + * schema.index({ prop1: 1 }, { expires: 60*60*24 }) + * + * // expire in 24 hours + * schema.index({ prop1: 1 }, { expires: '24h' }) + * + * // expire in 1.5 hours + * schema.index({ prop1: 1 }, { expires: '1.5h' }) + * + * // expire in 7 days + * schema.index({ prop1: 1 }, { expires: '7d' }) + * ``` + */ + expires?: number | string; + weights?: AnyObject; + } + + interface ValidatorProps { + path: string; + value: any; + } + + interface ValidatorMessageFn { + (props: ValidatorProps): string; + } + + interface ValidateFn { + (value: T): boolean; + } + + interface LegacyAsyncValidateFn { + (value: T, done: (result: boolean) => void): void; + } + + interface AsyncValidateFn { + (value: any): Promise; + } + + interface ValidateOpts { + msg?: string; + message?: string | ValidatorMessageFn; + type?: string; + validator: ValidateFn | LegacyAsyncValidateFn | AsyncValidateFn; + } + + interface VirtualTypeOptions { + /** If `ref` is not nullish, this becomes a populated virtual. */ + ref?: string | Function; + + /** The local field to populate on if this is a populated virtual. */ + localField?: string | Function; + + /** The foreign field to populate on if this is a populated virtual. */ + foreignField?: string | Function; + + /** + * By default, a populated virtual is an array. If you set `justOne`, + * the populated virtual will be a single doc or `null`. + */ + justOne?: boolean; + + /** If you set this to `true`, Mongoose will call any custom getters you defined on this virtual. */ + getters?: boolean; + + /** + * If you set this to `true`, `populate()` will set this virtual to the number of populated + * documents, as opposed to the documents themselves, using `Query#countDocuments()`. + */ + count?: boolean; + + /** Add an extra match condition to `populate()`. */ + match?: FilterQuery | Function; + + /** Add a default `limit` to the `populate()` query. */ + limit?: number; + + /** Add a default `skip` to the `populate()` query. */ + skip?: number; + + /** + * For legacy reasons, `limit` with `populate()` may give incorrect results because it only + * executes a single query for every document being populated. If you set `perDocumentLimit`, + * Mongoose will ensure correct `limit` per document by executing a separate query for each + * document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` + * will execute 2 additional queries if `.find()` returns 2 documents. + */ + perDocumentLimit?: number; + + /** Additional options like `limit` and `lean`. */ + options?: QueryOptions & { match?: AnyObject }; + + /** Additional options for plugins */ + [extra: string]: any; + } + + class VirtualType { + /** Applies getters to `value`. */ + applyGetters(value: any, doc: Document): any; + + /** Applies setters to `value`. */ + applySetters(value: any, doc: Document): any; + + /** Adds a custom getter to this virtual. */ + get(fn: Function): this; + + /** Adds a custom setter to this virtual. */ + set(fn: Function): this; + } + + namespace Schema { + namespace Types { + class Array extends SchemaType implements AcceptsDiscriminator { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + static options: { castNonArrays: boolean; }; + + discriminator(name: string | number, schema: Schema, value?: string): Model; + discriminator(name: string | number, schema: Schema, value?: string): U; + + /** + * Adds an enum validator if this is an array of strings or numbers. Equivalent to + * `SchemaString.prototype.enum()` or `SchemaNumber.prototype.enum()` + */ + enum(vals: string[] | number[]): this; + } + + class Boolean extends SchemaType { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + /** Configure which values get casted to `true`. */ + static convertToTrue: Set; + + /** Configure which values get casted to `false`. */ + static convertToFalse: Set; + } + + class Buffer extends SchemaType { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + /** + * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/) + * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html). + */ + subtype(subtype: number): this; + } + + class Date extends SchemaType { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + /** Declares a TTL index (rounded to the nearest second) for _Date_ types only. */ + expires(when: number | string): this; + + /** Sets a maximum date validator. */ + max(value: NativeDate, message: string): this; + + /** Sets a minimum date validator. */ + min(value: NativeDate, message: string): this; + } + + class Decimal128 extends SchemaType { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + class DocumentArray extends SchemaType implements AcceptsDiscriminator { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + static options: { castNonArrays: boolean; }; + + discriminator(name: string | number, schema: Schema, value?: string): Model; + discriminator(name: string | number, schema: Schema, value?: string): U; + + /** The schema used for documents in this array */ + schema: Schema; + } + + class Map extends SchemaType { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + class Mixed extends SchemaType { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + class Number extends SchemaType { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + /** Sets a enum validator */ + enum(vals: number[]): this; + + /** Sets a maximum number validator. */ + max(value: number, message: string): this; + + /** Sets a minimum number validator. */ + min(value: number, message: string): this; + } + + class ObjectId extends SchemaType { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + /** Adds an auto-generated ObjectId default if turnOn is true. */ + auto(turnOn: boolean): this; + } + + class Subdocument extends SchemaType implements AcceptsDiscriminator { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + /** The document's schema */ + schema: Schema; + + discriminator(name: string | number, schema: Schema, value?: string): Model; + discriminator(name: string | number, schema: Schema, value?: string): U; + } + + class String extends SchemaType { + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + /** Adds an enum validator */ + enum(vals: string[] | any): this; + + /** Adds a lowercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */ + lowercase(shouldApply?: boolean): this; + + /** Sets a regexp validator. */ + match(value: RegExp, message: string): this; + + /** Sets a maximum length validator. */ + maxlength(value: number, message: string): this; + + /** Sets a minimum length validator. */ + minlength(value: number, message: string): this; + + /** Adds a trim [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */ + trim(shouldTrim?: boolean): this; + + /** Adds an uppercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */ + uppercase(shouldApply?: boolean): this; + } + } + } + + namespace Types { + class Array extends global.Array { + /** Pops the array atomically at most one time per document `save()`. */ + $pop(): T; + + /** Atomically shifts the array at most one time per document `save()`. */ + $shift(): T; + + /** Adds values to the array if not already present. */ + addToSet(...args: any[]): any[]; + + isMongooseArray: true; + + /** Pushes items to the array non-atomically. */ + nonAtomicPush(...args: any[]): number; + + /** Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. */ + push(...args: any[]): number; + + /** + * Pulls items from the array atomically. Equality is determined by casting + * the provided value to an embedded document and comparing using + * [the `Document.equals()` function.](./api.html#document_Document-equals) + */ + pull(...args: any[]): this; + + /** + * Alias of [pull](#mongoosearray_MongooseArray-pull) + */ + remove(...args: any[]): this; + + /** Sets the casted `val` at index `i` and marks the array modified. */ + set(i: number, val: T): this; + + /** Atomically shifts the array at most one time per document `save()`. */ + shift(): T; + + /** Returns a native js Array. */ + toObject(options?: ToObjectOptions): any; + toObject(options?: ToObjectOptions): T; + + /** Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. */ + unshift(...args: any[]): number; + } + + class Buffer extends global.Buffer { + /** Sets the subtype option and marks the buffer modified. */ + subtype(subtype: number | ToObjectOptions): void; + + /** Converts this buffer to its Binary type representation. */ + toObject(subtype?: number): mongodb.Binary; + } + + class Decimal128 extends mongodb.Decimal128 { } + + class DocumentArray extends Types.Array { + /** DocumentArray constructor */ + constructor(values: any[]); + + isMongooseDocumentArray: true; + + /** Creates a subdocument casted to this schema. */ + create(obj: any): T; + + /** Searches array items for the first document with a matching _id. */ + id(id: any): T | null; + + push(...args: (AnyKeys & AnyObject)[]): number; + } + + class Map extends global.Map { + /** Converts a Mongoose map into a vanilla JavaScript map. */ + toObject(options?: ToObjectOptions & { flattenMaps?: boolean }): any; + } + + class ObjectId extends mongodb.ObjectId { + _id: this; + } + + class Subdocument extends Document { + $isSingleNested: true; + + /** Returns the top level document of this sub-document. */ + ownerDocument(): Document; + + /** Returns this sub-documents parent document. */ + parent(): Document; + + /** Returns this sub-documents parent document. */ + $parent(): Document; + } + } + + type ReturnsNewDoc = { new: true } | { returnOriginal: false } | {returnDocument: 'after'}; + + type QueryWithHelpers = Query & THelpers; + + class Query { + _mongooseOptions: MongooseQueryOptions; + + /** + * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html). + * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function. + * This is equivalent to calling `.cursor()` with no arguments. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + + /** Executes the query */ + exec(): Promise; + exec(callback?: Callback): void; + // @todo: this doesn't seem right + exec(callback?: Callback): Promise | any; + + $where(argument: string | Function): QueryWithHelpers; + + /** Specifies an `$all` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + all(val: Array): this; + all(path: string, val: Array): this; + + /** Sets the allowDiskUse option for the query (ignored for < 4.4.0) */ + allowDiskUse(value: boolean): this; + + /** Specifies arguments for an `$and` condition. */ + and(array: FilterQuery[]): this; + + /** Specifies the batchSize option. */ + batchSize(val: number): this; + + /** Specifies a `$box` condition */ + box(val: any): this; + box(lower: number[], upper: number[]): this; + + /** + * Casts this query to the schema of `model`. + * + * @param {Model} [model] the model to cast to. If not set, defaults to `this.model` + * @param {Object} [obj] If not set, defaults to this query's conditions + * @return {Object} the casted `obj` + */ + cast(model?: Model | null, obj?: any): any; + + /** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * Like `.then()`, but only takes a rejection handler. + */ + catch: Promise['catch']; + + /** Specifies a `$center` or `$centerSphere` condition. */ + circle(area: any): this; + circle(path: string, area: any): this; + + /** Adds a collation to this op (MongoDB 3.4 and up) */ + collation(value: mongodb.CollationOptions): this; + + /** Specifies the `comment` option. */ + comment(val: string): this; + + /** Specifies this query as a `count` query. */ + count(callback?: Callback): QueryWithHelpers; + count(criteria: FilterQuery, callback?: Callback): QueryWithHelpers; + + /** Specifies this query as a `countDocuments` query. */ + countDocuments(callback?: Callback): QueryWithHelpers; + countDocuments(criteria: FilterQuery, callback?: Callback): QueryWithHelpers; + + /** + * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html). + * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function. + */ + cursor(options?: any): QueryCursor; + + /** + * Declare and/or execute this query as a `deleteMany()` operation. Works like + * remove, except it deletes _every_ document that matches `filter` in the + * collection, regardless of the value of `single`. + */ + deleteMany(filter?: FilterQuery, options?: QueryOptions, callback?: Callback): QueryWithHelpers; + deleteMany(filter: FilterQuery, callback: Callback): QueryWithHelpers; + deleteMany(callback: Callback): QueryWithHelpers; + + /** + * Declare and/or execute this query as a `deleteOne()` operation. Works like + * remove, except it deletes at most one document regardless of the `single` + * option. + */ + deleteOne(filter?: FilterQuery, options?: QueryOptions, callback?: Callback): QueryWithHelpers; + deleteOne(filter: FilterQuery, callback: Callback): QueryWithHelpers; + deleteOne(callback: Callback): QueryWithHelpers; + + /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */ + distinct(field: string, filter?: FilterQuery, callback?: Callback): QueryWithHelpers, DocType, THelpers, RawDocType>; + + /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + elemMatch(val: Function | any): this; + elemMatch(path: string, val: Function | any): this; + + /** + * Gets/sets the error flag on this query. If this flag is not null or + * undefined, the `exec()` promise will reject without executing. + */ + error(): NativeError | null; + error(val: NativeError | null): this; + + /** Specifies the complementary comparison value for paths specified with `where()` */ + equals(val: any): this; + + /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */ + estimatedDocumentCount(options?: QueryOptions, callback?: Callback): QueryWithHelpers; + + /** Specifies a `$exists` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + exists(val: boolean): this; + exists(path: string, val: boolean): this; + + /** + * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/), + * which makes this query return detailed execution stats instead of the actual + * query result. This method is useful for determining what index your queries + * use. + */ + explain(verbose?: string): this; + + /** Creates a `find` query: gets a list of documents that match `filter`. */ + find(callback?: Callback): QueryWithHelpers, DocType, THelpers, RawDocType>; + find(filter: FilterQuery, callback?: Callback): QueryWithHelpers, DocType, THelpers, RawDocType>; + find(filter: FilterQuery, projection?: any | null, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers, DocType, THelpers, RawDocType>; + + /** Declares the query a findOne operation. When executed, the first found document is passed to the callback. */ + findOne(filter?: FilterQuery, projection?: any | null, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers; + + /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */ + findOneAndDelete(filter?: FilterQuery, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers; + + /** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */ + findOneAndRemove(filter?: FilterQuery, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers; + + /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */ + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: DocType | null, res: mongodb.ModifyResult) => void): QueryWithHelpers, DocType, THelpers, RawDocType>; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: DocType, res: mongodb.ModifyResult) => void): QueryWithHelpers; + findOneAndUpdate(filter?: FilterQuery, update?: UpdateQuery, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null, res: mongodb.ModifyResult) => void): QueryWithHelpers; + + /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */ + findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers; + + /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */ + findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: any, res?: any) => void): QueryWithHelpers; + findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: DocType, res?: any) => void): QueryWithHelpers; + findByIdAndUpdate(id?: mongodb.ObjectId | any, update?: UpdateQuery, options?: QueryOptions | null, callback?: (CallbackError: any, doc: DocType | null, res?: any) => void): QueryWithHelpers; + findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery, callback: (CallbackError: any, doc: DocType | null, res?: any) => void): QueryWithHelpers; + + /** Specifies a `$geometry` condition */ + geometry(object: { type: string, coordinates: any[] }): this; + + /** + * For update operations, returns the value of a path in the update's `$set`. + * Useful for writing getters/setters that can work with both update operations + * and `save()`. + */ + get(path: string): any; + + /** Returns the current query filter (also known as conditions) as a POJO. */ + getFilter(): FilterQuery; + + /** Gets query options. */ + getOptions(): QueryOptions; + + /** Gets a list of paths to be populated by this query */ + getPopulatedPaths(): Array; + + /** Returns the current query filter. Equivalent to `getFilter()`. */ + getQuery(): FilterQuery; + + /** Returns the current update operations as a JSON object. */ + getUpdate(): UpdateQuery | UpdateWithAggregationPipeline | null; + + /** Specifies a `$gt` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + gt(val: number): this; + gt(path: string, val: number): this; + + /** Specifies a `$gte` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + gte(val: number): this; + gte(path: string, val: number): this; + + /** Sets query hints. */ + hint(val: any): this; + + /** Specifies an `$in` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + in(val: Array): this; + in(path: string, val: Array): this; + + /** Declares an intersects query for `geometry()`. */ + intersects(arg?: any): this; + + /** Requests acknowledgement that this operation has been persisted to MongoDB's on-disk journal. */ + j(val: boolean | null): this; + + /** Sets the lean option. */ + lean : LeanDocumentOrArrayWithRawType>(val?: boolean | any): QueryWithHelpers; + + /** Specifies the maximum number of documents the query will return. */ + limit(val: number): this; + + /** Specifies a `$lt` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + lt(val: number): this; + lt(path: string, val: number): this; + + /** Specifies a `$lte` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + lte(val: number): this; + lte(path: string, val: number): this; + + /** + * Runs a function `fn` and treats the return value of `fn` as the new value + * for the query to resolve to. + */ + map(fn: (doc: ResultType) => MappedType): QueryWithHelpers; + + /** Specifies an `$maxDistance` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + maxDistance(val: number): this; + maxDistance(path: string, val: number): this; + + /** Specifies the maxScan option. */ + maxScan(val: number): this; + + /** + * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/) + * option. This will tell the MongoDB server to abort if the query or write op + * has been running for more than `ms` milliseconds. + */ + maxTimeMS(ms: number): this; + + /** Merges another Query or conditions object into this one. */ + merge(source: Query | FilterQuery): this; + + /** Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`. */ + mod(val: Array): this; + mod(path: string, val: Array): this; + + /** The model this query was created from */ + model: typeof Model; + + /** + * Getter/setter around the current mongoose-specific options for this query + * Below are the current Mongoose-specific options. + */ + mongooseOptions(val?: MongooseQueryOptions): MongooseQueryOptions; + + /** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + ne(val: any): this; + ne(path: string, val: any): this; + + /** Specifies a `$near` or `$nearSphere` condition */ + near(val: any): this; + near(path: string, val: any): this; + + /** Specifies an `$nin` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + nin(val: Array): this; + nin(path: string, val: Array): this; + + /** Specifies arguments for an `$nor` condition. */ + nor(array: Array>): this; + + /** Specifies arguments for an `$or` condition. */ + or(array: Array>): this; + + /** + * Make this query throw an error if no documents match the given `filter`. + * This is handy for integrating with async/await, because `orFail()` saves you + * an extra `if` statement to check if no document was found. + */ + orFail(err?: NativeError | (() => NativeError)): QueryWithHelpers, DocType, THelpers, RawDocType>; + + /** Specifies a `$polygon` condition */ + polygon(...coordinatePairs: number[][]): this; + polygon(path: string, ...coordinatePairs: number[][]): this; + + /** Specifies paths which should be populated with other documents. */ + populate(path: string | any, select?: string | any, model?: string | Model, match?: any): QueryWithHelpers; + populate(options: PopulateOptions | Array): QueryWithHelpers; + + /** Get/set the current projection (AKA fields). Pass `null` to remove the current projection. */ + projection(fields?: any | null): any; + + /** Determines the MongoDB nodes from which to read. */ + read(pref: string | mongodb.ReadPreferenceMode, tags?: any[]): this; + + /** Sets the readConcern option for the query. */ + readConcern(level: string): this; + + /** Specifies a `$regex` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + regex(val: string | RegExp): this; + regex(path: string, val: string | RegExp): this; + + /** + * Declare and/or execute this query as a remove() operation. `remove()` is + * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne) + * or [`deleteMany()`](#query_Query-deleteMany) instead. + */ + remove(filter?: FilterQuery, callback?: Callback): Query; + + /** + * Declare and/or execute this query as a replaceOne() operation. Same as + * `update()`, except MongoDB will replace the existing document and will + * not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.) + */ + replaceOne(filter?: FilterQuery, replacement?: DocType | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers; + replaceOne(filter?: FilterQuery, replacement?: DocType | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers; + + /** Specifies which document fields to include or exclude (also known as the query "projection") */ + select(arg: string | any): this; + + /** Determines if field selection has been made. */ + selected(): boolean; + + /** Determines if exclusive field selection has been made. */ + selectedExclusively(): boolean; + + /** Determines if inclusive field selection has been made. */ + selectedInclusively(): boolean; + + /** + * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/) + * associated with this query. Sessions are how you mark a query as part of a + * [transaction](/docs/transactions.html). + */ + session(session: mongodb.ClientSession | null): this; + + /** + * Adds a `$set` to this query's update without changing the operation. + * This is useful for query middleware so you can add an update regardless + * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc. + */ + set(path: string, value: any): this; + + /** Sets query options. Some options only make sense for certain operations. */ + setOptions(options: QueryOptions, overwrite?: boolean): this; + + /** Sets the query conditions to the provided JSON object. */ + setQuery(val: FilterQuery | null): void; + + setUpdate(update: UpdateQuery | UpdateWithAggregationPipeline): void; + + /** Specifies an `$size` query condition. When called with one argument, the most recent path passed to `where()` is used. */ + size(val: number): this; + size(path: string, val: number): this; + + /** Specifies the number of documents to skip. */ + skip(val: number): this; + + /** Specifies a `$slice` projection for an array. */ + slice(val: number | Array): this; + slice(path: string, val: number | Array): this; + + /** Specifies this query as a `snapshot` query. */ + snapshot(val?: boolean): this; + + /** Sets the sort order. If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. */ + sort(arg: string | any): this; + + /** Sets the tailable option (for use with capped collections). */ + tailable(bool?: boolean, opts?: { + numberOfRetries?: number; + tailableRetryInterval?: number; + }): this; + + /** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + */ + then: Promise['then']; + + /** Converts this query to a customized, reusable query constructor with all arguments and options retained. */ + toConstructor(): new (...args: any[]) => QueryWithHelpers; + + /** Declare and/or execute this query as an update() operation. */ + update(filter?: FilterQuery, update?: UpdateQuery | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers; + + /** + * Declare and/or execute this query as an updateMany() operation. Same as + * `update()`, except MongoDB will update _all_ documents that match + * `filter` (as opposed to just the first one) regardless of the value of + * the `multi` option. + */ + updateMany(filter?: FilterQuery, update?: UpdateQuery | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers; + + /** + * Declare and/or execute this query as an updateOne() operation. Same as + * `update()`, except it does not support the `multi` or `overwrite` options. + */ + updateOne(filter?: FilterQuery, update?: UpdateQuery | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers; + + /** + * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, + * that must acknowledge this write before this write is considered successful. + */ + w(val: string | number | null): this; + + /** Specifies a path for use with chaining. */ + where(path: string, val?: any): this; + where(obj: object): this; + where(): this; + + /** Defines a `$within` or `$geoWithin` argument for geo-spatial queries. */ + within(val?: any): this; + + /** + * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to + * wait for this write to propagate through the replica set before this + * operation fails. The default is `0`, which means no timeout. + */ + wtimeout(ms: number): this; + } + + export type QuerySelector = { + // Comparison + $eq?: T; + $gt?: T; + $gte?: T; + $in?: [T] extends AnyArray ? Unpacked[] : T[]; + $lt?: T; + $lte?: T; + $ne?: T; + $nin?: [T] extends AnyArray ? Unpacked[] : T[]; + // Logical + $not?: T extends string ? QuerySelector | RegExp : QuerySelector; + // Element + /** + * When `true`, `$exists` matches the documents that contain the field, + * including documents where the field value is null. + */ + $exists?: boolean; + $type?: string | number; + // Evaluation + $expr?: any; + $jsonSchema?: any; + $mod?: T extends number ? [number, number] : never; + $regex?: T extends string ? RegExp | string : never; + $options?: T extends string ? string : never; + // Geospatial + // TODO: define better types for geo queries + $geoIntersects?: { $geometry: object }; + $geoWithin?: object; + $near?: object; + $nearSphere?: object; + $maxDistance?: number; + // Array + // TODO: define better types for $all and $elemMatch + $all?: T extends AnyArray ? any[] : never; + $elemMatch?: T extends AnyArray ? object : never; + $size?: T extends AnyArray ? number : never; + // Bitwise + $bitsAllClear?: number | mongodb.Binary | number[]; + $bitsAllSet?: number | mongodb.Binary | number[]; + $bitsAnyClear?: number | mongodb.Binary | number[]; + $bitsAnySet?: number | mongodb.Binary | number[]; + }; + + export type RootQuerySelector = { + /** @see https://docs.mongodb.com/manual/reference/operator/query/and/#op._S_and */ + $and?: Array>; + /** @see https://docs.mongodb.com/manual/reference/operator/query/nor/#op._S_nor */ + $nor?: Array>; + /** @see https://docs.mongodb.com/manual/reference/operator/query/or/#op._S_or */ + $or?: Array>; + /** @see https://docs.mongodb.com/manual/reference/operator/query/text */ + $text?: { + $search: string; + $language?: string; + $caseSensitive?: boolean; + $diacriticSensitive?: boolean; + }; + /** @see https://docs.mongodb.com/manual/reference/operator/query/where/#op._S_where */ + $where?: string | Function; + /** @see https://docs.mongodb.com/manual/reference/operator/query/comment/#op._S_comment */ + $comment?: string; + // we could not find a proper TypeScript generic to support nested queries e.g. 'user.friends.name' + // this will mark all unrecognized properties as any (including nested queries) + [key: string]: any; + }; + + type ReadonlyPartial = { + [key in keyof TSchema]?: TSchema[key]; + }; + + type MatchKeysAndValues = ReadonlyPartial & AnyObject; + + type ApplyBasicQueryCasting = T extends mongodb.ObjectId ? T | string : // Allow strings for ObjectIds + T extends string ? T | RegExp : // Allow RegExps for strings + T extends (infer U)[] ? T | U : // Allow single array elements for arrays + T; + type Condition = ApplyBasicQueryCasting | QuerySelector>; + + type _FilterQuery = { + [P in keyof T]?: Condition; + } & + RootQuerySelector; + + export type FilterQuery = _FilterQuery; + + type AddToSetOperators = { + $each: Type; + }; + + type SortValues = -1 | 1 | 'asc' | 'desc'; + + type ArrayOperator = { + $each: Type; + $slice?: number; + $position?: number; + $sort?: SortValues | Record; + }; + + type OnlyFieldsOfType = { + [key in keyof TSchema]?: [Extract] extends [never] ? never : AssignableType; + }; + + type NumericTypes = number | Decimal128 | mongodb.Double | mongodb.Int32 | mongodb.Long; + + type _UpdateQuery = { + /** @see https://docs.mongodb.com/manual/reference/operator/update-field/ */ + $currentDate?: OnlyFieldsOfType & AnyObject; + $inc?: OnlyFieldsOfType & AnyObject; + $min?: AnyKeys & AnyObject; + $max?: AnyKeys & AnyObject; + $mul?: OnlyFieldsOfType & AnyObject; + $rename?: { [key: string]: string }; + $set?: AnyKeys & AnyObject; + $setOnInsert?: AnyKeys & AnyObject; + $unset?: AnyKeys & AnyObject; + + /** @see https://docs.mongodb.com/manual/reference/operator/update-array/ */ + $addToSet?: OnlyFieldsOfType & AnyObject; + $pop?: OnlyFieldsOfType, 1 | -1> & AnyObject; + $pull?: OnlyFieldsOfType, any> & AnyObject; + $push?: OnlyFieldsOfType, any> & AnyObject; + $pullAll?: OnlyFieldsOfType, any> & AnyObject; + + /** @see https://docs.mongodb.com/manual/reference/operator/update-bitwise/ */ + $bit?: { + [key: string]: { [key in 'and' | 'or' | 'xor']?: number }; + }; + }; + + type UpdateWithAggregationPipeline = UpdateAggregationStage[]; + type UpdateAggregationStage = { $addFields: any } | + { $set: any } | + { $project: any } | + { $unset: any } | + { $replaceRoot: any } | + { $replaceWith: any }; + + type __UpdateDefProperty = + [Extract] extends [never] ? T : + T | string; + type _UpdateQueryDef = { + [K in keyof T]: __UpdateDefProperty; + }; + + export type UpdateQuery = (_UpdateQuery<_UpdateQueryDef> & MatchKeysAndValues<_UpdateQueryDef>>); + + type _AllowStringsForIds = { + [K in keyof T]: [Extract] extends [never] + ? T[K] extends TreatAsPrimitives + ? T[K] + : _AllowStringsForIds + : T[K] | string; + }; + + type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined; + type TreatAsPrimitives = actualPrimitives | + NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId; + + type LeanType = + 0 extends (1 & T) ? T : // any + T extends TreatAsPrimitives ? T : // primitives + T extends Types.Subdocument ? Omit, '$isSingleNested' | 'ownerDocument' | 'parent'> : // subdocs + LeanDocument; // Documents and everything else + + type LeanArray = T extends unknown[][] ? LeanArray[] : LeanType[]; + + export type _LeanDocument = { + [K in keyof T]: LeanDocumentElement; + }; + + // Keep this a separate type, to ensure that T is a naked type. + // This way, the conditional type is distributive over union types. + // This is required for PopulatedDoc. + type LeanDocumentElement = + T extends unknown[] ? LeanArray : // Array + T extends Document ? LeanDocument : // Subdocument + T; + + export type SchemaDefinitionType = T extends Document ? Omit> : T; + export type LeanDocument = Omit<_LeanDocument, Exclude | '$isSingleNested'>; + + export type LeanDocumentOrArray = 0 extends (1 & T) ? T : + T extends unknown[] ? LeanDocument[] : + T extends Document ? LeanDocument : + T; + + export type LeanDocumentOrArrayWithRawType = 0 extends (1 & T) ? T : + T extends unknown[] ? RawDocType[] : + T extends Document ? RawDocType : + T; + + class QueryCursor extends stream.Readable { + [Symbol.asyncIterator](): AsyncIterableIterator; + + /** + * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). + * Useful for setting the `noCursorTimeout` and `tailable` flags. + */ + addCursorFlag(flag: string, value: boolean): this; + + /** + * Marks this cursor as closed. Will stop streaming and subsequent calls to + * `next()` will error. + */ + close(): Promise; + close(callback: CallbackWithoutResult): void; + + /** + * Execute `fn` for every document(s) in the cursor. If batchSize is provided + * `fn` will be executed for each batch of documents. If `fn` returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + */ + eachAsync(fn: (doc: DocType) => any, options?: { parallel?: number }): Promise; + eachAsync(fn: (doc: DocType[]) => any, options: { parallel?: number, batchSize: number }): Promise; + eachAsync(fn: (doc: DocType) => any, options?: { parallel?: number, batchSize?: number }, cb?: CallbackWithoutResult): void; + eachAsync(fn: (doc: DocType[]) => any, options: { parallel?: number, batchSize: number }, cb?: CallbackWithoutResult): void; + + /** + * Registers a transform function which subsequently maps documents retrieved + * via the streams interface or `.next()` + */ + map(fn: (res: DocType) => ResultType): QueryCursor; + + /** + * Get the next document from this cursor. Will return `null` when there are + * no documents left. + */ + next(): Promise; + next(callback: Callback): void; + + options: any; + } + + class Aggregate { + /** + * Sets an option on this aggregation. This function will be deprecated in a + * future release. */ + addCursorFlag(flag: string, value: boolean): this; + + /** + * Appends a new $addFields operator to this aggregate pipeline. + * Requires MongoDB v3.4+ to work + */ + addFields(arg: any): this; + + /** Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) */ + allowDiskUse(value: boolean): this; + + /** Appends new operators to this aggregate pipeline */ + append(...args: any[]): this; + + /** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * Like [`.then()`](#query_Query-then), but only takes a rejection handler. + */ + catch: Promise['catch']; + + /** Adds a collation. */ + collation(options: mongodb.CollationOptions): this; + + /** Appends a new $count operator to this aggregate pipeline. */ + count(countName: string): this; + + /** + * Sets the cursor option for the aggregation query (ignored for < 2.6.0). + */ + cursor(options?: Record): AggregationCursor; + + /** Executes the aggregate pipeline on the currently bound Model. */ + exec(callback?: Callback): Promise; + + /** Execute the aggregation with explain */ + explain(callback?: Callback): Promise; + + /** Combines multiple aggregation pipelines. */ + facet(options: any): this; + + /** Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection. */ + graphLookup(options: any): this; + + /** Appends new custom $group operator to this aggregate pipeline. */ + group(arg: any): this; + + /** Sets the hint option for the aggregation query (ignored for < 3.6.0) */ + hint(value: Record | string): this; + + /** + * Appends a new $limit operator to this aggregate pipeline. + * @param num maximum number of records to pass to the next stage + */ + limit(num: number): this; + + /** Appends new custom $lookup operator to this aggregate pipeline. */ + lookup(options: any): this; + + /** + * Appends a new custom $match operator to this aggregate pipeline. + * @param arg $match operator contents + */ + match(arg: any): this; + + /** + * Binds this aggregate to a model. + * @param model the model to which the aggregate is to be bound + */ + model(model: any): this; + + /** + * Append a new $near operator to this aggregation pipeline + * @param arg $near operator contents + */ + near(arg: { near?: number[]; distanceField: string; maxDistance?: number; query?: Record; includeLocs?: string; num?: number; uniqueDocs?: boolean }): this; + + /** Returns the current pipeline */ + pipeline(): any[]; + + /** Appends a new $project operator to this aggregate pipeline. */ + project(arg: string | Object): this; + + /** Sets the readPreference option for the aggregation query. */ + read(pref: string | mongodb.ReadPreferenceMode, tags?: any[]): this; + + /** Sets the readConcern level for the aggregation query. */ + readConcern(level: string): this; + + /** Appends a new $redact operator to this aggregate pipeline. */ + redact(expression: any, thenExpr: string | any, elseExpr: string | any): this; + + /** Appends a new $replaceRoot operator to this aggregate pipeline. */ + replaceRoot(newRoot: object | string): this; + + /** + * Helper for [Atlas Text Search](https://docs.atlas.mongodb.com/reference/atlas-search/tutorial/)'s + * `$search` stage. + */ + search(options: any): this; + + /** Lets you set arbitrary options, for middleware or plugins. */ + option(value: Record): this; + + /** Appends new custom $sample operator to this aggregate pipeline. */ + sample(size: number): this; + + /** Sets the session for this aggregation. Useful for [transactions](/docs/transactions.html). */ + session(session: mongodb.ClientSession | null): this; + + /** + * Appends a new $skip operator to this aggregate pipeline. + * @param num number of records to skip before next stage + */ + skip(num: number): this; + + /** Appends a new $sort operator to this aggregate pipeline. */ + sort(arg: any): this; + + /** Provides promise for aggregate. */ + then: Promise['then']; + + /** + * Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name + * or a pipeline object. + */ + sortByCount(arg: string | any): this; + + /** Appends new custom $unwind operator(s) to this aggregate pipeline. */ + unwind(...args: any[]): this; + } + + class AggregationCursor extends stream.Readable { + /** + * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). + * Useful for setting the `noCursorTimeout` and `tailable` flags. + */ + addCursorFlag(flag: string, value: boolean): this; + + /** + * Marks this cursor as closed. Will stop streaming and subsequent calls to + * `next()` will error. + */ + close(): Promise; + close(callback: CallbackWithoutResult): void; + + /** + * Execute `fn` for every document(s) in the cursor. If batchSize is provided + * `fn` will be executed for each batch of documents. If `fn` returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + */ + eachAsync(fn: (doc: any) => any, options?: { parallel?: number, batchSize?: number }): Promise; + eachAsync(fn: (doc: any) => any, options?: { parallel?: number, batchSize?: number }, cb?: CallbackWithoutResult): void; + + /** + * Registers a transform function which subsequently maps documents retrieved + * via the streams interface or `.next()` + */ + map(fn: (res: any) => any): this; + + /** + * Get the next document from this cursor. Will return `null` when there are + * no documents left. + */ + next(): Promise; + next(callback: Callback): void; + } + + class SchemaType { + /** SchemaType constructor */ + constructor(path: string, options?: AnyObject, instance?: string); + + /** Get/set the function used to cast arbitrary values to this type. */ + static cast(caster?: Function | boolean): Function; + + static checkRequired(checkRequired?: (v: any) => boolean): (v: any) => boolean; + + /** Sets a default option for this schema type. */ + static set(option: string, value: any): void; + + /** Attaches a getter for all instances of this schema type. */ + static get(getter: (value: any) => any): void; + + /** The class that Mongoose uses internally to instantiate this SchemaType's `options` property. */ + OptionsConstructor: typeof SchemaTypeOptions; + + /** Cast `val` to this schema type. Each class that inherits from schema type should implement this function. */ + cast(val: any, doc: Document, init: boolean, prev?: any, options?: any): any; + + /** Sets a default value for this SchemaType. */ + default(val: any): any; + + /** Adds a getter to this schematype. */ + get(fn: Function): this; + + /** + * Defines this path as immutable. Mongoose prevents you from changing + * immutable paths unless the parent document has [`isNew: true`](/docs/api.html#document_Document-isNew). + */ + immutable(bool: boolean): this; + + /** Declares the index options for this schematype. */ + index(options: any): this; + + /** String representation of what type this is, like 'ObjectID' or 'Number' */ + instance: string; + + /** The options this SchemaType was instantiated with */ + options: AnyObject; + + /** + * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html) + * looks at to determine the foreign collection it should query. + */ + ref(ref: string | boolean | Model): this; + + /** + * Adds a required validator to this SchemaType. The validator gets added + * to the front of this SchemaType's validators array using unshift(). + */ + required(required: boolean, message?: string): this; + + /** The schema this SchemaType instance is part of */ + schema: Schema; + + /** Sets default select() behavior for this path. */ + select(val: boolean): this; + + /** Adds a setter to this schematype. */ + set(fn: Function): this; + + /** Declares a sparse index. */ + sparse(bool: boolean): this; + + /** Declares a full text index. */ + text(bool: boolean): this; + + /** Defines a custom function for transforming this path when converting a document to JSON. */ + transform(fn: (value: any) => any): this; + + /** Declares an unique index. */ + unique(bool: boolean): this; + + /** Adds validator(s) for this document path. */ + validate(obj: RegExp | Function | any, errorMsg?: string, + type?: string): this; + } + + type Callback = (error: CallbackError, result: T) => void; + + type CallbackWithoutResult = (error: CallbackError) => void; + + class NativeError extends global.Error { } + type CallbackError = NativeError | null; + + class Error extends global.Error { + constructor(msg: string); + + /** The type of error. "MongooseError" for generic errors. */ + name: string; + + static messages: any; + + static Messages: any; + } + + namespace Error { + export class CastError extends Error { + name: 'CastError'; + stringValue: string; + kind: string; + value: any; + path: string; + reason?: NativeError | null; + model?: any; + + constructor(type: string, value: any, path: string, reason?: NativeError, schemaType?: SchemaType); + } + + export class DisconnectedError extends Error { + name: 'DisconnectedError'; + } + + export class DivergentArrayError extends Error { + name: 'DivergentArrayError'; + } + + export class MissingSchemaError extends Error { + name: 'MissingSchemaError'; + } + + export class DocumentNotFoundError extends Error { + name: 'DocumentNotFoundError'; + result: any; + numAffected: number; + filter: any; + query: any; + } + + export class ObjectExpectedError extends Error { + name: 'ObjectExpectedError'; + path: string; + } + + export class ObjectParameterError extends Error { + name: 'ObjectParameterError'; + } + + export class OverwriteModelError extends Error { + name: 'OverwriteModelError'; + } + + export class ParallelSaveError extends Error { + name: 'ParallelSaveError'; + } + + export class ParallelValidateError extends Error { + name: 'ParallelValidateError'; + } + + export class MongooseServerSelectionError extends Error { + name: 'MongooseServerSelectionError'; + } + + export class StrictModeError extends Error { + name: 'StrictModeError'; + isImmutableError: boolean; + path: string; + } + + export class ValidationError extends Error { + name: 'ValidationError'; + + errors: { [path: string]: ValidatorError | CastError | ValidationError }; + addError: (path: string, error: ValidatorError | CastError | ValidationError) => void; + + constructor(instance?: Error); + } + + export class ValidatorError extends Error { + name: 'ValidatorError'; + properties: { + message: string, + type?: string, + path?: string, + value?: any, + reason?: any + }; + kind: string; + path: string; + value: any; + reason?: Error | null; + + constructor(properties: { + message?: string, + type?: string, + path?: string, + value?: any, + reason?: any + }); + } + + export class VersionError extends Error { + name: 'VersionError'; + version: number; + modifiedPaths: Array; + + constructor(doc: Document, currentVersion: number, modifiedPaths: Array); + } + } + + /* for ts-mongoose */ + class mquery {} +} diff --git a/node_modules/mongoose/index.js b/node_modules/mongoose/index.js new file mode 100644 index 0000000..a938b44 --- /dev/null +++ b/node_modules/mongoose/index.js @@ -0,0 +1,9 @@ + +/** + * Export lib/mongoose + * + */ + +'use strict'; + +module.exports = require('./lib/'); diff --git a/node_modules/mongoose/lib/aggregate.js b/node_modules/mongoose/lib/aggregate.js new file mode 100644 index 0000000..aa07bc5 --- /dev/null +++ b/node_modules/mongoose/lib/aggregate.js @@ -0,0 +1,1141 @@ +'use strict'; + +/*! + * Module dependencies + */ + +const AggregationCursor = require('./cursor/AggregationCursor'); +const Query = require('./query'); +const applyGlobalMaxTimeMS = require('./helpers/query/applyGlobalMaxTimeMS'); +const getConstructorName = require('./helpers/getConstructorName'); +const promiseOrCallback = require('./helpers/promiseOrCallback'); +const stringifyFunctionOperators = require('./helpers/aggregate/stringifyFunctionOperators'); +const util = require('util'); +const utils = require('./utils'); +const read = Query.prototype.read; +const readConcern = Query.prototype.readConcern; + +/** + * Aggregate constructor used for building aggregation pipelines. Do not + * instantiate this class directly, use [Model.aggregate()](/docs/api.html#model_Model.aggregate) instead. + * + * ####Example: + * + * const aggregate = Model.aggregate([ + * { $project: { a: 1, b: 1 } }, + * { $skip: 5 } + * ]); + * + * Model. + * aggregate([{ $match: { age: { $gte: 21 }}}]). + * unwind('tags'). + * exec(callback); + * + * ####Note: + * + * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). + * - Mongoose does **not** cast pipeline stages. The below will **not** work unless `_id` is a string in the database + * + * ```javascript + * new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]); + * // Do this instead to cast to an ObjectId + * new Aggregate([{ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }]); + * ``` + * + * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ + * @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate + * @param {Array} [pipeline] aggregation pipeline as an array of objects + * @param {Model} [model] the model to use with this aggregate. + * @api public + */ + +function Aggregate(pipeline, model) { + this._pipeline = []; + this._model = model; + this.options = {}; + + if (arguments.length === 1 && util.isArray(pipeline)) { + this.append.apply(this, pipeline); + } +} + +/** + * Contains options passed down to the [aggregate command](https://docs.mongodb.com/manual/reference/command/aggregate/). + * Supported options are: + * + * - `readPreference` + * - [`cursor`](./api.html#aggregate_Aggregate-cursor) + * - [`explain`](./api.html#aggregate_Aggregate-explain) + * - [`allowDiskUse`](./api.html#aggregate_Aggregate-allowDiskUse) + * - `maxTimeMS` + * - `bypassDocumentValidation` + * - `raw` + * - `promoteLongs` + * - `promoteValues` + * - `promoteBuffers` + * - [`collation`](./api.html#aggregate_Aggregate-collation) + * - `comment` + * - [`session`](./api.html#aggregate_Aggregate-session) + * + * @property options + * @memberOf Aggregate + * @api public + */ + +Aggregate.prototype.options; + +/** + * Get/set the model that this aggregation will execute on. + * + * ####Example: + * const aggregate = MyModel.aggregate([{ $match: { answer: 42 } }]); + * aggregate.model() === MyModel; // true + * + * // Change the model. There's rarely any reason to do this. + * aggregate.model(SomeOtherModel); + * aggregate.model() === SomeOtherModel; // true + * + * @param {Model} [model] set the model associated with this aggregate. + * @return {Model} + * @api public + */ + +Aggregate.prototype.model = function(model) { + if (arguments.length === 0) { + return this._model; + } + + this._model = model; + if (model.schema != null) { + if (this.options.readPreference == null && + model.schema.options.read != null) { + this.options.readPreference = model.schema.options.read; + } + if (this.options.collation == null && + model.schema.options.collation != null) { + this.options.collation = model.schema.options.collation; + } + } + + return model; +}; + +/** + * Appends new operators to this aggregate pipeline + * + * ####Examples: + * + * aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); + * + * // or pass an array + * const pipeline = [{ $match: { daw: 'Logic Audio X' }} ]; + * aggregate.append(pipeline); + * + * @param {Object} ops operator(s) to append + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.append = function() { + const args = (arguments.length === 1 && util.isArray(arguments[0])) + ? arguments[0] + : utils.args(arguments); + + if (!args.every(isOperator)) { + throw new Error('Arguments must be aggregate pipeline operators'); + } + + this._pipeline = this._pipeline.concat(args); + + return this; +}; + +/** + * Appends a new $addFields operator to this aggregate pipeline. + * Requires MongoDB v3.4+ to work + * + * ####Examples: + * + * // adding new fields based on existing fields + * aggregate.addFields({ + * newField: '$b.nested' + * , plusTen: { $add: ['$val', 10]} + * , sub: { + * name: '$a' + * } + * }) + * + * // etc + * aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } }); + * + * @param {Object} arg field specification + * @see $addFields https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/ + * @return {Aggregate} + * @api public + */ +Aggregate.prototype.addFields = function(arg) { + const fields = {}; + if (typeof arg === 'object' && !util.isArray(arg)) { + Object.keys(arg).forEach(function(field) { + fields[field] = arg[field]; + }); + } else { + throw new Error('Invalid addFields() argument. Must be an object'); + } + return this.append({ $addFields: fields }); +}; + +/** + * Appends a new $project operator to this aggregate pipeline. + * + * Mongoose query [selection syntax](#query_Query-select) is also supported. + * + * ####Examples: + * + * // include a, include b, exclude _id + * aggregate.project("a b -_id"); + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * aggregate.project({a: 1, b: 1, _id: 0}); + * + * // reshaping documents + * aggregate.project({ + * newField: '$b.nested' + * , plusTen: { $add: ['$val', 10]} + * , sub: { + * name: '$a' + * } + * }) + * + * // etc + * aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); + * + * @param {Object|String} arg field specification + * @see projection http://docs.mongodb.org/manual/reference/aggregation/project/ + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.project = function(arg) { + const fields = {}; + + if (typeof arg === 'object' && !util.isArray(arg)) { + Object.keys(arg).forEach(function(field) { + fields[field] = arg[field]; + }); + } else if (arguments.length === 1 && typeof arg === 'string') { + arg.split(/\s+/).forEach(function(field) { + if (!field) { + return; + } + const include = field[0] === '-' ? 0 : 1; + if (include === 0) { + field = field.substring(1); + } + fields[field] = include; + }); + } else { + throw new Error('Invalid project() argument. Must be string or object'); + } + + return this.append({ $project: fields }); +}; + +/** + * Appends a new custom $group operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.group({ _id: "$department" }); + * + * @see $group http://docs.mongodb.org/manual/reference/aggregation/group/ + * @method group + * @memberOf Aggregate + * @instance + * @param {Object} arg $group operator contents + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new custom $match operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.match({ department: { $in: [ "sales", "engineering" ] } }); + * + * @see $match http://docs.mongodb.org/manual/reference/aggregation/match/ + * @method match + * @memberOf Aggregate + * @instance + * @param {Object} arg $match operator contents + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new $skip operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.skip(10); + * + * @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/ + * @method skip + * @memberOf Aggregate + * @instance + * @param {Number} num number of records to skip before next stage + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new $limit operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.limit(10); + * + * @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/ + * @method limit + * @memberOf Aggregate + * @instance + * @param {Number} num maximum number of records to pass to the next stage + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new $geoNear operator to this aggregate pipeline. + * + * ####NOTE: + * + * **MUST** be used as the first operator in the pipeline. + * + * ####Examples: + * + * aggregate.near({ + * near: [40.724, -73.997], + * distanceField: "dist.calculated", // required + * maxDistance: 0.008, + * query: { type: "public" }, + * includeLocs: "dist.location", + * uniqueDocs: true, + * num: 5 + * }); + * + * @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/ + * @method near + * @memberOf Aggregate + * @instance + * @param {Object} arg + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.near = function(arg) { + const op = {}; + op.$geoNear = arg; + return this.append(op); +}; + +/*! + * define methods + */ + +'group match skip limit out'.split(' ').forEach(function($operator) { + Aggregate.prototype[$operator] = function(arg) { + const op = {}; + op['$' + $operator] = arg; + return this.append(op); + }; +}); + +/** + * Appends new custom $unwind operator(s) to this aggregate pipeline. + * + * Note that the `$unwind` operator requires the path name to start with '$'. + * Mongoose will prepend '$' if the specified field doesn't start '$'. + * + * ####Examples: + * + * aggregate.unwind("tags"); + * aggregate.unwind("a", "b", "c"); + * aggregate.unwind({ path: '$tags', preserveNullAndEmptyArrays: true }); + * + * @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/ + * @param {String|Object} fields the field(s) to unwind, either as field names or as [objects with options](https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#document-operand-with-options). If passing a string, prefixing the field name with '$' is optional. If passing an object, `path` must start with '$'. + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.unwind = function() { + const args = utils.args(arguments); + + const res = []; + for (const arg of args) { + if (arg && typeof arg === 'object') { + res.push({ $unwind: arg }); + } else if (typeof arg === 'string') { + res.push({ + $unwind: (arg && arg.startsWith('$')) ? arg : '$' + arg + }); + } else { + throw new Error('Invalid arg "' + arg + '" to unwind(), ' + + 'must be string or object'); + } + } + + return this.append.apply(this, res); +}; + +/** + * Appends a new $replaceRoot operator to this aggregate pipeline. + * + * Note that the `$replaceRoot` operator requires field strings to start with '$'. + * If you are passing in a string Mongoose will prepend '$' if the specified field doesn't start '$'. + * If you are passing in an object the strings in your expression will not be altered. + * + * ####Examples: + * + * aggregate.replaceRoot("user"); + * + * aggregate.replaceRoot({ x: { $concat: ['$this', '$that'] } }); + * + * @see $replaceRoot https://docs.mongodb.org/manual/reference/operator/aggregation/replaceRoot + * @param {String|Object} the field or document which will become the new root document + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.replaceRoot = function(newRoot) { + let ret; + + if (typeof newRoot === 'string') { + ret = newRoot.startsWith('$') ? newRoot : '$' + newRoot; + } else { + ret = newRoot; + } + + return this.append({ + $replaceRoot: { + newRoot: ret + } + }); +}; + +/** + * Appends a new $count operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.count("userCount"); + * + * @see $count https://docs.mongodb.org/manual/reference/operator/aggregation/count + * @param {String} the name of the count field + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.count = function(countName) { + return this.append({ $count: countName }); +}; + +/** + * Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name + * or a pipeline object. + * + * Note that the `$sortByCount` operator requires the new root to start with '$'. + * Mongoose will prepend '$' if the specified field name doesn't start with '$'. + * + * ####Examples: + * + * aggregate.sortByCount('users'); + * aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] }) + * + * @see $sortByCount https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/ + * @param {Object|String} arg + * @return {Aggregate} this + * @api public + */ + +Aggregate.prototype.sortByCount = function(arg) { + if (arg && typeof arg === 'object') { + return this.append({ $sortByCount: arg }); + } else if (typeof arg === 'string') { + return this.append({ + $sortByCount: (arg && arg.startsWith('$')) ? arg : '$' + arg + }); + } else { + throw new TypeError('Invalid arg "' + arg + '" to sortByCount(), ' + + 'must be string or object'); + } +}; + +/** + * Appends new custom $lookup operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' }); + * + * @see $lookup https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/#pipe._S_lookup + * @param {Object} options to $lookup as described in the above link + * @return {Aggregate}* @api public + */ + +Aggregate.prototype.lookup = function(options) { + return this.append({ $lookup: options }); +}; + +/** + * Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection. + * + * Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if `{ allowDiskUse: true }` is specified. + * + * #### Examples: + * // Suppose we have a collection of courses, where a document might look like `{ _id: 0, name: 'Calculus', prerequisite: 'Trigonometry'}` and `{ _id: 0, name: 'Trigonometry', prerequisite: 'Algebra' }` + * aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites + * + * @see $graphLookup https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/#pipe._S_graphLookup + * @param {Object} options to $graphLookup as described in the above link + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.graphLookup = function(options) { + const cloneOptions = {}; + if (options) { + if (!utils.isObject(options)) { + throw new TypeError('Invalid graphLookup() argument. Must be an object.'); + } + + utils.mergeClone(cloneOptions, options); + const startWith = cloneOptions.startWith; + + if (startWith && typeof startWith === 'string') { + cloneOptions.startWith = cloneOptions.startWith.startsWith('$') ? + cloneOptions.startWith : + '$' + cloneOptions.startWith; + } + + } + return this.append({ $graphLookup: cloneOptions }); +}; + +/** + * Appends new custom $sample operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.sample(3); // Add a pipeline that picks 3 random documents + * + * @see $sample https://docs.mongodb.org/manual/reference/operator/aggregation/sample/#pipe._S_sample + * @param {Number} size number of random documents to pick + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.sample = function(size) { + return this.append({ $sample: { size: size } }); +}; + +/** + * Appends a new $sort operator to this aggregate pipeline. + * + * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + * + * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + * + * ####Examples: + * + * // these are equivalent + * aggregate.sort({ field: 'asc', test: -1 }); + * aggregate.sort('field -test'); + * + * @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/ + * @param {Object|String} arg + * @return {Aggregate} this + * @api public + */ + +Aggregate.prototype.sort = function(arg) { + // TODO refactor to reuse the query builder logic + + const sort = {}; + + if (getConstructorName(arg) === 'Object') { + const desc = ['desc', 'descending', -1]; + Object.keys(arg).forEach(function(field) { + // If sorting by text score, skip coercing into 1/-1 + if (arg[field] instanceof Object && arg[field].$meta) { + sort[field] = arg[field]; + return; + } + sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1; + }); + } else if (arguments.length === 1 && typeof arg === 'string') { + arg.split(/\s+/).forEach(function(field) { + if (!field) { + return; + } + const ascend = field[0] === '-' ? -1 : 1; + if (ascend === -1) { + field = field.substring(1); + } + sort[field] = ascend; + }); + } else { + throw new TypeError('Invalid sort() argument. Must be a string or object.'); + } + + return this.append({ $sort: sort }); +}; + +/** + * Sets the readPreference option for the aggregation query. + * + * ####Example: + * + * Model.aggregate(..).read('primaryPreferred').exec(callback) + * + * @param {String} pref one of the listed preference options or their aliases + * @param {Array} [tags] optional tags for this query + * @return {Aggregate} this + * @api public + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + */ + +Aggregate.prototype.read = function(pref, tags) { + if (!this.options) { + this.options = {}; + } + read.call(this, pref, tags); + return this; +}; + +/** + * Sets the readConcern level for the aggregation query. + * + * ####Example: + * + * Model.aggregate(..).readConcern('majority').exec(callback) + * + * @param {String} level one of the listed read concern level or their aliases + * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ + * @return {Aggregate} this + * @api public + */ + +Aggregate.prototype.readConcern = function(level) { + if (!this.options) { + this.options = {}; + } + readConcern.call(this, level); + return this; +}; + +/** + * Appends a new $redact operator to this aggregate pipeline. + * + * If 3 arguments are supplied, Mongoose will wrap them with if-then-else of $cond operator respectively + * If `thenExpr` or `elseExpr` is string, make sure it starts with $$, like `$$DESCEND`, `$$PRUNE` or `$$KEEP`. + * + * ####Example: + * + * Model.aggregate(...) + * .redact({ + * $cond: { + * if: { $eq: [ '$level', 5 ] }, + * then: '$$PRUNE', + * else: '$$DESCEND' + * } + * }) + * .exec(); + * + * // $redact often comes with $cond operator, you can also use the following syntax provided by mongoose + * Model.aggregate(...) + * .redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND') + * .exec(); + * + * @param {Object} expression redact options or conditional expression + * @param {String|Object} [thenExpr] true case for the condition + * @param {String|Object} [elseExpr] false case for the condition + * @return {Aggregate} this + * @see $redact https://docs.mongodb.com/manual/reference/operator/aggregation/redact/ + * @api public + */ + +Aggregate.prototype.redact = function(expression, thenExpr, elseExpr) { + if (arguments.length === 3) { + if ((typeof thenExpr === 'string' && !thenExpr.startsWith('$$')) || + (typeof elseExpr === 'string' && !elseExpr.startsWith('$$'))) { + throw new Error('If thenExpr or elseExpr is string, it must start with $$. e.g. $$DESCEND, $$PRUNE, $$KEEP'); + } + + expression = { + $cond: { + if: expression, + then: thenExpr, + else: elseExpr + } + }; + } else if (arguments.length !== 1) { + throw new TypeError('Invalid arguments'); + } + + return this.append({ $redact: expression }); +}; + +/** + * Execute the aggregation with explain + * + * ####Example: + * + * Model.aggregate(..).explain(callback) + * + * @param {Function} callback + * @return {Promise} + */ + +Aggregate.prototype.explain = function(callback) { + const model = this._model; + + return promiseOrCallback(callback, cb => { + if (!this._pipeline.length) { + const err = new Error('Aggregate has empty pipeline'); + return cb(err); + } + + prepareDiscriminatorPipeline(this); + + model.hooks.execPre('aggregate', this, error => { + if (error) { + const _opts = { error: error }; + return model.hooks.execPost('aggregate', this, [null], _opts, error => { + cb(error); + }); + } + + this.options.explain = true; + + model.collection.aggregate(this._pipeline, this.options, (error, cursor) => { + if (error != null) { + const _opts = { error: error }; + return model.hooks.execPost('aggregate', this, [null], _opts, error => { + cb(error); + }); + } + cursor.explain((error, result) => { + const _opts = { error: error }; + return model.hooks.execPost('aggregate', this, [result], _opts, error => { + if (error) { + return cb(error); + } + return cb(null, result); + }); + }); + }); + }); + }, model.events); +}; + +/** + * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) + * + * ####Example: + * + * await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true); + * + * @param {Boolean} value Should tell server it can use hard drive to store data during aggregation. + * @param {Array} [tags] optional tags for this query + * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ + */ + +Aggregate.prototype.allowDiskUse = function(value) { + this.options.allowDiskUse = value; + return this; +}; + +/** + * Sets the hint option for the aggregation query (ignored for < 3.6.0) + * + * ####Example: + * + * Model.aggregate(..).hint({ qty: 1, category: 1 }).exec(callback) + * + * @param {Object|String} value a hint object or the index name + * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ + */ + +Aggregate.prototype.hint = function(value) { + this.options.hint = value; + return this; +}; + +/** + * Sets the session for this aggregation. Useful for [transactions](/docs/transactions.html). + * + * ####Example: + * + * const session = await Model.startSession(); + * await Model.aggregate(..).session(session); + * + * @param {ClientSession} session + * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ + */ + +Aggregate.prototype.session = function(session) { + if (session == null) { + delete this.options.session; + } else { + this.options.session = session; + } + return this; +}; + +/** + * Lets you set arbitrary options, for middleware or plugins. + * + * ####Example: + * + * const agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option + * agg.options; // `{ allowDiskUse: true }` + * + * @param {Object} options keys to merge into current options + * @param [options.maxTimeMS] number limits the time this aggregation will run, see [MongoDB docs on `maxTimeMS`](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) + * @param [options.allowDiskUse] boolean if true, the MongoDB server will use the hard drive to store data during this aggregation + * @param [options.collation] object see [`Aggregate.prototype.collation()`](./docs/api.html#aggregate_Aggregate-collation) + * @param [options.session] ClientSession see [`Aggregate.prototype.session()`](./docs/api.html#aggregate_Aggregate-session) + * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ + * @return {Aggregate} this + * @api public + */ + +Aggregate.prototype.option = function(value) { + for (const key in value) { + this.options[key] = value[key]; + } + return this; +}; + +/** + * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). + * Note the different syntax below: .exec() returns a cursor object, and no callback + * is necessary. + * + * ####Example: + * + * const cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec(); + * cursor.eachAsync(function(doc, i) { + * // use doc + * }); + * + * @param {Object} options + * @param {Number} options.batchSize set the cursor batch size + * @param {Boolean} [options.useMongooseAggCursor] use experimental mongoose-specific aggregation cursor (for `eachAsync()` and other query cursor semantics) + * @return {Aggregate} this + * @api public + * @see mongodb http://mongodb.github.io/node-mongodb-native/2.0/api/AggregationCursor.html + */ + +Aggregate.prototype.cursor = function(options) { + if (!this.options) { + this.options = {}; + } + this.options.cursor = options || {}; + return new AggregationCursor(this); // return this; +}; + +/** + * Adds a collation + * + * ####Example: + * + * Model.aggregate(..).collation({ locale: 'en_US', strength: 1 }).exec(); + * + * @param {Object} collation options + * @return {Aggregate} this + * @api public + * @see mongodb http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#aggregate + */ + +Aggregate.prototype.collation = function(collation) { + if (!this.options) { + this.options = {}; + } + this.options.collation = collation; + return this; +}; + +/** + * Combines multiple aggregation pipelines. + * + * ####Example: + * + * Model.aggregate(...) + * .facet({ + * books: [{ groupBy: '$author' }], + * price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }] + * }) + * .exec(); + * + * // Output: { books: [...], price: [{...}, {...}] } + * + * @param {Object} facet options + * @return {Aggregate} this + * @see $facet https://docs.mongodb.com/v3.4/reference/operator/aggregation/facet/ + * @api public + */ + +Aggregate.prototype.facet = function(options) { + return this.append({ $facet: options }); +}; + +/** + * Helper for [Atlas Text Search](https://docs.atlas.mongodb.com/reference/atlas-search/tutorial/)'s + * `$search` stage. + * + * ####Example: + * + * Model.aggregate(). + * search({ + * text: { + * query: 'baseball', + * path: 'plot' + * } + * }); + * + * // Output: [{ plot: '...', title: '...' }] + * + * @param {Object} $search options + * @return {Aggregate} this + * @see $search https://docs.atlas.mongodb.com/reference/atlas-search/tutorial/ + * @api public + */ + +Aggregate.prototype.search = function(options) { + return this.append({ $search: options }); +}; + +/** + * Returns the current pipeline + * + * ####Example: + * + * MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }] + * + * @return {Array} + * @api public + */ + + +Aggregate.prototype.pipeline = function() { + return this._pipeline; +}; + +/** + * Executes the aggregate pipeline on the currently bound Model. + * + * ####Example: + * + * aggregate.exec(callback); + * + * // Because a promise is returned, the `callback` is optional. + * const promise = aggregate.exec(); + * promise.then(..); + * + * @see Promise #promise_Promise + * @param {Function} [callback] + * @return {Promise} + * @api public + */ + +Aggregate.prototype.exec = function(callback) { + if (!this._model) { + throw new Error('Aggregate not bound to any Model'); + } + const model = this._model; + const collection = this._model.collection; + + applyGlobalMaxTimeMS(this.options, model); + + if (this.options && this.options.cursor) { + return new AggregationCursor(this); + } + + return promiseOrCallback(callback, cb => { + prepareDiscriminatorPipeline(this); + stringifyFunctionOperators(this._pipeline); + + model.hooks.execPre('aggregate', this, error => { + if (error) { + const _opts = { error: error }; + return model.hooks.execPost('aggregate', this, [null], _opts, error => { + cb(error); + }); + } + if (!this._pipeline.length) { + return cb(new Error('Aggregate has empty pipeline')); + } + + const options = utils.clone(this.options || {}); + + collection.aggregate(this._pipeline, options, (err, cursor) => { + if (err != null) { + return cb(err); + } + + cursor.toArray((error, result) => { + const _opts = { error: error }; + model.hooks.execPost('aggregate', this, [result], _opts, (error, result) => { + if (error) { + return cb(error); + } + + cb(null, result); + }); + }); + }); + }); + }, model.events); +}; + +/** + * Provides promise for aggregate. + * + * ####Example: + * + * Model.aggregate(..).then(successCallback, errorCallback); + * + * @see Promise #promise_Promise + * @param {Function} [resolve] successCallback + * @param {Function} [reject] errorCallback + * @return {Promise} + */ +Aggregate.prototype.then = function(resolve, reject) { + return this.exec().then(resolve, reject); +}; + +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * Like [`.then()`](#query_Query-then), but only takes a rejection handler. + * + * @param {Function} [reject] + * @return {Promise} + * @api public + */ + +Aggregate.prototype.catch = function(reject) { + return this.exec().then(null, reject); +}; + +/** + * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js + * You do not need to call this function explicitly, the JavaScript runtime + * will call it for you. + * + * ####Example + * + * const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]); + * for await (const doc of agg) { + * console.log(doc.name); + * } + * + * Node.js 10.x supports async iterators natively without any flags. You can + * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). + * + * **Note:** This function is not set if `Symbol.asyncIterator` is undefined. If + * `Symbol.asyncIterator` is undefined, that means your Node.js version does not + * support async iterators. + * + * @method Symbol.asyncIterator + * @memberOf Aggregate + * @instance + * @api public + */ + +if (Symbol.asyncIterator != null) { + Aggregate.prototype[Symbol.asyncIterator] = function() { + return this.cursor({ useMongooseAggCursor: true }). + transformNull(). + _transformForAsyncIterator(); + }; +} + +/*! + * Helpers + */ + +/** + * Checks whether an object is likely a pipeline operator + * + * @param {Object} obj object to check + * @return {Boolean} + * @api private + */ + +function isOperator(obj) { + if (typeof obj !== 'object') { + return false; + } + + const k = Object.keys(obj); + + return k.length === 1 && k.some(key => { return key[0] === '$'; }); +} + +/*! + * Adds the appropriate `$match` pipeline step to the top of an aggregate's + * pipeline, should it's model is a non-root discriminator type. This is + * analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`. + * + * @param {Aggregate} aggregate Aggregate to prepare + */ + +Aggregate._prepareDiscriminatorPipeline = prepareDiscriminatorPipeline; + +function prepareDiscriminatorPipeline(aggregate) { + const schema = aggregate._model.schema; + const discriminatorMapping = schema && schema.discriminatorMapping; + + if (discriminatorMapping && !discriminatorMapping.isRoot) { + const originalPipeline = aggregate._pipeline; + const discriminatorKey = discriminatorMapping.key; + const discriminatorValue = discriminatorMapping.value; + + // If the first pipeline stage is a match and it doesn't specify a `__t` + // key, add the discriminator key to it. This allows for potential + // aggregation query optimizations not to be disturbed by this feature. + if (originalPipeline[0] != null && originalPipeline[0].$match && !originalPipeline[0].$match[discriminatorKey]) { + originalPipeline[0].$match[discriminatorKey] = discriminatorValue; + // `originalPipeline` is a ref, so there's no need for + // aggregate._pipeline = originalPipeline + } else if (originalPipeline[0] != null && originalPipeline[0].$geoNear) { + originalPipeline[0].$geoNear.query = + originalPipeline[0].$geoNear.query || {}; + originalPipeline[0].$geoNear.query[discriminatorKey] = discriminatorValue; + } else if (originalPipeline[0] != null && originalPipeline[0].$search) { + if (originalPipeline[1] && originalPipeline[1].$match != null) { + originalPipeline[1].$match[discriminatorKey] = originalPipeline[1].$match[discriminatorKey] || discriminatorValue; + } else { + const match = {}; + match[discriminatorKey] = discriminatorValue; + originalPipeline.splice(1, 0, { $match: match }); + } + } else { + const match = {}; + match[discriminatorKey] = discriminatorValue; + aggregate._pipeline.unshift({ $match: match }); + } + } +} + +/*! + * Exports + */ + +module.exports = Aggregate; diff --git a/node_modules/mongoose/lib/browser.js b/node_modules/mongoose/lib/browser.js new file mode 100644 index 0000000..f71a479 --- /dev/null +++ b/node_modules/mongoose/lib/browser.js @@ -0,0 +1,158 @@ +/* eslint-env browser */ + +'use strict'; + +require('./driver').set(require('./drivers/browser')); + +const DocumentProvider = require('./document_provider.js'); +const PromiseProvider = require('./promise_provider'); + +DocumentProvider.setBrowser(true); + +/** + * The Mongoose [Promise](#promise_Promise) constructor. + * + * @method Promise + * @api public + */ + +Object.defineProperty(exports, 'Promise', { + get: function() { + return PromiseProvider.get(); + }, + set: function(lib) { + PromiseProvider.set(lib); + } +}); + +/** + * Storage layer for mongoose promises + * + * @method PromiseProvider + * @api public + */ + +exports.PromiseProvider = PromiseProvider; + +/** + * The [MongooseError](#error_MongooseError) constructor. + * + * @method Error + * @api public + */ + +exports.Error = require('./error/index'); + +/** + * The Mongoose [Schema](#schema_Schema) constructor + * + * ####Example: + * + * const mongoose = require('mongoose'); + * const Schema = mongoose.Schema; + * const CatSchema = new Schema(..); + * + * @method Schema + * @api public + */ + +exports.Schema = require('./schema'); + +/** + * The various Mongoose Types. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * const array = mongoose.Types.Array; + * + * ####Types: + * + * - [Array](/docs/schematypes.html#arrays) + * - [Buffer](/docs/schematypes.html#buffers) + * - [Embedded](/docs/schematypes.html#schemas) + * - [DocumentArray](/docs/api/documentarraypath.html) + * - [Decimal128](/docs/api.html#mongoose_Mongoose-Decimal128) + * - [ObjectId](/docs/schematypes.html#objectids) + * - [Map](/docs/schematypes.html#maps) + * - [Subdocument](/docs/schematypes.html#schemas) + * + * Using this exposed access to the `ObjectId` type, we can construct ids on demand. + * + * const ObjectId = mongoose.Types.ObjectId; + * const id1 = new ObjectId; + * + * @property Types + * @api public + */ +exports.Types = require('./types'); + +/** + * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor + * + * @method VirtualType + * @api public + */ +exports.VirtualType = require('./virtualtype'); + +/** + * The various Mongoose SchemaTypes. + * + * ####Note: + * + * _Alias of mongoose.Schema.Types for backwards compatibility._ + * + * @property SchemaTypes + * @see Schema.SchemaTypes #schema_Schema.Types + * @api public + */ + +exports.SchemaType = require('./schematype.js'); + +/** + * Internal utils + * + * @property utils + * @api private + */ + +exports.utils = require('./utils.js'); + +/** + * The Mongoose browser [Document](/api/document.html) constructor. + * + * @method Document + * @api public + */ +exports.Document = DocumentProvider(); + +/** + * Return a new browser model. In the browser, a model is just + * a simplified document with a schema - it does **not** have + * functions like `findOne()`, etc. + * + * @method model + * @api public + * @param {String} name + * @param {Schema} schema + * @return Class + */ +exports.model = function(name, schema) { + class Model extends exports.Document { + constructor(obj, fields) { + super(obj, schema, fields); + } + } + Model.modelName = name; + + return Model; +}; + +/*! + * Module exports. + */ + +if (typeof window !== 'undefined') { + window.mongoose = module.exports; + window.Buffer = Buffer; +} diff --git a/node_modules/mongoose/lib/browserDocument.js b/node_modules/mongoose/lib/browserDocument.js new file mode 100644 index 0000000..a44f307 --- /dev/null +++ b/node_modules/mongoose/lib/browserDocument.js @@ -0,0 +1,100 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const NodeJSDocument = require('./document'); +const EventEmitter = require('events').EventEmitter; +const MongooseError = require('./error/index'); +const Schema = require('./schema'); +const ObjectId = require('./types/objectid'); +const ValidationError = MongooseError.ValidationError; +const applyHooks = require('./helpers/model/applyHooks'); +const isObject = require('./helpers/isObject'); + +/** + * Document constructor. + * + * @param {Object} obj the values to set + * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data + * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose. + * @event `save`: Emitted when the document is successfully saved + * @api private + */ + +function Document(obj, schema, fields, skipId, skipInit) { + if (!(this instanceof Document)) { + return new Document(obj, schema, fields, skipId, skipInit); + } + + if (isObject(schema) && !schema.instanceOfSchema) { + schema = new Schema(schema); + } + + // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id + schema = this.schema || schema; + + // Generate ObjectId if it is missing, but it requires a scheme + if (!this.schema && schema.options._id) { + obj = obj || {}; + + if (obj._id === undefined) { + obj._id = new ObjectId(); + } + } + + if (!schema) { + throw new MongooseError.MissingSchemaError(); + } + + this.$__setSchema(schema); + + NodeJSDocument.call(this, obj, fields, skipId, skipInit); + + applyHooks(this, schema, { decorateDoc: true }); + + // apply methods + for (const m in schema.methods) { + this[m] = schema.methods[m]; + } + // apply statics + for (const s in schema.statics) { + this[s] = schema.statics[s]; + } +} + +/*! + * Inherit from the NodeJS document + */ + +Document.prototype = Object.create(NodeJSDocument.prototype); +Document.prototype.constructor = Document; + +/*! + * ignore + */ + +Document.events = new EventEmitter(); + +/*! + * Browser doc exposes the event emitter API + */ + +Document.$emitter = new EventEmitter(); + +['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', + 'removeAllListeners', 'addListener'].forEach(function(emitterFn) { + Document[emitterFn] = function() { + return Document.$emitter[emitterFn].apply(Document.$emitter, arguments); + }; +}); + +/*! + * Module exports. + */ + +Document.ValidationError = ValidationError; +module.exports = exports = Document; diff --git a/node_modules/mongoose/lib/cast.js b/node_modules/mongoose/lib/cast.js new file mode 100644 index 0000000..cb99ed6 --- /dev/null +++ b/node_modules/mongoose/lib/cast.js @@ -0,0 +1,369 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const CastError = require('./error/cast'); +const StrictModeError = require('./error/strict'); +const Types = require('./schema/index'); +const castTextSearch = require('./schema/operators/text'); +const get = require('./helpers/get'); +const getConstructorName = require('./helpers/getConstructorName'); +const getSchemaDiscriminatorByValue = require('./helpers/discriminator/getSchemaDiscriminatorByValue'); +const isOperator = require('./helpers/query/isOperator'); +const util = require('util'); +const isObject = require('./helpers/isObject'); +const isMongooseObject = require('./helpers/isMongooseObject'); + +const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon']; + +/** + * Handles internal casting for query filters. + * + * @param {Schema} schema + * @param {Object} obj Object to cast + * @param {Object} options the query options + * @param {Query} context passed to setters + * @api private + */ +module.exports = function cast(schema, obj, options, context) { + if (Array.isArray(obj)) { + throw new Error('Query filter must be an object, got an array ', util.inspect(obj)); + } + + if (obj == null) { + return obj; + } + + // bson 1.x has the unfortunate tendency to remove filters that have a top-level + // `_bsontype` property. But we should still allow ObjectIds because + // `Collection#find()` has a special case to support `find(objectid)`. + // Should remove this when we upgrade to bson 4.x. See gh-8222, gh-8268 + if (obj.hasOwnProperty('_bsontype') && obj._bsontype !== 'ObjectID') { + delete obj._bsontype; + } + + if (schema != null && schema.discriminators != null && obj[schema.options.discriminatorKey] != null) { + schema = getSchemaDiscriminatorByValue(schema, obj[schema.options.discriminatorKey]) || schema; + } + + const paths = Object.keys(obj); + let i = paths.length; + let _keys; + let any$conditionals; + let schematype; + let nested; + let path; + let type; + let val; + + options = options || {}; + + while (i--) { + path = paths[i]; + val = obj[path]; + + if (path === '$or' || path === '$nor' || path === '$and') { + if (!Array.isArray(val)) { + throw new CastError('Array', val, path); + } + for (let k = 0; k < val.length; ++k) { + if (val[k] == null || typeof val[k] !== 'object') { + throw new CastError('Object', val[k], path + '.' + k); + } + val[k] = cast(schema, val[k], options, context); + } + } else if (path === '$where') { + type = typeof val; + + if (type !== 'string' && type !== 'function') { + throw new Error('Must have a string or function for $where'); + } + + if (type === 'function') { + obj[path] = val.toString(); + } + + continue; + } else if (path === '$expr') { + if (typeof val !== 'object' || val == null) { + throw new Error('`$expr` must be an object'); + } + continue; + } else if (path === '$elemMatch') { + val = cast(schema, val, options, context); + } else if (path === '$text') { + val = castTextSearch(val, path); + } else { + if (!schema) { + // no casting for Mixed types + continue; + } + + schematype = schema.path(path); + + // Check for embedded discriminator paths + if (!schematype) { + const split = path.split('.'); + let j = split.length; + while (j--) { + const pathFirstHalf = split.slice(0, j).join('.'); + const pathLastHalf = split.slice(j).join('.'); + const _schematype = schema.path(pathFirstHalf); + const discriminatorKey = get(_schematype, 'schema.options.discriminatorKey'); + + // gh-6027: if we haven't found the schematype but this path is + // underneath an embedded discriminator and the embedded discriminator + // key is in the query, use the embedded discriminator schema + if (_schematype != null && + get(_schematype, 'schema.discriminators') != null && + discriminatorKey != null && + pathLastHalf !== discriminatorKey) { + const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey); + if (discriminatorVal != null) { + schematype = _schematype.schema.discriminators[discriminatorVal]. + path(pathLastHalf); + } + } + } + } + + if (!schematype) { + // Handle potential embedded array queries + const split = path.split('.'); + let j = split.length; + let pathFirstHalf; + let pathLastHalf; + let remainingConds; + + // Find the part of the var path that is a path of the Schema + while (j--) { + pathFirstHalf = split.slice(0, j).join('.'); + schematype = schema.path(pathFirstHalf); + if (schematype) { + break; + } + } + + // If a substring of the input path resolves to an actual real path... + if (schematype) { + // Apply the casting; similar code for $elemMatch in schema/array.js + if (schematype.caster && schematype.caster.schema) { + remainingConds = {}; + pathLastHalf = split.slice(j).join('.'); + remainingConds[pathLastHalf] = val; + obj[path] = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf]; + } else { + obj[path] = val; + } + continue; + } + + if (isObject(val)) { + // handle geo schemas that use object notation + // { loc: { long: Number, lat: Number } + + let geo = ''; + if (val.$near) { + geo = '$near'; + } else if (val.$nearSphere) { + geo = '$nearSphere'; + } else if (val.$within) { + geo = '$within'; + } else if (val.$geoIntersects) { + geo = '$geoIntersects'; + } else if (val.$geoWithin) { + geo = '$geoWithin'; + } + + if (geo) { + const numbertype = new Types.Number('__QueryCasting__'); + let value = val[geo]; + + if (val.$maxDistance != null) { + val.$maxDistance = numbertype.castForQueryWrapper({ + val: val.$maxDistance, + context: context + }); + } + if (val.$minDistance != null) { + val.$minDistance = numbertype.castForQueryWrapper({ + val: val.$minDistance, + context: context + }); + } + + if (geo === '$within') { + const withinType = value.$center + || value.$centerSphere + || value.$box + || value.$polygon; + + if (!withinType) { + throw new Error('Bad $within parameter: ' + JSON.stringify(val)); + } + + value = withinType; + } else if (geo === '$near' && + typeof value.type === 'string' && Array.isArray(value.coordinates)) { + // geojson; cast the coordinates + value = value.coordinates; + } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') && + value.$geometry && typeof value.$geometry.type === 'string' && + Array.isArray(value.$geometry.coordinates)) { + if (value.$maxDistance != null) { + value.$maxDistance = numbertype.castForQueryWrapper({ + val: value.$maxDistance, + context: context + }); + } + if (value.$minDistance != null) { + value.$minDistance = numbertype.castForQueryWrapper({ + val: value.$minDistance, + context: context + }); + } + if (isMongooseObject(value.$geometry)) { + value.$geometry = value.$geometry.toObject({ + transform: false, + virtuals: false + }); + } + value = value.$geometry.coordinates; + } else if (geo === '$geoWithin') { + if (value.$geometry) { + if (isMongooseObject(value.$geometry)) { + value.$geometry = value.$geometry.toObject({ virtuals: false }); + } + const geoWithinType = value.$geometry.type; + if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) { + throw new Error('Invalid geoJSON type for $geoWithin "' + + geoWithinType + '", must be "Polygon" or "MultiPolygon"'); + } + value = value.$geometry.coordinates; + } else { + value = value.$box || value.$polygon || value.$center || + value.$centerSphere; + if (isMongooseObject(value)) { + value = value.toObject({ virtuals: false }); + } + } + } + + _cast(value, numbertype, context); + continue; + } + } + + if (schema.nested[path]) { + continue; + } + if (options.upsert && options.strict) { + if (options.strict === 'throw') { + throw new StrictModeError(path); + } + throw new StrictModeError(path, 'Path "' + path + '" is not in ' + + 'schema, strict mode is `true`, and upsert is `true`.'); + } if (options.strictQuery === 'throw') { + throw new StrictModeError(path, 'Path "' + path + '" is not in ' + + 'schema and strictQuery is \'throw\'.'); + } else if (options.strictQuery) { + delete obj[path]; + } + } else if (val == null) { + continue; + } else if (getConstructorName(val) === 'Object') { + any$conditionals = Object.keys(val).some(isOperator); + + if (!any$conditionals) { + obj[path] = schematype.castForQueryWrapper({ + val: val, + context: context + }); + } else { + const ks = Object.keys(val); + let $cond; + + let k = ks.length; + + while (k--) { + $cond = ks[k]; + nested = val[$cond]; + + if ($cond === '$not') { + if (nested && schematype) { + _keys = Object.keys(nested); + if (_keys.length && isOperator(_keys[0])) { + for (const key in nested) { + nested[key] = schematype.castForQueryWrapper({ + $conditional: key, + val: nested[key], + context: context + }); + } + } else { + val[$cond] = schematype.castForQueryWrapper({ + $conditional: $cond, + val: nested, + context: context + }); + } + continue; + } + } else { + val[$cond] = schematype.castForQueryWrapper({ + $conditional: $cond, + val: nested, + context: context + }); + } + } + } + } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) { + const casted = []; + const valuesArray = val; + + for (const _val of valuesArray) { + casted.push(schematype.castForQueryWrapper({ + val: _val, + context: context + })); + } + + obj[path] = { $in: casted }; + } else { + obj[path] = schematype.castForQueryWrapper({ + val: val, + context: context + }); + } + } + } + + return obj; +}; + +function _cast(val, numbertype, context) { + if (Array.isArray(val)) { + val.forEach(function(item, i) { + if (Array.isArray(item) || isObject(item)) { + return _cast(item, numbertype, context); + } + val[i] = numbertype.castForQueryWrapper({ val: item, context: context }); + }); + } else { + const nearKeys = Object.keys(val); + let nearLen = nearKeys.length; + while (nearLen--) { + const nkey = nearKeys[nearLen]; + const item = val[nkey]; + if (Array.isArray(item) || isObject(item)) { + _cast(item, numbertype, context); + val[nkey] = item; + } else { + val[nkey] = numbertype.castForQuery({ val: item, context: context }); + } + } + } +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/boolean.js b/node_modules/mongoose/lib/cast/boolean.js new file mode 100644 index 0000000..92551d4 --- /dev/null +++ b/node_modules/mongoose/lib/cast/boolean.js @@ -0,0 +1,32 @@ +'use strict'; + +const CastError = require('../error/cast'); + +/*! + * Given a value, cast it to a boolean, or throw a `CastError` if the value + * cannot be casted. `null` and `undefined` are considered valid. + * + * @param {Any} value + * @param {String} [path] optional the path to set on the CastError + * @return {Boolean|null|undefined} + * @throws {CastError} if `value` is not one of the allowed values + * @api private + */ + +module.exports = function castBoolean(value, path) { + if (module.exports.convertToTrue.has(value)) { + return true; + } + if (module.exports.convertToFalse.has(value)) { + return false; + } + + if (value == null) { + return value; + } + + throw new CastError('boolean', value, path); +}; + +module.exports.convertToTrue = new Set([true, 'true', 1, '1', 'yes']); +module.exports.convertToFalse = new Set([false, 'false', 0, '0', 'no']); diff --git a/node_modules/mongoose/lib/cast/date.js b/node_modules/mongoose/lib/cast/date.js new file mode 100644 index 0000000..ac17006 --- /dev/null +++ b/node_modules/mongoose/lib/cast/date.js @@ -0,0 +1,41 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = function castDate(value) { + // Support empty string because of empty form values. Originally introduced + // in https://github.com/Automattic/mongoose/commit/efc72a1898fc3c33a319d915b8c5463a22938dfe + if (value == null || value === '') { + return null; + } + + if (value instanceof Date) { + assert.ok(!isNaN(value.valueOf())); + + return value; + } + + let date; + + assert.ok(typeof value !== 'boolean'); + + if (value instanceof Number || typeof value === 'number') { + date = new Date(value); + } else if (typeof value === 'string' && !isNaN(Number(value)) && (Number(value) >= 275761 || Number(value) < -271820)) { + // string representation of milliseconds take this path + date = new Date(Number(value)); + } else if (typeof value.valueOf === 'function') { + // support for moment.js. This is also the path strings will take because + // strings have a `valueOf()` + date = new Date(value.valueOf()); + } else { + // fallback + date = new Date(value); + } + + if (!isNaN(date.valueOf())) { + return date; + } + + assert.ok(false); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/decimal128.js b/node_modules/mongoose/lib/cast/decimal128.js new file mode 100644 index 0000000..bfb1578 --- /dev/null +++ b/node_modules/mongoose/lib/cast/decimal128.js @@ -0,0 +1,36 @@ +'use strict'; + +const Decimal128Type = require('../types/decimal128'); +const assert = require('assert'); + +module.exports = function castDecimal128(value) { + if (value == null) { + return value; + } + + if (typeof value === 'object' && typeof value.$numberDecimal === 'string') { + return Decimal128Type.fromString(value.$numberDecimal); + } + + if (value instanceof Decimal128Type) { + return value; + } + + if (typeof value === 'string') { + return Decimal128Type.fromString(value); + } + + if (Buffer.isBuffer(value)) { + return new Decimal128Type(value); + } + + if (typeof value === 'number') { + return Decimal128Type.fromString(String(value)); + } + + if (typeof value.valueOf === 'function' && typeof value.valueOf() === 'string') { + return Decimal128Type.fromString(value.valueOf()); + } + + assert.ok(false); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/number.js b/node_modules/mongoose/lib/cast/number.js new file mode 100644 index 0000000..7cd7f84 --- /dev/null +++ b/node_modules/mongoose/lib/cast/number.js @@ -0,0 +1,43 @@ +'use strict'; + +const assert = require('assert'); + +/*! + * Given a value, cast it to a number, or throw a `CastError` if the value + * cannot be casted. `null` and `undefined` are considered valid. + * + * @param {Any} value + * @param {String} [path] optional the path to set on the CastError + * @return {Boolean|null|undefined} + * @throws {Error} if `value` is not one of the allowed values + * @api private + */ + +module.exports = function castNumber(val) { + if (val == null) { + return val; + } + if (val === '') { + return null; + } + + if (typeof val === 'string' || typeof val === 'boolean') { + val = Number(val); + } + + assert.ok(!isNaN(val)); + if (val instanceof Number) { + return val.valueOf(); + } + if (typeof val === 'number') { + return val; + } + if (!Array.isArray(val) && typeof val.valueOf === 'function') { + return Number(val.valueOf()); + } + if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) { + return Number(val); + } + + assert.ok(false); +}; diff --git a/node_modules/mongoose/lib/cast/objectid.js b/node_modules/mongoose/lib/cast/objectid.js new file mode 100644 index 0000000..67cffb5 --- /dev/null +++ b/node_modules/mongoose/lib/cast/objectid.js @@ -0,0 +1,29 @@ +'use strict'; + +const ObjectId = require('../driver').get().ObjectId; +const assert = require('assert'); + +module.exports = function castObjectId(value) { + if (value == null) { + return value; + } + + if (value instanceof ObjectId) { + return value; + } + + if (value._id) { + if (value._id instanceof ObjectId) { + return value._id; + } + if (value._id.toString instanceof Function) { + return new ObjectId(value._id.toString()); + } + } + + if (value.toString instanceof Function) { + return new ObjectId(value.toString()); + } + + assert.ok(false); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/string.js b/node_modules/mongoose/lib/cast/string.js new file mode 100644 index 0000000..4d89f8e --- /dev/null +++ b/node_modules/mongoose/lib/cast/string.js @@ -0,0 +1,37 @@ +'use strict'; + +const CastError = require('../error/cast'); + +/*! + * Given a value, cast it to a string, or throw a `CastError` if the value + * cannot be casted. `null` and `undefined` are considered valid. + * + * @param {Any} value + * @param {String} [path] optional the path to set on the CastError + * @return {string|null|undefined} + * @throws {CastError} + * @api private + */ + +module.exports = function castString(value, path) { + // If null or undefined + if (value == null) { + return value; + } + + // handle documents being passed + if (value._id && typeof value._id === 'string') { + return value._id; + } + + // Re: gh-647 and gh-3030, we're ok with casting using `toString()` + // **unless** its the default Object.toString, because "[object Object]" + // doesn't really qualify as useful data + if (value.toString && + value.toString !== Object.prototype.toString && + !Array.isArray(value)) { + return value.toString(); + } + + throw new CastError('string', value, path); +}; diff --git a/node_modules/mongoose/lib/collection.js b/node_modules/mongoose/lib/collection.js new file mode 100644 index 0000000..9120636 --- /dev/null +++ b/node_modules/mongoose/lib/collection.js @@ -0,0 +1,318 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const EventEmitter = require('events').EventEmitter; +const STATES = require('./connectionstate'); +const immediate = require('./helpers/immediate'); + +/** + * Abstract Collection constructor + * + * This is the base class that drivers inherit from and implement. + * + * @param {String} name name of the collection + * @param {Connection} conn A MongooseConnection instance + * @param {Object} opts optional collection options + * @api public + */ + +function Collection(name, conn, opts) { + if (opts === void 0) { + opts = {}; + } + if (opts.capped === void 0) { + opts.capped = {}; + } + + if (typeof opts.capped === 'number') { + opts.capped = { size: opts.capped }; + } + + this.opts = opts; + this.name = name; + this.collectionName = name; + this.conn = conn; + this.queue = []; + this.buffer = true; + this.emitter = new EventEmitter(); + + if (STATES.connected === this.conn.readyState) { + this.onOpen(); + } +} + +/** + * The collection name + * + * @api public + * @property name + */ + +Collection.prototype.name; + +/** + * The collection name + * + * @api public + * @property collectionName + */ + +Collection.prototype.collectionName; + +/** + * The Connection instance + * + * @api public + * @property conn + */ + +Collection.prototype.conn; + +/** + * Called when the database connects + * + * @api private + */ + +Collection.prototype.onOpen = function() { + this.buffer = false; + immediate(() => this.doQueue()); +}; + +/** + * Called when the database disconnects + * + * @api private + */ + +Collection.prototype.onClose = function() {}; + +/** + * Queues a method for later execution when its + * database connection opens. + * + * @param {String} name name of the method to queue + * @param {Array} args arguments to pass to the method when executed + * @api private + */ + +Collection.prototype.addQueue = function(name, args) { + this.queue.push([name, args]); + return this; +}; + +/** + * Removes a queued method + * + * @param {String} name name of the method to queue + * @param {Array} args arguments to pass to the method when executed + * @api private + */ + +Collection.prototype.removeQueue = function(name, args) { + const index = this.queue.findIndex(v => v[0] === name && v[1] === args); + if (index === -1) { + return false; + } + this.queue.splice(index, 1); + return true; +}; + +/** + * Executes all queued methods and clears the queue. + * + * @api private + */ + +Collection.prototype.doQueue = function() { + for (const method of this.queue) { + if (typeof method[0] === 'function') { + method[0].apply(this, method[1]); + } else { + this[method[0]].apply(this, method[1]); + } + } + this.queue = []; + const _this = this; + immediate(function() { + _this.emitter.emit('queue'); + }); + return this; +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.ensureIndex = function() { + throw new Error('Collection#ensureIndex unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.createIndex = function() { + throw new Error('Collection#createIndex unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.findAndModify = function() { + throw new Error('Collection#findAndModify unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.findOneAndUpdate = function() { + throw new Error('Collection#findOneAndUpdate unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.findOneAndDelete = function() { + throw new Error('Collection#findOneAndDelete unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.findOneAndReplace = function() { + throw new Error('Collection#findOneAndReplace unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.findOne = function() { + throw new Error('Collection#findOne unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.find = function() { + throw new Error('Collection#find unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.insert = function() { + throw new Error('Collection#insert unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.insertOne = function() { + throw new Error('Collection#insertOne unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.insertMany = function() { + throw new Error('Collection#insertMany unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.save = function() { + throw new Error('Collection#save unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.update = function() { + throw new Error('Collection#update unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.getIndexes = function() { + throw new Error('Collection#getIndexes unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.mapReduce = function() { + throw new Error('Collection#mapReduce unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.watch = function() { + throw new Error('Collection#watch unimplemented by driver'); +}; + +/*! + * ignore + */ + +Collection.prototype._shouldBufferCommands = function _shouldBufferCommands() { + const opts = this.opts; + + if (opts.bufferCommands != null) { + return opts.bufferCommands; + } + if (opts && opts.schemaUserProvidedOptions != null && opts.schemaUserProvidedOptions.bufferCommands != null) { + return opts.schemaUserProvidedOptions.bufferCommands; + } + + return this.conn._shouldBufferCommands(); +}; + +/*! + * ignore + */ + +Collection.prototype._getBufferTimeoutMS = function _getBufferTimeoutMS() { + const conn = this.conn; + const opts = this.opts; + + if (opts.bufferTimeoutMS != null) { + return opts.bufferTimeoutMS; + } + if (opts && opts.schemaUserProvidedOptions != null && opts.schemaUserProvidedOptions.bufferTimeoutMS != null) { + return opts.schemaUserProvidedOptions.bufferTimeoutMS; + } + if (conn.config.bufferTimeoutMS != null) { + return conn.config.bufferTimeoutMS; + } + if (conn.base != null && conn.base.get('bufferTimeoutMS') != null) { + return conn.base.get('bufferTimeoutMS'); + } + return 10000; +}; + +/*! + * Module exports. + */ + +module.exports = Collection; diff --git a/node_modules/mongoose/lib/connection.js b/node_modules/mongoose/lib/connection.js new file mode 100644 index 0000000..fcc4899 --- /dev/null +++ b/node_modules/mongoose/lib/connection.js @@ -0,0 +1,1395 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const ChangeStream = require('./cursor/ChangeStream'); +const EventEmitter = require('events').EventEmitter; +const Schema = require('./schema'); +const Collection = require('./driver').get().Collection; +const STATES = require('./connectionstate'); +const MongooseError = require('./error/index'); +const PromiseProvider = require('./promise_provider'); +const ServerSelectionError = require('./error/serverSelection'); +const applyPlugins = require('./helpers/schema/applyPlugins'); +const promiseOrCallback = require('./helpers/promiseOrCallback'); +const get = require('./helpers/get'); +const immediate = require('./helpers/immediate'); +const mongodb = require('mongodb'); +const pkg = require('../package.json'); +const utils = require('./utils'); +const processConnectionOptions = require('./helpers/processConnectionOptions'); + +const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol; +const sessionNewDocuments = require('./helpers/symbols').sessionNewDocuments; + +/*! + * A list of authentication mechanisms that don't require a password for authentication. + * This is used by the authMechanismDoesNotRequirePassword method. + * + * @api private + */ +const noPasswordAuthMechanisms = [ + 'MONGODB-X509' +]; + +/** + * Connection constructor + * + * For practical reasons, a Connection equals a Db. + * + * @param {Mongoose} base a mongoose instance + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `connecting`: Emitted when `connection.openUri()` is executed on this connection. + * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios. + * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models. + * @event `disconnecting`: Emitted when `connection.close()` was executed. + * @event `disconnected`: Emitted after getting disconnected from the db. + * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models. + * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successful connection. + * @event `error`: Emitted when an error occurs on this connection. + * @event `fullsetup`: Emitted after the driver has connected to primary and all secondaries if specified in the connection string. + * @api public + */ + +function Connection(base) { + this.base = base; + this.collections = {}; + this.models = {}; + this.config = {}; + this.replica = false; + this.options = null; + this.otherDbs = []; // FIXME: To be replaced with relatedDbs + this.relatedDbs = {}; // Hashmap of other dbs that share underlying connection + this.states = STATES; + this._readyState = STATES.disconnected; + this._closeCalled = false; + this._hasOpened = false; + this.plugins = []; + if (typeof base === 'undefined' || !base.connections.length) { + this.id = 0; + } else { + this.id = base.connections.length; + } + this._queue = []; +} + +/*! + * Inherit from EventEmitter + */ + +Connection.prototype.__proto__ = EventEmitter.prototype; + +/** + * Connection ready state + * + * - 0 = disconnected + * - 1 = connected + * - 2 = connecting + * - 3 = disconnecting + * + * Each state change emits its associated event name. + * + * ####Example + * + * conn.on('connected', callback); + * conn.on('disconnected', callback); + * + * @property readyState + * @memberOf Connection + * @instance + * @api public + */ + +Object.defineProperty(Connection.prototype, 'readyState', { + get: function() { + return this._readyState; + }, + set: function(val) { + if (!(val in STATES)) { + throw new Error('Invalid connection state: ' + val); + } + + if (this._readyState !== val) { + this._readyState = val; + // [legacy] loop over the otherDbs on this connection and change their state + for (const db of this.otherDbs) { + db.readyState = val; + } + + if (STATES.connected === val) { + this._hasOpened = true; + } + + this.emit(STATES[val]); + } + } +}); + +/** + * Gets the value of the option `key`. Equivalent to `conn.options[key]` + * + * ####Example: + * + * conn.get('test'); // returns the 'test' value + * + * @param {String} key + * @method get + * @api public + */ + +Connection.prototype.get = function(key) { + if (this.config.hasOwnProperty(key)) { + return this.config[key]; + } + + return get(this.options, key); +}; + +/** + * Sets the value of the option `key`. Equivalent to `conn.options[key] = val` + * + * Supported options include: + * + * - `maxTimeMS`: Set [`maxTimeMS`](/docs/api.html#query_Query-maxTimeMS) for all queries on this connection. + * + * ####Example: + * + * conn.set('test', 'foo'); + * conn.get('test'); // 'foo' + * conn.options.test; // 'foo' + * + * @param {String} key + * @param {Any} val + * @method set + * @api public + */ + +Connection.prototype.set = function(key, val) { + if (this.config.hasOwnProperty(key)) { + this.config[key] = val; + return val; + } + + this.options = this.options || {}; + this.options[key] = val; + return val; +}; + +/** + * A hash of the collections associated with this connection + * + * @property collections + * @memberOf Connection + * @instance + * @api public + */ + +Connection.prototype.collections; + +/** + * The name of the database this connection points to. + * + * ####Example + * + * mongoose.createConnection('mongodb://localhost:27017/mydb').name; // "mydb" + * + * @property name + * @memberOf Connection + * @instance + * @api public + */ + +Connection.prototype.name; + +/** + * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing + * a map from model names to models. Contains all models that have been + * added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model). + * + * ####Example + * + * const conn = mongoose.createConnection(); + * const Test = conn.model('Test', mongoose.Schema({ name: String })); + * + * Object.keys(conn.models).length; // 1 + * conn.models.Test === Test; // true + * + * @property models + * @memberOf Connection + * @instance + * @api public + */ + +Connection.prototype.models; + +/** + * A number identifier for this connection. Used for debugging when + * you have [multiple connections](/docs/connections.html#multiple_connections). + * + * ####Example + * + * // The default connection has `id = 0` + * mongoose.connection.id; // 0 + * + * // If you create a new connection, Mongoose increments id + * const conn = mongoose.createConnection(); + * conn.id; // 1 + * + * @property id + * @memberOf Connection + * @instance + * @api public + */ + +Connection.prototype.id; + +/** + * The plugins that will be applied to all models created on this connection. + * + * ####Example: + * + * const db = mongoose.createConnection('mongodb://localhost:27017/mydb'); + * db.plugin(() => console.log('Applied')); + * db.plugins.length; // 1 + * + * db.model('Test', new Schema({})); // Prints "Applied" + * + * @property plugins + * @memberOf Connection + * @instance + * @api public + */ + +Object.defineProperty(Connection.prototype, 'plugins', { + configurable: false, + enumerable: true, + writable: true +}); + +/** + * The host name portion of the URI. If multiple hosts, such as a replica set, + * this will contain the first host name in the URI + * + * ####Example + * + * mongoose.createConnection('mongodb://localhost:27017/mydb').host; // "localhost" + * + * @property host + * @memberOf Connection + * @instance + * @api public + */ + +Object.defineProperty(Connection.prototype, 'host', { + configurable: true, + enumerable: true, + writable: true +}); + +/** + * The port portion of the URI. If multiple hosts, such as a replica set, + * this will contain the port from the first host name in the URI. + * + * ####Example + * + * mongoose.createConnection('mongodb://localhost:27017/mydb').port; // 27017 + * + * @property port + * @memberOf Connection + * @instance + * @api public + */ + +Object.defineProperty(Connection.prototype, 'port', { + configurable: true, + enumerable: true, + writable: true +}); + +/** + * The username specified in the URI + * + * ####Example + * + * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').user; // "val" + * + * @property user + * @memberOf Connection + * @instance + * @api public + */ + +Object.defineProperty(Connection.prototype, 'user', { + configurable: true, + enumerable: true, + writable: true +}); + +/** + * The password specified in the URI + * + * ####Example + * + * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').pass; // "psw" + * + * @property pass + * @memberOf Connection + * @instance + * @api public + */ + +Object.defineProperty(Connection.prototype, 'pass', { + configurable: true, + enumerable: true, + writable: true +}); + +/** + * The mongodb.Db instance, set when the connection is opened + * + * @property db + * @memberOf Connection + * @instance + * @api public + */ + +Connection.prototype.db; + +/** + * The MongoClient instance this connection uses to talk to MongoDB. Mongoose automatically sets this property + * when the connection is opened. + * + * @property client + * @memberOf Connection + * @instance + * @api public + */ + +Connection.prototype.client; + +/** + * A hash of the global options that are associated with this connection + * + * @property config + * @memberOf Connection + * @instance + * @api public + */ + +Connection.prototype.config; + +/** + * Helper for `createCollection()`. Will explicitly create the given collection + * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/) + * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose. + * + * Options are passed down without modification to the [MongoDB driver's `createCollection()` function](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection) + * + * @method createCollection + * @param {string} collection The collection to create + * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection) + * @param {Function} [callback] + * @return {Promise} + * @api public + */ + +Connection.prototype.createCollection = _wrapConnHelper(function createCollection(collection, options, cb) { + if (typeof options === 'function') { + cb = options; + options = {}; + } + this.db.createCollection(collection, options, cb); +}); + +/** + * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) + * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), + * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). + * + * ####Example: + * + * const session = await conn.startSession(); + * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); + * await doc.remove(); + * // `doc` will always be null, even if reading from a replica set + * // secondary. Without causal consistency, it is possible to + * // get a doc back from the below query if the query reads from a + * // secondary that is experiencing replication lag. + * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); + * + * + * @method startSession + * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) + * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency + * @param {Function} [callback] + * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` + * @api public + */ + +Connection.prototype.startSession = _wrapConnHelper(function startSession(options, cb) { + if (typeof options === 'function') { + cb = options; + options = null; + } + const session = this.client.startSession(options); + cb(null, session); +}); + +/** + * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function + * in a transaction. Mongoose will commit the transaction if the + * async function executes successfully and attempt to retry if + * there was a retriable error. + * + * Calls the MongoDB driver's [`session.withTransaction()`](http://mongodb.github.io/node-mongodb-native/3.5/api/ClientSession.html#withTransaction), + * but also handles resetting Mongoose document state as shown below. + * + * ####Example: + * + * const doc = new Person({ name: 'Will Riker' }); + * await db.transaction(async function setRank(session) { + * doc.rank = 'Captain'; + * await doc.save({ session }); + * doc.isNew; // false + * + * // Throw an error to abort the transaction + * throw new Error('Oops!'); + * },{ readPreference: 'primary' }).catch(() => {}); + * + * // true, `transaction()` reset the document's state because the + * // transaction was aborted. + * doc.isNew; + * + * @method transaction + * @param {Function} fn Function to execute in a transaction + * @param {mongodb.TransactionOptions} [options] Optional settings for the transaction + * @return {Promise} promise that is fulfilled if Mongoose successfully committed the transaction, or rejects if the transaction was aborted or if Mongoose failed to commit the transaction. If fulfilled, the promise resolves to a MongoDB command result. + * @api public + */ + +Connection.prototype.transaction = function transaction(fn, options) { + return this.startSession().then(session => { + session[sessionNewDocuments] = new Map(); + return session.withTransaction(() => fn(session), options). + then(res => { + delete session[sessionNewDocuments]; + return res; + }). + catch(err => { + // If transaction was aborted, we need to reset newly + // inserted documents' `isNew`. + for (const doc of session[sessionNewDocuments].keys()) { + const state = session[sessionNewDocuments].get(doc); + if (state.hasOwnProperty('isNew')) { + doc.$isNew = state.$isNew; + } + if (state.hasOwnProperty('versionKey')) { + doc.set(doc.schema.options.versionKey, state.versionKey); + } + + for (const path of state.modifiedPaths) { + doc.$__.activePaths.paths[path] = 'modify'; + doc.$__.activePaths.states.modify[path] = true; + } + + for (const path of state.atomics.keys()) { + const val = doc.$__getValue(path); + if (val == null) { + continue; + } + val[arrayAtomicsSymbol] = state.atomics.get(path); + } + } + delete session[sessionNewDocuments]; + throw err; + }); + }); +}; + +/** + * Helper for `dropCollection()`. Will delete the given collection, including + * all documents and indexes. + * + * @method dropCollection + * @param {string} collection The collection to delete + * @param {Function} [callback] + * @return {Promise} + * @api public + */ + +Connection.prototype.dropCollection = _wrapConnHelper(function dropCollection(collection, cb) { + this.db.dropCollection(collection, cb); +}); + +/** + * Helper for `dropDatabase()`. Deletes the given database, including all + * collections, documents, and indexes. + * + * ####Example: + * + * const conn = mongoose.createConnection('mongodb://localhost:27017/mydb'); + * // Deletes the entire 'mydb' database + * await conn.dropDatabase(); + * + * @method dropDatabase + * @param {Function} [callback] + * @return {Promise} + * @api public + */ + +Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) { + // If `dropDatabase()` is called, this model's collection will not be + // init-ed. It is sufficiently common to call `dropDatabase()` after + // `mongoose.connect()` but before creating models that we want to + // support this. See gh-6967 + for (const name of Object.keys(this.models)) { + delete this.models[name].$init; + } + this.db.dropDatabase(cb); +}); + +/*! + * ignore + */ + +function _wrapConnHelper(fn) { + return function() { + const cb = arguments.length > 0 ? arguments[arguments.length - 1] : null; + const argsWithoutCb = typeof cb === 'function' ? + Array.prototype.slice.call(arguments, 0, arguments.length - 1) : + Array.prototype.slice.call(arguments); + const disconnectedError = new MongooseError('Connection ' + this.id + + ' was disconnected when calling `' + fn.name + '`'); + + return promiseOrCallback(cb, cb => { + immediate(() => { + if ((this.readyState === STATES.connecting || this.readyState === STATES.disconnected) && this._shouldBufferCommands()) { + this._queue.push({ fn: fn, ctx: this, args: argsWithoutCb.concat([cb]) }); + } else if (this.readyState === STATES.disconnected && this.db == null) { + cb(disconnectedError); + } else { + try { + fn.apply(this, argsWithoutCb.concat([cb])); + } catch (err) { + return cb(err); + } + } + }); + }); + }; +} + +/*! + * ignore + */ + +Connection.prototype._shouldBufferCommands = function _shouldBufferCommands() { + if (this.config.bufferCommands != null) { + return this.config.bufferCommands; + } + if (this.base.get('bufferCommands') != null) { + return this.base.get('bufferCommands'); + } + return true; +}; + +/** + * error + * + * Graceful error handling, passes error to callback + * if available, else emits error on the connection. + * + * @param {Error} err + * @param {Function} callback optional + * @api private + */ + +Connection.prototype.error = function(err, callback) { + if (callback) { + callback(err); + return null; + } + if (this.listeners('error').length > 0) { + this.emit('error', err); + } + return Promise.reject(err); +}; + +/** + * Called when the connection is opened + * + * @api private + */ + +Connection.prototype.onOpen = function() { + this.readyState = STATES.connected; + + for (const d of this._queue) { + d.fn.apply(d.ctx, d.args); + } + this._queue = []; + + // avoid having the collection subscribe to our event emitter + // to prevent 0.3 warning + for (const i in this.collections) { + if (utils.object.hasOwnProperty(this.collections, i)) { + this.collections[i].onOpen(); + } + } + + this.emit('open'); +}; + +/** + * Opens the connection with a URI using `MongoClient.connect()`. + * + * @param {String} uri The URI to connect with. + * @param {Object} [options] Passed on to http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect + * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. + * @param {Number} [options.bufferTimeoutMS=10000] Mongoose specific option. If `bufferCommands` is true, Mongoose will throw an error after `bufferTimeoutMS` if the operation is still buffered. + * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string. + * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. + * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. + * @param {Number} [options.maxPoolSize=100] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). + * @param {Number} [options.minPoolSize=0] The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). + * @param {Number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds). + * @param {Number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation. + * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. + * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). + * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). + * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. + * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. + * @param {Boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. + * @param {Function} [callback] + * @returns {Connection} this + * @api public + */ + +Connection.prototype.openUri = function(uri, options, callback) { + if (typeof options === 'function') { + callback = options; + options = null; + } + + if (['string', 'number'].indexOf(typeof options) !== -1) { + throw new MongooseError('Mongoose 5.x no longer supports ' + + '`mongoose.connect(host, dbname, port)` or ' + + '`mongoose.createConnection(host, dbname, port)`. See ' + + 'http://mongoosejs.com/docs/connections.html for supported connection syntax'); + } + + if (typeof uri !== 'string') { + throw new MongooseError('The `uri` parameter to `openUri()` must be a ' + + `string, got "${typeof uri}". Make sure the first parameter to ` + + '`mongoose.connect()` or `mongoose.createConnection()` is a string.'); + } + + if (callback != null && typeof callback !== 'function') { + throw new MongooseError('3rd parameter to `mongoose.connect()` or ' + + '`mongoose.createConnection()` must be a function, got "' + + typeof callback + '"'); + } + + if (this.readyState === STATES.connecting || this.readyState === STATES.connected) { + if (this._connectionString !== uri) { + throw new MongooseError('Can\'t call `openUri()` on an active connection with ' + + 'different connection strings. Make sure you aren\'t calling `mongoose.connect()` ' + + 'multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections'); + } + + if (typeof callback === 'function') { + this.$initialConnection = this.$initialConnection.then( + () => callback(null, this), + err => callback(err) + ); + } + return this; + } + + this._connectionString = uri; + this.readyState = STATES.connecting; + this._closeCalled = false; + + const Promise = PromiseProvider.get(); + const _this = this; + + options = processConnectionOptions(uri, options); + + if (options) { + options = utils.clone(options); + + const autoIndex = options.config && options.config.autoIndex != null ? + options.config.autoIndex : + options.autoIndex; + if (autoIndex != null) { + this.config.autoIndex = autoIndex !== false; + delete options.config; + delete options.autoIndex; + } + + if ('autoCreate' in options) { + this.config.autoCreate = !!options.autoCreate; + delete options.autoCreate; + } + + if ('sanitizeFilter' in options) { + this.config.sanitizeFilter = options.sanitizeFilter; + delete options.sanitizeFilter; + } + + // Backwards compat + if (options.user || options.pass) { + options.auth = options.auth || {}; + options.auth.username = options.user; + options.auth.password = options.pass; + + this.user = options.user; + this.pass = options.pass; + } + delete options.user; + delete options.pass; + + if (options.bufferCommands != null) { + this.config.bufferCommands = options.bufferCommands; + delete options.bufferCommands; + } + } else { + options = {}; + } + + this._connectionOptions = options; + const dbName = options.dbName; + if (dbName != null) { + this.$dbName = dbName; + } + delete options.dbName; + + if (!utils.hasUserDefinedProperty(options, 'driverInfo')) { + options.driverInfo = { + name: 'Mongoose', + version: pkg.version + }; + } + + const promise = new Promise((resolve, reject) => { + let client; + try { + client = new mongodb.MongoClient(uri, options); + } catch (error) { + _this.readyState = STATES.disconnected; + return reject(error); + } + _this.client = client; + client.setMaxListeners(0); + client.connect((error) => { + if (error) { + return reject(error); + } + + _setClient(_this, client, options, dbName); + + resolve(_this); + }); + }); + + const serverSelectionError = new ServerSelectionError(); + this.$initialConnection = promise. + then(() => this). + catch(err => { + this.readyState = STATES.disconnected; + if (err != null && err.name === 'MongoServerSelectionError') { + err = serverSelectionError.assimilateError(err); + } + + if (this.listeners('error').length > 0) { + immediate(() => this.emit('error', err)); + } + throw err; + }); + + if (callback != null) { + this.$initialConnection = this.$initialConnection.then( + () => { callback(null, this); return this; }, + err => callback(err) + ); + } + + return this.$initialConnection; +}; + +/*! + * ignore + */ + +function _setClient(conn, client, options, dbName) { + const db = dbName != null ? client.db(dbName) : client.db(); + conn.db = db; + conn.client = client; + conn.host = get(client, 's.options.hosts.0.host', void 0); + conn.port = get(client, 's.options.hosts.0.port', void 0); + conn.name = dbName != null ? dbName : get(client, 's.options.dbName', void 0); + conn._closeCalled = client._closeCalled; + + const _handleReconnect = () => { + // If we aren't disconnected, we assume this reconnect is due to a + // socket timeout. If there's no activity on a socket for + // `socketTimeoutMS`, the driver will attempt to reconnect and emit + // this event. + if (conn.readyState !== STATES.connected) { + conn.readyState = STATES.connected; + conn.emit('reconnect'); + conn.emit('reconnected'); + conn.onOpen(); + } + }; + + const type = get(client, 'topology.description.type', ''); + + if (type === 'Single') { + client.on('serverDescriptionChanged', ev => { + const newDescription = ev.newDescription; + if (newDescription.type === 'Standalone') { + _handleReconnect(); + } else { + conn.readyState = STATES.disconnected; + } + }); + } else if (type.startsWith('ReplicaSet')) { + client.on('topologyDescriptionChanged', ev => { + // Emit disconnected if we've lost connectivity to the primary + const description = ev.newDescription; + if (conn.readyState === STATES.connected && description.type !== 'ReplicaSetWithPrimary') { + // Implicitly emits 'disconnected' + conn.readyState = STATES.disconnected; + } else if (conn.readyState === STATES.disconnected && description.type === 'ReplicaSetWithPrimary') { + _handleReconnect(); + } + }); + } + + conn.onOpen(); + + for (const i in conn.collections) { + if (utils.object.hasOwnProperty(conn.collections, i)) { + conn.collections[i].onOpen(); + } + } +} + +/** + * Closes the connection + * + * @param {Boolean} [force] optional + * @param {Function} [callback] optional + * @return {Promise} + * @api public + */ + +Connection.prototype.close = function(force, callback) { + if (typeof force === 'function') { + callback = force; + force = false; + } + + this.$wasForceClosed = !!force; + + return promiseOrCallback(callback, cb => { + this._close(force, cb); + }); +}; + +/** + * Handles closing the connection + * + * @param {Boolean} force + * @param {Function} callback + * @api private + */ +Connection.prototype._close = function(force, callback) { + const _this = this; + const closeCalled = this._closeCalled; + this._closeCalled = true; + if (this.client != null) { + this.client._closeCalled = true; + } + + switch (this.readyState) { + case STATES.disconnected: + if (closeCalled) { + callback(); + } else { + this.doClose(force, function(err) { + if (err) { + return callback(err); + } + _this.onClose(force); + callback(null); + }); + } + break; + + case STATES.connected: + this.readyState = STATES.disconnecting; + this.doClose(force, function(err) { + if (err) { + return callback(err); + } + _this.onClose(force); + callback(null); + }); + + break; + case STATES.connecting: + this.once('open', function() { + _this.close(callback); + }); + break; + + case STATES.disconnecting: + this.once('close', function() { + callback(); + }); + break; + } + + return this; +}; + +/** + * Called when the connection closes + * + * @api private + */ + +Connection.prototype.onClose = function(force) { + this.readyState = STATES.disconnected; + + // avoid having the collection subscribe to our event emitter + // to prevent 0.3 warning + for (const i in this.collections) { + if (utils.object.hasOwnProperty(this.collections, i)) { + this.collections[i].onClose(force); + } + } + + this.emit('close', force); + + for (const db of this.otherDbs) { + db.close(force); + } +}; + +/** + * Retrieves a collection, creating it if not cached. + * + * Not typically needed by applications. Just talk to your collection through your model. + * + * @param {String} name of the collection + * @param {Object} [options] optional collection options + * @return {Collection} collection instance + * @api public + */ + +Connection.prototype.collection = function(name, options) { + const defaultOptions = { + autoIndex: this.config.autoIndex != null ? this.config.autoIndex : this.base.options.autoIndex, + autoCreate: this.config.autoCreate != null ? this.config.autoCreate : this.base.options.autoCreate + }; + options = Object.assign({}, defaultOptions, options ? utils.clone(options) : {}); + options.$wasForceClosed = this.$wasForceClosed; + if (!(name in this.collections)) { + this.collections[name] = new Collection(name, this, options); + } + return this.collections[name]; +}; + +/** + * Declares a plugin executed on all schemas you pass to `conn.model()` + * + * Equivalent to calling `.plugin(fn)` on each schema you create. + * + * ####Example: + * const db = mongoose.createConnection('mongodb://localhost:27017/mydb'); + * db.plugin(() => console.log('Applied')); + * db.plugins.length; // 1 + * + * db.model('Test', new Schema({})); // Prints "Applied" + * + * @param {Function} fn plugin callback + * @param {Object} [opts] optional options + * @return {Connection} this + * @see plugins ./plugins.html + * @api public + */ + +Connection.prototype.plugin = function(fn, opts) { + this.plugins.push([fn, opts]); + return this; +}; + +/** + * Defines or retrieves a model. + * + * const mongoose = require('mongoose'); + * const db = mongoose.createConnection(..); + * db.model('Venue', new Schema(..)); + * const Ticket = db.model('Ticket', new Schema(..)); + * const Venue = db.model('Venue'); + * + * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ + * + * ####Example: + * + * const schema = new Schema({ name: String }, { collection: 'actor' }); + * + * // or + * + * schema.set('collection', 'actor'); + * + * // or + * + * const collectionName = 'actor' + * const M = conn.model('Actor', schema, collectionName) + * + * @param {String|Function} name the model name or class extending Model + * @param {Schema} [schema] a schema. necessary when defining a model + * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name + * @param {Object} [options] + * @param {Boolean} [options.overwriteModels=false] If true, overwrite existing models with the same name to avoid `OverwriteModelError` + * @see Mongoose#model #index_Mongoose-model + * @return {Model} The compiled model + * @api public + */ + +Connection.prototype.model = function(name, schema, collection, options) { + if (!(this instanceof Connection)) { + throw new MongooseError('`connection.model()` should not be run with ' + + '`new`. If you are doing `new db.model(foo)(bar)`, use ' + + '`db.model(foo)(bar)` instead'); + } + + let fn; + if (typeof name === 'function') { + fn = name; + name = fn.name; + } + + // collection name discovery + if (typeof schema === 'string') { + collection = schema; + schema = false; + } + + if (utils.isObject(schema) && !schema.instanceOfSchema) { + schema = new Schema(schema); + } + if (schema && !schema.instanceOfSchema) { + throw new Error('The 2nd parameter to `mongoose.model()` should be a ' + + 'schema or a POJO'); + } + + const defaultOptions = { cache: false, overwriteModels: this.base.options.overwriteModels }; + const opts = Object.assign(defaultOptions, options, { connection: this }); + if (this.models[name] && !collection && opts.overwriteModels !== true) { + // model exists but we are not subclassing with custom collection + if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { + throw new MongooseError.OverwriteModelError(name); + } + return this.models[name]; + } + + let model; + + if (schema && schema.instanceOfSchema) { + applyPlugins(schema, this.plugins, null, '$connectionPluginsApplied'); + + // compile a model + model = this.base._model(fn || name, schema, collection, opts); + + // only the first model with this name is cached to allow + // for one-offs with custom collection names etc. + if (!this.models[name]) { + this.models[name] = model; + } + + // Errors handled internally, so safe to ignore error + model.init(function $modelInitNoop() {}); + + return model; + } + + if (this.models[name] && collection) { + // subclassing current model with alternate collection + model = this.models[name]; + schema = model.prototype.schema; + const sub = model.__subclass(this, schema, collection); + // do not cache the sub model + return sub; + } + + if (!model) { + throw new MongooseError.MissingSchemaError(name); + } + + if (this === model.prototype.db + && (!collection || collection === model.collection.name)) { + // model already uses this connection. + + // only the first model with this name is cached to allow + // for one-offs with custom collection names etc. + if (!this.models[name]) { + this.models[name] = model; + } + + return model; + } + this.models[name] = model.__subclass(this, schema, collection); + return this.models[name]; +}; + +/** + * Removes the model named `name` from this connection, if it exists. You can + * use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + * + * ####Example: + * + * conn.model('User', new Schema({ name: String })); + * console.log(conn.model('User')); // Model object + * conn.deleteModel('User'); + * console.log(conn.model('User')); // undefined + * + * // Usually useful in a Mocha `afterEach()` hook + * afterEach(function() { + * conn.deleteModel(/.+/); // Delete every model + * }); + * + * @api public + * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. + * @return {Connection} this + */ + +Connection.prototype.deleteModel = function(name) { + if (typeof name === 'string') { + const model = this.model(name); + if (model == null) { + return this; + } + const collectionName = model.collection.name; + delete this.models[name]; + delete this.collections[collectionName]; + + this.emit('deleteModel', model); + } else if (name instanceof RegExp) { + const pattern = name; + const names = this.modelNames(); + for (const name of names) { + if (pattern.test(name)) { + this.deleteModel(name); + } + } + } else { + throw new Error('First parameter to `deleteModel()` must be a string ' + + 'or regexp, got "' + name + '"'); + } + + return this; +}; + +/** + * Watches the entire underlying database for changes. Similar to + * [`Model.watch()`](/docs/api/model.html#model_Model.watch). + * + * This function does **not** trigger any middleware. In particular, it + * does **not** trigger aggregate middleware. + * + * The ChangeStream object is an event emitter that emits the following events: + * + * - 'change': A change occurred, see below example + * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates. + * - 'end': Emitted if the underlying stream is closed + * - 'close': Emitted if the underlying stream is closed + * + * ####Example: + * + * const User = conn.model('User', new Schema({ name: String })); + * + * const changeStream = conn.watch().on('change', data => console.log(data)); + * + * // Triggers a 'change' event on the change stream. + * await User.create({ name: 'test' }); + * + * @api public + * @param {Array} [pipeline] + * @param {Object} [options] passed without changes to [the MongoDB driver's `Db#watch()` function](https://mongodb.github.io/node-mongodb-native/3.4/api/Db.html#watch) + * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter + */ + +Connection.prototype.watch = function(pipeline, options) { + const disconnectedError = new MongooseError('Connection ' + this.id + + ' was disconnected when calling `watch()`'); + + const changeStreamThunk = cb => { + immediate(() => { + if (this.readyState === STATES.connecting) { + this.once('open', function() { + const driverChangeStream = this.db.watch(pipeline, options); + cb(null, driverChangeStream); + }); + } else if (this.readyState === STATES.disconnected && this.db == null) { + cb(disconnectedError); + } else { + const driverChangeStream = this.db.watch(pipeline, options); + cb(null, driverChangeStream); + } + }); + }; + + const changeStream = new ChangeStream(changeStreamThunk, pipeline, options); + return changeStream; +}; + +/** + * Returns a promise that resolves when this connection + * successfully connects to MongoDB, or rejects if this connection failed + * to connect. + * + * ####Example: + * const conn = await mongoose.createConnection('mongodb://localhost:27017/test'). + * asPromise(); + * conn.readyState; // 1, means Mongoose is connected + * + * @api public + * @return {Promise} + */ + +Connection.prototype.asPromise = function asPromise() { + return this.$initialConnection; +}; + +/** + * Returns an array of model names created on this connection. + * @api public + * @return {Array} + */ + +Connection.prototype.modelNames = function() { + return Object.keys(this.models); +}; + +/** + * @brief Returns if the connection requires authentication after it is opened. Generally if a + * username and password are both provided than authentication is needed, but in some cases a + * password is not required. + * @api private + * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false. + */ +Connection.prototype.shouldAuthenticate = function() { + return this.user != null && + (this.pass != null || this.authMechanismDoesNotRequirePassword()); +}; + +/** + * @brief Returns a boolean value that specifies if the current authentication mechanism needs a + * password to authenticate according to the auth objects passed into the openUri methods. + * @api private + * @return {Boolean} true if the authentication mechanism specified in the options object requires + * a password, otherwise false. + */ +Connection.prototype.authMechanismDoesNotRequirePassword = function() { + if (this.options && this.options.auth) { + return noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= 0; + } + return true; +}; + +/** + * @brief Returns a boolean value that specifies if the provided objects object provides enough + * data to authenticate with. Generally this is true if the username and password are both specified + * but in some authentication methods, a password is not required for authentication so only a username + * is required. + * @param {Object} [options] the options object passed into the openUri methods. + * @api private + * @return {Boolean} true if the provided options object provides enough data to authenticate with, + * otherwise false. + */ +Connection.prototype.optionsProvideAuthenticationData = function(options) { + return (options) && + (options.user) && + ((options.pass) || this.authMechanismDoesNotRequirePassword()); +}; + +/** + * Returns the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance + * that this connection uses to talk to MongoDB. + * + * ####Example: + * const conn = await mongoose.createConnection('mongodb://localhost:27017/test'); + * + * conn.getClient(); // MongoClient { ... } + * + * @api public + * @return {MongoClient} + */ + +Connection.prototype.getClient = function getClient() { + return this.client; +}; + +/** + * Set the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance + * that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to + * reuse it. + * + * ####Example: + * const client = await mongodb.MongoClient.connect('mongodb://localhost:27017/test'); + * + * const conn = mongoose.createConnection().setClient(client); + * + * conn.getClient(); // MongoClient { ... } + * conn.readyState; // 1, means 'CONNECTED' + * + * @api public + * @return {Connection} this + */ + +Connection.prototype.setClient = function setClient(client) { + if (!(client instanceof mongodb.MongoClient)) { + throw new MongooseError('Must call `setClient()` with an instance of MongoClient'); + } + if (this.client != null || this.readyState !== STATES.disconnected) { + throw new MongooseError('Cannot call `setClient()` on a connection that is already connected.'); + } + if (client.topology == null) { + throw new MongooseError('Cannot call `setClient()` with a MongoClient that you have not called `connect()` on yet.'); + } + + this._connectionString = client.s.url; + _setClient(this, client, { useUnifiedTopology: client.s.options.useUnifiedTopology }, client.s.options.dbName); + + return this; +}; + +/** + * Switches to a different database using the same connection pool. + * + * Returns a new connection object, with the new db. + * + * @method useDb + * @memberOf Connection + * @param {String} name The database name + * @param {Object} [options] + * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object. + * @param {Boolean} [options.noListener=false] If true, the connection object will not make the db listen to events on the original connection. See [issue #9961](https://github.com/Automattic/mongoose/issues/9961). + * @return {Connection} New Connection Object + * @api public + */ + +/*! + * Module exports. + */ + +Connection.STATES = STATES; +module.exports = Connection; diff --git a/node_modules/mongoose/lib/connectionstate.js b/node_modules/mongoose/lib/connectionstate.js new file mode 100644 index 0000000..920f45b --- /dev/null +++ b/node_modules/mongoose/lib/connectionstate.js @@ -0,0 +1,26 @@ + +/*! + * Connection states + */ + +'use strict'; + +const STATES = module.exports = exports = Object.create(null); + +const disconnected = 'disconnected'; +const connected = 'connected'; +const connecting = 'connecting'; +const disconnecting = 'disconnecting'; +const uninitialized = 'uninitialized'; + +STATES[0] = disconnected; +STATES[1] = connected; +STATES[2] = connecting; +STATES[3] = disconnecting; +STATES[99] = uninitialized; + +STATES[disconnected] = 0; +STATES[connected] = 1; +STATES[connecting] = 2; +STATES[disconnecting] = 3; +STATES[uninitialized] = 99; diff --git a/node_modules/mongoose/lib/cursor/AggregationCursor.js b/node_modules/mongoose/lib/cursor/AggregationCursor.js new file mode 100644 index 0000000..cecc589 --- /dev/null +++ b/node_modules/mongoose/lib/cursor/AggregationCursor.js @@ -0,0 +1,375 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseError = require('../error/mongooseError'); +const Readable = require('stream').Readable; +const promiseOrCallback = require('../helpers/promiseOrCallback'); +const eachAsync = require('../helpers/cursor/eachAsync'); +const immediate = require('../helpers/immediate'); +const util = require('util'); + +/** + * An AggregationCursor is a concurrency primitive for processing aggregation + * results one document at a time. It is analogous to QueryCursor. + * + * An AggregationCursor fulfills the Node.js streams3 API, + * in addition to several other mechanisms for loading documents from MongoDB + * one at a time. + * + * Creating an AggregationCursor executes the model's pre aggregate hooks, + * but **not** the model's post aggregate hooks. + * + * Unless you're an advanced user, do **not** instantiate this class directly. + * Use [`Aggregate#cursor()`](/docs/api.html#aggregate_Aggregate-cursor) instead. + * + * @param {Aggregate} agg + * @param {Object} options + * @inherits Readable + * @event `cursor`: Emitted when the cursor is created + * @event `error`: Emitted when an error occurred + * @event `data`: Emitted when the stream is flowing and the next doc is ready + * @event `end`: Emitted when the stream is exhausted + * @api public + */ + +function AggregationCursor(agg) { + Readable.call(this, { objectMode: true }); + + this.cursor = null; + this.agg = agg; + this._transforms = []; + const model = agg._model; + delete agg.options.cursor.useMongooseAggCursor; + this._mongooseOptions = {}; + + _init(model, this, agg); +} + +util.inherits(AggregationCursor, Readable); + +/*! + * ignore + */ + +function _init(model, c, agg) { + if (!model.collection.buffer) { + model.hooks.execPre('aggregate', agg, function() { + c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {}); + c.emit('cursor', c.cursor); + }); + } else { + model.collection.emitter.once('queue', function() { + model.hooks.execPre('aggregate', agg, function() { + c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {}); + c.emit('cursor', c.cursor); + }); + }); + } +} + +/*! + * Necessary to satisfy the Readable API + */ + +AggregationCursor.prototype._read = function() { + const _this = this; + _next(this, function(error, doc) { + if (error) { + return _this.emit('error', error); + } + if (!doc) { + _this.push(null); + _this.cursor.close(function(error) { + if (error) { + return _this.emit('error', error); + } + setTimeout(function() { + // on node >= 14 streams close automatically (gh-8834) + const isNotClosedAutomatically = !_this.destroyed; + if (isNotClosedAutomatically) { + // call destroy method if exists to prevent emit twice 'close' by autoDestroy (gh-10876) + // @see https://nodejs.org/api/stream.html#stream_readable_destroy_error + if (_this.destroy) { + _this.destroy(); + } else { + _this.emit('close'); + } + } + }, 0); + }); + return; + } + _this.push(doc); + }); +}; + +if (Symbol.asyncIterator != null) { + const msg = 'Mongoose does not support using async iterators with an ' + + 'existing aggregation cursor. See http://bit.ly/mongoose-async-iterate-aggregation'; + + AggregationCursor.prototype[Symbol.asyncIterator] = function() { + throw new MongooseError(msg); + }; +} + +/** + * Registers a transform function which subsequently maps documents retrieved + * via the streams interface or `.next()` + * + * ####Example + * + * // Map documents returned by `data` events + * Thing. + * find({ name: /^hello/ }). + * cursor(). + * map(function (doc) { + * doc.foo = "bar"; + * return doc; + * }) + * on('data', function(doc) { console.log(doc.foo); }); + * + * // Or map documents returned by `.next()` + * const cursor = Thing.find({ name: /^hello/ }). + * cursor(). + * map(function (doc) { + * doc.foo = "bar"; + * return doc; + * }); + * cursor.next(function(error, doc) { + * console.log(doc.foo); + * }); + * + * @param {Function} fn + * @return {AggregationCursor} + * @api public + * @method map + */ + +AggregationCursor.prototype.map = function(fn) { + this._transforms.push(fn); + return this; +}; + +/*! + * Marks this cursor as errored + */ + +AggregationCursor.prototype._markError = function(error) { + this._error = error; + return this; +}; + +/** + * Marks this cursor as closed. Will stop streaming and subsequent calls to + * `next()` will error. + * + * @param {Function} callback + * @return {Promise} + * @api public + * @method close + * @emits close + * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close + */ + +AggregationCursor.prototype.close = function(callback) { + return promiseOrCallback(callback, cb => { + this.cursor.close(error => { + if (error) { + cb(error); + return this.listeners('error').length > 0 && this.emit('error', error); + } + this.emit('close'); + cb(null); + }); + }); +}; + +/** + * Get the next document from this cursor. Will return `null` when there are + * no documents left. + * + * @param {Function} callback + * @return {Promise} + * @api public + * @method next + */ + +AggregationCursor.prototype.next = function(callback) { + return promiseOrCallback(callback, cb => { + _next(this, cb); + }); +}; + +/** + * Execute `fn` for every document in the cursor. If `fn` returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * + * @param {Function} fn + * @param {Object} [options] + * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1. + * @param {Function} [callback] executed when all docs have been processed + * @return {Promise} + * @api public + * @method eachAsync + */ + +AggregationCursor.prototype.eachAsync = function(fn, opts, callback) { + const _this = this; + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = opts || {}; + + return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback); +}; + +/** + * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js + * You do not need to call this function explicitly, the JavaScript runtime + * will call it for you. + * + * ####Example + * + * // Async iterator without explicitly calling `cursor()`. Mongoose still + * // creates an AggregationCursor instance internally. + * const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]); + * for await (const doc of agg) { + * console.log(doc.name); + * } + * + * // You can also use an AggregationCursor instance for async iteration + * const cursor = Model.aggregate([{ $match: { age: { $gte: 25 } } }]).cursor(); + * for await (const doc of cursor) { + * console.log(doc.name); + * } + * + * Node.js 10.x supports async iterators natively without any flags. You can + * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). + * + * **Note:** This function is not set if `Symbol.asyncIterator` is undefined. If + * `Symbol.asyncIterator` is undefined, that means your Node.js version does not + * support async iterators. + * + * @method Symbol.asyncIterator + * @memberOf AggregationCursor + * @instance + * @api public + */ + +if (Symbol.asyncIterator != null) { + AggregationCursor.prototype[Symbol.asyncIterator] = function() { + return this.transformNull()._transformForAsyncIterator(); + }; +} + +/*! + * ignore + */ + +AggregationCursor.prototype._transformForAsyncIterator = function() { + if (this._transforms.indexOf(_transformForAsyncIterator) === -1) { + this.map(_transformForAsyncIterator); + } + return this; +}; + +/*! + * ignore + */ + +AggregationCursor.prototype.transformNull = function(val) { + if (arguments.length === 0) { + val = true; + } + this._mongooseOptions.transformNull = val; + return this; +}; + +/*! + * ignore + */ + +function _transformForAsyncIterator(doc) { + return doc == null ? { done: true } : { value: doc, done: false }; +} + +/** + * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). + * Useful for setting the `noCursorTimeout` and `tailable` flags. + * + * @param {String} flag + * @param {Boolean} value + * @return {AggregationCursor} this + * @api public + * @method addCursorFlag + */ + +AggregationCursor.prototype.addCursorFlag = function(flag, value) { + const _this = this; + _waitForCursor(this, function() { + _this.cursor.addCursorFlag(flag, value); + }); + return this; +}; + +/*! + * ignore + */ + +function _waitForCursor(ctx, cb) { + if (ctx.cursor) { + return cb(); + } + ctx.once('cursor', function() { + cb(); + }); +} + +/*! + * Get the next doc from the underlying cursor and mongooseify it + * (populate, etc.) + */ + +function _next(ctx, cb) { + let callback = cb; + if (ctx._transforms.length) { + callback = function(err, doc) { + if (err || (doc === null && !ctx._mongooseOptions.transformNull)) { + return cb(err, doc); + } + cb(err, ctx._transforms.reduce(function(doc, fn) { + return fn(doc); + }, doc)); + }; + } + + if (ctx._error) { + return immediate(function() { + callback(ctx._error); + }); + } + + if (ctx.cursor) { + return ctx.cursor.next(function(error, doc) { + if (error) { + return callback(error); + } + if (!doc) { + return callback(null, null); + } + + callback(null, doc); + }); + } else { + ctx.once('cursor', function() { + _next(ctx, cb); + }); + } +} + +module.exports = AggregationCursor; diff --git a/node_modules/mongoose/lib/cursor/ChangeStream.js b/node_modules/mongoose/lib/cursor/ChangeStream.js new file mode 100644 index 0000000..b3445b0 --- /dev/null +++ b/node_modules/mongoose/lib/cursor/ChangeStream.js @@ -0,0 +1,61 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const EventEmitter = require('events').EventEmitter; + +/*! + * ignore + */ + +class ChangeStream extends EventEmitter { + constructor(changeStreamThunk, pipeline, options) { + super(); + + this.driverChangeStream = null; + this.closed = false; + this.pipeline = pipeline; + this.options = options; + + // This wrapper is necessary because of buffering. + changeStreamThunk((err, driverChangeStream) => { + if (err != null) { + this.emit('error', err); + return; + } + + this.driverChangeStream = driverChangeStream; + this._bindEvents(); + this.emit('ready'); + }); + } + + _bindEvents() { + this.driverChangeStream.on('close', () => { + this.closed = true; + }); + + ['close', 'change', 'end', 'error'].forEach(ev => { + this.driverChangeStream.on(ev, data => this.emit(ev, data)); + }); + } + + _queue(cb) { + this.once('ready', () => cb()); + } + + close() { + this.closed = true; + if (this.driverChangeStream) { + this.driverChangeStream.close(); + } + } +} + +/*! + * ignore + */ + +module.exports = ChangeStream; diff --git a/node_modules/mongoose/lib/cursor/QueryCursor.js b/node_modules/mongoose/lib/cursor/QueryCursor.js new file mode 100644 index 0000000..4fc37f8 --- /dev/null +++ b/node_modules/mongoose/lib/cursor/QueryCursor.js @@ -0,0 +1,528 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const Readable = require('stream').Readable; +const promiseOrCallback = require('../helpers/promiseOrCallback'); +const eachAsync = require('../helpers/cursor/eachAsync'); +const helpers = require('../queryhelpers'); +const immediate = require('../helpers/immediate'); +const util = require('util'); + +/** + * A QueryCursor is a concurrency primitive for processing query results + * one document at a time. A QueryCursor fulfills the Node.js streams3 API, + * in addition to several other mechanisms for loading documents from MongoDB + * one at a time. + * + * QueryCursors execute the model's pre `find` hooks before loading any documents + * from MongoDB, and the model's post `find` hooks after loading each document. + * + * Unless you're an advanced user, do **not** instantiate this class directly. + * Use [`Query#cursor()`](/docs/api.html#query_Query-cursor) instead. + * + * @param {Query} query + * @param {Object} options query options passed to `.find()` + * @inherits Readable + * @event `cursor`: Emitted when the cursor is created + * @event `error`: Emitted when an error occurred + * @event `data`: Emitted when the stream is flowing and the next doc is ready + * @event `end`: Emitted when the stream is exhausted + * @api public + */ + +function QueryCursor(query, options) { + Readable.call(this, { objectMode: true }); + + this.cursor = null; + this.query = query; + const _this = this; + const model = query.model; + this._mongooseOptions = {}; + this._transforms = []; + this.model = model; + this.options = options || {}; + + model.hooks.execPre('find', query, (err) => { + if (err != null) { + _this._markError(err); + _this.listeners('error').length > 0 && _this.emit('error', err); + return; + } + this._transforms = this._transforms.concat(query._transforms.slice()); + if (this.options.transform) { + this._transforms.push(options.transform); + } + // Re: gh-8039, you need to set the `cursor.batchSize` option, top-level + // `batchSize` option doesn't work. + if (this.options.batchSize) { + this.options.cursor = options.cursor || {}; + this.options.cursor.batchSize = options.batchSize; + + // Max out the number of documents we'll populate in parallel at 5000. + this.options._populateBatchSize = Math.min(this.options.batchSize, 5000); + } + model.collection.find(query._conditions, this.options, (err, cursor) => { + if (err != null) { + _this._markError(err); + _this.listeners('error').length > 0 && _this.emit('error', _this._error); + return; + } + + if (_this._error) { + cursor.close(function() {}); + _this.listeners('error').length > 0 && _this.emit('error', _this._error); + } + _this.cursor = cursor; + _this.emit('cursor', cursor); + }); + }); +} + +util.inherits(QueryCursor, Readable); + +/*! + * Necessary to satisfy the Readable API + */ + +QueryCursor.prototype._read = function() { + const _this = this; + _next(this, function(error, doc) { + if (error) { + return _this.emit('error', error); + } + if (!doc) { + _this.push(null); + _this.cursor.close(function(error) { + if (error) { + return _this.emit('error', error); + } + setTimeout(function() { + // on node >= 14 streams close automatically (gh-8834) + const isNotClosedAutomatically = !_this.destroyed; + if (isNotClosedAutomatically) { + // call destroy method if exists to prevent emit twice 'close' by autoDestroy (gh-10876) + // https://nodejs.org/api/stream.html#stream_readable_destroy_error + if (_this.destroy) { + _this.destroy(); + } else { + _this.emit('close'); + } + } + }, 0); + }); + return; + } + _this.push(doc); + }); +}; + +/** + * Registers a transform function which subsequently maps documents retrieved + * via the streams interface or `.next()` + * + * ####Example + * + * // Map documents returned by `data` events + * Thing. + * find({ name: /^hello/ }). + * cursor(). + * map(function (doc) { + * doc.foo = "bar"; + * return doc; + * }) + * on('data', function(doc) { console.log(doc.foo); }); + * + * // Or map documents returned by `.next()` + * const cursor = Thing.find({ name: /^hello/ }). + * cursor(). + * map(function (doc) { + * doc.foo = "bar"; + * return doc; + * }); + * cursor.next(function(error, doc) { + * console.log(doc.foo); + * }); + * + * @param {Function} fn + * @return {QueryCursor} + * @api public + * @method map + */ + +QueryCursor.prototype.map = function(fn) { + this._transforms.push(fn); + return this; +}; + +/*! + * Marks this cursor as errored + */ + +QueryCursor.prototype._markError = function(error) { + this._error = error; + return this; +}; + +/** + * Marks this cursor as closed. Will stop streaming and subsequent calls to + * `next()` will error. + * + * @param {Function} callback + * @return {Promise} + * @api public + * @method close + * @emits close + * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close + */ + +QueryCursor.prototype.close = function(callback) { + return promiseOrCallback(callback, cb => { + this.cursor.close(error => { + if (error) { + cb(error); + return this.listeners('error').length > 0 && this.emit('error', error); + } + this.emit('close'); + cb(null); + }); + }, this.model.events); +}; + +/** + * Get the next document from this cursor. Will return `null` when there are + * no documents left. + * + * @param {Function} callback + * @return {Promise} + * @api public + * @method next + */ + +QueryCursor.prototype.next = function(callback) { + return promiseOrCallback(callback, cb => { + _next(this, function(error, doc) { + if (error) { + return cb(error); + } + cb(null, doc); + }); + }, this.model.events); +}; + +/** + * Execute `fn` for every document in the cursor. If `fn` returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * + * ####Example + * + * // Iterate over documents asynchronously + * Thing. + * find({ name: /^hello/ }). + * cursor(). + * eachAsync(async function (doc, i) { + * doc.foo = doc.bar + i; + * await doc.save(); + * }) + * + * @param {Function} fn + * @param {Object} [options] + * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1. + * @param {Function} [callback] executed when all docs have been processed + * @return {Promise} + * @api public + * @method eachAsync + */ + +QueryCursor.prototype.eachAsync = function(fn, opts, callback) { + const _this = this; + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = opts || {}; + + return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback); +}; + +/** + * The `options` passed in to the `QueryCursor` constructor. + * + * @api public + * @property options + */ + +QueryCursor.prototype.options; + +/** + * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). + * Useful for setting the `noCursorTimeout` and `tailable` flags. + * + * @param {String} flag + * @param {Boolean} value + * @return {AggregationCursor} this + * @api public + * @method addCursorFlag + */ + +QueryCursor.prototype.addCursorFlag = function(flag, value) { + const _this = this; + _waitForCursor(this, function() { + _this.cursor.addCursorFlag(flag, value); + }); + return this; +}; + +/*! + * ignore + */ + +QueryCursor.prototype.transformNull = function(val) { + if (arguments.length === 0) { + val = true; + } + this._mongooseOptions.transformNull = val; + return this; +}; + +/*! + * ignore + */ + +QueryCursor.prototype._transformForAsyncIterator = function() { + if (this._transforms.indexOf(_transformForAsyncIterator) === -1) { + this.map(_transformForAsyncIterator); + } + return this; +}; + +/** + * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js). + * You do not need to call this function explicitly, the JavaScript runtime + * will call it for you. + * + * ####Example + * + * // Works without using `cursor()` + * for await (const doc of Model.find([{ $sort: { name: 1 } }])) { + * console.log(doc.name); + * } + * + * // Can also use `cursor()` + * for await (const doc of Model.find([{ $sort: { name: 1 } }]).cursor()) { + * console.log(doc.name); + * } + * + * Node.js 10.x supports async iterators natively without any flags. You can + * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). + * + * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If + * `Symbol.asyncIterator` is undefined, that means your Node.js version does not + * support async iterators. + * + * @method Symbol.asyncIterator + * @memberOf Query + * @instance + * @api public + */ + +if (Symbol.asyncIterator != null) { + QueryCursor.prototype[Symbol.asyncIterator] = function() { + return this.transformNull()._transformForAsyncIterator(); + }; +} + +/*! + * ignore + */ + +function _transformForAsyncIterator(doc) { + return doc == null ? { done: true } : { value: doc, done: false }; +} + +/*! + * Get the next doc from the underlying cursor and mongooseify it + * (populate, etc.) + */ + +function _next(ctx, cb) { + let callback = cb; + if (ctx._transforms.length) { + callback = function(err, doc) { + if (err || (doc === null && !ctx._mongooseOptions.transformNull)) { + return cb(err, doc); + } + cb(err, ctx._transforms.reduce(function(doc, fn) { + return fn.call(ctx, doc); + }, doc)); + }; + } + + if (ctx._error) { + return immediate(function() { + callback(ctx._error); + }); + } + + if (ctx.cursor) { + if (ctx.query._mongooseOptions.populate && !ctx._pop) { + ctx._pop = helpers.preparePopulationOptionsMQ(ctx.query, + ctx.query._mongooseOptions); + ctx._pop.__noPromise = true; + } + if (ctx.query._mongooseOptions.populate && ctx.options._populateBatchSize > 1) { + if (ctx._batchDocs && ctx._batchDocs.length) { + // Return a cached populated doc + return _nextDoc(ctx, ctx._batchDocs.shift(), ctx._pop, callback); + } else if (ctx._batchExhausted) { + // Internal cursor reported no more docs. Act the same here + return callback(null, null); + } else { + // Request as many docs as batchSize, to populate them also in batch + ctx._batchDocs = []; + return ctx.cursor.next(_onNext.bind({ ctx, callback })); + } + } else { + return ctx.cursor.next(function(error, doc) { + if (error) { + return callback(error); + } + if (!doc) { + return callback(null, null); + } + + if (!ctx.query._mongooseOptions.populate) { + return _nextDoc(ctx, doc, null, callback); + } + + ctx.query.model.populate(doc, ctx._pop, function(err, doc) { + if (err) { + return callback(err); + } + return _nextDoc(ctx, doc, ctx._pop, callback); + }); + }); + } + } else { + ctx.once('error', cb); + + ctx.once('cursor', function(cursor) { + ctx.removeListener('error', cb); + if (cursor == null) { + return; + } + _next(ctx, cb); + }); + } +} + +/*! + * ignore + */ + +function _onNext(error, doc) { + if (error) { + return this.callback(error); + } + if (!doc) { + this.ctx._batchExhausted = true; + return _populateBatch.call(this); + } + + this.ctx._batchDocs.push(doc); + + if (this.ctx._batchDocs.length < this.ctx.options._populateBatchSize) { + // If both `batchSize` and `_populateBatchSize` are huge, calling `next()` repeatedly may + // cause a stack overflow. So make sure we clear the stack regularly. + if (this.ctx._batchDocs.length > 0 && this.ctx._batchDocs.length % 1000 === 0) { + return immediate(() => this.ctx.cursor.next(_onNext.bind(this))); + } + this.ctx.cursor.next(_onNext.bind(this)); + } else { + _populateBatch.call(this); + } +} + +/*! + * ignore + */ + +function _populateBatch() { + if (!this.ctx._batchDocs.length) { + return this.callback(null, null); + } + const _this = this; + this.ctx.query.model.populate(this.ctx._batchDocs, this.ctx._pop, function(err) { + if (err) { + return _this.callback(err); + } + + _nextDoc(_this.ctx, _this.ctx._batchDocs.shift(), _this.ctx._pop, _this.callback); + }); +} + +/*! + * ignore + */ + +function _nextDoc(ctx, doc, pop, callback) { + if (ctx.query._mongooseOptions.lean) { + return ctx.model.hooks.execPost('find', ctx.query, [[doc]], err => { + if (err != null) { + return callback(err); + } + callback(null, doc); + }); + } + + _create(ctx, doc, pop, (err, doc) => { + if (err != null) { + return callback(err); + } + ctx.model.hooks.execPost('find', ctx.query, [[doc]], err => { + if (err != null) { + return callback(err); + } + callback(null, doc); + }); + }); +} + +/*! + * ignore + */ + +function _waitForCursor(ctx, cb) { + if (ctx.cursor) { + return cb(); + } + ctx.once('cursor', function(cursor) { + if (cursor == null) { + return; + } + cb(); + }); +} + +/*! + * Convert a raw doc into a full mongoose doc. + */ + +function _create(ctx, doc, populatedIds, cb) { + const instance = helpers.createModel(ctx.query.model, doc, ctx.query._fields); + const opts = populatedIds ? + { populated: populatedIds } : + undefined; + + instance.$init(doc, opts, function(err) { + if (err) { + return cb(err); + } + cb(null, instance); + }); +} + +module.exports = QueryCursor; diff --git a/node_modules/mongoose/lib/document.js b/node_modules/mongoose/lib/document.js new file mode 100644 index 0000000..3e61626 --- /dev/null +++ b/node_modules/mongoose/lib/document.js @@ -0,0 +1,4362 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const EventEmitter = require('events').EventEmitter; +const InternalCache = require('./internal'); +const MongooseError = require('./error/index'); +const MixedSchema = require('./schema/mixed'); +const ObjectExpectedError = require('./error/objectExpected'); +const ObjectParameterError = require('./error/objectParameter'); +const ParallelValidateError = require('./error/parallelValidate'); +const Schema = require('./schema'); +const StrictModeError = require('./error/strict'); +const ValidationError = require('./error/validation'); +const ValidatorError = require('./error/validator'); +const VirtualType = require('./virtualtype'); +const promiseOrCallback = require('./helpers/promiseOrCallback'); +const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths'); +const compile = require('./helpers/document/compile').compile; +const defineKey = require('./helpers/document/compile').defineKey; +const flatten = require('./helpers/common').flatten; +const flattenObjectWithDottedPaths = require('./helpers/path/flattenObjectWithDottedPaths'); +const get = require('./helpers/get'); +const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath'); +const getKeysInSchemaOrder = require('./helpers/schema/getKeysInSchemaOrder'); +const handleSpreadDoc = require('./helpers/document/handleSpreadDoc'); +const immediate = require('./helpers/immediate'); +const isDefiningProjection = require('./helpers/projection/isDefiningProjection'); +const isExclusive = require('./helpers/projection/isExclusive'); +const inspect = require('util').inspect; +const internalToObjectOptions = require('./options').internalToObjectOptions; +const markArraySubdocsPopulated = require('./helpers/populate/markArraySubdocsPopulated'); +const mpath = require('mpath'); +const queryhelpers = require('./queryhelpers'); +const utils = require('./utils'); +const isPromise = require('./helpers/isPromise'); + +const clone = utils.clone; +const deepEqual = utils.deepEqual; +const isMongooseObject = utils.isMongooseObject; + +const arrayAtomicsBackupSymbol = require('./helpers/symbols').arrayAtomicsBackupSymbol; +const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol; +const documentArrayParent = require('./helpers/symbols').documentArrayParent; +const documentIsModified = require('./helpers/symbols').documentIsModified; +const documentModifiedPaths = require('./helpers/symbols').documentModifiedPaths; +const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol; +const getSymbol = require('./helpers/symbols').getSymbol; +const populateModelSymbol = require('./helpers/symbols').populateModelSymbol; +const scopeSymbol = require('./helpers/symbols').scopeSymbol; +const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol; +const parentPaths = require('./helpers/path/parentPaths'); +let DocumentArray; +let MongooseArray; +let Embedded; + +const specialProperties = utils.specialProperties; + +/** + * The core Mongoose document constructor. You should not call this directly, + * the Mongoose [Model constructor](./api.html#Model) calls this for you. + * + * @param {Object} obj the values to set + * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data + * @param {Object} [options] various configuration options for the document + * @param {Boolean} [options.defaults=true] if `false`, skip applying default values to this document. + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted on a document after it has been retrieved from the db and fully hydrated by Mongoose. + * @event `save`: Emitted when the document is successfully saved + * @api private + */ + +function Document(obj, fields, skipId, options) { + if (typeof skipId === 'object' && skipId != null) { + options = skipId; + skipId = options.skipId; + } + options = Object.assign({}, options); + + // Support `browserDocument.js` syntax + if (this.$__schema == null) { + const _schema = utils.isObject(fields) && !fields.instanceOfSchema ? + new Schema(fields) : + fields; + this.$__setSchema(_schema); + fields = skipId; + skipId = options; + options = arguments[4] || {}; + } + + this.$__ = new InternalCache; + this.$__.emitter = new EventEmitter(); + this.$isNew = 'isNew' in options ? options.isNew : true; + + if ('priorDoc' in options) { + this.$__.priorDoc = options.priorDoc; + } + + if (obj != null && typeof obj !== 'object') { + throw new ObjectParameterError(obj, 'obj', 'Document'); + } + + let defaults = true; + if (options.defaults !== undefined) { + this.$__.defaults = options.defaults; + defaults = options.defaults; + } + + const schema = this.$__schema; + + if (typeof fields === 'boolean' || fields === 'throw') { + this.$__.strictMode = fields; + fields = undefined; + } else { + this.$__.strictMode = schema.options.strict; + if (fields !== undefined) { + this.$__.selected = fields; + } + } + + const requiredPaths = schema.requiredPaths(true); + for (const path of requiredPaths) { + this.$__.activePaths.require(path); + } + + this.$__.emitter.setMaxListeners(0); + + let exclude = null; + + // determine if this doc is a result of a query with + // excluded fields + if (utils.isPOJO(fields)) { + exclude = isExclusive(fields); + } + + const hasIncludedChildren = exclude === false && fields ? + $__hasIncludedChildren(fields) : + {}; + + if (this._doc == null) { + this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false); + + // By default, defaults get applied **before** setting initial values + // Re: gh-6155 + if (defaults) { + $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, true, { + isNew: this.$isNew + }); + } + } + if (obj) { + // Skip set hooks + if (this.$__original_set) { + this.$__original_set(obj, undefined, true); + } else { + this.$set(obj, undefined, true); + } + + if (obj instanceof Document) { + this.$isNew = obj.$isNew; + } + } + + // Function defaults get applied **after** setting initial values so they + // see the full doc rather than an empty one, unless they opt out. + // Re: gh-3781, gh-6155 + if (options.willInit && defaults) { + EventEmitter.prototype.once.call(this, 'init', () => { + $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { + isNew: this.$isNew + }); + }); + } else if (defaults) { + $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { + isNew: this.$isNew + }); + } + + this.$__._id = this._id; + + if (!this.$__.strictMode && obj) { + const _this = this; + const keys = Object.keys(this._doc); + + keys.forEach(function(key) { + if (!(key in schema.tree)) { + defineKey({ prop: key, subprops: null, prototype: _this }); + } + }); + } + + applyQueue(this); +} + +Object.defineProperty(Document.prototype, 'isNew', { + get: function() { + return this.$isNew; + }, + set: function(value) { + this.$isNew = value; + } +}); + +Object.defineProperty(Document.prototype, 'errors', { + get: function() { + return this.$errors; + }, + set: function(value) { + this.$errors = value; + } +}); +/*! + * Document exposes the NodeJS event emitter API, so you can use + * `on`, `once`, etc. + */ +utils.each( + ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', + 'removeAllListeners', 'addListener'], + function(emitterFn) { + Document.prototype[emitterFn] = function() { + return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments); + }; + Document.prototype[`$${emitterFn}`] = Document.prototype[emitterFn]; + }); + +Document.prototype.constructor = Document; + +for (const i in EventEmitter.prototype) { + Document[i] = EventEmitter.prototype[i]; +} + +/** + * The document's internal schema. + * + * @api private + * @property schema + * @memberOf Document + * @instance + */ + +Document.prototype.$__schema; + +/** + * The document's schema. + * + * @api public + * @property schema + * @memberOf Document + * @instance + */ + +Document.prototype.schema; + +/** + * Empty object that you can use for storing properties on the document. This + * is handy for passing data to middleware without conflicting with Mongoose + * internals. + * + * ####Example: + * + * schema.pre('save', function() { + * // Mongoose will set `isNew` to `false` if `save()` succeeds + * this.$locals.wasNew = this.isNew; + * }); + * + * schema.post('save', function() { + * // Prints true if `isNew` was set before `save()` + * console.log(this.$locals.wasNew); + * }); + * + * @api public + * @property $locals + * @memberOf Document + * @instance + */ + +Object.defineProperty(Document.prototype, '$locals', { + configurable: false, + enumerable: false, + get: function() { + if (this.$__.locals == null) { + this.$__.locals = {}; + } + return this.$__.locals; + }, + set: function(v) { + this.$__.locals = v; + } +}); + + +/** + * Boolean flag specifying if the document is new. + * + * @api public + * @property $isNew + * @memberOf Document + * @instance + */ + +Document.prototype.$isNew; + +/** + * Boolean flag specifying if the document is new. + * + * @api public + * @property isNew + * @memberOf Document + * @instance + */ + +Document.prototype.isNew; + +/** + * Set this property to add additional query filters when Mongoose saves this document and `isNew` is false. + * + * ####Example: + * + * // Make sure `save()` never updates a soft deleted document. + * schema.pre('save', function() { + * this.$where = { isDeleted: false }; + * }); + * + * @api public + * @property $where + * @memberOf Document + * @instance + */ + +Object.defineProperty(Document.prototype, '$where', { + configurable: false, + enumerable: false, + writable: true +}); + +/** + * The string version of this documents _id. + * + * ####Note: + * + * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. + * + * new Schema({ name: String }, { id: false }); + * + * @api public + * @see Schema options /docs/guide.html#options + * @property id + * @memberOf Document + * @instance + */ + +Document.prototype.id; + +/** + * Hash containing current validation $errors. + * + * @api public + * @property $errors + * @memberOf Document + * @instance + */ + +Document.prototype.$errors; + +/** + * Hash containing current validation errors. + * + * @api public + * @property errors + * @memberOf Document + * @instance + */ + +Document.prototype.errors; + +/** + * A string containing the current operation that Mongoose is executing + * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`. + * + * ####Example: + * + * const doc = new Model({ name: 'test' }); + * doc.$op; // null + * + * const promise = doc.save(); + * doc.$op; // 'save' + * + * await promise; + * doc.$op; // null + * + * @api public + * @property $op + * @memberOf Document + * @instance + */ + +Object.defineProperty(Document.prototype, '$op', { + get: function() { + return this.$__.op || null; + }, + set: function(value) { + this.$__.op = value; + } +}); + +/*! + * ignore + */ + +function $__hasIncludedChildren(fields) { + const hasIncludedChildren = {}; + const keys = Object.keys(fields); + + for (const key of keys) { + const parts = key.split('.'); + const c = []; + + for (const part of parts) { + c.push(part); + hasIncludedChildren[c.join('.')] = 1; + } + } + + return hasIncludedChildren; +} + +/*! + * ignore + */ + +function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) { + const paths = Object.keys(doc.$__schema.paths); + const plen = paths.length; + + for (let i = 0; i < plen; ++i) { + let def; + let curPath = ''; + const p = paths[i]; + + if (p === '_id' && skipId) { + continue; + } + + const type = doc.$__schema.paths[p]; + const path = type.splitPath(); + const len = path.length; + let included = false; + let doc_ = doc._doc; + for (let j = 0; j < len; ++j) { + if (doc_ == null) { + break; + } + + const piece = path[j]; + curPath += (!curPath.length ? '' : '.') + piece; + + if (exclude === true) { + if (curPath in fields) { + break; + } + } else if (exclude === false && fields && !included) { + if (curPath in fields) { + included = true; + } else if (!hasIncludedChildren[curPath]) { + break; + } + } + + if (j === len - 1) { + if (doc_[piece] !== void 0) { + break; + } + + if (typeof type.defaultValue === 'function') { + if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) { + break; + } + if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) { + break; + } + } else if (!isBeforeSetters) { + // Non-function defaults should always run **before** setters + continue; + } + + if (pathsToSkip && pathsToSkip[curPath]) { + break; + } + + if (fields && exclude !== null) { + if (exclude === true) { + // apply defaults to all non-excluded fields + if (p in fields) { + continue; + } + + try { + def = type.getDefault(doc, false); + } catch (err) { + doc.invalidate(p, err); + break; + } + + if (typeof def !== 'undefined') { + doc_[piece] = def; + doc.$__.activePaths.default(p); + } + } else if (included) { + // selected field + try { + def = type.getDefault(doc, false); + } catch (err) { + doc.invalidate(p, err); + break; + } + + if (typeof def !== 'undefined') { + doc_[piece] = def; + doc.$__.activePaths.default(p); + } + } + } else { + try { + def = type.getDefault(doc, false); + } catch (err) { + doc.invalidate(p, err); + break; + } + + if (typeof def !== 'undefined') { + doc_[piece] = def; + doc.$__.activePaths.default(p); + } + } + } else { + doc_ = doc_[piece]; + } + } + } +} + +/*! + * ignore + */ + +function $applyDefaultsToNested(val, path, doc) { + if (val == null) { + return; + } + + flattenObjectWithDottedPaths(val); + + const paths = Object.keys(doc.$__schema.paths); + const plen = paths.length; + + const pathPieces = path.indexOf('.') === -1 ? [path] : path.split('.'); + + for (let i = 0; i < plen; ++i) { + let curPath = ''; + const p = paths[i]; + + if (!p.startsWith(path + '.')) { + continue; + } + + const type = doc.$__schema.paths[p]; + const pieces = type.splitPath().slice(pathPieces.length); + const len = pieces.length; + + if (type.defaultValue === void 0) { + continue; + } + + let cur = val; + + for (let j = 0; j < len; ++j) { + if (cur == null) { + break; + } + + const piece = pieces[j]; + + if (j === len - 1) { + if (cur[piece] !== void 0) { + break; + } + + try { + const def = type.getDefault(doc, false); + if (def !== void 0) { + cur[piece] = def; + } + } catch (err) { + doc.invalidate(path + '.' + curPath, err); + break; + } + + break; + } + + curPath += (!curPath.length ? '' : '.') + piece; + + cur[piece] = cur[piece] || {}; + cur = cur[piece]; + } + } +} + +/** + * Builds the default doc structure + * + * @param {Object} obj + * @param {Object} [fields] + * @param {Boolean} [skipId] + * @api private + * @method $__buildDoc + * @memberOf Document + * @instance + */ + +Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) { + const doc = {}; + + const paths = Object.keys(this.$__schema.paths). + // Don't build up any paths that are underneath a map, we don't know + // what the keys will be + filter(p => !p.includes('$*')); + const plen = paths.length; + let ii = 0; + + for (; ii < plen; ++ii) { + const p = paths[ii]; + + if (p === '_id') { + if (skipId) { + continue; + } + if (obj && '_id' in obj) { + continue; + } + } + + const path = this.$__schema.paths[p].splitPath(); + const len = path.length; + const last = len - 1; + let curPath = ''; + let doc_ = doc; + let included = false; + + for (let i = 0; i < len; ++i) { + const piece = path[i]; + + curPath += (!curPath.length ? '' : '.') + piece; + + // support excluding intermediary levels + if (exclude === true) { + if (curPath in fields) { + break; + } + } else if (exclude === false && fields && !included) { + if (curPath in fields) { + included = true; + } else if (!hasIncludedChildren[curPath]) { + break; + } + } + + if (i < last) { + doc_ = doc_[piece] || (doc_[piece] = {}); + } + } + } + + this._doc = doc; +}; + +/*! + * Converts to POJO when you use the document for querying + */ + +Document.prototype.toBSON = function() { + return this.toObject(internalToObjectOptions); +}; + +/** + * Initializes the document without setters or marking anything modified. + * + * Called internally after a document is returned from mongodb. Normally, + * you do **not** need to call this function on your own. + * + * This function triggers `init` [middleware](/docs/middleware.html). + * Note that `init` hooks are [synchronous](/docs/middleware.html#synchronous). + * + * @param {Object} doc document returned by mongo + * @api public + * @memberOf Document + * @instance + */ + +Document.prototype.init = function(doc, opts, fn) { + if (typeof opts === 'function') { + fn = opts; + opts = null; + } + + this.$__init(doc, opts); + + if (fn) { + fn(null, this); + } + + return this; +}; + +Document.prototype.$init = function() { + return this.constructor.prototype.init.apply(this, arguments); +}; + +/*! + * ignore + */ + +Document.prototype.$__init = function(doc, opts) { + this.$isNew = false; + this.$init = true; + opts = opts || {}; + + // handle docs with populated paths + // If doc._id is not null or undefined + if (doc._id != null && opts.populated && opts.populated.length) { + const id = String(doc._id); + for (const item of opts.populated) { + if (item.isVirtual) { + this.$populated(item.path, utils.getValue(item.path, doc), item); + } else { + this.$populated(item.path, item._docs[id], item); + } + + if (item._childDocs == null) { + continue; + } + for (const child of item._childDocs) { + if (child == null || child.$__ == null) { + continue; + } + child.$__.parent = this; + } + item._childDocs = []; + } + } + + init(this, doc, this._doc, opts); + + markArraySubdocsPopulated(this, opts.populated); + + this.$emit('init', this); + this.constructor.emit('init', this); + + this.$__._id = this._id; + return this; +}; + +/*! + * Init helper. + * + * @param {Object} self document instance + * @param {Object} obj raw mongodb doc + * @param {Object} doc object we are initializing + * @api private + */ + +function init(self, obj, doc, opts, prefix) { + prefix = prefix || ''; + + const keys = Object.keys(obj); + const len = keys.length; + let schema; + let path; + let i; + let index = 0; + const strict = self.$__.strictMode; + + while (index < len) { + _init(index++); + } + + function _init(index) { + i = keys[index]; + path = prefix + i; + schema = self.$__schema.path(path); + + // Should still work if not a model-level discriminator, but should not be + // necessary. This is *only* to catch the case where we queried using the + // base model and the discriminated model has a projection + if (self.$__schema.$isRootDiscriminator && !self.$__isSelected(path)) { + return; + } + + if (!schema && utils.isPOJO(obj[i])) { + // assume nested object + if (!doc[i]) { + doc[i] = {}; + } + init(self, obj[i], doc[i], opts, path + '.'); + } else if (!schema) { + doc[i] = obj[i]; + if (!strict) { + self[i] = obj[i]; + } + } else { + // Retain order when overwriting defaults + if (doc.hasOwnProperty(i) && obj[i] !== void 0) { + delete doc[i]; + } + if (obj[i] === null) { + doc[i] = schema._castNullish(null); + } else if (obj[i] !== undefined) { + const intCache = obj[i].$__ || {}; + const wasPopulated = intCache.wasPopulated || null; + + if (schema && !wasPopulated) { + try { + doc[i] = schema.cast(obj[i], self, true); + } catch (e) { + self.invalidate(e.path, new ValidatorError({ + path: e.path, + message: e.message, + type: 'cast', + value: e.value, + reason: e + })); + } + } else { + doc[i] = obj[i]; + } + } + // mark as hydrated + if (!self.$isModified(path)) { + self.$__.activePaths.init(path); + } + } + } +} + +/** + * Sends an update command with this document `_id` as the query selector. + * + * ####Example: + * + * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback); + * + * ####Valid options: + * + * - same as in [Model.update](#model_Model.update) + * + * @see Model.update #model_Model.update + * @param {Object} doc + * @param {Object} options + * @param {Function} callback + * @return {Query} + * @api public + * @memberOf Document + * @instance + */ + +Document.prototype.update = function update() { + const args = utils.args(arguments); + args.unshift({ _id: this._id }); + const query = this.constructor.update.apply(this.constructor, args); + + if (this.$session() != null) { + if (!('session' in query.options)) { + query.options.session = this.$session(); + } + } + + return query; +}; + +/** + * Sends an updateOne command with this document `_id` as the query selector. + * + * ####Example: + * + * weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback); + * + * ####Valid options: + * + * - same as in [Model.updateOne](#model_Model.updateOne) + * + * @see Model.updateOne #model_Model.updateOne + * @param {Object} doc + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Function} callback + * @return {Query} + * @api public + * @memberOf Document + * @instance + */ + +Document.prototype.updateOne = function updateOne(doc, options, callback) { + const query = this.constructor.updateOne({ _id: this._id }, doc, options); + query.pre(cb => { + this.constructor._middleware.execPre('updateOne', this, [this], cb); + }); + query.post(cb => { + this.constructor._middleware.execPost('updateOne', this, [this], {}, cb); + }); + + if (this.$session() != null) { + if (!('session' in query.options)) { + query.options.session = this.$session(); + } + } + + if (callback != null) { + return query.exec(callback); + } + + return query; +}; + +/** + * Sends a replaceOne command with this document `_id` as the query selector. + * + * ####Valid options: + * + * - same as in [Model.replaceOne](https://mongoosejs.com/docs/api/model.html#model_Model.replaceOne) + * + * @see Model.replaceOne #model_Model.replaceOne + * @param {Object} doc + * @param {Object} options + * @param {Function} callback + * @return {Query} + * @api public + * @memberOf Document + * @instance + */ + +Document.prototype.replaceOne = function replaceOne() { + const args = utils.args(arguments); + args.unshift({ _id: this._id }); + return this.constructor.replaceOne.apply(this.constructor, args); +}; + +/** + * Getter/setter around the session associated with this document. Used to + * automatically set `session` if you `save()` a doc that you got from a + * query with an associated session. + * + * ####Example: + * + * const session = MyModel.startSession(); + * const doc = await MyModel.findOne().session(session); + * doc.$session() === session; // true + * doc.$session(null); + * doc.$session() === null; // true + * + * If this is a top-level document, setting the session propagates to all child + * docs. + * + * @param {ClientSession} [session] overwrite the current session + * @return {ClientSession} + * @method $session + * @api public + * @memberOf Document + */ + +Document.prototype.$session = function $session(session) { + if (arguments.length === 0) { + if (this.$__.session != null && this.$__.session.hasEnded) { + this.$__.session = null; + return null; + } + return this.$__.session; + } + + if (session != null && session.hasEnded) { + throw new MongooseError('Cannot set a document\'s session to a session that has ended. Make sure you haven\'t ' + + 'called `endSession()` on the session you are passing to `$session()`.'); + } + + this.$__.session = session; + + if (!this.ownerDocument) { + const subdocs = this.$getAllSubdocs(); + for (const child of subdocs) { + child.$session(session); + } + } + + return session; +}; + +/** + * Overwrite all values in this document with the values of `obj`, except + * for immutable properties. Behaves similarly to `set()`, except for it + * unsets all properties that aren't in `obj`. + * + * @param {Object} obj the object to overwrite this document with + * @method overwrite + * @name overwrite + * @memberOf Document + * @instance + * @api public + */ + +Document.prototype.overwrite = function overwrite(obj) { + const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj)))); + + for (const key of keys) { + if (key === '_id') { + continue; + } + // Explicitly skip version key + if (this.$__schema.options.versionKey && key === this.$__schema.options.versionKey) { + continue; + } + if (this.$__schema.options.discriminatorKey && key === this.$__schema.options.discriminatorKey) { + continue; + } + this.$set(key, obj[key]); + } + + return this; +}; + +/** + * Alias for `set()`, used internally to avoid conflicts + * + * @param {String|Object} path path or object of key/vals to set + * @param {Any} val the value to set + * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes + * @param {Object} [options] optionally specify options that modify the behavior of the set + * @method $set + * @name $set + * @memberOf Document + * @instance + * @api public + */ + +Document.prototype.$set = function $set(path, val, type, options) { + if (utils.isPOJO(type)) { + options = type; + type = undefined; + } + + options = options || {}; + const merge = options.merge; + const adhoc = type && type !== true; + const constructing = type === true; + const typeKey = this.$__schema.options.typeKey; + let adhocs; + let keys; + let i = 0; + let pathtype; + let key; + let prefix; + + const strict = 'strict' in options + ? options.strict + : this.$__.strictMode; + + if (adhoc) { + adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); + adhocs[path] = this.$__schema.interpretAsType(path, type, this.$__schema.options); + } + + if (path == null) { + [path, val] = [val, path]; + } else if (typeof path !== 'string') { + // new Document({ key: val }) + if (path instanceof Document) { + if (path.$__isNested) { + path = path.toObject(); + } else { + path = path._doc; + } + } + if (path == null) { + [path, val] = [val, path]; + } + + prefix = val ? val + '.' : ''; + keys = getKeysInSchemaOrder(this.$__schema, path); + + const len = keys.length; + + // `_skipMinimizeTopLevel` is because we may have deleted the top-level + // nested key to ensure key order. + const _skipMinimizeTopLevel = get(options, '_skipMinimizeTopLevel', false); + if (len === 0 && _skipMinimizeTopLevel) { + delete options._skipMinimizeTopLevel; + if (val) { + this.$set(val, {}); + } + return this; + } + + for (let i = 0; i < len; ++i) { + key = keys[i]; + const pathName = prefix + key; + pathtype = this.$__schema.pathType(pathName); + const valForKey = path[key]; + + // On initial set, delete any nested keys if we're going to overwrite + // them to ensure we keep the user's key order. + if (type === true && + !prefix && + path[key] != null && + pathtype === 'nested' && + this._doc[key] != null) { + delete this._doc[key]; + // Make sure we set `{}` back even if we minimize re: gh-8565 + options = Object.assign({}, options, { _skipMinimizeTopLevel: true }); + } else { + // Make sure we set `{_skipMinimizeTopLevel: false}` if don't have overwrite: gh-10441 + options = Object.assign({}, options, { _skipMinimizeTopLevel: false }); + } + + if (utils.isNonBuiltinObject(valForKey) && pathtype === 'nested') { + $applyDefaultsToNested(path[key], prefix + key, this); + this.$set(prefix + key, path[key], constructing, Object.assign({}, options, { _skipMarkModified: true })); + continue; + } else if (strict) { + // Don't overwrite defaults with undefined keys (gh-3981) (gh-9039) + if (constructing && path[key] === void 0 && + this.$get(pathName) !== void 0) { + continue; + } + + if (pathtype === 'adhocOrUndefined') { + pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true }); + } + + if (pathtype === 'real' || pathtype === 'virtual') { + // Check for setting single embedded schema to document (gh-3535) + let p = path[key]; + if (this.$__schema.paths[pathName] && + this.$__schema.paths[pathName].$isSingleNested && + path[key] instanceof Document) { + p = p.toObject({ virtuals: false, transform: false }); + } + this.$set(prefix + key, p, constructing, options); + } else if (pathtype === 'nested' && path[key] instanceof Document) { + this.$set(prefix + key, + path[key].toObject({ transform: false }), constructing, options); + } else if (strict === 'throw') { + if (pathtype === 'nested') { + throw new ObjectExpectedError(key, path[key]); + } else { + throw new StrictModeError(key); + } + } + } else if (path[key] !== void 0) { + this.$set(prefix + key, path[key], constructing, options); + } + } + + // Ensure all properties are in correct order by deleting and recreating every property. + for (const key of Object.keys(this.$__schema.tree)) { + if (this._doc.hasOwnProperty(key)) { + const val = this._doc[key]; + delete this._doc[key]; + this._doc[key] = val; + } + } + + return this; + } + + let pathType = this.$__schema.pathType(path); + if (pathType === 'adhocOrUndefined') { + pathType = getEmbeddedDiscriminatorPath(this, path, { typeOnly: true }); + } + + // Assume this is a Mongoose document that was copied into a POJO using + // `Object.assign()` or `{...doc}` + val = handleSpreadDoc(val); + + // if this doc is being constructed we should not trigger getters + const priorVal = (() => { + if (this.$__.priorDoc != null) { + return this.$__.priorDoc.$__getValue(path); + } + if (constructing) { + return void 0; + } + return this.$__getValue(path); + })(); + + if (pathType === 'nested' && val) { + if (typeof val === 'object' && val != null) { + const hasInitialVal = this.$__.savedState != null && this.$__.savedState.hasOwnProperty(path); + if (this.$__.savedState != null && !this.$isNew && !this.$__.savedState.hasOwnProperty(path)) { + const initialVal = this.$__getValue(path); + this.$__.savedState[path] = initialVal; + + const keys = Object.keys(initialVal || {}); + for (const key of keys) { + this.$__.savedState[path + '.' + key] = initialVal[key]; + } + } + + if (!merge) { + this.$__setValue(path, null); + cleanModifiedSubpaths(this, path); + } else { + return this.$set(val, path, constructing); + } + + const keys = getKeysInSchemaOrder(this.$__schema, val, path); + + this.$__setValue(path, {}); + for (const key of keys) { + this.$set(path + '.' + key, val[key], constructing, options); + } + if (priorVal != null && utils.deepEqual(hasInitialVal ? this.$__.savedState[path] : priorVal, val)) { + this.unmarkModified(path); + } else { + this.markModified(path); + } + cleanModifiedSubpaths(this, path, { skipDocArrays: true }); + return this; + } + this.invalidate(path, new MongooseError.CastError('Object', val, path)); + return this; + } + + let schema; + const parts = path.indexOf('.') === -1 ? [path] : path.split('.'); + + // Might need to change path for top-level alias + if (typeof this.$__schema.aliases[parts[0]] == 'string') { + parts[0] = this.$__schema.aliases[parts[0]]; + } + + if (pathType === 'adhocOrUndefined' && strict) { + // check for roots that are Mixed types + let mixed; + + for (i = 0; i < parts.length; ++i) { + const subpath = parts.slice(0, i + 1).join('.'); + + // If path is underneath a virtual, bypass everything and just set it. + if (i + 1 < parts.length && this.$__schema.pathType(subpath) === 'virtual') { + mpath.set(path, val, this); + return this; + } + + schema = this.$__schema.path(subpath); + if (schema == null) { + continue; + } + + if (schema instanceof MixedSchema) { + // allow changes to sub paths of mixed types + mixed = true; + break; + } + } + + if (schema == null) { + // Check for embedded discriminators + schema = getEmbeddedDiscriminatorPath(this, path); + } + + if (!mixed && !schema) { + if (strict === 'throw') { + throw new StrictModeError(path); + } + return this; + } + } else if (pathType === 'virtual') { + schema = this.$__schema.virtualpath(path); + schema.applySetters(val, this); + return this; + } else { + schema = this.$__path(path); + } + + // gh-4578, if setting a deeply nested path that doesn't exist yet, create it + let cur = this._doc; + let curPath = ''; + for (i = 0; i < parts.length - 1; ++i) { + cur = cur[parts[i]]; + curPath += (curPath.length > 0 ? '.' : '') + parts[i]; + if (!cur) { + this.$set(curPath, {}); + // Hack re: gh-5800. If nested field is not selected, it probably exists + // so `MongoServerError: cannot use the part (nested of nested.num) to + // traverse the element ({nested: null})` is not likely. If user gets + // that error, its their fault for now. We should reconsider disallowing + // modifying not selected paths for 6.x + if (!this.$__isSelected(curPath)) { + this.unmarkModified(curPath); + } + cur = this.$__getValue(curPath); + } + } + + let pathToMark; + + // When using the $set operator the path to the field must already exist. + // Else mongodb throws: "LEFT_SUBFIELD only supports Object" + + if (parts.length <= 1) { + pathToMark = path; + } else { + for (i = 0; i < parts.length; ++i) { + const subpath = parts.slice(0, i + 1).join('.'); + if (this.$get(subpath, null, { getters: false }) === null) { + pathToMark = subpath; + break; + } + } + + if (!pathToMark) { + pathToMark = path; + } + } + + if (!schema) { + this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal); + return this; + } + + // If overwriting a subdocument path, make sure to clear out + // any errors _before_ setting, so new errors that happen + // get persisted. Re: #9080 + if (schema.$isSingleNested || schema.$isMongooseArray) { + _markValidSubpaths(this, path); + } + + if (schema.$isSingleNested && val != null && merge) { + if (val instanceof Document) { + val = val.toObject({ virtuals: false, transform: false }); + } + const keys = Object.keys(val); + for (const key of keys) { + this.$set(path + '.' + key, val[key], constructing, options); + } + + return this; + } + + let shouldSet = true; + try { + // If the user is trying to set a ref path to a document with + // the correct model name, treat it as populated + const refMatches = (() => { + if (schema.options == null) { + return false; + } + if (!(val instanceof Document)) { + return false; + } + const model = val.constructor; + + // Check ref + const ref = schema.options.ref; + if (ref != null && (ref === model.modelName || ref === model.baseModelName)) { + return true; + } + + // Check refPath + const refPath = schema.options.refPath; + if (refPath == null) { + return false; + } + const modelName = val.get(refPath); + return modelName === model.modelName || modelName === model.baseModelName; + })(); + + let didPopulate = false; + if (refMatches && val instanceof Document) { + this.$populated(path, val._id, { [populateModelSymbol]: val.constructor }); + val.$__.wasPopulated = true; + didPopulate = true; + } + + let popOpts; + if (schema.options && + Array.isArray(schema.options[typeKey]) && + schema.options[typeKey].length && + schema.options[typeKey][0].ref && + _isManuallyPopulatedArray(val, schema.options[typeKey][0].ref)) { + popOpts = { [populateModelSymbol]: val[0].constructor }; + this.$populated(path, val.map(function(v) { return v._id; }), popOpts); + + for (const doc of val) { + doc.$__.wasPopulated = true; + } + didPopulate = true; + } + + if (this.$__schema.singleNestedPaths[path] == null) { + // If this path is underneath a single nested schema, we'll call the setter + // later in `$__set()` because we don't take `_doc` when we iterate through + // a single nested doc. That's to make sure we get the correct context. + // Otherwise we would double-call the setter, see gh-7196. + val = schema.applySetters(val, this, false, priorVal); + } + + if (schema.$isMongooseDocumentArray && + Array.isArray(val) && + val.length > 0 && + val[0] != null && + val[0].$__ != null && + val[0].$__.populated != null) { + const populatedPaths = Object.keys(val[0].$__.populated); + for (const populatedPath of populatedPaths) { + this.$populated(path + '.' + populatedPath, + val.map(v => v.$populated(populatedPath)), + val[0].$__.populated[populatedPath].options); + } + didPopulate = true; + } + + if (!didPopulate && this.$__.populated) { + // If this array partially contains populated documents, convert them + // all to ObjectIds re: #8443 + if (Array.isArray(val) && this.$__.populated[path]) { + for (let i = 0; i < val.length; ++i) { + if (val[i] instanceof Document) { + val.set(i, val[i]._id, true); + } + } + } + delete this.$__.populated[path]; + } + + if (schema.$isSingleNested && val != null) { + _checkImmutableSubpaths(val, schema, priorVal); + } + + this.$markValid(path); + } catch (e) { + if (e instanceof MongooseError.StrictModeError && e.isImmutableError) { + this.invalidate(path, e); + } else if (e instanceof MongooseError.CastError) { + this.invalidate(e.path, e); + if (e.$originalErrorPath) { + this.invalidate(path, + new MongooseError.CastError(schema.instance, val, path, e.$originalErrorPath)); + } + } else { + this.invalidate(path, + new MongooseError.CastError(schema.instance, val, path, e)); + } + shouldSet = false; + } + + if (shouldSet) { + const doc = this.ownerDocument ? this.ownerDocument() : this; + const savedState = doc.$__.savedState; + const savedStatePath = this.ownerDocument ? this.$__.fullPath + '.' + path : path; + if (savedState != null) { + const firstDot = savedStatePath.indexOf('.'); + const topLevelPath = firstDot === -1 ? savedStatePath : savedStatePath.slice(0, firstDot); + if (!savedState.hasOwnProperty(topLevelPath)) { + savedState[topLevelPath] = utils.clone(doc.$__getValue(topLevelPath)); + } + } + + this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal); + + if (savedState != null && savedState.hasOwnProperty(savedStatePath) && utils.deepEqual(val, savedState[savedStatePath])) { + this.unmarkModified(path); + } + } + + if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) { + cleanModifiedSubpaths(this, path); + } + + return this; +}; + +/*! + * ignore + */ + +function _isManuallyPopulatedArray(val, ref) { + if (!Array.isArray(val)) { + return false; + } + if (val.length === 0) { + return false; + } + + for (const el of val) { + if (!(el instanceof Document)) { + return false; + } + const modelName = el.constructor.modelName; + if (modelName == null) { + return false; + } + if (el.constructor.modelName != ref && el.constructor.baseModelName != ref) { + return false; + } + } + + return true; +} + +/** + * Sets the value of a path, or many paths. + * + * ####Example: + * + * // path, value + * doc.set(path, value) + * + * // object + * doc.set({ + * path : value + * , path2 : { + * path : value + * } + * }) + * + * // on-the-fly cast to number + * doc.set(path, value, Number) + * + * // on-the-fly cast to string + * doc.set(path, value, String) + * + * // changing strict mode behavior + * doc.set(path, value, { strict: false }); + * + * @param {String|Object} path path or object of key/vals to set + * @param {Any} val the value to set + * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes + * @param {Object} [options] optionally specify options that modify the behavior of the set + * @api public + * @method set + * @memberOf Document + * @instance + */ + +Document.prototype.set = Document.prototype.$set; + +/** + * Determine if we should mark this change as modified. + * + * @return {Boolean} + * @api private + * @method $__shouldModify + * @memberOf Document + * @instance + */ + +Document.prototype.$__shouldModify = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) { + if (options._skipMarkModified) { + return false; + } + if (this.$isNew) { + return true; + } + + // Re: the note about gh-7196, `val` is the raw value without casting or + // setters if the full path is under a single nested subdoc because we don't + // want to double run setters. So don't set it as modified. See gh-7264. + if (this.$__schema.singleNestedPaths[path] != null) { + return false; + } + + if (val === void 0 && !this.$__isSelected(path)) { + // when a path is not selected in a query, its initial + // value will be undefined. + return true; + } + + if (val === void 0 && path in this.$__.activePaths.states.default) { + // we're just unsetting the default value which was never saved + return false; + } + + // gh-3992: if setting a populated field to a doc, don't mark modified + // if they have the same _id + if (this.$populated(path) && + val instanceof Document && + deepEqual(val._id, priorVal)) { + return false; + } + + if (!deepEqual(val, priorVal || utils.getValue(path, this))) { + return true; + } + + if (!constructing && + val !== null && + val !== undefined && + path in this.$__.activePaths.states.default && + deepEqual(val, schema.getDefault(this, constructing))) { + // a path with a default was $unset on the server + // and the user is setting it to the same value again + return true; + } + return false; +}; + +/** + * Handles the actual setting of the value and marking the path modified if appropriate. + * + * @api private + * @method $__set + * @memberOf Document + * @instance + */ + +Document.prototype.$__set = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) { + Embedded = Embedded || require('./types/ArraySubdocument'); + + const shouldModify = this.$__shouldModify(pathToMark, path, options, constructing, parts, + schema, val, priorVal); + const _this = this; + + if (shouldModify) { + this.markModified(pathToMark); + + // handle directly setting arrays (gh-1126) + MongooseArray || (MongooseArray = require('./types/array')); + if (val && val.isMongooseArray) { + val._registerAtomic('$set', val); + + // Update embedded document parent references (gh-5189) + if (val.isMongooseDocumentArray) { + val.forEach(function(item) { + item && item.__parentArray && (item.__parentArray = val); + }); + } + + // Small hack for gh-1638: if we're overwriting the entire array, ignore + // paths that were modified before the array overwrite + this.$__.activePaths.forEach(function(modifiedPath) { + if (modifiedPath.startsWith(path + '.')) { + _this.$__.activePaths.ignore(modifiedPath); + } + }); + } + } else if (Array.isArray(val) && val.isMongooseArray && Array.isArray(priorVal) && priorVal.isMongooseArray) { + val[arrayAtomicsSymbol] = priorVal[arrayAtomicsSymbol]; + val[arrayAtomicsBackupSymbol] = priorVal[arrayAtomicsBackupSymbol]; + } + + let obj = this._doc; + let i = 0; + const l = parts.length; + let cur = ''; + + for (; i < l; i++) { + const next = i + 1; + const last = next === l; + cur += (cur ? '.' + parts[i] : parts[i]); + if (specialProperties.has(parts[i])) { + return; + } + + if (last) { + if (obj instanceof Map) { + obj.set(parts[i], val); + } else { + obj[parts[i]] = val; + } + } else { + if (utils.isPOJO(obj[parts[i]])) { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { + obj = obj[parts[i]]; + } else { + obj[parts[i]] = obj[parts[i]] || {}; + obj = obj[parts[i]]; + } + } + } +}; + +/** + * Gets a raw value from a path (no getters) + * + * @param {String} path + * @api private + */ + +Document.prototype.$__getValue = function(path) { + return utils.getValue(path, this._doc); +}; + +/** + * Sets a raw value for a path (no casting, setters, transformations) + * + * @param {String} path + * @param {Object} value + * @api private + */ + +Document.prototype.$__setValue = function(path, val) { + utils.setValue(path, val, this._doc); + return this; +}; + +/** + * Returns the value of a path. + * + * ####Example + * + * // path + * doc.get('age') // 47 + * + * // dynamic casting to a string + * doc.get('age', String) // "47" + * + * @param {String} path + * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes + * @param {Object} [options] + * @param {Boolean} [options.virtuals=false] Apply virtuals before getting this path + * @param {Boolean} [options.getters=true] If false, skip applying getters and just get the raw value + * @api public + */ + +Document.prototype.get = function(path, type, options) { + let adhoc; + options = options || {}; + if (type) { + adhoc = this.$__schema.interpretAsType(path, type, this.$__schema.options); + } + + let schema = this.$__path(path); + if (schema == null) { + schema = this.$__schema.virtualpath(path); + } + if (schema instanceof MixedSchema) { + const virtual = this.$__schema.virtualpath(path); + if (virtual != null) { + schema = virtual; + } + } + const pieces = path.indexOf('.') === -1 ? [path] : path.split('.'); + let obj = this._doc; + + if (schema instanceof VirtualType) { + return schema.applyGetters(void 0, this); + } + + // Might need to change path for top-level alias + if (typeof this.$__schema.aliases[pieces[0]] == 'string') { + pieces[0] = this.$__schema.aliases[pieces[0]]; + } + + for (let i = 0, l = pieces.length; i < l; i++) { + if (obj && obj._doc) { + obj = obj._doc; + } + + if (obj == null) { + obj = void 0; + } else if (obj instanceof Map) { + obj = obj.get(pieces[i], { getters: false }); + } else if (i === l - 1) { + obj = utils.getValue(pieces[i], obj); + } else { + obj = obj[pieces[i]]; + } + } + + if (adhoc) { + obj = adhoc.cast(obj); + } + + if (schema != null && options.getters !== false) { + obj = schema.applyGetters(obj, this); + } else if (this.$__schema.nested[path] && options.virtuals) { + // Might need to apply virtuals if this is a nested path + return applyVirtuals(this, utils.clone(obj) || {}, { path: path }); + } + + return obj; +}; + +/*! + * ignore + */ + +Document.prototype[getSymbol] = Document.prototype.get; +Document.prototype.$get = Document.prototype.get; +/** + * Returns the schematype for the given `path`. + * + * @param {String} path + * @api private + * @method $__path + * @memberOf Document + * @instance + */ + +Document.prototype.$__path = function(path) { + const adhocs = this.$__.adhocPaths; + const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null; + + if (adhocType) { + return adhocType; + } + return this.$__schema.path(path); +}; + +/** + * Marks the path as having pending changes to write to the db. + * + * _Very helpful when using [Mixed](./schematypes.html#mixed) types._ + * + * ####Example: + * + * doc.mixed.type = 'changed'; + * doc.markModified('mixed.type'); + * doc.save() // changes to mixed.type are now persisted + * + * @param {String} path the path to mark modified + * @param {Document} [scope] the scope to run validators with + * @api public + */ + +Document.prototype.markModified = function(path, scope) { + this.$__.activePaths.modify(path); + if (scope != null && !this.ownerDocument) { + this.$__.pathsToScopes = this.$__pathsToScopes || {}; + this.$__.pathsToScopes[path] = scope; + } +}; + +/** + * Clears the modified state on the specified path. + * + * ####Example: + * + * doc.foo = 'bar'; + * doc.unmarkModified('foo'); + * doc.save(); // changes to foo will not be persisted + * + * @param {String} path the path to unmark modified + * @api public + */ + +Document.prototype.unmarkModified = function(path) { + this.$__.activePaths.init(path); + if (this.$__.pathsToScopes != null) { + delete this.$__.pathsToScopes[path]; + } +}; + +/** + * Don't run validation on this path or persist changes to this path. + * + * ####Example: + * + * doc.foo = null; + * doc.$ignore('foo'); + * doc.save(); // changes to foo will not be persisted and validators won't be run + * + * @memberOf Document + * @instance + * @method $ignore + * @param {String} path the path to ignore + * @api public + */ + +Document.prototype.$ignore = function(path) { + this.$__.activePaths.ignore(path); +}; + +/** + * Returns the list of paths that have been directly modified. A direct + * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`, + * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`. + * + * A path `a` may be in `modifiedPaths()` but not in `directModifiedPaths()` + * because a child of `a` was directly modified. + * + * ####Example + * const schema = new Schema({ foo: String, nested: { bar: String } }); + * const Model = mongoose.model('Test', schema); + * await Model.create({ foo: 'original', nested: { bar: 'original' } }); + * + * const doc = await Model.findOne(); + * doc.nested.bar = 'modified'; + * doc.directModifiedPaths(); // ['nested.bar'] + * doc.modifiedPaths(); // ['nested', 'nested.bar'] + * + * @return {Array} + * @api public + */ + +Document.prototype.directModifiedPaths = function() { + return Object.keys(this.$__.activePaths.states.modify); +}; + +/** + * Returns true if the given path is nullish or only contains empty objects. + * Useful for determining whether this subdoc will get stripped out by the + * [minimize option](/docs/guide.html#minimize). + * + * ####Example: + * const schema = new Schema({ nested: { foo: String } }); + * const Model = mongoose.model('Test', schema); + * const doc = new Model({}); + * doc.$isEmpty('nested'); // true + * doc.nested.$isEmpty(); // true + * + * doc.nested.foo = 'bar'; + * doc.$isEmpty('nested'); // false + * doc.nested.$isEmpty(); // false + * + * @memberOf Document + * @instance + * @api public + * @method $isEmpty + * @return {Boolean} + */ + +Document.prototype.$isEmpty = function(path) { + const isEmptyOptions = { + minimize: true, + virtuals: false, + getters: false, + transform: false + }; + + if (arguments.length > 0) { + const v = this.$get(path); + if (v == null) { + return true; + } + if (typeof v !== 'object') { + return false; + } + if (utils.isPOJO(v)) { + return _isEmpty(v); + } + return Object.keys(v.toObject(isEmptyOptions)).length === 0; + } + + return Object.keys(this.toObject(isEmptyOptions)).length === 0; +}; + +function _isEmpty(v) { + if (v == null) { + return true; + } + if (typeof v !== 'object' || Array.isArray(v)) { + return false; + } + for (const key of Object.keys(v)) { + if (!_isEmpty(v[key])) { + return false; + } + } + return true; +} + +/** + * Returns the list of paths that have been modified. + * + * @param {Object} [options] + * @param {Boolean} [options.includeChildren=false] if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`. + * @return {Array} + * @api public + */ + +Document.prototype.modifiedPaths = function(options) { + options = options || {}; + const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); + const _this = this; + return directModifiedPaths.reduce(function(list, path) { + const parts = path.split('.'); + list = list.concat(parts.reduce(function(chains, part, i) { + return chains.concat(parts.slice(0, i).concat(part).join('.')); + }, []).filter(function(chain) { + return (list.indexOf(chain) === -1); + })); + + if (!options.includeChildren) { + return list; + } + + let cur = _this.$get(path); + if (cur != null && typeof cur === 'object') { + if (cur._doc) { + cur = cur._doc; + } + if (Array.isArray(cur)) { + const len = cur.length; + for (let i = 0; i < len; ++i) { + if (list.indexOf(path + '.' + i) === -1) { + list.push(path + '.' + i); + if (cur[i] != null && cur[i].$__) { + const modified = cur[i].modifiedPaths(); + for (const childPath of modified) { + list.push(path + '.' + i + '.' + childPath); + } + } + } + } + } else { + Object.keys(cur). + filter(function(key) { + return list.indexOf(path + '.' + key) === -1; + }). + forEach(function(key) { + list.push(path + '.' + key); + }); + } + } + + return list; + }, []); +}; + +Document.prototype[documentModifiedPaths] = Document.prototype.modifiedPaths; + +/** + * Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path + * in this document is modified. + * + * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. + * + * ####Example + * + * doc.set('documents.0.title', 'changed'); + * doc.isModified() // true + * doc.isModified('documents') // true + * doc.isModified('documents.0.title') // true + * doc.isModified('documents otherProp') // true + * doc.isDirectModified('documents') // false + * + * @param {String} [path] optional + * @return {Boolean} + * @api public + */ + +Document.prototype.isModified = function(paths, modifiedPaths) { + if (paths) { + if (!Array.isArray(paths)) { + paths = paths.split(' '); + } + const modified = modifiedPaths || this[documentModifiedPaths](); + const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); + const isModifiedChild = paths.some(function(path) { + return !!~modified.indexOf(path); + }); + + return isModifiedChild || paths.some(function(path) { + return directModifiedPaths.some(function(mod) { + return mod === path || path.startsWith(mod + '.'); + }); + }); + } + + return this.$__.activePaths.some('modify'); +}; + +Document.prototype.$isModified = Document.prototype.isModified; + +Document.prototype[documentIsModified] = Document.prototype.isModified; + +/** + * Checks if a path is set to its default. + * + * ####Example + * + * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} }); + * const m = new MyModel(); + * m.$isDefault('name'); // true + * + * @memberOf Document + * @instance + * @method $isDefault + * @param {String} [path] + * @return {Boolean} + * @api public + */ + +Document.prototype.$isDefault = function(path) { + if (path == null) { + return this.$__.activePaths.some('default'); + } + + if (typeof path === 'string' && path.indexOf(' ') === -1) { + return this.$__.activePaths.states.default.hasOwnProperty(path); + } + + let paths = path; + if (!Array.isArray(paths)) { + paths = paths.split(' '); + } + + return paths.some(path => this.$__.activePaths.states.default.hasOwnProperty(path)); +}; + +/** + * Getter/setter, determines whether the document was removed or not. + * + * ####Example: + * const product = await product.remove(); + * product.$isDeleted(); // true + * product.remove(); // no-op, doesn't send anything to the db + * + * product.$isDeleted(false); + * product.$isDeleted(); // false + * product.remove(); // will execute a remove against the db + * + * + * @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted + * @return {Boolean} whether mongoose thinks this doc is deleted. + * @method $isDeleted + * @memberOf Document + * @instance + * @api public + */ + +Document.prototype.$isDeleted = function(val) { + if (arguments.length === 0) { + return !!this.$__.isDeleted; + } + + this.$__.isDeleted = !!val; + return this; +}; + +/** + * Returns true if `path` was directly set and modified, else false. + * + * ####Example + * + * doc.set('documents.0.title', 'changed'); + * doc.isDirectModified('documents.0.title') // true + * doc.isDirectModified('documents') // false + * + * @param {String|Array} path + * @return {Boolean} + * @api public + */ + +Document.prototype.isDirectModified = function(path) { + if (path == null) { + return this.$__.activePaths.some('modify'); + } + + if (typeof path === 'string' && path.indexOf(' ') === -1) { + return this.$__.activePaths.states.modify.hasOwnProperty(path); + } + + let paths = path; + if (!Array.isArray(paths)) { + paths = paths.split(' '); + } + + return paths.some(path => this.$__.activePaths.states.modify.hasOwnProperty(path)); +}; + +/** + * Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since. + * + * @param {String} path + * @return {Boolean} + * @api public + */ + +Document.prototype.isInit = function(path) { + if (path == null) { + return this.$__.activePaths.some('init'); + } + + if (typeof path === 'string' && path.indexOf(' ') === -1) { + return this.$__.activePaths.states.init.hasOwnProperty(path); + } + + let paths = path; + if (!Array.isArray(paths)) { + paths = paths.split(' '); + } + + return paths.some(path => this.$__.activePaths.states.init.hasOwnProperty(path)); +}; + +/** + * Checks if `path` was selected in the source query which initialized this document. + * + * ####Example + * + * const doc = await Thing.findOne().select('name'); + * doc.isSelected('name') // true + * doc.isSelected('age') // false + * + * @param {String|Array} path + * @return {Boolean} + * @api public + */ + +Document.prototype.isSelected = function isSelected(path) { + if (this.$__.selected == null) { + return true; + } + + if (path === '_id') { + return this.$__.selected._id !== 0; + } + + if (path.indexOf(' ') !== -1) { + path = path.split(' '); + } + if (Array.isArray(path)) { + return path.some(p => this.$__isSelected(p)); + } + + const paths = Object.keys(this.$__.selected); + let inclusive = null; + + if (paths.length === 1 && paths[0] === '_id') { + // only _id was selected. + return this.$__.selected._id === 0; + } + + for (const cur of paths) { + if (cur === '_id') { + continue; + } + if (!isDefiningProjection(this.$__.selected[cur])) { + continue; + } + inclusive = !!this.$__.selected[cur]; + break; + } + + if (inclusive === null) { + return true; + } + + if (path in this.$__.selected) { + return inclusive; + } + + const pathDot = path + '.'; + + for (const cur of paths) { + if (cur === '_id') { + continue; + } + + if (cur.startsWith(pathDot)) { + return inclusive || cur !== pathDot; + } + + if (pathDot.startsWith(cur + '.')) { + return inclusive; + } + } + + return !inclusive; +}; + +Document.prototype.$__isSelected = Document.prototype.isSelected; + +/** + * Checks if `path` was explicitly selected. If no projection, always returns + * true. + * + * ####Example + * + * Thing.findOne().select('nested.name').exec(function (err, doc) { + * doc.isDirectSelected('nested.name') // true + * doc.isDirectSelected('nested.otherName') // false + * doc.isDirectSelected('nested') // false + * }) + * + * @param {String} path + * @return {Boolean} + * @api public + */ + +Document.prototype.isDirectSelected = function isDirectSelected(path) { + if (this.$__.selected == null) { + return true; + } + + if (path === '_id') { + return this.$__.selected._id !== 0; + } + + if (path.indexOf(' ') !== -1) { + path = path.split(' '); + } + if (Array.isArray(path)) { + return path.some(p => this.isDirectSelected(p)); + } + + const paths = Object.keys(this.$__.selected); + let inclusive = null; + + if (paths.length === 1 && paths[0] === '_id') { + // only _id was selected. + return this.$__.selected._id === 0; + } + + for (const cur of paths) { + if (cur === '_id') { + continue; + } + if (!isDefiningProjection(this.$__.selected[cur])) { + continue; + } + inclusive = !!this.$__.selected[cur]; + break; + } + + if (inclusive === null) { + return true; + } + + if (this.$__.selected.hasOwnProperty(path)) { + return inclusive; + } + + return !inclusive; +}; + +/** + * Executes registered validation rules for this document. + * + * ####Note: + * + * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`. + * + * ####Example: + * + * doc.validate(function (err) { + * if (err) handleError(err); + * else // validation passed + * }); + * + * @param {Array|String} [pathsToValidate] list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list. + * @param {Object} [options] internal options + * @param {Boolean} [options.validateModifiedOnly=false] if `true` mongoose validates only modified paths. + * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. + * @param {Function} [callback] optional callback called after validation completes, passing an error if one occurred + * @return {Promise} Promise + * @api public + */ + +Document.prototype.validate = function(pathsToValidate, options, callback) { + let parallelValidate; + this.$op = 'validate'; + + if (this.ownerDocument != null) { + // Skip parallel validate check for subdocuments + } else if (this.$__.validating) { + parallelValidate = new ParallelValidateError(this, { + parentStack: options && options.parentStack, + conflictStack: this.$__.validating.stack + }); + } else { + this.$__.validating = new ParallelValidateError(this, { parentStack: options && options.parentStack }); + } + + if (arguments.length === 1) { + if (typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) { + options = arguments[0]; + callback = null; + pathsToValidate = null; + } else if (typeof arguments[0] === 'function') { + callback = arguments[0]; + options = null; + pathsToValidate = null; + } + } else if (typeof pathsToValidate === 'function') { + callback = pathsToValidate; + options = null; + pathsToValidate = null; + } else if (typeof options === 'function') { + callback = options; + options = pathsToValidate; + pathsToValidate = null; + } + if (options && typeof options.pathsToSkip === 'string') { + const isOnePathOnly = options.pathsToSkip.indexOf(' ') === -1; + options.pathsToSkip = isOnePathOnly ? [options.pathsToSkip] : options.pathsToSkip.split(' '); + } + + return promiseOrCallback(callback, cb => { + if (parallelValidate != null) { + return cb(parallelValidate); + } + + this.$__validate(pathsToValidate, options, (error) => { + this.$op = null; + cb(error); + }); + }, this.constructor.events); +}; + +Document.prototype.$validate = Document.prototype.validate; + +/*! + * ignore + */ + +function _evaluateRequiredFunctions(doc) { + Object.keys(doc.$__.activePaths.states.require).forEach(path => { + const p = doc.$__schema.path(path); + + if (p != null && typeof p.originalRequiredValue === 'function') { + doc.$__.cachedRequired = doc.$__.cachedRequired || {}; + doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc, doc); + } + }); +} + +/*! + * ignore + */ + +function _getPathsToValidate(doc) { + const skipSchemaValidators = {}; + + _evaluateRequiredFunctions(doc); + // only validate required fields when necessary + let paths = new Set(Object.keys(doc.$__.activePaths.states.require).filter(function(path) { + if (!doc.$__isSelected(path) && !doc.$isModified(path)) { + return false; + } + if (doc.$__.cachedRequired != null && path in doc.$__.cachedRequired) { + return doc.$__.cachedRequired[path]; + } + return true; + })); + + + Object.keys(doc.$__.activePaths.states.init).forEach(addToPaths); + Object.keys(doc.$__.activePaths.states.modify).forEach(addToPaths); + Object.keys(doc.$__.activePaths.states.default).forEach(addToPaths); + function addToPaths(p) { paths.add(p); } + + const subdocs = doc.$getAllSubdocs(); + const modifiedPaths = doc.modifiedPaths(); + for (const subdoc of subdocs) { + if (subdoc.$basePath) { + // Remove child paths for now, because we'll be validating the whole + // subdoc + for (const p of paths) { + if (p === null || p.startsWith(subdoc.$basePath + '.')) { + paths.delete(p); + } + } + + if (doc.$isModified(subdoc.$basePath, modifiedPaths) && + !doc.isDirectModified(subdoc.$basePath) && + !doc.$isDefault(subdoc.$basePath)) { + paths.add(subdoc.$basePath); + + skipSchemaValidators[subdoc.$basePath] = true; + } + } + } + + // from here on we're not removing items from paths + + // gh-661: if a whole array is modified, make sure to run validation on all + // the children as well + for (const path of paths) { + const _pathType = doc.$__schema.path(path); + if (!_pathType || + !_pathType.$isMongooseArray || + // To avoid potential performance issues, skip doc arrays whose children + // are not required. `getPositionalPathType()` may be slow, so avoid + // it unless we have a case of #6364 + (_pathType.$isMongooseDocumentArray && !get(_pathType, 'schemaOptions.required'))) { + continue; + } + + const val = doc.$__getValue(path); + _pushNestedArrayPaths(val, paths, path); + } + + function _pushNestedArrayPaths(val, paths, path) { + if (val != null) { + const numElements = val.length; + for (let j = 0; j < numElements; ++j) { + if (Array.isArray(val[j])) { + _pushNestedArrayPaths(val[j], paths, path + '.' + j); + } else { + paths.add(path + '.' + j); + } + } + } + } + + const flattenOptions = { skipArrays: true }; + for (const pathToCheck of paths) { + if (doc.$__schema.nested[pathToCheck]) { + let _v = doc.$__getValue(pathToCheck); + if (isMongooseObject(_v)) { + _v = _v.toObject({ transform: false }); + } + const flat = flatten(_v, pathToCheck, flattenOptions, doc.$__schema); + Object.keys(flat).forEach(addToPaths); + } + } + + for (const path of paths) { + // Single nested paths (paths embedded under single nested subdocs) will + // be validated on their own when we call `validate()` on the subdoc itself. + // Re: gh-8468 + if (doc.$__schema.singleNestedPaths.hasOwnProperty(path)) { + paths.delete(path); + continue; + } + const _pathType = doc.$__schema.path(path); + if (!_pathType || !_pathType.$isSchemaMap) { + continue; + } + + const val = doc.$__getValue(path); + if (val == null) { + continue; + } + for (const key of val.keys()) { + paths.add(path + '.' + key); + } + } + + paths = Array.from(paths); + return [paths, skipSchemaValidators]; +} + +/*! + * ignore + */ + +Document.prototype.$__validate = function(pathsToValidate, options, callback) { + if (typeof pathsToValidate === 'function') { + callback = pathsToValidate; + options = null; + pathsToValidate = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } + + const hasValidateModifiedOnlyOption = options && + (typeof options === 'object') && + ('validateModifiedOnly' in options); + + const pathsToSkip = get(options, 'pathsToSkip', null); + + let shouldValidateModifiedOnly; + if (hasValidateModifiedOnlyOption) { + shouldValidateModifiedOnly = !!options.validateModifiedOnly; + } else { + shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly; + } + + const _this = this; + const _complete = () => { + let validationError = this.$__.validationError; + this.$__.validationError = undefined; + + if (shouldValidateModifiedOnly && validationError != null) { + // Remove any validation errors that aren't from modified paths + const errors = Object.keys(validationError.errors); + for (const errPath of errors) { + if (!this.$isModified(errPath)) { + delete validationError.errors[errPath]; + } + } + if (Object.keys(validationError.errors).length === 0) { + validationError = void 0; + } + } + + this.$__.cachedRequired = {}; + this.$emit('validate', _this); + this.constructor.emit('validate', _this); + + this.$__.validating = null; + if (validationError) { + for (const key in validationError.errors) { + // Make sure cast errors persist + if (!this[documentArrayParent] && + validationError.errors[key] instanceof MongooseError.CastError) { + this.invalidate(key, validationError.errors[key]); + } + } + + return validationError; + } + }; + + // only validate required fields when necessary + const pathDetails = _getPathsToValidate(this); + let paths = shouldValidateModifiedOnly ? + pathDetails[0].filter((path) => this.$isModified(path)) : + pathDetails[0]; + const skipSchemaValidators = pathDetails[1]; + if (typeof pathsToValidate === 'string') { + pathsToValidate = pathsToValidate.split(' '); + } + if (Array.isArray(pathsToValidate)) { + paths = _handlePathsToValidate(paths, pathsToValidate); + } else if (pathsToSkip) { + paths = _handlePathsToSkip(paths, pathsToSkip); + } + if (paths.length === 0) { + return immediate(function() { + const error = _complete(); + if (error) { + return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { + callback(error); + }); + } + callback(null, _this); + }); + } + + const validated = {}; + let total = 0; + + for (const path of paths) { + validatePath(path); + } + + function validatePath(path) { + if (path == null || validated[path]) { + return; + } + + validated[path] = true; + total++; + + immediate(function() { + const schemaType = _this.$__schema.path(path); + + if (!schemaType) { + return --total || complete(); + } + + // If user marked as invalid or there was a cast error, don't validate + if (!_this.$isValid(path)) { + --total || complete(); + return; + } + + // If setting a path under a mixed path, avoid using the mixed path validator (gh-10141) + if (schemaType[schemaMixedSymbol] != null && path !== schemaType.path) { + return --total || complete(); + } + + let val = _this.$__getValue(path); + + // If you `populate()` and get back a null value, required validators + // shouldn't fail (gh-8018). We should always fall back to the populated + // value. + let pop; + if ((pop = _this.$populated(path))) { + val = pop; + } else if (val != null && val.$__ != null && val.$__.wasPopulated) { + // Array paths, like `somearray.1`, do not show up as populated with `$populated()`, + // so in that case pull out the document's id + val = val._id; + } + const scope = _this.$__.pathsToScopes != null && path in _this.$__.pathsToScopes ? + _this.$__.pathsToScopes[path] : + _this; + + const doValidateOptions = { + skipSchemaValidators: skipSchemaValidators[path], + path: path, + validateModifiedOnly: shouldValidateModifiedOnly + }; + + schemaType.doValidate(val, function(err) { + if (err) { + const isSubdoc = schemaType.$isSingleNested || + schemaType.$isArraySubdocument || + schemaType.$isMongooseDocumentArray; + if (isSubdoc && err instanceof ValidationError) { + return --total || complete(); + } + _this.invalidate(path, err, undefined, true); + } + --total || complete(); + }, scope, doValidateOptions); + }); + } + + function complete() { + const error = _complete(); + if (error) { + return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { + callback(error); + }); + } + callback(null, _this); + } + +}; + +/*! + * ignore + */ + +function _handlePathsToValidate(paths, pathsToValidate) { + const _pathsToValidate = new Set(pathsToValidate); + const parentPaths = new Map([]); + for (const path of pathsToValidate) { + if (path.indexOf('.') === -1) { + continue; + } + const pieces = path.split('.'); + let cur = pieces[0]; + for (let i = 1; i < pieces.length; ++i) { + // Since we skip subpaths under single nested subdocs to + // avoid double validation, we need to add back the + // single nested subpath if the user asked for it (gh-8626) + parentPaths.set(cur, path); + cur = cur + '.' + pieces[i]; + } + } + + const ret = []; + for (const path of paths) { + if (_pathsToValidate.has(path)) { + ret.push(path); + } else if (parentPaths.has(path)) { + ret.push(parentPaths.get(path)); + } + } + return ret; +} + +/*! + * ignore + */ +function _handlePathsToSkip(paths, pathsToSkip) { + pathsToSkip = new Set(pathsToSkip); + paths = paths.filter(p => !pathsToSkip.has(p)); + return paths; +} + +/** + * Executes registered validation rules (skipping asynchronous validators) for this document. + * + * ####Note: + * + * This method is useful if you need synchronous validation. + * + * ####Example: + * + * const err = doc.validateSync(); + * if (err) { + * handleError(err); + * } else { + * // validation passed + * } + * + * @param {Array|string} pathsToValidate only validate the given paths + * @param {Object} [options] options for validation + * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. + * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. + * @return {ValidationError|undefined} ValidationError if there are errors during validation, or undefined if there is no error. + * @api public + */ + +Document.prototype.validateSync = function(pathsToValidate, options) { + const _this = this; + + if (arguments.length === 1 && typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) { + options = arguments[0]; + pathsToValidate = null; + } + + const hasValidateModifiedOnlyOption = options && + (typeof options === 'object') && + ('validateModifiedOnly' in options); + + let shouldValidateModifiedOnly; + if (hasValidateModifiedOnlyOption) { + shouldValidateModifiedOnly = !!options.validateModifiedOnly; + } else { + shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly; + } + + let pathsToSkip = options && options.pathsToSkip; + + if (typeof pathsToValidate === 'string') { + const isOnePathOnly = pathsToValidate.indexOf(' ') === -1; + pathsToValidate = isOnePathOnly ? [pathsToValidate] : pathsToValidate.split(' '); + } else if (typeof pathsToSkip === 'string' && pathsToSkip.indexOf(' ') !== -1) { + pathsToSkip = pathsToSkip.split(' '); + } + + // only validate required fields when necessary + const pathDetails = _getPathsToValidate(this); + let paths = shouldValidateModifiedOnly ? + pathDetails[0].filter((path) => this.$isModified(path)) : + pathDetails[0]; + const skipSchemaValidators = pathDetails[1]; + + if (Array.isArray(pathsToValidate)) { + paths = _handlePathsToValidate(paths, pathsToValidate); + } else if (Array.isArray(pathsToSkip)) { + paths = _handlePathsToSkip(paths, pathsToSkip); + } + const validating = {}; + + paths.forEach(function(path) { + if (validating[path]) { + return; + } + + validating[path] = true; + + const p = _this.$__schema.path(path); + if (!p) { + return; + } + if (!_this.$isValid(path)) { + return; + } + + const val = _this.$__getValue(path); + const err = p.doValidateSync(val, _this, { + skipSchemaValidators: skipSchemaValidators[path], + path: path, + validateModifiedOnly: shouldValidateModifiedOnly + }); + if (err) { + const isSubdoc = p.$isSingleNested || + p.$isArraySubdocument || + p.$isMongooseDocumentArray; + if (isSubdoc && err instanceof ValidationError) { + return; + } + _this.invalidate(path, err, undefined, true); + } + }); + + const err = _this.$__.validationError; + _this.$__.validationError = undefined; + _this.$emit('validate', _this); + _this.constructor.emit('validate', _this); + + if (err) { + for (const key in err.errors) { + // Make sure cast errors persist + if (err.errors[key] instanceof MongooseError.CastError) { + _this.invalidate(key, err.errors[key]); + } + } + } + + return err; +}; + +/** + * Marks a path as invalid, causing validation to fail. + * + * The `errorMsg` argument will become the message of the `ValidationError`. + * + * The `value` argument (if passed) will be available through the `ValidationError.value` property. + * + * doc.invalidate('size', 'must be less than 20', 14); + + * doc.validate(function (err) { + * console.log(err) + * // prints + * { message: 'Validation failed', + * name: 'ValidationError', + * errors: + * { size: + * { message: 'must be less than 20', + * name: 'ValidatorError', + * path: 'size', + * type: 'user defined', + * value: 14 } } } + * }) + * + * @param {String} path the field to invalidate. For array elements, use the `array.i.field` syntax, where `i` is the 0-based index in the array. + * @param {String|Error} errorMsg the error which states the reason `path` was invalid + * @param {Object|String|Number|any} value optional invalid value + * @param {String} [kind] optional `kind` property for the error + * @return {ValidationError} the current ValidationError, with all currently invalidated paths + * @api public + */ + +Document.prototype.invalidate = function(path, err, val, kind) { + if (!this.$__.validationError) { + this.$__.validationError = new ValidationError(this); + } + + if (this.$__.validationError.errors[path]) { + return; + } + + if (!err || typeof err === 'string') { + err = new ValidatorError({ + path: path, + message: err, + type: kind || 'user defined', + value: val + }); + } + + if (this.$__.validationError === err) { + return this.$__.validationError; + } + + this.$__.validationError.addError(path, err); + return this.$__.validationError; +}; + +/** + * Marks a path as valid, removing existing validation errors. + * + * @param {String} path the field to mark as valid + * @api public + * @memberOf Document + * @instance + * @method $markValid + */ + +Document.prototype.$markValid = function(path) { + if (!this.$__.validationError || !this.$__.validationError.errors[path]) { + return; + } + + delete this.$__.validationError.errors[path]; + if (Object.keys(this.$__.validationError.errors).length === 0) { + this.$__.validationError = null; + } +}; + +/*! + * ignore + */ + +function _markValidSubpaths(doc, path) { + if (!doc.$__.validationError) { + return; + } + + const keys = Object.keys(doc.$__.validationError.errors); + for (const key of keys) { + if (key.startsWith(path + '.')) { + delete doc.$__.validationError.errors[key]; + } + } + if (Object.keys(doc.$__.validationError.errors).length === 0) { + doc.$__.validationError = null; + } +} + +/*! + * ignore + */ + +function _checkImmutableSubpaths(subdoc, schematype, priorVal) { + const schema = schematype.schema; + if (schema == null) { + return; + } + + for (const key of Object.keys(schema.paths)) { + const path = schema.paths[key]; + if (path.$immutableSetter == null) { + continue; + } + const oldVal = priorVal == null ? void 0 : priorVal.$__getValue(key); + // Calling immutableSetter with `oldVal` even though it expects `newVal` + // is intentional. That's because `$immutableSetter` compares its param + // to the current value. + path.$immutableSetter.call(subdoc, oldVal); + } +} + +/** + * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, + * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation **only** with the modifications to the database, it does not replace the whole document in the latter case. + * + * ####Example: + * + * product.sold = Date.now(); + * product = await product.save(); + * + * If save is successful, the returned promise will fulfill with the document + * saved. + * + * ####Example: + * + * const newProduct = await product.save(); + * newProduct === product; // true + * + * @param {Object} [options] options optional options + * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). + * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. + * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. + * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. + * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) + * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) + * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). + * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) + * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. + * @param {Function} [fn] optional callback + * @method save + * @memberOf Document + * @instance + * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). + * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. + * @api public + * @see middleware http://mongoosejs.com/docs/middleware.html + */ + +/** + * Checks if a path is invalid + * + * @param {String|Array} path the field to check + * @method $isValid + * @memberOf Document + * @instance + * @api private + */ + +Document.prototype.$isValid = function(path) { + if (this.$__.validationError == null || Object.keys(this.$__.validationError.errors).length === 0) { + return true; + } + if (path == null) { + return false; + } + + if (path.indexOf(' ') !== -1) { + path = path.split(' '); + } + if (Array.isArray(path)) { + return path.some(p => this.$__.validationError.errors[p] == null); + } + + return this.$__.validationError.errors[path] == null; +}; + +/** + * Resets the internal modified state of this document. + * + * @api private + * @return {Document} + * @method $__reset + * @memberOf Document + * @instance + */ + +Document.prototype.$__reset = function reset() { + let _this = this; + DocumentArray || (DocumentArray = require('./types/DocumentArray')); + + this.$__.activePaths + .map('init', 'modify', function(i) { + return _this.$__getValue(i); + }) + .filter(function(val) { + return val && val instanceof Array && val.isMongooseDocumentArray && val.length; + }) + .forEach(function(array) { + let i = array.length; + while (i--) { + const doc = array[i]; + if (!doc) { + continue; + } + doc.$__reset(); + } + + _this.$__.activePaths.init(array.$path()); + + array[arrayAtomicsBackupSymbol] = array[arrayAtomicsSymbol]; + array[arrayAtomicsSymbol] = {}; + }); + + this.$__.activePaths. + map('init', 'modify', function(i) { + return _this.$__getValue(i); + }). + filter(function(val) { + return val && val.$isSingleNested; + }). + forEach(function(doc) { + doc.$__reset(); + if (doc.$parent() === _this) { + _this.$__.activePaths.init(doc.$basePath); + } else if (doc.$parent() != null && doc.$parent().ownerDocument) { + // If map path underneath subdocument, may end up with a case where + // map path is modified but parent still needs to be reset. See gh-10295 + doc.$parent().$__reset(); + } + }); + + // clear atomics + this.$__dirty().forEach(function(dirt) { + const type = dirt.value; + + if (type && type[arrayAtomicsSymbol]) { + type[arrayAtomicsBackupSymbol] = type[arrayAtomicsSymbol]; + type[arrayAtomicsSymbol] = {}; + } + }); + + this.$__.backup = {}; + this.$__.backup.activePaths = { + modify: Object.assign({}, this.$__.activePaths.states.modify), + default: Object.assign({}, this.$__.activePaths.states.default) + }; + this.$__.backup.validationError = this.$__.validationError; + this.$__.backup.errors = this.$errors; + + // Clear 'dirty' cache + this.$__.activePaths.clear('modify'); + this.$__.activePaths.clear('default'); + this.$__.validationError = undefined; + this.$errors = undefined; + _this = this; + this.$__schema.requiredPaths().forEach(function(path) { + _this.$__.activePaths.require(path); + }); + + return this; +}; + +/*! + * ignore + */ + +Document.prototype.$__undoReset = function $__undoReset() { + if (this.$__.backup == null || this.$__.backup.activePaths == null) { + return; + } + + this.$__.activePaths.states.modify = this.$__.backup.activePaths.modify; + this.$__.activePaths.states.default = this.$__.backup.activePaths.default; + + this.$__.validationError = this.$__.backup.validationError; + this.$errors = this.$__.backup.errors; + + for (const dirt of this.$__dirty()) { + const type = dirt.value; + + if (type && type[arrayAtomicsSymbol] && type[arrayAtomicsBackupSymbol]) { + type[arrayAtomicsSymbol] = type[arrayAtomicsBackupSymbol]; + } + } + + for (const subdoc of this.$getAllSubdocs()) { + subdoc.$__undoReset(); + } +}; + +/** + * Returns this documents dirty paths / vals. + * + * @api private + * @method $__dirty + * @memberOf Document + * @instance + */ + +Document.prototype.$__dirty = function() { + const _this = this; + let all = this.$__.activePaths.map('modify', function(path) { + return { + path: path, + value: _this.$__getValue(path), + schema: _this.$__path(path) + }; + }); + // gh-2558: if we had to set a default and the value is not undefined, + // we have to save as well + all = all.concat(this.$__.activePaths.map('default', function(path) { + if (path === '_id' || _this.$__getValue(path) == null) { + return; + } + return { + path: path, + value: _this.$__getValue(path), + schema: _this.$__path(path) + }; + })); + + const allPaths = new Map(all.filter((el) => el != null).map((el) => [el.path, el.value])); + // Ignore "foo.a" if "foo" is dirty already. + const minimal = []; + + all.forEach(function(item) { + if (!item) { + return; + } + + let top = null; + + const array = parentPaths(item.path); + for (let i = 0; i < array.length - 1; i++) { + if (allPaths.has(array[i])) { + top = allPaths.get(array[i]); + break; + } + } + if (top == null) { + minimal.push(item); + } else if (top != null && + top[arrayAtomicsSymbol] != null && + top.hasAtomics()) { + // special case for top level MongooseArrays + // the `top` array itself and a sub path of `top` are being set. + // the only way to honor all of both modifications is through a $set + // of entire array. + top[arrayAtomicsSymbol] = {}; + top[arrayAtomicsSymbol].$set = top; + } + }); + return minimal; +}; + +/** + * Assigns/compiles `schema` into this documents prototype. + * + * @param {Schema} schema + * @api private + * @method $__setSchema + * @memberOf Document + * @instance + */ + +Document.prototype.$__setSchema = function(schema) { + compile(schema.tree, this, undefined, schema.options); + + // Apply default getters if virtual doesn't have any (gh-6262) + for (const key of Object.keys(schema.virtuals)) { + schema.virtuals[key]._applyDefaultGetters(); + } + if (schema.path('schema') == null) { + this.schema = schema; + } + this.$__schema = schema; + this[documentSchemaSymbol] = schema; +}; + + +/** + * Get active path that were changed and are arrays + * + * @api private + * @method $__getArrayPathsToValidate + * @memberOf Document + * @instance + */ + +Document.prototype.$__getArrayPathsToValidate = function() { + DocumentArray || (DocumentArray = require('./types/DocumentArray')); + + // validate all document arrays. + return this.$__.activePaths + .map('init', 'modify', function(i) { + return this.$__getValue(i); + }.bind(this)) + .filter(function(val) { + return val && val instanceof Array && val.isMongooseDocumentArray && val.length; + }).reduce(function(seed, array) { + return seed.concat(array); + }, []) + .filter(function(doc) { + return doc; + }); +}; + + +/** + * Get all subdocs (by bfs) + * + * @api public + * @method $getAllSubdocs + * @memberOf Document + * @instance + */ + +Document.prototype.$getAllSubdocs = function() { + DocumentArray || (DocumentArray = require('./types/DocumentArray')); + Embedded = Embedded || require('./types/ArraySubdocument'); + + function docReducer(doc, seed, path) { + let val = doc; + let isNested = false; + if (path) { + if (doc instanceof Document && doc[documentSchemaSymbol].paths[path]) { + val = doc._doc[path]; + } else if (doc instanceof Document && doc[documentSchemaSymbol].nested[path]) { + val = doc._doc[path]; + isNested = true; + } else { + val = doc[path]; + } + } + if (val instanceof Embedded) { + seed.push(val); + } else if (val instanceof Map) { + seed = Array.from(val.keys()).reduce(function(seed, path) { + return docReducer(val.get(path), seed, null); + }, seed); + } else if (val && val.$isSingleNested) { + seed = Object.keys(val._doc).reduce(function(seed, path) { + return docReducer(val._doc, seed, path); + }, seed); + seed.push(val); + } else if (val && val.isMongooseDocumentArray) { + val.forEach(function _docReduce(doc) { + if (!doc || !doc._doc) { + return; + } + seed = Object.keys(doc._doc).reduce(function(seed, path) { + return docReducer(doc._doc, seed, path); + }, seed); + if (doc instanceof Embedded) { + seed.push(doc); + } + }); + } else if (isNested && val != null) { + for (const path of Object.keys(val)) { + docReducer(val, seed, path); + } + } + return seed; + } + + const subDocs = []; + for (const path of Object.keys(this._doc)) { + docReducer(this, subDocs, path); + } + + return subDocs; +}; + +/*! + * Runs queued functions + */ + +function applyQueue(doc) { + const q = doc.$__schema && doc.$__schema.callQueue; + if (!q.length) { + return; + } + + for (const pair of q) { + if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') { + doc[pair[0]].apply(doc, pair[1]); + } + } +} + +/*! + * ignore + */ + +Document.prototype.$__handleReject = function handleReject(err) { + // emit on the Model if listening + if (this.$listeners('error').length) { + this.$emit('error', err); + } else if (this.constructor.listeners && this.constructor.listeners('error').length) { + this.constructor.emit('error', err); + } +}; + +/** + * Internal helper for toObject() and toJSON() that doesn't manipulate options + * + * @api private + * @method $toObject + * @memberOf Document + * @instance + */ + +Document.prototype.$toObject = function(options, json) { + let defaultOptions = { + transform: true, + flattenDecimals: true + }; + + const path = json ? 'toJSON' : 'toObject'; + const baseOptions = get(this, 'constructor.base.options.' + path, {}); + const schemaOptions = get(this, '$__schema.options', {}); + // merge base default options with Schema's set default options if available. + // `clone` is necessary here because `utils.options` directly modifies the second input. + defaultOptions = utils.options(defaultOptions, clone(baseOptions)); + defaultOptions = utils.options(defaultOptions, clone(schemaOptions[path] || {})); + + // If options do not exist or is not an object, set it to empty object + options = utils.isPOJO(options) ? clone(options) : {}; + options._calledWithOptions = options._calledWithOptions || clone(options); + + let _minimize; + if (options._calledWithOptions.minimize != null) { + _minimize = options.minimize; + } else if (defaultOptions.minimize != null) { + _minimize = defaultOptions.minimize; + } else { + _minimize = schemaOptions.minimize; + } + + let flattenMaps; + if (options._calledWithOptions.flattenMaps != null) { + flattenMaps = options.flattenMaps; + } else if (defaultOptions.flattenMaps != null) { + flattenMaps = defaultOptions.flattenMaps; + } else { + flattenMaps = schemaOptions.flattenMaps; + } + + // The original options that will be passed to `clone()`. Important because + // `clone()` will recursively call `$toObject()` on embedded docs, so we + // need the original options the user passed in, plus `_isNested` and + // `_parentOptions` for checking whether we need to depopulate. + const cloneOptions = Object.assign(utils.clone(options), { + _isNested: true, + json: json, + minimize: _minimize, + flattenMaps: flattenMaps + }); + + if (utils.hasUserDefinedProperty(options, 'getters')) { + cloneOptions.getters = options.getters; + } + if (utils.hasUserDefinedProperty(options, 'virtuals')) { + cloneOptions.virtuals = options.virtuals; + } + + const depopulate = options.depopulate || + get(options, '_parentOptions.depopulate', false); + // _isNested will only be true if this is not the top level document, we + // should never depopulate + if (depopulate && options._isNested && this.$__.wasPopulated) { + // populated paths that we set to a document + return clone(this._id, cloneOptions); + } + + // merge default options with input options. + options = utils.options(defaultOptions, options); + options._isNested = true; + options.json = json; + options.minimize = _minimize; + + cloneOptions._parentOptions = options; + cloneOptions._skipSingleNestedGetters = true; + + const gettersOptions = Object.assign({}, cloneOptions); + gettersOptions._skipSingleNestedGetters = false; + + // remember the root transform function + // to save it from being overwritten by sub-transform functions + const originalTransform = options.transform; + + let ret = clone(this._doc, cloneOptions) || {}; + + if (options.getters) { + applyGetters(this, ret, gettersOptions); + + if (options.minimize) { + ret = minimize(ret) || {}; + } + } + + if (options.virtuals || (options.getters && options.virtuals !== false)) { + applyVirtuals(this, ret, gettersOptions, options); + } + + if (options.versionKey === false && this.$__schema.options.versionKey) { + delete ret[this.$__schema.options.versionKey]; + } + + let transform = options.transform; + + // In the case where a subdocument has its own transform function, we need to + // check and see if the parent has a transform (options.transform) and if the + // child schema has a transform (this.schema.options.toObject) In this case, + // we need to adjust options.transform to be the child schema's transform and + // not the parent schema's + if (transform) { + applySchemaTypeTransforms(this, ret); + } + + if (options.useProjection) { + omitDeselectedFields(this, ret); + } + + if (transform === true || (schemaOptions.toObject && transform)) { + const opts = options.json ? schemaOptions.toJSON : schemaOptions.toObject; + + if (opts) { + transform = (typeof options.transform === 'function' ? options.transform : opts.transform); + } + } else { + options.transform = originalTransform; + } + + if (typeof transform === 'function') { + const xformed = transform(this, ret, options); + if (typeof xformed !== 'undefined') { + ret = xformed; + } + } + + return ret; +}; + +/** + * Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). + * + * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage. + * + * ####Options: + * + * - `getters` apply all getters (path and virtual getters), defaults to false + * - `aliases` apply all aliases if `virtuals=true`, defaults to true + * - `virtuals` apply virtual getters (can override `getters` option), defaults to false + * - `minimize` remove empty objects, defaults to true + * - `transform` a transform function to apply to the resulting document before returning + * - `depopulate` depopulate any populated paths, replacing them with their original refs, defaults to false + * - `versionKey` whether to include the version key, defaults to true + * - `flattenMaps` convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to false + * - `useProjection` set to `true` to omit fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. + * + * ####Getters/Virtuals + * + * Example of only applying path getters + * + * doc.toObject({ getters: true, virtuals: false }) + * + * Example of only applying virtual getters + * + * doc.toObject({ virtuals: true }) + * + * Example of applying both path and virtual getters + * + * doc.toObject({ getters: true }) + * + * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. + * + * schema.set('toObject', { virtuals: true }) + * + * ####Transform + * + * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. + * + * Transform functions receive three arguments + * + * function (doc, ret, options) {} + * + * - `doc` The mongoose document which is being converted + * - `ret` The plain object representation which has been converted + * - `options` The options in use (either schema options or the options passed inline) + * + * ####Example + * + * // specify the transform schema option + * if (!schema.options.toObject) schema.options.toObject = {}; + * schema.options.toObject.transform = function (doc, ret, options) { + * // remove the _id of every document before returning the result + * delete ret._id; + * return ret; + * } + * + * // without the transformation in the schema + * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } + * + * // with the transformation + * doc.toObject(); // { name: 'Wreck-it Ralph' } + * + * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: + * + * if (!schema.options.toObject) schema.options.toObject = {}; + * schema.options.toObject.transform = function (doc, ret, options) { + * return { movie: ret.name } + * } + * + * // without the transformation in the schema + * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } + * + * // with the transformation + * doc.toObject(); // { movie: 'Wreck-it Ralph' } + * + * _Note: if a transform function returns `undefined`, the return value will be ignored._ + * + * Transformations may also be applied inline, overridding any transform set in the options: + * + * function xform (doc, ret, options) { + * return { inline: ret.name, custom: true } + * } + * + * // pass the transform as an inline option + * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } + * + * If you want to skip transformations, use `transform: false`: + * + * schema.options.toObject.hide = '_id'; + * schema.options.toObject.transform = function (doc, ret, options) { + * if (options.hide) { + * options.hide.split(' ').forEach(function (prop) { + * delete ret[prop]; + * }); + * } + * return ret; + * } + * + * const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); + * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } + * doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } + * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } + * + * If you pass a transform in `toObject()` options, Mongoose will apply the transform + * to [subdocuments](/docs/subdocs.html) in addition to the top-level document. + * Similarly, `transform: false` skips transforms for all subdocuments. + * Note that this is behavior is different for transforms defined in the schema: + * if you define a transform in `schema.options.toObject.transform`, that transform + * will **not** apply to subdocuments. + * + * const memberSchema = new Schema({ name: String, email: String }); + * const groupSchema = new Schema({ members: [memberSchema], name: String, email }); + * const Group = mongoose.model('Group', groupSchema); + * + * const doc = new Group({ + * name: 'Engineering', + * email: 'dev@mongoosejs.io', + * members: [{ name: 'Val', email: 'val@mongoosejs.io' }] + * }); + * + * // Removes `email` from both top-level document **and** array elements + * // { name: 'Engineering', members: [{ name: 'Val' }] } + * doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } }); + * + * Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions. + * + * See [schema options](/docs/guide.html#toObject) for some more details. + * + * _During save, no custom options are applied to the document before being sent to the database._ + * + * @param {Object} [options] + * @param {Boolean} [options.getters=false] if true, apply all getters, including virtuals + * @param {Boolean} [options.virtuals=false] if true, apply virtuals, including aliases. Use `{ getters: true, virtuals: false }` to just apply getters, not virtuals + * @param {Boolean} [options.aliases=true] if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. + * @param {Boolean} [options.minimize=true] if true, omit any empty objects from the output + * @param {Function|null} [options.transform=null] if set, mongoose will call this function to allow you to transform the returned object + * @param {Boolean} [options.depopulate=false] if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. + * @param {Boolean} [options.versionKey=true] if false, exclude the version key (`__v` by default) from the output + * @param {Boolean} [options.flattenMaps=false] if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. + * @param {Boolean} [options.useProjection=false] - If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. + * @return {Object} js object + * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html + * @api public + * @memberOf Document + * @instance + */ + +Document.prototype.toObject = function(options) { + return this.$toObject(options); +}; + +/*! + * Minimizes an object, removing undefined values and empty objects + * + * @param {Object} object to minimize + * @return {Object} + */ + +function minimize(obj) { + const keys = Object.keys(obj); + let i = keys.length; + let hasKeys; + let key; + let val; + + while (i--) { + key = keys[i]; + val = obj[key]; + + if (utils.isPOJO(val)) { + obj[key] = minimize(val); + } + + if (undefined === obj[key]) { + delete obj[key]; + continue; + } + + hasKeys = true; + } + + return hasKeys + ? obj + : undefined; +} + +/*! + * Applies virtuals properties to `json`. + */ + +function applyVirtuals(self, json, options, toObjectOptions) { + const schema = self.$__schema; + const paths = Object.keys(schema.virtuals); + let i = paths.length; + const numPaths = i; + let path; + let assignPath; + let cur = self._doc; + let v; + const aliases = get(toObjectOptions, 'aliases', true); + + let virtualsToApply = null; + if (Array.isArray(options.virtuals)) { + virtualsToApply = new Set(options.virtuals); + } + else if (options.virtuals && options.virtuals.pathsToSkip) { + virtualsToApply = new Set(paths); + for (let i = 0; i < options.virtuals.pathsToSkip.length; i++) { + if (virtualsToApply.has(options.virtuals.pathsToSkip[i])) { + virtualsToApply.delete(options.virtuals.pathsToSkip[i]); + } + } + } + + if (!cur) { + return json; + } + + options = options || {}; + for (i = 0; i < numPaths; ++i) { + path = paths[i]; + + if (virtualsToApply != null && !virtualsToApply.has(path)) { + continue; + } + + // Allow skipping aliases with `toObject({ virtuals: true, aliases: false })` + if (!aliases && schema.aliases.hasOwnProperty(path)) { + continue; + } + + // We may be applying virtuals to a nested object, for example if calling + // `doc.nestedProp.toJSON()`. If so, the path we assign to, `assignPath`, + // will be a trailing substring of the `path`. + assignPath = path; + if (options.path != null) { + if (!path.startsWith(options.path + '.')) { + continue; + } + assignPath = path.substr(options.path.length + 1); + } + const parts = assignPath.split('.'); + v = clone(self.get(path), options); + if (v === void 0) { + continue; + } + const plen = parts.length; + cur = json; + for (let j = 0; j < plen - 1; ++j) { + cur[parts[j]] = cur[parts[j]] || {}; + cur = cur[parts[j]]; + } + cur[parts[plen - 1]] = v; + } + + return json; +} + + +/*! + * Applies virtuals properties to `json`. + * + * @param {Document} self + * @param {Object} json + * @return {Object} `json` + */ + +function applyGetters(self, json, options) { + const schema = self.$__schema; + const paths = Object.keys(schema.paths); + let i = paths.length; + let path; + let cur = self._doc; + let v; + + if (!cur) { + return json; + } + + while (i--) { + path = paths[i]; + + const parts = path.split('.'); + const plen = parts.length; + const last = plen - 1; + let branch = json; + let part; + cur = self._doc; + + if (!self.$__isSelected(path)) { + continue; + } + + for (let ii = 0; ii < plen; ++ii) { + part = parts[ii]; + v = cur[part]; + if (ii === last) { + const val = self.$get(path); + branch[part] = clone(val, options); + } else if (v == null) { + if (part in cur) { + branch[part] = v; + } + break; + } else { + branch = branch[part] || (branch[part] = {}); + } + cur = v; + } + } + + return json; +} + +/*! + * Applies schema type transforms to `json`. + * + * @param {Document} self + * @param {Object} json + * @return {Object} `json` + */ + +function applySchemaTypeTransforms(self, json) { + const schema = self.$__schema; + const paths = Object.keys(schema.paths || {}); + const cur = self._doc; + + if (!cur) { + return json; + } + + for (const path of paths) { + const schematype = schema.paths[path]; + if (typeof schematype.options.transform === 'function') { + const val = self.$get(path); + const transformedValue = schematype.options.transform.call(self, val); + throwErrorIfPromise(path, transformedValue); + utils.setValue(path, transformedValue, json); + } else if (schematype.$embeddedSchemaType != null && + typeof schematype.$embeddedSchemaType.options.transform === 'function') { + const vals = [].concat(self.$get(path)); + const transform = schematype.$embeddedSchemaType.options.transform; + for (let i = 0; i < vals.length; ++i) { + const transformedValue = transform.call(self, vals[i]); + vals[i] = transformedValue; + throwErrorIfPromise(path, transformedValue); + } + + json[path] = vals; + } + } + + return json; +} + +function throwErrorIfPromise(path, transformedValue) { + if (isPromise(transformedValue)) { + throw new Error('`transform` function must be synchronous, but the transform on path `' + path + '` returned a promise.'); + } +} + +/*! + * ignore + */ + +function omitDeselectedFields(self, json) { + const schema = self.$__schema; + const paths = Object.keys(schema.paths || {}); + const cur = self._doc; + + if (!cur) { + return json; + } + + let selected = self.$__.selected; + if (selected === void 0) { + selected = {}; + queryhelpers.applyPaths(selected, schema); + } + if (selected == null || Object.keys(selected).length === 0) { + return json; + } + + for (const path of paths) { + if (selected[path] != null && !selected[path]) { + delete json[path]; + } + } + + return json; +} + +/** + * The return value of this method is used in calls to JSON.stringify(doc). + * + * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. + * + * schema.set('toJSON', { virtuals: true }) + * + * See [schema options](/docs/guide.html#toJSON) for details. + * + * @param {Object} options + * @return {Object} + * @see Document#toObject #document_Document-toObject + * @see JSON.stringify() in JavaScript https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html + * @api public + * @memberOf Document + * @instance + */ + +Document.prototype.toJSON = function(options) { + return this.$toObject(options, true); +}; + +/** + * If this document is a subdocument or populated document, returns the document's + * parent. Returns `undefined` otherwise. + * + * @api public + * @method parent + * @memberOf Document + * @instance + */ + +Document.prototype.parent = function() { + return this.$__.parent; +}; + +/** + * Alias for `parent()`. If this document is a subdocument or populated + * document, returns the document's parent. Returns `undefined` otherwise. + * + * @api public + * @method $parent + * @memberOf Document + * @instance + */ + +Document.prototype.$parent = Document.prototype.parent; + +/** + * Helper for console.log + * + * @api public + * @method inspect + * @memberOf Document + * @instance + */ + +Document.prototype.inspect = function(options) { + const isPOJO = utils.isPOJO(options); + let opts; + if (isPOJO) { + opts = options; + opts.minimize = false; + } + const ret = this.toObject(opts); + + if (ret == null) { + // If `toObject()` returns null, `this` is still an object, so if `inspect()` + // prints out null this can cause some serious confusion. See gh-7942. + return 'MongooseDocument { ' + ret + ' }'; + } + + return ret; +}; + +if (inspect.custom) { + /*! + * Avoid Node deprecation warning DEP0079 + */ + + Document.prototype[inspect.custom] = Document.prototype.inspect; +} + +/** + * Helper for console.log + * + * @api public + * @method toString + * @memberOf Document + * @instance + */ + +Document.prototype.toString = function() { + const ret = this.inspect(); + if (typeof ret === 'string') { + return ret; + } + return inspect(ret); +}; + +/** + * Returns true if this document is equal to another document. + * + * Documents are considered equal when they have matching `_id`s, unless neither + * document has an `_id`, in which case this function falls back to using + * `deepEqual()`. + * + * @param {Document} doc a document to compare + * @return {Boolean} + * @api public + * @memberOf Document + * @instance + */ + +Document.prototype.equals = function(doc) { + if (!doc) { + return false; + } + + const tid = this.$__getValue('_id'); + const docid = doc.$__ != null ? doc.$__getValue('_id') : doc; + if (!tid && !docid) { + return deepEqual(this, doc); + } + return tid && tid.equals + ? tid.equals(docid) + : tid === docid; +}; + +/** + * Populates paths on an existing document. + * + * ####Example: + * + * await doc.populate([ + * 'stories', + * { path: 'fans', sort: { name: -1 } } + * ]); + * doc.populated('stories'); // Array of ObjectIds + * doc.stories[0].title; // 'Casino Royale' + * doc.populated('fans'); // Array of ObjectIds + * + * await doc.populate('fans', '-email'); + * doc.fans[0].email // not populated + * + * await doc.populate('author fans', '-email'); + * doc.author.email // not populated + * doc.fans[0].email // not populated + * + * @param {String|Object|Array} path either the path to populate or an object specifying all parameters, or either an array of those + * @param {Object|String} [select] Field selection for the population query + * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field. + * @param {Object} [match] Conditions for the population query + * @param {Object} [options] Options for the population query (sort, etc) + * @param {String} [options.path=null] The path to populate. + * @param {boolean} [options.retainNullValues=false] by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. + * @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). + * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. + * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. + * @param {Function} [options.transform=null] Function that Mongoose will call on every populated document that allows you to transform the populated document. + * @param {Object} [options.options=null] Additional options like `limit` and `lean`. + * @param {Function} [callback] Callback + * @see population ./populate.html + * @see Query#select #query_Query-select + * @see Model.populate #model_Model.populate + * @memberOf Document + * @instance + * @return {Promise|null} + * @api public + */ + +Document.prototype.populate = function populate() { + const pop = {}; + const args = utils.args(arguments); + let fn; + + if (args.length > 0) { + if (typeof args[args.length - 1] === 'function') { + fn = args.pop(); + } + + // use hash to remove duplicate paths + const res = utils.populate.apply(null, args); + for (const populateOptions of res) { + pop[populateOptions.path] = populateOptions; + } + } + + const paths = utils.object.vals(pop); + let topLevelModel = this.constructor; + if (this.$__isNested) { + topLevelModel = this.$__[scopeSymbol].constructor; + const nestedPath = this.$__.nestedPath; + paths.forEach(function(populateOptions) { + populateOptions.path = nestedPath + '.' + populateOptions.path; + }); + } + + // Use `$session()` by default if the document has an associated session + // See gh-6754 + if (this.$session() != null) { + const session = this.$session(); + paths.forEach(path => { + if (path.options == null) { + path.options = { session: session }; + return; + } + if (!('session' in path.options)) { + path.options.session = session; + } + }); + } + + paths.forEach(p => { + p._localModel = topLevelModel; + }); + + return topLevelModel.populate(this, paths, fn); +}; + +/** + * Gets all populated documents associated with this document. + * + * @api public + * @return {Array} array of populated documents. Empty array if there are no populated documents associated with this document. + * @memberOf Document + * @instance + */ +Document.prototype.$getPopulatedDocs = function $getPopulatedDocs() { + let keys = []; + if (this.$__.populated != null) { + keys = keys.concat(Object.keys(this.$__.populated)); + } + let result = []; + for (const key of keys) { + const value = this.$get(key); + if (Array.isArray(value)) { + result = result.concat(value); + } else if (value instanceof Document) { + result.push(value); + } + } + return result; +}; + +/** + * Gets _id(s) used during population of the given `path`. + * + * ####Example: + * + * Model.findOne().populate('author').exec(function (err, doc) { + * console.log(doc.author.name) // Dr.Seuss + * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7' + * }) + * + * If the path was not populated, returns `undefined`. + * + * @param {String} path + * @return {Array|ObjectId|Number|Buffer|String|undefined} + * @memberOf Document + * @instance + * @api public + */ + +Document.prototype.populated = function(path, val, options) { + // val and options are internal + if (val == null || val === true) { + if (!this.$__.populated) { + return undefined; + } + if (typeof path !== 'string') { + return undefined; + } + + // Map paths can be populated with either `path.$*` or just `path` + const _path = path.endsWith('.$*') ? path.replace(/\.\$\*$/, '') : path; + + const v = this.$__.populated[_path]; + if (v) { + return val === true ? v : v.value; + } + return undefined; + } + + this.$__.populated || (this.$__.populated = {}); + this.$__.populated[path] = { value: val, options: options }; + + // If this was a nested populate, make sure each populated doc knows + // about its populated children (gh-7685) + const pieces = path.split('.'); + for (let i = 0; i < pieces.length - 1; ++i) { + const subpath = pieces.slice(0, i + 1).join('.'); + const subdoc = this.$get(subpath); + if (subdoc != null && subdoc.$__ != null && this.$populated(subpath)) { + const rest = pieces.slice(i + 1).join('.'); + subdoc.$populated(rest, val, options); + // No need to continue because the above recursion should take care of + // marking the rest of the docs as populated + break; + } + } + + return val; +}; + +Document.prototype.$populated = Document.prototype.populated; + +/** + * Takes a populated field and returns it to its unpopulated state. + * + * ####Example: + * + * Model.findOne().populate('author').exec(function (err, doc) { + * console.log(doc.author.name); // Dr.Seuss + * console.log(doc.depopulate('author')); + * console.log(doc.author); // '5144cf8050f071d979c118a7' + * }) + * + * If the path was not provided, then all populated fields are returned to their unpopulated state. + * + * @param {String} path + * @return {Document} this + * @see Document.populate #document_Document-populate + * @api public + * @memberOf Document + * @instance + */ + +Document.prototype.depopulate = function(path) { + if (typeof path === 'string') { + path = path.indexOf(' ') === -1 ? [path] : path.split(' '); + } + + let populatedIds; + const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : []; + const populated = get(this, '$__.populated', {}); + + if (arguments.length === 0) { + // Depopulate all + for (const virtualKey of virtualKeys) { + delete this.$$populatedVirtuals[virtualKey]; + delete this._doc[virtualKey]; + delete populated[virtualKey]; + } + + const keys = Object.keys(populated); + + for (const key of keys) { + populatedIds = this.$populated(key); + if (!populatedIds) { + continue; + } + delete populated[key]; + utils.setValue(key, populatedIds, this._doc); + } + return this; + } + + for (const singlePath of path) { + populatedIds = this.$populated(singlePath); + delete populated[singlePath]; + + if (virtualKeys.indexOf(singlePath) !== -1) { + delete this.$$populatedVirtuals[singlePath]; + delete this._doc[singlePath]; + } else if (populatedIds) { + utils.setValue(singlePath, populatedIds, this._doc); + } + } + return this; +}; + + +/** + * Returns the full path to this document. + * + * @param {String} [path] + * @return {String} + * @api private + * @method $__fullPath + * @memberOf Document + * @instance + */ + +Document.prototype.$__fullPath = function(path) { + // overridden in SubDocuments + return path || ''; +}; + +/** + * Returns the changes that happened to the document + * in the format that will be sent to MongoDB. + * + * #### Example: + * + * const userSchema = new Schema({ + * name: String, + * age: Number, + * country: String + * }); + * const User = mongoose.model('User', userSchema); + * const user = await User.create({ + * name: 'Hafez', + * age: 25, + * country: 'Egypt' + * }); + * + * // returns an empty object, no changes happened yet + * user.getChanges(); // { } + * + * user.country = undefined; + * user.age = 26; + * + * user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } } + * + * await user.save(); + * + * user.getChanges(); // { } + * + * Modifying the object that `getChanges()` returns does not affect the document's + * change tracking state. Even if you `delete user.getChanges().$set`, Mongoose + * will still send a `$set` to the server. + * + * @return {Object} + * @api public + * @method getChanges + * @memberOf Document + * @instance + */ + +Document.prototype.getChanges = function() { + const delta = this.$__delta(); + const changes = delta ? delta[1] : {}; + return changes; +}; + +/*! + * Module exports. + */ + +Document.ValidationError = ValidationError; +module.exports = exports = Document; diff --git a/node_modules/mongoose/lib/document_provider.js b/node_modules/mongoose/lib/document_provider.js new file mode 100644 index 0000000..1ace61f --- /dev/null +++ b/node_modules/mongoose/lib/document_provider.js @@ -0,0 +1,30 @@ +'use strict'; + +/* eslint-env browser */ + +/*! + * Module dependencies. + */ +const Document = require('./document.js'); +const BrowserDocument = require('./browserDocument.js'); + +let isBrowser = false; + +/** + * Returns the Document constructor for the current context + * + * @api private + */ +module.exports = function() { + if (isBrowser) { + return BrowserDocument; + } + return Document; +}; + +/*! + * ignore + */ +module.exports.setBrowser = function(flag) { + isBrowser = flag; +}; diff --git a/node_modules/mongoose/lib/driver.js b/node_modules/mongoose/lib/driver.js new file mode 100644 index 0000000..cf7ca3d --- /dev/null +++ b/node_modules/mongoose/lib/driver.js @@ -0,0 +1,15 @@ +'use strict'; + +/*! + * ignore + */ + +let driver = null; + +module.exports.get = function() { + return driver; +}; + +module.exports.set = function(v) { + driver = v; +}; diff --git a/node_modules/mongoose/lib/drivers/SPEC.md b/node_modules/mongoose/lib/drivers/SPEC.md new file mode 100644 index 0000000..6464693 --- /dev/null +++ b/node_modules/mongoose/lib/drivers/SPEC.md @@ -0,0 +1,4 @@ + +# Driver Spec + +TODO diff --git a/node_modules/mongoose/lib/drivers/browser/ReadPreference.js b/node_modules/mongoose/lib/drivers/browser/ReadPreference.js new file mode 100644 index 0000000..1363570 --- /dev/null +++ b/node_modules/mongoose/lib/drivers/browser/ReadPreference.js @@ -0,0 +1,7 @@ +/*! + * ignore + */ + +'use strict'; + +module.exports = function() {}; diff --git a/node_modules/mongoose/lib/drivers/browser/binary.js b/node_modules/mongoose/lib/drivers/browser/binary.js new file mode 100644 index 0000000..4658f7b --- /dev/null +++ b/node_modules/mongoose/lib/drivers/browser/binary.js @@ -0,0 +1,14 @@ + +/*! + * Module dependencies. + */ + +'use strict'; + +const Binary = require('bson').Binary; + +/*! + * Module exports. + */ + +module.exports = exports = Binary; diff --git a/node_modules/mongoose/lib/drivers/browser/decimal128.js b/node_modules/mongoose/lib/drivers/browser/decimal128.js new file mode 100644 index 0000000..5668182 --- /dev/null +++ b/node_modules/mongoose/lib/drivers/browser/decimal128.js @@ -0,0 +1,7 @@ +/*! + * ignore + */ + +'use strict'; + +module.exports = require('bson').Decimal128; diff --git a/node_modules/mongoose/lib/drivers/browser/index.js b/node_modules/mongoose/lib/drivers/browser/index.js new file mode 100644 index 0000000..bc4ac5f --- /dev/null +++ b/node_modules/mongoose/lib/drivers/browser/index.js @@ -0,0 +1,16 @@ +/*! + * Module exports. + */ + +'use strict'; + +exports.Binary = require('./binary'); +exports.Collection = function() { + throw new Error('Cannot create a collection from browser library'); +}; +exports.getConnection = () => function() { + throw new Error('Cannot create a connection from browser library'); +}; +exports.Decimal128 = require('./decimal128'); +exports.ObjectId = require('./objectid'); +exports.ReadPreference = require('./ReadPreference'); diff --git a/node_modules/mongoose/lib/drivers/browser/objectid.js b/node_modules/mongoose/lib/drivers/browser/objectid.js new file mode 100644 index 0000000..b1e603d --- /dev/null +++ b/node_modules/mongoose/lib/drivers/browser/objectid.js @@ -0,0 +1,28 @@ + +/*! + * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId + * @constructor NodeMongoDbObjectId + * @see ObjectId + */ + +'use strict'; + +const ObjectId = require('bson').ObjectID; + +/*! + * Getter for convenience with populate, see gh-6115 + */ + +Object.defineProperty(ObjectId.prototype, '_id', { + enumerable: false, + configurable: true, + get: function() { + return this; + } +}); + +/*! + * ignore + */ + +module.exports = exports = ObjectId; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js new file mode 100644 index 0000000..024ee18 --- /dev/null +++ b/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js @@ -0,0 +1,47 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const mongodb = require('mongodb'); +const ReadPref = mongodb.ReadPreference; + +/*! + * Converts arguments to ReadPrefs the driver + * can understand. + * + * @param {String|Array} pref + * @param {Array} [tags] + */ + +module.exports = function readPref(pref, tags) { + if (Array.isArray(pref)) { + tags = pref[1]; + pref = pref[0]; + } + + if (pref instanceof ReadPref) { + return pref; + } + + switch (pref) { + case 'p': + pref = 'primary'; + break; + case 'pp': + pref = 'primaryPreferred'; + break; + case 's': + pref = 'secondary'; + break; + case 'sp': + pref = 'secondaryPreferred'; + break; + case 'n': + pref = 'nearest'; + break; + } + + return new ReadPref(pref, tags); +}; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js new file mode 100644 index 0000000..4e3c86f --- /dev/null +++ b/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js @@ -0,0 +1,10 @@ + +/*! + * Module dependencies. + */ + +'use strict'; + +const Binary = require('mongodb').Binary; + +module.exports = exports = Binary; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js new file mode 100644 index 0000000..2c364f8 --- /dev/null +++ b/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js @@ -0,0 +1,411 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const MongooseCollection = require('../../collection'); +const MongooseError = require('../../error/mongooseError'); +const Collection = require('mongodb').Collection; +const ObjectId = require('./objectid'); +const get = require('../../helpers/get'); +const getConstructorName = require('../../helpers/getConstructorName'); +const sliced = require('sliced'); +const stream = require('stream'); +const util = require('util'); + +/** + * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation. + * + * All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management. + * + * @inherits Collection + * @api private + */ + +function NativeCollection(name, conn, options) { + this.collection = null; + this.Promise = options.Promise || Promise; + this.modelName = options.modelName; + delete options.modelName; + this._closed = false; + MongooseCollection.apply(this, arguments); +} + +/*! + * Inherit from abstract Collection. + */ + +NativeCollection.prototype.__proto__ = MongooseCollection.prototype; + +/** + * Called when the connection opens. + * + * @api private + */ + +NativeCollection.prototype.onOpen = function() { + const _this = this; + + _this.collection = _this.conn.db.collection(_this.name); + MongooseCollection.prototype.onOpen.call(_this); + return _this.collection; +}; + +/** + * Called when the connection closes + * + * @api private + */ + +NativeCollection.prototype.onClose = function(force) { + MongooseCollection.prototype.onClose.call(this, force); +}; + +/*! + * ignore + */ + +const syncCollectionMethods = { watch: true, find: true, aggregate: true }; + +/*! + * Copy the collection methods and make them subject to queues + */ + +function iter(i) { + NativeCollection.prototype[i] = function() { + const collection = this.collection; + const args = Array.from(arguments); + const _this = this; + const debug = get(_this, 'conn.base.options.debug'); + const lastArg = arguments[arguments.length - 1]; + const opId = new ObjectId(); + + // If user force closed, queueing will hang forever. See #5664 + if (this.conn.$wasForceClosed) { + const error = new MongooseError('Connection was force closed'); + if (args.length > 0 && + typeof args[args.length - 1] === 'function') { + args[args.length - 1](error); + return; + } else { + throw error; + } + } + + let _args = args; + let callback = null; + if (this._shouldBufferCommands() && this.buffer) { + if (syncCollectionMethods[i] && typeof lastArg !== 'function') { + throw new Error('Collection method ' + i + ' is synchronous'); + } + + this.conn.emit('buffer', { + _id: opId, + modelName: _this.modelName, + collectionName: _this.name, + method: i, + args: args + }); + + let callback; + let _args = args; + let promise = null; + let timeout = null; + if (syncCollectionMethods[i]) { + this.addQueue(() => { + lastArg.call(this, null, this[i].apply(this, _args.slice(0, _args.length - 1))); + }, []); + } else if (typeof lastArg === 'function') { + callback = function collectionOperationCallback() { + if (timeout != null) { + clearTimeout(timeout); + } + return lastArg.apply(this, arguments); + }; + _args = args.slice(0, args.length - 1).concat([callback]); + } else { + promise = new this.Promise((resolve, reject) => { + callback = function collectionOperationCallback(err, res) { + if (timeout != null) { + clearTimeout(timeout); + } + if (err != null) { + return reject(err); + } + resolve(res); + }; + _args = args.concat([callback]); + this.addQueue(i, _args); + }); + } + + const bufferTimeoutMS = this._getBufferTimeoutMS(); + timeout = setTimeout(() => { + const removed = this.removeQueue(i, _args); + if (removed) { + const message = 'Operation `' + this.name + '.' + i + '()` buffering timed out after ' + + bufferTimeoutMS + 'ms'; + const err = new MongooseError(message); + this.conn.emit('buffer-end', { _id: opId, modelName: _this.modelName, collectionName: _this.name, method: i, error: err }); + callback(err); + } + }, bufferTimeoutMS); + + if (!syncCollectionMethods[i] && typeof lastArg === 'function') { + this.addQueue(i, _args); + return; + } + + return promise; + } else if (!syncCollectionMethods[i] && typeof lastArg === 'function') { + callback = function collectionOperationCallback(err, res) { + if (err != null) { + _this.conn.emit('operation-end', { _id: opId, modelName: _this.modelName, collectionName: _this.name, method: i, error: err }); + } else { + _this.conn.emit('operation-end', { _id: opId, modelName: _this.modelName, collectionName: _this.name, method: i, result: res }); + } + return lastArg.apply(this, arguments); + }; + _args = args.slice(0, args.length - 1).concat([callback]); + } + + if (debug) { + if (typeof debug === 'function') { + debug.apply(_this, + [_this.name, i].concat(sliced(args, 0, args.length - 1))); + } else if (debug instanceof stream.Writable) { + this.$printToStream(_this.name, i, args, debug); + } else { + const color = debug.color == null ? true : debug.color; + const shell = debug.shell == null ? false : debug.shell; + this.$print(_this.name, i, args, color, shell); + } + } + + this.conn.emit('operation-start', { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, params: _args }); + + try { + if (collection == null) { + const message = 'Cannot call `' + this.name + '.' + i + '()` before initial connection ' + + 'is complete if `bufferCommands = false`. Make sure you `await mongoose.connect()` if ' + + 'you have `bufferCommands = false`.'; + throw new MongooseError(message); + } + + if (syncCollectionMethods[i] && typeof lastArg === 'function') { + return lastArg.call(this, null, collection[i].apply(collection, _args.slice(0, _args.length - 1))); + } + + const ret = collection[i].apply(collection, _args); + if (ret != null && typeof ret.then === 'function') { + return ret.then( + res => { + this.conn.emit('operation-end', { _id: opId, modelName: this.modelName, collectionName: this.name, method: i, result: res }); + return res; + }, + err => { + this.conn.emit('operation-end', { _id: opId, modelName: this.modelName, collectionName: this.name, method: i, error: err }); + throw err; + } + ); + } + return ret; + } catch (error) { + // Collection operation may throw because of max bson size, catch it here + // See gh-3906 + if (typeof callback === 'function') { + callback(error); + } else { + this.conn.emit('operation-end', { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, error: error }); + } + if (typeof lastArg === 'function') { + lastArg(error); + } else { + throw error; + } + } + }; +} + +for (const key of Object.getOwnPropertyNames(Collection.prototype)) { + // Janky hack to work around gh-3005 until we can get rid of the mongoose + // collection abstraction + const descriptor = Object.getOwnPropertyDescriptor(Collection.prototype, key); + // Skip properties with getters because they may throw errors (gh-8528) + if (descriptor.get !== undefined) { + continue; + } + if (typeof Collection.prototype[key] !== 'function') { + continue; + } + + iter(key); +} + +/** + * Debug print helper + * + * @api public + * @method $print + */ + +NativeCollection.prototype.$print = function(name, i, args, color, shell) { + const moduleName = color ? '\x1B[0;36mMongoose:\x1B[0m ' : 'Mongoose: '; + const functionCall = [name, i].join('.'); + const _args = []; + for (let j = args.length - 1; j >= 0; --j) { + if (this.$format(args[j]) || _args.length) { + _args.unshift(this.$format(args[j], color, shell)); + } + } + const params = '(' + _args.join(', ') + ')'; + + console.info(moduleName + functionCall + params); +}; + +/** + * Debug print helper + * + * @api public + * @method $print + */ + +NativeCollection.prototype.$printToStream = function(name, i, args, stream) { + const functionCall = [name, i].join('.'); + const _args = []; + for (let j = args.length - 1; j >= 0; --j) { + if (this.$format(args[j]) || _args.length) { + _args.unshift(this.$format(args[j])); + } + } + const params = '(' + _args.join(', ') + ')'; + + stream.write(functionCall + params, 'utf8'); +}; + +/** + * Formatter for debug print args + * + * @api public + * @method $format + */ + +NativeCollection.prototype.$format = function(arg, color, shell) { + const type = typeof arg; + if (type === 'function' || type === 'undefined') return ''; + return format(arg, false, color, shell); +}; + +/*! + * Debug print helper + */ + +function inspectable(representation) { + const ret = { + inspect: function() { return representation; } + }; + if (util.inspect.custom) { + ret[util.inspect.custom] = ret.inspect; + } + return ret; +} +function map(o) { + return format(o, true); +} +function formatObjectId(x, key) { + x[key] = inspectable('ObjectId("' + x[key].toHexString() + '")'); +} +function formatDate(x, key, shell) { + if (shell) { + x[key] = inspectable('ISODate("' + x[key].toUTCString() + '")'); + } else { + x[key] = inspectable('new Date("' + x[key].toUTCString() + '")'); + } +} +function format(obj, sub, color, shell) { + if (obj && typeof obj.toBSON === 'function') { + obj = obj.toBSON(); + } + if (obj == null) { + return obj; + } + + const clone = require('../../helpers/clone'); + let x = clone(obj, { transform: false }); + const constructorName = getConstructorName(x); + + if (constructorName === 'Binary') { + x = 'BinData(' + x.sub_type + ', "' + x.toString('base64') + '")'; + } else if (constructorName === 'ObjectID') { + x = inspectable('ObjectId("' + x.toHexString() + '")'); + } else if (constructorName === 'Date') { + x = inspectable('new Date("' + x.toUTCString() + '")'); + } else if (constructorName === 'Object') { + const keys = Object.keys(x); + const numKeys = keys.length; + let key; + for (let i = 0; i < numKeys; ++i) { + key = keys[i]; + if (x[key]) { + let error; + if (typeof x[key].toBSON === 'function') { + try { + // `session.toBSON()` throws an error. This means we throw errors + // in debug mode when using transactions, see gh-6712. As a + // workaround, catch `toBSON()` errors, try to serialize without + // `toBSON()`, and rethrow if serialization still fails. + x[key] = x[key].toBSON(); + } catch (_error) { + error = _error; + } + } + const _constructorName = getConstructorName(x[key]); + if (_constructorName === 'Binary') { + x[key] = 'BinData(' + x[key].sub_type + ', "' + + x[key].buffer.toString('base64') + '")'; + } else if (_constructorName === 'Object') { + x[key] = format(x[key], true); + } else if (_constructorName === 'ObjectID') { + formatObjectId(x, key); + } else if (_constructorName === 'Date') { + formatDate(x, key, shell); + } else if (_constructorName === 'ClientSession') { + x[key] = inspectable('ClientSession("' + + get(x[key], 'id.id.buffer', '').toString('hex') + '")'); + } else if (Array.isArray(x[key])) { + x[key] = x[key].map(map); + } else if (error != null) { + // If there was an error with `toBSON()` and the object wasn't + // already converted to a string representation, rethrow it. + // Open to better ideas on how to handle this. + throw error; + } + } + } + } + if (sub) { + return x; + } + + return util. + inspect(x, false, 10, color). + replace(/\n/g, ''). + replace(/\s{2,}/g, ' '); +} + +/** + * Retrieves information about this collections indexes. + * + * @param {Function} callback + * @method getIndexes + * @api public + */ + +NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation; + +/*! + * Module exports. + */ + +module.exports = NativeCollection; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js new file mode 100644 index 0000000..f976c55 --- /dev/null +++ b/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js @@ -0,0 +1,153 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseConnection = require('../../connection'); +const STATES = require('../../connectionstate'); +const immediate = require('../../helpers/immediate'); +const setTimeout = require('../../helpers/timers').setTimeout; + +/** + * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation. + * + * @inherits Connection + * @api private + */ + +function NativeConnection() { + MongooseConnection.apply(this, arguments); + this._listening = false; +} + +/** + * Expose the possible connection states. + * @api public + */ + +NativeConnection.STATES = STATES; + +/*! + * Inherits from Connection. + */ + +NativeConnection.prototype.__proto__ = MongooseConnection.prototype; + +/** + * Switches to a different database using the same connection pool. + * + * Returns a new connection object, with the new db. If you set the `useCache` + * option, `useDb()` will cache connections by `name`. + * + * **Note:** Calling `close()` on a `useDb()` connection will close the base connection as well. + * + * @param {String} name The database name + * @param {Object} [options] + * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object. + * @param {Boolean} [options.noListener=false] If true, the new connection object won't listen to any events on the base connection. This is better for memory usage in cases where you're calling `useDb()` for every request. + * @return {Connection} New Connection Object + * @api public + */ + +NativeConnection.prototype.useDb = function(name, options) { + // Return immediately if cached + options = options || {}; + if (options.useCache && this.relatedDbs[name]) { + return this.relatedDbs[name]; + } + + // we have to manually copy all of the attributes... + const newConn = new this.constructor(); + newConn.name = name; + newConn.base = this.base; + newConn.collections = {}; + newConn.models = {}; + newConn.replica = this.replica; + newConn.config = Object.assign({}, this.config, newConn.config); + newConn.name = this.name; + newConn.options = this.options; + newConn._readyState = this._readyState; + newConn._closeCalled = this._closeCalled; + newConn._hasOpened = this._hasOpened; + newConn._listening = false; + + newConn.host = this.host; + newConn.port = this.port; + newConn.user = this.user; + newConn.pass = this.pass; + + // First, when we create another db object, we are not guaranteed to have a + // db object to work with. So, in the case where we have a db object and it + // is connected, we can just proceed with setting everything up. However, if + // we do not have a db or the state is not connected, then we need to wait on + // the 'open' event of the connection before doing the rest of the setup + // the 'connected' event is the first time we'll have access to the db object + + const _this = this; + + newConn.client = _this.client; + + if (this.db && this._readyState === STATES.connected) { + wireup(); + } else { + this.once('connected', wireup); + } + + function wireup() { + newConn.client = _this.client; + const _opts = {}; + if (options.hasOwnProperty('noListener')) { + _opts.noListener = options.noListener; + } + newConn.db = _this.client.db(name, _opts); + newConn.onOpen(); + } + + newConn.name = name; + + // push onto the otherDbs stack, this is used when state changes + if (options.noListener !== true) { + this.otherDbs.push(newConn); + } + newConn.otherDbs.push(this); + + // push onto the relatedDbs cache, this is used when state changes + if (options && options.useCache) { + this.relatedDbs[newConn.name] = newConn; + newConn.relatedDbs = this.relatedDbs; + } + + return newConn; +}; + +/** + * Closes the connection + * + * @param {Boolean} [force] + * @param {Function} [fn] + * @return {Connection} this + * @api private + */ + +NativeConnection.prototype.doClose = function(force, fn) { + if (this.client == null) { + immediate(() => fn()); + return this; + } + + this.client.close(force, (err, res) => { + // Defer because the driver will wait at least 1ms before finishing closing + // the pool, see https://github.com/mongodb-js/mongodb-core/blob/a8f8e4ce41936babc3b9112bf42d609779f03b39/lib/connection/pool.js#L1026-L1030. + // If there's queued operations, you may still get some background work + // after the callback is called. + setTimeout(() => fn(err, res), 1); + }); + return this; +}; + +/*! + * Module exports. + */ + +module.exports = NativeConnection; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/decimal128.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/decimal128.js new file mode 100644 index 0000000..c895f17 --- /dev/null +++ b/node_modules/mongoose/lib/drivers/node-mongodb-native/decimal128.js @@ -0,0 +1,7 @@ +/*! + * ignore + */ + +'use strict'; + +module.exports = require('mongodb').Decimal128; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js new file mode 100644 index 0000000..2ed9eb0 --- /dev/null +++ b/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js @@ -0,0 +1,12 @@ +/*! + * Module exports. + */ + +'use strict'; + +exports.Binary = require('./binary'); +exports.Collection = require('./collection'); +exports.Decimal128 = require('./decimal128'); +exports.ObjectId = require('./objectid'); +exports.ReadPreference = require('./ReadPreference'); +exports.getConnection = () => require('./connection'); \ No newline at end of file diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js new file mode 100644 index 0000000..6f432b7 --- /dev/null +++ b/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js @@ -0,0 +1,16 @@ + +/*! + * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId + * @constructor NodeMongoDbObjectId + * @see ObjectId + */ + +'use strict'; + +const ObjectId = require('mongodb').ObjectId; + +/*! + * ignore + */ + +module.exports = exports = ObjectId; diff --git a/node_modules/mongoose/lib/error/browserMissingSchema.js b/node_modules/mongoose/lib/error/browserMissingSchema.js new file mode 100644 index 0000000..fe492d5 --- /dev/null +++ b/node_modules/mongoose/lib/error/browserMissingSchema.js @@ -0,0 +1,28 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseError = require('./'); + + +class MissingSchemaError extends MongooseError { + /*! + * MissingSchema Error constructor. + */ + constructor() { + super('Schema hasn\'t been registered for document.\n' + + 'Use mongoose.Document(name, schema)'); + } +} + +Object.defineProperty(MissingSchemaError.prototype, 'name', { + value: 'MongooseError' +}); + +/*! + * exports + */ + +module.exports = MissingSchemaError; diff --git a/node_modules/mongoose/lib/error/cast.js b/node_modules/mongoose/lib/error/cast.js new file mode 100644 index 0000000..dc604b5 --- /dev/null +++ b/node_modules/mongoose/lib/error/cast.js @@ -0,0 +1,150 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const MongooseError = require('./mongooseError'); +const get = require('../helpers/get'); +const util = require('util'); + +/** + * Casting Error constructor. + * + * @param {String} type + * @param {String} value + * @inherits MongooseError + * @api private + */ + +class CastError extends MongooseError { + constructor(type, value, path, reason, schemaType) { + // If no args, assume we'll `init()` later. + if (arguments.length > 0) { + const stringValue = getStringValue(value); + const valueType = getValueType(value); + const messageFormat = getMessageFormat(schemaType); + const msg = formatMessage(null, type, stringValue, path, messageFormat, valueType); + super(msg); + this.init(type, value, path, reason, schemaType); + } else { + super(formatMessage()); + } + } + + toJSON() { + return { + stringValue: this.stringValue, + valueType: this.valueType, + kind: this.kind, + value: this.value, + path: this.path, + reason: this.reason, + name: this.name, + message: this.message + }; + } + /*! + * ignore + */ + init(type, value, path, reason, schemaType) { + this.stringValue = getStringValue(value); + this.messageFormat = getMessageFormat(schemaType); + this.kind = type; + this.value = value; + this.path = path; + this.reason = reason; + this.valueType = getValueType(value); + } + + /*! + * ignore + * @param {Readonly} other + */ + copy(other) { + this.messageFormat = other.messageFormat; + this.stringValue = other.stringValue; + this.kind = other.kind; + this.value = other.value; + this.path = other.path; + this.reason = other.reason; + this.message = other.message; + this.valueType = other.valueType; + } + + /*! + * ignore + */ + setModel(model) { + this.model = model; + this.message = formatMessage(model, this.kind, this.stringValue, this.path, + this.messageFormat, this.valueType); + } +} + +Object.defineProperty(CastError.prototype, 'name', { + value: 'CastError' +}); + +function getStringValue(value) { + let stringValue = util.inspect(value); + stringValue = stringValue.replace(/^'|'$/g, '"'); + if (!stringValue.startsWith('"')) { + stringValue = '"' + stringValue + '"'; + } + return stringValue; +} + +function getValueType(value) { + if (value == null) { + return '' + value; + } + + const t = typeof value; + if (t !== 'object') { + return t; + } + if (typeof value.constructor !== 'function') { + return t; + } + return value.constructor.name; +} + +function getMessageFormat(schemaType) { + const messageFormat = get(schemaType, 'options.cast', null); + if (typeof messageFormat === 'string') { + return messageFormat; + } +} + +/*! + * ignore + */ + +function formatMessage(model, kind, stringValue, path, messageFormat, valueType) { + if (messageFormat != null) { + let ret = messageFormat. + replace('{KIND}', kind). + replace('{VALUE}', stringValue). + replace('{PATH}', path); + if (model != null) { + ret = ret.replace('{MODEL}', model.modelName); + } + + return ret; + } else { + const valueTypeMsg = valueType ? ' (type ' + valueType + ')' : ''; + let ret = 'Cast to ' + kind + ' failed for value ' + + stringValue + valueTypeMsg + ' at path "' + path + '"'; + if (model != null) { + ret += ' for model "' + model.modelName + '"'; + } + return ret; + } +} + +/*! + * exports + */ + +module.exports = CastError; diff --git a/node_modules/mongoose/lib/error/disconnected.js b/node_modules/mongoose/lib/error/disconnected.js new file mode 100644 index 0000000..777a1de --- /dev/null +++ b/node_modules/mongoose/lib/error/disconnected.js @@ -0,0 +1,34 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseError = require('./'); + + +/** + * The connection failed to reconnect and will never successfully reconnect to + * MongoDB without manual intervention. + * @api private + */ +class DisconnectedError extends MongooseError { + /** + * @param {String} connectionString + */ + constructor(connectionString) { + super('Ran out of retries trying to reconnect to "' + + connectionString + '". Try setting `server.reconnectTries` and ' + + '`server.reconnectInterval` to something higher.'); + } +} + +Object.defineProperty(DisconnectedError.prototype, 'name', { + value: 'DisconnectedError' +}); + +/*! + * exports + */ + +module.exports = DisconnectedError; diff --git a/node_modules/mongoose/lib/error/divergentArray.js b/node_modules/mongoose/lib/error/divergentArray.js new file mode 100644 index 0000000..ed86caf --- /dev/null +++ b/node_modules/mongoose/lib/error/divergentArray.js @@ -0,0 +1,37 @@ + +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseError = require('./'); + +class DivergentArrayError extends MongooseError { + /*! + * DivergentArrayError constructor. + * @param {Array} paths + */ + constructor(paths) { + const msg = 'For your own good, using `document.save()` to update an array ' + + 'which was selected using an $elemMatch projection OR ' + + 'populated using skip, limit, query conditions, or exclusion of ' + + 'the _id field when the operation results in a $pop or $set of ' + + 'the entire array is not supported. The following ' + + 'path(s) would have been modified unsafely:\n' + + ' ' + paths.join('\n ') + '\n' + + 'Use Model.update() to update these arrays instead.'; + // TODO write up a docs page (FAQ) and link to it + super(msg); + } +} + +Object.defineProperty(DivergentArrayError.prototype, 'name', { + value: 'DivergentArrayError' +}); + +/*! + * exports + */ + +module.exports = DivergentArrayError; diff --git a/node_modules/mongoose/lib/error/index.js b/node_modules/mongoose/lib/error/index.js new file mode 100644 index 0000000..ec4188d --- /dev/null +++ b/node_modules/mongoose/lib/error/index.js @@ -0,0 +1,205 @@ +'use strict'; + +/** + * MongooseError constructor. MongooseError is the base class for all + * Mongoose-specific errors. + * + * ####Example: + * const Model = mongoose.model('Test', new Schema({ answer: Number })); + * const doc = new Model({ answer: 'not a number' }); + * const err = doc.validateSync(); + * + * err instanceof mongoose.Error; // true + * + * @constructor Error + * @param {String} msg Error message + * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error + */ + +const MongooseError = require('./mongooseError'); + +/** + * The name of the error. The name uniquely identifies this Mongoose error. The + * possible values are: + * + * - `MongooseError`: general Mongoose error + * - `CastError`: Mongoose could not convert a value to the type defined in the schema path. May be in a `ValidationError` class' `errors` property. + * - `DisconnectedError`: This [connection](connections.html) timed out in trying to reconnect to MongoDB and will not successfully reconnect to MongoDB unless you explicitly reconnect. + * - `DivergentArrayError`: You attempted to `save()` an array that was modified after you loaded it with a `$elemMatch` or similar projection + * - `MissingSchemaError`: You tried to access a model with [`mongoose.model()`](api.html#mongoose_Mongoose-model) that was not defined + * - `DocumentNotFoundError`: The document you tried to [`save()`](api.html#document_Document-save) was not found + * - `ValidatorError`: error from an individual schema path's validator + * - `ValidationError`: error returned from [`validate()`](api.html#document_Document-validate) or [`validateSync()`](api.html#document_Document-validateSync). Contains zero or more `ValidatorError` instances in `.errors` property. + * - `MissingSchemaError`: You called `mongoose.Document()` without a schema + * - `ObjectExpectedError`: Thrown when you set a nested path to a non-object value with [strict mode set](guide.html#strict). + * - `ObjectParameterError`: Thrown when you pass a non-object value to a function which expects an object as a paramter + * - `OverwriteModelError`: Thrown when you call [`mongoose.model()`](api.html#mongoose_Mongoose-model) to re-define a model that was already defined. + * - `ParallelSaveError`: Thrown when you call [`save()`](api.html#model_Model-save) on a document when the same document instance is already saving. + * - `StrictModeError`: Thrown when you set a path that isn't the schema and [strict mode](guide.html#strict) is set to `throw`. + * - `VersionError`: Thrown when the [document is out of sync](guide.html#versionKey) + * + * @api public + * @property {String} name + * @memberOf Error + * @instance + */ + +/*! + * Module exports. + */ + +module.exports = exports = MongooseError; + +/** + * The default built-in validator error messages. + * + * @see Error.messages #error_messages_MongooseError-messages + * @api public + * @memberOf Error + * @static messages + */ + +MongooseError.messages = require('./messages'); + +// backward compat +MongooseError.Messages = MongooseError.messages; + +/** + * An instance of this error class will be returned when `save()` fails + * because the underlying + * document was not found. The constructor takes one parameter, the + * conditions that mongoose passed to `update()` when trying to update + * the document. + * + * @api public + * @memberOf Error + * @static DocumentNotFoundError + */ + +MongooseError.DocumentNotFoundError = require('./notFound'); + +/** + * An instance of this error class will be returned when mongoose failed to + * cast a value. + * + * @api public + * @memberOf Error + * @static CastError + */ + +MongooseError.CastError = require('./cast'); + +/** + * An instance of this error class will be returned when [validation](/docs/validation.html) failed. + * The `errors` property contains an object whose keys are the paths that failed and whose values are + * instances of CastError or ValidationError. + * + * @api public + * @memberOf Error + * @static ValidationError + */ + +MongooseError.ValidationError = require('./validation'); + +/** + * A `ValidationError` has a hash of `errors` that contain individual + * `ValidatorError` instances. + * + * ####Example: + * + * const schema = Schema({ name: { type: String, required: true } }); + * const Model = mongoose.model('Test', schema); + * const doc = new Model({}); + * + * // Top-level error is a ValidationError, **not** a ValidatorError + * const err = doc.validateSync(); + * err instanceof mongoose.Error.ValidationError; // true + * + * // A ValidationError `err` has 0 or more ValidatorErrors keyed by the + * // path in the `err.errors` property. + * err.errors['name'] instanceof mongoose.Error.ValidatorError; + * + * err.errors['name'].kind; // 'required' + * err.errors['name'].path; // 'name' + * err.errors['name'].value; // undefined + * + * Instances of `ValidatorError` have the following properties: + * + * - `kind`: The validator's `type`, like `'required'` or `'regexp'` + * - `path`: The path that failed validation + * - `value`: The value that failed validation + * + * @api public + * @memberOf Error + * @static ValidatorError + */ + +MongooseError.ValidatorError = require('./validator'); + +/** + * An instance of this error class will be returned when you call `save()` after + * the document in the database was changed in a potentially unsafe way. See + * the [`versionKey` option](/docs/guide.html#versionKey) for more information. + * + * @api public + * @memberOf Error + * @static VersionError + */ + +MongooseError.VersionError = require('./version'); + +/** + * An instance of this error class will be returned when you call `save()` multiple + * times on the same document in parallel. See the [FAQ](/docs/faq.html) for more + * information. + * + * @api public + * @memberOf Error + * @static ParallelSaveError + */ + +MongooseError.ParallelSaveError = require('./parallelSave'); + +/** + * Thrown when a model with the given name was already registered on the connection. + * See [the FAQ about `OverwriteModelError`](/docs/faq.html#overwrite-model-error). + * + * @api public + * @memberOf Error + * @static OverwriteModelError + */ + +MongooseError.OverwriteModelError = require('./overwriteModel'); + +/** + * Thrown when you try to access a model that has not been registered yet + * + * @api public + * @memberOf Error + * @static MissingSchemaError + */ + +MongooseError.MissingSchemaError = require('./missingSchema'); + +/** + * An instance of this error will be returned if you used an array projection + * and then modified the array in an unsafe way. + * + * @api public + * @memberOf Error + * @static DivergentArrayError + */ + +MongooseError.DivergentArrayError = require('./divergentArray'); + +/** + * Thrown when your try to pass values to model contrtuctor that + * were not specified in schema or change immutable properties when + * `strict` mode is `"throw"` + * + * @api public + * @memberOf Error + * @static StrictModeError + */ + +MongooseError.StrictModeError = require('./strict'); diff --git a/node_modules/mongoose/lib/error/messages.js b/node_modules/mongoose/lib/error/messages.js new file mode 100644 index 0000000..ac0294a --- /dev/null +++ b/node_modules/mongoose/lib/error/messages.js @@ -0,0 +1,47 @@ + +/** + * The default built-in validator error messages. These may be customized. + * + * // customize within each schema or globally like so + * const mongoose = require('mongoose'); + * mongoose.Error.messages.String.enum = "Your custom message for {PATH}."; + * + * As you might have noticed, error messages support basic templating + * + * - `{PATH}` is replaced with the invalid document path + * - `{VALUE}` is replaced with the invalid value + * - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined" + * - `{MIN}` is replaced with the declared min value for the Number.min validator + * - `{MAX}` is replaced with the declared max value for the Number.max validator + * + * Click the "show code" link below to see all defaults. + * + * @static messages + * @receiver MongooseError + * @api public + */ + +'use strict'; + +const msg = module.exports = exports = {}; + +msg.DocumentNotFoundError = null; + +msg.general = {}; +msg.general.default = 'Validator failed for path `{PATH}` with value `{VALUE}`'; +msg.general.required = 'Path `{PATH}` is required.'; + +msg.Number = {}; +msg.Number.min = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).'; +msg.Number.max = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).'; +msg.Number.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; + +msg.Date = {}; +msg.Date.min = 'Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).'; +msg.Date.max = 'Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).'; + +msg.String = {}; +msg.String.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; +msg.String.match = 'Path `{PATH}` is invalid ({VALUE}).'; +msg.String.minlength = 'Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'; +msg.String.maxlength = 'Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).'; diff --git a/node_modules/mongoose/lib/error/missingSchema.js b/node_modules/mongoose/lib/error/missingSchema.js new file mode 100644 index 0000000..ca306b7 --- /dev/null +++ b/node_modules/mongoose/lib/error/missingSchema.js @@ -0,0 +1,30 @@ + +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseError = require('./'); + +class MissingSchemaError extends MongooseError { + /*! + * MissingSchema Error constructor. + * @param {String} name + */ + constructor(name) { + const msg = 'Schema hasn\'t been registered for model "' + name + '".\n' + + 'Use mongoose.model(name, schema)'; + super(msg); + } +} + +Object.defineProperty(MissingSchemaError.prototype, 'name', { + value: 'MissingSchemaError' +}); + +/*! + * exports + */ + +module.exports = MissingSchemaError; diff --git a/node_modules/mongoose/lib/error/mongooseError.js b/node_modules/mongoose/lib/error/mongooseError.js new file mode 100644 index 0000000..5505105 --- /dev/null +++ b/node_modules/mongoose/lib/error/mongooseError.js @@ -0,0 +1,13 @@ +'use strict'; + +/*! + * ignore + */ + +class MongooseError extends Error { } + +Object.defineProperty(MongooseError.prototype, 'name', { + value: 'MongooseError' +}); + +module.exports = MongooseError; diff --git a/node_modules/mongoose/lib/error/notFound.js b/node_modules/mongoose/lib/error/notFound.js new file mode 100644 index 0000000..0e8386b --- /dev/null +++ b/node_modules/mongoose/lib/error/notFound.js @@ -0,0 +1,44 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const MongooseError = require('./'); +const util = require('util'); + +class DocumentNotFoundError extends MongooseError { + /*! + * OverwriteModel Error constructor. + */ + constructor(filter, model, numAffected, result) { + let msg; + const messages = MongooseError.messages; + if (messages.DocumentNotFoundError != null) { + msg = typeof messages.DocumentNotFoundError === 'function' ? + messages.DocumentNotFoundError(filter, model) : + messages.DocumentNotFoundError; + } else { + msg = 'No document found for query "' + util.inspect(filter) + + '" on model "' + model + '"'; + } + + super(msg); + + this.result = result; + this.numAffected = numAffected; + this.filter = filter; + // Backwards compat + this.query = filter; + } +} + +Object.defineProperty(DocumentNotFoundError.prototype, 'name', { + value: 'DocumentNotFoundError' +}); + +/*! + * exports + */ + +module.exports = DocumentNotFoundError; diff --git a/node_modules/mongoose/lib/error/objectExpected.js b/node_modules/mongoose/lib/error/objectExpected.js new file mode 100644 index 0000000..6506f60 --- /dev/null +++ b/node_modules/mongoose/lib/error/objectExpected.js @@ -0,0 +1,30 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseError = require('./'); + + +class ObjectExpectedError extends MongooseError { + /** + * Strict mode error constructor + * + * @param {string} type + * @param {string} value + * @api private + */ + constructor(path, val) { + const typeDescription = Array.isArray(val) ? 'array' : 'primitive value'; + super('Tried to set nested object field `' + path + + `\` to ${typeDescription} \`` + val + '`'); + this.path = path; + } +} + +Object.defineProperty(ObjectExpectedError.prototype, 'name', { + value: 'ObjectExpectedError' +}); + +module.exports = ObjectExpectedError; diff --git a/node_modules/mongoose/lib/error/objectParameter.js b/node_modules/mongoose/lib/error/objectParameter.js new file mode 100644 index 0000000..5881a48 --- /dev/null +++ b/node_modules/mongoose/lib/error/objectParameter.js @@ -0,0 +1,30 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseError = require('./'); + +class ObjectParameterError extends MongooseError { + /** + * Constructor for errors that happen when a parameter that's expected to be + * an object isn't an object + * + * @param {Any} value + * @param {String} paramName + * @param {String} fnName + * @api private + */ + constructor(value, paramName, fnName) { + super('Parameter "' + paramName + '" to ' + fnName + + '() must be an object, got ' + value.toString()); + } +} + + +Object.defineProperty(ObjectParameterError.prototype, 'name', { + value: 'ObjectParameterError' +}); + +module.exports = ObjectParameterError; diff --git a/node_modules/mongoose/lib/error/overwriteModel.js b/node_modules/mongoose/lib/error/overwriteModel.js new file mode 100644 index 0000000..d509e19 --- /dev/null +++ b/node_modules/mongoose/lib/error/overwriteModel.js @@ -0,0 +1,29 @@ + +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseError = require('./'); + + +class OverwriteModelError extends MongooseError { + /*! + * OverwriteModel Error constructor. + * @param {String} name + */ + constructor(name) { + super('Cannot overwrite `' + name + '` model once compiled.'); + } +} + +Object.defineProperty(OverwriteModelError.prototype, 'name', { + value: 'OverwriteModelError' +}); + +/*! + * exports + */ + +module.exports = OverwriteModelError; diff --git a/node_modules/mongoose/lib/error/parallelSave.js b/node_modules/mongoose/lib/error/parallelSave.js new file mode 100644 index 0000000..e062857 --- /dev/null +++ b/node_modules/mongoose/lib/error/parallelSave.js @@ -0,0 +1,30 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const MongooseError = require('./'); + +class ParallelSaveError extends MongooseError { + /** + * ParallelSave Error constructor. + * + * @param {Document} doc + * @api private + */ + constructor(doc) { + const msg = 'Can\'t save() the same doc multiple times in parallel. Document: '; + super(msg + doc._id); + } +} + +Object.defineProperty(ParallelSaveError.prototype, 'name', { + value: 'ParallelSaveError' +}); + +/*! + * exports + */ + +module.exports = ParallelSaveError; diff --git a/node_modules/mongoose/lib/error/parallelValidate.js b/node_modules/mongoose/lib/error/parallelValidate.js new file mode 100644 index 0000000..18697b6 --- /dev/null +++ b/node_modules/mongoose/lib/error/parallelValidate.js @@ -0,0 +1,31 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const MongooseError = require('./mongooseError'); + + +class ParallelValidateError extends MongooseError { + /** + * ParallelValidate Error constructor. + * + * @param {Document} doc + * @api private + */ + constructor(doc) { + const msg = 'Can\'t validate() the same doc multiple times in parallel. Document: '; + super(msg + doc._id); + } +} + +Object.defineProperty(ParallelValidateError.prototype, 'name', { + value: 'ParallelValidateError' +}); + +/*! + * exports + */ + +module.exports = ParallelValidateError; \ No newline at end of file diff --git a/node_modules/mongoose/lib/error/serverSelection.js b/node_modules/mongoose/lib/error/serverSelection.js new file mode 100644 index 0000000..162e2fc --- /dev/null +++ b/node_modules/mongoose/lib/error/serverSelection.js @@ -0,0 +1,61 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseError = require('./mongooseError'); +const allServersUnknown = require('../helpers/topology/allServersUnknown'); +const isAtlas = require('../helpers/topology/isAtlas'); +const isSSLError = require('../helpers/topology/isSSLError'); + +/*! + * ignore + */ + +const atlasMessage = 'Could not connect to any servers in your MongoDB Atlas cluster. ' + + 'One common reason is that you\'re trying to access the database from ' + + 'an IP that isn\'t whitelisted. Make sure your current IP address is on your Atlas ' + + 'cluster\'s IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/'; + +const sslMessage = 'Mongoose is connecting with SSL enabled, but the server is ' + + 'not accepting SSL connections. Please ensure that the MongoDB server you are ' + + 'connecting to is configured to accept SSL connections. Learn more: ' + + 'https://mongoosejs.com/docs/tutorials/ssl.html'; + +class MongooseServerSelectionError extends MongooseError { + /** + * MongooseServerSelectionError constructor + * + * @api private + */ + assimilateError(err) { + const reason = err.reason; + // Special message for a case that is likely due to IP whitelisting issues. + const isAtlasWhitelistError = isAtlas(reason) && + allServersUnknown(reason) && + err.message.indexOf('bad auth') === -1 && + err.message.indexOf('Authentication failed') === -1; + + if (isAtlasWhitelistError) { + this.message = atlasMessage; + } else if (isSSLError(reason)) { + this.message = sslMessage; + } else { + this.message = err.message; + } + for (const key in err) { + if (key !== 'name') { + this[key] = err[key]; + } + } + + return this; + } +} + +Object.defineProperty(MongooseServerSelectionError.prototype, 'name', { + value: 'MongooseServerSelectionError' +}); + +module.exports = MongooseServerSelectionError; diff --git a/node_modules/mongoose/lib/error/strict.js b/node_modules/mongoose/lib/error/strict.js new file mode 100644 index 0000000..393ca6e --- /dev/null +++ b/node_modules/mongoose/lib/error/strict.js @@ -0,0 +1,33 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseError = require('./'); + + +class StrictModeError extends MongooseError { + /** + * Strict mode error constructor + * + * @param {String} path + * @param {String} [msg] + * @param {Boolean} [immutable] + * @inherits MongooseError + * @api private + */ + constructor(path, msg, immutable) { + msg = msg || 'Field `' + path + '` is not in schema and strict ' + + 'mode is set to throw.'; + super(msg); + this.isImmutableError = !!immutable; + this.path = path; + } +} + +Object.defineProperty(StrictModeError.prototype, 'name', { + value: 'StrictModeError' +}); + +module.exports = StrictModeError; diff --git a/node_modules/mongoose/lib/error/validation.js b/node_modules/mongoose/lib/error/validation.js new file mode 100644 index 0000000..5ca993a --- /dev/null +++ b/node_modules/mongoose/lib/error/validation.js @@ -0,0 +1,112 @@ +/*! + * Module requirements + */ + +'use strict'; + +const MongooseError = require('./mongooseError'); +const getConstructorName = require('../helpers/getConstructorName'); +const util = require('util'); + +class ValidationError extends MongooseError { + /** + * Document Validation Error + * + * @api private + * @param {Document} [instance] + * @inherits MongooseError + */ + constructor(instance) { + let _message; + if (getConstructorName(instance) === 'model') { + _message = instance.constructor.modelName + ' validation failed'; + } else { + _message = 'Validation failed'; + } + + super(_message); + + this.errors = {}; + this._message = _message; + + if (instance) { + instance.$errors = this.errors; + } + } + + /** + * Console.log helper + */ + toString() { + return this.name + ': ' + _generateMessage(this); + } + + /*! + * inspect helper + */ + inspect() { + return Object.assign(new Error(this.message), this); + } + + /*! + * add message + */ + addError(path, error) { + this.errors[path] = error; + this.message = this._message + ': ' + _generateMessage(this); + } +} + + +if (util.inspect.custom) { + /*! + * Avoid Node deprecation warning DEP0079 + */ + + ValidationError.prototype[util.inspect.custom] = ValidationError.prototype.inspect; +} + +/*! + * Helper for JSON.stringify + * Ensure `name` and `message` show up in toJSON output re: gh-9847 + */ +Object.defineProperty(ValidationError.prototype, 'toJSON', { + enumerable: false, + writable: false, + configurable: true, + value: function() { + return Object.assign({}, this, { name: this.name, message: this.message }); + } +}); + + +Object.defineProperty(ValidationError.prototype, 'name', { + value: 'ValidationError' +}); + +/*! + * ignore + */ + +function _generateMessage(err) { + const keys = Object.keys(err.errors || {}); + const len = keys.length; + const msgs = []; + let key; + + for (let i = 0; i < len; ++i) { + key = keys[i]; + if (err === err.errors[key]) { + continue; + } + msgs.push(key + ': ' + err.errors[key].message); + } + + return msgs.join(', '); +} + +/*! + * Module exports + */ + +module.exports = ValidationError; diff --git a/node_modules/mongoose/lib/error/validator.js b/node_modules/mongoose/lib/error/validator.js new file mode 100644 index 0000000..f880e2b --- /dev/null +++ b/node_modules/mongoose/lib/error/validator.js @@ -0,0 +1,94 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseError = require('./'); + + +class ValidatorError extends MongooseError { + /** + * Schema validator error + * + * @param {Object} properties + * @api private + */ + constructor(properties) { + let msg = properties.message; + if (!msg) { + msg = MongooseError.messages.general.default; + } + + const message = formatMessage(msg, properties); + super(message); + + properties = Object.assign({}, properties, { message: message }); + this.properties = properties; + this.kind = properties.type; + this.path = properties.path; + this.value = properties.value; + this.reason = properties.reason; + } + + /*! + * toString helper + * TODO remove? This defaults to `${this.name}: ${this.message}` + */ + toString() { + return this.message; + } + + /*! + * Ensure `name` and `message` show up in toJSON output re: gh-9296 + */ + + toJSON() { + return Object.assign({ name: this.name, message: this.message }, this); + } +} + + +Object.defineProperty(ValidatorError.prototype, 'name', { + value: 'ValidatorError' +}); + +/*! + * The object used to define this validator. Not enumerable to hide + * it from `require('util').inspect()` output re: gh-3925 + */ + +Object.defineProperty(ValidatorError.prototype, 'properties', { + enumerable: false, + writable: true, + value: null +}); + +// Exposed for testing +ValidatorError.prototype.formatMessage = formatMessage; + +/*! + * Formats error messages + */ + +function formatMessage(msg, properties) { + if (typeof msg === 'function') { + return msg(properties); + } + + const propertyNames = Object.keys(properties); + for (const propertyName of propertyNames) { + if (propertyName === 'message') { + continue; + } + msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); + } + + return msg; +} + +/*! + * exports + */ + +module.exports = ValidatorError; diff --git a/node_modules/mongoose/lib/error/version.js b/node_modules/mongoose/lib/error/version.js new file mode 100644 index 0000000..b357fb1 --- /dev/null +++ b/node_modules/mongoose/lib/error/version.js @@ -0,0 +1,36 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const MongooseError = require('./'); + +class VersionError extends MongooseError { + /** + * Version Error constructor. + * + * @param {Document} doc + * @param {Number} currentVersion + * @param {Array} modifiedPaths + * @api private + */ + constructor(doc, currentVersion, modifiedPaths) { + const modifiedPathsStr = modifiedPaths.join(', '); + super('No matching document found for id "' + doc._id + + '" version ' + currentVersion + ' modifiedPaths "' + modifiedPathsStr + '"'); + this.version = currentVersion; + this.modifiedPaths = modifiedPaths; + } +} + + +Object.defineProperty(VersionError.prototype, 'name', { + value: 'VersionError' +}); + +/*! + * exports + */ + +module.exports = VersionError; diff --git a/node_modules/mongoose/lib/helpers/aggregate/stringifyFunctionOperators.js b/node_modules/mongoose/lib/helpers/aggregate/stringifyFunctionOperators.js new file mode 100644 index 0000000..124418e --- /dev/null +++ b/node_modules/mongoose/lib/helpers/aggregate/stringifyFunctionOperators.js @@ -0,0 +1,50 @@ +'use strict'; + +module.exports = function stringifyFunctionOperators(pipeline) { + if (!Array.isArray(pipeline)) { + return; + } + + for (const stage of pipeline) { + if (stage == null) { + continue; + } + + const canHaveAccumulator = stage.$group || stage.$bucket || stage.$bucketAuto; + if (canHaveAccumulator != null) { + for (const key of Object.keys(canHaveAccumulator)) { + handleAccumulator(canHaveAccumulator[key]); + } + } + + const stageType = Object.keys(stage)[0]; + if (stageType && typeof stage[stageType] === 'object') { + const stageOptions = stage[stageType]; + for (const key of Object.keys(stageOptions)) { + if (stageOptions[key] != null && + stageOptions[key].$function != null && + typeof stageOptions[key].$function.body === 'function') { + stageOptions[key].$function.body = stageOptions[key].$function.body.toString(); + } + } + } + + if (stage.$facet != null) { + for (const key of Object.keys(stage.$facet)) { + stringifyFunctionOperators(stage.$facet[key]); + } + } + } +}; + +function handleAccumulator(operator) { + if (operator == null || operator.$accumulator == null) { + return; + } + + for (const key of ['init', 'accumulate', 'merge', 'finalize']) { + if (typeof operator.$accumulator[key] === 'function') { + operator.$accumulator[key] = String(operator.$accumulator[key]); + } + } +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/arrayDepth.js b/node_modules/mongoose/lib/helpers/arrayDepth.js new file mode 100644 index 0000000..e55de7f --- /dev/null +++ b/node_modules/mongoose/lib/helpers/arrayDepth.js @@ -0,0 +1,33 @@ +'use strict'; + +module.exports = arrayDepth; + +function arrayDepth(arr) { + if (!Array.isArray(arr)) { + return { min: 0, max: 0, containsNonArrayItem: true }; + } + if (arr.length === 0) { + return { min: 1, max: 1, containsNonArrayItem: false }; + } + if (arr.length === 1 && !Array.isArray(arr[0])) { + return { min: 1, max: 1, containsNonArrayItem: false }; + } + + const res = arrayDepth(arr[0]); + + for (let i = 1; i < arr.length; ++i) { + const _res = arrayDepth(arr[i]); + if (_res.min < res.min) { + res.min = _res.min; + } + if (_res.max > res.max) { + res.max = _res.max; + } + res.containsNonArrayItem = res.containsNonArrayItem || _res.containsNonArrayItem; + } + + res.min = res.min + 1; + res.max = res.max + 1; + + return res; +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/clone.js b/node_modules/mongoose/lib/helpers/clone.js new file mode 100644 index 0000000..4cdd9ec --- /dev/null +++ b/node_modules/mongoose/lib/helpers/clone.js @@ -0,0 +1,148 @@ +'use strict'; + + +const cloneRegExp = require('regexp-clone'); +const Decimal = require('../types/decimal128'); +const ObjectId = require('../types/objectid'); +const specialProperties = require('./specialProperties'); +const isMongooseObject = require('./isMongooseObject'); +const getFunctionName = require('./getFunctionName'); +const isBsonType = require('./isBsonType'); +const isObject = require('./isObject'); +const symbols = require('./symbols'); +const trustedSymbol = require('./query/trusted').trustedSymbol; +const utils = require('../utils'); + + +/*! + * Object clone with Mongoose natives support. + * + * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. + * + * Functions are never cloned. + * + * @param {Object} obj the object to clone + * @param {Object} options + * @param {Boolean} isArrayChild true if cloning immediately underneath an array. Special case for minimize. + * @return {Object} the cloned object + * @api private + */ + +function clone(obj, options, isArrayChild) { + if (obj == null) { + return obj; + } + + if (Array.isArray(obj)) { + return cloneArray(obj, options); + } + + if (isMongooseObject(obj)) { + // Single nested subdocs should apply getters later in `applyGetters()` + // when calling `toObject()`. See gh-7442, gh-8295 + if (options && options._skipSingleNestedGetters && obj.$isSingleNested) { + options = Object.assign({}, options, { getters: false }); + } + + if (utils.isPOJO(obj) && obj.$__ != null && obj._doc != null) { + return obj._doc; + } + + if (options && options.json && typeof obj.toJSON === 'function') { + return obj.toJSON(options); + } + return obj.toObject(options); + } + + if (obj.constructor) { + switch (getFunctionName(obj.constructor)) { + case 'Object': + return cloneObject(obj, options, isArrayChild); + case 'Date': + return new obj.constructor(+obj); + case 'RegExp': + return cloneRegExp(obj); + default: + // ignore + break; + } + } + + if (obj instanceof ObjectId) { + return new ObjectId(obj.id); + } + + if (isBsonType(obj, 'Decimal128')) { + if (options && options.flattenDecimals) { + return obj.toJSON(); + } + return Decimal.fromString(obj.toString()); + } + + if (!obj.constructor && isObject(obj)) { + // object created with Object.create(null) + return cloneObject(obj, options, isArrayChild); + } + + if (obj[symbols.schemaTypeSymbol]) { + return obj.clone(); + } + + // If we're cloning this object to go into a MongoDB command, + // and there's a `toBSON()` function, assume this object will be + // stored as a primitive in MongoDB and doesn't need to be cloned. + if (options && options.bson && typeof obj.toBSON === 'function') { + return obj; + } + + if (obj.valueOf != null) { + return obj.valueOf(); + } + + return cloneObject(obj, options, isArrayChild); +} +module.exports = clone; + +/*! + * ignore + */ + +function cloneObject(obj, options, isArrayChild) { + const minimize = options && options.minimize; + const ret = {}; + let hasKeys; + + if (obj[trustedSymbol]) { + ret[trustedSymbol] = obj[trustedSymbol]; + } + + for (const k of Object.keys(obj)) { + if (specialProperties.has(k)) { + continue; + } + + // Don't pass `isArrayChild` down + const val = clone(obj[k], options); + + if (!minimize || (typeof val !== 'undefined')) { + if (minimize === false && typeof val === 'undefined') { + delete ret[k]; + } else { + hasKeys || (hasKeys = true); + ret[k] = val; + } + } + } + + return minimize && !isArrayChild ? hasKeys && ret : ret; +} + +function cloneArray(arr, options) { + const ret = []; + + for (const item of arr) { + ret.push(clone(item, options, true)); + } + + return ret; +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/common.js b/node_modules/mongoose/lib/helpers/common.js new file mode 100644 index 0000000..a191b8a --- /dev/null +++ b/node_modules/mongoose/lib/helpers/common.js @@ -0,0 +1,115 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const Binary = require('../driver').get().Binary; +const Decimal128 = require('../types/decimal128'); +const ObjectId = require('../types/objectid'); +const isMongooseObject = require('./isMongooseObject'); + +exports.flatten = flatten; +exports.modifiedPaths = modifiedPaths; + +/*! + * ignore + */ + +function flatten(update, path, options, schema) { + let keys; + if (update && isMongooseObject(update) && !Buffer.isBuffer(update)) { + keys = Object.keys(update.toObject({ transform: false, virtuals: false })); + } else { + keys = Object.keys(update || {}); + } + + const numKeys = keys.length; + const result = {}; + path = path ? path + '.' : ''; + + for (let i = 0; i < numKeys; ++i) { + const key = keys[i]; + const val = update[key]; + result[path + key] = val; + + // Avoid going into mixed paths if schema is specified + const keySchema = schema && schema.path && schema.path(path + key); + const isNested = schema && schema.nested && schema.nested[path + key]; + if (keySchema && keySchema.instance === 'Mixed') continue; + + if (shouldFlatten(val)) { + if (options && options.skipArrays && Array.isArray(val)) { + continue; + } + const flat = flatten(val, path + key, options, schema); + for (const k in flat) { + result[k] = flat[k]; + } + if (Array.isArray(val)) { + result[path + key] = val; + } + } + + if (isNested) { + const paths = Object.keys(schema.paths); + for (const p of paths) { + if (p.startsWith(path + key + '.') && !result.hasOwnProperty(p)) { + result[p] = void 0; + } + } + } + } + + return result; +} + +/*! + * ignore + */ + +function modifiedPaths(update, path, result) { + const keys = Object.keys(update || {}); + const numKeys = keys.length; + result = result || {}; + path = path ? path + '.' : ''; + + for (let i = 0; i < numKeys; ++i) { + const key = keys[i]; + let val = update[key]; + + const _path = path + key; + result[_path] = true; + if (_path.indexOf('.') !== -1) { + const sp = _path.split('.'); + let cur = sp[0]; + for (let i = 1; i < sp.length; ++i) { + result[cur] = true; + cur += '.' + sp[i]; + } + } + if (isMongooseObject(val) && !Buffer.isBuffer(val)) { + val = val.toObject({ transform: false, virtuals: false }); + } + if (shouldFlatten(val)) { + modifiedPaths(val, path + key, result); + } + } + + return result; +} + +/*! + * ignore + */ + +function shouldFlatten(val) { + return val && + typeof val === 'object' && + !(val instanceof Date) && + !(val instanceof ObjectId) && + (!Array.isArray(val) || val.length > 0) && + !(val instanceof Buffer) && + !(val instanceof Decimal128) && + !(val instanceof Binary); +} diff --git a/node_modules/mongoose/lib/helpers/cursor/eachAsync.js b/node_modules/mongoose/lib/helpers/cursor/eachAsync.js new file mode 100644 index 0000000..2ef0346 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/cursor/eachAsync.js @@ -0,0 +1,157 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const immediate = require('../immediate'); +const promiseOrCallback = require('../promiseOrCallback'); + +/** + * Execute `fn` for every document in the cursor. If `fn` returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * + * @param {Function} next the thunk to call to get the next document + * @param {Function} fn + * @param {Object} options + * @param {Function} [callback] executed when all docs have been processed + * @return {Promise} + * @api public + * @method eachAsync + */ + +module.exports = function eachAsync(next, fn, options, callback) { + const parallel = options.parallel || 1; + const batchSize = options.batchSize; + const enqueue = asyncQueue(); + + return promiseOrCallback(callback, cb => { + if (batchSize != null) { + if (typeof batchSize !== 'number') { + throw new TypeError('batchSize must be a number'); + } + if (batchSize < 1) { + throw new TypeError('batchSize must be at least 1'); + } + if (batchSize !== Math.floor(batchSize)) { + throw new TypeError('batchSize must be a positive integer'); + } + } + + iterate(cb); + }); + + function iterate(finalCallback) { + let drained = false; + let handleResultsInProgress = 0; + let currentDocumentIndex = 0; + let documentsBatch = []; + + let error = null; + for (let i = 0; i < parallel; ++i) { + enqueue(fetch); + } + + function fetch(done) { + if (drained || error) { + return done(); + } + + next(function(err, doc) { + if (drained || error != null) { + return done(); + } + if (err != null) { + error = err; + finalCallback(err); + return done(); + } + if (doc == null) { + drained = true; + if (handleResultsInProgress <= 0) { + finalCallback(null); + } else if (batchSize != null && documentsBatch.length) { + handleNextResult(documentsBatch, currentDocumentIndex++, handleNextResultCallBack); + } + return done(); + } + + ++handleResultsInProgress; + + // Kick off the subsequent `next()` before handling the result, but + // make sure we know that we still have a result to handle re: #8422 + immediate(() => done()); + + if (batchSize != null) { + documentsBatch.push(doc); + } + + // If the current documents size is less than the provided patch size don't process the documents yet + if (batchSize != null && documentsBatch.length !== batchSize) { + setTimeout(() => enqueue(fetch), 0); + return; + } + + const docsToProcess = batchSize != null ? documentsBatch : doc; + + function handleNextResultCallBack(err) { + if (batchSize != null) { + handleResultsInProgress -= documentsBatch.length; + documentsBatch = []; + } else { + --handleResultsInProgress; + } + if (err != null) { + error = err; + return finalCallback(err); + } + if (drained && handleResultsInProgress <= 0) { + return finalCallback(null); + } + + setTimeout(() => enqueue(fetch), 0); + } + + handleNextResult(docsToProcess, currentDocumentIndex++, handleNextResultCallBack); + }); + } + } + + function handleNextResult(doc, i, callback) { + const promise = fn(doc, i); + if (promise && typeof promise.then === 'function') { + promise.then( + function() { callback(null); }, + function(error) { callback(error || new Error('`eachAsync()` promise rejected without error')); }); + } else { + callback(null); + } + } +}; + +// `next()` can only execute one at a time, so make sure we always execute +// `next()` in series, while still allowing multiple `fn()` instances to run +// in parallel. +function asyncQueue() { + const _queue = []; + let inProgress = null; + let id = 0; + + return function enqueue(fn) { + if (_queue.length === 0 && inProgress == null) { + inProgress = id++; + return fn(_step); + } + _queue.push(fn); + }; + + function _step() { + inProgress = null; + if (_queue.length > 0) { + inProgress = id++; + const fn = _queue.shift(); + fn(_step); + } + } +} diff --git a/node_modules/mongoose/lib/helpers/discriminator/areDiscriminatorValuesEqual.js b/node_modules/mongoose/lib/helpers/discriminator/areDiscriminatorValuesEqual.js new file mode 100644 index 0000000..87b2408 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/discriminator/areDiscriminatorValuesEqual.js @@ -0,0 +1,16 @@ +'use strict'; + +const ObjectId = require('../../types/objectid'); + +module.exports = function areDiscriminatorValuesEqual(a, b) { + if (typeof a === 'string' && typeof b === 'string') { + return a === b; + } + if (typeof a === 'number' && typeof b === 'number') { + return a === b; + } + if (a instanceof ObjectId && b instanceof ObjectId) { + return a.toString() === b.toString(); + } + return false; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js b/node_modules/mongoose/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js new file mode 100644 index 0000000..755de88 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function checkEmbeddedDiscriminatorKeyProjection(userProjection, path, schema, selected, addedPaths) { + const userProjectedInPath = Object.keys(userProjection). + reduce((cur, key) => cur || key.startsWith(path + '.'), false); + const _discriminatorKey = path + '.' + schema.options.discriminatorKey; + if (!userProjectedInPath && + addedPaths.length === 1 && + addedPaths[0] === _discriminatorKey) { + selected.splice(selected.indexOf(_discriminatorKey), 1); + } +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/discriminator/getConstructor.js b/node_modules/mongoose/lib/helpers/discriminator/getConstructor.js new file mode 100644 index 0000000..728da3b --- /dev/null +++ b/node_modules/mongoose/lib/helpers/discriminator/getConstructor.js @@ -0,0 +1,25 @@ +'use strict'; + +const getDiscriminatorByValue = require('./getDiscriminatorByValue'); + +/*! + * Find the correct constructor, taking into account discriminators + */ + +module.exports = function getConstructor(Constructor, value) { + const discriminatorKey = Constructor.schema.options.discriminatorKey; + if (value != null && + Constructor.discriminators && + value[discriminatorKey] != null) { + if (Constructor.discriminators[value[discriminatorKey]]) { + Constructor = Constructor.discriminators[value[discriminatorKey]]; + } else { + const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[discriminatorKey]); + if (constructorByValue) { + Constructor = constructorByValue; + } + } + } + + return Constructor; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/discriminator/getDiscriminatorByValue.js b/node_modules/mongoose/lib/helpers/discriminator/getDiscriminatorByValue.js new file mode 100644 index 0000000..099aaef --- /dev/null +++ b/node_modules/mongoose/lib/helpers/discriminator/getDiscriminatorByValue.js @@ -0,0 +1,27 @@ +'use strict'; + +const areDiscriminatorValuesEqual = require('./areDiscriminatorValuesEqual'); + +/*! +* returns discriminator by discriminatorMapping.value +* +* @param {Model} model +* @param {string} value +*/ + +module.exports = function getDiscriminatorByValue(discriminators, value) { + if (discriminators == null) { + return null; + } + for (const name of Object.keys(discriminators)) { + const it = discriminators[name]; + if ( + it.schema && + it.schema.discriminatorMapping && + areDiscriminatorValuesEqual(it.schema.discriminatorMapping.value, value) + ) { + return it; + } + } + return null; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js b/node_modules/mongoose/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js new file mode 100644 index 0000000..b29fb65 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js @@ -0,0 +1,26 @@ +'use strict'; + +const areDiscriminatorValuesEqual = require('./areDiscriminatorValuesEqual'); + +/*! +* returns discriminator by discriminatorMapping.value +* +* @param {Schema} schema +* @param {string} value +*/ + +module.exports = function getSchemaDiscriminatorByValue(schema, value) { + if (schema == null || schema.discriminators == null) { + return null; + } + for (const key of Object.keys(schema.discriminators)) { + const discriminatorSchema = schema.discriminators[key]; + if (discriminatorSchema.discriminatorMapping == null) { + continue; + } + if (areDiscriminatorValuesEqual(discriminatorSchema.discriminatorMapping.value, value)) { + return discriminatorSchema; + } + } + return null; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js b/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js new file mode 100644 index 0000000..98de475 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js @@ -0,0 +1,28 @@ +'use strict'; + +/*! + * ignore + */ + +module.exports = function cleanModifiedSubpaths(doc, path, options) { + options = options || {}; + const skipDocArrays = options.skipDocArrays; + + let deleted = 0; + if (!doc) { + return deleted; + } + for (const modifiedPath of Object.keys(doc.$__.activePaths.states.modify)) { + if (skipDocArrays) { + const schemaType = doc.$__schema.path(modifiedPath); + if (schemaType && schemaType.$isMongooseDocumentArray) { + continue; + } + } + if (modifiedPath.startsWith(path + '.')) { + delete doc.$__.activePaths.states.modify[modifiedPath]; + ++deleted; + } + } + return deleted; +}; diff --git a/node_modules/mongoose/lib/helpers/document/compile.js b/node_modules/mongoose/lib/helpers/document/compile.js new file mode 100644 index 0000000..9981e8f --- /dev/null +++ b/node_modules/mongoose/lib/helpers/document/compile.js @@ -0,0 +1,207 @@ +'use strict'; + +const documentSchemaSymbol = require('../../helpers/symbols').documentSchemaSymbol; +const get = require('../../helpers/get'); +const internalToObjectOptions = require('../../options').internalToObjectOptions; +const utils = require('../../utils'); + +let Document; +const getSymbol = require('../../helpers/symbols').getSymbol; +const scopeSymbol = require('../../helpers/symbols').scopeSymbol; + +/*! + * exports + */ + +exports.compile = compile; +exports.defineKey = defineKey; + +/*! + * Compiles schemas. + */ + +function compile(tree, proto, prefix, options) { + Document = Document || require('../../document'); + + for (const key of Object.keys(tree)) { + const limb = tree[key]; + + const hasSubprops = utils.isPOJO(limb) && Object.keys(limb).length && + (!limb[options.typeKey] || (options.typeKey === 'type' && limb.type.type)); + const subprops = hasSubprops ? limb : null; + + defineKey({ prop: key, subprops: subprops, prototype: proto, prefix: prefix, options: options }); + } +} + +/*! + * Defines the accessor named prop on the incoming prototype. + */ + +function defineKey({ prop, subprops, prototype, prefix, options }) { + Document = Document || require('../../document'); + const path = (prefix ? prefix + '.' : '') + prop; + prefix = prefix || ''; + + if (subprops) { + Object.defineProperty(prototype, prop, { + enumerable: true, + configurable: true, + get: function() { + const _this = this; + if (!this.$__.getters) { + this.$__.getters = {}; + } + + if (!this.$__.getters[path]) { + const nested = Object.create(Document.prototype, getOwnPropertyDescriptors(this)); + + // save scope for nested getters/setters + if (!prefix) { + nested.$__[scopeSymbol] = this; + } + nested.$__.nestedPath = path; + + Object.defineProperty(nested, 'schema', { + enumerable: false, + configurable: true, + writable: false, + value: prototype.schema + }); + + Object.defineProperty(nested, '$__schema', { + enumerable: false, + configurable: true, + writable: false, + value: prototype.schema + }); + + Object.defineProperty(nested, documentSchemaSymbol, { + enumerable: false, + configurable: true, + writable: false, + value: prototype.schema + }); + + Object.defineProperty(nested, 'toObject', { + enumerable: false, + configurable: true, + writable: false, + value: function() { + return utils.clone(_this.get(path, null, { + virtuals: get(this, 'schema.options.toObject.virtuals', null) + })); + } + }); + + Object.defineProperty(nested, '$__get', { + enumerable: false, + configurable: true, + writable: false, + value: function() { + return _this.get(path, null, { + virtuals: get(this, 'schema.options.toObject.virtuals', null) + }); + } + }); + + Object.defineProperty(nested, 'toJSON', { + enumerable: false, + configurable: true, + writable: false, + value: function() { + return _this.get(path, null, { + virtuals: get(_this, 'schema.options.toJSON.virtuals', null) + }); + } + }); + + Object.defineProperty(nested, '$__isNested', { + enumerable: false, + configurable: true, + writable: false, + value: true + }); + + const _isEmptyOptions = Object.freeze({ + minimize: true, + virtuals: false, + getters: false, + transform: false + }); + Object.defineProperty(nested, '$isEmpty', { + enumerable: false, + configurable: true, + writable: false, + value: function() { + return Object.keys(this.get(path, null, _isEmptyOptions) || {}).length === 0; + } + }); + + Object.defineProperty(nested, '$__parent', { + enumerable: false, + configurable: true, + writable: false, + value: this + }); + + compile(subprops, nested, path, options); + this.$__.getters[path] = nested; + } + + return this.$__.getters[path]; + }, + set: function(v) { + if (v != null && v.$__isNested) { + // Convert top-level to POJO, but leave subdocs hydrated so `$set` + // can handle them. See gh-9293. + v = v.$__get(); + } else if (v instanceof Document && !v.$__isNested) { + v = v.$toObject(internalToObjectOptions); + } + const doc = this.$__[scopeSymbol] || this; + doc.$set(path, v); + } + }); + } else { + Object.defineProperty(prototype, prop, { + enumerable: true, + configurable: true, + get: function() { + return this[getSymbol].call(this.$__[scopeSymbol] || this, path); + }, + set: function(v) { + this.$set.call(this.$__[scopeSymbol] || this, path, v); + } + }); + } +} + +// gets descriptors for all properties of `object` +// makes all properties non-enumerable to match previous behavior to #2211 +function getOwnPropertyDescriptors(object) { + const result = {}; + + Object.getOwnPropertyNames(object).forEach(function(key) { + const skip = [ + 'isNew', + '$__', + '$errors', + 'errors', + '_doc', + '$locals', + '$op', + '__parentArray', + '__index', + '$isDocumentArrayElement' + ].indexOf(key) === -1; + if (skip) { + return; + } + + result[key] = Object.getOwnPropertyDescriptor(object, key); + result[key].enumerable = false; + }); + + return result; +} diff --git a/node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js b/node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js new file mode 100644 index 0000000..3f4d22a --- /dev/null +++ b/node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js @@ -0,0 +1,46 @@ +'use strict'; + +const get = require('../get'); +const getSchemaDiscriminatorByValue = require('../discriminator/getSchemaDiscriminatorByValue'); + +/*! + * Like `schema.path()`, except with a document, because impossible to + * determine path type without knowing the embedded discriminator key. + */ + +module.exports = function getEmbeddedDiscriminatorPath(doc, path, options) { + options = options || {}; + const typeOnly = options.typeOnly; + const parts = path.indexOf('.') === -1 ? [path] : path.split('.'); + let schemaType = null; + let type = 'adhocOrUndefined'; + + const schema = getSchemaDiscriminatorByValue(doc.schema, doc.get(doc.schema.options.discriminatorKey)) || doc.schema; + + for (let i = 0; i < parts.length; ++i) { + const subpath = parts.slice(0, i + 1).join('.'); + schemaType = schema.path(subpath); + if (schemaType == null) { + type = 'adhocOrUndefined'; + continue; + } + if (schemaType.instance === 'Mixed') { + return typeOnly ? 'real' : schemaType; + } + type = schema.pathType(subpath); + if ((schemaType.$isSingleNested || schemaType.$isMongooseDocumentArrayElement) && + schemaType.schema.discriminators != null) { + const discriminators = schemaType.schema.discriminators; + const discriminatorKey = doc.get(subpath + '.' + + get(schemaType, 'schema.options.discriminatorKey')); + if (discriminatorKey == null || discriminators[discriminatorKey] == null) { + continue; + } + const rest = parts.slice(i + 1).join('.'); + return getEmbeddedDiscriminatorPath(doc.get(subpath), rest, options); + } + } + + // Are we getting the whole schema or just the type, 'real', 'nested', etc. + return typeOnly ? type : schemaType; +}; diff --git a/node_modules/mongoose/lib/helpers/document/handleSpreadDoc.js b/node_modules/mongoose/lib/helpers/document/handleSpreadDoc.js new file mode 100644 index 0000000..d3075e4 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/document/handleSpreadDoc.js @@ -0,0 +1,17 @@ +'use strict'; + +const utils = require('../../utils'); + +/** + * Using spread operator on a Mongoose document gives you a + * POJO that has a tendency to cause infinite recursion. So + * we use this function on `set()` to prevent that. + */ + +module.exports = function handleSpreadDoc(v) { + if (utils.isPOJO(v) && v.$__ != null && v._doc != null) { + return v._doc; + } + + return v; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/each.js b/node_modules/mongoose/lib/helpers/each.js new file mode 100644 index 0000000..fe70069 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/each.js @@ -0,0 +1,25 @@ +'use strict'; + +module.exports = function each(arr, cb, done) { + if (arr.length === 0) { + return done(); + } + + let remaining = arr.length; + let err = null; + for (const v of arr) { + cb(v, function(_err) { + if (err != null) { + return; + } + if (_err != null) { + err = _err; + return done(err); + } + + if (--remaining <= 0) { + return done(); + } + }); + } +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/get.js b/node_modules/mongoose/lib/helpers/get.js new file mode 100644 index 0000000..dbab306 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/get.js @@ -0,0 +1,64 @@ +'use strict'; + +/*! + * Simplified lodash.get to work around the annoying null quirk. See: + * https://github.com/lodash/lodash/issues/3659 + */ + +module.exports = function get(obj, path, def) { + let parts; + let isPathArray = false; + if (typeof path === 'string') { + if (path.indexOf('.') === -1) { + const _v = getProperty(obj, path); + if (_v == null) { + return def; + } + return _v; + } + + parts = path.split('.'); + } else { + isPathArray = true; + parts = path; + + if (parts.length === 1) { + const _v = getProperty(obj, parts[0]); + if (_v == null) { + return def; + } + return _v; + } + } + let rest = path; + let cur = obj; + for (const part of parts) { + if (cur == null) { + return def; + } + + // `lib/cast.js` depends on being able to get dotted paths in updates, + // like `{ $set: { 'a.b': 42 } }` + if (!isPathArray && cur[rest] != null) { + return cur[rest]; + } + + cur = getProperty(cur, part); + + if (!isPathArray) { + rest = rest.substr(part.length + 1); + } + } + + return cur == null ? def : cur; +}; + +function getProperty(obj, prop) { + if (obj == null) { + return obj; + } + if (obj instanceof Map) { + return obj.get(prop); + } + return obj[prop]; +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/getConstructorName.js b/node_modules/mongoose/lib/helpers/getConstructorName.js new file mode 100644 index 0000000..a4e1924 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/getConstructorName.js @@ -0,0 +1,15 @@ +'use strict'; + +/*! + * If `val` is an object, returns constructor name, if possible. Otherwise returns undefined. + */ + +module.exports = function getConstructorName(val) { + if (val == null) { + return void 0; + } + if (typeof val.constructor !== 'function') { + return void 0; + } + return val.constructor.name; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/getDefaultBulkwriteResult.js b/node_modules/mongoose/lib/helpers/getDefaultBulkwriteResult.js new file mode 100644 index 0000000..7d10f17 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/getDefaultBulkwriteResult.js @@ -0,0 +1,27 @@ +'use strict'; +function getDefaultBulkwriteResult() { + return { + result: { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }, + insertedCount: 0, + matchedCount: 0, + modifiedCount: 0, + deletedCount: 0, + upsertedCount: 0, + upsertedIds: {}, + insertedIds: {}, + n: 0 + }; +} + +module.exports = getDefaultBulkwriteResult; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/getFunctionName.js b/node_modules/mongoose/lib/helpers/getFunctionName.js new file mode 100644 index 0000000..87a2c69 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/getFunctionName.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function(fn) { + if (fn.name) { + return fn.name; + } + return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1]; +}; diff --git a/node_modules/mongoose/lib/helpers/immediate.js b/node_modules/mongoose/lib/helpers/immediate.js new file mode 100644 index 0000000..0a1c26c --- /dev/null +++ b/node_modules/mongoose/lib/helpers/immediate.js @@ -0,0 +1,14 @@ +/*! + * Centralize this so we can more easily work around issues with people + * stubbing out `process.nextTick()` in tests using sinon: + * https://github.com/sinonjs/lolex#automatically-incrementing-mocked-time + * See gh-6074 + */ + +'use strict'; + +const nextTick = process.nextTick.bind(process); + +module.exports = function immediate(cb) { + return nextTick(cb); +}; diff --git a/node_modules/mongoose/lib/helpers/indexes/isDefaultIdIndex.js b/node_modules/mongoose/lib/helpers/indexes/isDefaultIdIndex.js new file mode 100644 index 0000000..c975dcf --- /dev/null +++ b/node_modules/mongoose/lib/helpers/indexes/isDefaultIdIndex.js @@ -0,0 +1,18 @@ +'use strict'; + +const get = require('../get'); + +module.exports = function isDefaultIdIndex(index) { + if (Array.isArray(index)) { + // Mongoose syntax + const keys = Object.keys(index[0]); + return keys.length === 1 && keys[0] === '_id' && index[0]._id !== 'hashed'; + } + + if (typeof index !== 'object') { + return false; + } + + const key = get(index, 'key', {}); + return Object.keys(key).length === 1 && key.hasOwnProperty('_id'); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/indexes/isIndexEqual.js b/node_modules/mongoose/lib/helpers/indexes/isIndexEqual.js new file mode 100644 index 0000000..12e5c3d --- /dev/null +++ b/node_modules/mongoose/lib/helpers/indexes/isIndexEqual.js @@ -0,0 +1,96 @@ +'use strict'; + +const get = require('../get'); +const utils = require('../../utils'); +/** + * Given a Mongoose index definition (key + options objects) and a MongoDB server + * index definition, determine if the two indexes are equal. + * + * @param {Object} key the Mongoose index spec + * @param {Object} options the Mongoose index definition's options + * @param {Object} dbIndex the index in MongoDB as returned by `listIndexes()` + * @api private + */ + +module.exports = function isIndexEqual(key, options, dbIndex) { + // Special case: text indexes have a special format in the db. For example, + // `{ name: 'text' }` becomes: + // { + // v: 2, + // key: { _fts: 'text', _ftsx: 1 }, + // name: 'name_text', + // ns: 'test.tests', + // background: true, + // weights: { name: 1 }, + // default_language: 'english', + // language_override: 'language', + // textIndexVersion: 3 + // } + if (dbIndex.textIndexVersion != null) { + delete dbIndex.key._fts; + delete dbIndex.key._ftsx; + const weights = { ...dbIndex.weights, ...dbIndex.key }; + if (Object.keys(weights).length !== Object.keys(key).length) { + return false; + } + for (const prop of Object.keys(weights)) { + if (!(prop in key)) { + return false; + } + const weight = weights[prop]; + if (weight !== get(options, 'weights.' + prop) && !(weight === 1 && get(options, 'weights.' + prop) == null)) { + return false; + } + } + + if (options['default_language'] !== dbIndex['default_language']) { + return dbIndex['default_language'] === 'english' && options['default_language'] == null; + } + + return true; + } + + const optionKeys = [ + 'unique', + 'partialFilterExpression', + 'sparse', + 'expireAfterSeconds', + 'collation' + ]; + for (const key of optionKeys) { + if (!(key in options) && !(key in dbIndex)) { + continue; + } + if (key === 'collation') { + if (options[key] == null || dbIndex[key] == null) { + return options[key] == null && dbIndex[key] == null; + } + const definedKeys = Object.keys(options.collation); + const schemaCollation = options.collation; + const dbCollation = dbIndex.collation; + for (const opt of definedKeys) { + if (get(schemaCollation, opt) !== get(dbCollation, opt)) { + return false; + } + } + } else if (!utils.deepEqual(options[key], dbIndex[key])) { + return false; + } + } + + const schemaIndexKeys = Object.keys(key); + const dbIndexKeys = Object.keys(dbIndex.key); + if (schemaIndexKeys.length !== dbIndexKeys.length) { + return false; + } + for (let i = 0; i < schemaIndexKeys.length; ++i) { + if (schemaIndexKeys[i] !== dbIndexKeys[i]) { + return false; + } + if (!utils.deepEqual(key[schemaIndexKeys[i]], dbIndex.key[dbIndexKeys[i]])) { + return false; + } + } + + return true; +}; diff --git a/node_modules/mongoose/lib/helpers/isAsyncFunction.js b/node_modules/mongoose/lib/helpers/isAsyncFunction.js new file mode 100644 index 0000000..ecd2872 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/isAsyncFunction.js @@ -0,0 +1,11 @@ +'use strict'; + +const { inspect } = require('util'); + +module.exports = function isAsyncFunction(v) { + if (typeof v !== 'function') { + return; + } + + return inspect(v).startsWith('[AsyncFunction:'); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/isBsonType.js b/node_modules/mongoose/lib/helpers/isBsonType.js new file mode 100644 index 0000000..01435d3 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/isBsonType.js @@ -0,0 +1,13 @@ +'use strict'; + +const get = require('./get'); + +/*! + * Get the bson type, if it exists + */ + +function isBsonType(obj, typename) { + return get(obj, '_bsontype', void 0) === typename; +} + +module.exports = isBsonType; diff --git a/node_modules/mongoose/lib/helpers/isMongooseObject.js b/node_modules/mongoose/lib/helpers/isMongooseObject.js new file mode 100644 index 0000000..016f9e6 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/isMongooseObject.js @@ -0,0 +1,21 @@ +'use strict'; + +/*! + * Returns if `v` is a mongoose object that has a `toObject()` method we can use. + * + * This is for compatibility with libs like Date.js which do foolish things to Natives. + * + * @param {any} v + * @api private + */ + +module.exports = function(v) { + if (v == null) { + return false; + } + + return v.$__ != null || // Document + v.isMongooseArray || // Array or Document Array + v.isMongooseBuffer || // Buffer + v.$isMongooseMap; // Map +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/isObject.js b/node_modules/mongoose/lib/helpers/isObject.js new file mode 100644 index 0000000..f8ac313 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/isObject.js @@ -0,0 +1,16 @@ +'use strict'; + +/*! + * Determines if `arg` is an object. + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @api private + * @return {Boolean} + */ + +module.exports = function(arg) { + if (Buffer.isBuffer(arg)) { + return true; + } + return Object.prototype.toString.call(arg) === '[object Object]'; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/isPromise.js b/node_modules/mongoose/lib/helpers/isPromise.js new file mode 100644 index 0000000..d6db260 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/isPromise.js @@ -0,0 +1,6 @@ +'use strict'; +function isPromise(val) { + return !!val && (typeof val === 'object' || typeof val === 'function') && typeof val.then === 'function'; +} + +module.exports = isPromise; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/model/applyHooks.js b/node_modules/mongoose/lib/helpers/model/applyHooks.js new file mode 100644 index 0000000..0498c75 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/model/applyHooks.js @@ -0,0 +1,138 @@ +'use strict'; + +const symbols = require('../../schema/symbols'); +const promiseOrCallback = require('../promiseOrCallback'); + +/*! + * ignore + */ + +module.exports = applyHooks; + +/*! + * ignore + */ + +applyHooks.middlewareFunctions = [ + 'deleteOne', + 'save', + 'validate', + 'remove', + 'updateOne', + 'init' +]; + +/*! + * Register hooks for this model + * + * @param {Model} model + * @param {Schema} schema + */ + +function applyHooks(model, schema, options) { + options = options || {}; + + const kareemOptions = { + useErrorHandlers: true, + numCallbackParams: 1, + nullResultByDefault: true, + contextParameter: true + }; + const objToDecorate = options.decorateDoc ? model : model.prototype; + + model.$appliedHooks = true; + for (const key of Object.keys(schema.paths)) { + const type = schema.paths[key]; + let childModel = null; + if (type.$isSingleNested) { + childModel = type.caster; + } else if (type.$isMongooseDocumentArray) { + childModel = type.Constructor; + } else { + continue; + } + + if (childModel.$appliedHooks) { + continue; + } + + applyHooks(childModel, type.schema, options); + if (childModel.discriminators != null) { + const keys = Object.keys(childModel.discriminators); + for (const key of keys) { + applyHooks(childModel.discriminators[key], + childModel.discriminators[key].schema, options); + } + } + } + + // Built-in hooks rely on hooking internal functions in order to support + // promises and make it so that `doc.save.toString()` provides meaningful + // information. + + const middleware = schema.s.hooks. + filter(hook => { + if (hook.name === 'updateOne' || hook.name === 'deleteOne') { + return !!hook['document']; + } + if (hook.name === 'remove' || hook.name === 'init') { + return hook['document'] == null || !!hook['document']; + } + if (hook.query != null || hook.document != null) { + return hook.document !== false; + } + return true; + }). + filter(hook => { + // If user has overwritten the method, don't apply built-in middleware + if (schema.methods[hook.name]) { + return !hook.fn[symbols.builtInMiddleware]; + } + + return true; + }); + + model._middleware = middleware; + + objToDecorate.$__originalValidate = objToDecorate.$__originalValidate || objToDecorate.$__validate; + + for (const method of ['save', 'validate', 'remove', 'deleteOne']) { + const toWrap = method === 'validate' ? '$__originalValidate' : `$__${method}`; + const wrapped = middleware. + createWrapper(method, objToDecorate[toWrap], null, kareemOptions); + objToDecorate[`$__${method}`] = wrapped; + } + objToDecorate.$__init = middleware. + createWrapperSync('init', objToDecorate.$__init, null, kareemOptions); + + // Support hooks for custom methods + const customMethods = Object.keys(schema.methods); + const customMethodOptions = Object.assign({}, kareemOptions, { + // Only use `checkForPromise` for custom methods, because mongoose + // query thunks are not as consistent as I would like about returning + // a nullish value rather than the query. If a query thunk returns + // a query, `checkForPromise` causes infinite recursion + checkForPromise: true + }); + for (const method of customMethods) { + if (!middleware.hasHooks(method)) { + // Don't wrap if there are no hooks for the custom method to avoid + // surprises. Also, `createWrapper()` enforces consistent async, + // so wrapping a sync method would break it. + continue; + } + const originalMethod = objToDecorate[method]; + objToDecorate[method] = function() { + const args = Array.prototype.slice.call(arguments); + const cb = args.slice(-1).pop(); + const argsWithoutCallback = typeof cb === 'function' ? + args.slice(0, args.length - 1) : args; + return promiseOrCallback(cb, callback => { + return this[`$__${method}`].apply(this, + argsWithoutCallback.concat([callback])); + }, model.events); + }; + objToDecorate[`$__${method}`] = middleware. + createWrapper(method, originalMethod, null, customMethodOptions); + } +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/model/applyMethods.js b/node_modules/mongoose/lib/helpers/model/applyMethods.js new file mode 100644 index 0000000..bd3718d --- /dev/null +++ b/node_modules/mongoose/lib/helpers/model/applyMethods.js @@ -0,0 +1,57 @@ +'use strict'; + +const get = require('../get'); +const utils = require('../../utils'); + +/*! + * Register methods for this model + * + * @param {Model} model + * @param {Schema} schema + */ + +module.exports = function applyMethods(model, schema) { + function apply(method, schema) { + Object.defineProperty(model.prototype, method, { + get: function() { + const h = {}; + for (const k in schema.methods[method]) { + h[k] = schema.methods[method][k].bind(this); + } + return h; + }, + configurable: true + }); + } + for (const method of Object.keys(schema.methods)) { + const fn = schema.methods[method]; + if (schema.tree.hasOwnProperty(method)) { + throw new Error('You have a method and a property in your schema both ' + + 'named "' + method + '"'); + } + if (schema.reserved[method] && + !get(schema, `methodOptions.${method}.suppressWarning`, false)) { + utils.warn(`mongoose: the method name "${method}" is used by mongoose ` + + 'internally, overwriting it may cause bugs. If you\'re sure you know ' + + 'what you\'re doing, you can suppress this error by using ' + + `\`schema.method('${method}', fn, { suppressWarning: true })\`.`); + } + if (typeof fn === 'function') { + model.prototype[method] = fn; + } else { + apply(method, schema); + } + } + + // Recursively call `applyMethods()` on child schemas + model.$appliedMethods = true; + for (const key of Object.keys(schema.paths)) { + const type = schema.paths[key]; + if (type.$isSingleNested && !type.caster.$appliedMethods) { + applyMethods(type.caster, type.schema); + } + if (type.$isMongooseDocumentArray && !type.Constructor.$appliedMethods) { + applyMethods(type.Constructor, type.schema); + } + } +}; diff --git a/node_modules/mongoose/lib/helpers/model/applyStaticHooks.js b/node_modules/mongoose/lib/helpers/model/applyStaticHooks.js new file mode 100644 index 0000000..219e289 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/model/applyStaticHooks.js @@ -0,0 +1,71 @@ +'use strict'; + +const middlewareFunctions = require('../query/applyQueryMiddleware').middlewareFunctions; +const promiseOrCallback = require('../promiseOrCallback'); + +module.exports = function applyStaticHooks(model, hooks, statics) { + const kareemOptions = { + useErrorHandlers: true, + numCallbackParams: 1 + }; + + hooks = hooks.filter(hook => { + // If the custom static overwrites an existing query middleware, don't apply + // middleware to it by default. This avoids a potential backwards breaking + // change with plugins like `mongoose-delete` that use statics to overwrite + // built-in Mongoose functions. + if (middlewareFunctions.indexOf(hook.name) !== -1) { + return !!hook.model; + } + return hook.model !== false; + }); + + model.$__insertMany = hooks.createWrapper('insertMany', + model.$__insertMany, model, kareemOptions); + + for (const key of Object.keys(statics)) { + if (hooks.hasHooks(key)) { + const original = model[key]; + + model[key] = function() { + const numArgs = arguments.length; + const lastArg = numArgs > 0 ? arguments[numArgs - 1] : null; + const cb = typeof lastArg === 'function' ? lastArg : null; + const args = Array.prototype.slice. + call(arguments, 0, cb == null ? numArgs : numArgs - 1); + // Special case: can't use `Kareem#wrap()` because it doesn't currently + // support wrapped functions that return a promise. + return promiseOrCallback(cb, callback => { + hooks.execPre(key, model, args, function(err) { + if (err != null) { + return callback(err); + } + + let postCalled = 0; + const ret = original.apply(model, args.concat(post)); + if (ret != null && typeof ret.then === 'function') { + ret.then(res => post(null, res), err => post(err)); + } + + function post(error, res) { + if (postCalled++ > 0) { + return; + } + + if (error != null) { + return callback(error); + } + + hooks.execPost(key, model, [res], function(error) { + if (error != null) { + return callback(error); + } + callback(null, res); + }); + } + }); + }, model.events); + }; + } + } +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/model/applyStatics.js b/node_modules/mongoose/lib/helpers/model/applyStatics.js new file mode 100644 index 0000000..3b9501e --- /dev/null +++ b/node_modules/mongoose/lib/helpers/model/applyStatics.js @@ -0,0 +1,12 @@ +'use strict'; + +/*! + * Register statics for this model + * @param {Model} model + * @param {Schema} schema + */ +module.exports = function applyStatics(model, schema) { + for (const i in schema.statics) { + model[i] = schema.statics[i]; + } +}; diff --git a/node_modules/mongoose/lib/helpers/model/castBulkWrite.js b/node_modules/mongoose/lib/helpers/model/castBulkWrite.js new file mode 100644 index 0000000..84bcb79 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/model/castBulkWrite.js @@ -0,0 +1,223 @@ +'use strict'; + +const getDiscriminatorByValue = require('../../helpers/discriminator/getDiscriminatorByValue'); +const applyTimestampsToChildren = require('../update/applyTimestampsToChildren'); +const applyTimestampsToUpdate = require('../update/applyTimestampsToUpdate'); +const cast = require('../../cast'); +const castUpdate = require('../query/castUpdate'); +const setDefaultsOnInsert = require('../setDefaultsOnInsert'); + +/*! + * Given a model and a bulkWrite op, return a thunk that handles casting and + * validating the individual op. + */ + +module.exports = function castBulkWrite(originalModel, op, options) { + const now = originalModel.base.now(); + + if (op['insertOne']) { + return (callback) => { + const model = decideModelByObject(originalModel, op['insertOne']['document']); + + const doc = new model(op['insertOne']['document']); + if (model.schema.options.timestamps) { + doc.initializeTimestamps(); + } + if (options.session != null) { + doc.$session(options.session); + } + op['insertOne']['document'] = doc; + op['insertOne']['document'].$validate({ __noPromise: true }, function(error) { + if (error) { + return callback(error, null); + } + callback(null); + }); + }; + } else if (op['updateOne']) { + return (callback) => { + try { + if (!op['updateOne']['filter']) { + throw new Error('Must provide a filter object.'); + } + if (!op['updateOne']['update']) { + throw new Error('Must provide an update object.'); + } + + const model = decideModelByObject(originalModel, op['updateOne']['filter']); + const schema = model.schema; + const strict = options.strict != null ? options.strict : model.schema.options.strict; + + _addDiscriminatorToObject(schema, op['updateOne']['filter']); + + if (model.schema.$timestamps != null && op['updateOne'].timestamps !== false) { + const createdAt = model.schema.$timestamps.createdAt; + const updatedAt = model.schema.$timestamps.updatedAt; + applyTimestampsToUpdate(now, createdAt, updatedAt, op['updateOne']['update'], {}); + } + + applyTimestampsToChildren(now, op['updateOne']['update'], model.schema); + + if (op['updateOne'].setDefaultsOnInsert !== false) { + setDefaultsOnInsert(op['updateOne']['filter'], model.schema, op['updateOne']['update'], { + setDefaultsOnInsert: true, + upsert: op['updateOne'].upsert + }); + } + + op['updateOne']['filter'] = cast(model.schema, op['updateOne']['filter'], { + strict: strict, + upsert: op['updateOne'].upsert + }); + + op['updateOne']['update'] = castUpdate(model.schema, op['updateOne']['update'], { + strict: strict, + overwrite: false, + upsert: op['updateOne'].upsert + }, model, op['updateOne']['filter']); + } catch (error) { + return callback(error, null); + } + + callback(null); + }; + } else if (op['updateMany']) { + return (callback) => { + try { + if (!op['updateMany']['filter']) { + throw new Error('Must provide a filter object.'); + } + if (!op['updateMany']['update']) { + throw new Error('Must provide an update object.'); + } + + const model = decideModelByObject(originalModel, op['updateMany']['filter']); + const schema = model.schema; + const strict = options.strict != null ? options.strict : model.schema.options.strict; + + if (op['updateMany'].setDefaultsOnInsert !== false) { + setDefaultsOnInsert(op['updateMany']['filter'], model.schema, op['updateMany']['update'], { + setDefaultsOnInsert: true, + upsert: op['updateMany'].upsert + }); + } + + if (model.schema.$timestamps != null && op['updateMany'].timestamps !== false) { + const createdAt = model.schema.$timestamps.createdAt; + const updatedAt = model.schema.$timestamps.updatedAt; + applyTimestampsToUpdate(now, createdAt, updatedAt, op['updateMany']['update'], {}); + } + + applyTimestampsToChildren(now, op['updateMany']['update'], model.schema); + + _addDiscriminatorToObject(schema, op['updateMany']['filter']); + + op['updateMany']['filter'] = cast(model.schema, op['updateMany']['filter'], { + strict: strict, + upsert: op['updateMany'].upsert + }); + + op['updateMany']['update'] = castUpdate(model.schema, op['updateMany']['update'], { + strict: strict, + overwrite: false, + upsert: op['updateMany'].upsert + }, model, op['updateMany']['filter']); + } catch (error) { + return callback(error, null); + } + + callback(null); + }; + } else if (op['replaceOne']) { + return (callback) => { + const model = decideModelByObject(originalModel, op['replaceOne']['filter']); + const schema = model.schema; + const strict = options.strict != null ? options.strict : model.schema.options.strict; + + _addDiscriminatorToObject(schema, op['replaceOne']['filter']); + try { + op['replaceOne']['filter'] = cast(model.schema, op['replaceOne']['filter'], { + strict: strict, + upsert: op['replaceOne'].upsert + }); + } catch (error) { + return callback(error, null); + } + + // set `skipId`, otherwise we get "_id field cannot be changed" + const doc = new model(op['replaceOne']['replacement'], strict, true); + if (model.schema.options.timestamps) { + doc.initializeTimestamps(); + } + if (options.session != null) { + doc.$session(options.session); + } + op['replaceOne']['replacement'] = doc; + + op['replaceOne']['replacement'].$validate({ __noPromise: true }, function(error) { + if (error) { + return callback(error, null); + } + op['replaceOne']['replacement'] = op['replaceOne']['replacement'].toBSON(); + callback(null); + }); + }; + } else if (op['deleteOne']) { + return (callback) => { + const model = decideModelByObject(originalModel, op['deleteOne']['filter']); + const schema = model.schema; + + _addDiscriminatorToObject(schema, op['deleteOne']['filter']); + + try { + op['deleteOne']['filter'] = cast(model.schema, + op['deleteOne']['filter']); + } catch (error) { + return callback(error, null); + } + + callback(null); + }; + } else if (op['deleteMany']) { + return (callback) => { + const model = decideModelByObject(originalModel, op['deleteMany']['filter']); + const schema = model.schema; + + _addDiscriminatorToObject(schema, op['deleteMany']['filter']); + + try { + op['deleteMany']['filter'] = cast(model.schema, + op['deleteMany']['filter']); + } catch (error) { + return callback(error, null); + } + + callback(null); + }; + } else { + return (callback) => { + callback(new Error('Invalid op passed to `bulkWrite()`'), null); + }; + } +}; + +function _addDiscriminatorToObject(schema, obj) { + if (schema == null) { + return; + } + if (schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { + obj[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; + } +} + +/*! + * gets discriminator model if discriminator key is present in object + */ + +function decideModelByObject(model, object) { + const discriminatorKey = model.schema.options.discriminatorKey; + if (object != null && object.hasOwnProperty(discriminatorKey)) { + model = getDiscriminatorByValue(model.discriminators, object[discriminatorKey]) || model; + } + return model; +} diff --git a/node_modules/mongoose/lib/helpers/model/discriminator.js b/node_modules/mongoose/lib/helpers/model/discriminator.js new file mode 100644 index 0000000..25485e9 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/model/discriminator.js @@ -0,0 +1,209 @@ +'use strict'; + +const Mixed = require('../../schema/mixed'); +const defineKey = require('../document/compile').defineKey; +const get = require('../get'); +const utils = require('../../utils'); + +const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { + toJSON: true, + toObject: true, + _id: true, + id: true +}; + +/*! + * ignore + */ + +module.exports = function discriminator(model, name, schema, tiedValue, applyPlugins) { + if (!(schema && schema.instanceOfSchema)) { + throw new Error('You must pass a valid discriminator Schema'); + } + + if (model.schema.discriminatorMapping && + !model.schema.discriminatorMapping.isRoot) { + throw new Error('Discriminator "' + name + + '" can only be a discriminator of the root model'); + } + + if (applyPlugins) { + const applyPluginsToDiscriminators = get(model.base, + 'options.applyPluginsToDiscriminators', false); + // Even if `applyPluginsToDiscriminators` isn't set, we should still apply + // global plugins to schemas embedded in the discriminator schema (gh-7370) + model.base._applyPlugins(schema, { + skipTopLevel: !applyPluginsToDiscriminators + }); + } + + const key = model.schema.options.discriminatorKey; + + const existingPath = model.schema.path(key); + if (existingPath != null) { + if (!utils.hasUserDefinedProperty(existingPath.options, 'select')) { + existingPath.options.select = true; + } + existingPath.options.$skipDiscriminatorCheck = true; + } else { + const baseSchemaAddition = {}; + baseSchemaAddition[key] = { + default: void 0, + select: true, + $skipDiscriminatorCheck: true + }; + baseSchemaAddition[key][model.schema.options.typeKey] = String; + model.schema.add(baseSchemaAddition); + defineKey({ + prop: key, + prototype: model.prototype, + options: model.schema.options + }); + } + + if (schema.path(key) && schema.path(key).options.$skipDiscriminatorCheck !== true) { + throw new Error('Discriminator "' + name + + '" cannot have field with name "' + key + '"'); + } + + let value = name; + if ((typeof tiedValue === 'string' && tiedValue.length) || tiedValue != null) { + value = tiedValue; + } + + function merge(schema, baseSchema) { + // Retain original schema before merging base schema + schema._baseSchema = baseSchema; + if (baseSchema.paths._id && + baseSchema.paths._id.options && + !baseSchema.paths._id.options.auto) { + schema.remove('_id'); + } + + // Find conflicting paths: if something is a path in the base schema + // and a nested path in the child schema, overwrite the base schema path. + // See gh-6076 + const baseSchemaPaths = Object.keys(baseSchema.paths); + const conflictingPaths = []; + + for (const path of baseSchemaPaths) { + if (schema.nested[path]) { + conflictingPaths.push(path); + continue; + } + + if (path.indexOf('.') === -1) { + continue; + } + const sp = path.split('.').slice(0, -1); + let cur = ''; + for (const piece of sp) { + cur += (cur.length ? '.' : '') + piece; + if (schema.paths[cur] instanceof Mixed || + schema.singleNestedPaths[cur] instanceof Mixed) { + conflictingPaths.push(path); + } + } + } + + utils.merge(schema, baseSchema, { + isDiscriminatorSchemaMerge: true, + omit: { discriminators: true, base: true }, + omitNested: conflictingPaths.reduce((cur, path) => { + cur['tree.' + path] = true; + return cur; + }, {}) + }); + + // Clean up conflicting paths _after_ merging re: gh-6076 + for (const conflictingPath of conflictingPaths) { + delete schema.paths[conflictingPath]; + } + + // Rebuild schema models because schemas may have been merged re: #7884 + schema.childSchemas.forEach(obj => { + obj.model.prototype.$__setSchema(obj.schema); + }); + + const obj = {}; + obj[key] = { + default: value, + select: true, + set: function(newName) { + if (newName === value || (Array.isArray(value) && utils.deepEqual(newName, value))) { + return value; + } + throw new Error('Can\'t set discriminator key "' + key + '"'); + }, + $skipDiscriminatorCheck: true + }; + obj[key][schema.options.typeKey] = existingPath ? existingPath.options[schema.options.typeKey] : String; + schema.add(obj); + + + schema.discriminatorMapping = { key: key, value: value, isRoot: false }; + + if (baseSchema.options.collection) { + schema.options.collection = baseSchema.options.collection; + } + + const toJSON = schema.options.toJSON; + const toObject = schema.options.toObject; + const _id = schema.options._id; + const id = schema.options.id; + + const keys = Object.keys(schema.options); + schema.options.discriminatorKey = baseSchema.options.discriminatorKey; + + for (const _key of keys) { + if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) { + // Special case: compiling a model sets `pluralization = true` by default. Avoid throwing an error + // for that case. See gh-9238 + if (_key === 'pluralization' && schema.options[_key] == true && baseSchema.options[_key] == null) { + continue; + } + + if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) { + throw new Error('Can\'t customize discriminator option ' + _key + + ' (can only modify ' + + Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') + + ')'); + } + } + } + schema.options = utils.clone(baseSchema.options); + if (toJSON) schema.options.toJSON = toJSON; + if (toObject) schema.options.toObject = toObject; + if (typeof _id !== 'undefined') { + schema.options._id = _id; + } + schema.options.id = id; + schema.s.hooks = model.schema.s.hooks.merge(schema.s.hooks); + + schema.plugins = Array.prototype.slice.call(baseSchema.plugins); + schema.callQueue = baseSchema.callQueue.concat(schema.callQueue); + delete schema._requiredpaths; // reset just in case Schema#requiredPaths() was called on either schema + } + + // merges base schema into new discriminator schema and sets new type field. + merge(schema, model.schema); + + if (!model.discriminators) { + model.discriminators = {}; + } + + if (!model.schema.discriminatorMapping) { + model.schema.discriminatorMapping = { key: key, value: null, isRoot: true }; + } + if (!model.schema.discriminators) { + model.schema.discriminators = {}; + } + + model.schema.discriminators[name] = schema; + + if (model.discriminators[name]) { + throw new Error('Discriminator with name "' + name + '" already exists'); + } + + return schema; +}; diff --git a/node_modules/mongoose/lib/helpers/once.js b/node_modules/mongoose/lib/helpers/once.js new file mode 100644 index 0000000..0267579 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/once.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function once(fn) { + let called = false; + return function() { + if (called) { + return; + } + called = true; + return fn.apply(null, arguments); + }; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/parallelLimit.js b/node_modules/mongoose/lib/helpers/parallelLimit.js new file mode 100644 index 0000000..9b07c02 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/parallelLimit.js @@ -0,0 +1,55 @@ +'use strict'; + +module.exports = parallelLimit; + +/*! + * ignore + */ + +function parallelLimit(fns, limit, callback) { + let numInProgress = 0; + let numFinished = 0; + let error = null; + + if (limit <= 0) { + throw new Error('Limit must be positive'); + } + + if (fns.length === 0) { + return callback(null, []); + } + + for (let i = 0; i < fns.length && i < limit; ++i) { + _start(); + } + + function _start() { + fns[numFinished + numInProgress](_done(numFinished + numInProgress)); + ++numInProgress; + } + + const results = []; + + function _done(index) { + return (err, res) => { + --numInProgress; + ++numFinished; + + if (error != null) { + return; + } + if (err != null) { + error = err; + return callback(error); + } + + results[index] = res; + + if (numFinished === fns.length) { + return callback(null, results); + } else if (numFinished + numInProgress < fns.length) { + _start(); + } + }; + } +} diff --git a/node_modules/mongoose/lib/helpers/path/flattenObjectWithDottedPaths.js b/node_modules/mongoose/lib/helpers/path/flattenObjectWithDottedPaths.js new file mode 100644 index 0000000..9c2e289 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/path/flattenObjectWithDottedPaths.js @@ -0,0 +1,25 @@ +'use strict'; + +const setDottedPath = require('../path/setDottedPath'); + +/** + * Given an object that may contain dotted paths, flatten the paths out. + * For example: `flattenObjectWithDottedPaths({ a: { 'b.c': 42 } })` => `{ a: { b: { c: 42 } } }` + */ + +module.exports = function flattenObjectWithDottedPaths(obj) { + if (obj == null || typeof obj !== 'object' || Array.isArray(obj)) { + return; + } + const keys = Object.keys(obj); + for (const key of keys) { + const val = obj[key]; + if (key.indexOf('.') !== -1) { + delete obj[key]; + setDottedPath(obj, key, val); + continue; + } + + flattenObjectWithDottedPaths(obj[key]); + } +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/path/parentPaths.js b/node_modules/mongoose/lib/helpers/path/parentPaths.js new file mode 100644 index 0000000..77d00ae --- /dev/null +++ b/node_modules/mongoose/lib/helpers/path/parentPaths.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function parentPaths(path) { + const pieces = path.split('.'); + let cur = ''; + const ret = []; + for (let i = 0; i < pieces.length; ++i) { + cur += (cur.length > 0 ? '.' : '') + pieces[i]; + ret.push(cur); + } + + return ret; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/path/setDottedPath.js b/node_modules/mongoose/lib/helpers/path/setDottedPath.js new file mode 100644 index 0000000..853769c --- /dev/null +++ b/node_modules/mongoose/lib/helpers/path/setDottedPath.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = function setDottedPath(obj, path, val) { + const parts = path.indexOf('.') === -1 ? [path] : path.split('.'); + let cur = obj; + for (const part of parts.slice(0, -1)) { + if (cur[part] == null) { + cur[part] = {}; + } + + cur = cur[part]; + } + + const last = parts[parts.length - 1]; + cur[last] = val; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/pluralize.js b/node_modules/mongoose/lib/helpers/pluralize.js new file mode 100644 index 0000000..c567950 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/pluralize.js @@ -0,0 +1,94 @@ +'use strict'; + +module.exports = pluralize; + +/** + * Pluralization rules. + */ + +exports.pluralization = [ + [/(m)an$/gi, '$1en'], + [/(pe)rson$/gi, '$1ople'], + [/(child)$/gi, '$1ren'], + [/^(ox)$/gi, '$1en'], + [/(ax|test)is$/gi, '$1es'], + [/(octop|vir)us$/gi, '$1i'], + [/(alias|status)$/gi, '$1es'], + [/(bu)s$/gi, '$1ses'], + [/(buffal|tomat|potat)o$/gi, '$1oes'], + [/([ti])um$/gi, '$1a'], + [/sis$/gi, 'ses'], + [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'], + [/(hive)$/gi, '$1s'], + [/([^aeiouy]|qu)y$/gi, '$1ies'], + [/(x|ch|ss|sh)$/gi, '$1es'], + [/(matr|vert|ind)ix|ex$/gi, '$1ices'], + [/([m|l])ouse$/gi, '$1ice'], + [/(kn|w|l)ife$/gi, '$1ives'], + [/(quiz)$/gi, '$1zes'], + [/^goose$/i, 'geese'], + [/s$/gi, 's'], + [/([^a-z])$/, '$1'], + [/$/gi, 's'] +]; +const rules = exports.pluralization; + +/** + * Uncountable words. + * + * These words are applied while processing the argument to `toCollectionName`. + * @api public + */ + +exports.uncountables = [ + 'advice', + 'energy', + 'excretion', + 'digestion', + 'cooperation', + 'health', + 'justice', + 'labour', + 'machinery', + 'equipment', + 'information', + 'pollution', + 'sewage', + 'paper', + 'money', + 'species', + 'series', + 'rain', + 'rice', + 'fish', + 'sheep', + 'moose', + 'deer', + 'news', + 'expertise', + 'status', + 'media' +]; +const uncountables = exports.uncountables; + +/*! + * Pluralize function. + * + * @author TJ Holowaychuk (extracted from _ext.js_) + * @param {String} string to pluralize + * @api private + */ + +function pluralize(str) { + let found; + str = str.toLowerCase(); + if (!~uncountables.indexOf(str)) { + found = rules.filter(function(rule) { + return str.match(rule[0]); + }); + if (found[0]) { + return str.replace(found[0][0], found[0][1]); + } + } + return str; +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/SkipPopulateValue.js b/node_modules/mongoose/lib/helpers/populate/SkipPopulateValue.js new file mode 100644 index 0000000..5d46cfd --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/SkipPopulateValue.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function SkipPopulateValue(val) { + if (!(this instanceof SkipPopulateValue)) { + return new SkipPopulateValue(val); + } + + this.val = val; + return this; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js b/node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js new file mode 100644 index 0000000..562b15c --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js @@ -0,0 +1,107 @@ +'use strict'; + +const leanPopulateMap = require('./leanPopulateMap'); +const modelSymbol = require('../symbols').modelSymbol; +const utils = require('../../utils'); + +module.exports = assignRawDocsToIdStructure; + +/*! + * Assign `vals` returned by mongo query to the `rawIds` + * structure returned from utils.getVals() honoring + * query sort order if specified by user. + * + * This can be optimized. + * + * Rules: + * + * if the value of the path is not an array, use findOne rules, else find. + * for findOne the results are assigned directly to doc path (including null results). + * for find, if user specified sort order, results are assigned directly + * else documents are put back in original order of array if found in results + * + * @param {Array} rawIds + * @param {Array} vals + * @param {Boolean} sort + * @api private + */ + +function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, recursed) { + // honor user specified sort order + const newOrder = []; + const sorting = options.sort && rawIds.length > 1; + const nullIfNotFound = options.$nullIfNotFound; + let doc; + let sid; + let id; + + if (rawIds.isMongooseArrayProxy) { + rawIds = rawIds.__array; + } + + for (let i = 0; i < rawIds.length; ++i) { + id = rawIds[i]; + + if (Array.isArray(id)) { + // handle [ [id0, id2], [id3] ] + assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, true); + newOrder.push(id); + continue; + } + + if (id === null && !sorting) { + // keep nulls for findOne unless sorting, which always + // removes them (backward compat) + newOrder.push(id); + continue; + } + + sid = String(id); + + doc = resultDocs[sid]; + // If user wants separate copies of same doc, use this option + if (options.clone && doc != null) { + if (options.lean) { + const _model = leanPopulateMap.get(doc); + doc = utils.clone(doc); + leanPopulateMap.set(doc, _model); + } else { + doc = doc.constructor.hydrate(doc._doc); + } + } + + if (recursed) { + if (doc) { + if (sorting) { + const _resultOrder = resultOrder[sid]; + if (Array.isArray(_resultOrder) && Array.isArray(doc) && _resultOrder.length === doc.length) { + newOrder.push(doc); + } else { + newOrder[_resultOrder] = doc; + } + } else { + newOrder.push(doc); + } + } else if (id != null && id[modelSymbol] != null) { + newOrder.push(id); + } else { + newOrder.push(options.retainNullValues || nullIfNotFound ? null : id); + } + } else { + // apply findOne behavior - if document in results, assign, else assign null + newOrder[i] = doc || null; + } + } + + rawIds.length = 0; + if (newOrder.length) { + // reassign the documents based on corrected order + + // forEach skips over sparse entries in arrays so we + // can safely use this to our advantage dealing with sorted + // result sets too. + newOrder.forEach(function(doc, i) { + rawIds[i] = doc; + }); + } +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/assignVals.js b/node_modules/mongoose/lib/helpers/populate/assignVals.js new file mode 100644 index 0000000..f0a3949 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/assignVals.js @@ -0,0 +1,307 @@ +'use strict'; + +const MongooseMap = require('../../types/map'); +const SkipPopulateValue = require('./SkipPopulateValue'); +const assignRawDocsToIdStructure = require('./assignRawDocsToIdStructure'); +const get = require('../get'); +const getVirtual = require('./getVirtual'); +const leanPopulateMap = require('./leanPopulateMap'); +const lookupLocalFields = require('./lookupLocalFields'); +const markArraySubdocsPopulated = require('./markArraySubdocsPopulated'); +const mpath = require('mpath'); +const sift = require('sift').default; +const utils = require('../../utils'); +const { populateModelSymbol } = require('../symbols'); + +module.exports = function assignVals(o) { + // Options that aren't explicitly listed in `populateOptions` + const userOptions = Object.assign({}, get(o, 'allOptions.options.options'), get(o, 'allOptions.options')); + // `o.options` contains options explicitly listed in `populateOptions`, like + // `match` and `limit`. + const populateOptions = Object.assign({}, o.options, userOptions, { + justOne: o.justOne + }); + populateOptions.$nullIfNotFound = o.isVirtual; + const populatedModel = o.populatedModel; + + const originalIds = [].concat(o.rawIds); + + // replace the original ids in our intermediate _ids structure + // with the documents found by query + o.allIds = [].concat(o.allIds); + assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, populateOptions); + + // now update the original documents being populated using the + // result structure that contains real documents. + const docs = o.docs; + const rawIds = o.rawIds; + const options = o.options; + const count = o.count && o.isVirtual; + let i; + + function setValue(val) { + if (count) { + return val; + } + if (val instanceof SkipPopulateValue) { + return val.val; + } + if (val === void 0) { + return val; + } + + const _allIds = o.allIds[i]; + + if (o.justOne === true && Array.isArray(val)) { + // Might be an embedded discriminator (re: gh-9244) with multiple models, so make sure to pick the right + // model before assigning. + const ret = []; + for (const doc of val) { + const _docPopulatedModel = leanPopulateMap.get(doc); + if (_docPopulatedModel == null || _docPopulatedModel === populatedModel) { + ret.push(doc); + } + } + // Since we don't want to have to create a new mongoosearray, make sure to + // modify the array in place + while (val.length > ret.length) { + Array.prototype.pop.apply(val, []); + } + for (let i = 0; i < ret.length; ++i) { + val[i] = ret[i]; + } + + return valueFilter(val[0], options, populateOptions, _allIds); + } else if (o.justOne === false && !Array.isArray(val)) { + if (val === null && o.isVirtual) { + return void 0; + } + return valueFilter([val], options, populateOptions, _allIds); + } + return valueFilter(val, options, populateOptions, _allIds); + } + + for (i = 0; i < docs.length; ++i) { + const _path = o.path.endsWith('.$*') ? o.path.slice(0, -3) : o.path; + const existingVal = mpath.get(_path, docs[i], lookupLocalFields); + if (existingVal == null && !getVirtual(o.originalModel.schema, _path)) { + continue; + } + + let valueToSet; + if (count) { + valueToSet = numDocs(rawIds[i]); + } else if (Array.isArray(o.match)) { + valueToSet = Array.isArray(rawIds[i]) ? + rawIds[i].filter(sift(o.match[i])) : + [rawIds[i]].filter(sift(o.match[i]))[0]; + } else { + valueToSet = rawIds[i]; + } + + // If we're populating a map, the existing value will be an object, so + // we need to transform again + const originalSchema = o.originalModel.schema; + const isDoc = get(docs[i], '$__', null) != null; + let isMap = isDoc ? + existingVal instanceof Map : + utils.isPOJO(existingVal); + // If we pass the first check, also make sure the local field's schematype + // is map (re: gh-6460) + isMap = isMap && get(originalSchema._getSchema(_path), '$isSchemaMap'); + if (!o.isVirtual && isMap) { + const _keys = existingVal instanceof Map ? + Array.from(existingVal.keys()) : + Object.keys(existingVal); + valueToSet = valueToSet.reduce((cur, v, i) => { + cur.set(_keys[i], v); + return cur; + }, new Map()); + } + + if (isDoc && Array.isArray(valueToSet)) { + for (const val of valueToSet) { + if (val != null && val.$__ != null) { + val.$__.parent = docs[i]; + } + } + } else if (isDoc && valueToSet != null && valueToSet.$__ != null) { + valueToSet.$__.parent = docs[i]; + } + + if (o.isVirtual && isDoc) { + docs[i].$populated(_path, o.justOne ? originalIds[0] : originalIds, o.allOptions); + // If virtual populate and doc is already init-ed, need to walk through + // the actual doc to set rather than setting `_doc` directly + mpath.set(_path, valueToSet, docs[i], void 0, setValue, false); + continue; + } + + const parts = _path.split('.'); + let cur = docs[i]; + const curPath = parts[0]; + for (let j = 0; j < parts.length - 1; ++j) { + // If we get to an array with a dotted path, like `arr.foo`, don't set + // `foo` on the array. + if (Array.isArray(cur) && !utils.isArrayIndex(parts[j])) { + break; + } + + if (parts[j] === '$*') { + break; + } + + if (cur[parts[j]] == null) { + // If nothing to set, avoid creating an unnecessary array. Otherwise + // we'll end up with a single doc in the array with only defaults. + // See gh-8342, gh-8455 + const schematype = originalSchema._getSchema(curPath); + if (valueToSet == null && schematype != null && schematype.$isMongooseArray) { + break; + } + cur[parts[j]] = {}; + } + cur = cur[parts[j]]; + // If the property in MongoDB is a primitive, we won't be able to populate + // the nested path, so skip it. See gh-7545 + if (typeof cur !== 'object') { + break; + } + } + if (docs[i].$__) { + o.allOptions.options[populateModelSymbol] = o.allOptions.model; + docs[i].$populated(_path, o.allIds[i], o.allOptions.options); + + if (valueToSet instanceof Map && !valueToSet.$isMongooseMap) { + valueToSet = new MongooseMap(valueToSet, _path, docs[i], docs[i].schema.path(_path).$__schemaType); + } + } + + // If lean, need to check that each individual virtual respects + // `justOne`, because you may have a populated virtual with `justOne` + // underneath an array. See gh-6867 + mpath.set(_path, valueToSet, docs[i], lookupLocalFields, setValue, false); + + if (docs[i].$__) { + markArraySubdocsPopulated(docs[i], [o.allOptions.options]); + } + } +}; + +function numDocs(v) { + if (Array.isArray(v)) { + // If setting underneath an array of populated subdocs, we may have an + // array of arrays. See gh-7573 + if (v.some(el => Array.isArray(el))) { + return v.map(el => numDocs(el)); + } + return v.length; + } + return v == null ? 0 : 1; +} + +/*! + * 1) Apply backwards compatible find/findOne behavior to sub documents + * + * find logic: + * a) filter out non-documents + * b) remove _id from sub docs when user specified + * + * findOne + * a) if no doc found, set to null + * b) remove _id from sub docs when user specified + * + * 2) Remove _ids when specified by users query. + * + * background: + * _ids are left in the query even when user excludes them so + * that population mapping can occur. + */ + +function valueFilter(val, assignmentOpts, populateOptions, allIds) { + const userSpecifiedTransform = typeof populateOptions.transform === 'function'; + const transform = userSpecifiedTransform ? populateOptions.transform : noop; + if (Array.isArray(val)) { + // find logic + const ret = []; + const numValues = val.length; + for (let i = 0; i < numValues; ++i) { + let subdoc = val[i]; + const _allIds = Array.isArray(allIds) ? allIds[i] : allIds; + if (!isPopulatedObject(subdoc) && (!populateOptions.retainNullValues || subdoc != null) && !userSpecifiedTransform) { + continue; + } else if (userSpecifiedTransform) { + subdoc = transform(isPopulatedObject(subdoc) ? subdoc : null, _allIds); + } + maybeRemoveId(subdoc, assignmentOpts); + ret.push(subdoc); + if (assignmentOpts.originalLimit && + ret.length >= assignmentOpts.originalLimit) { + break; + } + } + + // Since we don't want to have to create a new mongoosearray, make sure to + // modify the array in place + while (val.length > ret.length) { + Array.prototype.pop.apply(val, []); + } + for (let i = 0; i < ret.length; ++i) { + if (val.isMongooseArrayProxy) { + val.set(i, ret[i], true); + } else { + val[i] = ret[i]; + } + } + return val; + } + + // findOne + if (isPopulatedObject(val) || utils.isPOJO(val)) { + maybeRemoveId(val, assignmentOpts); + return transform(val, allIds); + } + if (val instanceof Map) { + return val; + } + + if (populateOptions.justOne === false) { + return []; + } + + return val == null ? transform(val, allIds) : transform(null, allIds); +} + +/*! + * Remove _id from `subdoc` if user specified "lean" query option + */ + +function maybeRemoveId(subdoc, assignmentOpts) { + if (subdoc != null && assignmentOpts.excludeId) { + if (typeof subdoc.$__setValue === 'function') { + delete subdoc._doc._id; + } else { + delete subdoc._id; + } + } +} + +/*! + * Determine if `obj` is something we can set a populated path to. Can be a + * document, a lean document, or an array/map that contains docs. + */ + +function isPopulatedObject(obj) { + if (obj == null) { + return false; + } + + return Array.isArray(obj) || + obj.$isMongooseMap || + obj.$__ != null || + leanPopulateMap.has(obj); +} + +function noop(v) { + return v; +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/createPopulateQueryFilter.js b/node_modules/mongoose/lib/helpers/populate/createPopulateQueryFilter.js new file mode 100644 index 0000000..1f133b7 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/createPopulateQueryFilter.js @@ -0,0 +1,80 @@ +'use strict'; + +const SkipPopulateValue = require('./SkipPopulateValue'); +const parentPaths = require('../path/parentPaths'); +const { trusted } = require('../query/trusted'); + +module.exports = function createPopulateQueryFilter(ids, _match, _foreignField, model, skipInvalidIds) { + const match = _formatMatch(_match); + + if (_foreignField.size === 1) { + const foreignField = Array.from(_foreignField)[0]; + const foreignSchemaType = model.schema.path(foreignField); + if (foreignField !== '_id' || !match['_id']) { + ids = _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds); + match[foreignField] = trusted({ $in: ids }); + } + + const _parentPaths = parentPaths(foreignField); + for (let i = 0; i < _parentPaths.length - 1; ++i) { + const cur = _parentPaths[i]; + if (match[cur] != null && match[cur].$elemMatch != null) { + match[cur].$elemMatch[foreignField.slice(cur.length + 1)] = trusted({ $in: ids }); + delete match[foreignField]; + break; + } + } + } else { + const $or = []; + if (Array.isArray(match.$or)) { + match.$and = [{ $or: match.$or }, { $or: $or }]; + delete match.$or; + } else { + match.$or = $or; + } + for (const foreignField of _foreignField) { + if (foreignField !== '_id' || !match['_id']) { + const foreignSchemaType = model.schema.path(foreignField); + ids = _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds); + $or.push({ [foreignField]: { $in: ids } }); + } + } + } + + return match; +}; + +/*! + * Optionally filter out invalid ids that don't conform to foreign field's schema + * to avoid cast errors (gh-7706) + */ + +function _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds) { + ids = ids.filter(v => !(v instanceof SkipPopulateValue)); + if (!skipInvalidIds) { + return ids; + } + return ids.filter(id => { + try { + foreignSchemaType.cast(id); + return true; + } catch (err) { + return false; + } + }); +} + +/*! + * Format `mod.match` given that it may be an array that we need to $or if + * the client has multiple docs with match functions + */ + +function _formatMatch(match) { + if (Array.isArray(match)) { + if (match.length > 1) { + return { $or: [].concat(match.map(m => Object.assign({}, m))) }; + } + return Object.assign({}, match[0]); + } + return Object.assign({}, match); +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js b/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js new file mode 100644 index 0000000..08cdef4 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js @@ -0,0 +1,680 @@ +'use strict'; + +const MongooseError = require('../../error/index'); +const SkipPopulateValue = require('./SkipPopulateValue'); +const get = require('../get'); +const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue'); +const getConstructorName = require('../getConstructorName'); +const getSchemaTypes = require('./getSchemaTypes'); +const getVirtual = require('./getVirtual'); +const lookupLocalFields = require('./lookupLocalFields'); +const mpath = require('mpath'); +const modelNamesFromRefPath = require('./modelNamesFromRefPath'); +const utils = require('../../utils'); + +const modelSymbol = require('../symbols').modelSymbol; +const populateModelSymbol = require('../symbols').populateModelSymbol; +const schemaMixedSymbol = require('../../schema/symbols').schemaMixedSymbol; + +module.exports = function getModelsMapForPopulate(model, docs, options) { + let doc; + const len = docs.length; + const map = []; + const modelNameFromQuery = options.model && options.model.modelName || options.model; + let schema; + let refPath; + let modelNames; + const available = {}; + + const modelSchema = model.schema; + + // Populating a nested path should always be a no-op re: #9073. + // People shouldn't do this, but apparently they do. + if (options._localModel != null && options._localModel.schema.nested[options.path]) { + return []; + } + + const _virtualRes = getVirtual(model.schema, options.path); + const virtual = _virtualRes == null ? null : _virtualRes.virtual; + if (virtual != null) { + return _virtualPopulate(model, docs, options, _virtualRes); + } + + let allSchemaTypes = getSchemaTypes(model, modelSchema, null, options.path); + allSchemaTypes = Array.isArray(allSchemaTypes) ? allSchemaTypes : [allSchemaTypes].filter(v => v != null); + + if (allSchemaTypes.length <= 0 && options.strictPopulate !== false && options._localModel != null) { + return new MongooseError('Cannot populate path `' + options.path + + '` because it is not in your schema. Set the `strictPopulate` option ' + + 'to false to override.'); + } + + for (let i = 0; i < len; i++) { + doc = docs[i]; + let justOne = null; + + const docSchema = doc != null && doc.$__ != null ? doc.$__schema : modelSchema; + schema = getSchemaTypes(model, docSchema, doc, options.path); + + // Special case: populating a path that's a DocumentArray unless + // there's an explicit `ref` or `refPath` re: gh-8946 + if (schema != null && + schema.$isMongooseDocumentArray && + schema.options.ref == null && + schema.options.refPath == null) { + continue; + } + const isUnderneathDocArray = schema && schema.$isUnderneathDocArray; + if (isUnderneathDocArray && get(options, 'options.sort') != null) { + return new MongooseError('Cannot populate with `sort` on path ' + options.path + + ' because it is a subproperty of a document array'); + } + + modelNames = null; + let isRefPath = false; + let normalizedRefPath = null; + let schemaOptions = null; + + if (Array.isArray(schema)) { + const schemasArray = schema; + for (const _schema of schemasArray) { + let _modelNames; + let res; + try { + res = _getModelNames(doc, _schema, modelNameFromQuery, model); + _modelNames = res.modelNames; + isRefPath = isRefPath || res.isRefPath; + normalizedRefPath = normalizedRefPath || res.refPath; + justOne = res.justOne; + } catch (error) { + return error; + } + + if (isRefPath && !res.isRefPath) { + continue; + } + if (!_modelNames) { + continue; + } + modelNames = modelNames || []; + for (const modelName of _modelNames) { + if (modelNames.indexOf(modelName) === -1) { + modelNames.push(modelName); + } + } + } + } else { + try { + const res = _getModelNames(doc, schema, modelNameFromQuery, model); + modelNames = res.modelNames; + isRefPath = res.isRefPath; + normalizedRefPath = normalizedRefPath || res.refPath; + justOne = res.justOne; + schemaOptions = get(schema, 'options.populate', null); + } catch (error) { + return error; + } + + if (!modelNames) { + continue; + } + } + + const data = {}; + const localField = options.path; + const foreignField = '_id'; + + // `justOne = null` means we don't know from the schema whether the end + // result should be an array or a single doc. This can result from + // populating a POJO using `Model.populate()` + if ('justOne' in options && options.justOne !== void 0) { + justOne = options.justOne; + } else if (schema && !schema[schemaMixedSymbol]) { + // Skip Mixed types because we explicitly don't do casting on those. + if (options.path.endsWith('.' + schema.path) || options.path === schema.path) { + justOne = Array.isArray(schema) ? + schema.every(schema => !schema.$isMongooseArray) : + !schema.$isMongooseArray; + } + } + + if (!modelNames) { + continue; + } + + data.isVirtual = false; + data.justOne = justOne; + data.localField = localField; + data.foreignField = foreignField; + + // Get local fields + const ret = _getLocalFieldValues(doc, localField, model, options, null, schema); + + const id = String(utils.getValue(foreignField, doc)); + options._docs[id] = Array.isArray(ret) ? ret.slice() : ret; + + let match = get(options, 'match', null); + + const hasMatchFunction = typeof match === 'function'; + if (hasMatchFunction) { + match = match.call(doc, doc); + } + data.match = match; + data.hasMatchFunction = hasMatchFunction; + data.isRefPath = isRefPath; + + if (isRefPath) { + const embeddedDiscriminatorModelNames = _findRefPathForDiscriminators(doc, + modelSchema, data, options, normalizedRefPath, ret); + + modelNames = embeddedDiscriminatorModelNames || modelNames; + } + + try { + addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc, schemaOptions); + } catch (err) { + return err; + } + } + return map; + + function _getModelNames(doc, schema, modelNameFromQuery, model) { + let modelNames; + let isRefPath = false; + let justOne = null; + + if (schema && schema.caster) { + schema = schema.caster; + } + if (schema && schema.$isSchemaMap) { + schema = schema.$__schemaType; + } + + const ref = schema && schema.options && schema.options.ref; + refPath = schema && schema.options && schema.options.refPath; + if (schema != null && + schema[schemaMixedSymbol] && + !ref && + !refPath && + !modelNameFromQuery) { + return { modelNames: null }; + } + + if (modelNameFromQuery) { + modelNames = [modelNameFromQuery]; // query options + } else if (refPath != null) { + if (typeof refPath === 'function') { + const subdocPath = options.path.slice(0, options.path.length - schema.path.length - 1); + const vals = mpath.get(subdocPath, doc, lookupLocalFields); + const subdocsBeingPopulated = Array.isArray(vals) ? + utils.array.flatten(vals) : + (vals ? [vals] : []); + + modelNames = new Set(); + for (const subdoc of subdocsBeingPopulated) { + refPath = refPath.call(subdoc, subdoc, options.path); + modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection). + forEach(name => modelNames.add(name)); + } + modelNames = Array.from(modelNames); + } else { + modelNames = modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection); + } + + isRefPath = true; + } else { + let ref; + let refPath; + let schemaForCurrentDoc; + let discriminatorValue; + let modelForCurrentDoc = model; + const discriminatorKey = model.schema.options.discriminatorKey; + + if (!schema && discriminatorKey && (discriminatorValue = utils.getValue(discriminatorKey, doc))) { + // `modelNameForFind` is the discriminator value, so we might need + // find the discriminated model name + const discriminatorModel = getDiscriminatorByValue(model.discriminators, discriminatorValue) || model; + if (discriminatorModel != null) { + modelForCurrentDoc = discriminatorModel; + } else { + try { + modelForCurrentDoc = model.db.model(discriminatorValue); + } catch (error) { + return error; + } + } + + schemaForCurrentDoc = modelForCurrentDoc.schema._getSchema(options.path); + + if (schemaForCurrentDoc && schemaForCurrentDoc.caster) { + schemaForCurrentDoc = schemaForCurrentDoc.caster; + } + } else { + schemaForCurrentDoc = schema; + } + + if (schemaForCurrentDoc != null) { + justOne = !schemaForCurrentDoc.$isMongooseArray && !schemaForCurrentDoc._arrayPath; + } + + if ((ref = get(schemaForCurrentDoc, 'options.ref')) != null) { + if (schemaForCurrentDoc != null && + typeof ref === 'function' && + options.path.endsWith('.' + schemaForCurrentDoc.path)) { + // Ensure correct context for ref functions: subdoc, not top-level doc. See gh-8469 + modelNames = new Set(); + + const subdocPath = options.path.slice(0, options.path.length - schemaForCurrentDoc.path.length - 1); + const vals = mpath.get(subdocPath, doc, lookupLocalFields); + const subdocsBeingPopulated = Array.isArray(vals) ? + utils.array.flatten(vals) : + (vals ? [vals] : []); + for (const subdoc of subdocsBeingPopulated) { + modelNames.add(handleRefFunction(ref, subdoc)); + } + + if (subdocsBeingPopulated.length === 0) { + modelNames = [handleRefFunction(ref, doc)]; + } else { + modelNames = Array.from(modelNames); + } + } else { + ref = handleRefFunction(ref, doc); + modelNames = [ref]; + } + } else if ((schemaForCurrentDoc = get(schema, 'options.refPath')) != null) { + isRefPath = true; + if (typeof refPath === 'function') { + const subdocPath = options.path.slice(0, options.path.length - schemaForCurrentDoc.path.length - 1); + const vals = mpath.get(subdocPath, doc, lookupLocalFields); + const subdocsBeingPopulated = Array.isArray(vals) ? + utils.array.flatten(vals) : + (vals ? [vals] : []); + + modelNames = new Set(); + for (const subdoc of subdocsBeingPopulated) { + refPath = refPath.call(subdoc, subdoc, options.path); + modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection). + forEach(name => modelNames.add(name)); + } + modelNames = Array.from(modelNames); + } else { + modelNames = modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection); + } + } + } + + if (!modelNames) { + return { modelNames: modelNames, justOne: justOne, isRefPath: isRefPath, refPath: refPath }; + } + + if (!Array.isArray(modelNames)) { + modelNames = [modelNames]; + } + + return { modelNames: modelNames, justOne: justOne, isRefPath: isRefPath, refPath: refPath }; + } +}; + +/*! + * ignore + */ + +function _virtualPopulate(model, docs, options, _virtualRes) { + const map = []; + const available = {}; + const virtual = _virtualRes.virtual; + + for (const doc of docs) { + let modelNames = null; + const data = {}; + + // localField and foreignField + let localField; + const virtualPrefix = _virtualRes.nestedSchemaPath ? + _virtualRes.nestedSchemaPath + '.' : ''; + if (typeof virtual.options.localField === 'function') { + localField = virtualPrefix + virtual.options.localField.call(doc, doc); + } else if (Array.isArray(virtual.options.localField)) { + localField = virtual.options.localField.map(field => virtualPrefix + field); + } else { + localField = virtualPrefix + virtual.options.localField; + } + data.count = virtual.options.count; + + if (virtual.options.skip != null && !options.hasOwnProperty('skip')) { + options.skip = virtual.options.skip; + } + if (virtual.options.limit != null && !options.hasOwnProperty('limit')) { + options.limit = virtual.options.limit; + } + if (virtual.options.perDocumentLimit != null && !options.hasOwnProperty('perDocumentLimit')) { + options.perDocumentLimit = virtual.options.perDocumentLimit; + } + let foreignField = virtual.options.foreignField; + + if (!localField || !foreignField) { + return new MongooseError('If you are populating a virtual, you must set the ' + + 'localField and foreignField options'); + } + + if (typeof localField === 'function') { + localField = localField.call(doc, doc); + } + if (typeof foreignField === 'function') { + foreignField = foreignField.call(doc); + } + + data.isRefPath = false; + + // `justOne = null` means we don't know from the schema whether the end + // result should be an array or a single doc. This can result from + // populating a POJO using `Model.populate()` + let justOne = null; + if ('justOne' in options && options.justOne !== void 0) { + justOne = options.justOne; + } + + if (virtual.options.refPath) { + modelNames = + modelNamesFromRefPath(virtual.options.refPath, doc, options.path); + justOne = !!virtual.options.justOne; + data.isRefPath = true; + } else if (virtual.options.ref) { + let normalizedRef; + if (typeof virtual.options.ref === 'function' && !virtual.options.ref[modelSymbol]) { + normalizedRef = virtual.options.ref.call(doc, doc); + } else { + normalizedRef = virtual.options.ref; + } + justOne = !!virtual.options.justOne; + // When referencing nested arrays, the ref should be an Array + // of modelNames. + if (Array.isArray(normalizedRef)) { + modelNames = normalizedRef; + } else { + modelNames = [normalizedRef]; + } + } + + data.isVirtual = true; + data.virtual = virtual; + data.justOne = justOne; + + // `match` + let match = get(options, 'match', null) || + get(data, 'virtual.options.match', null) || + get(data, 'virtual.options.options.match', null); + + let hasMatchFunction = typeof match === 'function'; + if (hasMatchFunction) { + match = match.call(doc, doc); + } + + if (Array.isArray(localField) && Array.isArray(foreignField) && localField.length === foreignField.length) { + match = Object.assign({}, match); + for (let i = 1; i < localField.length; ++i) { + match[foreignField[i]] = convertTo_id(mpath.get(localField[i], doc, lookupLocalFields), model.schema); + hasMatchFunction = true; + } + + localField = localField[0]; + foreignField = foreignField[0]; + } + + data.localField = localField; + data.foreignField = foreignField; + data.match = match; + data.hasMatchFunction = hasMatchFunction; + + // Get local fields + const ret = _getLocalFieldValues(doc, localField, model, options, virtual); + + try { + addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc); + } catch (err) { + return err; + } + } + + return map; +} + +/*! + * ignore + */ + +function addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc, schemaOptions) { + // `PopulateOptions#connection`: if the model is passed as a string, the + // connection matters because different connections have different models. + const connection = options.connection != null ? options.connection : model.db; + + if (modelNames == null) { + return; + } + + let k = modelNames.length; + while (k--) { + const modelName = modelNames[k]; + if (modelName == null) { + continue; + } + + let Model; + if (options.model && options.model[modelSymbol]) { + Model = options.model; + } else if (modelName[modelSymbol]) { + Model = modelName; + } else { + try { + Model = connection.model(modelName); + } catch (err) { + if (ret !== void 0) { + throw err; + } + Model = null; + } + } + + let ids = ret; + const flat = Array.isArray(ret) ? utils.array.flatten(ret) : []; + + if (data.isRefPath && Array.isArray(ret) && flat.length === modelNames.length) { + ids = flat.filter((val, i) => modelNames[i] === modelName); + } + + const perDocumentLimit = options.perDocumentLimit == null ? + get(options, 'options.perDocumentLimit', null) : + options.perDocumentLimit; + + if (!available[modelName] || perDocumentLimit != null) { + const currentOptions = { + model: Model + }; + + if (data.isVirtual && get(data.virtual, 'options.options')) { + currentOptions.options = utils.clone(data.virtual.options.options); + } else if (schemaOptions != null) { + currentOptions.options = Object.assign({}, schemaOptions); + } + utils.merge(currentOptions, options); + + // Used internally for checking what model was used to populate this + // path. + options[populateModelSymbol] = Model; + + available[modelName] = { + model: Model, + options: currentOptions, + match: data.hasMatchFunction ? [data.match] : data.match, + docs: [doc], + ids: [ids], + allIds: [ret], + localField: new Set([data.localField]), + foreignField: new Set([data.foreignField]), + justOne: data.justOne, + isVirtual: data.isVirtual, + virtual: data.virtual, + count: data.count, + [populateModelSymbol]: Model + }; + map.push(available[modelName]); + } else { + available[modelName].localField.add(data.localField); + available[modelName].foreignField.add(data.foreignField); + available[modelName].docs.push(doc); + available[modelName].ids.push(ids); + available[modelName].allIds.push(ret); + if (data.hasMatchFunction) { + available[modelName].match.push(data.match); + } + } + } +} + +/*! + * ignore + */ + +function handleRefFunction(ref, doc) { + if (typeof ref === 'function' && !ref[modelSymbol]) { + return ref.call(doc, doc); + } + return ref; +} + +/*! + * ignore + */ + +function _getLocalFieldValues(doc, localField, model, options, virtual, schema) { + // Get Local fields + const localFieldPathType = model.schema._getPathType(localField); + const localFieldPath = localFieldPathType === 'real' ? + model.schema.path(localField) : + localFieldPathType.schema; + const localFieldGetters = localFieldPath && localFieldPath.getters ? + localFieldPath.getters : []; + + const _populateOptions = get(options, 'options', {}); + + const getters = 'getters' in _populateOptions ? + _populateOptions.getters : + get(virtual, 'options.getters', false); + if (localFieldGetters.length > 0 && getters) { + const hydratedDoc = (doc.$__ != null) ? doc : model.hydrate(doc); + const localFieldValue = utils.getValue(localField, doc); + if (Array.isArray(localFieldValue)) { + const localFieldHydratedValue = utils.getValue(localField.split('.').slice(0, -1), hydratedDoc); + return localFieldValue.map((localFieldArrVal, localFieldArrIndex) => + localFieldPath.applyGetters(localFieldArrVal, localFieldHydratedValue[localFieldArrIndex])); + } else { + return localFieldPath.applyGetters(localFieldValue, hydratedDoc); + } + } else { + return convertTo_id(mpath.get(localField, doc, lookupLocalFields), schema); + } +} + +/*! + * Retrieve the _id of `val` if a Document or Array of Documents. + * + * @param {Array|Document|Any} val + * @return {Array|Document|Any} + */ + +function convertTo_id(val, schema) { + if (val != null && val.$__ != null) { + return val._id; + } + if (val != null && val._id != null && (schema == null || !schema.$isSchemaMap)) { + return val._id; + } + + if (Array.isArray(val)) { + const rawVal = val.__array != null ? val.__array : val; + for (let i = 0; i < rawVal.length; ++i) { + if (rawVal[i] != null && rawVal[i].$__ != null) { + rawVal[i] = rawVal[i]._id; + } + } + if (val.isMongooseArray && val.$schema()) { + return val.$schema()._castForPopulate(val, val.$parent()); + } + + return [].concat(val); + } + + // `populate('map')` may be an object if populating on a doc that hasn't + // been hydrated yet + if (getConstructorName(val) === 'Object' && + // The intent here is we should only flatten the object if we expect + // to get a Map in the end. Avoid doing this for mixed types. + (schema == null || schema[schemaMixedSymbol] == null)) { + const ret = []; + for (const key of Object.keys(val)) { + ret.push(val[key]); + } + return ret; + } + // If doc has already been hydrated, e.g. `doc.populate('map')` + // then `val` will already be a map + if (val instanceof Map) { + return Array.from(val.values()); + } + + return val; +} + +/*! + * ignore + */ + +function _findRefPathForDiscriminators(doc, modelSchema, data, options, normalizedRefPath, ret) { + // Re: gh-8452. Embedded discriminators may not have `refPath`, so clear + // out embedded discriminator docs that don't have a `refPath` on the + // populated path. + if (!data.isRefPath || normalizedRefPath == null) { + return; + } + + const pieces = normalizedRefPath.split('.'); + let cur = ''; + let modelNames = void 0; + for (let i = 0; i < pieces.length; ++i) { + const piece = pieces[i]; + cur = cur + (cur.length === 0 ? '' : '.') + piece; + const schematype = modelSchema.path(cur); + if (schematype != null && + schematype.$isMongooseArray && + schematype.caster.discriminators != null && + Object.keys(schematype.caster.discriminators).length > 0) { + const subdocs = utils.getValue(cur, doc); + const remnant = options.path.substr(cur.length + 1); + const discriminatorKey = schematype.caster.schema.options.discriminatorKey; + modelNames = []; + for (const subdoc of subdocs) { + const discriminatorName = utils.getValue(discriminatorKey, subdoc); + const discriminator = schematype.caster.discriminators[discriminatorName]; + const discriminatorSchema = discriminator && discriminator.schema; + if (discriminatorSchema == null) { + continue; + } + const _path = discriminatorSchema.path(remnant); + if (_path == null || _path.options.refPath == null) { + const docValue = utils.getValue(data.localField.substr(cur.length + 1), subdoc); + ret.forEach((v, i) => { + if (v === docValue) { + ret[i] = SkipPopulateValue(v); + } + }); + continue; + } + const modelName = utils.getValue(pieces.slice(i + 1).join('.'), subdoc); + modelNames.push(modelName); + } + } + } + + return modelNames; +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js b/node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js new file mode 100644 index 0000000..76c4286 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js @@ -0,0 +1,229 @@ +'use strict'; + +/*! + * ignore + */ + +const Mixed = require('../../schema/mixed'); +const get = require('../get'); +const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue'); +const leanPopulateMap = require('./leanPopulateMap'); +const mpath = require('mpath'); + +const populateModelSymbol = require('../symbols').populateModelSymbol; + +/*! + * Given a model and its schema, find all possible schema types for `path`, + * including searching through discriminators. If `doc` is specified, will + * use the doc's values for discriminator keys when searching, otherwise + * will search all discriminators. + * + * @param {Schema} schema + * @param {Object} doc POJO + * @param {string} path + */ + +module.exports = function getSchemaTypes(model, schema, doc, path) { + const pathschema = schema.path(path); + const topLevelDoc = doc; + if (pathschema) { + return pathschema; + } + + const discriminatorKey = schema.discriminatorMapping && + schema.discriminatorMapping.key; + if (discriminatorKey && model != null) { + if (doc != null && doc[discriminatorKey] != null) { + const discriminator = getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]); + schema = discriminator ? discriminator.schema : schema; + } else if (model.discriminators != null) { + return Object.keys(model.discriminators).reduce((arr, name) => { + const disc = model.discriminators[name]; + return arr.concat(getSchemaTypes(disc, disc.schema, null, path)); + }, []); + } + } + + function search(parts, schema, subdoc, nestedPath) { + let p = parts.length + 1; + let foundschema; + let trypath; + + while (p--) { + trypath = parts.slice(0, p).join('.'); + foundschema = schema.path(trypath); + if (foundschema == null) { + continue; + } + + if (foundschema.caster) { + // array of Mixed? + if (foundschema.caster instanceof Mixed) { + return foundschema.caster; + } + + let schemas = null; + if (foundschema.schema != null && foundschema.schema.discriminators != null) { + const discriminators = foundschema.schema.discriminators; + const discriminatorKeyPath = trypath + '.' + + foundschema.schema.options.discriminatorKey; + const keys = subdoc ? mpath.get(discriminatorKeyPath, subdoc) || [] : []; + schemas = Object.keys(discriminators). + reduce(function(cur, discriminator) { + const tiedValue = discriminators[discriminator].discriminatorMapping.value; + if (doc == null || keys.indexOf(discriminator) !== -1 || keys.indexOf(tiedValue) !== -1) { + cur.push(discriminators[discriminator]); + } + return cur; + }, []); + } + + // Now that we found the array, we need to check if there + // are remaining document paths to look up for casting. + // Also we need to handle array.$.path since schema.path + // doesn't work for that. + // If there is no foundschema.schema we are dealing with + // a path like array.$ + if (p !== parts.length && foundschema.schema) { + let ret; + if (parts[p] === '$') { + if (p + 1 === parts.length) { + // comments.$ + return foundschema; + } + // comments.$.comments.$.title + ret = search( + parts.slice(p + 1), + schema, + subdoc ? mpath.get(trypath, subdoc) : null, + nestedPath.concat(parts.slice(0, p)) + ); + if (ret) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !foundschema.schema.$isSingleNested; + } + return ret; + } + + if (schemas != null && schemas.length > 0) { + ret = []; + for (const schema of schemas) { + const _ret = search( + parts.slice(p), + schema, + subdoc ? mpath.get(trypath, subdoc) : null, + nestedPath.concat(parts.slice(0, p)) + ); + if (_ret != null) { + _ret.$isUnderneathDocArray = _ret.$isUnderneathDocArray || + !foundschema.schema.$isSingleNested; + if (_ret.$isUnderneathDocArray) { + ret.$isUnderneathDocArray = true; + } + ret.push(_ret); + } + } + return ret; + } else { + ret = search( + parts.slice(p), + foundschema.schema, + subdoc ? mpath.get(trypath, subdoc) : null, + nestedPath.concat(parts.slice(0, p)) + ); + + if (ret) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !foundschema.schema.$isSingleNested; + } + return ret; + } + } else if (p !== parts.length && + foundschema.$isMongooseArray && + foundschema.casterConstructor.$isMongooseArray) { + // Nested arrays. Drill down to the bottom of the nested array. + let type = foundschema; + while (type.$isMongooseArray && !type.$isMongooseDocumentArray) { + type = type.casterConstructor; + } + + const ret = search( + parts.slice(p), + type.schema, + null, + nestedPath.concat(parts.slice(0, p)) + ); + if (ret != null) { + return ret; + } + + if (type.schema.discriminators) { + const discriminatorPaths = []; + for (const discriminatorName of Object.keys(type.schema.discriminators)) { + const _schema = type.schema.discriminators[discriminatorName] || type.schema; + const ret = search(parts.slice(p), _schema, null, nestedPath.concat(parts.slice(0, p))); + if (ret != null) { + discriminatorPaths.push(ret); + } + } + if (discriminatorPaths.length > 0) { + return discriminatorPaths; + } + } + } + } + + const fullPath = nestedPath.concat([trypath]).join('.'); + if (topLevelDoc != null && topLevelDoc.$__ && topLevelDoc.$populated(fullPath) && p < parts.length) { + const model = doc.$__.populated[fullPath].options[populateModelSymbol]; + if (model != null) { + const ret = search( + parts.slice(p), + model.schema, + subdoc ? mpath.get(trypath, subdoc) : null, + nestedPath.concat(parts.slice(0, p)) + ); + + if (ret) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !model.schema.$isSingleNested; + } + return ret; + } + } + + const _val = get(topLevelDoc, trypath); + if (_val != null) { + const model = Array.isArray(_val) && _val.length > 0 ? + leanPopulateMap.get(_val[0]) : + leanPopulateMap.get(_val); + // Populated using lean, `leanPopulateMap` value is the foreign model + const schema = model != null ? model.schema : null; + if (schema != null) { + const ret = search( + parts.slice(p), + schema, + subdoc ? mpath.get(trypath, subdoc) : null, + nestedPath.concat(parts.slice(0, p)) + ); + + if (ret != null) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !schema.$isSingleNested; + return ret; + } + } + } + return foundschema; + } + } + // look for arrays + const parts = path.split('.'); + for (let i = 0; i < parts.length; ++i) { + if (parts[i] === '$') { + // Re: gh-5628, because `schema.path()` doesn't take $ into account. + parts[i] = '0'; + } + } + return search(parts, schema, doc, []); +}; diff --git a/node_modules/mongoose/lib/helpers/populate/getVirtual.js b/node_modules/mongoose/lib/helpers/populate/getVirtual.js new file mode 100644 index 0000000..fc1641d --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/getVirtual.js @@ -0,0 +1,72 @@ +'use strict'; + +module.exports = getVirtual; + +/*! + * ignore + */ + +function getVirtual(schema, name) { + if (schema.virtuals[name]) { + return { virtual: schema.virtuals[name], path: void 0 }; + } + + const parts = name.split('.'); + let cur = ''; + let nestedSchemaPath = ''; + for (let i = 0; i < parts.length; ++i) { + cur += (cur.length > 0 ? '.' : '') + parts[i]; + if (schema.virtuals[cur]) { + if (i === parts.length - 1) { + return { virtual: schema.virtuals[cur], path: nestedSchemaPath }; + } + continue; + } + + if (schema.nested[cur]) { + continue; + } + + if (schema.paths[cur] && schema.paths[cur].schema) { + schema = schema.paths[cur].schema; + const rest = parts.slice(i + 1).join('.'); + + if (schema.virtuals[rest]) { + if (i === parts.length - 2) { + return { + virtual: schema.virtuals[rest], + nestedSchemaPath: [nestedSchemaPath, cur].filter(v => !!v).join('.') + }; + } + continue; + } + + if (i + 1 < parts.length && schema.discriminators) { + for (const key of Object.keys(schema.discriminators)) { + const res = getVirtual(schema.discriminators[key], rest); + if (res != null) { + const _path = [nestedSchemaPath, cur, res.nestedSchemaPath]. + filter(v => !!v).join('.'); + return { + virtual: res.virtual, + nestedSchemaPath: _path + }; + } + } + } + + nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + cur; + cur = ''; + continue; + } + + if (schema.discriminators) { + for (const discriminatorKey of Object.keys(schema.discriminators)) { + const virtualFromDiscriminator = getVirtual(schema.discriminators[discriminatorKey], name); + if (virtualFromDiscriminator) return virtualFromDiscriminator; + } + } + + return null; + } +} diff --git a/node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js b/node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js new file mode 100644 index 0000000..a333124 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js @@ -0,0 +1,7 @@ +'use strict'; + +/*! + * ignore + */ + +module.exports = new WeakMap(); \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/lookupLocalFields.js b/node_modules/mongoose/lib/helpers/populate/lookupLocalFields.js new file mode 100644 index 0000000..be553eb --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/lookupLocalFields.js @@ -0,0 +1,40 @@ +'use strict'; + +module.exports = function lookupLocalFields(cur, path, val) { + if (cur == null) { + return cur; + } + + if (cur._doc != null) { + cur = cur._doc; + } + + if (arguments.length >= 3) { + if (typeof cur !== 'object') { + return void 0; + } + if (val === void 0) { + return void 0; + } + if (cur instanceof Map) { + cur.set(path, val); + } else { + cur[path] = val; + } + return val; + } + + + // Support populating paths under maps using `map.$*.subpath` + if (path === '$*') { + return cur instanceof Map ? + Array.from(cur.values()) : + Object.keys(cur).map(key => cur[key]); + } + + if (cur instanceof Map) { + return cur.get(path); + } + + return cur[path]; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/markArraySubdocsPopulated.js b/node_modules/mongoose/lib/helpers/populate/markArraySubdocsPopulated.js new file mode 100644 index 0000000..fd7a2dd --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/markArraySubdocsPopulated.js @@ -0,0 +1,40 @@ +'use strict'; + +/*! + * If populating a path within a document array, make sure each + * subdoc within the array knows its subpaths are populated. + * + * ####Example: + * const doc = await Article.findOne().populate('comments.author'); + * doc.comments[0].populated('author'); // Should be set + */ + +module.exports = function markArraySubdocsPopulated(doc, populated) { + if (doc._id == null || populated == null || populated.length === 0) { + return; + } + + const id = String(doc._id); + for (const item of populated) { + if (item.isVirtual) { + continue; + } + const path = item.path; + const pieces = path.split('.'); + for (let i = 0; i < pieces.length - 1; ++i) { + const subpath = pieces.slice(0, i + 1).join('.'); + const rest = pieces.slice(i + 1).join('.'); + const val = doc.get(subpath); + if (val == null) { + continue; + } + + if (val.isMongooseDocumentArray) { + for (let j = 0; j < val.length; ++j) { + val[j].populated(rest, item._docs[id] == null ? void 0 : item._docs[id][j], item); + } + break; + } + } + } +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/modelNamesFromRefPath.js b/node_modules/mongoose/lib/helpers/populate/modelNamesFromRefPath.js new file mode 100644 index 0000000..c441f56 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/modelNamesFromRefPath.js @@ -0,0 +1,65 @@ +'use strict'; + +const MongooseError = require('../../error/mongooseError'); +const isPathExcluded = require('../projection/isPathExcluded'); +const util = require('util'); +const utils = require('../../utils'); + +module.exports = function modelNamesFromRefPath(refPath, doc, populatedPath, modelSchema, queryProjection) { + if (refPath == null) { + return []; + } + + if (typeof refPath === 'string' && queryProjection != null && isPathExcluded(queryProjection, refPath)) { + throw new MongooseError('refPath `' + refPath + '` must not be excluded in projection, got ' + + util.inspect(queryProjection)); + } + + // If populated path has numerics, the end `refPath` should too. For example, + // if populating `a.0.b` instead of `a.b` and `b` has `refPath = a.c`, we + // should return `a.0.c` for the refPath. + const hasNumericProp = /(\.\d+$|\.\d+\.)/g; + + if (hasNumericProp.test(populatedPath)) { + const chunks = populatedPath.split(hasNumericProp); + + if (chunks[chunks.length - 1] === '') { + throw new Error('Can\'t populate individual element in an array'); + } + + let _refPath = ''; + let _remaining = refPath; + // 2nd, 4th, etc. will be numeric props. For example: `[ 'a', '.0.', 'b' ]` + for (let i = 0; i < chunks.length; i += 2) { + const chunk = chunks[i]; + if (_remaining.startsWith(chunk + '.')) { + _refPath += _remaining.substr(0, chunk.length) + chunks[i + 1]; + _remaining = _remaining.substr(chunk.length + 1); + } else if (i === chunks.length - 1) { + _refPath += _remaining; + _remaining = ''; + break; + } else { + throw new Error('Could not normalize ref path, chunk ' + chunk + ' not in populated path'); + } + } + + const refValue = utils.getValue(_refPath, doc); + let modelNames = Array.isArray(refValue) ? refValue : [refValue]; + modelNames = utils.array.flatten(modelNames); + return modelNames; + } + + const refValue = utils.getValue(refPath, doc); + + let modelNames; + if (modelSchema != null && modelSchema.virtuals.hasOwnProperty(refPath)) { + modelNames = [modelSchema.virtuals[refPath].applyGetters(void 0, doc)]; + } else { + modelNames = Array.isArray(refValue) ? refValue : [refValue]; + } + + modelNames = utils.array.flatten(modelNames); + + return modelNames; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/removeDeselectedForeignField.js b/node_modules/mongoose/lib/helpers/populate/removeDeselectedForeignField.js new file mode 100644 index 0000000..39b893a --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/removeDeselectedForeignField.js @@ -0,0 +1,31 @@ +'use strict'; + +const get = require('../get'); +const mpath = require('mpath'); +const parseProjection = require('../projection/parseProjection'); + +/*! + * ignore + */ + +module.exports = function removeDeselectedForeignField(foreignFields, options, docs) { + const projection = parseProjection(get(options, 'select', null), true) || + parseProjection(get(options, 'options.select', null), true); + + if (projection == null) { + return; + } + for (const foreignField of foreignFields) { + if (!projection.hasOwnProperty('-' + foreignField)) { + continue; + } + + for (const val of docs) { + if (val.$__ != null) { + mpath.unset(foreignField, val._doc); + } else { + mpath.unset(foreignField, val); + } + } + } +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/validateRef.js b/node_modules/mongoose/lib/helpers/populate/validateRef.js new file mode 100644 index 0000000..9dc2b6f --- /dev/null +++ b/node_modules/mongoose/lib/helpers/populate/validateRef.js @@ -0,0 +1,19 @@ +'use strict'; + +const MongooseError = require('../../error/mongooseError'); +const util = require('util'); + +module.exports = validateRef; + +function validateRef(ref, path) { + if (typeof ref === 'string') { + return; + } + + if (typeof ref === 'function') { + return; + } + + throw new MongooseError('Invalid ref at path "' + path + '". Got ' + + util.inspect(ref, { depth: 0 })); +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/printJestWarning.js b/node_modules/mongoose/lib/helpers/printJestWarning.js new file mode 100644 index 0000000..cc112e2 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/printJestWarning.js @@ -0,0 +1,17 @@ +'use strict'; + +const utils = require('../utils'); + +if (typeof jest !== 'undefined' && typeof window !== 'undefined') { + utils.warn('Mongoose: looks like you\'re trying to test a Mongoose app ' + + 'with Jest\'s default jsdom test environment. Please make sure you read ' + + 'Mongoose\'s docs on configuring Jest to test Node.js apps: ' + + 'http://mongoosejs.com/docs/jest.html'); +} + +if (typeof jest !== 'undefined' && process.nextTick.toString().indexOf('nextTick') === -1) { + utils.warn('Mongoose: looks like you\'re trying to test a Mongoose app ' + + 'with Jest\'s mock timers enabled. Please make sure you read ' + + 'Mongoose\'s docs on configuring Jest to test Node.js apps: ' + + 'http://mongoosejs.com/docs/jest.html'); +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/processConnectionOptions.js b/node_modules/mongoose/lib/helpers/processConnectionOptions.js new file mode 100644 index 0000000..214a009 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/processConnectionOptions.js @@ -0,0 +1,64 @@ +'use strict'; + +const clone = require('./clone'); +const MongooseError = require('../error/index'); + +function processConnectionOptions(uri, options) { + const opts = options ? options : {}; + const readPreference = opts.readPreference + ? opts.readPreference + : getUriReadPreference(uri); + + const resolvedOpts = (readPreference && readPreference !== 'primary') + ? resolveOptsConflicts(readPreference, opts) + : opts; + + return clone(resolvedOpts); +} + +function resolveOptsConflicts(pref, opts) { + // don't silently override user-provided indexing options + if (setsIndexOptions(opts) && setsSecondaryRead(pref)) { + throwReadPreferenceError(); + } + + // if user has not explicitly set any auto-indexing options, + // we can silently default them all to false + else { + return defaultIndexOptsToFalse(opts); + } +} + +function setsIndexOptions(opts) { + const configIdx = opts.config && opts.config.autoIndex; + const { autoCreate, autoIndex } = opts; + return !!(configIdx || autoCreate || autoIndex); +} + +function setsSecondaryRead(prefString) { + return !!(prefString === 'secondary' || prefString === 'secondaryPreferred'); +} + +function getUriReadPreference(connectionString) { + const exp = /(?:&|\?)readPreference=(\w+)(?:&|$)/; + const match = exp.exec(connectionString); + return match ? match[1] : null; +} + +function defaultIndexOptsToFalse(opts) { + opts.config = { autoIndex: false }; + opts.autoCreate = false; + opts.autoIndex = false; + return opts; +} + +function throwReadPreferenceError() { + throw new MongooseError( + 'MongoDB prohibits index creation on connections that read from ' + + 'non-primary replicas. Connections that set "readPreference" to "secondary" or ' + + '"secondaryPreferred" may not opt-in to the following connection options: ' + + 'autoCreate, autoIndex' + ); +} + +module.exports = processConnectionOptions; diff --git a/node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js b/node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js new file mode 100644 index 0000000..67dfb39 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js @@ -0,0 +1,18 @@ +'use strict'; + +/*! + * ignore + */ + +module.exports = function isDefiningProjection(val) { + if (val == null) { + // `undefined` or `null` become exclusive projections + return true; + } + if (typeof val === 'object') { + // Only cases where a value does **not** define whether the whole projection + // is inclusive or exclusive are `$meta` and `$slice`. + return !('$meta' in val) && !('$slice' in val); + } + return true; +}; diff --git a/node_modules/mongoose/lib/helpers/projection/isExclusive.js b/node_modules/mongoose/lib/helpers/projection/isExclusive.js new file mode 100644 index 0000000..abc1bce --- /dev/null +++ b/node_modules/mongoose/lib/helpers/projection/isExclusive.js @@ -0,0 +1,32 @@ +'use strict'; + +const isDefiningProjection = require('./isDefiningProjection'); + +/*! + * ignore + */ + +module.exports = function isExclusive(projection) { + if (projection == null) { + return null; + } + + const keys = Object.keys(projection); + let ki = keys.length; + let exclude = null; + + if (ki === 1 && keys[0] === '_id') { + exclude = !projection._id; + } else { + while (ki--) { + // Does this projection explicitly define inclusion/exclusion? + // Explicitly avoid `$meta` and `$slice` + if (keys[ki] !== '_id' && isDefiningProjection(projection[keys[ki]])) { + exclude = !projection[keys[ki]]; + break; + } + } + } + + return exclude; +}; diff --git a/node_modules/mongoose/lib/helpers/projection/isInclusive.js b/node_modules/mongoose/lib/helpers/projection/isInclusive.js new file mode 100644 index 0000000..098309f --- /dev/null +++ b/node_modules/mongoose/lib/helpers/projection/isInclusive.js @@ -0,0 +1,34 @@ +'use strict'; + +const isDefiningProjection = require('./isDefiningProjection'); + +/*! + * ignore + */ + +module.exports = function isInclusive(projection) { + if (projection == null) { + return false; + } + + const props = Object.keys(projection); + const numProps = props.length; + if (numProps === 0) { + return false; + } + + for (let i = 0; i < numProps; ++i) { + const prop = props[i]; + // Plus paths can't define the projection (see gh-7050) + if (prop.startsWith('+')) { + continue; + } + // If field is truthy (1, true, etc.) and not an object, then this + // projection must be inclusive. If object, assume its $meta, $slice, etc. + if (isDefiningProjection(projection[prop]) && !!projection[prop]) { + return true; + } + } + + return false; +}; diff --git a/node_modules/mongoose/lib/helpers/projection/isPathExcluded.js b/node_modules/mongoose/lib/helpers/projection/isPathExcluded.js new file mode 100644 index 0000000..fc2592c --- /dev/null +++ b/node_modules/mongoose/lib/helpers/projection/isPathExcluded.js @@ -0,0 +1,35 @@ +'use strict'; + +const isDefiningProjection = require('./isDefiningProjection'); + +/*! + * Determines if `path` is excluded by `projection` + * + * @param {Object} projection + * @param {string} path + * @return {Boolean} + */ + +module.exports = function isPathExcluded(projection, path) { + if (path === '_id') { + return projection._id === 0; + } + + const paths = Object.keys(projection); + let type = null; + + for (const _path of paths) { + if (isDefiningProjection(projection[_path])) { + type = projection[path] === 1 ? 'inclusive' : 'exclusive'; + break; + } + } + + if (type === 'inclusive') { + return projection[path] !== 1; + } + if (type === 'exclusive') { + return projection[path] === 0; + } + return false; +}; diff --git a/node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js b/node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js new file mode 100644 index 0000000..8a05fc9 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js @@ -0,0 +1,28 @@ +'use strict'; + +/*! + * ignore + */ + +module.exports = function isPathSelectedInclusive(fields, path) { + const chunks = path.split('.'); + let cur = ''; + let j; + let keys; + let numKeys; + for (let i = 0; i < chunks.length; ++i) { + cur += cur.length ? '.' : '' + chunks[i]; + if (fields[cur]) { + keys = Object.keys(fields); + numKeys = keys.length; + for (j = 0; j < numKeys; ++j) { + if (keys[i].indexOf(cur + '.') === 0 && keys[i].indexOf(path) !== 0) { + continue; + } + } + return true; + } + } + + return false; +}; diff --git a/node_modules/mongoose/lib/helpers/projection/parseProjection.js b/node_modules/mongoose/lib/helpers/projection/parseProjection.js new file mode 100644 index 0000000..d2a44b1 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/projection/parseProjection.js @@ -0,0 +1,33 @@ +'use strict'; + +/** + * Convert a string or array into a projection object, retaining all + * `-` and `+` paths. + */ + +module.exports = function parseProjection(v, retainMinusPaths) { + const type = typeof v; + + if (type === 'string') { + v = v.split(/\s+/); + } + if (!Array.isArray(v) && Object.prototype.toString.call(v) !== '[object Arguments]') { + return v; + } + + const len = v.length; + const ret = {}; + for (let i = 0; i < len; ++i) { + let field = v[i]; + if (!field) { + continue; + } + const include = '-' == field[0] ? 0 : 1; + if (!retainMinusPaths && include === 0) { + field = field.substring(1); + } + ret[field] = include; + } + + return ret; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/promiseOrCallback.js b/node_modules/mongoose/lib/helpers/promiseOrCallback.js new file mode 100644 index 0000000..69ba385 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/promiseOrCallback.js @@ -0,0 +1,46 @@ +'use strict'; + +const PromiseProvider = require('../promise_provider'); +const immediate = require('./immediate'); + +const emittedSymbol = Symbol('mongoose:emitted'); + +module.exports = function promiseOrCallback(callback, fn, ee, Promise) { + if (typeof callback === 'function') { + return fn(function(error) { + if (error != null) { + if (ee != null && ee.listeners != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) { + error[emittedSymbol] = true; + ee.emit('error', error); + } + try { + callback(error); + } catch (error) { + return immediate(() => { + throw error; + }); + } + return; + } + callback.apply(this, arguments); + }); + } + + Promise = Promise || PromiseProvider.get(); + + return new Promise((resolve, reject) => { + fn(function(error, res) { + if (error != null) { + if (ee != null && ee.listeners != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) { + error[emittedSymbol] = true; + ee.emit('error', error); + } + return reject(error); + } + if (arguments.length > 2) { + return resolve(Array.prototype.slice.call(arguments, 1)); + } + resolve(res); + }); + }); +}; diff --git a/node_modules/mongoose/lib/helpers/query/applyGlobalMaxTimeMS.js b/node_modules/mongoose/lib/helpers/query/applyGlobalMaxTimeMS.js new file mode 100644 index 0000000..cb49260 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/applyGlobalMaxTimeMS.js @@ -0,0 +1,15 @@ +'use strict'; + +const utils = require('../../utils'); + +module.exports = function applyGlobalMaxTimeMS(options, model) { + if (utils.hasUserDefinedProperty(options, 'maxTimeMS')) { + return; + } + + if (utils.hasUserDefinedProperty(model.db.options, 'maxTimeMS')) { + options.maxTimeMS = model.db.options.maxTimeMS; + } else if (utils.hasUserDefinedProperty(model.base.options, 'maxTimeMS')) { + options.maxTimeMS = model.base.options.maxTimeMS; + } +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/applyQueryMiddleware.js b/node_modules/mongoose/lib/helpers/query/applyQueryMiddleware.js new file mode 100644 index 0000000..99e096b --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/applyQueryMiddleware.js @@ -0,0 +1,78 @@ +'use strict'; + +/*! + * ignore + */ + +module.exports = applyQueryMiddleware; + +const validOps = require('./validOps'); + +/*! + * ignore + */ + +applyQueryMiddleware.middlewareFunctions = validOps.concat([ + 'validate' +]); + +/*! + * Apply query middleware + * + * @param {Query} query constructor + * @param {Model} model + */ + +function applyQueryMiddleware(Query, model) { + const kareemOptions = { + useErrorHandlers: true, + numCallbackParams: 1, + nullResultByDefault: true + }; + + const middleware = model.hooks.filter(hook => { + const contexts = _getContexts(hook); + if (hook.name === 'updateOne') { + return contexts.query == null || !!contexts.query; + } + if (hook.name === 'deleteOne') { + return !!contexts.query || Object.keys(contexts).length === 0; + } + if (hook.name === 'validate' || hook.name === 'remove') { + return !!contexts.query; + } + if (hook.query != null || hook.document != null) { + return !!hook.query; + } + return true; + }); + + // `update()` thunk has a different name because `_update` was already taken + Query.prototype._execUpdate = middleware.createWrapper('update', + Query.prototype._execUpdate, null, kareemOptions); + // `distinct()` thunk has a different name because `_distinct` was already taken + Query.prototype.__distinct = middleware.createWrapper('distinct', + Query.prototype.__distinct, null, kareemOptions); + + // `validate()` doesn't have a thunk because it doesn't execute a query. + Query.prototype.validate = middleware.createWrapper('validate', + Query.prototype.validate, null, kareemOptions); + + applyQueryMiddleware.middlewareFunctions. + filter(v => v !== 'update' && v !== 'distinct' && v !== 'validate'). + forEach(fn => { + Query.prototype[`_${fn}`] = middleware.createWrapper(fn, + Query.prototype[`_${fn}`], null, kareemOptions); + }); +} + +function _getContexts(hook) { + const ret = {}; + if (hook.hasOwnProperty('query')) { + ret.query = hook.query; + } + if (hook.hasOwnProperty('document')) { + ret.document = hook.document; + } + return ret; +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/castFilterPath.js b/node_modules/mongoose/lib/helpers/query/castFilterPath.js new file mode 100644 index 0000000..42b8460 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/castFilterPath.js @@ -0,0 +1,55 @@ +'use strict'; + +const isOperator = require('./isOperator'); + +module.exports = function castFilterPath(query, schematype, val) { + const ctx = query; + const any$conditionals = Object.keys(val).some(isOperator); + + if (!any$conditionals) { + return schematype.castForQueryWrapper({ + val: val, + context: ctx + }); + } + + const ks = Object.keys(val); + + let k = ks.length; + + while (k--) { + const $cond = ks[k]; + const nested = val[$cond]; + + if ($cond === '$not') { + if (nested && schematype && !schematype.caster) { + const _keys = Object.keys(nested); + if (_keys.length && isOperator(_keys[0])) { + for (const key of Object.keys(nested)) { + nested[key] = schematype.castForQueryWrapper({ + $conditional: key, + val: nested[key], + context: ctx + }); + } + } else { + val[$cond] = schematype.castForQueryWrapper({ + $conditional: $cond, + val: nested, + context: ctx + }); + } + continue; + } + // cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context); + } else { + val[$cond] = schematype.castForQueryWrapper({ + $conditional: $cond, + val: nested, + context: ctx + }); + } + } + + return val; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/castUpdate.js b/node_modules/mongoose/lib/helpers/query/castUpdate.js new file mode 100644 index 0000000..21b7f94 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/castUpdate.js @@ -0,0 +1,532 @@ +'use strict'; + +const CastError = require('../../error/cast'); +const MongooseError = require('../../error/mongooseError'); +const StrictModeError = require('../../error/strict'); +const ValidationError = require('../../error/validation'); +const castNumber = require('../../cast/number'); +const cast = require('../../cast'); +const getConstructorName = require('../getConstructorName'); +const getEmbeddedDiscriminatorPath = require('./getEmbeddedDiscriminatorPath'); +const handleImmutable = require('./handleImmutable'); +const moveImmutableProperties = require('../update/moveImmutableProperties'); +const schemaMixedSymbol = require('../../schema/symbols').schemaMixedSymbol; +const setDottedPath = require('../path/setDottedPath'); +const utils = require('../../utils'); + +/*! + * Casts an update op based on the given schema + * + * @param {Schema} schema + * @param {Object} obj + * @param {Object} options + * @param {Boolean} [options.overwrite] defaults to false + * @param {Boolean|String} [options.strict] defaults to true + * @param {Query} context passed to setters + * @return {Boolean} true iff the update is non-empty + */ +module.exports = function castUpdate(schema, obj, options, context, filter) { + if (obj == null) { + return undefined; + } + options = options || {}; + // Update pipeline + if (Array.isArray(obj)) { + const len = obj.length; + for (let i = 0; i < len; ++i) { + const ops = Object.keys(obj[i]); + for (const op of ops) { + obj[i][op] = castPipelineOperator(op, obj[i][op]); + } + } + return obj; + } + if (schema.options.strict === 'throw' && obj.hasOwnProperty(schema.options.discriminatorKey)) { + throw new StrictModeError(schema.options.discriminatorKey); + } else if (context._mongooseOptions != null && !context._mongooseOptions.overwriteDiscriminatorKey) { + delete obj[schema.options.discriminatorKey]; + } + if (options.upsert) { + moveImmutableProperties(schema, obj, context); + } + + const ops = Object.keys(obj); + let i = ops.length; + const ret = {}; + let val; + let hasDollarKey = false; + const overwrite = options.overwrite; + + filter = filter || {}; + while (i--) { + const op = ops[i]; + // if overwrite is set, don't do any of the special $set stuff + if (op[0] !== '$' && !overwrite) { + // fix up $set sugar + if (!ret.$set) { + if (obj.$set) { + ret.$set = obj.$set; + } else { + ret.$set = {}; + } + } + ret.$set[op] = obj[op]; + ops.splice(i, 1); + if (!~ops.indexOf('$set')) ops.push('$set'); + } else if (op === '$set') { + if (!ret.$set) { + ret[op] = obj[op]; + } + } else { + ret[op] = obj[op]; + } + } + // cast each value + i = ops.length; + while (i--) { + const op = ops[i]; + val = ret[op]; + hasDollarKey = hasDollarKey || op.startsWith('$'); + + if (val && + typeof val === 'object' && + !Buffer.isBuffer(val) && + (!overwrite || hasDollarKey)) { + walkUpdatePath(schema, val, op, options, context, filter); + } else if (overwrite && ret && typeof ret === 'object') { + walkUpdatePath(schema, ret, '$set', options, context, filter); + } else { + const msg = 'Invalid atomic update value for ' + op + '. ' + + 'Expected an object, received ' + typeof val; + throw new Error(msg); + } + + if (op.startsWith('$') && utils.isEmptyObject(val)) { + delete ret[op]; + } + } + + if (Object.keys(ret).length === 0 && + options.upsert && + Object.keys(filter).length > 0) { + // Trick the driver into allowing empty upserts to work around + // https://github.com/mongodb/node-mongodb-native/pull/2490 + return { $setOnInsert: filter }; + } + return ret; +}; + +/*! + * ignore + */ + +function castPipelineOperator(op, val) { + if (op === '$unset') { + if (!Array.isArray(val) || val.find(v => typeof v !== 'string')) { + throw new MongooseError('Invalid $unset in pipeline, must be ' + + 'an array of strings'); + } + return val; + } + if (op === '$project') { + if (val == null || typeof val !== 'object') { + throw new MongooseError('Invalid $project in pipeline, must be an object'); + } + return val; + } + if (op === '$addFields' || op === '$set') { + if (val == null || typeof val !== 'object') { + throw new MongooseError('Invalid ' + op + ' in pipeline, must be an object'); + } + return val; + } else if (op === '$replaceRoot' || op === '$replaceWith') { + if (val == null || typeof val !== 'object') { + throw new MongooseError('Invalid ' + op + ' in pipeline, must be an object'); + } + return val; + } + + throw new MongooseError('Invalid update pipeline operator: "' + op + '"'); +} + +/*! + * Walk each path of obj and cast its values + * according to its schema. + * + * @param {Schema} schema + * @param {Object} obj - part of a query + * @param {String} op - the atomic operator ($pull, $set, etc) + * @param {Object} options + * @param {Boolean|String} [options.strict] + * @param {Query} context + * @param {String} pref - path prefix (internal only) + * @return {Bool} true if this path has keys to update + * @api private + */ + +function walkUpdatePath(schema, obj, op, options, context, filter, pref) { + const strict = options.strict; + const prefix = pref ? pref + '.' : ''; + const keys = Object.keys(obj); + let i = keys.length; + let hasKeys = false; + let schematype; + let key; + let val; + + let aggregatedError = null; + + while (i--) { + key = keys[i]; + val = obj[key]; + + // `$pull` is special because we need to cast the RHS as a query, not as + // an update. + if (op === '$pull') { + schematype = schema._getSchema(prefix + key); + if (schematype != null && schematype.schema != null) { + obj[key] = cast(schematype.schema, obj[key], options, context); + hasKeys = true; + continue; + } + } + + if (getConstructorName(val) === 'Object') { + // watch for embedded doc schemas + schematype = schema._getSchema(prefix + key); + + if (schematype == null) { + const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, prefix + key, options); + if (_res.schematype != null) { + schematype = _res.schematype; + } + } + + if (op !== '$setOnInsert' && + handleImmutable(schematype, strict, obj, key, prefix + key, context)) { + continue; + } + + if (schematype && schematype.caster && op in castOps) { + // embedded doc schema + if ('$each' in val) { + hasKeys = true; + try { + obj[key] = { + $each: castUpdateVal(schematype, val.$each, op, key, context, prefix + key) + }; + } catch (error) { + aggregatedError = _handleCastError(error, context, key, aggregatedError); + } + + if (val.$slice != null) { + obj[key].$slice = val.$slice | 0; + } + + if (val.$sort) { + obj[key].$sort = val.$sort; + } + + if (val.$position != null) { + obj[key].$position = castNumber(val.$position); + } + } else { + if (schematype != null && schematype.$isSingleNested) { + const _strict = strict == null ? schematype.schema.options.strict : strict; + try { + obj[key] = schematype.castForQuery(val, context, { strict: _strict }); + } catch (error) { + aggregatedError = _handleCastError(error, context, key, aggregatedError); + } + } else { + try { + obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); + } catch (error) { + aggregatedError = _handleCastError(error, context, key, aggregatedError); + } + } + + if (obj[key] === void 0) { + delete obj[key]; + continue; + } + + hasKeys = true; + } + } else if ((op === '$currentDate') || (op in castOps && schematype)) { + // $currentDate can take an object + try { + obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); + } catch (error) { + aggregatedError = _handleCastError(error, context, key, aggregatedError); + } + + if (obj[key] === void 0) { + delete obj[key]; + continue; + } + + hasKeys = true; + } else { + const pathToCheck = (prefix + key); + const v = schema._getPathType(pathToCheck); + let _strict = strict; + if (v && v.schema && _strict == null) { + _strict = v.schema.options.strict; + } + + if (v.pathType === 'undefined') { + if (_strict === 'throw') { + throw new StrictModeError(pathToCheck); + } else if (_strict) { + delete obj[key]; + continue; + } + } + + // gh-2314 + // we should be able to set a schema-less field + // to an empty object literal + hasKeys |= walkUpdatePath(schema, val, op, options, context, filter, prefix + key) || + (utils.isObject(val) && Object.keys(val).length === 0); + } + } else { + const checkPath = (key === '$each' || key === '$or' || key === '$and' || key === '$in') ? + pref : prefix + key; + schematype = schema._getSchema(checkPath); + + // You can use `$setOnInsert` with immutable keys + if (op !== '$setOnInsert' && + handleImmutable(schematype, strict, obj, key, prefix + key, context)) { + continue; + } + + let pathDetails = schema._getPathType(checkPath); + + // If no schema type, check for embedded discriminators because the + // filter or update may imply an embedded discriminator type. See #8378 + if (schematype == null) { + const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, checkPath, options); + if (_res.schematype != null) { + schematype = _res.schematype; + pathDetails = _res.type; + } + } + + let isStrict = strict; + if (pathDetails && pathDetails.schema && strict == null) { + isStrict = pathDetails.schema.options.strict; + } + + const skip = isStrict && + !schematype && + !/real|nested/.test(pathDetails.pathType); + + if (skip) { + // Even if strict is `throw`, avoid throwing an error because of + // virtuals because of #6731 + if (isStrict === 'throw' && schema.virtuals[checkPath] == null) { + throw new StrictModeError(prefix + key); + } else { + delete obj[key]; + } + } else { + // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking + // improving this. + if (op === '$rename') { + hasKeys = true; + continue; + } + + try { + if (prefix.length === 0 || key.indexOf('.') === -1) { + obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); + } else { + // Setting a nested dotted path that's in the schema. We don't allow paths with '.' in + // a schema, so replace the dotted path with a nested object to avoid ending up with + // dotted properties in the updated object. See (gh-10200) + setDottedPath(obj, key, castUpdateVal(schematype, val, op, key, context, prefix + key)); + delete obj[key]; + } + } catch (error) { + aggregatedError = _handleCastError(error, context, key, aggregatedError); + } + + if (Array.isArray(obj[key]) && (op === '$addToSet' || op === '$push') && key !== '$each') { + if (schematype && schematype.caster && !schematype.caster.$isMongooseArray) { + obj[key] = { $each: obj[key] }; + } + } + + if (obj[key] === void 0) { + delete obj[key]; + continue; + } + + hasKeys = true; + } + } + } + + if (aggregatedError != null) { + throw aggregatedError; + } + + return hasKeys; +} + +/*! + * ignore + */ + +function _handleCastError(error, query, key, aggregatedError) { + if (typeof query !== 'object' || !query.options.multipleCastError) { + throw error; + } + aggregatedError = aggregatedError || new ValidationError(); + aggregatedError.addError(key, error); + return aggregatedError; +} + +/*! + * These operators should be cast to numbers instead + * of their path schema type. + */ + +const numberOps = { + $pop: 1, + $inc: 1 +}; + +/*! + * These ops require no casting because the RHS doesn't do anything. + */ + +const noCastOps = { + $unset: 1 +}; + +/*! + * These operators require casting docs + * to real Documents for Update operations. + */ + +const castOps = { + $push: 1, + $addToSet: 1, + $set: 1, + $setOnInsert: 1 +}; + +/*! + * ignore + */ + +const overwriteOps = { + $set: 1, + $setOnInsert: 1 +}; + +/*! + * Casts `val` according to `schema` and atomic `op`. + * + * @param {SchemaType} schema + * @param {Object} val + * @param {String} op - the atomic operator ($pull, $set, etc) + * @param {String} $conditional + * @param {Query} context + * @api private + */ + +function castUpdateVal(schema, val, op, $conditional, context, path) { + if (!schema) { + // non-existing schema path + if (op in numberOps) { + try { + return castNumber(val); + } catch (err) { + throw new CastError('number', val, path); + } + } + return val; + } + + const cond = schema.caster && op in castOps && + (utils.isObject(val) || Array.isArray(val)); + if (cond && !overwriteOps[op]) { + // Cast values for ops that add data to MongoDB. + // Ensures embedded documents get ObjectIds etc. + let schemaArrayDepth = 0; + let cur = schema; + while (cur.$isMongooseArray) { + ++schemaArrayDepth; + cur = cur.caster; + } + let arrayDepth = 0; + let _val = val; + while (Array.isArray(_val)) { + ++arrayDepth; + _val = _val[0]; + } + + const additionalNesting = schemaArrayDepth - arrayDepth; + while (arrayDepth < schemaArrayDepth) { + val = [val]; + ++arrayDepth; + } + + let tmp = schema.applySetters(Array.isArray(val) ? val : [val], context); + + for (let i = 0; i < additionalNesting; ++i) { + tmp = tmp[0]; + } + return tmp; + } + + if (op in noCastOps) { + return val; + } + if (op in numberOps) { + // Null and undefined not allowed for $pop, $inc + if (val == null) { + throw new CastError('number', val, schema.path); + } + if (op === '$inc') { + // Support `$inc` with long, int32, etc. (gh-4283) + return schema.castForQueryWrapper({ + val: val, + context: context + }); + } + try { + return castNumber(val); + } catch (error) { + throw new CastError('number', val, schema.path); + } + } + if (op === '$currentDate') { + if (typeof val === 'object') { + return { $type: val.$type }; + } + return Boolean(val); + } + + if (/^\$/.test($conditional)) { + return schema.castForQueryWrapper({ + $conditional: $conditional, + val: val, + context: context + }); + } + + if (overwriteOps[op]) { + return schema.castForQueryWrapper({ + val: val, + context: context, + $skipQueryCastForUpdate: val != null && schema.$isMongooseArray && schema.$fullPath != null && !schema.$fullPath.match(/\d+$/), + $applySetters: schema[schemaMixedSymbol] != null + }); + } + + return schema.castForQueryWrapper({ val: val, context: context }); +} diff --git a/node_modules/mongoose/lib/helpers/query/completeMany.js b/node_modules/mongoose/lib/helpers/query/completeMany.js new file mode 100644 index 0000000..b52da43 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/completeMany.js @@ -0,0 +1,51 @@ +'use strict'; + +const helpers = require('../../queryhelpers'); +const immediate = require('../immediate'); + +module.exports = completeMany; + +/*! + * Given a model and an array of docs, hydrates all the docs to be instances + * of the model. Used to initialize docs returned from the db from `find()` + * + * @param {Model} model + * @param {Array} docs + * @param {Object} fields the projection used, including `select` from schemas + * @param {Object} userProvidedFields the user-specified projection + * @param {Object} opts + * @param {Array} [opts.populated] + * @param {ClientSession} [opts.session] + * @param {Function} callback + */ + +function completeMany(model, docs, fields, userProvidedFields, opts, callback) { + const arr = []; + let count = docs.length; + const len = count; + let error = null; + + function init(_error) { + if (_error != null) { + error = error || _error; + } + if (error != null) { + --count || immediate(() => callback(error)); + return; + } + --count || immediate(() => callback(error, arr)); + } + + for (let i = 0; i < len; ++i) { + arr[i] = helpers.createModel(model, docs[i], fields, userProvidedFields); + try { + arr[i].$init(docs[i], opts, init); + } catch (error) { + init(error); + } + + if (opts.session != null) { + arr[i].$session(opts.session); + } + } +} diff --git a/node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js b/node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js new file mode 100644 index 0000000..2f3f39d --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js @@ -0,0 +1,84 @@ +'use strict'; + +const cleanPositionalOperators = require('../schema/cleanPositionalOperators'); +const get = require('../get'); +const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue'); +const updatedPathsByArrayFilter = require('../update/updatedPathsByArrayFilter'); + +/*! + * Like `schema.path()`, except with a document, because impossible to + * determine path type without knowing the embedded discriminator key. + */ + +module.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, path, options) { + const parts = path.split('.'); + let schematype = null; + let type = 'adhocOrUndefined'; + + filter = filter || {}; + update = update || {}; + const arrayFilters = options != null && Array.isArray(options.arrayFilters) ? + options.arrayFilters : []; + const updatedPathsByFilter = updatedPathsByArrayFilter(update); + + for (let i = 0; i < parts.length; ++i) { + const subpath = cleanPositionalOperators(parts.slice(0, i + 1).join('.')); + schematype = schema.path(subpath); + if (schematype == null) { + continue; + } + + type = schema.pathType(subpath); + if ((schematype.$isSingleNested || schematype.$isMongooseDocumentArrayElement) && + schematype.schema.discriminators != null) { + const key = get(schematype, 'schema.options.discriminatorKey'); + const discriminatorValuePath = subpath + '.' + key; + const discriminatorFilterPath = + discriminatorValuePath.replace(/\.\d+\./, '.'); + let discriminatorKey = null; + + if (discriminatorValuePath in filter) { + discriminatorKey = filter[discriminatorValuePath]; + } + if (discriminatorFilterPath in filter) { + discriminatorKey = filter[discriminatorFilterPath]; + } + + const wrapperPath = subpath.replace(/\.\d+$/, ''); + if (schematype.$isMongooseDocumentArrayElement && + get(filter[wrapperPath], '$elemMatch.' + key) != null) { + discriminatorKey = filter[wrapperPath].$elemMatch[key]; + } + + if (discriminatorValuePath in update) { + discriminatorKey = update[discriminatorValuePath]; + } + + for (const filterKey of Object.keys(updatedPathsByFilter)) { + const schemaKey = updatedPathsByFilter[filterKey] + '.' + key; + const arrayFilterKey = filterKey + '.' + key; + if (schemaKey === discriminatorFilterPath) { + const filter = arrayFilters.find(filter => filter.hasOwnProperty(arrayFilterKey)); + if (filter != null) { + discriminatorKey = filter[arrayFilterKey]; + } + } + } + + if (discriminatorKey == null) { + continue; + } + + const discriminatorSchema = getDiscriminatorByValue(schematype.caster.discriminators, discriminatorKey).schema; + + const rest = parts.slice(i + 1).join('.'); + schematype = discriminatorSchema.path(rest); + if (schematype != null) { + type = discriminatorSchema._getPathType(rest); + break; + } + } + } + + return { type: type, schematype: schematype }; +}; diff --git a/node_modules/mongoose/lib/helpers/query/handleImmutable.js b/node_modules/mongoose/lib/helpers/query/handleImmutable.js new file mode 100644 index 0000000..22adb3c --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/handleImmutable.js @@ -0,0 +1,28 @@ +'use strict'; + +const StrictModeError = require('../../error/strict'); + +module.exports = function handleImmutable(schematype, strict, obj, key, fullPath, ctx) { + if (schematype == null || !schematype.options || !schematype.options.immutable) { + return false; + } + let immutable = schematype.options.immutable; + + if (typeof immutable === 'function') { + immutable = immutable.call(ctx, ctx); + } + if (!immutable) { + return false; + } + + if (strict === false) { + return false; + } + if (strict === 'throw') { + throw new StrictModeError(null, + `Field ${fullPath} is immutable and strict = 'throw'`); + } + + delete obj[key]; + return true; +}; diff --git a/node_modules/mongoose/lib/helpers/query/hasDollarKeys.js b/node_modules/mongoose/lib/helpers/query/hasDollarKeys.js new file mode 100644 index 0000000..09c40d7 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/hasDollarKeys.js @@ -0,0 +1,19 @@ +'use strict'; + +/*! + * ignore + */ + +module.exports = function(obj) { + if (obj == null || typeof obj !== 'object') { + return false; + } + const keys = Object.keys(obj); + const len = keys.length; + for (let i = 0; i < len; ++i) { + if (keys[i].startsWith('$')) { + return true; + } + } + return false; +}; diff --git a/node_modules/mongoose/lib/helpers/query/isOperator.js b/node_modules/mongoose/lib/helpers/query/isOperator.js new file mode 100644 index 0000000..3b98139 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/isOperator.js @@ -0,0 +1,11 @@ +'use strict'; + +const specialKeys = new Set([ + '$ref', + '$id', + '$db' +]); + +module.exports = function isOperator(path) { + return path.startsWith('$') && !specialKeys.has(path); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/sanitizeFilter.js b/node_modules/mongoose/lib/helpers/query/sanitizeFilter.js new file mode 100644 index 0000000..4177a0c --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/sanitizeFilter.js @@ -0,0 +1,38 @@ +'use strict'; + +const hasDollarKeys = require('./hasDollarKeys'); +const { trustedSymbol } = require('./trusted'); + +module.exports = function sanitizeFilter(filter) { + if (filter == null || typeof filter !== 'object') { + return filter; + } + if (Array.isArray(filter)) { + for (const subfilter of filter) { + sanitizeFilter(subfilter); + } + return filter; + } + + const filterKeys = Object.keys(filter); + for (const key of filterKeys) { + const value = filter[key]; + if (value != null && value[trustedSymbol]) { + continue; + } + if (key === '$and' || key === '$or') { + sanitizeFilter(value); + continue; + } + + if (hasDollarKeys(value)) { + const keys = Object.keys(value); + if (keys.length === 1 && keys[0] === '$eq') { + continue; + } + filter[key] = { $eq: filter[key] }; + } + } + + return filter; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/sanitizeProjection.js b/node_modules/mongoose/lib/helpers/query/sanitizeProjection.js new file mode 100644 index 0000000..dcb61fb --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/sanitizeProjection.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function sanitizeProjection(projection) { + if (projection == null) { + return; + } + + const keys = Object.keys(projection); + for (let i = 0; i < keys.length; ++i) { + if (typeof projection[keys[i]] === 'string') { + projection[keys[i]] = 1; + } + } +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js b/node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js new file mode 100644 index 0000000..92f1d87 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js @@ -0,0 +1,49 @@ +'use strict'; + +const isExclusive = require('../projection/isExclusive'); +const isInclusive = require('../projection/isInclusive'); + +/*! + * ignore + */ + +module.exports = function selectPopulatedFields(fields, userProvidedFields, populateOptions) { + if (populateOptions == null) { + return; + } + + const paths = Object.keys(populateOptions); + userProvidedFields = userProvidedFields || {}; + if (isInclusive(fields)) { + for (const path of paths) { + if (!isPathInFields(userProvidedFields, path)) { + fields[path] = 1; + } else if (userProvidedFields[path] === 0) { + delete fields[path]; + } + } + } else if (isExclusive(fields)) { + for (const path of paths) { + if (userProvidedFields[path] == null) { + delete fields[path]; + } + } + } +}; + +/*! + * ignore + */ + +function isPathInFields(userProvidedFields, path) { + const pieces = path.split('.'); + const len = pieces.length; + let cur = pieces[0]; + for (let i = 1; i < len; ++i) { + if (userProvidedFields[cur] != null || userProvidedFields[cur + '.$'] != null) { + return true; + } + cur += '.' + pieces[i]; + } + return userProvidedFields[cur] != null || userProvidedFields[cur + '.$'] != null; +} diff --git a/node_modules/mongoose/lib/helpers/query/trusted.js b/node_modules/mongoose/lib/helpers/query/trusted.js new file mode 100644 index 0000000..98c6054 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/trusted.js @@ -0,0 +1,13 @@ +'use strict'; + +const trustedSymbol = Symbol('mongoose#trustedSymbol'); + +exports.trustedSymbol = trustedSymbol; + +exports.trusted = function trusted(obj) { + if (obj == null || typeof obj !== 'object') { + return obj; + } + obj[trustedSymbol] = true; + return obj; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/validOps.js b/node_modules/mongoose/lib/helpers/query/validOps.js new file mode 100644 index 0000000..c0ac397 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/validOps.js @@ -0,0 +1,24 @@ +'use strict'; + +module.exports = Object.freeze([ + // Read + 'count', + 'countDocuments', + 'distinct', + 'estimatedDocumentCount', + 'find', + 'findOne', + // Update + 'findOneAndReplace', + 'findOneAndUpdate', + 'replaceOne', + 'update', + 'updateMany', + 'updateOne', + // Delete + 'deleteMany', + 'deleteOne', + 'findOneAndDelete', + 'findOneAndRemove', + 'remove' +]); \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/wrapThunk.js b/node_modules/mongoose/lib/helpers/query/wrapThunk.js new file mode 100644 index 0000000..daa4681 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/wrapThunk.js @@ -0,0 +1,29 @@ +'use strict'; + +const MongooseError = require('../../error/mongooseError'); + +/*! + * A query thunk is the function responsible for sending the query to MongoDB, + * like `Query#_findOne()` or `Query#_execUpdate()`. The `Query#exec()` function + * calls a thunk. The term "thunk" here is the traditional Node.js definition: + * a function that takes exactly 1 parameter, a callback. + * + * This function defines common behavior for all query thunks. + */ + +module.exports = function wrapThunk(fn) { + return function _wrappedThunk(cb) { + if (this._executionStack != null) { + let str = this.toString(); + if (str.length > 60) { + str = str.slice(0, 60) + '...'; + } + const err = new MongooseError('Query was already executed: ' + str); + err.originalStack = this._executionStack.stack; + return cb(err); + } + this._executionStack = new Error(); + + fn.call(this, cb); + }; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/addAutoId.js b/node_modules/mongoose/lib/helpers/schema/addAutoId.js new file mode 100644 index 0000000..11a1f23 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schema/addAutoId.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function addAutoId(schema) { + const _obj = { _id: { auto: true } }; + _obj._id[schema.options.typeKey] = 'ObjectId'; + schema.add(_obj); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/applyPlugins.js b/node_modules/mongoose/lib/helpers/schema/applyPlugins.js new file mode 100644 index 0000000..f1daf40 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schema/applyPlugins.js @@ -0,0 +1,44 @@ +'use strict'; + +module.exports = function applyPlugins(schema, plugins, options, cacheKey) { + if (schema[cacheKey]) { + return; + } + schema[cacheKey] = true; + + if (!options || !options.skipTopLevel) { + for (const plugin of plugins) { + schema.plugin(plugin[0], plugin[1]); + } + } + + options = Object.assign({}, options); + delete options.skipTopLevel; + + if (options.applyPluginsToChildSchemas !== false) { + for (const path of Object.keys(schema.paths)) { + const type = schema.paths[path]; + if (type.schema != null) { + applyPlugins(type.schema, plugins, options, cacheKey); + + // Recompile schema because plugins may have changed it, see gh-7572 + type.caster.prototype.$__setSchema(type.schema); + } + } + } + + const discriminators = schema.discriminators; + if (discriminators == null) { + return; + } + + const applyPluginsToDiscriminators = options.applyPluginsToDiscriminators; + + const keys = Object.keys(discriminators); + for (const discriminatorKey of keys) { + const discriminatorSchema = discriminators[discriminatorKey]; + + applyPlugins(discriminatorSchema, plugins, + { skipTopLevel: !applyPluginsToDiscriminators }, cacheKey); + } +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js b/node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js new file mode 100644 index 0000000..4095bd9 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js @@ -0,0 +1,30 @@ +'use strict'; + +const get = require('../get'); + +module.exports = function applyWriteConcern(schema, options) { + const writeConcern = get(schema, 'options.writeConcern', {}); + if (Object.keys(writeConcern).length != 0) { + options.writeConcern = {}; + if (!('w' in options) && writeConcern.w != null) { + options.writeConcern.w = writeConcern.w; + } + if (!('j' in options) && writeConcern.j != null) { + options.writeConcern.j = writeConcern.j; + } + if (!('wtimeout' in options) && writeConcern.wtimeout != null) { + options.writeConcern.wtimeout = writeConcern.wtimeout; + } + } + else { + if (!('w' in options) && writeConcern.w != null) { + options.w = writeConcern.w; + } + if (!('j' in options) && writeConcern.j != null) { + options.j = writeConcern.j; + } + if (!('wtimeout' in options) && writeConcern.wtimeout != null) { + options.wtimeout = writeConcern.wtimeout; + } + } +}; diff --git a/node_modules/mongoose/lib/helpers/schema/cleanPositionalOperators.js b/node_modules/mongoose/lib/helpers/schema/cleanPositionalOperators.js new file mode 100644 index 0000000..905bb78 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schema/cleanPositionalOperators.js @@ -0,0 +1,12 @@ +'use strict'; + +/** + * For consistency's sake, we replace positional operator `$` and array filters + * `$[]` and `$[foo]` with `0` when looking up schema paths. + */ + +module.exports = function cleanPositionalOperators(path) { + return path. + replace(/\.\$(\[[^\]]*\])?(?=\.)/g, '.0'). + replace(/\.\$(\[[^\]]*\])?$/g, '.0'); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/getIndexes.js b/node_modules/mongoose/lib/helpers/schema/getIndexes.js new file mode 100644 index 0000000..be907db --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schema/getIndexes.js @@ -0,0 +1,155 @@ +'use strict'; + +const get = require('../get'); +const helperIsObject = require('../isObject'); + +/*! + * Gather all indexes defined in the schema, including single nested, + * document arrays, and embedded discriminators. + */ + +module.exports = function getIndexes(schema) { + let indexes = []; + const schemaStack = new WeakMap(); + const indexTypes = schema.constructor.indexTypes; + const indexByName = new Map(); + + collectIndexes(schema); + return indexes; + + function collectIndexes(schema, prefix, baseSchema) { + // Ignore infinitely nested schemas, if we've already seen this schema + // along this path there must be a cycle + if (schemaStack.has(schema)) { + return; + } + schemaStack.set(schema, true); + + prefix = prefix || ''; + const keys = Object.keys(schema.paths); + + for (const key of keys) { + const path = schema.paths[key]; + if (baseSchema != null && baseSchema.paths[key]) { + // If looking at an embedded discriminator schema, don't look at paths + // that the + continue; + } + + if (path.$isMongooseDocumentArray || path.$isSingleNested) { + if (get(path, 'options.excludeIndexes') !== true && + get(path, 'schemaOptions.excludeIndexes') !== true && + get(path, 'schema.options.excludeIndexes') !== true) { + collectIndexes(path.schema, prefix + key + '.'); + } + + if (path.schema.discriminators != null) { + const discriminators = path.schema.discriminators; + const discriminatorKeys = Object.keys(discriminators); + for (const discriminatorKey of discriminatorKeys) { + collectIndexes(discriminators[discriminatorKey], + prefix + key + '.', path.schema); + } + } + + // Retained to minimize risk of backwards breaking changes due to + // gh-6113 + if (path.$isMongooseDocumentArray) { + continue; + } + } + + const index = path._index || (path.caster && path.caster._index); + + if (index !== false && index !== null && index !== undefined) { + const field = {}; + const isObject = helperIsObject(index); + const options = isObject ? index : {}; + const type = typeof index === 'string' ? index : + isObject ? index.type : + false; + + if (type && indexTypes.indexOf(type) !== -1) { + field[prefix + key] = type; + } else if (options.text) { + field[prefix + key] = 'text'; + delete options.text; + } else { + const isDescendingIndex = Number(index) === -1; + field[prefix + key] = isDescendingIndex ? -1 : 1; + } + + delete options.type; + if (!('background' in options)) { + options.background = true; + } + if (schema.options.autoIndex != null) { + options._autoIndex = schema.options.autoIndex; + } + + const indexName = options && options.name; + if (typeof indexName === 'string') { + if (indexByName.has(indexName)) { + Object.assign(indexByName.get(indexName), field); + } else { + indexes.push([field, options]); + indexByName.set(indexName, field); + } + } else { + indexes.push([field, options]); + indexByName.set(indexName, field); + } + } + } + + schemaStack.delete(schema); + + if (prefix) { + fixSubIndexPaths(schema, prefix); + } else { + schema._indexes.forEach(function(index) { + if (!('background' in index[1])) { + index[1].background = true; + } + }); + indexes = indexes.concat(schema._indexes); + } + } + + /*! + * Checks for indexes added to subdocs using Schema.index(). + * These indexes need their paths prefixed properly. + * + * schema._indexes = [ [indexObj, options], [indexObj, options] ..] + */ + + function fixSubIndexPaths(schema, prefix) { + const subindexes = schema._indexes; + const len = subindexes.length; + for (let i = 0; i < len; ++i) { + const indexObj = subindexes[i][0]; + const indexOptions = subindexes[i][1]; + const keys = Object.keys(indexObj); + const klen = keys.length; + const newindex = {}; + + // use forward iteration, order matters + for (let j = 0; j < klen; ++j) { + const key = keys[j]; + newindex[prefix + key] = indexObj[key]; + } + + const newIndexOptions = Object.assign({}, indexOptions); + if (indexOptions != null && indexOptions.partialFilterExpression != null) { + newIndexOptions.partialFilterExpression = {}; + const partialFilterExpression = indexOptions.partialFilterExpression; + for (const key of Object.keys(partialFilterExpression)) { + newIndexOptions.partialFilterExpression[prefix + key] = + partialFilterExpression[key]; + } + } + + indexes.push([newindex, newIndexOptions]); + } + } +}; diff --git a/node_modules/mongoose/lib/helpers/schema/getKeysInSchemaOrder.js b/node_modules/mongoose/lib/helpers/schema/getKeysInSchemaOrder.js new file mode 100644 index 0000000..f84a88f --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schema/getKeysInSchemaOrder.js @@ -0,0 +1,28 @@ +'use strict'; + +const get = require('../get'); + +module.exports = function getKeysInSchemaOrder(schema, val, path) { + const schemaKeys = path != null ? Object.keys(get(schema.tree, path, {})) : Object.keys(schema.tree); + const valKeys = new Set(Object.keys(val)); + + let keys; + if (valKeys.size > 1) { + keys = new Set(); + for (const key of schemaKeys) { + if (valKeys.has(key)) { + keys.add(key); + } + } + for (const key of valKeys) { + if (!keys.has(key)) { + keys.add(key); + } + } + keys = Array.from(keys); + } else { + keys = Array.from(valKeys); + } + + return keys; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/getPath.js b/node_modules/mongoose/lib/helpers/schema/getPath.js new file mode 100644 index 0000000..ccbc67c --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schema/getPath.js @@ -0,0 +1,35 @@ +'use strict'; + +/*! + * Behaves like `Schema#path()`, except for it also digs into arrays without + * needing to put `.0.`, so `getPath(schema, 'docArr.elProp')` works. + */ + +module.exports = function getPath(schema, path) { + let schematype = schema.path(path); + if (schematype != null) { + return schematype; + } + + const pieces = path.split('.'); + let cur = ''; + let isArray = false; + + for (const piece of pieces) { + if (/^\d+$/.test(piece) && isArray) { + continue; + } + cur = cur.length === 0 ? piece : cur + '.' + piece; + + schematype = schema.path(cur); + if (schematype != null && schematype.schema) { + schema = schematype.schema; + cur = ''; + if (schematype.$isMongooseDocumentArray) { + isArray = true; + } + } + } + + return schematype; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/handleIdOption.js b/node_modules/mongoose/lib/helpers/schema/handleIdOption.js new file mode 100644 index 0000000..569bf9f --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schema/handleIdOption.js @@ -0,0 +1,20 @@ +'use strict'; + +const addAutoId = require('./addAutoId'); + +module.exports = function handleIdOption(schema, options) { + if (options == null || options._id == null) { + return schema; + } + + schema = schema.clone(); + if (!options._id) { + schema.remove('_id'); + schema.options._id = false; + } else if (!schema.paths['_id']) { + addAutoId(schema); + schema.options._id = true; + } + + return schema; +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js b/node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js new file mode 100644 index 0000000..1551b7c --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js @@ -0,0 +1,24 @@ +'use strict'; + +module.exports = handleTimestampOption; + +/*! + * ignore + */ + +function handleTimestampOption(arg, prop) { + if (arg == null) { + return null; + } + + if (typeof arg === 'boolean') { + return prop; + } + if (typeof arg[prop] === 'boolean') { + return arg[prop] ? prop : null; + } + if (!(prop in arg)) { + return prop; + } + return arg[prop]; +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/idGetter.js b/node_modules/mongoose/lib/helpers/schema/idGetter.js new file mode 100644 index 0000000..5a07417 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schema/idGetter.js @@ -0,0 +1,31 @@ +'use strict'; + +/*! + * ignore + */ + +module.exports = function addIdGetter(schema) { + // ensure the documents receive an id getter unless disabled + const autoIdGetter = !schema.paths['id'] && + schema.paths['_id'] && + schema.options.id; + if (!autoIdGetter) { + return schema; + } + + schema.virtual('id').get(idGetter); + + return schema; +}; + +/*! + * Returns this documents _id cast to a string. + */ + +function idGetter() { + if (this._id != null) { + return String(this._id); + } + + return null; +} diff --git a/node_modules/mongoose/lib/helpers/schema/merge.js b/node_modules/mongoose/lib/helpers/schema/merge.js new file mode 100644 index 0000000..edc5175 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schema/merge.js @@ -0,0 +1,27 @@ +'use strict'; + +module.exports = function merge(s1, s2, skipConflictingPaths) { + const paths = Object.keys(s2.tree); + const pathsToAdd = {}; + for (const key of paths) { + if (skipConflictingPaths && (s1.paths[key] || s1.nested[key] || s1.singleNestedPaths[key])) { + continue; + } + pathsToAdd[key] = s2.tree[key]; + } + s1.add(pathsToAdd); + + s1.callQueue = s1.callQueue.concat(s2.callQueue); + s1.method(s2.methods); + s1.static(s2.statics); + + for (const query in s2.query) { + s1.query[query] = s2.query[query]; + } + + for (const virtual in s2.virtuals) { + s1.virtuals[virtual] = s2.virtuals[virtual].clone(); + } + + s1.s.hooks.merge(s2.s.hooks, false); +}; diff --git a/node_modules/mongoose/lib/helpers/schematype/handleImmutable.js b/node_modules/mongoose/lib/helpers/schematype/handleImmutable.js new file mode 100644 index 0000000..a9a0b7f --- /dev/null +++ b/node_modules/mongoose/lib/helpers/schematype/handleImmutable.js @@ -0,0 +1,47 @@ +'use strict'; + +const StrictModeError = require('../../error/strict'); + +/*! + * ignore + */ + +module.exports = function(schematype) { + if (schematype.$immutable) { + schematype.$immutableSetter = createImmutableSetter(schematype.path, + schematype.options.immutable); + schematype.set(schematype.$immutableSetter); + } else if (schematype.$immutableSetter) { + schematype.setters = schematype.setters. + filter(fn => fn !== schematype.$immutableSetter); + delete schematype.$immutableSetter; + } +}; + +function createImmutableSetter(path, immutable) { + return function immutableSetter(v) { + if (this == null || this.$__ == null) { + return v; + } + if (this.isNew) { + return v; + } + + const _immutable = typeof immutable === 'function' ? + immutable.call(this, this) : + immutable; + if (!_immutable) { + return v; + } + + const _value = this.$__.priorDoc != null ? + this.$__.priorDoc.$__getValue(path) : + this.$__getValue(path); + if (this.$__.strictMode === 'throw' && v !== _value) { + throw new StrictModeError(path, 'Path `' + path + '` is immutable ' + + 'and strict mode is set to throw.', true); + } + + return _value; + }; +} diff --git a/node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js b/node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js new file mode 100644 index 0000000..03cc4e8 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js @@ -0,0 +1,108 @@ +'use strict'; +const modifiedPaths = require('./common').modifiedPaths; +const get = require('./get'); + +/** + * Applies defaults to update and findOneAndUpdate operations. + * + * @param {Object} filter + * @param {Schema} schema + * @param {Object} castedDoc + * @param {Object} options + * @method setDefaultsOnInsert + * @api private + */ + +module.exports = function(filter, schema, castedDoc, options) { + options = options || {}; + + const shouldSetDefaultsOnInsert = + options.setDefaultsOnInsert != null ? + options.setDefaultsOnInsert : + schema.base.options.setDefaultsOnInsert; + + if (!options.upsert || shouldSetDefaultsOnInsert === false) { + return castedDoc; + } + + const keys = Object.keys(castedDoc || {}); + const updatedKeys = {}; + const updatedValues = {}; + const numKeys = keys.length; + const modified = {}; + + let hasDollarUpdate = false; + + for (let i = 0; i < numKeys; ++i) { + if (keys[i].startsWith('$')) { + modifiedPaths(castedDoc[keys[i]], '', modified); + hasDollarUpdate = true; + } + } + + if (!hasDollarUpdate) { + modifiedPaths(castedDoc, '', modified); + } + + const paths = Object.keys(filter); + const numPaths = paths.length; + for (let i = 0; i < numPaths; ++i) { + const path = paths[i]; + const condition = filter[path]; + if (condition && typeof condition === 'object') { + const conditionKeys = Object.keys(condition); + const numConditionKeys = conditionKeys.length; + let hasDollarKey = false; + for (let j = 0; j < numConditionKeys; ++j) { + if (conditionKeys[j].startsWith('$')) { + hasDollarKey = true; + break; + } + } + if (hasDollarKey) { + continue; + } + } + updatedKeys[path] = true; + modified[path] = true; + } + + if (options && options.overwrite && !hasDollarUpdate) { + // Defaults will be set later, since we're overwriting we'll cast + // the whole update to a document + return castedDoc; + } + + schema.eachPath(function(path, schemaType) { + // Skip single nested paths if underneath a map + if (schemaType.path === '_id' && schemaType.options.auto) { + return; + } + const def = schemaType.getDefault(null, true); + if (!isModified(modified, path) && typeof def !== 'undefined') { + castedDoc = castedDoc || {}; + castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; + if (get(castedDoc, path) == null) { + castedDoc.$setOnInsert[path] = def; + } + updatedValues[path] = def; + } + }); + + return castedDoc; +}; + +function isModified(modified, path) { + if (modified[path]) { + return true; + } + const sp = path.split('.'); + let cur = sp[0]; + for (let i = 1; i < sp.length; ++i) { + if (modified[cur]) { + return true; + } + cur += '.' + sp[i]; + } + return false; +} diff --git a/node_modules/mongoose/lib/helpers/specialProperties.js b/node_modules/mongoose/lib/helpers/specialProperties.js new file mode 100644 index 0000000..1e1aca5 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/specialProperties.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = new Set(['__proto__', 'constructor', 'prototype']); \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/symbols.js b/node_modules/mongoose/lib/helpers/symbols.js new file mode 100644 index 0000000..7e323e2 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/symbols.js @@ -0,0 +1,20 @@ +'use strict'; + +exports.arrayAtomicsBackupSymbol = Symbol('mongoose#Array#atomicsBackup'); +exports.arrayAtomicsSymbol = Symbol('mongoose#Array#_atomics'); +exports.arrayParentSymbol = Symbol('mongoose#Array#_parent'); +exports.arrayPathSymbol = Symbol('mongoose#Array#_path'); +exports.arraySchemaSymbol = Symbol('mongoose#Array#_schema'); +exports.documentArrayParent = Symbol('mongoose:documentArrayParent'); +exports.documentIsSelected = Symbol('mongoose#Document#isSelected'); +exports.documentIsModified = Symbol('mongoose#Document#isModified'); +exports.documentModifiedPaths = Symbol('mongoose#Document#modifiedPaths'); +exports.documentSchemaSymbol = Symbol('mongoose#Document#schema'); +exports.getSymbol = Symbol('mongoose#Document#get'); +exports.modelSymbol = Symbol('mongoose#Model'); +exports.objectIdSymbol = Symbol('mongoose#ObjectId'); +exports.populateModelSymbol = Symbol('mongoose.PopulateOptions#Model'); +exports.schemaTypeSymbol = Symbol('mongoose#schemaType'); +exports.sessionNewDocuments = Symbol('mongoose:ClientSession#newDocuments'); +exports.scopeSymbol = Symbol('mongoose#Document#scope'); +exports.validatorErrorSymbol = Symbol('mongoose:validatorError'); \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/timers.js b/node_modules/mongoose/lib/helpers/timers.js new file mode 100644 index 0000000..7bd09c7 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/timers.js @@ -0,0 +1,3 @@ +'use strict'; + +exports.setTimeout = setTimeout; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/timestamps/setupTimestamps.js b/node_modules/mongoose/lib/helpers/timestamps/setupTimestamps.js new file mode 100644 index 0000000..8b39842 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/timestamps/setupTimestamps.js @@ -0,0 +1,107 @@ +'use strict'; + +const applyTimestampsToChildren = require('../update/applyTimestampsToChildren'); +const applyTimestampsToUpdate = require('../update/applyTimestampsToUpdate'); +const get = require('../get'); +const handleTimestampOption = require('../schema/handleTimestampOption'); +const symbols = require('../../schema/symbols'); + +module.exports = function setupTimestamps(schema, timestamps) { + const childHasTimestamp = schema.childSchemas.find(withTimestamp); + function withTimestamp(s) { + const ts = s.schema.options.timestamps; + return !!ts; + } + + if (!timestamps && !childHasTimestamp) { + return; + } + + const createdAt = handleTimestampOption(timestamps, 'createdAt'); + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); + const currentTime = timestamps != null && timestamps.hasOwnProperty('currentTime') ? + timestamps.currentTime : + null; + const schemaAdditions = {}; + + schema.$timestamps = { createdAt: createdAt, updatedAt: updatedAt }; + + if (updatedAt && !schema.paths[updatedAt]) { + schemaAdditions[updatedAt] = Date; + } + + if (createdAt && !schema.paths[createdAt]) { + schemaAdditions[createdAt] = { [schema.options.typeKey || 'type']: Date, immutable: true }; + } + schema.add(schemaAdditions); + + schema.pre('save', function(next) { + const timestampOption = get(this, '$__.saveOptions.timestamps'); + if (timestampOption === false) { + return next(); + } + + const skipUpdatedAt = timestampOption != null && timestampOption.updatedAt === false; + const skipCreatedAt = timestampOption != null && timestampOption.createdAt === false; + + const defaultTimestamp = currentTime != null ? + currentTime() : + (this.ownerDocument ? this.ownerDocument() : this).constructor.base.now(); + const auto_id = this._id && this._id.auto; + + if (!skipCreatedAt && createdAt && !this.$__getValue(createdAt) && this.$__isSelected(createdAt)) { + this.$set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp); + } + + if (!skipUpdatedAt && updatedAt && (this.isNew || this.$isModified())) { + let ts = defaultTimestamp; + if (this.isNew) { + if (createdAt != null) { + ts = this.$__getValue(createdAt); + } else if (auto_id) { + ts = this._id.getTimestamp(); + } + } + this.$set(updatedAt, ts); + } + + next(); + }); + + schema.methods.initializeTimestamps = function() { + const ts = currentTime != null ? + currentTime() : + this.constructor.base.now(); + if (createdAt && !this.get(createdAt)) { + this.$set(createdAt, ts); + } + if (updatedAt && !this.get(updatedAt)) { + this.$set(updatedAt, ts); + } + return this; + }; + + _setTimestampsOnUpdate[symbols.builtInMiddleware] = true; + + const opts = { query: true, model: false }; + schema.pre('findOneAndReplace', opts, _setTimestampsOnUpdate); + schema.pre('findOneAndUpdate', opts, _setTimestampsOnUpdate); + schema.pre('replaceOne', opts, _setTimestampsOnUpdate); + schema.pre('update', opts, _setTimestampsOnUpdate); + schema.pre('updateOne', opts, _setTimestampsOnUpdate); + schema.pre('updateMany', opts, _setTimestampsOnUpdate); + + function _setTimestampsOnUpdate(next) { + const now = currentTime != null ? + currentTime() : + this.model.base.now(); + // Replacing with null update should still trigger timestamps + if (this.op === 'findOneAndReplace' && this.getUpdate() == null) { + this.setUpdate({}); + } + applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(), + this.options, this.schema); + applyTimestampsToChildren(now, this.getUpdate(), this.model.schema); + next(); + } +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/topology/allServersUnknown.js b/node_modules/mongoose/lib/helpers/topology/allServersUnknown.js new file mode 100644 index 0000000..33d23ab --- /dev/null +++ b/node_modules/mongoose/lib/helpers/topology/allServersUnknown.js @@ -0,0 +1,12 @@ +'use strict'; + +const getConstructorName = require('../getConstructorName'); + +module.exports = function allServersUnknown(topologyDescription) { + if (getConstructorName(topologyDescription) !== 'TopologyDescription') { + return false; + } + + const servers = Array.from(topologyDescription.servers.values()); + return servers.length > 0 && servers.every(server => server.type === 'Unknown'); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/topology/isAtlas.js b/node_modules/mongoose/lib/helpers/topology/isAtlas.js new file mode 100644 index 0000000..f0638d5 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/topology/isAtlas.js @@ -0,0 +1,13 @@ +'use strict'; + +const getConstructorName = require('../getConstructorName'); + +module.exports = function isAtlas(topologyDescription) { + if (getConstructorName(topologyDescription) !== 'TopologyDescription') { + return false; + } + + const hostnames = Array.from(topologyDescription.servers.keys()); + return hostnames.length > 0 && + hostnames.every(host => host.endsWith('.mongodb.net:27017')); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/topology/isSSLError.js b/node_modules/mongoose/lib/helpers/topology/isSSLError.js new file mode 100644 index 0000000..d910fc8 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/topology/isSSLError.js @@ -0,0 +1,16 @@ +'use strict'; + +const getConstructorName = require('../getConstructorName'); + +const nonSSLMessage = 'Client network socket disconnected before secure TLS ' + + 'connection was established'; + +module.exports = function isSSLError(topologyDescription) { + if (getConstructorName(topologyDescription) !== 'TopologyDescription') { + return false; + } + + const descriptions = Array.from(topologyDescription.servers.values()); + return descriptions.length > 0 && + descriptions.every(descr => descr.error && descr.error.message.indexOf(nonSSLMessage) !== -1); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js b/node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js new file mode 100644 index 0000000..6186c3d --- /dev/null +++ b/node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js @@ -0,0 +1,185 @@ +'use strict'; + +const cleanPositionalOperators = require('../schema/cleanPositionalOperators'); +const handleTimestampOption = require('../schema/handleTimestampOption'); + +module.exports = applyTimestampsToChildren; + +/*! + * ignore + */ + +function applyTimestampsToChildren(now, update, schema) { + if (update == null) { + return; + } + + const keys = Object.keys(update); + const hasDollarKey = keys.some(key => key.startsWith('$')); + + if (hasDollarKey) { + if (update.$push) { + _applyTimestampToUpdateOperator(update.$push); + } + if (update.$addToSet) { + _applyTimestampToUpdateOperator(update.$addToSet); + } + if (update.$set != null) { + const keys = Object.keys(update.$set); + for (const key of keys) { + applyTimestampsToUpdateKey(schema, key, update.$set, now); + } + } + if (update.$setOnInsert != null) { + const keys = Object.keys(update.$setOnInsert); + for (const key of keys) { + applyTimestampsToUpdateKey(schema, key, update.$setOnInsert, now); + } + } + } + + const updateKeys = Object.keys(update).filter(key => !key.startsWith('$')); + for (const key of updateKeys) { + applyTimestampsToUpdateKey(schema, key, update, now); + } + + function _applyTimestampToUpdateOperator(op) { + for (const key of Object.keys(op)) { + const $path = schema.path(key.replace(/\.\$\./i, '.').replace(/.\$$/, '')); + if (op[key] && + $path && + $path.$isMongooseDocumentArray && + $path.schema.options.timestamps) { + const timestamps = $path.schema.options.timestamps; + const createdAt = handleTimestampOption(timestamps, 'createdAt'); + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); + if (op[key].$each) { + op[key].$each.forEach(function(subdoc) { + if (updatedAt != null) { + subdoc[updatedAt] = now; + } + if (createdAt != null) { + subdoc[createdAt] = now; + } + }); + } else { + if (updatedAt != null) { + op[key][updatedAt] = now; + } + if (createdAt != null) { + op[key][createdAt] = now; + } + } + } + } + } +} + +function applyTimestampsToDocumentArray(arr, schematype, now) { + const timestamps = schematype.schema.options.timestamps; + + if (!timestamps) { + return; + } + + const len = arr.length; + + const createdAt = handleTimestampOption(timestamps, 'createdAt'); + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); + for (let i = 0; i < len; ++i) { + if (updatedAt != null) { + arr[i][updatedAt] = now; + } + if (createdAt != null) { + arr[i][createdAt] = now; + } + + applyTimestampsToChildren(now, arr[i], schematype.schema); + } +} + +function applyTimestampsToSingleNested(subdoc, schematype, now) { + const timestamps = schematype.schema.options.timestamps; + if (!timestamps) { + return; + } + + const createdAt = handleTimestampOption(timestamps, 'createdAt'); + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); + if (updatedAt != null) { + subdoc[updatedAt] = now; + } + if (createdAt != null) { + subdoc[createdAt] = now; + } + + applyTimestampsToChildren(now, subdoc, schematype.schema); +} + +function applyTimestampsToUpdateKey(schema, key, update, now) { + // Replace positional operator `$` and array filters `$[]` and `$[.*]` + const keyToSearch = cleanPositionalOperators(key); + const path = schema.path(keyToSearch); + if (!path) { + return; + } + + const parentSchemaTypes = []; + const pieces = keyToSearch.split('.'); + for (let i = pieces.length - 1; i > 0; --i) { + const s = schema.path(pieces.slice(0, i).join('.')); + if (s != null && + (s.$isMongooseDocumentArray || s.$isSingleNested)) { + parentSchemaTypes.push({ parentPath: key.split('.').slice(0, i).join('.'), parentSchemaType: s }); + } + } + + if (Array.isArray(update[key]) && path.$isMongooseDocumentArray) { + applyTimestampsToDocumentArray(update[key], path, now); + } else if (update[key] && path.$isSingleNested) { + applyTimestampsToSingleNested(update[key], path, now); + } else if (parentSchemaTypes.length > 0) { + for (const item of parentSchemaTypes) { + const parentPath = item.parentPath; + const parentSchemaType = item.parentSchemaType; + const timestamps = parentSchemaType.schema.options.timestamps; + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); + + if (!timestamps || updatedAt == null) { + continue; + } + + if (parentSchemaType.$isSingleNested) { + // Single nested is easy + update[parentPath + '.' + updatedAt] = now; + } else if (parentSchemaType.$isMongooseDocumentArray) { + let childPath = key.substr(parentPath.length + 1); + + if (/^\d+$/.test(childPath)) { + update[parentPath + '.' + childPath][updatedAt] = now; + continue; + } + + const firstDot = childPath.indexOf('.'); + childPath = firstDot !== -1 ? childPath.substr(0, firstDot) : childPath; + + update[parentPath + '.' + childPath + '.' + updatedAt] = now; + } + } + } else if (path.schema != null && path.schema != schema && update[key]) { + const timestamps = path.schema.options.timestamps; + const createdAt = handleTimestampOption(timestamps, 'createdAt'); + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); + + if (!timestamps) { + return; + } + + if (updatedAt != null) { + update[key][updatedAt] = now; + } + if (createdAt != null) { + update[key][createdAt] = now; + } + } +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js b/node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js new file mode 100644 index 0000000..6fab29b --- /dev/null +++ b/node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js @@ -0,0 +1,118 @@ +'use strict'; + +/*! + * ignore + */ + +const get = require('../get'); + +module.exports = applyTimestampsToUpdate; + +/*! + * ignore + */ + +function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, options) { + const updates = currentUpdate; + let _updates = updates; + const overwrite = get(options, 'overwrite', false); + const timestamps = get(options, 'timestamps', true); + + // Support skipping timestamps at the query level, see gh-6980 + if (!timestamps || updates == null) { + return currentUpdate; + } + + const skipCreatedAt = timestamps != null && timestamps.createdAt === false; + const skipUpdatedAt = timestamps != null && timestamps.updatedAt === false; + + if (overwrite) { + if (currentUpdate && currentUpdate.$set) { + currentUpdate = currentUpdate.$set; + updates.$set = {}; + _updates = updates.$set; + } + if (!skipUpdatedAt && updatedAt && !currentUpdate[updatedAt]) { + _updates[updatedAt] = now; + } + if (!skipCreatedAt && createdAt && !currentUpdate[createdAt]) { + _updates[createdAt] = now; + } + return updates; + } + currentUpdate = currentUpdate || {}; + + if (Array.isArray(updates)) { + // Update with aggregation pipeline + updates.push({ $set: { updatedAt: now } }); + + return updates; + } + + updates.$set = updates.$set || {}; + if (!skipUpdatedAt && updatedAt && + (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) { + let timestampSet = false; + if (updatedAt.indexOf('.') !== -1) { + const pieces = updatedAt.split('.'); + for (let i = 1; i < pieces.length; ++i) { + const remnant = pieces.slice(-i).join('.'); + const start = pieces.slice(0, -i).join('.'); + if (currentUpdate[start] != null) { + currentUpdate[start][remnant] = now; + timestampSet = true; + break; + } else if (currentUpdate.$set && currentUpdate.$set[start]) { + currentUpdate.$set[start][remnant] = now; + timestampSet = true; + break; + } + } + } + + if (!timestampSet) { + updates.$set[updatedAt] = now; + } + + if (updates.hasOwnProperty(updatedAt)) { + delete updates[updatedAt]; + } + } + + if (!skipCreatedAt && createdAt) { + + if (currentUpdate[createdAt]) { + delete currentUpdate[createdAt]; + } + if (currentUpdate.$set && currentUpdate.$set[createdAt]) { + delete currentUpdate.$set[createdAt]; + } + let timestampSet = false; + if (createdAt.indexOf('.') !== -1) { + const pieces = createdAt.split('.'); + for (let i = 1; i < pieces.length; ++i) { + const remnant = pieces.slice(-i).join('.'); + const start = pieces.slice(0, -i).join('.'); + if (currentUpdate[start] != null) { + currentUpdate[start][remnant] = now; + timestampSet = true; + break; + } else if (currentUpdate.$set && currentUpdate.$set[start]) { + currentUpdate.$set[start][remnant] = now; + timestampSet = true; + break; + } + } + } + + if (!timestampSet) { + updates.$setOnInsert = updates.$setOnInsert || {}; + updates.$setOnInsert[createdAt] = now; + } + } + + if (Object.keys(updates.$set).length === 0) { + delete updates.$set; + } + return updates; +} diff --git a/node_modules/mongoose/lib/helpers/update/castArrayFilters.js b/node_modules/mongoose/lib/helpers/update/castArrayFilters.js new file mode 100644 index 0000000..c60ebdc --- /dev/null +++ b/node_modules/mongoose/lib/helpers/update/castArrayFilters.js @@ -0,0 +1,70 @@ +'use strict'; + +const castFilterPath = require('../query/castFilterPath'); +const cleanPositionalOperators = require('../schema/cleanPositionalOperators'); +const getPath = require('../schema/getPath'); +const updatedPathsByArrayFilter = require('./updatedPathsByArrayFilter'); + +module.exports = function castArrayFilters(query) { + const arrayFilters = query.options.arrayFilters; + const update = query.getUpdate(); + const schema = query.schema; + const updatedPathsByFilter = updatedPathsByArrayFilter(update); + const strictQuery = schema.options.strictQuery; + + _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilter, query); +}; + +function _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilter, query) { + if (!Array.isArray(arrayFilters)) { + return; + } + + for (const filter of arrayFilters) { + if (filter == null) { + throw new Error(`Got null array filter in ${arrayFilters}`); + } + for (const key of Object.keys(filter)) { + if (key === '$and' || key === '$or') { + _castArrayFilters(filter[key], schema, strictQuery, updatedPathsByFilter, query); + continue; + } + if (filter[key] == null) { + continue; + } + if (updatedPathsByFilter[key] === null) { + continue; + } + if (Object.keys(updatedPathsByFilter).length === 0) { + continue; + } + const dot = key.indexOf('.'); + let filterPath = dot === -1 ? + updatedPathsByFilter[key] + '.0' : + updatedPathsByFilter[key.substr(0, dot)] + '.0' + key.substr(dot); + if (filterPath == null) { + throw new Error(`Filter path not found for ${key}`); + } + + // If there are multiple array filters in the path being updated, make sure + // to replace them so we can get the schema path. + filterPath = cleanPositionalOperators(filterPath); + const schematype = getPath(schema, filterPath); + if (schematype == null) { + if (!strictQuery) { + return; + } + // For now, treat `strictQuery = true` and `strictQuery = 'throw'` as + // equivalent for casting array filters. `strictQuery = true` doesn't + // quite work in this context because we never want to silently strip out + // array filters, even if the path isn't in the schema. + throw new Error(`Could not find path "${filterPath}" in schema`); + } + if (typeof filter[key] === 'object') { + filter[key] = castFilterPath(query, schematype, filter[key]); + } else { + filter[key] = schematype.castForQuery(filter[key]); + } + } + } +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/update/modifiedPaths.js b/node_modules/mongoose/lib/helpers/update/modifiedPaths.js new file mode 100644 index 0000000..9cb567d --- /dev/null +++ b/node_modules/mongoose/lib/helpers/update/modifiedPaths.js @@ -0,0 +1,33 @@ +'use strict'; + +const _modifiedPaths = require('../common').modifiedPaths; + +/** + * Given an update document with potential update operators (`$set`, etc.) + * returns an object whose keys are the directly modified paths. + * + * If there are any top-level keys that don't start with `$`, we assume those + * will get wrapped in a `$set`. The Mongoose Query is responsible for wrapping + * top-level keys in `$set`. + * + * @param {Object} update + * @return {Object} modified + */ + +module.exports = function modifiedPaths(update) { + const keys = Object.keys(update); + const res = {}; + + const withoutDollarKeys = {}; + for (const key of keys) { + if (key.startsWith('$')) { + _modifiedPaths(update[key], '', res); + continue; + } + withoutDollarKeys[key] = update[key]; + } + + _modifiedPaths(withoutDollarKeys, '', res); + + return res; +}; diff --git a/node_modules/mongoose/lib/helpers/update/moveImmutableProperties.js b/node_modules/mongoose/lib/helpers/update/moveImmutableProperties.js new file mode 100644 index 0000000..8541c5b --- /dev/null +++ b/node_modules/mongoose/lib/helpers/update/moveImmutableProperties.js @@ -0,0 +1,53 @@ +'use strict'; + +const get = require('../get'); + +/** + * Given an update, move all $set on immutable properties to $setOnInsert. + * This should only be called for upserts, because $setOnInsert bypasses the + * strictness check for immutable properties. + */ + +module.exports = function moveImmutableProperties(schema, update, ctx) { + if (update == null) { + return; + } + + const keys = Object.keys(update); + for (const key of keys) { + const isDollarKey = key.startsWith('$'); + + if (key === '$set') { + const updatedPaths = Object.keys(update[key]); + for (const path of updatedPaths) { + _walkUpdatePath(schema, update[key], path, update, ctx); + } + } else if (!isDollarKey) { + _walkUpdatePath(schema, update, key, update, ctx); + } + + } +}; + +function _walkUpdatePath(schema, op, path, update, ctx) { + const schematype = schema.path(path); + if (schematype == null) { + return; + } + + let immutable = get(schematype, 'options.immutable', null); + if (immutable == null) { + return; + } + if (typeof immutable === 'function') { + immutable = immutable.call(ctx, ctx); + } + + if (!immutable) { + return; + } + + update.$setOnInsert = update.$setOnInsert || {}; + update.$setOnInsert[path] = op[path]; + delete op[path]; +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/update/removeUnusedArrayFilters.js b/node_modules/mongoose/lib/helpers/update/removeUnusedArrayFilters.js new file mode 100644 index 0000000..6a52f91 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/update/removeUnusedArrayFilters.js @@ -0,0 +1,32 @@ +'use strict'; + +/** + * MongoDB throws an error if there's unused array filters. That is, if `options.arrayFilters` defines + * a filter, but none of the `update` keys use it. This should be enough to filter out all unused array + * filters. + */ + +module.exports = function removeUnusedArrayFilters(update, arrayFilters) { + const updateKeys = Object.keys(update). + map(key => Object.keys(update[key])). + reduce((cur, arr) => cur.concat(arr), []); + return arrayFilters.filter(obj => { + return _checkSingleFilterKey(obj, updateKeys); + }); +}; + +function _checkSingleFilterKey(arrayFilter, updateKeys) { + const firstKey = Object.keys(arrayFilter)[0]; + + if (firstKey === '$and' || firstKey === '$or') { + if (!Array.isArray(arrayFilter[firstKey])) { + return false; + } + return arrayFilter[firstKey].find(filter => _checkSingleFilterKey(filter, updateKeys)) != null; + } + + const firstDot = firstKey.indexOf('.'); + const arrayFilterKey = firstDot === -1 ? firstKey : firstKey.slice(0, firstDot); + + return updateKeys.find(key => key.includes('$[' + arrayFilterKey + ']')) != null; +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/update/updatedPathsByArrayFilter.js b/node_modules/mongoose/lib/helpers/update/updatedPathsByArrayFilter.js new file mode 100644 index 0000000..0958808 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/update/updatedPathsByArrayFilter.js @@ -0,0 +1,27 @@ +'use strict'; + +const modifiedPaths = require('./modifiedPaths'); + +module.exports = function updatedPathsByArrayFilter(update) { + if (update == null) { + return {}; + } + const updatedPaths = modifiedPaths(update); + + return Object.keys(updatedPaths).reduce((cur, path) => { + const matches = path.match(/\$\[[^\]]+\]/g); + if (matches == null) { + return cur; + } + for (const match of matches) { + const firstMatch = path.indexOf(match); + if (firstMatch !== path.lastIndexOf(match)) { + throw new Error(`Path '${path}' contains the same array filter multiple times`); + } + cur[match.substring(2, match.length - 1)] = path. + substr(0, firstMatch - 1). + replace(/\$\[[^\]]+\]/g, '0'); + } + return cur; + }, {}); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/updateValidators.js b/node_modules/mongoose/lib/helpers/updateValidators.js new file mode 100644 index 0000000..eddb857 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/updateValidators.js @@ -0,0 +1,256 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const ValidationError = require('../error/validation'); +const cleanPositionalOperators = require('./schema/cleanPositionalOperators'); +const flatten = require('./common').flatten; +const modifiedPaths = require('./common').modifiedPaths; + +/** + * Applies validators and defaults to update and findOneAndUpdate operations, + * specifically passing a null doc as `this` to validators and defaults + * + * @param {Query} query + * @param {Schema} schema + * @param {Object} castedDoc + * @param {Object} options + * @method runValidatorsOnUpdate + * @api private + */ + +module.exports = function(query, schema, castedDoc, options, callback) { + const keys = Object.keys(castedDoc || {}); + let updatedKeys = {}; + let updatedValues = {}; + const isPull = {}; + const arrayAtomicUpdates = {}; + const numKeys = keys.length; + let hasDollarUpdate = false; + const modified = {}; + let currentUpdate; + let key; + let i; + + for (i = 0; i < numKeys; ++i) { + if (keys[i].startsWith('$')) { + hasDollarUpdate = true; + if (keys[i] === '$push' || keys[i] === '$addToSet') { + const _keys = Object.keys(castedDoc[keys[i]]); + for (let ii = 0; ii < _keys.length; ++ii) { + currentUpdate = castedDoc[keys[i]][_keys[ii]]; + if (currentUpdate && currentUpdate.$each) { + arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []). + concat(currentUpdate.$each); + } else { + arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []). + concat([currentUpdate]); + } + } + continue; + } + modifiedPaths(castedDoc[keys[i]], '', modified); + const flat = flatten(castedDoc[keys[i]], null, null, schema); + const paths = Object.keys(flat); + const numPaths = paths.length; + for (let j = 0; j < numPaths; ++j) { + const updatedPath = cleanPositionalOperators(paths[j]); + key = keys[i]; + // With `$pull` we might flatten `$in`. Skip stuff nested under `$in` + // for the rest of the logic, it will get handled later. + if (updatedPath.includes('$')) { + continue; + } + if (key === '$set' || key === '$setOnInsert' || + key === '$pull' || key === '$pullAll') { + updatedValues[updatedPath] = flat[paths[j]]; + isPull[updatedPath] = key === '$pull' || key === '$pullAll'; + } else if (key === '$unset') { + updatedValues[updatedPath] = undefined; + } + updatedKeys[updatedPath] = true; + } + } + } + + if (!hasDollarUpdate) { + modifiedPaths(castedDoc, '', modified); + updatedValues = flatten(castedDoc, null, null, schema); + updatedKeys = Object.keys(updatedValues); + } + + const updates = Object.keys(updatedValues); + const numUpdates = updates.length; + const validatorsToExecute = []; + const validationErrors = []; + + const alreadyValidated = []; + + const context = query; + function iter(i, v) { + const schemaPath = schema._getSchema(updates[i]); + if (schemaPath == null) { + return; + } + if (schemaPath.instance === 'Mixed' && schemaPath.path !== updates[i]) { + return; + } + + if (v && Array.isArray(v.$in)) { + v.$in.forEach((v, i) => { + validatorsToExecute.push(function(callback) { + schemaPath.doValidate( + v, + function(err) { + if (err) { + err.path = updates[i] + '.$in.' + i; + validationErrors.push(err); + } + callback(null); + }, + context, + { updateValidator: true }); + }); + }); + } else { + if (isPull[updates[i]] && + schemaPath.$isMongooseArray) { + return; + } + + if (schemaPath.$isMongooseDocumentArrayElement && v != null && v.$__ != null) { + alreadyValidated.push(updates[i]); + validatorsToExecute.push(function(callback) { + schemaPath.doValidate(v, function(err) { + if (err) { + err.path = updates[i]; + validationErrors.push(err); + return callback(null); + } + + v.validate(function(err) { + if (err) { + if (err.errors) { + for (const key of Object.keys(err.errors)) { + const _err = err.errors[key]; + _err.path = updates[i] + '.' + key; + validationErrors.push(_err); + } + } else { + err.path = updates[i]; + validationErrors.push(err); + } + } + callback(null); + }); + }, context, { updateValidator: true }); + }); + } else { + validatorsToExecute.push(function(callback) { + for (const path of alreadyValidated) { + if (updates[i].startsWith(path + '.')) { + return callback(null); + } + } + + schemaPath.doValidate(v, function(err) { + if (schemaPath.schema != null && + schemaPath.schema.options.storeSubdocValidationError === false && + err instanceof ValidationError) { + return callback(null); + } + + if (err) { + err.path = updates[i]; + validationErrors.push(err); + } + callback(null); + }, context, { updateValidator: true }); + }); + } + } + } + for (i = 0; i < numUpdates; ++i) { + iter(i, updatedValues[updates[i]]); + } + + const arrayUpdates = Object.keys(arrayAtomicUpdates); + for (const arrayUpdate of arrayUpdates) { + let schemaPath = schema._getSchema(arrayUpdate); + if (schemaPath && schemaPath.$isMongooseDocumentArray) { + validatorsToExecute.push(function(callback) { + schemaPath.doValidate( + arrayAtomicUpdates[arrayUpdate], + getValidationCallback(arrayUpdate, validationErrors, callback), + options && options.context === 'query' ? query : null); + }); + } else { + schemaPath = schema._getSchema(arrayUpdate + '.0'); + for (const atomicUpdate of arrayAtomicUpdates[arrayUpdate]) { + validatorsToExecute.push(function(callback) { + schemaPath.doValidate( + atomicUpdate, + getValidationCallback(arrayUpdate, validationErrors, callback), + options && options.context === 'query' ? query : null, + { updateValidator: true }); + }); + } + } + } + + if (callback != null) { + let numValidators = validatorsToExecute.length; + if (numValidators === 0) { + return _done(callback); + } + for (const validator of validatorsToExecute) { + validator(function() { + if (--numValidators <= 0) { + _done(callback); + } + }); + } + + return; + } + + return function(callback) { + let numValidators = validatorsToExecute.length; + if (numValidators === 0) { + return _done(callback); + } + for (const validator of validatorsToExecute) { + validator(function() { + if (--numValidators <= 0) { + _done(callback); + } + }); + } + }; + + function _done(callback) { + if (validationErrors.length) { + const err = new ValidationError(null); + + for (const validationError of validationErrors) { + err.addError(validationError.path, validationError); + } + + return callback(err); + } + callback(null); + } + + function getValidationCallback(arrayUpdate, validationErrors, callback) { + return function(err) { + if (err) { + err.path = arrayUpdate; + validationErrors.push(err); + } + callback(null); + }; + } +}; + diff --git a/node_modules/mongoose/lib/index.js b/node_modules/mongoose/lib/index.js new file mode 100644 index 0000000..a0e7b98 --- /dev/null +++ b/node_modules/mongoose/lib/index.js @@ -0,0 +1,1162 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +require('./driver').set(require('./drivers/node-mongodb-native')); + +const Document = require('./document'); +const EventEmitter = require('events').EventEmitter; +const Schema = require('./schema'); +const SchemaType = require('./schematype'); +const SchemaTypes = require('./schema/index'); +const VirtualType = require('./virtualtype'); +const STATES = require('./connectionstate'); +const VALID_OPTIONS = require('./validoptions'); +const Types = require('./types'); +const Query = require('./query'); +const Model = require('./model'); +const applyPlugins = require('./helpers/schema/applyPlugins'); +const driver = require('./driver'); +const get = require('./helpers/get'); +const promiseOrCallback = require('./helpers/promiseOrCallback'); +const legacyPluralize = require('./helpers/pluralize'); +const utils = require('./utils'); +const pkg = require('../package.json'); +const cast = require('./cast'); +const removeSubdocs = require('./plugins/removeSubdocs'); +const saveSubdocs = require('./plugins/saveSubdocs'); +const trackTransaction = require('./plugins/trackTransaction'); +const validateBeforeSave = require('./plugins/validateBeforeSave'); + +const Aggregate = require('./aggregate'); +const PromiseProvider = require('./promise_provider'); +const shardingPlugin = require('./plugins/sharding'); +const trusted = require('./helpers/query/trusted').trusted; +const sanitizeFilter = require('./helpers/query/sanitizeFilter'); + +const defaultMongooseSymbol = Symbol.for('mongoose:default'); + +require('./helpers/printJestWarning'); + +/** + * Mongoose constructor. + * + * The exports object of the `mongoose` module is an instance of this class. + * Most apps will only use this one instance. + * + * ####Example: + * const mongoose = require('mongoose'); + * mongoose instanceof mongoose.Mongoose; // true + * + * // Create a new Mongoose instance with its own `connect()`, `set()`, `model()`, etc. + * const m = new mongoose.Mongoose(); + * + * @api public + * @param {Object} options see [`Mongoose#set()` docs](/docs/api/mongoose.html#mongoose_Mongoose-set) + */ +function Mongoose(options) { + this.connections = []; + this.models = {}; + this.events = new EventEmitter(); + // default global options + this.options = Object.assign({ + pluralization: true, + autoIndex: true, + autoCreate: true + }, options); + const conn = this.createConnection(); // default connection + conn.models = this.models; + + if (this.options.pluralization) { + this._pluralize = legacyPluralize; + } + + // If a user creates their own Mongoose instance, give them a separate copy + // of the `Schema` constructor so they get separate custom types. (gh-6933) + if (!options || !options[defaultMongooseSymbol]) { + const _this = this; + this.Schema = function() { + this.base = _this; + return Schema.apply(this, arguments); + }; + this.Schema.prototype = Object.create(Schema.prototype); + + Object.assign(this.Schema, Schema); + this.Schema.base = this; + this.Schema.Types = Object.assign({}, Schema.Types); + } else { + // Hack to work around babel's strange behavior with + // `import mongoose, { Schema } from 'mongoose'`. Because `Schema` is not + // an own property of a Mongoose global, Schema will be undefined. See gh-5648 + for (const key of ['Schema', 'model']) { + this[key] = Mongoose.prototype[key]; + } + } + this.Schema.prototype.base = this; + + Object.defineProperty(this, 'plugins', { + configurable: false, + enumerable: true, + writable: false, + value: [ + [saveSubdocs, { deduplicate: true }], + [validateBeforeSave, { deduplicate: true }], + [shardingPlugin, { deduplicate: true }], + [removeSubdocs, { deduplicate: true }], + [trackTransaction, { deduplicate: true }] + ] + }); +} +Mongoose.prototype.cast = cast; +/** + * Expose connection states for user-land + * + * @memberOf Mongoose + * @property STATES + * @api public + */ +Mongoose.prototype.STATES = STATES; + +/** + * Object with `get()` and `set()` containing the underlying driver this Mongoose instance + * uses to communicate with the database. A driver is a Mongoose-specific interface that defines functions + * like `find()`. + * + * @memberOf Mongoose + * @property driver + * @api public + */ + +Mongoose.prototype.driver = driver; + +/** + * Sets mongoose options + * + * ####Example: + * + * mongoose.set('test', value) // sets the 'test' option to `value` + * + * mongoose.set('debug', true) // enable logging collection methods + arguments to the console/file + * + * mongoose.set('debug', function(collectionName, methodName, ...methodArgs) {}); // use custom function to log collection methods + arguments + * + * Currently supported options are: + * - 'debug': If `true`, prints the operations mongoose sends to MongoDB to the console. If a writable stream is passed, it will log to that stream, without colorization. If a callback function is passed, it will receive the collection name, the method name, then all arugments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callback `Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})`. + * - 'returnOriginal': If `false`, changes the default `returnOriginal` option to `findOneAndUpdate()`, `findByIdAndUpdate`, and `findOneAndReplace()` to false. This is equivalent to setting the `new` option to `true` for `findOneAndX()` calls by default. Read our [`findOneAndUpdate()` tutorial](/docs/tutorials/findoneandupdate.html) for more information. + * - 'bufferCommands': enable/disable mongoose's buffering mechanism for all connections and models + * - 'cloneSchemas': false by default. Set to `true` to `clone()` all schemas before compiling into a model. + * - 'applyPluginsToDiscriminators': false by default. Set to true to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema. + * - 'applyPluginsToChildSchemas': true by default. Set to false to skip applying global plugins to child schemas + * - 'objectIdGetter': true by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that returns `this` for convenience with populate. Set this to false to remove the getter. + * - 'runValidators': false by default. Set to true to enable [update validators](/docs/validation.html#update-validators) for all validators by default. + * - 'toObject': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toObject()`](/docs/api.html#document_Document-toObject) + * - 'toJSON': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toJSON()`](/docs/api.html#document_Document-toJSON), for determining how Mongoose documents get serialized by `JSON.stringify()` + * - 'strict': true by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas. + * - 'strictQuery': false by default, may be `false`, `true`, or `'throw'`. Sets the default [strictQuery](/docs/guide.html#strictQuery) mode for schemas. + * - 'selectPopulatedPaths': true by default. Set to false to opt out of Mongoose adding all fields that you `populate()` to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one. + * - 'maxTimeMS': If set, attaches [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) to every query + * - 'autoIndex': true by default. Set to false to disable automatic index creation for all models associated with this Mongoose instance. + * - 'autoCreate': Set to `true` to make Mongoose call [`Model.createCollection()`](/docs/api/model.html#model_Model.createCollection) automatically when you create a model with `mongoose.model()` or `conn.model()`. This is useful for testing transactions, change streams, and other features that require the collection to exist. + * - 'overwriteModels': Set to `true` to default to overwriting models with the same name when calling `mongoose.model()`, as opposed to throwing an `OverwriteModelError`. + * + * @param {String} key + * @param {String|Function|Boolean} value + * @api public + */ + +Mongoose.prototype.set = function(key, value) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + if (VALID_OPTIONS.indexOf(key) === -1) throw new Error(`\`${key}\` is an invalid option.`); + + if (arguments.length === 1) { + return _mongoose.options[key]; + } + + _mongoose.options[key] = value; + + if (key === 'objectIdGetter') { + if (value) { + Object.defineProperty(mongoose.Types.ObjectId.prototype, '_id', { + enumerable: false, + configurable: true, + get: function() { + return this; + } + }); + } else { + delete mongoose.Types.ObjectId.prototype._id; + } + } + + return _mongoose; +}; + +/** + * Gets mongoose options + * + * ####Example: + * + * mongoose.get('test') // returns the 'test' value + * + * @param {String} key + * @method get + * @api public + */ + +Mongoose.prototype.get = Mongoose.prototype.set; + +/** + * Creates a Connection instance. + * + * Each `connection` instance maps to a single database. This method is helpful when managing multiple db connections. + * + * + * _Options passed take precedence over options included in connection strings._ + * + * ####Example: + * + * // with mongodb:// URI + * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); + * + * // and options + * const opts = { db: { native_parser: true }} + * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts); + * + * // replica sets + * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database'); + * + * // and options + * const opts = { replset: { strategy: 'ping', rs_name: 'testSet' }} + * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts); + * + * // and options + * const opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' } + * db = mongoose.createConnection('localhost', 'database', port, opts) + * + * // initialize now, connect later + * db = mongoose.createConnection(); + * db.openUri('localhost', 'database', port, [opts]); + * + * @param {String} [uri] a mongodb:// URI + * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below. + * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. + * @param {String} [options.dbName] The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. + * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. + * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. + * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. + * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. + * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. + * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). + * @param {Number} [options.maxPoolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). + * @param {Number} [options.minPoolSize=1] The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). + * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). + * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. + * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. + * @return {Connection} the created Connection object. Connections are thenable, so you can do `await mongoose.createConnection()` + * @api public + */ + +Mongoose.prototype.createConnection = function(uri, options, callback) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + const conn = new Connection(_mongoose); + if (typeof options === 'function') { + callback = options; + options = null; + } + _mongoose.connections.push(conn); + _mongoose.events.emit('createConnection', conn); + + if (arguments.length > 0) { + conn.openUri(uri, options, callback); + } + + return conn; +}; + +/** + * Opens the default mongoose connection. + * + * ####Example: + * + * mongoose.connect('mongodb://user:pass@localhost:port/database'); + * + * // replica sets + * const uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase'; + * mongoose.connect(uri); + * + * // with options + * mongoose.connect(uri, options); + * + * // optional callback that gets fired when initial connection completed + * const uri = 'mongodb://nonexistent.domain:27000'; + * mongoose.connect(uri, function(error) { + * // if error is truthy, the initial connection failed. + * }) + * + * @param {String} uri(s) + * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below. + * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. + * @param {Number} [options.bufferTimeoutMS=10000] Mongoose specific option. If `bufferCommands` is true, Mongoose will throw an error after `bufferTimeoutMS` if the operation is still buffered. + * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string. + * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. + * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. + * @param {Number} [options.maxPoolSize=100] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). + * @param {Number} [options.minPoolSize=0] The minimum number of sockets the MongoDB driver will keep open for this connection. + * @param {Number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds). + * @param {Number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation. + * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. + * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. + * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. + * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). + * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). + * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. + * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. + * @param {Boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. + * @param {Function} [callback] + * @see Mongoose#createConnection #index_Mongoose-createConnection + * @api public + * @return {Promise} resolves to `this` if connection succeeded + */ + +Mongoose.prototype.connect = function(uri, options, callback) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + const conn = _mongoose.connection; + + return _mongoose._promiseOrCallback(callback, cb => { + conn.openUri(uri, options, err => { + if (err != null) { + return cb(err); + } + return cb(null, _mongoose); + }); + }); +}; + +/** + * Runs `.close()` on all connections in parallel. + * + * @param {Function} [callback] called after all connection close, or when first error occurred. + * @return {Promise} resolves when all connections are closed, or rejects with the first error that occurred. + * @api public + */ + +Mongoose.prototype.disconnect = function(callback) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + return _mongoose._promiseOrCallback(callback, cb => { + let remaining = _mongoose.connections.length; + if (remaining <= 0) { + return cb(null); + } + _mongoose.connections.forEach(conn => { + conn.close(function(error) { + if (error) { + return cb(error); + } + if (!--remaining) { + cb(null); + } + }); + }); + }); +}; + +/** + * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) + * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), + * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). + * + * Calling `mongoose.startSession()` is equivalent to calling `mongoose.connection.startSession()`. + * Sessions are scoped to a connection, so calling `mongoose.startSession()` + * starts a session on the [default mongoose connection](/docs/api.html#mongoose_Mongoose-connection). + * + * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) + * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency + * @param {Function} [callback] + * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` + * @api public + */ + +Mongoose.prototype.startSession = function() { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + return _mongoose.connection.startSession.apply(_mongoose.connection, arguments); +}; + +/** + * Getter/setter around function for pluralizing collection names. + * + * @param {Function|null} [fn] overwrites the function used to pluralize collection names + * @return {Function|null} the current function used to pluralize collection names, defaults to the legacy function from `mongoose-legacy-pluralize`. + * @api public + */ + +Mongoose.prototype.pluralize = function(fn) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + if (arguments.length > 0) { + _mongoose._pluralize = fn; + } + return _mongoose._pluralize; +}; + +/** + * Defines a model or retrieves it. + * + * Models defined on the `mongoose` instance are available to all connection + * created by the same `mongoose` instance. + * + * If you call `mongoose.model()` with twice the same name but a different schema, + * you will get an `OverwriteModelError`. If you call `mongoose.model()` with + * the same name and same schema, you'll get the same schema back. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * + * // define an Actor model with this mongoose instance + * const schema = new Schema({ name: String }); + * mongoose.model('Actor', schema); + * + * // create a new connection + * const conn = mongoose.createConnection(..); + * + * // create Actor model + * const Actor = conn.model('Actor', schema); + * conn.model('Actor') === Actor; // true + * conn.model('Actor', schema) === Actor; // true, same schema + * conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name + * + * // This throws an `OverwriteModelError` because the schema is different. + * conn.model('Actor', new Schema({ name: String })); + * + * _When no `collection` argument is passed, Mongoose uses the model name. If you don't like this behavior, either pass a collection name, use `mongoose.pluralize()`, or set your schemas collection name option._ + * + * ####Example: + * + * const schema = new Schema({ name: String }, { collection: 'actor' }); + * + * // or + * + * schema.set('collection', 'actor'); + * + * // or + * + * const collectionName = 'actor' + * const M = mongoose.model('Actor', schema, collectionName) + * + * @param {String|Function} name model name or class extending Model + * @param {Schema} [schema] the schema to use. + * @param {String} [collection] name (optional, inferred from model name) + * @return {Model} The model associated with `name`. Mongoose will create the model if it doesn't already exist. + * @api public + */ + +Mongoose.prototype.model = function(name, schema, collection, options) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + if (typeof schema === 'string') { + collection = schema; + schema = false; + } + + if (utils.isObject(schema) && !(schema instanceof Schema)) { + schema = new Schema(schema); + } + if (schema && !(schema instanceof Schema)) { + throw new Error('The 2nd parameter to `mongoose.model()` should be a ' + + 'schema or a POJO'); + } + + // handle internal options from connection.model() + options = options || {}; + + const originalSchema = schema; + if (schema) { + if (_mongoose.get('cloneSchemas')) { + schema = schema.clone(); + } + _mongoose._applyPlugins(schema); + } + + // connection.model() may be passing a different schema for + // an existing model name. in this case don't read from cache. + const overwriteModels = _mongoose.options.hasOwnProperty('overwriteModels') ? + _mongoose.options.overwriteModels : + options.overwriteModels; + if (_mongoose.models.hasOwnProperty(name) && options.cache !== false && overwriteModels !== true) { + if (originalSchema && + originalSchema.instanceOfSchema && + originalSchema !== _mongoose.models[name].schema) { + throw new _mongoose.Error.OverwriteModelError(name); + } + if (collection && collection !== _mongoose.models[name].collection.name) { + // subclass current model with alternate collection + const model = _mongoose.models[name]; + schema = model.prototype.schema; + const sub = model.__subclass(_mongoose.connection, schema, collection); + // do not cache the sub model + return sub; + } + return _mongoose.models[name]; + } + if (schema == null) { + throw new _mongoose.Error.MissingSchemaError(name); + } + + const model = _mongoose._model(name, schema, collection, options); + + _mongoose.connection.models[name] = model; + _mongoose.models[name] = model; + + return model; +}; + +/*! + * ignore + */ + +Mongoose.prototype._model = function(name, schema, collection, options) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + let model; + if (typeof name === 'function') { + model = name; + name = model.name; + if (!(model.prototype instanceof Model)) { + throw new _mongoose.Error('The provided class ' + name + ' must extend Model'); + } + } + + if (schema) { + if (_mongoose.get('cloneSchemas')) { + schema = schema.clone(); + } + _mongoose._applyPlugins(schema); + } + + // Apply relevant "global" options to the schema + if (schema == null || !('pluralization' in schema.options)) { + schema.options.pluralization = _mongoose.options.pluralization; + } + + if (!collection) { + collection = schema.get('collection') || + utils.toCollectionName(name, _mongoose.pluralize()); + } + + const connection = options.connection || _mongoose.connection; + model = _mongoose.Model.compile(model || name, schema, collection, connection, _mongoose); + + // Errors handled internally, so safe to ignore error + model.init(function $modelInitNoop() {}); + + connection.emit('model', model); + + return model; +}; + +/** + * Removes the model named `name` from the default connection, if it exists. + * You can use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + * + * Equivalent to `mongoose.connection.deleteModel(name)`. + * + * ####Example: + * + * mongoose.model('User', new Schema({ name: String })); + * console.log(mongoose.model('User')); // Model object + * mongoose.deleteModel('User'); + * console.log(mongoose.model('User')); // undefined + * + * // Usually useful in a Mocha `afterEach()` hook + * afterEach(function() { + * mongoose.deleteModel(/.+/); // Delete every model + * }); + * + * @api public + * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. + * @return {Mongoose} this + */ + +Mongoose.prototype.deleteModel = function(name) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + _mongoose.connection.deleteModel(name); + delete _mongoose.models[name]; + return _mongoose; +}; + +/** + * Returns an array of model names created on this instance of Mongoose. + * + * ####Note: + * + * _Does not include names of models created using `connection.model()`._ + * + * @api public + * @return {Array} + */ + +Mongoose.prototype.modelNames = function() { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + const names = Object.keys(_mongoose.models); + return names; +}; + +/** + * Applies global plugins to `schema`. + * + * @param {Schema} schema + * @api private + */ + +Mongoose.prototype._applyPlugins = function(schema, options) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + options = options || {}; + options.applyPluginsToDiscriminators = get(_mongoose, + 'options.applyPluginsToDiscriminators', false); + options.applyPluginsToChildSchemas = get(_mongoose, + 'options.applyPluginsToChildSchemas', true); + applyPlugins(schema, _mongoose.plugins, options, '$globalPluginsApplied'); +}; + +/** + * Declares a global plugin executed on all Schemas. + * + * Equivalent to calling `.plugin(fn)` on each Schema you create. + * + * @param {Function} fn plugin callback + * @param {Object} [opts] optional options + * @return {Mongoose} this + * @see plugins ./plugins.html + * @api public + */ + +Mongoose.prototype.plugin = function(fn, opts) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + _mongoose.plugins.push([fn, opts]); + return _mongoose; +}; + +/** + * The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections). + * + * ####Example: + * + * const mongoose = require('mongoose'); + * mongoose.connect(...); + * mongoose.connection.on('error', cb); + * + * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model). + * + * To create a new connection, use [`createConnection()`](#mongoose_Mongoose-createConnection). + * + * @memberOf Mongoose + * @instance + * @property {Connection} connection + * @api public + */ + +Mongoose.prototype.__defineGetter__('connection', function() { + return this.connections[0]; +}); + +Mongoose.prototype.__defineSetter__('connection', function(v) { + if (v instanceof Connection) { + this.connections[0] = v; + this.models = v.models; + } +}); + +/** + * An array containing all [connections](connections.html) associated with this + * Mongoose instance. By default, there is 1 connection. Calling + * [`createConnection()`](#mongoose_Mongoose-createConnection) adds a connection + * to this array. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * mongoose.connections.length; // 1, just the default connection + * mongoose.connections[0] === mongoose.connection; // true + * + * mongoose.createConnection('mongodb://localhost:27017/test'); + * mongoose.connections.length; // 2 + * + * @memberOf Mongoose + * @instance + * @property {Array} connections + * @api public + */ + +Mongoose.prototype.connections; + +/*! + * Connection + */ + +const Connection = driver.get().getConnection(); + +/*! + * Collection + */ + +const Collection = driver.get().Collection; + +/** + * The Mongoose Aggregate constructor + * + * @method Aggregate + * @api public + */ + +Mongoose.prototype.Aggregate = Aggregate; + +/** + * The Mongoose Collection constructor + * + * @method Collection + * @api public + */ + +Mongoose.prototype.Collection = Collection; + +/** + * The Mongoose [Connection](#connection_Connection) constructor + * + * @memberOf Mongoose + * @instance + * @method Connection + * @api public + */ + +Mongoose.prototype.Connection = Connection; + +/** + * The Mongoose version + * + * #### Example + * + * console.log(mongoose.version); // '5.x.x' + * + * @property version + * @api public + */ + +Mongoose.prototype.version = pkg.version; + +/** + * The Mongoose constructor + * + * The exports of the mongoose module is an instance of this class. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * const mongoose2 = new mongoose.Mongoose(); + * + * @method Mongoose + * @api public + */ + +Mongoose.prototype.Mongoose = Mongoose; + +/** + * The Mongoose [Schema](#schema_Schema) constructor + * + * ####Example: + * + * const mongoose = require('mongoose'); + * const Schema = mongoose.Schema; + * const CatSchema = new Schema(..); + * + * @method Schema + * @api public + */ + +Mongoose.prototype.Schema = Schema; + +/** + * The Mongoose [SchemaType](#schematype_SchemaType) constructor + * + * @method SchemaType + * @api public + */ + +Mongoose.prototype.SchemaType = SchemaType; + +/** + * The various Mongoose SchemaTypes. + * + * ####Note: + * + * _Alias of mongoose.Schema.Types for backwards compatibility._ + * + * @property SchemaTypes + * @see Schema.SchemaTypes #schema_Schema.Types + * @api public + */ + +Mongoose.prototype.SchemaTypes = Schema.Types; + +/** + * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor + * + * @method VirtualType + * @api public + */ + +Mongoose.prototype.VirtualType = VirtualType; + +/** + * The various Mongoose Types. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * const array = mongoose.Types.Array; + * + * ####Types: + * + * - [Array](/docs/schematypes.html#arrays) + * - [Buffer](/docs/schematypes.html#buffers) + * - [Embedded](/docs/schematypes.html#schemas) + * - [DocumentArray](/docs/api/documentarraypath.html) + * - [Decimal128](/docs/api.html#mongoose_Mongoose-Decimal128) + * - [ObjectId](/docs/schematypes.html#objectids) + * - [Map](/docs/schematypes.html#maps) + * - [Subdocument](/docs/schematypes.html#schemas) + * + * Using this exposed access to the `ObjectId` type, we can construct ids on demand. + * + * const ObjectId = mongoose.Types.ObjectId; + * const id1 = new ObjectId; + * + * @property Types + * @api public + */ + +Mongoose.prototype.Types = Types; + +/** + * The Mongoose [Query](#query_Query) constructor. + * + * @method Query + * @api public + */ + +Mongoose.prototype.Query = Query; + +/** + * The Mongoose [Promise](#promise_Promise) constructor. + * + * @memberOf Mongoose + * @instance + * @property Promise + * @api public + */ + +Object.defineProperty(Mongoose.prototype, 'Promise', { + get: function() { + return PromiseProvider.get(); + }, + set: function(lib) { + PromiseProvider.set(lib); + } +}); + +/** + * Storage layer for mongoose promises + * + * @method PromiseProvider + * @api public + */ + +Mongoose.prototype.PromiseProvider = PromiseProvider; + +/** + * The Mongoose [Model](#model_Model) constructor. + * + * @method Model + * @api public + */ + +Mongoose.prototype.Model = Model; + +/** + * The Mongoose [Document](/api/document.html) constructor. + * + * @method Document + * @api public + */ + +Mongoose.prototype.Document = Document; + +/** + * The Mongoose DocumentProvider constructor. Mongoose users should not have to + * use this directly + * + * @method DocumentProvider + * @api public + */ + +Mongoose.prototype.DocumentProvider = require('./document_provider'); + +/** + * The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that should be + * [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/). + * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId` + * instead. + * + * ####Example: + * + * const childSchema = new Schema({ parentId: mongoose.ObjectId }); + * + * @property ObjectId + * @api public + */ + +Mongoose.prototype.ObjectId = SchemaTypes.ObjectId; + +/** + * Returns true if Mongoose can cast the given value to an ObjectId, or + * false otherwise. + * + * ####Example: + * + * mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true + * mongoose.isValidObjectId('0123456789ab'); // true + * mongoose.isValidObjectId(6); // false + * + * @method isValidObjectId + * @api public + */ + +Mongoose.prototype.isValidObjectId = function(v) { + if (v == null) { + return true; + } + const base = this || mongoose; + const ObjectId = base.driver.get().ObjectId; + if (v instanceof ObjectId) { + return true; + } + + if (v._id != null) { + if (v._id instanceof ObjectId) { + return true; + } + if (v._id.toString instanceof Function) { + v = v._id.toString(); + if (typeof v === 'string' && v.length === 12) { + return true; + } + if (typeof v === 'string' && /^[0-9A-Fa-f]{24}$/.test(v)) { + return true; + } + return false; + } + } + + if (v.toString instanceof Function) { + v = v.toString(); + } + + if (typeof v === 'string' && v.length === 12) { + return true; + } + if (typeof v === 'string' && /^[0-9A-Fa-f]{24}$/.test(v)) { + return true; + } + + return false; +}; + +/** + * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that should be + * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html). + * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128` + * instead. + * + * ####Example: + * + * const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 }); + * + * @property Decimal128 + * @api public + */ + +Mongoose.prototype.Decimal128 = SchemaTypes.Decimal128; + +/** + * The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that Mongoose's change tracking, casting, + * and validation should ignore. + * + * ####Example: + * + * const schema = new Schema({ arbitrary: mongoose.Mixed }); + * + * @property Mixed + * @api public + */ + +Mongoose.prototype.Mixed = SchemaTypes.Mixed; + +/** + * The Mongoose Date [SchemaType](/docs/schematypes.html). + * + * ####Example: + * + * const schema = new Schema({ test: Date }); + * schema.path('test') instanceof mongoose.Date; // true + * + * @property Date + * @api public + */ + +Mongoose.prototype.Date = SchemaTypes.Date; + +/** + * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that Mongoose should cast to numbers. + * + * ####Example: + * + * const schema = new Schema({ num: mongoose.Number }); + * // Equivalent to: + * const schema = new Schema({ num: 'number' }); + * + * @property Number + * @api public + */ + +Mongoose.prototype.Number = SchemaTypes.Number; + +/** + * The [MongooseError](#error_MongooseError) constructor. + * + * @method Error + * @api public + */ + +Mongoose.prototype.Error = require('./error/index'); + +/** + * Mongoose uses this function to get the current time when setting + * [timestamps](/docs/guide.html#timestamps). You may stub out this function + * using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing. + * + * @method now + * @returns Date the current time + * @api public + */ + +Mongoose.prototype.now = function now() { return new Date(); }; + +/** + * The Mongoose CastError constructor + * + * @method CastError + * @param {String} type The name of the type + * @param {Any} value The value that failed to cast + * @param {String} path The path `a.b.c` in the doc where this cast error occurred + * @param {Error} [reason] The original error that was thrown + * @api public + */ + +Mongoose.prototype.CastError = require('./error/cast'); + +/** + * The constructor used for schematype options + * + * @method SchemaTypeOptions + * @api public + */ + +Mongoose.prototype.SchemaTypeOptions = require('./options/SchemaTypeOptions'); + +/** + * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses. + * + * @property mongo + * @api public + */ + +Mongoose.prototype.mongo = require('mongodb'); + +/** + * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses. + * + * @property mquery + * @api public + */ + +Mongoose.prototype.mquery = require('mquery'); + +/** + * Sanitizes query filters against [query selector injection attacks](https://thecodebarbarian.com/2014/09/04/defending-against-query-selector-injection-attacks.html) + * by wrapping any nested objects that have a property whose name starts with `$` in a `$eq`. + * + * ```javascript + * const obj = { username: 'val', pwd: { $ne: null } }; + * sanitizeFilter(obj); + * obj; // { username: 'val', pwd: { $eq: { $ne: null } } }); + * ``` + * + * @method sanitizeFilter + * @param {Object} filter + * @returns Object the sanitized object + * @api public + */ + +Mongoose.prototype.sanitizeFilter = sanitizeFilter; + +/** + * Tells `sanitizeFilter()` to skip the given object when filtering out potential [query selector injection attacks](https://thecodebarbarian.com/2014/09/04/defending-against-query-selector-injection-attacks.html). + * Use this method when you have a known query selector that you want to use. + * + * ```javascript + * const obj = { username: 'val', pwd: trusted({ $type: 'string', $eq: 'my secret' }) }; + * sanitizeFilter(obj); + * + * // Note that `sanitizeFilter()` did not add `$eq` around `$type`. + * obj; // { username: 'val', pwd: { $type: 'string', $eq: 'my secret' } }); + * ``` + * + * @method trusted + * @param {Object} obj + * @returns Object the passed in object + * @api public + */ + +Mongoose.prototype.trusted = trusted; + +/*! + * ignore + */ + +Mongoose.prototype._promiseOrCallback = function(callback, fn, ee) { + return promiseOrCallback(callback, fn, ee, this.Promise); +}; + +/*! + * The exports object is an instance of Mongoose. + * + * @api public + */ + +const mongoose = module.exports = exports = new Mongoose({ + [defaultMongooseSymbol]: true +}); diff --git a/node_modules/mongoose/lib/internal.js b/node_modules/mongoose/lib/internal.js new file mode 100644 index 0000000..7e534dc --- /dev/null +++ b/node_modules/mongoose/lib/internal.js @@ -0,0 +1,38 @@ +/*! + * Dependencies + */ + +'use strict'; + +const StateMachine = require('./statemachine'); +const ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore'); + +module.exports = exports = InternalCache; + +function InternalCache() { + this.activePaths = new ActiveRoster; + + // embedded docs + this.ownerDocument = undefined; + this.fullPath = undefined; +} + +InternalCache.prototype.strictMode = undefined; +InternalCache.prototype.selected = undefined; +InternalCache.prototype.shardval = undefined; +InternalCache.prototype.saveError = undefined; +InternalCache.prototype.validationError = undefined; +InternalCache.prototype.adhocPaths = undefined; +InternalCache.prototype.removing = undefined; +InternalCache.prototype.inserting = undefined; +InternalCache.prototype.saving = undefined; +InternalCache.prototype.version = undefined; +InternalCache.prototype._id = undefined; +InternalCache.prototype.populate = undefined; // what we want to populate in this doc +InternalCache.prototype.populated = undefined;// the _ids that have been populated +InternalCache.prototype.wasPopulated = false; // if this doc was the result of a population +InternalCache.prototype.scope = undefined; + +InternalCache.prototype.session = null; +InternalCache.prototype.pathsToScopes = null; +InternalCache.prototype.cachedRequired = null; diff --git a/node_modules/mongoose/lib/model.js b/node_modules/mongoose/lib/model.js new file mode 100644 index 0000000..c7aeb5a --- /dev/null +++ b/node_modules/mongoose/lib/model.js @@ -0,0 +1,4980 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const Aggregate = require('./aggregate'); +const ChangeStream = require('./cursor/ChangeStream'); +const Document = require('./document'); +const DocumentNotFoundError = require('./error/notFound'); +const DivergentArrayError = require('./error/divergentArray'); +const EventEmitter = require('events').EventEmitter; +const MongooseBuffer = require('./types/buffer'); +const MongooseError = require('./error/index'); +const OverwriteModelError = require('./error/overwriteModel'); +const PromiseProvider = require('./promise_provider'); +const Query = require('./query'); +const RemoveOptions = require('./options/removeOptions'); +const SaveOptions = require('./options/saveOptions'); +const Schema = require('./schema'); +const ServerSelectionError = require('./error/serverSelection'); +const ValidationError = require('./error/validation'); +const VersionError = require('./error/version'); +const ParallelSaveError = require('./error/parallelSave'); +const applyQueryMiddleware = require('./helpers/query/applyQueryMiddleware'); +const applyHooks = require('./helpers/model/applyHooks'); +const applyMethods = require('./helpers/model/applyMethods'); +const applyStaticHooks = require('./helpers/model/applyStaticHooks'); +const applyStatics = require('./helpers/model/applyStatics'); +const applyWriteConcern = require('./helpers/schema/applyWriteConcern'); +const assignVals = require('./helpers/populate/assignVals'); +const castBulkWrite = require('./helpers/model/castBulkWrite'); +const createPopulateQueryFilter = require('./helpers/populate/createPopulateQueryFilter'); +const getDefaultBulkwriteResult = require('./helpers/getDefaultBulkwriteResult'); +const discriminator = require('./helpers/model/discriminator'); +const each = require('./helpers/each'); +const get = require('./helpers/get'); +const getConstructorName = require('./helpers/getConstructorName'); +const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue'); +const getModelsMapForPopulate = require('./helpers/populate/getModelsMapForPopulate'); +const immediate = require('./helpers/immediate'); +const internalToObjectOptions = require('./options').internalToObjectOptions; +const isDefaultIdIndex = require('./helpers/indexes/isDefaultIdIndex'); +const isIndexEqual = require('./helpers/indexes/isIndexEqual'); +const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive'); +const leanPopulateMap = require('./helpers/populate/leanPopulateMap'); +const modifiedPaths = require('./helpers/update/modifiedPaths'); +const parallelLimit = require('./helpers/parallelLimit'); +const removeDeselectedForeignField = require('./helpers/populate/removeDeselectedForeignField'); +const util = require('util'); +const utils = require('./utils'); + +const VERSION_WHERE = 1; +const VERSION_INC = 2; +const VERSION_ALL = VERSION_WHERE | VERSION_INC; + +const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol; +const modelCollectionSymbol = Symbol('mongoose#Model#collection'); +const modelDbSymbol = Symbol('mongoose#Model#db'); +const modelSymbol = require('./helpers/symbols').modelSymbol; +const subclassedSymbol = Symbol('mongoose#Model#subclassed'); + +const saveToObjectOptions = Object.assign({}, internalToObjectOptions, { + bson: true +}); + +/** + * A Model is a class that's your primary tool for interacting with MongoDB. + * An instance of a Model is called a [Document](./api.html#Document). + * + * In Mongoose, the term "Model" refers to subclasses of the `mongoose.Model` + * class. You should not use the `mongoose.Model` class directly. The + * [`mongoose.model()`](./api.html#mongoose_Mongoose-model) and + * [`connection.model()`](./api.html#connection_Connection-model) functions + * create subclasses of `mongoose.Model` as shown below. + * + * ####Example: + * + * // `UserModel` is a "Model", a subclass of `mongoose.Model`. + * const UserModel = mongoose.model('User', new Schema({ name: String })); + * + * // You can use a Model to create new documents using `new`: + * const userDoc = new UserModel({ name: 'Foo' }); + * await userDoc.save(); + * + * // You also use a model to create queries: + * const userFromDb = await UserModel.findOne({ name: 'Foo' }); + * + * @param {Object} doc values for initial set + * @param [fields] optional object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projection](./api.html#query_Query-select). + * @param {Boolean} [skipId=false] optional boolean. If true, mongoose doesn't add an `_id` field to the document. + * @inherits Document http://mongoosejs.com/docs/api/document.html + * @event `error`: If listening to this event, 'error' is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model. + * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event. + * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event. + * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed. + * @api public + */ + +function Model(doc, fields, skipId) { + if (fields instanceof Schema) { + throw new TypeError('2nd argument to `Model` must be a POJO or string, ' + + '**not** a schema. Make sure you\'re calling `mongoose.model()`, not ' + + '`mongoose.Model()`.'); + } + Document.call(this, doc, fields, skipId); +} + +/*! + * Inherits from Document. + * + * All Model.prototype features are available on + * top level (non-sub) documents. + */ + +Model.prototype.__proto__ = Document.prototype; +Model.prototype.$isMongooseModelPrototype = true; + +/** + * Connection the model uses. + * + * @api public + * @property db + * @memberOf Model + * @instance + */ + +Model.prototype.db; + +/** + * Collection the model uses. + * + * This property is read-only. Modifying this property is a no-op. + * + * @api public + * @property collection + * @memberOf Model + * @instance + */ + +Model.prototype.collection; + +/** + * Internal collection the model uses. + * + * This property is read-only. Modifying this property is a no-op. + * + * @api private + * @property collection + * @memberOf Model + * @instance + */ + + +Model.prototype.$__collection; + +/** + * The name of the model + * + * @api public + * @property modelName + * @memberOf Model + * @instance + */ + +Model.prototype.modelName; + +/** + * Additional properties to attach to the query when calling `save()` and + * `isNew` is false. + * + * @api public + * @property $where + * @memberOf Model + * @instance + */ + +Model.prototype.$where; + +/** + * If this is a discriminator model, `baseModelName` is the name of + * the base model. + * + * @api public + * @property baseModelName + * @memberOf Model + * @instance + */ + +Model.prototype.baseModelName; + +/** + * Event emitter that reports any errors that occurred. Useful for global error + * handling. + * + * ####Example: + * + * MyModel.events.on('error', err => console.log(err.message)); + * + * // Prints a 'CastError' because of the above handler + * await MyModel.findOne({ _id: 'notanid' }).catch(noop); + * + * @api public + * @fires error whenever any query or model function errors + * @memberOf Model + * @static events + */ + +Model.events; + +/*! + * Compiled middleware for this model. Set in `applyHooks()`. + * + * @api private + * @property _middleware + * @memberOf Model + * @static + */ + +Model._middleware; + +/*! + * ignore + */ + +function _applyCustomWhere(doc, where) { + if (doc.$where == null) { + return; + } + for (const key of Object.keys(doc.$where)) { + where[key] = doc.$where[key]; + } +} + +/*! + * ignore + */ + +Model.prototype.$__handleSave = function(options, callback) { + const _this = this; + let saveOptions = {}; + + applyWriteConcern(this.$__schema, options); + if (typeof options.writeConcern != 'undefined') { + saveOptions.writeConcern = {}; + if ('w' in options.writeConcern) { + saveOptions.writeConcern.w = options.writeConcern.w; + } + if ('j' in options.writeConcern) { + saveOptions.writeConcern.j = options.writeConcern.j; + } + if ('wtimeout' in options.writeConcern) { + saveOptions.writeConcern.wtimeout = options.writeConcern.wtimeout; + } + } else { + if ('w' in options) { + saveOptions.w = options.w; + } + if ('j' in options) { + saveOptions.j = options.j; + } + if ('wtimeout' in options) { + saveOptions.wtimeout = options.wtimeout; + } + } + if ('checkKeys' in options) { + saveOptions.checkKeys = options.checkKeys; + } + const session = this.$session(); + if (!saveOptions.hasOwnProperty('session')) { + saveOptions.session = session; + } + + if (Object.keys(saveOptions).length === 0) { + saveOptions = null; + } + if (this.$isNew) { + // send entire doc + const obj = this.toObject(saveToObjectOptions); + if ((obj || {})._id === void 0) { + // documents must have an _id else mongoose won't know + // what to update later if more changes are made. the user + // wouldn't know what _id was generated by mongodb either + // nor would the ObjectId generated by mongodb necessarily + // match the schema definition. + immediate(function() { + callback(new MongooseError('document must have an _id before saving')); + }); + return; + } + + this.$__version(true, obj); + this[modelCollectionSymbol].insertOne(obj, saveOptions, function(err, ret) { + if (err) { + _setIsNew(_this, true); + + callback(err, null); + return; + } + + callback(null, ret); + }); + this.$__reset(); + _setIsNew(this, false); + // Make it possible to retry the insert + this.$__.inserting = true; + } else { + // Make sure we don't treat it as a new object on error, + // since it already exists + this.$__.inserting = false; + + const delta = this.$__delta(); + if (delta) { + if (delta instanceof MongooseError) { + callback(delta); + return; + } + + const where = this.$__where(delta[0]); + if (where instanceof MongooseError) { + callback(where); + return; + } + + _applyCustomWhere(this, where); + this[modelCollectionSymbol].updateOne(where, delta[1], saveOptions, (err, ret) => { + if (err) { + this.$__undoReset(); + + callback(err); + return; + } + ret.$where = where; + callback(null, ret); + }); + } else { + const optionsWithCustomValues = Object.assign({}, options, saveOptions); + const where = this.$__where(); + if (this.$__schema.options.optimisticConcurrency) { + const key = this.$__schema.options.versionKey; + const val = this.$__getValue(key); + if (val != null) { + where[key] = val; + } + } + this.constructor.exists(where, optionsWithCustomValues) + .then((documentExists) => { + if (!documentExists) { + throw new DocumentNotFoundError(this.$__where(), this.constructor.modelName); + } + + callback(); + }) + .catch(callback); + return; + } + + // store the modified paths before the document is reset + this.$__.modifiedPaths = this.modifiedPaths(); + this.$__reset(); + + _setIsNew(this, false); + } +}; + +/*! + * ignore + */ + +Model.prototype.$__save = function(options, callback) { + this.$__handleSave(options, (error, result) => { + const hooks = this.$__schema.s.hooks; + if (error) { + return hooks.execPost('save:error', this, [this], { error: error }, (error) => { + callback(error, this); + }); + } + let numAffected = 0; + if (get(options, 'safe.w') !== 0 && get(options, 'w') !== 0) { + // Skip checking if write succeeded if writeConcern is set to + // unacknowledged writes, because otherwise `numAffected` will always be 0 + if (result) { + if (Array.isArray(result)) { + numAffected = result.length; + } else if (result.matchedCount != null) { + numAffected = result.matchedCount; + } else { + numAffected = result; + } + } + // was this an update that required a version bump? + if (this.$__.version && !this.$__.inserting) { + const doIncrement = VERSION_INC === (VERSION_INC & this.$__.version); + this.$__.version = undefined; + const key = this.$__schema.options.versionKey; + const version = this.$__getValue(key) || 0; + if (numAffected <= 0) { + // the update failed. pass an error back + this.$__undoReset(); + const err = this.$__.$versionError || + new VersionError(this, version, this.$__.modifiedPaths); + return callback(err); + } + + // increment version if was successful + if (doIncrement) { + this.$__setValue(key, version + 1); + } + } + if (result != null && numAffected <= 0) { + this.$__undoReset(); + error = new DocumentNotFoundError(result.$where, + this.constructor.modelName, numAffected, result); + return hooks.execPost('save:error', this, [this], { error: error }, (error) => { + callback(error, this); + }); + } + } + this.$__.saving = undefined; + this.$__.savedState = {}; + this.$emit('save', this, numAffected); + this.constructor.emit('save', this, numAffected); + callback(null, this); + }); +}; + +/*! + * ignore + */ + +function generateVersionError(doc, modifiedPaths) { + const key = doc.$__schema.options.versionKey; + if (!key) { + return null; + } + const version = doc.$__getValue(key) || 0; + return new VersionError(doc, version, modifiedPaths); +} + +/** + * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, + * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation with just the modified paths if `isNew` is `false`. + * + * ####Example: + * + * product.sold = Date.now(); + * product = await product.save(); + * + * If save is successful, the returned promise will fulfill with the document + * saved. + * + * ####Example: + * + * const newProduct = await product.save(); + * newProduct === product; // true + * + * @param {Object} [options] options optional options + * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). + * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. + * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. + * @param {Boolean} [options.validateModifiedOnly=false] if `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. + * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) + * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) + * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). + * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) + * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. + * @param {Function} [fn] optional callback + * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). + * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. + * @api public + * @see middleware http://mongoosejs.com/docs/middleware.html + */ + +Model.prototype.save = function(options, fn) { + let parallelSave; + this.$op = 'save'; + + if (this.$__.saving) { + parallelSave = new ParallelSaveError(this); + } else { + this.$__.saving = new ParallelSaveError(this); + } + + if (typeof options === 'function') { + fn = options; + options = undefined; + } + + options = new SaveOptions(options); + if (options.hasOwnProperty('session')) { + this.$session(options.session); + } + this.$__.$versionError = generateVersionError(this, this.modifiedPaths()); + + fn = this.constructor.$handleCallbackError(fn); + return this.constructor.db.base._promiseOrCallback(fn, cb => { + cb = this.constructor.$wrapCallback(cb); + + if (parallelSave) { + this.$__handleReject(parallelSave); + return cb(parallelSave); + } + + this.$__.saveOptions = options; + + this.$__save(options, error => { + this.$__.saving = undefined; + delete this.$__.saveOptions; + delete this.$__.$versionError; + this.$op = null; + + if (error) { + this.$__handleReject(error); + return cb(error); + } + cb(null, this); + }); + }, this.constructor.events); +}; + +Model.prototype.$save = Model.prototype.save; + +/*! + * Determines whether versioning should be skipped for the given path + * + * @param {Document} self + * @param {String} path + * @return {Boolean} true if versioning should be skipped for the given path + */ +function shouldSkipVersioning(self, path) { + const skipVersioning = self.$__schema.options.skipVersioning; + if (!skipVersioning) return false; + + // Remove any array indexes from the path + path = path.replace(/\.\d+\./, '.'); + + return skipVersioning[path]; +} + +/*! + * Apply the operation to the delta (update) clause as + * well as track versioning for our where clause. + * + * @param {Document} self + * @param {Object} where + * @param {Object} delta + * @param {Object} data + * @param {Mixed} val + * @param {String} [operation] + */ + +function operand(self, where, delta, data, val, op) { + // delta + op || (op = '$set'); + if (!delta[op]) delta[op] = {}; + delta[op][data.path] = val; + // disabled versioning? + if (self.$__schema.options.versionKey === false) return; + + // path excluded from versioning? + if (shouldSkipVersioning(self, data.path)) return; + + // already marked for versioning? + if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return; + + if (self.$__schema.options.optimisticConcurrency) { + self.$__.version = VERSION_ALL; + return; + } + + switch (op) { + case '$set': + case '$unset': + case '$pop': + case '$pull': + case '$pullAll': + case '$push': + case '$addToSet': + break; + default: + // nothing to do + return; + } + + // ensure updates sent with positional notation are + // editing the correct array element. + // only increment the version if an array position changes. + // modifying elements of an array is ok if position does not change. + if (op === '$push' || op === '$addToSet' || op === '$pullAll' || op === '$pull') { + self.$__.version = VERSION_INC; + } else if (/^\$p/.test(op)) { + // potentially changing array positions + increment.call(self); + } else if (Array.isArray(val)) { + // $set an array + increment.call(self); + } else if (/\.\d+\.|\.\d+$/.test(data.path)) { + // now handling $set, $unset + // subpath of array + self.$__.version = VERSION_WHERE; + } +} + +/*! + * Compiles an update and where clause for a `val` with _atomics. + * + * @param {Document} self + * @param {Object} where + * @param {Object} delta + * @param {Object} data + * @param {Array} value + */ + +function handleAtomics(self, where, delta, data, value) { + if (delta.$set && delta.$set[data.path]) { + // $set has precedence over other atomics + return; + } + + if (typeof value.$__getAtomics === 'function') { + value.$__getAtomics().forEach(function(atomic) { + const op = atomic[0]; + const val = atomic[1]; + operand(self, where, delta, data, val, op); + }); + return; + } + + // legacy support for plugins + + const atomics = value[arrayAtomicsSymbol]; + const ops = Object.keys(atomics); + let i = ops.length; + let val; + let op; + + if (i === 0) { + // $set + + if (utils.isMongooseObject(value)) { + value = value.toObject({ depopulate: 1, _isNested: true }); + } else if (value.valueOf) { + value = value.valueOf(); + } + + return operand(self, where, delta, data, value); + } + + function iter(mem) { + return utils.isMongooseObject(mem) + ? mem.toObject({ depopulate: 1, _isNested: true }) + : mem; + } + + while (i--) { + op = ops[i]; + val = atomics[op]; + + if (utils.isMongooseObject(val)) { + val = val.toObject({ depopulate: true, transform: false, _isNested: true }); + } else if (Array.isArray(val)) { + val = val.map(iter); + } else if (val.valueOf) { + val = val.valueOf(); + } + + if (op === '$addToSet') { + val = { $each: val }; + } + + operand(self, where, delta, data, val, op); + } +} + +/** + * Produces a special query document of the modified properties used in updates. + * + * @api private + * @method $__delta + * @memberOf Model + * @instance + */ + +Model.prototype.$__delta = function() { + const dirty = this.$__dirty(); + if (!dirty.length && VERSION_ALL !== this.$__.version) { + return; + } + const where = {}; + const delta = {}; + const len = dirty.length; + const divergent = []; + let d = 0; + + where._id = this._doc._id; + // If `_id` is an object, need to depopulate, but also need to be careful + // because `_id` can technically be null (see gh-6406) + if (get(where, '_id.$__', null) != null) { + where._id = where._id.toObject({ transform: false, depopulate: true }); + } + for (; d < len; ++d) { + const data = dirty[d]; + let value = data.value; + const match = checkDivergentArray(this, data.path, value); + if (match) { + divergent.push(match); + continue; + } + + const pop = this.$populated(data.path, true); + if (!pop && this.$__.selected) { + // If any array was selected using an $elemMatch projection, we alter the path and where clause + // NOTE: MongoDB only supports projected $elemMatch on top level array. + const pathSplit = data.path.split('.'); + const top = pathSplit[0]; + if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) { + // If the selected array entry was modified + if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === 'undefined') { + where[top] = this.$__.selected[top]; + pathSplit[1] = '$'; + data.path = pathSplit.join('.'); + } + // if the selected array was modified in any other way throw an error + else { + divergent.push(data.path); + continue; + } + } + } + + if (divergent.length) continue; + if (value === undefined) { + operand(this, where, delta, data, 1, '$unset'); + } else if (value === null) { + operand(this, where, delta, data, null); + } else if (value.isMongooseArray && value.$path() && value[arrayAtomicsSymbol]) { + // arrays and other custom types (support plugins etc) + handleAtomics(this, where, delta, data, value); + } else if (value[MongooseBuffer.pathSymbol] && Buffer.isBuffer(value)) { + // MongooseBuffer + value = value.toObject(); + operand(this, where, delta, data, value); + } else { + value = utils.clone(value, { + depopulate: true, + transform: false, + virtuals: false, + getters: false, + _isNested: true + }); + operand(this, where, delta, data, value); + } + } + + if (divergent.length) { + return new DivergentArrayError(divergent); + } + + if (this.$__.version) { + this.$__version(where, delta); + } + return [where, delta]; +}; + +/*! + * Determine if array was populated with some form of filter and is now + * being updated in a manner which could overwrite data unintentionally. + * + * @see https://github.com/Automattic/mongoose/issues/1334 + * @param {Document} doc + * @param {String} path + * @return {String|undefined} + */ + +function checkDivergentArray(doc, path, array) { + // see if we populated this path + const pop = doc.$populated(path, true); + + if (!pop && doc.$__.selected) { + // If any array was selected using an $elemMatch projection, we deny the update. + // NOTE: MongoDB only supports projected $elemMatch on top level array. + const top = path.split('.')[0]; + if (doc.$__.selected[top + '.$']) { + return top; + } + } + + if (!(pop && array && array.isMongooseArray)) return; + + // If the array was populated using options that prevented all + // documents from being returned (match, skip, limit) or they + // deselected the _id field, $pop and $set of the array are + // not safe operations. If _id was deselected, we do not know + // how to remove elements. $pop will pop off the _id from the end + // of the array in the db which is not guaranteed to be the + // same as the last element we have here. $set of the entire array + // would be similarily destructive as we never received all + // elements of the array and potentially would overwrite data. + const check = pop.options.match || + pop.options.options && utils.object.hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted + pop.options.options && pop.options.options.skip || // 0 is permitted + pop.options.select && // deselected _id? + (pop.options.select._id === 0 || + /\s?-_id\s?/.test(pop.options.select)); + + if (check) { + const atomics = array[arrayAtomicsSymbol]; + if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) { + return path; + } + } +} + +/** + * Appends versioning to the where and update clauses. + * + * @api private + * @method $__version + * @memberOf Model + * @instance + */ + +Model.prototype.$__version = function(where, delta) { + const key = this.$__schema.options.versionKey; + + if (where === true) { + // this is an insert + if (key) { + this.$__setValue(key, delta[key] = 0); + } + return; + } + + // updates + + // only apply versioning if our versionKey was selected. else + // there is no way to select the correct version. we could fail + // fast here and force them to include the versionKey but + // thats a bit intrusive. can we do this automatically? + if (!this.$__isSelected(key)) { + return; + } + + // $push $addToSet don't need the where clause set + if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { + const value = this.$__getValue(key); + if (value != null) where[key] = value; + } + + if (VERSION_INC === (VERSION_INC & this.$__.version)) { + if (get(delta.$set, key, null) != null) { + // Version key is getting set, means we'll increment the doc's version + // after a successful save, so we should set the incremented version so + // future saves don't fail (gh-5779) + ++delta.$set[key]; + } else { + delta.$inc = delta.$inc || {}; + delta.$inc[key] = 1; + } + } +}; + +/** + * Signal that we desire an increment of this documents version. + * + * ####Example: + * + * Model.findById(id, function (err, doc) { + * doc.increment(); + * doc.save(function (err) { .. }) + * }) + * + * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey + * @api public + */ + +function increment() { + this.$__.version = VERSION_ALL; + return this; +} + +Model.prototype.increment = increment; + +/** + * Returns a query object + * + * @api private + * @method $__where + * @memberOf Model + * @instance + */ + +Model.prototype.$__where = function _where(where) { + where || (where = {}); + + if (!where._id) { + where._id = this._doc._id; + } + + if (this._doc._id === void 0) { + return new MongooseError('No _id found on document!'); + } + + return where; +}; + +/** + * Removes this document from the db. + * + * ####Example: + * product.remove(function (err, product) { + * if (err) return handleError(err); + * Product.findById(product._id, function (err, product) { + * console.log(product) // null + * }) + * }) + * + * + * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recieve errors + * + * ####Example: + * product.remove().then(function (product) { + * ... + * }).catch(function (err) { + * assert.ok(err) + * }) + * + * @param {Object} [options] + * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). + * @param {function(err,product)} [fn] optional callback + * @return {Promise} Promise + * @api public + */ + +Model.prototype.remove = function remove(options, fn) { + if (typeof options === 'function') { + fn = options; + options = undefined; + } + + options = new RemoveOptions(options); + if (options.hasOwnProperty('session')) { + this.$session(options.session); + } + this.$op = 'remove'; + + fn = this.constructor.$handleCallbackError(fn); + + return this.constructor.db.base._promiseOrCallback(fn, cb => { + cb = this.constructor.$wrapCallback(cb); + this.$__remove(options, (err, res) => { + this.$op = null; + cb(err, res); + }); + }, this.constructor.events); +}; + +/*! + * Alias for remove + */ + +Model.prototype.$remove = Model.prototype.remove; +Model.prototype.delete = Model.prototype.remove; + +/** + * Removes this document from the db. Equivalent to `.remove()`. + * + * ####Example: + * product = await product.deleteOne(); + * await Product.findById(product._id); // null + * + * @param {function(err,product)} [fn] optional callback + * @return {Promise} Promise + * @api public + */ + +Model.prototype.deleteOne = function deleteOne(options, fn) { + if (typeof options === 'function') { + fn = options; + options = undefined; + } + + if (!options) { + options = {}; + } + + fn = this.constructor.$handleCallbackError(fn); + + return this.constructor.db.base._promiseOrCallback(fn, cb => { + cb = this.constructor.$wrapCallback(cb); + this.$__deleteOne(options, cb); + }, this.constructor.events); +}; + +/*! + * ignore + */ + +Model.prototype.$__remove = function $__remove(options, cb) { + if (this.$__.isDeleted) { + return immediate(() => cb(null, this)); + } + + const where = this.$__where(); + if (where instanceof MongooseError) { + return cb(where); + } + + _applyCustomWhere(this, where); + + const session = this.$session(); + if (!options.hasOwnProperty('session')) { + options.session = session; + } + + this[modelCollectionSymbol].deleteOne(where, options, err => { + if (!err) { + this.$__.isDeleted = true; + this.$emit('remove', this); + this.constructor.emit('remove', this); + return cb(null, this); + } + this.$__.isDeleted = false; + cb(err); + }); +}; + +/*! + * ignore + */ + +Model.prototype.$__deleteOne = Model.prototype.$__remove; + +/** + * Returns another Model instance. + * + * ####Example: + * + * const doc = new Tank; + * doc.model('User').findById(id, callback); + * + * @param {String} name model name + * @api public + */ + +Model.prototype.model = function model(name) { + return this[modelDbSymbol].model(name); +}; + +/** + * Returns true if at least one document exists in the database that matches + * the given `filter`, and false otherwise. + * + * Under the hood, `MyModel.exists({ answer: 42 })` is equivalent to + * `MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean()` + * + * ####Example: + * await Character.deleteMany({}); + * await Character.create({ name: 'Jean-Luc Picard' }); + * + * await Character.exists({ name: /picard/i }); // { _id: ... } + * await Character.exists({ name: /riker/i }); // null + * + * This function triggers the following middleware. + * + * - `findOne()` + * + * @param {Object} filter + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] callback + * @return {Query} + */ + +Model.exists = function exists(filter, options, callback) { + _checkContext(this, 'exists'); + if (typeof options === 'function') { + callback = options; + options = null; + } + + const query = this.findOne(filter). + select({ _id: 1 }). + lean(). + setOptions(options); + + if (typeof callback === 'function') { + return query.exec(callback); + } + options = options || {}; + if (!options.explain) { + return query.then(doc => !!doc); + } + + return query; +}; + +/** + * Adds a discriminator type. + * + * ####Example: + * + * function BaseSchema() { + * Schema.apply(this, arguments); + * + * this.add({ + * name: String, + * createdAt: Date + * }); + * } + * util.inherits(BaseSchema, Schema); + * + * const PersonSchema = new BaseSchema(); + * const BossSchema = new BaseSchema({ department: String }); + * + * const Person = mongoose.model('Person', PersonSchema); + * const Boss = Person.discriminator('Boss', BossSchema); + * new Boss().__t; // "Boss". `__t` is the default `discriminatorKey` + * + * const employeeSchema = new Schema({ boss: ObjectId }); + * const Employee = Person.discriminator('Employee', employeeSchema, 'staff'); + * new Employee().__t; // "staff" because of 3rd argument above + * + * @param {String} name discriminator model name + * @param {Schema} schema discriminator model schema + * @param {Object|String} [options] If string, same as `options.value`. + * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. + * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning. + * @return {Model} The newly created discriminator model + * @api public + */ + +Model.discriminator = function(name, schema, options) { + let model; + if (typeof name === 'function') { + model = name; + name = utils.getFunctionName(model); + if (!(model.prototype instanceof Model)) { + throw new MongooseError('The provided class ' + name + ' must extend Model'); + } + } + + options = options || {}; + const value = utils.isPOJO(options) ? options.value : options; + const clone = get(options, 'clone', true); + + _checkContext(this, 'discriminator'); + + if (utils.isObject(schema) && !schema.instanceOfSchema) { + schema = new Schema(schema); + } + if (schema instanceof Schema && clone) { + schema = schema.clone(); + } + + schema = discriminator(this, name, schema, value, true); + if (this.db.models[name]) { + throw new OverwriteModelError(name); + } + + schema.$isRootDiscriminator = true; + schema.$globalPluginsApplied = true; + + model = this.db.model(model || name, schema, this.$__collection.name); + this.discriminators[name] = model; + const d = this.discriminators[name]; + d.prototype.__proto__ = this.prototype; + Object.defineProperty(d, 'baseModelName', { + value: this.modelName, + configurable: true, + writable: false + }); + + // apply methods and statics + applyMethods(d, schema); + applyStatics(d, schema); + + if (this[subclassedSymbol] != null) { + for (const submodel of this[subclassedSymbol]) { + submodel.discriminators = submodel.discriminators || {}; + submodel.discriminators[name] = + model.__subclass(model.db, schema, submodel.collection.name); + } + } + + return d; +}; + +/*! + * Make sure `this` is a model + */ + +function _checkContext(ctx, fnName) { + // Check context, because it is easy to mistakenly type + // `new Model.discriminator()` and get an incomprehensible error + if (ctx == null || ctx === global) { + throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' + + 'model as `this`. Make sure you are calling `MyModel.' + fnName + '()` ' + + 'where `MyModel` is a Mongoose model.'); + } else if (ctx[modelSymbol] == null) { + throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' + + 'model as `this`. Make sure you are not calling ' + + '`new Model.' + fnName + '()`'); + } +} + +// Model (class) features + +/*! + * Give the constructor the ability to emit events. + */ + +for (const i in EventEmitter.prototype) { + Model[i] = EventEmitter.prototype[i]; +} + +/** + * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/), + * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off. + * + * Mongoose calls this function automatically when a model is created using + * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or + * [`connection.model()`](/docs/api.html#connection_Connection-model), so you + * don't need to call it. This function is also idempotent, so you may call it + * to get back a promise that will resolve when your indexes are finished + * building as an alternative to [`MyModel.on('index')`](/docs/guide.html#indexes) + * + * ####Example: + * + * const eventSchema = new Schema({ thing: { type: 'string', unique: true }}) + * // This calls `Event.init()` implicitly, so you don't need to call + * // `Event.init()` on your own. + * const Event = mongoose.model('Event', eventSchema); + * + * Event.init().then(function(Event) { + * // You can also use `Event.on('index')` if you prefer event emitters + * // over promises. + * console.log('Indexes are done building!'); + * }); + * + * @api public + * @param {Function} [callback] + * @returns {Promise} + */ + +Model.init = function init(callback) { + _checkContext(this, 'init'); + + this.schema.emit('init', this); + + if (this.$init != null) { + if (callback) { + this.$init.then(() => callback(), err => callback(err)); + return null; + } + return this.$init; + } + + const Promise = PromiseProvider.get(); + const autoIndex = utils.getOption('autoIndex', + this.schema.options, this.db.config, this.db.base.options); + const autoCreate = utils.getOption('autoCreate', + this.schema.options, this.db.config, this.db.base.options); + + const _ensureIndexes = autoIndex ? + cb => this.ensureIndexes({ _automatic: true }, cb) : + cb => cb(); + const _createCollection = autoCreate ? + cb => this.createCollection({}, cb) : + cb => cb(); + + this.$init = new Promise((resolve, reject) => { + _createCollection(error => { + if (error) { + return reject(error); + } + _ensureIndexes(error => { + if (error) { + return reject(error); + } + resolve(this); + }); + }); + }); + + if (callback) { + this.$init.then(() => callback(), err => callback(err)); + this.$caught = true; + return null; + } else { + const _catch = this.$init.catch; + const _this = this; + this.$init.catch = function() { + this.$caught = true; + return _catch.apply(_this.$init, arguments); + }; + } + + return this.$init; +}; + + +/** + * Create the collection for this model. By default, if no indexes are specified, + * mongoose will not create the collection for the model until any documents are + * created. Use this method to create the collection explicitly. + * + * Note 1: You may need to call this before starting a transaction + * See https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations + * + * Note 2: You don't have to call this if your schema contains index or unique field. + * In that case, just use `Model.init()` + * + * ####Example: + * + * const userSchema = new Schema({ name: String }) + * const User = mongoose.model('User', userSchema); + * + * User.createCollection().then(function(collection) { + * console.log('Collection is created!'); + * }); + * + * @api public + * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection) + * @param {Function} [callback] + * @returns {Promise} + */ + +Model.createCollection = function createCollection(options, callback) { + _checkContext(this, 'createCollection'); + + if (typeof options === 'string') { + throw new MongooseError('You can\'t specify a new collection name in Model.createCollection.' + + 'This is not like Connection.createCollection. Only options are accepted here.'); + } else if (typeof options === 'function') { + callback = options; + options = void 0; + } + + const schemaCollation = get(this, 'schema.options.collation', null); + if (schemaCollation != null) { + options = Object.assign({ collation: schemaCollation }, options); + } + const capped = get(this, 'schema.options.capped'); + if (capped) { + options = Object.assign({ capped: true }, capped, options); + } + + callback = this.$handleCallbackError(callback); + + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); + + this.db.createCollection(this.$__collection.collectionName, options, utils.tick((err) => { + if (err != null && (err.name !== 'MongoServerError' || err.code !== 48)) { + return cb(err); + } + this.$__collection = this.db.collection(this.$__collection.collectionName, options); + cb(null, this.$__collection); + })); + }, this.events); +}; + +/** + * Makes the indexes in MongoDB match the indexes defined in this model's + * schema. This function will drop any indexes that are not defined in + * the model's schema except the `_id` index, and build any indexes that + * are in your schema but not in MongoDB. + * + * See the [introductory blog post](http://thecodebarbarian.com/whats-new-in-mongoose-5-2-syncindexes) + * for more information. + * + * ####Example: + * + * const schema = new Schema({ name: { type: String, unique: true } }); + * const Customer = mongoose.model('Customer', schema); + * await Customer.collection.createIndex({ age: 1 }); // Index is not in schema + * // Will drop the 'age' index and create an index on `name` + * await Customer.syncIndexes(); + * + * @param {Object} [options] options to pass to `ensureIndexes()` + * @param {Boolean} [options.background=null] if specified, overrides each index's `background` property + * @param {Function} [callback] optional callback + * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. + * @api public + */ + +Model.syncIndexes = function syncIndexes(options, callback) { + _checkContext(this, 'syncIndexes'); + + callback = this.$handleCallbackError(callback); + + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); + + this.createCollection(err => { + if (err != null && (err.name !== 'MongoServerError' || err.code !== 48)) { + return cb(err); + } + this.cleanIndexes((err, dropped) => { + if (err != null) { + return cb(err); + } + this.createIndexes(options, err => { + if (err != null) { + return cb(err); + } + cb(null, dropped); + }); + }); + }); + }, this.events); +}; + +/** + * Does a dry-run of Model.syncIndexes(), meaning that + * the result of this function would be the result of + * Model.syncIndexes(). + * + * @param {Object} options not used at all. + * @param {Function} callback optional callback + * @returns {Promise} which containts an object, {toDrop, toCreate}, which + * are indexes that would be dropped in mongodb and indexes that would be created in mongodb. + */ + +Model.diffIndexes = function diffIndexes(options, callback) { + const toDrop = []; + const toCreate = []; + callback = this.$handleCallbackError(callback); + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); + this.listIndexes((err, indexes) => { + if (indexes === undefined) { + indexes = []; + } + const schemaIndexes = this.schema.indexes(); + // Iterate through the indexes created in mongodb and + // compare against the indexes in the schema. + for (const index of indexes) { + let found = false; + // Never try to drop `_id` index, MongoDB server doesn't allow it + if (isDefaultIdIndex(index)) { + continue; + } + + for (const schemaIndex of schemaIndexes) { + const key = schemaIndex[0]; + const options = _decorateDiscriminatorIndexOptions(this, + utils.clone(schemaIndex[1])); + if (isIndexEqual(key, options, index)) { + found = true; + } + } + + if (!found) { + toDrop.push(index.name); + } + } + // Iterate through the indexes created on the schema and + // compare against the indexes in mongodb. + for (const schemaIndex of schemaIndexes) { + const key = schemaIndex[0]; + let found = false; + const options = _decorateDiscriminatorIndexOptions(this, + utils.clone(schemaIndex[1])); + for (const index of indexes) { + if (isDefaultIdIndex(index)) { + continue; + } + if (isIndexEqual(key, options, index)) { + found = true; + } + } + if (!found) { + toCreate.push(key); + } + } + cb(null, { toDrop, toCreate }); + }); + }); +}; + +/** + * Deletes all indexes that aren't defined in this model's schema. Used by + * `syncIndexes()`. + * + * The returned promise resolves to a list of the dropped indexes' names as an array + * + * @param {Function} [callback] optional callback + * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. + * @api public + */ + +Model.cleanIndexes = function cleanIndexes(callback) { + _checkContext(this, 'cleanIndexes'); + + callback = this.$handleCallbackError(callback); + + return this.db.base._promiseOrCallback(callback, cb => { + const collection = this.$__collection; + + this.listIndexes((err, indexes) => { + if (err != null) { + return cb(err); + } + + const schemaIndexes = this.schema.indexes(); + const toDrop = []; + + for (const index of indexes) { + let found = false; + // Never try to drop `_id` index, MongoDB server doesn't allow it + if (isDefaultIdIndex(index)) { + continue; + } + + for (const schemaIndex of schemaIndexes) { + const key = schemaIndex[0]; + const options = _decorateDiscriminatorIndexOptions(this, + utils.clone(schemaIndex[1])); + if (isIndexEqual(key, options, index)) { + found = true; + } + } + + if (!found) { + toDrop.push(index.name); + } + } + + if (toDrop.length === 0) { + return cb(null, []); + } + + dropIndexes(toDrop, cb); + }); + + function dropIndexes(toDrop, cb) { + let remaining = toDrop.length; + let error = false; + toDrop.forEach(indexName => { + collection.dropIndex(indexName, err => { + if (err != null) { + error = true; + return cb(err); + } + if (!error) { + --remaining || cb(null, toDrop); + } + }); + }); + } + }); +}; + +/** + * Lists the indexes currently defined in MongoDB. This may or may not be + * the same as the indexes defined in your schema depending on whether you + * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you + * build indexes manually. + * + * @param {Function} [cb] optional callback + * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. + * @api public + */ + +Model.listIndexes = function init(callback) { + _checkContext(this, 'listIndexes'); + + const _listIndexes = cb => { + this.$__collection.listIndexes().toArray(cb); + }; + + callback = this.$handleCallbackError(callback); + + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); + + // Buffering + if (this.$__collection.buffer) { + this.$__collection.addQueue(_listIndexes, [cb]); + } else { + _listIndexes(cb); + } + }, this.events); +}; + +/** + * Sends `createIndex` commands to mongo for each index declared in the schema. + * The `createIndex` commands are sent in series. + * + * ####Example: + * + * Event.ensureIndexes(function (err) { + * if (err) return handleError(err); + * }); + * + * After completion, an `index` event is emitted on this `Model` passing an error if one occurred. + * + * ####Example: + * + * const eventSchema = new Schema({ thing: { type: 'string', unique: true }}) + * const Event = mongoose.model('Event', eventSchema); + * + * Event.on('index', function (err) { + * if (err) console.error(err); // error occurred during index creation + * }) + * + * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._ + * + * @param {Object} [options] internal options + * @param {Function} [cb] optional callback + * @return {Promise} + * @api public + */ + +Model.ensureIndexes = function ensureIndexes(options, callback) { + _checkContext(this, 'ensureIndexes'); + + if (typeof options === 'function') { + callback = options; + options = null; + } + + callback = this.$handleCallbackError(callback); + + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); + + _ensureIndexes(this, options || {}, error => { + if (error) { + return cb(error); + } + cb(null); + }); + }, this.events); +}; + +/** + * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex) + * function. + * + * @param {Object} [options] internal options + * @param {Function} [cb] optional callback + * @return {Promise} + * @api public + */ + +Model.createIndexes = function createIndexes(options, callback) { + _checkContext(this, 'createIndexes'); + + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + options.createIndex = true; + return this.ensureIndexes(options, callback); +}; + +/*! + * ignore + */ + +function _ensureIndexes(model, options, callback) { + const indexes = model.schema.indexes(); + let indexError; + + options = options || {}; + const done = function(err) { + if (err && !model.$caught) { + model.emit('error', err); + } + model.emit('index', err || indexError); + callback && callback(err || indexError); + }; + + for (const index of indexes) { + if (isDefaultIdIndex(index)) { + utils.warn('mongoose: Cannot specify a custom index on `_id` for ' + + 'model name "' + model.modelName + '", ' + + 'MongoDB does not allow overwriting the default `_id` index. See ' + + 'http://bit.ly/mongodb-id-index'); + } + } + + if (!indexes.length) { + immediate(function() { + done(); + }); + return; + } + // Indexes are created one-by-one to support how MongoDB < 2.4 deals + // with background indexes. + + const indexSingleDone = function(err, fields, options, name) { + model.emit('index-single-done', err, fields, options, name); + }; + const indexSingleStart = function(fields, options) { + model.emit('index-single-start', fields, options); + }; + + const baseSchema = model.schema._baseSchema; + const baseSchemaIndexes = baseSchema ? baseSchema.indexes() : []; + + const create = function() { + if (options._automatic) { + if (model.schema.options.autoIndex === false || + (model.schema.options.autoIndex == null && model.db.config.autoIndex === false)) { + return done(); + } + } + + const index = indexes.shift(); + if (!index) { + return done(); + } + if (options._automatic && index[1]._autoIndex === false) { + return create(); + } + + if (baseSchemaIndexes.find(i => utils.deepEqual(i, index))) { + return create(); + } + + const indexFields = utils.clone(index[0]); + const indexOptions = utils.clone(index[1]); + let isTextIndex = false; + for (const key of Object.keys(indexFields)) { + if (indexFields[key] === 'text') { + isTextIndex = true; + } + } + delete indexOptions._autoIndex; + _decorateDiscriminatorIndexOptions(model, indexOptions); + applyWriteConcern(model.schema, indexOptions); + + indexSingleStart(indexFields, options); + + if ('background' in options) { + indexOptions.background = options.background; + } + if (model.schema.options.hasOwnProperty('collation') && + !indexOptions.hasOwnProperty('collation') && + !isTextIndex) { + indexOptions.collation = model.schema.options.collation; + } + + model.collection.createIndex(indexFields, indexOptions, utils.tick(function(err, name) { + indexSingleDone(err, indexFields, indexOptions, name); + if (err) { + if (!indexError) { + indexError = err; + } + if (!model.$caught) { + model.emit('error', err); + } + } + create(); + })); + }; + + immediate(function() { + // If buffering is off, do this manually. + if (options._automatic && !model.collection.collection) { + model.collection.addQueue(create, []); + } else { + create(); + } + }); +} + +function _decorateDiscriminatorIndexOptions(model, indexOptions) { + // If the model is a discriminator and it has a unique index, add a + // partialFilterExpression by default so the unique index will only apply + // to that discriminator. + if (model.baseModelName != null && + !('partialFilterExpression' in indexOptions) && + !('sparse' in indexOptions)) { + const value = ( + model.schema.discriminatorMapping && + model.schema.discriminatorMapping.value + ) || model.modelName; + const discriminatorKey = model.schema.options.discriminatorKey; + + indexOptions.partialFilterExpression = { [discriminatorKey]: value }; + } + return indexOptions; +} + +/** + * Schema the model uses. + * + * @property schema + * @receiver Model + * @api public + * @memberOf Model + */ + +Model.schema; + +/*! + * Connection instance the model uses. + * + * @property db + * @api public + * @memberOf Model + */ + +Model.db; + +/*! + * Collection the model uses. + * + * @property collection + * @api public + * @memberOf Model + */ + +Model.collection; + +/** + * Internal collection the model uses. + * + * @property collection + * @api private + * @memberOf Model + */ +Model.$__collection; + +/** + * Base Mongoose instance the model uses. + * + * @property base + * @api public + * @memberOf Model + */ + +Model.base; + +/** + * Registered discriminators for this model. + * + * @property discriminators + * @api public + * @memberOf Model + */ + +Model.discriminators; + +/** + * Translate any aliases fields/conditions so the final query or document object is pure + * + * ####Example: + * + * Character + * .find(Character.translateAliases({ + * '名': 'Eddard Stark' // Alias for 'name' + * }) + * .exec(function(err, characters) {}) + * + * ####Note: + * Only translate arguments of object type anything else is returned raw + * + * @param {Object} raw fields/conditions that may contain aliased keys + * @return {Object} the translated 'pure' fields/conditions + */ +Model.translateAliases = function translateAliases(fields) { + _checkContext(this, 'translateAliases'); + + const translate = (key, value) => { + let alias; + const translated = []; + const fieldKeys = key.split('.'); + let currentSchema = this.schema; + for (const i in fieldKeys) { + const name = fieldKeys[i]; + if (currentSchema && currentSchema.aliases[name]) { + alias = currentSchema.aliases[name]; + // Alias found, + translated.push(alias); + } else { + alias = name; + // Alias not found, so treat as un-aliased key + translated.push(name); + } + + // Check if aliased path is a schema + if (currentSchema && currentSchema.paths[alias]) { + currentSchema = currentSchema.paths[alias].schema; + } + else + currentSchema = null; + } + + const translatedKey = translated.join('.'); + if (fields instanceof Map) + fields.set(translatedKey, value); + else + fields[translatedKey] = value; + + if (translatedKey !== key) { + // We'll be using the translated key instead + if (fields instanceof Map) { + // Delete from map + fields.delete(key); + } else { + // Delete from object + delete fields[key]; // We'll be using the translated key instead + } + } + return fields; + }; + + if (typeof fields === 'object') { + // Fields is an object (query conditions or document fields) + if (fields instanceof Map) { + // A Map was supplied + for (const field of new Map(fields)) { + fields = translate(field[0], field[1]); + } + } else { + // Infer a regular object was supplied + for (const key of Object.keys(fields)) { + fields = translate(key, fields[key]); + if (key[0] === '$') { + if (Array.isArray(fields[key])) { + for (const i in fields[key]) { + // Recursively translate nested queries + fields[key][i] = this.translateAliases(fields[key][i]); + } + } + } + } + } + + return fields; + } else { + // Don't know typeof fields + return fields; + } +}; + +/** + * Removes all documents that match `conditions` from the collection. + * To remove just the first document that matches `conditions`, set the `single` + * option to true. + * + * This method is deprecated. See [Deprecation Warnings](../deprecations.html#remove) for details. + * + * ####Example: + * + * const res = await Character.remove({ name: 'Eddard Stark' }); + * res.deletedCount; // Number of documents removed + * + * ####Note: + * + * This method sends a remove command directly to MongoDB, no Mongoose documents + * are involved. Because no Mongoose documents are involved, Mongoose does + * not execute [document middleware](/docs/middleware.html#types-of-middleware). + * + * @deprecated + * @param {Object} conditions + * @param {Object} [options] + * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.remove = function remove(conditions, options, callback) { + _checkContext(this, 'remove'); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } + + // get the mongodb collection object + const mq = new this.Query({}, {}, this, this.$__collection); + mq.setOptions(options); + + callback = this.$handleCallbackError(callback); + + return mq.remove(conditions, callback); +}; + +/** + * Deletes the first document that matches `conditions` from the collection. + * Behaves like `remove()`, but deletes at most one document regardless of the + * `single` option. + * + * ####Example: + * + * await Character.deleteOne({ name: 'Eddard Stark' }); + * + * ####Note: + * + * This function triggers `deleteOne` query hooks. Read the + * [middleware docs](/docs/middleware.html#naming) to learn more. + * + * @param {Object} conditions + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.deleteOne = function deleteOne(conditions, options, callback) { + _checkContext(this, 'deleteOne'); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + options = null; + } + else if (typeof options === 'function') { + callback = options; + options = null; + } + + const mq = new this.Query({}, {}, this, this.$__collection); + mq.setOptions(options); + + callback = this.$handleCallbackError(callback); + + return mq.deleteOne(conditions, callback); +}; + +/** + * Deletes all of the documents that match `conditions` from the collection. + * Behaves like `remove()`, but deletes all documents that match `conditions` + * regardless of the `single` option. + * + * ####Example: + * + * await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); + * + * ####Note: + * + * This function triggers `deleteMany` query hooks. Read the + * [middleware docs](/docs/middleware.html#naming) to learn more. + * + * @param {Object} conditions + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.deleteMany = function deleteMany(conditions, options, callback) { + _checkContext(this, 'deleteMany'); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } + + const mq = new this.Query({}, {}, this, this.$__collection); + mq.setOptions(options); + + callback = this.$handleCallbackError(callback); + + return mq.deleteMany(conditions, callback); +}; + +/** + * Finds documents. + * + * Mongoose casts the `filter` to match the model's schema before the command is sent. + * See our [query casting tutorial](/docs/tutorials/query_casting.html) for + * more information on how Mongoose casts `filter`. + * + * ####Examples: + * + * // find all documents + * await MyModel.find({}); + * + * // find all documents named john and at least 18 + * await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec(); + * + * // executes, passing results to callback + * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); + * + * // executes, name LIKE john and only selecting the "name" and "friends" fields + * await MyModel.find({ name: /john/i }, 'name friends').exec(); + * + * // passing options + * await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec(); + * + * @param {Object|ObjectId} filter + * @param {Object|String|Array} [projection] optional fields to return, see [`Query.prototype.select()`](http://mongoosejs.com/docs/api.html#query_Query-select) + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see query casting /docs/tutorials/query_casting.html + * @api public + */ + +Model.find = function find(conditions, projection, options, callback) { + _checkContext(this, 'find'); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + projection = null; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + projection = null; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } + + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(projection); + + mq.setOptions(options); + if (this.schema.discriminatorMapping && + this.schema.discriminatorMapping.isRoot && + mq.selectedInclusively()) { + // Need to select discriminator key because original schema doesn't have it + mq.select(this.schema.options.discriminatorKey); + } + + callback = this.$handleCallbackError(callback); + + return mq.find(conditions, callback); +}; + +/** + * Finds a single document by its _id field. `findById(id)` is almost* + * equivalent to `findOne({ _id: id })`. If you want to query by a document's + * `_id`, use `findById()` instead of `findOne()`. + * + * The `id` is cast based on the Schema before sending the command. + * + * This function triggers the following middleware. + * + * - `findOne()` + * + * \* Except for how it treats `undefined`. If you use `findOne()`, you'll see + * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent + * to `findOne({})` and return arbitrary documents. However, mongoose + * translates `findById(undefined)` into `findOne({ _id: null })`. + * + * ####Example: + * + * // Find the adventure with the given `id`, or `null` if not found + * await Adventure.findById(id).exec(); + * + * // using callback + * Adventure.findById(id, function (err, adventure) {}); + * + * // select only the adventures name and length + * await Adventure.findById(id, 'name length').exec(); + * + * @param {Any} id value of `_id` to query by + * @param {Object|String|Array} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see lean queries /docs/tutorials/lean.html + * @see findById in Mongoose https://masteringjs.io/tutorials/mongoose/find-by-id + * @api public + */ + +Model.findById = function findById(id, projection, options, callback) { + _checkContext(this, 'findById'); + + if (typeof id === 'undefined') { + id = null; + } + + callback = this.$handleCallbackError(callback); + + return this.findOne({ _id: id }, projection, options, callback); +}; + +/** + * Finds one document. + * + * The `conditions` are cast to their respective SchemaTypes before the command is sent. + * + * *Note:* `conditions` is optional, and if `conditions` is null or undefined, + * mongoose will send an empty `findOne` command to MongoDB, which will return + * an arbitrary document. If you're querying by `_id`, use `findById()` instead. + * + * ####Example: + * + * // Find one adventure whose `country` is 'Croatia', otherwise `null` + * await Adventure.findOne({ country: 'Croatia' }).exec(); + * + * // using callback + * Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {}); + * + * // select only the adventures name and length + * await Adventure.findOne({ country: 'Croatia' }, 'name length').exec(); + * + * @param {Object} [conditions] + * @param {Object|String|Array} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see lean queries /docs/tutorials/lean.html + * @api public + */ + +Model.findOne = function findOne(conditions, projection, options, callback) { + _checkContext(this, 'findOne'); + if (typeof options === 'function') { + callback = options; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + projection = null; + options = null; + } else if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + projection = null; + options = null; + } + + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(projection); + mq.setOptions(options); + if (this.schema.discriminatorMapping && + this.schema.discriminatorMapping.isRoot && + mq.selectedInclusively()) { + mq.select(this.schema.options.discriminatorKey); + } + + callback = this.$handleCallbackError(callback); + return mq.findOne(conditions, callback); +}; + +/** + * Estimates the number of documents in the MongoDB collection. Faster than + * using `countDocuments()` for large collections because + * `estimatedDocumentCount()` uses collection metadata rather than scanning + * the entire collection. + * + * ####Example: + * + * const numAdventures = Adventure.estimatedDocumentCount(); + * + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.estimatedDocumentCount = function estimatedDocumentCount(options, callback) { + _checkContext(this, 'estimatedDocumentCount'); + + const mq = new this.Query({}, {}, this, this.$__collection); + + callback = this.$handleCallbackError(callback); + + return mq.estimatedDocumentCount(options, callback); +}; + +/** + * Counts number of documents matching `filter` in a database collection. + * + * ####Example: + * + * Adventure.countDocuments({ type: 'jungle' }, function (err, count) { + * console.log('there are %d jungle adventures', count); + * }); + * + * If you want to count all documents in a large collection, + * use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) + * instead. If you call `countDocuments({})`, MongoDB will always execute + * a full collection scan and **not** use any indexes. + * + * The `countDocuments()` function is similar to `count()`, but there are a + * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). + * Below are the operators that `count()` supports but `countDocuments()` does not, + * and the suggested replacement: + * + * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/) + * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center) + * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere) + * + * @param {Object} filter + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.countDocuments = function countDocuments(conditions, options, callback) { + _checkContext(this, 'countDocuments'); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + if (typeof options === 'function') { + callback = options; + options = null; + } + + const mq = new this.Query({}, {}, this, this.$__collection); + if (options != null) { + mq.setOptions(options); + } + + callback = this.$handleCallbackError(callback); + + return mq.countDocuments(conditions, callback); +}; + +/** + * Counts number of documents that match `filter` in a database collection. + * + * This method is deprecated. If you want to count the number of documents in + * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) + * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#model_Model.countDocuments) function instead. + * + * ####Example: + * + * const count = await Adventure.count({ type: 'jungle' }); + * console.log('there are %d jungle adventures', count); + * + * @deprecated + * @param {Object} filter + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.count = function count(conditions, callback) { + _checkContext(this, 'count'); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + + const mq = new this.Query({}, {}, this, this.$__collection); + + callback = this.$handleCallbackError(callback); + + return mq.count(conditions, callback); +}; + +/** + * Creates a Query for a `distinct` operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) { + * if (err) return handleError(err); + * + * assert(Array.isArray(result)); + * console.log('unique urls with more than 100 clicks', result); + * }) + * + * const query = Link.distinct('url'); + * query.exec(callback); + * + * @param {String} field + * @param {Object} [conditions] optional + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.distinct = function distinct(field, conditions, callback) { + _checkContext(this, 'distinct'); + + const mq = new this.Query({}, {}, this, this.$__collection); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + callback = this.$handleCallbackError(callback); + + return mq.distinct(field, conditions, callback); +}; + +/** + * Creates a Query, applies the passed conditions, and returns the Query. + * + * For example, instead of writing: + * + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * we can instead write: + * + * User.where('age').gte(21).lte(65).exec(callback); + * + * Since the Query class also supports `where` you can continue chaining + * + * User + * .where('age').gte(21).lte(65) + * .where('name', /^b/i) + * ... etc + * + * @param {String} path + * @param {Object} [val] optional value + * @return {Query} + * @api public + */ + +Model.where = function where(path, val) { + _checkContext(this, 'where'); + + void val; // eslint + const mq = new this.Query({}, {}, this, this.$__collection).find({}); + return mq.where.apply(mq, arguments); +}; + +/** + * Creates a `Query` and specifies a `$where` condition. + * + * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model. + * + * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {}); + * + * @param {String|Function} argument is a javascript string or anonymous function + * @method $where + * @memberOf Model + * @return {Query} + * @see Query.$where #query_Query-%24where + * @api public + */ + +Model.$where = function $where() { + _checkContext(this, '$where'); + + const mq = new this.Query({}, {}, this, this.$__collection).find({}); + return mq.$where.apply(mq, arguments); +}; + +/** + * Issues a mongodb findAndModify update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes if `callback` is passed else a Query object is returned. + * + * ####Options: + * + * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `overwrite`: bool - if true, replace the entire document. + * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * - `setDefaultsOnInsert`: `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findOneAndUpdate(conditions, update, options, callback) // executes + * A.findOneAndUpdate(conditions, update, options) // returns Query + * A.findOneAndUpdate(conditions, update, callback) // executes + * A.findOneAndUpdate(conditions, update) // returns Query + * A.findOneAndUpdate() // returns Query + * + * ####Note: + * + * All top level update keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * const query = { name: 'borne' }; + * Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback) + * + * // is sent as + * Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback) + * + * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. + * + * ####Note: + * + * `findOneAndX` and `findByIdAndX` functions support limited validation that + * you can enable by setting the `runValidators` option. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * const doc = await Model.findById(id); + * doc.name = 'jason bourne'; + * await doc.save(); + * + * @param {Object} [conditions] + * @param {Object} [update] + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. To change the default to `true`, use `mongoose.set('returnOriginal', false);`. + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. + * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace(conditions, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace). + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Function} [callback] + * @return {Query} + * @see Tutorial /docs/tutorials/findoneandupdate.html + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Model.findOneAndUpdate = function(conditions, update, options, callback) { + _checkContext(this, 'findOneAndUpdate'); + + if (typeof options === 'function') { + callback = options; + options = null; + } else if (arguments.length === 1) { + if (typeof conditions === 'function') { + const msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n' + + ' ' + this.modelName + '.findOneAndUpdate(update)\n' + + ' ' + this.modelName + '.findOneAndUpdate()\n'; + throw new TypeError(msg); + } + update = conditions; + conditions = undefined; + } + callback = this.$handleCallbackError(callback); + + let fields; + if (options) { + fields = options.fields || options.projection; + } + + update = utils.clone(update, { + depopulate: true, + _isNested: true + }); + + _decorateUpdateWithVersionKey(update, options, this.schema.options.versionKey); + + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(fields); + + return mq.findOneAndUpdate(conditions, update, options, callback); +}; + +/*! + * Decorate the update with a version key, if necessary + */ + +function _decorateUpdateWithVersionKey(update, options, versionKey) { + if (!versionKey || !get(options, 'upsert', false)) { + return; + } + + const updatedPaths = modifiedPaths(update); + if (!updatedPaths[versionKey]) { + if (options.overwrite) { + update[versionKey] = 0; + } else { + if (!update.$setOnInsert) { + update.$setOnInsert = {}; + } + update.$setOnInsert[versionKey] = 0; + } + } +} + +/** + * Issues a mongodb findAndModify update command by a document's _id field. + * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`. + * + * Finds a matching document, updates it according to the `update` arg, + * passing any `options`, and returns the found document (if any) to the + * callback. The query executes if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndUpdate()` + * + * ####Options: + * + * - `new`: bool - true to return the modified document rather than the original. defaults to false + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * - `setDefaultsOnInsert`: `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findByIdAndUpdate(id, update, options, callback) // executes + * A.findByIdAndUpdate(id, update, options) // returns Query + * A.findByIdAndUpdate(id, update, callback) // executes + * A.findByIdAndUpdate(id, update) // returns Query + * A.findByIdAndUpdate() // returns Query + * + * ####Note: + * + * All top level update keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback) + * + * // is sent as + * Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback) + * + * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. + * + * ####Note: + * + * `findOneAndX` and `findByIdAndX` functions support limited validation. You can + * enable validation by setting the `runValidators` option. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason bourne'; + * doc.save(callback); + * }); + * + * @param {Object|Number|String} id value of `_id` to query by + * @param {Object} [update] + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean} [options.new=false] By default, `findByIdAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. To change the default to `true`, use `mongoose.set('returnOriginal', false);`. + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. + * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace({ _id: id }, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace). + * @param {Function} [callback] + * @return {Query} + * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Model.findByIdAndUpdate = function(id, update, options, callback) { + _checkContext(this, 'findByIdAndUpdate'); + + callback = this.$handleCallbackError(callback); + if (arguments.length === 1) { + if (typeof id === 'function') { + const msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n' + + ' ' + this.modelName + '.findByIdAndUpdate(id)\n' + + ' ' + this.modelName + '.findByIdAndUpdate()\n'; + throw new TypeError(msg); + } + return this.findOneAndUpdate({ _id: id }, undefined); + } + + // if a model is passed in instead of an id + if (id instanceof Document) { + id = id._id; + } + + return this.findOneAndUpdate.call(this, { _id: id }, update, options, callback); +}; + +/** + * Issue a MongoDB `findOneAndDelete()` command. + * + * Finds a matching document, removes it, and passes the found document + * (if any) to the callback. + * + * Executes the query if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndDelete()` + * + * This function differs slightly from `Model.findOneAndRemove()` in that + * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), + * as opposed to a `findOneAndDelete()` command. For most mongoose use cases, + * this distinction is purely pedantic. You should use `findOneAndDelete()` + * unless you have a good reason not to. + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `select`: sets the document fields to return, ex. `{ projection: { _id: 0 } }` + * - `projection`: equivalent to `select` + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findOneAndDelete(conditions, options, callback) // executes + * A.findOneAndDelete(conditions, options) // return Query + * A.findOneAndDelete(conditions, callback) // executes + * A.findOneAndDelete(conditions) // returns Query + * A.findOneAndDelete() // returns Query + * + * `findOneAndX` and `findByIdAndX` functions support limited validation. You can + * enable validation by setting the `runValidators` option. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason bourne'; + * doc.save(callback); + * }); + * + * @param {Object} conditions + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.findOneAndDelete = function(conditions, options, callback) { + _checkContext(this, 'findOneAndDelete'); + + if (arguments.length === 1 && typeof conditions === 'function') { + const msg = 'Model.findOneAndDelete(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndDelete(conditions, callback)\n' + + ' ' + this.modelName + '.findOneAndDelete(conditions)\n' + + ' ' + this.modelName + '.findOneAndDelete()\n'; + throw new TypeError(msg); + } + + if (typeof options === 'function') { + callback = options; + options = undefined; + } + callback = this.$handleCallbackError(callback); + + let fields; + if (options) { + fields = options.select; + options.select = undefined; + } + + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(fields); + + return mq.findOneAndDelete(conditions, options, callback); +}; + +/** + * Issue a MongoDB `findOneAndDelete()` command by a document's _id field. + * In other words, `findByIdAndDelete(id)` is a shorthand for + * `findOneAndDelete({ _id: id })`. + * + * This function triggers the following middleware. + * + * - `findOneAndDelete()` + * + * @param {Object|Number|String} id value of `_id` to query by + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Function} [callback] + * @return {Query} + * @see Model.findOneAndRemove #model_Model.findOneAndRemove + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + */ + +Model.findByIdAndDelete = function(id, options, callback) { + _checkContext(this, 'findByIdAndDelete'); + + if (arguments.length === 1 && typeof id === 'function') { + const msg = 'Model.findByIdAndDelete(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findByIdAndDelete(id, callback)\n' + + ' ' + this.modelName + '.findByIdAndDelete(id)\n' + + ' ' + this.modelName + '.findByIdAndDelete()\n'; + throw new TypeError(msg); + } + callback = this.$handleCallbackError(callback); + + return this.findOneAndDelete({ _id: id }, options, callback); +}; + +/** + * Issue a MongoDB `findOneAndReplace()` command. + * + * Finds a matching document, replaces it with the provided doc, and passes the + * returned doc to the callback. + * + * Executes the query if `callback` is passed. + * + * This function triggers the following query middleware. + * + * - `findOneAndReplace()` + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `select`: sets the document fields to return + * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findOneAndReplace(conditions, options, callback) // executes + * A.findOneAndReplace(conditions, options) // return Query + * A.findOneAndReplace(conditions, callback) // executes + * A.findOneAndReplace(conditions) // returns Query + * A.findOneAndReplace() // returns Query + * + * @param {Object} filter Replace the first document that matches this filter + * @param {Object} [replacement] Replace with this document + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean} [options.new=false] By default, `findOneAndReplace()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndReplace()` will instead give you the object after `update` was applied. To change the default to `true`, use `mongoose.set('returnOriginal', false);`. + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. + * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.findOneAndReplace = function(filter, replacement, options, callback) { + _checkContext(this, 'findOneAndReplace'); + + if (arguments.length === 1 && typeof filter === 'function') { + const msg = 'Model.findOneAndReplace(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndReplace(conditions, callback)\n' + + ' ' + this.modelName + '.findOneAndReplace(conditions)\n' + + ' ' + this.modelName + '.findOneAndReplace()\n'; + throw new TypeError(msg); + } + + if (arguments.length === 3 && typeof options === 'function') { + callback = options; + options = replacement; + replacement = void 0; + } + if (arguments.length === 2 && typeof replacement === 'function') { + callback = replacement; + replacement = void 0; + options = void 0; + } + callback = this.$handleCallbackError(callback); + + let fields; + if (options) { + fields = options.select; + options.select = undefined; + } + + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(fields); + + return mq.findOneAndReplace(filter, replacement, options, callback); +}; + +/** + * Issue a mongodb findAndModify remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * + * Executes the query if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndRemove()` + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `select`: sets the document fields to return + * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findOneAndRemove(conditions, options, callback) // executes + * A.findOneAndRemove(conditions, options) // return Query + * A.findOneAndRemove(conditions, callback) // executes + * A.findOneAndRemove(conditions) // returns Query + * A.findOneAndRemove() // returns Query + * + * `findOneAndX` and `findByIdAndX` functions support limited validation. You can + * enable validation by setting the `runValidators` option. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason bourne'; + * doc.save(callback); + * }); + * + * @param {Object} conditions + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Function} [callback] + * @return {Query} + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Model.findOneAndRemove = function(conditions, options, callback) { + _checkContext(this, 'findOneAndRemove'); + + if (arguments.length === 1 && typeof conditions === 'function') { + const msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n' + + ' ' + this.modelName + '.findOneAndRemove(conditions)\n' + + ' ' + this.modelName + '.findOneAndRemove()\n'; + throw new TypeError(msg); + } + + if (typeof options === 'function') { + callback = options; + options = undefined; + } + callback = this.$handleCallbackError(callback); + + let fields; + if (options) { + fields = options.select; + options.select = undefined; + } + + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(fields); + + return mq.findOneAndRemove(conditions, options, callback); +}; + +/** + * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * + * Executes the query if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndRemove()` + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findByIdAndRemove(id, options, callback) // executes + * A.findByIdAndRemove(id, options) // return Query + * A.findByIdAndRemove(id, callback) // executes + * A.findByIdAndRemove(id) // returns Query + * A.findByIdAndRemove() // returns Query + * + * @param {Object|Number|String} id value of `_id` to query by + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Function} [callback] + * @return {Query} + * @see Model.findOneAndRemove #model_Model.findOneAndRemove + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + */ + +Model.findByIdAndRemove = function(id, options, callback) { + _checkContext(this, 'findByIdAndRemove'); + + if (arguments.length === 1 && typeof id === 'function') { + const msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n' + + ' ' + this.modelName + '.findByIdAndRemove(id)\n' + + ' ' + this.modelName + '.findByIdAndRemove()\n'; + throw new TypeError(msg); + } + callback = this.$handleCallbackError(callback); + + return this.findOneAndRemove({ _id: id }, options, callback); +}; + +/** + * Shortcut for saving one or more documents to the database. + * `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in + * docs. + * + * This function triggers the following middleware. + * + * - `save()` + * + * ####Example: + * + * // Insert one new `Character` document + * await Character.create({ name: 'Jean-Luc Picard' }); + * + * // Insert multiple new `Character` documents + * await Character.create([{ name: 'Will Riker' }, { name: 'Geordi LaForge' }]); + * + * // Create a new character within a transaction. Note that you **must** + * // pass an array as the first parameter to `create()` if you want to + * // specify options. + * await Character.create([{ name: 'Jean-Luc Picard' }], { session }); + * + * @param {Array|Object} docs Documents to insert, as a spread or array + * @param {Object} [options] Options passed down to `save()`. To specify `options`, `docs` **must** be an array, not a spread. + * @param {Function} [callback] callback + * @return {Promise} + * @api public + */ + +Model.create = function create(doc, options, callback) { + _checkContext(this, 'create'); + + let args; + let cb; + const discriminatorKey = this.schema.options.discriminatorKey; + + if (Array.isArray(doc)) { + args = doc; + cb = typeof options === 'function' ? options : callback; + options = options != null && typeof options === 'object' ? options : {}; + } else { + const last = arguments[arguments.length - 1]; + options = {}; + // Handle falsy callbacks re: #5061 + if (typeof last === 'function' || (arguments.length > 1 && !last)) { + cb = last; + args = utils.args(arguments, 0, arguments.length - 1); + } else { + args = utils.args(arguments); + } + + if (args.length === 2 && + args[0] != null && + args[1] != null && + args[0].session == null && + getConstructorName(last.session) === 'ClientSession' && + !this.schema.path('session')) { + // Probably means the user is running into the common mistake of trying + // to use a spread to specify options, see gh-7535 + utils.warn('WARNING: to pass a `session` to `Model.create()` in ' + + 'Mongoose, you **must** pass an array as the first argument. See: ' + + 'https://mongoosejs.com/docs/api.html#model_Model.create'); + } + } + + return this.db.base._promiseOrCallback(cb, cb => { + cb = this.$wrapCallback(cb); + + if (args.length === 0) { + if (Array.isArray(doc)) { + return cb(null, []); + } else { + return cb(null); + } + } + + const toExecute = []; + let firstError; + args.forEach(doc => { + toExecute.push(callback => { + const Model = this.discriminators && doc[discriminatorKey] != null ? + this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) : + this; + if (Model == null) { + throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` + + `found for model "${this.modelName}"`); + } + let toSave = doc; + const callbackWrapper = (error, doc) => { + if (error) { + if (!firstError) { + firstError = error; + } + return callback(null, { error: error }); + } + callback(null, { doc: doc }); + }; + + if (!(toSave instanceof Model)) { + try { + toSave = new Model(toSave); + } catch (error) { + return callbackWrapper(error); + } + } + + toSave.$save(options, callbackWrapper); + }); + }); + + let numFns = toExecute.length; + if (numFns === 0) { + return cb(null, []); + } + const _done = (error, res) => { + const savedDocs = []; + const len = res.length; + for (let i = 0; i < len; ++i) { + if (res[i].doc) { + savedDocs.push(res[i].doc); + } + } + + if (firstError) { + return cb(firstError, savedDocs); + } + + if (doc instanceof Array) { + cb(null, savedDocs); + } else { + cb.apply(this, [null].concat(savedDocs)); + } + }; + + const _res = []; + toExecute.forEach((fn, i) => { + fn((err, res) => { + _res[i] = res; + if (--numFns <= 0) { + return _done(null, _res); + } + }); + }); + }, this.events); +}; + +/** + * _Requires a replica set running MongoDB >= 3.6.0._ Watches the + * underlying collection for changes using + * [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). + * + * This function does **not** trigger any middleware. In particular, it + * does **not** trigger aggregate middleware. + * + * The ChangeStream object is an event emitter that emits the following events: + * + * - 'change': A change occurred, see below example + * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates. + * - 'end': Emitted if the underlying stream is closed + * - 'close': Emitted if the underlying stream is closed + * + * ####Example: + * + * const doc = await Person.create({ name: 'Ned Stark' }); + * const changeStream = Person.watch().on('change', change => console.log(change)); + * // Will print from the above `console.log()`: + * // { _id: { _data: ... }, + * // operationType: 'delete', + * // ns: { db: 'mydb', coll: 'Person' }, + * // documentKey: { _id: 5a51b125c5500f5aa094c7bd } } + * await doc.remove(); + * + * @param {Array} [pipeline] + * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch) + * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter + * @api public + */ + +Model.watch = function(pipeline, options) { + _checkContext(this, 'watch'); + + const changeStreamThunk = cb => { + if (this.$__collection.buffer) { + this.$__collection.addQueue(() => { + if (this.closed) { + return; + } + const driverChangeStream = this.$__collection.watch(pipeline, options); + cb(null, driverChangeStream); + }); + } else { + const driverChangeStream = this.$__collection.watch(pipeline, options); + cb(null, driverChangeStream); + } + }; + + return new ChangeStream(changeStreamThunk, pipeline, options); +}; + +/** + * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) + * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), + * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). + * + * Calling `MyModel.startSession()` is equivalent to calling `MyModel.db.startSession()`. + * + * This function does not trigger any middleware. + * + * ####Example: + * + * const session = await Person.startSession(); + * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); + * await doc.remove(); + * // `doc` will always be null, even if reading from a replica set + * // secondary. Without causal consistency, it is possible to + * // get a doc back from the below query if the query reads from a + * // secondary that is experiencing replication lag. + * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); + * + * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) + * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency + * @param {Function} [callback] + * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` + * @api public + */ + +Model.startSession = function() { + _checkContext(this, 'startSession'); + + return this.db.startSession.apply(this.db, arguments); +}; + +/** + * Shortcut for validating an array of documents and inserting them into + * MongoDB if they're all valid. This function is faster than `.create()` + * because it only sends one operation to the server, rather than one for each + * document. + * + * Mongoose always validates each document **before** sending `insertMany` + * to MongoDB. So if one document has a validation error, no documents will + * be saved, unless you set + * [the `ordered` option to false](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#error-handling). + * + * This function does **not** trigger save middleware. + * + * This function triggers the following middleware. + * + * - `insertMany()` + * + * ####Example: + * + * const arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }]; + * Movies.insertMany(arr, function(error, docs) {}); + * + * @param {Array|Object|*} doc(s) + * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany) + * @param {Boolean} [options.ordered = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An `insertMany()` with `ordered = false` is called an "unordered" `insertMany()`. + * @param {Boolean} [options.rawResult = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`. + * @param {Boolean} [options.lean = false] if `true`, skips hydrating and validating the documents. This option is useful if you need the extra performance, but Mongoose won't validate the documents before inserting. + * @param {Number} [options.limit = null] this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does **NOT** send the documents in batches to MongoDB. Use this option if you're processing a large number of documents and your app is running out of memory. + * @param {String|Object|Array} [options.populate = null] populates the result documents. This option is a no-op if `rawResult` is set. + * @param {Function} [callback] callback + * @return {Promise} resolving to the raw result from the MongoDB driver if `options.rawResult` was `true`, or the documents that passed validation, otherwise + * @api public + */ + +Model.insertMany = function(arr, options, callback) { + _checkContext(this, 'insertMany'); + + if (typeof options === 'function') { + callback = options; + options = null; + } + return this.db.base._promiseOrCallback(callback, cb => { + this.$__insertMany(arr, options, cb); + }, this.events); +}; + +/*! + * ignore + */ + +Model.$__insertMany = function(arr, options, callback) { + const _this = this; + if (typeof options === 'function') { + callback = options; + options = null; + } + if (callback) { + callback = this.$handleCallbackError(callback); + callback = this.$wrapCallback(callback); + } + callback = callback || utils.noop; + options = options || {}; + const limit = get(options, 'limit', 1000); + const rawResult = get(options, 'rawResult', false); + const ordered = get(options, 'ordered', true); + const lean = get(options, 'lean', false); + + if (!Array.isArray(arr)) { + arr = [arr]; + } + + const validationErrors = []; + const toExecute = arr.map(doc => + callback => { + if (!(doc instanceof _this)) { + try { + doc = new _this(doc); + } catch (err) { + return callback(err); + } + } + if (options.session != null) { + doc.$session(options.session); + } + // If option `lean` is set to true bypass validation + if (lean) { + // we have to execute callback at the nextTick to be compatible + // with parallelLimit, as `results` variable has TDZ issue if we + // execute the callback synchronously + return immediate(() => callback(null, doc)); + } + doc.$validate({ __noPromise: true }, function(error) { + if (error) { + // Option `ordered` signals that insert should be continued after reaching + // a failing insert. Therefore we delegate "null", meaning the validation + // failed. It's up to the next function to filter out all failed models + if (ordered === false) { + validationErrors.push(error); + return callback(null, null); + } + return callback(error); + } + callback(null, doc); + }); + }); + + parallelLimit(toExecute, limit, function(error, docs) { + if (error) { + callback(error, null); + return; + } + // We filter all failed pre-validations by removing nulls + const docAttributes = docs.filter(function(doc) { + return doc != null; + }); + // Quickly escape while there aren't any valid docAttributes + if (docAttributes.length < 1) { + if (rawResult) { + const res = { + mongoose: { + validationErrors: validationErrors + } + }; + return callback(null, res); + } + callback(null, []); + return; + } + const docObjects = docAttributes.map(function(doc) { + if (doc.$__schema.options.versionKey) { + doc[doc.$__schema.options.versionKey] = 0; + } + if (doc.initializeTimestamps) { + return doc.initializeTimestamps().toObject(internalToObjectOptions); + } + return doc.toObject(internalToObjectOptions); + }); + + _this.$__collection.insertMany(docObjects, options, function(error, res) { + if (error) { + // `writeErrors` is a property reported by the MongoDB driver, + // just not if there's only 1 error. + if (error.writeErrors == null && + get(error, 'result.result.writeErrors') != null) { + error.writeErrors = error.result.result.writeErrors; + } + + // `insertedDocs` is a Mongoose-specific property + const erroredIndexes = new Set(get(error, 'writeErrors', []).map(err => err.index)); + + let firstErroredIndex = -1; + error.insertedDocs = docAttributes. + filter((doc, i) => { + const isErrored = erroredIndexes.has(i); + + if (ordered) { + if (firstErroredIndex > -1) { + return i < firstErroredIndex; + } + + if (isErrored) { + firstErroredIndex = i; + } + } + + return !isErrored; + }). + map(function setIsNewForInsertedDoc(doc) { + doc.$__reset(); + _setIsNew(doc, false); + return doc; + }); + + callback(error, null); + return; + } + + for (const attribute of docAttributes) { + attribute.$__reset(); + _setIsNew(attribute, false); + } + + if (rawResult) { + if (ordered === false) { + // Decorate with mongoose validation errors in case of unordered, + // because then still do `insertMany()` + res.mongoose = { + validationErrors: validationErrors + }; + } + return callback(null, res); + } + + if (options.populate != null) { + return _this.populate(docAttributes, options.populate, err => { + if (err != null) { + error.insertedDocs = docAttributes; + return callback(err); + } + + callback(null, docs); + }); + } + + callback(null, docAttributes); + }); + }); +}; + +/*! + * ignore + */ + +function _setIsNew(doc, val) { + doc.$isNew = val; + doc.$emit('isNew', val); + doc.constructor.emit('isNew', val); + + const subdocs = doc.$getAllSubdocs(); + for (const subdoc of subdocs) { + subdoc.$isNew = val; + } +} + +/** + * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`, + * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one + * command. This is faster than sending multiple independent operations (e.g. + * if you use `create()`) because with `bulkWrite()` there is only one round + * trip to MongoDB. + * + * Mongoose will perform casting on all operations you provide. + * + * This function does **not** trigger any middleware, neither `save()`, nor `update()`. + * If you need to trigger + * `save()` middleware for every document use [`create()`](http://mongoosejs.com/docs/api.html#model_Model.create) instead. + * + * ####Example: + * + * Character.bulkWrite([ + * { + * insertOne: { + * document: { + * name: 'Eddard Stark', + * title: 'Warden of the North' + * } + * } + * }, + * { + * updateOne: { + * filter: { name: 'Eddard Stark' }, + * // If you were using the MongoDB driver directly, you'd need to do + * // `update: { $set: { title: ... } }` but mongoose adds $set for + * // you. + * update: { title: 'Hand of the King' } + * } + * }, + * { + * deleteOne: { + * { + * filter: { name: 'Eddard Stark' } + * } + * } + * } + * ]).then(res => { + * // Prints "1 1 1" + * console.log(res.insertedCount, res.modifiedCount, res.deletedCount); + * }); + * + * The [supported operations](https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#db.collection.bulkWrite) are: + * + * - `insertOne` + * - `updateOne` + * - `updateMany` + * - `deleteOne` + * - `deleteMany` + * - `replaceOne` + * + * @param {Array} ops + * @param {Object} [ops.insertOne.document] The document to insert + * @param {Object} [opts.updateOne.filter] Update the first document that matches this filter + * @param {Object} [opts.updateOne.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/) + * @param {Boolean} [opts.updateOne.upsert=false] If true, insert a doc if none match + * @param {Boolean} [opts.updateOne.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation + * @param {Object} [opts.updateOne.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use + * @param {Array} [opts.updateOne.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update` + * @param {Object} [opts.updateMany.filter] Update all the documents that match this filter + * @param {Object} [opts.updateMany.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/) + * @param {Boolean} [opts.updateMany.upsert=false] If true, insert a doc if no documents match `filter` + * @param {Boolean} [opts.updateMany.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation + * @param {Object} [opts.updateMany.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use + * @param {Array} [opts.updateMany.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update` + * @param {Object} [opts.deleteOne.filter] Delete the first document that matches this filter + * @param {Object} [opts.deleteMany.filter] Delete all documents that match this filter + * @param {Object} [opts.replaceOne.filter] Replace the first document that matches this filter + * @param {Object} [opts.replaceOne.replacement] The replacement document + * @param {Boolean} [opts.replaceOne.upsert=false] If true, insert a doc if no documents match `filter` + * @param {Object} [options] + * @param {Boolean} [options.ordered=true] If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored. + * @param {ClientSession} [options.session=null] The session associated with this bulk write. See [transactions docs](/docs/transactions.html). + * @param {String|number} [options.w=1] The [write concern](https://docs.mongodb.com/manual/reference/write-concern/). See [`Query#w()`](/docs/api.html#query_Query-w) for more information. + * @param {number} [options.wtimeout=null] The [write concern timeout](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). + * @param {Boolean} [options.j=true] If false, disable [journal acknowledgement](https://docs.mongodb.com/manual/reference/write-concern/#j-option) + * @param {Boolean} [options.bypassDocumentValidation=false] If true, disable [MongoDB server-side schema validation](https://docs.mongodb.com/manual/core/schema-validation/) for all writes in this bulk. + * @param {Boolean} [options.strict=null] Overwrites the [`strict` option](/docs/guide.html#strict) on schema. If false, allows filtering and writing fields not defined in the schema for all writes in this bulk. + * @param {Function} [callback] callback `function(error, bulkWriteOpResult) {}` + * @return {Promise} resolves to a [`BulkWriteOpResult`](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult) if the operation succeeds + * @api public + */ + +Model.bulkWrite = function(ops, options, callback) { + _checkContext(this, 'bulkWrite'); + + if (typeof options === 'function') { + callback = options; + options = null; + } + options = options || {}; + + const validations = ops.map(op => castBulkWrite(this, op, options)); + + callback = this.$handleCallbackError(callback); + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); + each(validations, (fn, cb) => fn(cb), error => { + if (error) { + return cb(error); + } + + if (ops.length === 0) { + return cb(null, getDefaultBulkwriteResult()); + } + + this.$__collection.bulkWrite(ops, options, (error, res) => { + if (error) { + return cb(error); + } + + cb(null, res); + }); + }); + }, this.events); +}; + +/** + * takes an array of documents, gets the changes and inserts/updates documents in the database + * according to whether or not the document is new, or whether it has changes or not. + * + * `bulkSave` uses `bulkWrite` under the hood, so it's mostly useful when dealing with many documents (10K+) + * + * @param {[Document]} documents + * + */ +Model.bulkSave = function(documents) { + const preSavePromises = documents.map(buildPreSavePromise); + + const writeOperations = this.buildBulkWriteOperations(documents, { skipValidation: true }); + + let bulkWriteResultPromise; + return Promise.all(preSavePromises) + .then(() => bulkWriteResultPromise = this.bulkWrite(writeOperations)) + .then(() => documents.map(buildSuccessfulWriteHandlerPromise)) + .then(() => bulkWriteResultPromise) + .catch((err) => { + if (!get(err, 'writeErrors.length')) { + throw err; + } + return Promise.all( + documents.map((document) => { + const documentError = err.writeErrors.find(writeError => { + const writeErrorDocumentId = writeError.err.op._id || writeError.err.op.q._id; + return writeErrorDocumentId.toString() === document._id.toString(); + }); + + if (documentError == null) { + return buildSuccessfulWriteHandlerPromise(document); + } + }) + ).then(() => { + throw err; + }); + }); +}; + +function buildPreSavePromise(document) { + return new Promise((resolve, reject) => { + document.schema.s.hooks.execPre('save', document, (err) => { + if (err) { + reject(err); + return; + } + resolve(); + }); + }); +} + +function buildSuccessfulWriteHandlerPromise(document) { + return new Promise((resolve, reject) => { + handleSuccessfulWrite(document, resolve, reject); + }); +} + +function handleSuccessfulWrite(document, resolve, reject) { + if (document.$isNew) { + _setIsNew(document, false); + } + + document.$__reset(); + document.schema.s.hooks.execPost('save', document, {}, (err) => { + if (err) { + reject(err); + return; + } + resolve(); + }); +} + +/** + * + * @param {[Document]} documents The array of documents to build write operations of + * @param {Object} options + * @param {Boolean} options.skipValidation defaults to `false`, when set to true, building the write operations will bypass validating the documents. + * @returns + */ +Model.buildBulkWriteOperations = function buildBulkWriteOperations(documents, options) { + if (!Array.isArray(documents)) { + throw new Error(`bulkSave expects an array of documents to be passed, received \`${documents}\` instead`); + } + + setDefaultOptions(); + + const writeOperations = documents.reduce((accumulator, document, i) => { + if (!options.skipValidation) { + if (!(document instanceof Document)) { + throw new Error(`documents.${i} was not a mongoose document, documents must be an array of mongoose documents (instanceof mongoose.Document).`); + } + const validationError = document.validateSync(); + if (validationError) { + throw validationError; + } + } + + const isANewDocument = document.isNew; + if (isANewDocument) { + accumulator.push({ + insertOne: { document } + }); + + return accumulator; + } + + const delta = document.$__delta(); + const isDocumentWithChanges = delta != null && !utils.isEmptyObject(delta[0]); + + if (isDocumentWithChanges) { + const where = document.$__where(delta[0]); + const changes = delta[1]; + + _applyCustomWhere(document, where); + + document.$__version(where, delta); + + accumulator.push({ + updateOne: { + filter: where, + update: changes + } + }); + + return accumulator; + } + + return accumulator; + }, []); + + return writeOperations; + + + function setDefaultOptions() { + options = options || {}; + if (options.skipValidation == null) { + options.skipValidation = false; + } + } +}; + +/** + * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. + * The document returned has no paths marked as modified initially. + * + * ####Example: + * + * // hydrate previous data into a Mongoose document + * const mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' }); + * + * @param {Object} obj + * @param {Object|String|Array} [projection] optional projection containing which fields should be selected for this document + * @return {Document} document instance + * @api public + */ + +Model.hydrate = function(obj, projection) { + _checkContext(this, 'hydrate'); + + const document = require('./queryhelpers').createModel(this, obj, projection); + document.$init(obj); + return document; +}; + +/** + * Updates one document in the database without returning it. + * + * This function triggers the following middleware. + * + * - `update()` + * + * This method is deprecated. See [Deprecation Warnings](../deprecations.html#update) for details. + * + * ####Examples: + * + * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); + * + * const res = await MyModel.update({ name: 'Tobi' }, { ferret: true }); + * res.n; // Number of documents that matched `{ name: 'Tobi' }` + * // Number of documents that were changed. If every doc matched already + * // had `ferret` set to `true`, `nModified` will be 0. + * res.nModified; + * + * ####Valid options: + * + * - `strict` (boolean): overrides the [schema-level `strict` option](/docs/guide.html#strict) for this update + * - `upsert` (boolean): whether to create the doc if it doesn't match (false) + * - `writeConcern` (object): sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * - `multi` (boolean): whether multiple documents should be updated (false) + * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * - `setDefaultsOnInsert` (boolean): if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). + * - `timestamps` (boolean): If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * - `overwrite` (boolean): disables update-only mode, allowing you to overwrite the doc (false) + * + * All `update` values are cast to their appropriate SchemaTypes before being sent. + * + * The `callback` function receives `(err, rawResponse)`. + * + * - `err` is the error if any occurred + * - `rawResponse` is the full response from Mongo + * + * ####Note: + * + * All top level keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * const query = { name: 'borne' }; + * Model.update(query, { name: 'jason bourne' }, options, callback); + * + * // is sent as + * Model.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res)); + * // if overwrite option is false. If overwrite is true, sent without the $set wrapper. + * + * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason bourne' }`. + * + * ####Note: + * + * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. + * + * @deprecated + * @see strict http://mongoosejs.com/docs/guide.html#strict + * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output + * @param {Object} filter + * @param {Object} doc + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.multi=false] whether multiple documents should be updated or just the first one that matches `filter`. + * @param {Boolean} [options.runValidators=false] if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * @param {Boolean} [options.setDefaultsOnInsert=false] `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `doc`, Mongoose will wrap `doc` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. + * @param {Function} [callback] params are (error, [updateWriteOpResult](https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~updateWriteOpResult)) + * @param {Function} [callback] + * @return {Query} + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @see writeOpResult https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~updateWriteOpResult + * @see Query docs https://mongoosejs.com/docs/queries.html + * @api public + */ + +Model.update = function update(conditions, doc, options, callback) { + _checkContext(this, 'update'); + + return _update(this, 'update', conditions, doc, options, callback); +}; + +/** + * Same as `update()`, except MongoDB will update _all_ documents that match + * `filter` (as opposed to just the first one) regardless of the value of + * the `multi` option. + * + * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')` + * and `post('updateMany')` instead. + * + * ####Example: + * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true }); + * res.n; // Number of documents matched + * res.nModified; // Number of documents modified + * + * This function triggers the following middleware. + * + * - `updateMany()` + * + * @param {Object} filter + * @param {Object|Array} update + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`. + * @return {Query} + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @api public + */ + +Model.updateMany = function updateMany(conditions, doc, options, callback) { + _checkContext(this, 'updateMany'); + + return _update(this, 'updateMany', conditions, doc, options, callback); +}; + +/** + * Same as `update()`, except it does not support the `multi` or `overwrite` + * options. + * + * - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option. + * - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`. + * + * ####Example: + * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' }); + * res.n; // Number of documents matched + * res.nModified; // Number of documents modified + * + * This function triggers the following middleware. + * + * - `updateOne()` + * + * @param {Object} filter + * @param {Object|Array} update + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] params are (error, writeOpResult) + * @return {Query} + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @api public + */ + +Model.updateOne = function updateOne(conditions, doc, options, callback) { + _checkContext(this, 'updateOne'); + + return _update(this, 'updateOne', conditions, doc, options, callback); +}; + +/** + * Same as `update()`, except MongoDB replace the existing document with the + * given document (no atomic operators like `$set`). + * + * ####Example: + * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' }); + * res.n; // Number of documents matched + * res.nModified; // Number of documents modified + * + * This function triggers the following middleware. + * + * - `replaceOne()` + * + * @param {Object} filter + * @param {Object} doc + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`. + * @return {Query} + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @return {Query} + * @api public + */ + +Model.replaceOne = function replaceOne(conditions, doc, options, callback) { + _checkContext(this, 'replaceOne'); + + const versionKey = get(this, 'schema.options.versionKey', null); + if (versionKey && !doc[versionKey]) { + doc[versionKey] = 0; + } + + return _update(this, 'replaceOne', conditions, doc, options, callback); +}; + +/*! + * Common code for `updateOne()`, `updateMany()`, `replaceOne()`, and `update()` + * because they need to do the same thing + */ + +function _update(model, op, conditions, doc, options, callback) { + const mq = new model.Query({}, {}, model, model.collection); + callback = model.$handleCallbackError(callback); + // gh-2406 + // make local deep copy of conditions + if (conditions instanceof Document) { + conditions = conditions.toObject(); + } else { + conditions = utils.clone(conditions); + } + options = typeof options === 'function' ? options : utils.clone(options); + + const versionKey = get(model, 'schema.options.versionKey', null); + _decorateUpdateWithVersionKey(doc, options, versionKey); + + return mq[op](conditions, doc, options, callback); +} + +/** + * Executes a mapReduce command. + * + * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options. + * + * This function does not trigger any middleware. + * + * ####Example: + * + * const o = {}; + * // `map()` and `reduce()` are run on the MongoDB server, not Node.js, + * // these functions are converted to strings + * o.map = function () { emit(this.name, 1) }; + * o.reduce = function (k, vals) { return vals.length }; + * User.mapReduce(o, function (err, results) { + * console.log(results) + * }) + * + * ####Other options: + * + * - `query` {Object} query filter object. + * - `sort` {Object} sort input objects using this key + * - `limit` {Number} max number of documents + * - `keeptemp` {Boolean, default:false} keep temporary data + * - `finalize` {Function} finalize function + * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution + * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X + * - `verbose` {Boolean, default:false} provide statistics on job execution time. + * - `readPreference` {String} + * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job. + * + * ####* out options: + * + * - `{inline:1}` the results are returned in an array + * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection + * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions + * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old + * + * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the [`lean` option](/docs/tutorials/lean.html); meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc). + * + * ####Example: + * + * const o = {}; + * // You can also define `map()` and `reduce()` as strings if your + * // linter complains about `emit()` not being defined + * o.map = 'function () { emit(this.name, 1) }'; + * o.reduce = 'function (k, vals) { return vals.length }'; + * o.out = { replace: 'createdCollectionNameForResults' } + * o.verbose = true; + * + * User.mapReduce(o, function (err, model, stats) { + * console.log('map reduce took %d ms', stats.processtime) + * model.find().where('value').gt(10).exec(function (err, docs) { + * console.log(docs); + * }); + * }) + * + * // `mapReduce()` returns a promise. However, ES6 promises can only + * // resolve to exactly one value, + * o.resolveToObject = true; + * const promise = User.mapReduce(o); + * promise.then(function (res) { + * const model = res.model; + * const stats = res.stats; + * console.log('map reduce took %d ms', stats.processtime) + * return model.find().where('value').gt(10).exec(); + * }).then(function (docs) { + * console.log(docs); + * }).then(null, handleError).end() + * + * @param {Object} o an object specifying map-reduce options + * @param {Function} [callback] optional callback + * @see http://www.mongodb.org/display/DOCS/MapReduce + * @return {Promise} + * @api public + */ + +Model.mapReduce = function mapReduce(o, callback) { + _checkContext(this, 'mapReduce'); + + callback = this.$handleCallbackError(callback); + + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); + + if (!Model.mapReduce.schema) { + const opts = { _id: false, id: false, strict: false }; + Model.mapReduce.schema = new Schema({}, opts); + } + + if (!o.out) o.out = { inline: 1 }; + if (o.verbose !== false) o.verbose = true; + + o.map = String(o.map); + o.reduce = String(o.reduce); + + if (o.query) { + let q = new this.Query(o.query); + q.cast(this); + o.query = q._conditions; + q = undefined; + } + + this.$__collection.mapReduce(null, null, o, (err, res) => { + if (err) { + return cb(err); + } + if (res.collection) { + // returned a collection, convert to Model + const model = Model.compile('_mapreduce_' + res.collection.collectionName, + Model.mapReduce.schema, res.collection.collectionName, this.db, + this.base); + + model._mapreduce = true; + res.model = model; + + return cb(null, res); + } + + cb(null, res); + }); + }, this.events); +}; + +/** + * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection. + * + * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned. + * + * This function triggers the following middleware. + * + * - `aggregate()` + * + * ####Example: + * + * // Find the max balance of all accounts + * const res = await Users.aggregate([ + * { $group: { _id: null, maxBalance: { $max: '$balance' }}}, + * { $project: { _id: 0, maxBalance: 1 }} + * ]); + * + * console.log(res); // [ { maxBalance: 98000 } ] + * + * // Or use the aggregation pipeline builder. + * const res = await Users.aggregate(). + * group({ _id: null, maxBalance: { $max: '$balance' } }). + * project('-id maxBalance'). + * exec(); + * console.log(res); // [ { maxBalance: 98 } ] + * + * ####NOTE: + * + * - Mongoose does **not** cast aggregation pipelines to the model's schema because `$project` and `$group` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. You can use the [mongoose-cast-aggregation plugin](https://github.com/AbdelrahmanHafez/mongoose-cast-aggregation) to enable minimal casting for aggregation pipelines. + * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). + * + * #### More About Aggregations: + * + * - [Mongoose `Aggregate`](/docs/api/aggregate.html) + * - [An Introduction to Mongoose Aggregate](https://masteringjs.io/tutorials/mongoose/aggregate) + * - [MongoDB Aggregation docs](http://docs.mongodb.org/manual/applications/aggregation/) + * + * @see Aggregate #aggregate_Aggregate + * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ + * @param {Array} [pipeline] aggregation pipeline as an array of objects + * @param {Object} [options] aggregation options + * @param {Function} [callback] + * @return {Aggregate} + * @api public + */ + +Model.aggregate = function aggregate(pipeline, options, callback) { + _checkContext(this, 'aggregate'); + + if (arguments.length > 3 || get(pipeline, 'constructor.name') === 'Object') { + throw new MongooseError('Mongoose 5.x disallows passing a spread of operators ' + + 'to `Model.aggregate()`. Instead of ' + + '`Model.aggregate({ $match }, { $skip })`, do ' + + '`Model.aggregate([{ $match }, { $skip }])`'); + } + + if (typeof pipeline === 'function') { + callback = pipeline; + pipeline = []; + } + + if (typeof options === 'function') { + callback = options; + options = null; + } + + const aggregate = new Aggregate(pipeline || []); + aggregate.model(this); + + if (options != null) { + aggregate.option(options); + } + + if (typeof callback === 'undefined') { + return aggregate; + } + + callback = this.$handleCallbackError(callback); + callback = this.$wrapCallback(callback); + + aggregate.exec(callback); + return aggregate; +}; + +/** + * Casts and validates the given object against this model's schema, passing the + * given `context` to custom validators. + * + * ####Example: + * + * const Model = mongoose.model('Test', Schema({ + * name: { type: String, required: true }, + * age: { type: Number, required: true } + * }); + * + * try { + * await Model.validate({ name: null }, ['name']) + * } catch (err) { + * err instanceof mongoose.Error.ValidationError; // true + * Object.keys(err.errors); // ['name'] + * } + * + * @param {Object} obj + * @param {Array} pathsToValidate + * @param {Object} [context] + * @param {Function} [callback] + * @return {Promise|undefined} + * @api public + */ + +Model.validate = function validate(obj, pathsToValidate, context, callback) { + if ((arguments.length < 3) || (arguments.length === 3 && typeof arguments[2] === 'function')) { + // For convenience, if we're validating a document or an object, make `context` default to + // the model so users don't have to always pass `context`, re: gh-10132, gh-10346 + context = obj; + } + + return this.db.base._promiseOrCallback(callback, cb => { + const schema = this.schema; + let paths = Object.keys(schema.paths); + + if (pathsToValidate != null) { + const _pathsToValidate = new Set(pathsToValidate); + paths = paths.filter(p => { + const pieces = p.split('.'); + let cur = pieces[0]; + + for (const piece of pieces) { + if (_pathsToValidate.has(cur)) { + return true; + } + cur += '.' + piece; + } + + return _pathsToValidate.has(p); + }); + } + + for (const path of paths) { + const schemaType = schema.path(path); + if (!schemaType || !schemaType.$isMongooseArray) { + continue; + } + + const val = get(obj, path); + pushNestedArrayPaths(val, path); + } + + let remaining = paths.length; + let error = null; + + for (const path of paths) { + const schemaType = schema.path(path); + if (schemaType == null) { + _checkDone(); + continue; + } + + const pieces = path.split('.'); + let cur = obj; + for (let i = 0; i < pieces.length - 1; ++i) { + cur = cur[pieces[i]]; + } + + let val = get(obj, path, void 0); + + if (val != null) { + try { + val = schemaType.cast(val); + cur[pieces[pieces.length - 1]] = val; + } catch (err) { + error = error || new ValidationError(); + error.addError(path, err); + + _checkDone(); + continue; + } + } + + schemaType.doValidate(val, err => { + if (err) { + error = error || new ValidationError(); + if (err instanceof ValidationError) { + for (const _err of Object.keys(err.errors)) { + error.addError(`${path}.${err.errors[_err].path}`, _err); + } + } else { + error.addError(err.path, err); + } + } + _checkDone(); + }, context, { path: path }); + } + + function pushNestedArrayPaths(nestedArray, path) { + if (nestedArray == null) { + return; + } + + for (let i = 0; i < nestedArray.length; ++i) { + if (Array.isArray(nestedArray[i])) { + pushNestedArrayPaths(nestedArray[i], path + '.' + i); + } else { + paths.push(path + '.' + i); + } + } + } + + function _checkDone() { + if (--remaining <= 0) { + return cb(error); + } + } + }); +}; + +/** + * Populates document references. + * + * Changed in Mongoose 6: the model you call `populate()` on should be the + * "local field" model, **not** the "foreign field" model. + * + * ####Available top-level options: + * + * - path: space delimited path(s) to populate + * - select: optional fields to select + * - match: optional query conditions to match + * - model: optional name of the model to use for population + * - options: optional query options like sort, limit, etc + * - justOne: optional boolean, if true Mongoose will always set `path` to an array. Inferred from schema by default. + * - strictPopulate: optional boolean, set to `false` to allow populating paths that aren't in the schema. + * + * ####Examples: + * + * const Dog = mongoose.model('Dog', new Schema({ name: String, breed: String })); + * const Person = mongoose.model('Person', new Schema({ + * name: String, + * pet: { type: mongoose.ObjectId, ref: 'Dog' } + * })); + * + * const pets = await Pet.create([ + * { name: 'Daisy', breed: 'Beagle' }, + * { name: 'Einstein', breed: 'Catalan Sheepdog' } + * ]); + * + * // populate many plain objects + * const users = [ + * { name: 'John Wick', dog: pets[0]._id }, + * { name: 'Doc Brown', dog: pets[1]._id } + * ]; + * await User.populate(users, { path: 'dog', select: 'name' }); + * users[0].dog.name; // 'Daisy' + * users[0].dog.breed; // undefined because of `select` + * + * @param {Document|Array} docs Either a single document or array of documents to populate. + * @param {Object|String} options Either the paths to populate or an object specifying all parameters + * @param {string} [options.path=null] The path to populate. + * @param {boolean} [options.retainNullValues=false] By default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. + * @param {boolean} [options.getters=false] If true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). + * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. + * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. + * @param {Boolean} [options.skipInvalidIds=false] By default, Mongoose throws a cast error if `localField` and `foreignField` schemas don't line up. If you enable this option, Mongoose will instead filter out any `localField` properties that cannot be casted to `foreignField`'s schema type. + * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents. + * @param {Boolean} [options.strictPopulate=true] Set to false to allow populating paths that aren't defined in the given model's schema. + * @param {Object} [options.options=null] Additional options like `limit` and `lean`. + * @param {Function} [options.transform=null] Function that Mongoose will call on every populated document that allows you to transform the populated document. + * @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. + * @return {Promise} + * @api public + */ + +Model.populate = function(docs, paths, callback) { + _checkContext(this, 'populate'); + + const _this = this; + + // normalized paths + paths = utils.populate(paths); + + // data that should persist across subPopulate calls + const cache = {}; + + callback = this.$handleCallbackError(callback); + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); + _populate(_this, docs, paths, cache, cb); + }, this.events); +}; + +/*! + * Populate helper + * + * @param {Model} model the model to use + * @param {Document|Array} docs Either a single document or array of documents to populate. + * @param {Object} paths + * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. + * @return {Function} + * @api private + */ + +function _populate(model, docs, paths, cache, callback) { + let pending = paths.length; + if (paths.length === 0) { + return callback(null, docs); + } + + // each path has its own query options and must be executed separately + for (const path of paths) { + populate(model, docs, path, next); + } + + function next(err) { + if (err) { + return callback(err, null); + } + if (--pending) { + return; + } + callback(null, docs); + } +} + +/*! + * Populates `docs` + */ +const excludeIdReg = /\s?-_id\s?/; +const excludeIdRegGlobal = /\s?-_id\s?/g; + +function populate(model, docs, options, callback) { + // normalize single / multiple docs passed + if (!Array.isArray(docs)) { + docs = [docs]; + } + if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) { + return callback(); + } + + const modelsMap = getModelsMapForPopulate(model, docs, options); + if (modelsMap instanceof MongooseError) { + return immediate(function() { + callback(modelsMap); + }); + } + + const len = modelsMap.length; + let vals = []; + + function flatten(item) { + // no need to include undefined values in our query + return undefined !== item; + } + + let _remaining = len; + let hasOne = false; + const params = []; + for (let i = 0; i < len; ++i) { + const mod = modelsMap[i]; + let select = mod.options.select; + let ids = utils.array.flatten(mod.ids, flatten); + ids = utils.array.unique(ids); + + const assignmentOpts = {}; + assignmentOpts.sort = get(mod, 'options.options.sort', void 0); + assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0); + + if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) { + // Ensure that we set to 0 or empty array even + // if we don't actually execute a query to make sure there's a value + // and we know this path was populated for future sets. See gh-7731, gh-8230 + --_remaining; + _assign(model, [], mod, assignmentOpts); + continue; + } + + hasOne = true; + const match = createPopulateQueryFilter(ids, mod.match, mod.foreignField, mod.model, mod.options.skipInvalidIds); + + if (assignmentOpts.excludeId) { + // override the exclusion from the query so we can use the _id + // for document matching during assignment. we'll delete the + // _id back off before returning the result. + if (typeof select === 'string') { + select = select.replace(excludeIdRegGlobal, ' '); + } else { + // preserve original select conditions by copying + select = utils.object.shallowCopy(select); + delete select._id; + } + } + + if (mod.options.options && mod.options.options.limit != null) { + assignmentOpts.originalLimit = mod.options.options.limit; + } else if (mod.options.limit != null) { + assignmentOpts.originalLimit = mod.options.limit; + } + params.push([mod, match, select, assignmentOpts, _next]); + } + if (!hasOne) { + // If models but no docs, skip further deep populate. + if (modelsMap.length > 0) { + return callback(); + } + // If no models to populate but we have a nested populate, + // keep trying, re: gh-8946 + if (options.populate != null) { + const opts = utils.populate(options.populate).map(pop => Object.assign({}, pop, { + path: options.path + '.' + pop.path + })); + return model.populate(docs, opts, callback); + } + return callback(); + } + + for (const arr of params) { + _execPopulateQuery.apply(null, arr); + } + function _next(err, valsFromDb) { + if (err != null) { + return callback(err, null); + } + vals = vals.concat(valsFromDb); + if (--_remaining === 0) { + _done(); + } + } + + function _done() { + for (const arr of params) { + const mod = arr[0]; + const assignmentOpts = arr[3]; + for (const val of vals) { + mod.options._childDocs.push(val); + } + _assign(model, vals, mod, assignmentOpts); + } + + for (const arr of params) { + removeDeselectedForeignField(arr[0].foreignField, arr[0].options, vals); + } + callback(); + } +} + +/*! + * ignore + */ + +function _execPopulateQuery(mod, match, select, assignmentOpts, callback) { + const subPopulate = utils.clone(mod.options.populate); + const queryOptions = Object.assign({ + skip: mod.options.skip, + limit: mod.options.limit, + perDocumentLimit: mod.options.perDocumentLimit + }, mod.options.options); + + if (mod.count) { + delete queryOptions.skip; + } + + if (queryOptions.perDocumentLimit != null) { + queryOptions.limit = queryOptions.perDocumentLimit; + delete queryOptions.perDocumentLimit; + } else if (queryOptions.limit != null) { + queryOptions.limit = queryOptions.limit * mod.ids.length; + } + + const query = mod.model.find(match, select, queryOptions); + // If we're doing virtual populate and projection is inclusive and foreign + // field is not selected, automatically select it because mongoose needs it. + // If projection is exclusive and client explicitly unselected the foreign + // field, that's the client's fault. + for (const foreignField of mod.foreignField) { + if (foreignField !== '_id' && query.selectedInclusively() && + !isPathSelectedInclusive(query._fields, foreignField)) { + query.select(foreignField); + } + } + + // If using count, still need the `foreignField` so we can match counts + // to documents, otherwise we would need a separate `count()` for every doc. + if (mod.count) { + for (const foreignField of mod.foreignField) { + query.select(foreignField); + } + } + + // If we need to sub-populate, call populate recursively + if (subPopulate) { + // If subpopulating on a discriminator, skip check for non-existent + // paths. Because the discriminator may not have the path defined. + if (mod.model.baseModelName != null) { + if (Array.isArray(subPopulate)) { + subPopulate.forEach(pop => { pop.strictPopulate = false; }); + } else { + subPopulate.strictPopulate = false; + } + } + query.populate(subPopulate); + } + + query.exec((err, docs) => { + if (err != null) { + return callback(err); + } + + for (const val of docs) { + leanPopulateMap.set(val, mod.model); + } + callback(null, docs); + }); +} + +/*! + * ignore + */ + +function _assign(model, vals, mod, assignmentOpts) { + const options = mod.options; + const isVirtual = mod.isVirtual; + const justOne = mod.justOne; + let _val; + const lean = get(options, 'options.lean', false); + const len = vals.length; + const rawOrder = {}; + const rawDocs = {}; + let key; + let val; + + // Clone because `assignRawDocsToIdStructure` will mutate the array + const allIds = utils.clone(mod.allIds); + // optimization: + // record the document positions as returned by + // the query result. + for (let i = 0; i < len; i++) { + val = vals[i]; + if (val == null) { + continue; + } + + for (const foreignField of mod.foreignField) { + _val = utils.getValue(foreignField, val); + if (Array.isArray(_val)) { + _val = utils.array.unique(utils.array.flatten(_val)); + + for (let __val of _val) { + if (__val instanceof Document) { + __val = __val._id; + } + key = String(__val); + if (rawDocs[key]) { + if (Array.isArray(rawDocs[key])) { + rawDocs[key].push(val); + rawOrder[key].push(i); + } else { + rawDocs[key] = [rawDocs[key], val]; + rawOrder[key] = [rawOrder[key], i]; + } + } else { + if (isVirtual && !justOne) { + rawDocs[key] = [val]; + rawOrder[key] = [i]; + } else { + rawDocs[key] = val; + rawOrder[key] = i; + } + } + } + } else { + if (_val instanceof Document) { + _val = _val._id; + } + key = String(_val); + if (rawDocs[key]) { + if (Array.isArray(rawDocs[key])) { + rawDocs[key].push(val); + rawOrder[key].push(i); + } else if (isVirtual || + rawDocs[key].constructor !== val.constructor || + String(rawDocs[key]._id) !== String(val._id)) { + // May need to store multiple docs with the same id if there's multiple models + // if we have discriminators or a ref function. But avoid converting to an array + // if we have multiple queries on the same model because of `perDocumentLimit` re: gh-9906 + rawDocs[key] = [rawDocs[key], val]; + rawOrder[key] = [rawOrder[key], i]; + } + } else { + rawDocs[key] = val; + rawOrder[key] = i; + } + } + // flag each as result of population + if (!lean) { + val.$__.wasPopulated = true; + } + } + } + + assignVals({ + originalModel: model, + // If virtual, make sure to not mutate original field + rawIds: mod.isVirtual ? allIds : mod.allIds, + allIds: allIds, + foreignField: mod.foreignField, + rawDocs: rawDocs, + rawOrder: rawOrder, + docs: mod.docs, + path: options.path, + options: assignmentOpts, + justOne: mod.justOne, + isVirtual: mod.isVirtual, + allOptions: mod, + populatedModel: mod.model, + lean: lean, + virtual: mod.virtual, + count: mod.count, + match: mod.match + }); +} + +/*! + * Compiler utility. + * + * @param {String|Function} name model name or class extending Model + * @param {Schema} schema + * @param {String} collectionName + * @param {Connection} connection + * @param {Mongoose} base mongoose instance + */ + +Model.compile = function compile(name, schema, collectionName, connection, base) { + const versioningEnabled = schema.options.versionKey !== false; + + if (versioningEnabled && !schema.paths[schema.options.versionKey]) { + // add versioning to top level documents only + const o = {}; + o[schema.options.versionKey] = Number; + schema.add(o); + } + + let model; + if (typeof name === 'function' && name.prototype instanceof Model) { + model = name; + name = model.name; + schema.loadClass(model, false); + model.prototype.$isMongooseModelPrototype = true; + } else { + // generate new class + model = function model(doc, fields, skipId) { + model.hooks.execPreSync('createModel', doc); + if (!(this instanceof model)) { + return new model(doc, fields, skipId); + } + const discriminatorKey = model.schema.options.discriminatorKey; + + if (model.discriminators == null || doc == null || doc[discriminatorKey] == null) { + Model.call(this, doc, fields, skipId); + return; + } + + // If discriminator key is set, use the discriminator instead (gh-7586) + const Discriminator = model.discriminators[doc[discriminatorKey]] || + getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]); + if (Discriminator != null) { + return new Discriminator(doc, fields, skipId); + } + + // Otherwise, just use the top-level model + Model.call(this, doc, fields, skipId); + }; + } + + model.hooks = schema.s.hooks.clone(); + model.base = base; + model.modelName = name; + + if (!(model.prototype instanceof Model)) { + model.__proto__ = Model; + model.prototype.__proto__ = Model.prototype; + } + model.model = function model(name) { + return this.db.model(name); + }; + model.db = connection; + model.prototype.db = connection; + model.prototype[modelDbSymbol] = connection; + model.discriminators = model.prototype.discriminators = undefined; + model[modelSymbol] = true; + model.events = new EventEmitter(); + + schema._preCompile(); + + model.prototype.$__setSchema(schema); + + const _userProvidedOptions = schema._userProvidedOptions || {}; + + const collectionOptions = { + schemaUserProvidedOptions: _userProvidedOptions, + capped: schema.options.capped, + Promise: model.base.Promise, + modelName: name + }; + if (schema.options.autoCreate !== void 0) { + collectionOptions.autoCreate = schema.options.autoCreate; + } + + model.prototype.collection = connection.collection( + collectionName, + collectionOptions + ); + + model.prototype.$collection = model.prototype.collection; + model.prototype[modelCollectionSymbol] = model.prototype.collection; + + // apply methods and statics + applyMethods(model, schema); + applyStatics(model, schema); + applyHooks(model, schema); + applyStaticHooks(model, schema.s.hooks, schema.statics); + + model.schema = model.prototype.$__schema; + model.collection = model.prototype.collection; + model.$__collection = model.collection; + + // Create custom query constructor + model.Query = function() { + Query.apply(this, arguments); + }; + model.Query.prototype = Object.create(Query.prototype); + model.Query.base = Query.base; + applyQueryMiddleware(model.Query, model); + applyQueryMethods(model, schema.query); + + return model; +}; + +/*! + * Register custom query methods for this model + * + * @param {Model} model + * @param {Schema} schema + */ + +function applyQueryMethods(model, methods) { + for (const i in methods) { + model.Query.prototype[i] = methods[i]; + } +} + +/*! + * Subclass this model with `conn`, `schema`, and `collection` settings. + * + * @param {Connection} conn + * @param {Schema} [schema] + * @param {String} [collection] + * @return {Model} + */ + +Model.__subclass = function subclass(conn, schema, collection) { + // subclass model using this connection and collection name + const _this = this; + + const Model = function Model(doc, fields, skipId) { + if (!(this instanceof Model)) { + return new Model(doc, fields, skipId); + } + _this.call(this, doc, fields, skipId); + }; + + Model.__proto__ = _this; + Model.prototype.__proto__ = _this.prototype; + Model.db = conn; + Model.prototype.db = conn; + Model.prototype[modelDbSymbol] = conn; + + _this[subclassedSymbol] = _this[subclassedSymbol] || []; + _this[subclassedSymbol].push(Model); + if (_this.discriminators != null) { + Model.discriminators = {}; + for (const key of Object.keys(_this.discriminators)) { + Model.discriminators[key] = _this.discriminators[key]. + __subclass(_this.db, _this.discriminators[key].schema, collection); + } + } + + const s = schema && typeof schema !== 'string' + ? schema + : _this.prototype.$__schema; + + const options = s.options || {}; + const _userProvidedOptions = s._userProvidedOptions || {}; + + if (!collection) { + collection = _this.prototype.$__schema.get('collection') || + utils.toCollectionName(_this.modelName, this.base.pluralize()); + } + + const collectionOptions = { + schemaUserProvidedOptions: _userProvidedOptions, + capped: s && options.capped + }; + + Model.prototype.collection = conn.collection(collection, collectionOptions); + Model.prototype.$collection = Model.prototype.collection; + Model.prototype[modelCollectionSymbol] = Model.prototype.collection; + Model.collection = Model.prototype.collection; + Model.$__collection = Model.collection; + // Errors handled internally, so ignore + Model.init(() => {}); + return Model; +}; + +Model.$handleCallbackError = function(callback) { + if (callback == null) { + return callback; + } + if (typeof callback !== 'function') { + throw new MongooseError('Callback must be a function, got ' + callback); + } + + const _this = this; + return function() { + immediate(() => { + try { + callback.apply(null, arguments); + } catch (error) { + _this.emit('error', error); + } + }); + }; +}; + +/*! + * ignore + */ + +Model.$wrapCallback = function(callback) { + const serverSelectionError = new ServerSelectionError(); + const _this = this; + + return function(err) { + if (err != null && err.name === 'MongoServerSelectionError') { + arguments[0] = serverSelectionError.assimilateError(err); + } + if (err != null && err.name === 'MongoNetworkTimeoutError' && err.message.endsWith('timed out')) { + _this.db.emit('timeout'); + } + + return callback.apply(null, arguments); + }; +}; + +/** + * Helper for console.log. Given a model named 'MyModel', returns the string + * `'Model { MyModel }'`. + * + * ####Example: + * + * const MyModel = mongoose.model('Test', Schema({ name: String })); + * MyModel.inspect(); // 'Model { Test }' + * console.log(MyModel); // Prints 'Model { Test }' + * + * @api public + */ + +Model.inspect = function() { + return `Model { ${this.modelName} }`; +}; + +if (util.inspect.custom) { + /*! + * Avoid Node deprecation warning DEP0079 + */ + + Model[util.inspect.custom] = Model.inspect; +} + +/*! + * Module exports. + */ + +module.exports = exports = Model; diff --git a/node_modules/mongoose/lib/options.js b/node_modules/mongoose/lib/options.js new file mode 100644 index 0000000..4826e59 --- /dev/null +++ b/node_modules/mongoose/lib/options.js @@ -0,0 +1,15 @@ +'use strict'; + +/*! + * ignore + */ + +exports.internalToObjectOptions = { + transform: false, + virtuals: false, + getters: false, + _skipDepopulateTopLevel: true, + depopulate: true, + flattenDecimals: false, + useProjection: false +}; diff --git a/node_modules/mongoose/lib/options/PopulateOptions.js b/node_modules/mongoose/lib/options/PopulateOptions.js new file mode 100644 index 0000000..5b98194 --- /dev/null +++ b/node_modules/mongoose/lib/options/PopulateOptions.js @@ -0,0 +1,36 @@ +'use strict'; + +const clone = require('../helpers/clone'); + +class PopulateOptions { + constructor(obj) { + this._docs = {}; + this._childDocs = []; + + if (obj == null) { + return; + } + obj = clone(obj); + Object.assign(this, obj); + if (typeof obj.subPopulate === 'object') { + this.populate = obj.subPopulate; + } + + + if (obj.perDocumentLimit != null && obj.limit != null) { + throw new Error('Can not use `limit` and `perDocumentLimit` at the same time. Path: `' + obj.path + '`.'); + } + } +} + +/** + * The connection used to look up models by name. If not specified, Mongoose + * will default to using the connection associated with the model in + * `PopulateOptions#model`. + * + * @memberOf PopulateOptions + * @property {Connection} connection + * @api public + */ + +module.exports = PopulateOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaArrayOptions.js b/node_modules/mongoose/lib/options/SchemaArrayOptions.js new file mode 100644 index 0000000..e3734ae --- /dev/null +++ b/node_modules/mongoose/lib/options/SchemaArrayOptions.js @@ -0,0 +1,59 @@ +'use strict'; + +const SchemaTypeOptions = require('./SchemaTypeOptions'); + +/** + * The options defined on an Array schematype. + * + * ####Example: + * + * const schema = new Schema({ tags: [String] }); + * schema.path('tags').options; // SchemaArrayOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaArrayOptions + */ + +class SchemaArrayOptions extends SchemaTypeOptions {} + +const opts = require('./propertyOptions'); + +/** + * If this is an array of strings, an array of allowed values for this path. + * Throws an error if this array isn't an array of strings. + * + * @api public + * @property enum + * @memberOf SchemaArrayOptions + * @type Array + * @instance + */ + +Object.defineProperty(SchemaArrayOptions.prototype, 'enum', opts); + +/** + * If set, specifies the type of this array's values. Equivalent to setting + * `type` to an array whose first element is `of`. + * + * ####Example: + * + * // `arr` is an array of numbers. + * new Schema({ arr: [Number] }); + * // Equivalent way to define `arr` as an array of numbers + * new Schema({ arr: { type: Array, of: Number } }); + * + * @api public + * @property of + * @memberOf SchemaArrayOptions + * @type Function|String + * @instance + */ + +Object.defineProperty(SchemaArrayOptions.prototype, 'of', opts); + +/*! + * ignore + */ + +module.exports = SchemaArrayOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaBufferOptions.js b/node_modules/mongoose/lib/options/SchemaBufferOptions.js new file mode 100644 index 0000000..258130d --- /dev/null +++ b/node_modules/mongoose/lib/options/SchemaBufferOptions.js @@ -0,0 +1,38 @@ +'use strict'; + +const SchemaTypeOptions = require('./SchemaTypeOptions'); + +/** + * The options defined on a Buffer schematype. + * + * ####Example: + * + * const schema = new Schema({ bitmap: Buffer }); + * schema.path('bitmap').options; // SchemaBufferOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaBufferOptions + */ + +class SchemaBufferOptions extends SchemaTypeOptions {} + +const opts = require('./propertyOptions'); + +/** + * Set the default subtype for this buffer. + * + * @api public + * @property subtype + * @memberOf SchemaBufferOptions + * @type Number + * @instance + */ + +Object.defineProperty(SchemaBufferOptions.prototype, 'subtype', opts); + +/*! + * ignore + */ + +module.exports = SchemaBufferOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaDateOptions.js b/node_modules/mongoose/lib/options/SchemaDateOptions.js new file mode 100644 index 0000000..09bf27f --- /dev/null +++ b/node_modules/mongoose/lib/options/SchemaDateOptions.js @@ -0,0 +1,64 @@ +'use strict'; + +const SchemaTypeOptions = require('./SchemaTypeOptions'); + +/** + * The options defined on a Date schematype. + * + * ####Example: + * + * const schema = new Schema({ startedAt: Date }); + * schema.path('startedAt').options; // SchemaDateOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaDateOptions + */ + +class SchemaDateOptions extends SchemaTypeOptions {} + +const opts = require('./propertyOptions'); + +/** + * If set, Mongoose adds a validator that checks that this path is after the + * given `min`. + * + * @api public + * @property min + * @memberOf SchemaDateOptions + * @type Date + * @instance + */ + +Object.defineProperty(SchemaDateOptions.prototype, 'min', opts); + +/** + * If set, Mongoose adds a validator that checks that this path is before the + * given `max`. + * + * @api public + * @property max + * @memberOf SchemaDateOptions + * @type Date + * @instance + */ + +Object.defineProperty(SchemaDateOptions.prototype, 'max', opts); + +/** + * If set, Mongoose creates a TTL index on this path. + * + * @api public + * @property expires + * @memberOf SchemaDateOptions + * @type Date + * @instance + */ + +Object.defineProperty(SchemaDateOptions.prototype, 'expires', opts); + +/*! + * ignore + */ + +module.exports = SchemaDateOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaDocumentArrayOptions.js b/node_modules/mongoose/lib/options/SchemaDocumentArrayOptions.js new file mode 100644 index 0000000..f3fb7a9 --- /dev/null +++ b/node_modules/mongoose/lib/options/SchemaDocumentArrayOptions.js @@ -0,0 +1,68 @@ +'use strict'; + +const SchemaTypeOptions = require('./SchemaTypeOptions'); + +/** + * The options defined on an Document Array schematype. + * + * ####Example: + * + * const schema = new Schema({ users: [{ name: string }] }); + * schema.path('users').options; // SchemaDocumentArrayOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaDocumentOptions + */ + +class SchemaDocumentArrayOptions extends SchemaTypeOptions {} + +const opts = require('./propertyOptions'); + +/** + * If `true`, Mongoose will skip building any indexes defined in this array's schema. + * If not set, Mongoose will build all indexes defined in this array's schema. + * + * ####Example: + * + * const childSchema = Schema({ name: { type: String, index: true } }); + * // If `excludeIndexes` is `true`, Mongoose will skip building an index + * // on `arr.name`. Otherwise, Mongoose will build an index on `arr.name`. + * const parentSchema = Schema({ + * arr: { type: [childSchema], excludeIndexes: true } + * }); + * + * @api public + * @property excludeIndexes + * @memberOf SchemaDocumentArrayOptions + * @type Array + * @instance + */ + +Object.defineProperty(SchemaDocumentArrayOptions.prototype, 'excludeIndexes', opts); + +/** + * If set, overwrites the child schema's `_id` option. + * + * ####Example: + * + * const childSchema = Schema({ name: String }); + * const parentSchema = Schema({ + * child: { type: childSchema, _id: false } + * }); + * parentSchema.path('child').schema.options._id; // false + * + * @api public + * @property _id + * @memberOf SchemaDocumentArrayOptions + * @type Array + * @instance + */ + +Object.defineProperty(SchemaDocumentArrayOptions.prototype, '_id', opts); + +/*! + * ignore + */ + +module.exports = SchemaDocumentArrayOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaMapOptions.js b/node_modules/mongoose/lib/options/SchemaMapOptions.js new file mode 100644 index 0000000..335d84a --- /dev/null +++ b/node_modules/mongoose/lib/options/SchemaMapOptions.js @@ -0,0 +1,43 @@ +'use strict'; + +const SchemaTypeOptions = require('./SchemaTypeOptions'); + +/** + * The options defined on a Map schematype. + * + * ####Example: + * + * const schema = new Schema({ socialMediaHandles: { type: Map, of: String } }); + * schema.path('socialMediaHandles').options; // SchemaMapOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaMapOptions + */ + +class SchemaMapOptions extends SchemaTypeOptions {} + +const opts = require('./propertyOptions'); + +/** + * If set, specifies the type of this map's values. Mongoose will cast + * this map's values to the given type. + * + * If not set, Mongoose will not cast the map's values. + * + * ####Example: + * + * // Mongoose will cast `socialMediaHandles` values to strings + * const schema = new Schema({ socialMediaHandles: { type: Map, of: String } }); + * schema.path('socialMediaHandles').options.of; // String + * + * @api public + * @property of + * @memberOf SchemaMapOptions + * @type Function|string + * @instance + */ + +Object.defineProperty(SchemaMapOptions.prototype, 'of', opts); + +module.exports = SchemaMapOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaNumberOptions.js b/node_modules/mongoose/lib/options/SchemaNumberOptions.js new file mode 100644 index 0000000..38553fb --- /dev/null +++ b/node_modules/mongoose/lib/options/SchemaNumberOptions.js @@ -0,0 +1,99 @@ +'use strict'; + +const SchemaTypeOptions = require('./SchemaTypeOptions'); + +/** + * The options defined on a Number schematype. + * + * ####Example: + * + * const schema = new Schema({ count: Number }); + * schema.path('count').options; // SchemaNumberOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaNumberOptions + */ + +class SchemaNumberOptions extends SchemaTypeOptions {} + +const opts = require('./propertyOptions'); + +/** + * If set, Mongoose adds a validator that checks that this path is at least the + * given `min`. + * + * @api public + * @property min + * @memberOf SchemaNumberOptions + * @type Number + * @instance + */ + +Object.defineProperty(SchemaNumberOptions.prototype, 'min', opts); + +/** + * If set, Mongoose adds a validator that checks that this path is less than the + * given `max`. + * + * @api public + * @property max + * @memberOf SchemaNumberOptions + * @type Number + * @instance + */ + +Object.defineProperty(SchemaNumberOptions.prototype, 'max', opts); + +/** + * If set, Mongoose adds a validator that checks that this path is strictly + * equal to one of the given values. + * + * ####Example: + * const schema = new Schema({ + * favoritePrime: { + * type: Number, + * enum: [3, 5, 7] + * } + * }); + * schema.path('favoritePrime').options.enum; // [3, 5, 7] + * + * @api public + * @property enum + * @memberOf SchemaNumberOptions + * @type Array + * @instance + */ + +Object.defineProperty(SchemaNumberOptions.prototype, 'enum', opts); + +/** + * Sets default [populate options](/docs/populate.html#query-conditions). + * + * ####Example: + * const schema = new Schema({ + * child: { + * type: Number, + * ref: 'Child', + * populate: { select: 'name' } + * } + * }); + * const Parent = mongoose.model('Parent', schema); + * + * // Automatically adds `.select('name')` + * Parent.findOne().populate('child'); + * + * @api public + * @property populate + * @memberOf SchemaNumberOptions + * @type Object + * @instance + */ + +Object.defineProperty(SchemaNumberOptions.prototype, 'populate', opts); + +/*! + * ignore + */ + +module.exports = SchemaNumberOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaObjectIdOptions.js b/node_modules/mongoose/lib/options/SchemaObjectIdOptions.js new file mode 100644 index 0000000..e07ed9e --- /dev/null +++ b/node_modules/mongoose/lib/options/SchemaObjectIdOptions.js @@ -0,0 +1,63 @@ +'use strict'; + +const SchemaTypeOptions = require('./SchemaTypeOptions'); + +/** + * The options defined on an ObjectId schematype. + * + * ####Example: + * + * const schema = new Schema({ testId: mongoose.ObjectId }); + * schema.path('testId').options; // SchemaObjectIdOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaObjectIdOptions + */ + +class SchemaObjectIdOptions extends SchemaTypeOptions {} + +const opts = require('./propertyOptions'); + +/** + * If truthy, uses Mongoose's default built-in ObjectId path. + * + * @api public + * @property auto + * @memberOf SchemaObjectIdOptions + * @type Boolean + * @instance + */ + +Object.defineProperty(SchemaObjectIdOptions.prototype, 'auto', opts); + +/** + * Sets default [populate options](/docs/populate.html#query-conditions). + * + * ####Example: + * const schema = new Schema({ + * child: { + * type: 'ObjectId', + * ref: 'Child', + * populate: { select: 'name' } + * } + * }); + * const Parent = mongoose.model('Parent', schema); + * + * // Automatically adds `.select('name')` + * Parent.findOne().populate('child'); + * + * @api public + * @property populate + * @memberOf SchemaObjectIdOptions + * @type Object + * @instance + */ + +Object.defineProperty(SchemaObjectIdOptions.prototype, 'populate', opts); + +/*! + * ignore + */ + +module.exports = SchemaObjectIdOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaStringOptions.js b/node_modules/mongoose/lib/options/SchemaStringOptions.js new file mode 100644 index 0000000..f67476f --- /dev/null +++ b/node_modules/mongoose/lib/options/SchemaStringOptions.js @@ -0,0 +1,138 @@ +'use strict'; + +const SchemaTypeOptions = require('./SchemaTypeOptions'); + +/** + * The options defined on a string schematype. + * + * ####Example: + * + * const schema = new Schema({ name: String }); + * schema.path('name').options; // SchemaStringOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaStringOptions + */ + +class SchemaStringOptions extends SchemaTypeOptions {} + +const opts = require('./propertyOptions'); + +/** + * Array of allowed values for this path + * + * @api public + * @property enum + * @memberOf SchemaStringOptions + * @type Array + * @instance + */ + +Object.defineProperty(SchemaStringOptions.prototype, 'enum', opts); + +/** + * Attach a validator that succeeds if the data string matches the given regular + * expression, and fails otherwise. + * + * @api public + * @property match + * @memberOf SchemaStringOptions + * @type RegExp + * @instance + */ + +Object.defineProperty(SchemaStringOptions.prototype, 'match', opts); + +/** + * If truthy, Mongoose will add a custom setter that lowercases this string + * using JavaScript's built-in `String#toLowerCase()`. + * + * @api public + * @property lowercase + * @memberOf SchemaStringOptions + * @type Boolean + * @instance + */ + +Object.defineProperty(SchemaStringOptions.prototype, 'lowercase', opts); + +/** + * If truthy, Mongoose will add a custom setter that removes leading and trailing + * whitespace using [JavaScript's built-in `String#trim()`](https://masteringjs.io/tutorials/fundamentals/trim-string). + * + * @api public + * @property trim + * @memberOf SchemaStringOptions + * @type Boolean + * @instance + */ + +Object.defineProperty(SchemaStringOptions.prototype, 'trim', opts); + +/** + * If truthy, Mongoose will add a custom setter that uppercases this string + * using JavaScript's built-in [`String#toUpperCase()`](https://masteringjs.io/tutorials/fundamentals/uppercase). + * + * @api public + * @property uppercase + * @memberOf SchemaStringOptions + * @type Boolean + * @instance + */ + +Object.defineProperty(SchemaStringOptions.prototype, 'uppercase', opts); + +/** + * If set, Mongoose will add a custom validator that ensures the given + * string's `length` is at least the given number. + * + * Mongoose supports two different spellings for this option: `minLength` and `minlength`. + * `minLength` is the recommended way to specify this option, but Mongoose also supports + * `minlength` (lowercase "l"). + * + * @api public + * @property minLength + * @memberOf SchemaStringOptions + * @type Number + * @instance + */ + +Object.defineProperty(SchemaStringOptions.prototype, 'minLength', opts); +Object.defineProperty(SchemaStringOptions.prototype, 'minlength', opts); + +/** + * If set, Mongoose will add a custom validator that ensures the given + * string's `length` is at most the given number. + * + * Mongoose supports two different spellings for this option: `maxLength` and `maxlength`. + * `maxLength` is the recommended way to specify this option, but Mongoose also supports + * `maxlength` (lowercase "l"). + * + * @api public + * @property maxLength + * @memberOf SchemaStringOptions + * @type Number + * @instance + */ + +Object.defineProperty(SchemaStringOptions.prototype, 'maxLength', opts); +Object.defineProperty(SchemaStringOptions.prototype, 'maxlength', opts); + +/** + * Sets default [populate options](/docs/populate.html#query-conditions). + * + * @api public + * @property populate + * @memberOf SchemaStringOptions + * @type Object + * @instance + */ + +Object.defineProperty(SchemaStringOptions.prototype, 'populate', opts); + +/*! + * ignore + */ + +module.exports = SchemaStringOptions; diff --git a/node_modules/mongoose/lib/options/SchemaSubdocumentOptions.js b/node_modules/mongoose/lib/options/SchemaSubdocumentOptions.js new file mode 100644 index 0000000..1675653 --- /dev/null +++ b/node_modules/mongoose/lib/options/SchemaSubdocumentOptions.js @@ -0,0 +1,42 @@ +'use strict'; + +const SchemaTypeOptions = require('./SchemaTypeOptions'); + +/** + * The options defined on a single nested schematype. + * + * ####Example: + * + * const schema = Schema({ child: Schema({ name: String }) }); + * schema.path('child').options; // SchemaSubdocumentOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaSubdocumentOptions + */ + +class SchemaSubdocumentOptions extends SchemaTypeOptions {} + +const opts = require('./propertyOptions'); + +/** + * If set, overwrites the child schema's `_id` option. + * + * ####Example: + * + * const childSchema = Schema({ name: String }); + * const parentSchema = Schema({ + * child: { type: childSchema, _id: false } + * }); + * parentSchema.path('child').schema.options._id; // false + * + * @api public + * @property of + * @memberOf SchemaSubdocumentOptions + * @type Function|string + * @instance + */ + +Object.defineProperty(SchemaSubdocumentOptions.prototype, '_id', opts); + +module.exports = SchemaSubdocumentOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaTypeOptions.js b/node_modules/mongoose/lib/options/SchemaTypeOptions.js new file mode 100644 index 0000000..d9149ba --- /dev/null +++ b/node_modules/mongoose/lib/options/SchemaTypeOptions.js @@ -0,0 +1,231 @@ +'use strict'; + +const clone = require('../helpers/clone'); + +/** + * The options defined on a schematype. + * + * ####Example: + * + * const schema = new Schema({ name: String }); + * schema.path('name').options instanceof mongoose.SchemaTypeOptions; // true + * + * @api public + * @constructor SchemaTypeOptions + */ + +class SchemaTypeOptions { + constructor(obj) { + if (obj == null) { + return this; + } + Object.assign(this, clone(obj)); + } +} + +const opts = require('./propertyOptions'); + +/** + * The type to cast this path to. + * + * @api public + * @property type + * @memberOf SchemaTypeOptions + * @type Function|String|Object + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'type', opts); + +/** + * Function or object describing how to validate this schematype. + * + * @api public + * @property validate + * @memberOf SchemaTypeOptions + * @type Function|Object + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'validate', opts); + +/** + * Allows overriding casting logic for this individual path. If a string, the + * given string overwrites Mongoose's default cast error message. + * + * ####Example: + * + * const schema = new Schema({ + * num: { + * type: Number, + * cast: '{VALUE} is not a valid number' + * } + * }); + * + * // Throws 'CastError: "bad" is not a valid number' + * schema.path('num').cast('bad'); + * + * const Model = mongoose.model('Test', schema); + * const doc = new Model({ num: 'fail' }); + * const err = doc.validateSync(); + * + * err.errors['num']; // 'CastError: "fail" is not a valid number' + * + * @api public + * @property cast + * @memberOf SchemaTypeOptions + * @type String + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'cast', opts); + +/** + * If true, attach a required validator to this path, which ensures this path + * path cannot be set to a nullish value. If a function, Mongoose calls the + * function and only checks for nullish values if the function returns a truthy value. + * + * @api public + * @property required + * @memberOf SchemaTypeOptions + * @type Function|Boolean + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'required', opts); + +/** + * The default value for this path. If a function, Mongoose executes the function + * and uses the return value as the default. + * + * @api public + * @property default + * @memberOf SchemaTypeOptions + * @type Function|Any + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'default', opts); + +/** + * The model that `populate()` should use if populating this path. + * + * @api public + * @property ref + * @memberOf SchemaTypeOptions + * @type Function|String + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'ref', opts); + +/** + * Whether to include or exclude this path by default when loading documents + * using `find()`, `findOne()`, etc. + * + * @api public + * @property select + * @memberOf SchemaTypeOptions + * @type Boolean|Number + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'select', opts); + +/** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will + * build an index on this path when the model is compiled. + * + * @api public + * @property index + * @memberOf SchemaTypeOptions + * @type Boolean|Number|Object + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'index', opts); + +/** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose + * will build a unique index on this path when the + * model is compiled. [The `unique` option is **not** a validator](/docs/validation.html#the-unique-option-is-not-a-validator). + * + * @api public + * @property unique + * @memberOf SchemaTypeOptions + * @type Boolean|Number + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'unique', opts); + +/** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will + * disallow changes to this path once the document + * is saved to the database for the first time. Read more about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html). + * + * @api public + * @property immutable + * @memberOf SchemaTypeOptions + * @type Function|Boolean + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'immutable', opts); + +/** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will + * build a sparse index on this path. + * + * @api public + * @property sparse + * @memberOf SchemaTypeOptions + * @type Boolean|Number + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'sparse', opts); + +/** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose + * will build a text index on this path. + * + * @api public + * @property text + * @memberOf SchemaTypeOptions + * @type Boolean|Number|Object + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'text', opts); + +/** + * Define a transform function for this individual schema type. + * Only called when calling `toJSON()` or `toObject()`. + * + * ####Example: + * + * const schema = Schema({ + * myDate: { + * type: Date, + * transform: v => v.getFullYear() + * } + * }); + * const Model = mongoose.model('Test', schema); + * + * const doc = new Model({ myDate: new Date('2019/06/01') }); + * doc.myDate instanceof Date; // true + * + * const res = doc.toObject({ transform: true }); + * res.myDate; // 2019 + * + * @api public + * @property transform + * @memberOf SchemaTypeOptions + * @type Function + * @instance + */ + +Object.defineProperty(SchemaTypeOptions.prototype, 'transform', opts); + +module.exports = SchemaTypeOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/VirtualOptions.js b/node_modules/mongoose/lib/options/VirtualOptions.js new file mode 100644 index 0000000..a266414 --- /dev/null +++ b/node_modules/mongoose/lib/options/VirtualOptions.js @@ -0,0 +1,164 @@ +'use strict'; + +const opts = require('./propertyOptions'); + +class VirtualOptions { + constructor(obj) { + Object.assign(this, obj); + + if (obj != null && obj.options != null) { + this.options = Object.assign({}, obj.options); + } + } +} + +/** + * Marks this virtual as a populate virtual, and specifies the model to + * use for populate. + * + * @api public + * @property ref + * @memberOf VirtualOptions + * @type String|Model|Function + * @instance + */ + +Object.defineProperty(VirtualOptions.prototype, 'ref', opts); + +/** + * Marks this virtual as a populate virtual, and specifies the path that + * contains the name of the model to populate + * + * @api public + * @property refPath + * @memberOf VirtualOptions + * @type String|Function + * @instance + */ + +Object.defineProperty(VirtualOptions.prototype, 'refPath', opts); + +/** + * The name of the property in the local model to match to `foreignField` + * in the foreign model. + * + * @api public + * @property localField + * @memberOf VirtualOptions + * @type String|Function + * @instance + */ + +Object.defineProperty(VirtualOptions.prototype, 'localField', opts); + +/** + * The name of the property in the foreign model to match to `localField` + * in the local model. + * + * @api public + * @property foreignField + * @memberOf VirtualOptions + * @type String|Function + * @instance + */ + +Object.defineProperty(VirtualOptions.prototype, 'foreignField', opts); + +/** + * Whether to populate this virtual as a single document (true) or an + * array of documents (false). + * + * @api public + * @property justOne + * @memberOf VirtualOptions + * @type Boolean + * @instance + */ + +Object.defineProperty(VirtualOptions.prototype, 'justOne', opts); + +/** + * If true, populate just the number of documents where `localField` + * matches `foreignField`, as opposed to the documents themselves. + * + * If `count` is set, it overrides `justOne`. + * + * @api public + * @property count + * @memberOf VirtualOptions + * @type Boolean + * @instance + */ + +Object.defineProperty(VirtualOptions.prototype, 'count', opts); + +/** + * Add an additional filter to populate, in addition to `localField` + * matches `foreignField`. + * + * @api public + * @property match + * @memberOf VirtualOptions + * @type Object|Function + * @instance + */ + +Object.defineProperty(VirtualOptions.prototype, 'match', opts); + +/** + * Additional options to pass to the query used to `populate()`: + * + * - `sort` + * - `skip` + * - `limit` + * + * @api public + * @property options + * @memberOf VirtualOptions + * @type Object + * @instance + */ + +Object.defineProperty(VirtualOptions.prototype, 'options', opts); + +/** + * If true, add a `skip` to the query used to `populate()`. + * + * @api public + * @property skip + * @memberOf VirtualOptions + * @type Number + * @instance + */ + +Object.defineProperty(VirtualOptions.prototype, 'skip', opts); + +/** + * If true, add a `limit` to the query used to `populate()`. + * + * @api public + * @property limit + * @memberOf VirtualOptions + * @type Number + * @instance + */ + +Object.defineProperty(VirtualOptions.prototype, 'limit', opts); + +/** + * The `limit` option for `populate()` has [some unfortunate edge cases](/docs/populate.html#query-conditions) + * when working with multiple documents, like `.find().populate()`. The + * `perDocumentLimit` option makes `populate()` execute a separate query + * for each document returned from `find()` to ensure each document + * gets up to `perDocumentLimit` populated docs if possible. + * + * @api public + * @property perDocumentLimit + * @memberOf VirtualOptions + * @type Number + * @instance + */ + +Object.defineProperty(VirtualOptions.prototype, 'perDocumentLimit', opts); + +module.exports = VirtualOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/propertyOptions.js b/node_modules/mongoose/lib/options/propertyOptions.js new file mode 100644 index 0000000..b7488a3 --- /dev/null +++ b/node_modules/mongoose/lib/options/propertyOptions.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = Object.freeze({ + enumerable: true, + configurable: true, + writable: true, + value: void 0 +}); \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/removeOptions.js b/node_modules/mongoose/lib/options/removeOptions.js new file mode 100644 index 0000000..0d91586 --- /dev/null +++ b/node_modules/mongoose/lib/options/removeOptions.js @@ -0,0 +1,14 @@ +'use strict'; + +const clone = require('../helpers/clone'); + +class RemoveOptions { + constructor(obj) { + if (obj == null) { + return; + } + Object.assign(this, clone(obj)); + } +} + +module.exports = RemoveOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/saveOptions.js b/node_modules/mongoose/lib/options/saveOptions.js new file mode 100644 index 0000000..22ef437 --- /dev/null +++ b/node_modules/mongoose/lib/options/saveOptions.js @@ -0,0 +1,14 @@ +'use strict'; + +const clone = require('../helpers/clone'); + +class SaveOptions { + constructor(obj) { + if (obj == null) { + return; + } + Object.assign(this, clone(obj)); + } +} + +module.exports = SaveOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/plugins/removeSubdocs.js b/node_modules/mongoose/lib/plugins/removeSubdocs.js new file mode 100644 index 0000000..c2756fc --- /dev/null +++ b/node_modules/mongoose/lib/plugins/removeSubdocs.js @@ -0,0 +1,31 @@ +'use strict'; + +const each = require('../helpers/each'); + +/*! + * ignore + */ + +module.exports = function(schema) { + const unshift = true; + schema.s.hooks.pre('remove', false, function(next) { + if (this.ownerDocument) { + next(); + return; + } + + const _this = this; + const subdocs = this.$getAllSubdocs(); + + each(subdocs, function(subdoc, cb) { + subdoc.$__remove(cb); + }, function(error) { + if (error) { + return _this.$__schema.s.hooks.execPost('remove:error', _this, [_this], { error: error }, function(error) { + next(error); + }); + } + next(); + }); + }, null, unshift); +}; diff --git a/node_modules/mongoose/lib/plugins/saveSubdocs.js b/node_modules/mongoose/lib/plugins/saveSubdocs.js new file mode 100644 index 0000000..fcc73d8 --- /dev/null +++ b/node_modules/mongoose/lib/plugins/saveSubdocs.js @@ -0,0 +1,66 @@ +'use strict'; + +const each = require('../helpers/each'); + +/*! + * ignore + */ + +module.exports = function(schema) { + const unshift = true; + schema.s.hooks.pre('save', false, function(next) { + if (this.ownerDocument) { + next(); + return; + } + + const _this = this; + const subdocs = this.$getAllSubdocs(); + + if (!subdocs.length) { + next(); + return; + } + + each(subdocs, function(subdoc, cb) { + subdoc.$__schema.s.hooks.execPre('save', subdoc, function(err) { + cb(err); + }); + }, function(error) { + if (error) { + return _this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { + next(error); + }); + } + next(); + }); + }, null, unshift); + + schema.s.hooks.post('save', function(doc, next) { + if (this.ownerDocument) { + next(); + return; + } + + const _this = this; + const subdocs = this.$getAllSubdocs(); + + if (!subdocs.length) { + next(); + return; + } + + each(subdocs, function(subdoc, cb) { + subdoc.$__schema.s.hooks.execPost('save', subdoc, [subdoc], function(err) { + cb(err); + }); + }, function(error) { + if (error) { + return _this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { + next(error); + }); + } + next(); + }); + }, null, unshift); +}; diff --git a/node_modules/mongoose/lib/plugins/sharding.js b/node_modules/mongoose/lib/plugins/sharding.js new file mode 100644 index 0000000..020ec06 --- /dev/null +++ b/node_modules/mongoose/lib/plugins/sharding.js @@ -0,0 +1,83 @@ +'use strict'; + +const objectIdSymbol = require('../helpers/symbols').objectIdSymbol; +const utils = require('../utils'); + +/*! + * ignore + */ + +module.exports = function shardingPlugin(schema) { + schema.post('init', function() { + storeShard.call(this); + return this; + }); + schema.pre('save', function(next) { + applyWhere.call(this); + next(); + }); + schema.pre('remove', function(next) { + applyWhere.call(this); + next(); + }); + schema.post('save', function() { + storeShard.call(this); + }); +}; + +/*! + * ignore + */ + +function applyWhere() { + let paths; + let len; + + if (this.$__.shardval) { + paths = Object.keys(this.$__.shardval); + len = paths.length; + + this.$where = this.$where || {}; + for (let i = 0; i < len; ++i) { + this.$where[paths[i]] = this.$__.shardval[paths[i]]; + } + } +} + +/*! + * ignore + */ + +module.exports.storeShard = storeShard; + +/*! + * ignore + */ + +function storeShard() { + // backwards compat + const key = this.$__schema.options.shardKey || this.$__schema.options.shardkey; + if (!utils.isPOJO(key)) { + return; + } + + const orig = this.$__.shardval = {}; + const paths = Object.keys(key); + const len = paths.length; + let val; + + for (let i = 0; i < len; ++i) { + val = this.$__getValue(paths[i]); + if (val == null) { + orig[paths[i]] = val; + } else if (utils.isMongooseObject(val)) { + orig[paths[i]] = val.toObject({ depopulate: true, _isNested: true }); + } else if (val instanceof Date || val[objectIdSymbol]) { + orig[paths[i]] = val; + } else if (typeof val.valueOf === 'function') { + orig[paths[i]] = val.valueOf(); + } else { + orig[paths[i]] = val; + } + } +} diff --git a/node_modules/mongoose/lib/plugins/trackTransaction.js b/node_modules/mongoose/lib/plugins/trackTransaction.js new file mode 100644 index 0000000..30ded87 --- /dev/null +++ b/node_modules/mongoose/lib/plugins/trackTransaction.js @@ -0,0 +1,91 @@ +'use strict'; + +const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol; +const sessionNewDocuments = require('../helpers/symbols').sessionNewDocuments; + +module.exports = function trackTransaction(schema) { + schema.pre('save', function() { + const session = this.$session(); + if (session == null) { + return; + } + if (session.transaction == null || session[sessionNewDocuments] == null) { + return; + } + + if (!session[sessionNewDocuments].has(this)) { + const initialState = {}; + if (this.isNew) { + initialState.isNew = true; + } + if (this.$__schema.options.versionKey) { + initialState.versionKey = this.get(this.$__schema.options.versionKey); + } + + initialState.modifiedPaths = new Set(Object.keys(this.$__.activePaths.states.modify)); + initialState.atomics = _getAtomics(this); + + session[sessionNewDocuments].set(this, initialState); + } else { + const state = session[sessionNewDocuments].get(this); + + for (const path of Object.keys(this.$__.activePaths.states.modify)) { + state.modifiedPaths.add(path); + } + state.atomics = _getAtomics(this, state.atomics); + } + }); +}; + +function _getAtomics(doc, previous) { + const pathToAtomics = new Map(); + previous = previous || new Map(); + + const pathsToCheck = Object.keys(doc.$__.activePaths.init).concat(Object.keys(doc.$__.activePaths.modify)); + + for (const path of pathsToCheck) { + const val = doc.$__getValue(path); + if (val != null && + val instanceof Array && + val.isMongooseDocumentArray && + val.length && + val[arrayAtomicsSymbol] != null && + Object.keys(val[arrayAtomicsSymbol]).length > 0) { + const existing = previous.get(path) || {}; + pathToAtomics.set(path, mergeAtomics(existing, val[arrayAtomicsSymbol])); + } + } + + const dirty = doc.$__dirty(); + for (const dirt of dirty) { + const path = dirt.path; + + const val = dirt.value; + if (val != null && val[arrayAtomicsSymbol] != null && Object.keys(val[arrayAtomicsSymbol]).length > 0) { + const existing = previous.get(path) || {}; + pathToAtomics.set(path, mergeAtomics(existing, val[arrayAtomicsSymbol])); + } + } + + return pathToAtomics; +} + +function mergeAtomics(destination, source) { + destination = destination || {}; + + if (source.$pullAll != null) { + destination.$pullAll = (destination.$pullAll || []).concat(source.$pullAll); + } + if (source.$push != null) { + destination.$push = destination.$push || {}; + destination.$push.$each = (destination.$push.$each || []).concat(source.$push.$each); + } + if (source.$addToSet != null) { + destination.$addToSet = (destination.$addToSet || []).concat(source.$addToSet); + } + if (source.$set != null) { + destination.$set = Object.assign(destination.$set || {}, source.$set); + } + + return destination; +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/plugins/validateBeforeSave.js b/node_modules/mongoose/lib/plugins/validateBeforeSave.js new file mode 100644 index 0000000..b9a93b2 --- /dev/null +++ b/node_modules/mongoose/lib/plugins/validateBeforeSave.js @@ -0,0 +1,45 @@ +'use strict'; + +/*! + * ignore + */ + +module.exports = function(schema) { + const unshift = true; + schema.pre('save', false, function validateBeforeSave(next, options) { + const _this = this; + // Nested docs have their own presave + if (this.ownerDocument) { + return next(); + } + + const hasValidateBeforeSaveOption = options && + (typeof options === 'object') && + ('validateBeforeSave' in options); + + let shouldValidate; + if (hasValidateBeforeSaveOption) { + shouldValidate = !!options.validateBeforeSave; + } else { + shouldValidate = this.$__schema.options.validateBeforeSave; + } + + // Validate + if (shouldValidate) { + const hasValidateModifiedOnlyOption = options && + (typeof options === 'object') && + ('validateModifiedOnly' in options); + const validateOptions = hasValidateModifiedOnlyOption ? + { validateModifiedOnly: options.validateModifiedOnly } : + null; + this.$validate(validateOptions, function(error) { + return _this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { + _this.$op = 'save'; + next(error); + }); + }); + } else { + next(); + } + }, null, unshift); +}; diff --git a/node_modules/mongoose/lib/promise_provider.js b/node_modules/mongoose/lib/promise_provider.js new file mode 100644 index 0000000..3febf36 --- /dev/null +++ b/node_modules/mongoose/lib/promise_provider.js @@ -0,0 +1,49 @@ +/*! + * ignore + */ + +'use strict'; + +const assert = require('assert'); +const mquery = require('mquery'); + +/** + * Helper for multiplexing promise implementations + * + * @api private + */ + +const store = { + _promise: null +}; + +/** + * Get the current promise constructor + * + * @api private + */ + +store.get = function() { + return store._promise; +}; + +/** + * Set the current promise constructor + * + * @api private + */ + +store.set = function(lib) { + assert.ok(typeof lib === 'function', + `mongoose.Promise must be a function, got ${lib}`); + store._promise = lib; + mquery.Promise = lib; +}; + +/*! + * Use native promises by default + */ + +store.set(global.Promise); + +module.exports = store; diff --git a/node_modules/mongoose/lib/query.js b/node_modules/mongoose/lib/query.js new file mode 100644 index 0000000..bfefb2b --- /dev/null +++ b/node_modules/mongoose/lib/query.js @@ -0,0 +1,5598 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const CastError = require('./error/cast'); +const DocumentNotFoundError = require('./error/notFound'); +const Kareem = require('kareem'); +const MongooseError = require('./error/mongooseError'); +const ObjectParameterError = require('./error/objectParameter'); +const QueryCursor = require('./cursor/QueryCursor'); +const ReadPreference = require('./driver').get().ReadPreference; +const applyGlobalMaxTimeMS = require('./helpers/query/applyGlobalMaxTimeMS'); +const applyWriteConcern = require('./helpers/schema/applyWriteConcern'); +const cast = require('./cast'); +const castArrayFilters = require('./helpers/update/castArrayFilters'); +const castUpdate = require('./helpers/query/castUpdate'); +const completeMany = require('./helpers/query/completeMany'); +const get = require('./helpers/get'); +const promiseOrCallback = require('./helpers/promiseOrCallback'); +const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue'); +const hasDollarKeys = require('./helpers/query/hasDollarKeys'); +const helpers = require('./queryhelpers'); +const immediate = require('./helpers/immediate'); +const isExclusive = require('./helpers/projection/isExclusive'); +const isInclusive = require('./helpers/projection/isInclusive'); +const mquery = require('mquery'); +const parseProjection = require('./helpers/projection/parseProjection'); +const removeUnusedArrayFilters = require('./helpers/update/removeUnusedArrayFilters'); +const sanitizeFilter = require('./helpers/query/sanitizeFilter'); +const sanitizeProjection = require('./helpers/query/sanitizeProjection'); +const selectPopulatedFields = require('./helpers/query/selectPopulatedFields'); +const setDefaultsOnInsert = require('./helpers/setDefaultsOnInsert'); +const slice = require('sliced'); +const updateValidators = require('./helpers/updateValidators'); +const util = require('util'); +const utils = require('./utils'); +const validOps = require('./helpers/query/validOps'); +const wrapThunk = require('./helpers/query/wrapThunk'); + +/** + * Query constructor used for building queries. You do not need + * to instantiate a `Query` directly. Instead use Model functions like + * [`Model.find()`](/docs/api.html#find_find). + * + * ####Example: + * + * const query = MyModel.find(); // `query` is an instance of `Query` + * query.setOptions({ lean : true }); + * query.collection(MyModel.collection); + * query.where('age').gte(21).exec(callback); + * + * // You can instantiate a query directly. There is no need to do + * // this unless you're an advanced user with a very good reason to. + * const query = new mongoose.Query(); + * + * @param {Object} [options] + * @param {Object} [model] + * @param {Object} [conditions] + * @param {Object} [collection] Mongoose collection + * @api public + */ + +function Query(conditions, options, model, collection) { + // this stuff is for dealing with custom queries created by #toConstructor + if (!this._mongooseOptions) { + this._mongooseOptions = {}; + } + options = options || {}; + + this._transforms = []; + this._hooks = new Kareem(); + this._executionStack = null; + + // this is the case where we have a CustomQuery, we need to check if we got + // options passed in, and if we did, merge them in + const keys = Object.keys(options); + for (const key of keys) { + this._mongooseOptions[key] = options[key]; + } + + if (collection) { + this.mongooseCollection = collection; + } + + if (model) { + this.model = model; + this.schema = model.schema; + } + + + // this is needed because map reduce returns a model that can be queried, but + // all of the queries on said model should be lean + if (this.model && this.model._mapreduce) { + this.lean(); + } + + // inherit mquery + mquery.call(this, this.mongooseCollection, options); + + if (conditions) { + this.find(conditions); + } + + this.options = this.options || {}; + + // For gh-6880. mquery still needs to support `fields` by default for old + // versions of MongoDB + this.$useProjection = true; + + const collation = get(this, 'schema.options.collation', null); + if (collation != null) { + this.options.collation = collation; + } +} + +/*! + * inherit mquery + */ + +Query.prototype = new mquery; +Query.prototype.constructor = Query; +Query.base = mquery.prototype; + +/** + * Flag to opt out of using `$geoWithin`. + * + * mongoose.Query.use$geoWithin = false; + * + * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with `$within`). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work. + * + * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/ + * @default true + * @property use$geoWithin + * @memberOf Query + * @receiver Query + * @api public + */ + +Query.use$geoWithin = mquery.use$geoWithin; + +/** + * Converts this query to a customized, reusable query constructor with all arguments and options retained. + * + * ####Example + * + * // Create a query for adventure movies and read from the primary + * // node in the replica-set unless it is down, in which case we'll + * // read from a secondary node. + * const query = Movie.find({ tags: 'adventure' }).read('primaryPreferred'); + * + * // create a custom Query constructor based off these settings + * const Adventure = query.toConstructor(); + * + * // Adventure is now a subclass of mongoose.Query and works the same way but with the + * // default query parameters and options set. + * Adventure().exec(callback) + * + * // further narrow down our query results while still using the previous settings + * Adventure().where({ name: /^Life/ }).exec(callback); + * + * // since Adventure is a stand-alone constructor we can also add our own + * // helper methods and getters without impacting global queries + * Adventure.prototype.startsWith = function (prefix) { + * this.where({ name: new RegExp('^' + prefix) }) + * return this; + * } + * Object.defineProperty(Adventure.prototype, 'highlyRated', { + * get: function () { + * this.where({ rating: { $gt: 4.5 }}); + * return this; + * } + * }) + * Adventure().highlyRated.startsWith('Life').exec(callback) + * + * @return {Query} subclass-of-Query + * @api public + */ + +Query.prototype.toConstructor = function toConstructor() { + const model = this.model; + const coll = this.mongooseCollection; + + const CustomQuery = function(criteria, options) { + if (!(this instanceof CustomQuery)) { + return new CustomQuery(criteria, options); + } + this._mongooseOptions = utils.clone(p._mongooseOptions); + Query.call(this, criteria, options || null, model, coll); + }; + + util.inherits(CustomQuery, model.Query); + + // set inherited defaults + const p = CustomQuery.prototype; + + p.options = {}; + + // Need to handle `sort()` separately because entries-style `sort()` syntax + // `sort([['prop1', 1]])` confuses mquery into losing the outer nested array. + // See gh-8159 + const options = Object.assign({}, this.options); + if (options.sort != null) { + p.sort(options.sort); + delete options.sort; + } + p.setOptions(options); + + p.op = this.op; + p._validateOp(); + p._conditions = utils.clone(this._conditions); + p._fields = utils.clone(this._fields); + p._update = utils.clone(this._update, { + flattenDecimals: false + }); + p._path = this._path; + p._distinct = this._distinct; + p._collection = this._collection; + p._mongooseOptions = this._mongooseOptions; + + return CustomQuery; +}; + +/** + * Make a copy of this query so you can re-execute it. + * + * ####Example: + * const q = Book.findOne({ title: 'Casino Royale' }); + * await q.exec(); + * await q.exec(); // Throws an error because you can't execute a query twice + * + * await q.clone().exec(); // Works + * + * @method clone + * @return {Query} copy + * @memberOf Query + * @instance + * @api public + */ + +Query.prototype.clone = function clone() { + const model = this.model; + const collection = this.mongooseCollection; + + const q = new this.constructor({}, {}, model, collection); + + // Need to handle `sort()` separately because entries-style `sort()` syntax + // `sort([['prop1', 1]])` confuses mquery into losing the outer nested array. + // See gh-8159 + const options = Object.assign({}, this.options); + if (options.sort != null) { + q.sort(options.sort); + delete options.sort; + } + q.setOptions(options); + + q.op = this.op; + q._validateOp(); + q._conditions = utils.clone(this._conditions); + q._fields = utils.clone(this._fields); + q._update = utils.clone(this._update, { + flattenDecimals: false + }); + q._path = this._path; + q._distinct = this._distinct; + q._collection = this._collection; + q._mongooseOptions = this._mongooseOptions; + + return q; +}; + +/** + * Specifies a javascript function or expression to pass to MongoDBs query system. + * + * ####Example + * + * query.$where('this.comments.length === 10 || this.name.length === 5') + * + * // or + * + * query.$where(function () { + * return this.comments.length === 10 || this.name.length === 5; + * }) + * + * ####NOTE: + * + * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. + * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.** + * + * @see $where http://docs.mongodb.org/manual/reference/operator/where/ + * @method $where + * @param {String|Function} js javascript string or function + * @return {Query} this + * @memberOf Query + * @instance + * @method $where + * @api public + */ + +/** + * Specifies a `path` for use with chaining. + * + * ####Example + * + * // instead of writing: + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * // we can instead write: + * User.where('age').gte(21).lte(65); + * + * // passing query conditions is permitted + * User.find().where({ name: 'vonderful' }) + * + * // chaining + * User + * .where('age').gte(21).lte(65) + * .where('name', /^vonderful/i) + * .where('friends').slice(10) + * .exec(callback) + * + * @method where + * @memberOf Query + * @instance + * @param {String|Object} [path] + * @param {any} [val] + * @return {Query} this + * @api public + */ + +/** + * Specifies a `$slice` projection for an array. + * + * ####Example + * + * query.slice('comments', 5) + * query.slice('comments', -5) + * query.slice('comments', [10, 5]) + * query.where('comments').slice(5) + * query.where('comments').slice([-10, 5]) + * + * @method slice + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val number/range of elements to slice + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements + * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice + * @api public + */ + +Query.prototype.slice = function() { + if (arguments.length === 0) { + return this; + } + + this._validate('slice'); + + let path; + let val; + + if (arguments.length === 1) { + const arg = arguments[0]; + if (typeof arg === 'object' && !Array.isArray(arg)) { + const keys = Object.keys(arg); + const numKeys = keys.length; + for (let i = 0; i < numKeys; ++i) { + this.slice(keys[i], arg[keys[i]]); + } + return this; + } + this._ensurePath('slice'); + path = this._path; + val = arguments[0]; + } else if (arguments.length === 2) { + if ('number' === typeof arguments[0]) { + this._ensurePath('slice'); + path = this._path; + val = slice(arguments); + } else { + path = arguments[0]; + val = arguments[1]; + } + } else if (arguments.length === 3) { + path = arguments[0]; + val = slice(arguments, 1); + } + + const p = {}; + p[path] = { $slice: val }; + this.select(p); + + return this; +}; + +/*! + * ignore + */ + +const validOpsSet = new Set(validOps); + +Query.prototype._validateOp = function() { + if (this.op != null && !validOpsSet.has(this.op)) { + this.error(new Error('Query has invalid `op`: "' + this.op + '"')); + } +}; + +/** + * Specifies the complementary comparison value for paths specified with `where()` + * + * ####Example + * + * User.where('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @method equals + * @memberOf Query + * @instance + * @param {Object} val + * @return {Query} this + * @api public + */ + +/** + * Specifies arguments for an `$or` condition. + * + * ####Example + * + * query.or([{ color: 'red' }, { status: 'emergency' }]) + * + * @see $or http://docs.mongodb.org/manual/reference/operator/or/ + * @method or + * @memberOf Query + * @instance + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +/** + * Specifies arguments for a `$nor` condition. + * + * ####Example + * + * query.nor([{ color: 'green' }, { status: 'ok' }]) + * + * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/ + * @method nor + * @memberOf Query + * @instance + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +/** + * Specifies arguments for a `$and` condition. + * + * ####Example + * + * query.and([{ color: 'green' }, { status: 'ok' }]) + * + * @method and + * @memberOf Query + * @instance + * @see $and http://docs.mongodb.org/manual/reference/operator/and/ + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +/** + * Specifies a `$gt` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * Thing.find().where('age').gt(21) + * + * // or + * Thing.find().gt('age', 21) + * + * @method gt + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/ + * @api public + */ + +/** + * Specifies a `$gte` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method gte + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/ + * @api public + */ + +/** + * Specifies a `$lt` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lt + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/ + * @api public + */ + +/** + * Specifies a `$lte` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lte + * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/ + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a `$ne` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/ + * @method ne + * @memberOf Query + * @instance + * @param {String} [path] + * @param {any} val + * @api public + */ + +/** + * Specifies an `$in` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $in http://docs.mongodb.org/manual/reference/operator/in/ + * @method in + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Array} val + * @api public + */ + +/** + * Specifies an `$nin` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/ + * @method nin + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Array} val + * @api public + */ + +/** + * Specifies an `$all` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example: + * + * MyModel.find().where('pets').all(['dog', 'cat', 'ferret']); + * // Equivalent: + * MyModel.find().all('pets', ['dog', 'cat', 'ferret']); + * + * @see $all http://docs.mongodb.org/manual/reference/operator/all/ + * @method all + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Array} val + * @api public + */ + +/** + * Specifies a `$size` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * const docs = await MyModel.where('tags').size(0).exec(); + * assert(Array.isArray(docs)); + * console.log('documents with 0 tags', docs); + * + * @see $size http://docs.mongodb.org/manual/reference/operator/size/ + * @method size + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a `$regex` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/ + * @method regex + * @memberOf Query + * @instance + * @param {String} [path] + * @param {String|RegExp} val + * @api public + */ + +/** + * Specifies a `maxDistance` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + * @method maxDistance + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a `$mod` condition, filters documents for documents whose + * `path` property is a number that is equal to `remainder` modulo `divisor`. + * + * ####Example + * + * // All find products whose inventory is odd + * Product.find().mod('inventory', [2, 1]); + * Product.find().where('inventory').mod([2, 1]); + * // This syntax is a little strange, but supported. + * Product.find().where('inventory').mod(2, 1); + * + * @method mod + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Array} val must be of length 2, first element is `divisor`, 2nd element is `remainder`. + * @return {Query} this + * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/ + * @api public + */ + +Query.prototype.mod = function() { + let val; + let path; + + if (arguments.length === 1) { + this._ensurePath('mod'); + val = arguments[0]; + path = this._path; + } else if (arguments.length === 2 && !Array.isArray(arguments[1])) { + this._ensurePath('mod'); + val = slice(arguments); + path = this._path; + } else if (arguments.length === 3) { + val = slice(arguments, 1); + path = arguments[0]; + } else { + val = arguments[1]; + path = arguments[0]; + } + + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$mod = val; + return this; +}; + +/** + * Specifies an `$exists` condition + * + * ####Example + * + * // { name: { $exists: true }} + * Thing.where('name').exists() + * Thing.where('name').exists(true) + * Thing.find().exists('name') + * + * // { name: { $exists: false }} + * Thing.where('name').exists(false); + * Thing.find().exists('name', false); + * + * @method exists + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Boolean} val + * @return {Query} this + * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/ + * @api public + */ + +/** + * Specifies an `$elemMatch` condition + * + * ####Example + * + * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) + * + * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + * + * query.elemMatch('comment', function (elem) { + * elem.where('author').equals('autobot'); + * elem.where('votes').gte(5); + * }) + * + * query.where('comment').elemMatch(function (elem) { + * elem.where({ author: 'autobot' }); + * elem.where('votes').gte(5); + * }) + * + * @method elemMatch + * @memberOf Query + * @instance + * @param {String|Object|Function} path + * @param {Object|Function} filter + * @return {Query} this + * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/ + * @api public + */ + +/** + * Defines a `$within` or `$geoWithin` argument for geo-spatial queries. + * + * ####Example + * + * query.where(path).within().box() + * query.where(path).within().circle() + * query.where(path).within().geometry() + * + * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); + * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); + * query.where('loc').within({ polygon: [[],[],[],[]] }); + * + * query.where('loc').within([], [], []) // polygon + * query.where('loc').within([], []) // box + * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry + * + * **MUST** be used after `where()`. + * + * ####NOTE: + * + * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin). + * + * ####NOTE: + * + * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). + * + * @method within + * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ + * @see $box http://docs.mongodb.org/manual/reference/operator/box/ + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see $center http://docs.mongodb.org/manual/reference/operator/center/ + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @memberOf Query + * @instance + * @return {Query} this + * @api public + */ + +/** + * Specifies the maximum number of documents the query will return. + * + * ####Example + * + * query.limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method limit + * @memberOf Query + * @instance + * @param {Number} val + * @api public + */ + +/** + * Specifies the number of documents to skip. + * + * ####Example + * + * query.skip(100).limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method skip + * @memberOf Query + * @instance + * @param {Number} val + * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/ + * @api public + */ + +/** + * Specifies the maxScan option. + * + * ####Example + * + * query.maxScan(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method maxScan + * @memberOf Query + * @instance + * @param {Number} val + * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/ + * @api public + */ + +/** + * Specifies the batchSize option. + * + * ####Example + * + * query.batchSize(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method batchSize + * @memberOf Query + * @instance + * @param {Number} val + * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/ + * @api public + */ + +/** + * Specifies the `comment` option. + * + * ####Example + * + * query.comment('login query') + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method comment + * @memberOf Query + * @instance + * @param {String} val + * @see comment http://docs.mongodb.org/manual/reference/operator/comment/ + * @api public + */ + +/** + * Specifies this query as a `snapshot` query. + * + * ####Example + * + * query.snapshot() // true + * query.snapshot(true) + * query.snapshot(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method snapshot + * @memberOf Query + * @instance + * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/ + * @return {Query} this + * @api public + */ + +/** + * Sets query hints. + * + * ####Example + * + * query.hint({ indexA: 1, indexB: -1}) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method hint + * @memberOf Query + * @instance + * @param {Object} val a hint object + * @return {Query} this + * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/ + * @api public + */ + +/** + * Get/set the current projection (AKA fields). Pass `null` to remove the + * current projection. + * + * Unlike `projection()`, the `select()` function modifies the current + * projection in place. This function overwrites the existing projection. + * + * ####Example: + * + * const q = Model.find(); + * q.projection(); // null + * + * q.select('a b'); + * q.projection(); // { a: 1, b: 1 } + * + * q.projection({ c: 1 }); + * q.projection(); // { c: 1 } + * + * q.projection(null); + * q.projection(); // null + * + * + * @method projection + * @memberOf Query + * @instance + * @param {Object|null} arg + * @return {Object} the current projection + * @api public + */ + +Query.prototype.projection = function(arg) { + if (arguments.length === 0) { + return this._fields; + } + + this._fields = {}; + this._userProvidedFields = {}; + this.select(arg); + return this._fields; +}; + +/** + * Specifies which document fields to include or exclude (also known as the query "projection") + * + * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select). + * + * A projection _must_ be either inclusive or exclusive. In other words, you must + * either list the fields to include (which excludes all others), or list the fields + * to exclude (which implies all other fields are included). The [`_id` field is the only exception because MongoDB includes it by default](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#suppress-id-field). + * + * ####Example + * + * // include a and b, exclude other fields + * query.select('a b'); + * // Equivalent syntaxes: + * query.select(['a', 'b']); + * query.select({ a: 1, b: 1 }); + * + * // exclude c and d, include other fields + * query.select('-c -d'); + * + * // Use `+` to override schema-level `select: false` without making the + * // projection inclusive. + * const schema = new Schema({ + * foo: { type: String, select: false }, + * bar: String + * }); + * // ... + * query.select('+foo'); // Override foo's `select: false` without excluding `bar` + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * query.select({ a: 1, b: 1 }); + * query.select({ c: 0, d: 0 }); + * + * + * @method select + * @memberOf Query + * @instance + * @param {Object|String|Array} arg + * @return {Query} this + * @see SchemaType + * @api public + */ + +Query.prototype.select = function select() { + let arg = arguments[0]; + if (!arg) return this; + + if (arguments.length !== 1) { + throw new Error('Invalid select: select only takes 1 argument'); + } + + this._validate('select'); + + const fields = this._fields || (this._fields = {}); + const userProvidedFields = this._userProvidedFields || (this._userProvidedFields = {}); + let sanitizeProjection = undefined; + if (this.model != null && utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeProjection')) { + sanitizeProjection = this.model.db.options.sanitizeProjection; + } else if (this.model != null && utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeProjection')) { + sanitizeProjection = this.model.base.options.sanitizeProjection; + } else { + sanitizeProjection = this._mongooseOptions.sanitizeProjection; + } + + arg = parseProjection(arg); + + if (utils.isObject(arg)) { + const keys = Object.keys(arg); + for (let i = 0; i < keys.length; ++i) { + let value = arg[keys[i]]; + if (typeof value === 'string' && sanitizeProjection) { + value = 1; + } + fields[keys[i]] = value; + userProvidedFields[keys[i]] = value; + } + return this; + } + + throw new TypeError('Invalid select() argument. Must be string or object.'); +}; + +/** + * _DEPRECATED_ Sets the slaveOk option. + * + * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read). + * + * ####Example: + * + * query.slaveOk() // true + * query.slaveOk(true) + * query.slaveOk(false) + * + * @method slaveOk + * @memberOf Query + * @instance + * @deprecated use read() preferences instead if on mongodb >= 2.2 + * @param {Boolean} v defaults to true + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/ + * @see read() #query_Query-read + * @return {Query} this + * @api public + */ + +/** + * Determines the MongoDB nodes from which to read. + * + * ####Preferences: + * + * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. + * secondary Read from secondary if available, otherwise error. + * primaryPreferred Read from primary if available, otherwise a secondary. + * secondaryPreferred Read from a secondary if available, otherwise read from the primary. + * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + * + * Aliases + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * ####Example: + * + * new Query().read('primary') + * new Query().read('p') // same as primary + * + * new Query().read('primaryPreferred') + * new Query().read('pp') // same as primaryPreferred + * + * new Query().read('secondary') + * new Query().read('s') // same as secondary + * + * new Query().read('secondaryPreferred') + * new Query().read('sp') // same as secondaryPreferred + * + * new Query().read('nearest') + * new Query().read('n') // same as nearest + * + * // read from secondaries with matching tags + * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) + * + * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + * + * @method read + * @memberOf Query + * @instance + * @param {String} pref one of the listed preference options or aliases + * @param {Array} [tags] optional tags for this query + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + * @return {Query} this + * @api public + */ + +Query.prototype.read = function read(pref, tags) { + // first cast into a ReadPreference object to support tags + const read = new ReadPreference(pref, tags); + this.options.readPreference = read; + return this; +}; + +/*! + * ignore + */ + +Query.prototype.toString = function toString() { + if (this.op === 'count' || + this.op === 'countDocuments' || + this.op === 'find' || + this.op === 'findOne' || + this.op === 'deleteMany' || + this.op === 'deleteOne' || + this.op === 'findOneAndDelete' || + this.op === 'findOneAndRemove' || + this.op === 'remove') { + return `${this.model.modelName}.${this.op}(${util.inspect(this._conditions)})`; + } + if (this.op === 'distinct') { + return `${this.model.modelName}.distinct('${this._distinct}', ${util.inspect(this._conditions)})`; + } + if (this.op === 'findOneAndReplace' || + this.op === 'findOneAndUpdate' || + this.op === 'replaceOne' || + this.op === 'update' || + this.op === 'updateMany' || + this.op === 'updateOne') { + return `${this.model.modelName}.${this.op}(${util.inspect(this._conditions)}, ${util.inspect(this._update)})`; + } + + // 'estimatedDocumentCount' or any others + return `${this.model.modelName}.${this.op}()`; +}; + +/** + * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/) + * associated with this query. Sessions are how you mark a query as part of a + * [transaction](/docs/transactions.html). + * + * Calling `session(null)` removes the session from this query. + * + * ####Example: + * + * const s = await mongoose.startSession(); + * await mongoose.model('Person').findOne({ name: 'Axl Rose' }).session(s); + * + * @method session + * @memberOf Query + * @instance + * @param {ClientSession} [session] from `await conn.startSession()` + * @see Connection.prototype.startSession() /docs/api.html#connection_Connection-startSession + * @see mongoose.startSession() /docs/api.html#mongoose_Mongoose-startSession + * @return {Query} this + * @api public + */ + +Query.prototype.session = function session(v) { + if (v == null) { + delete this.options.session; + } + this.options.session = v; + return this; +}; + +/** + * Sets the 3 write concern parameters for this query: + * + * - `w`: Sets the specified number of `mongod` servers, or tag set of `mongod` servers, that must acknowledge this write before this write is considered successful. + * - `j`: Boolean, set to `true` to request acknowledgement that this operation has been persisted to MongoDB's on-disk journal. + * - `wtimeout`: If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to wait for this write to propagate through the replica set before this operation fails. The default is `0`, which means no timeout. + * + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndReplace()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the schema's [`writeConcern` option](/docs/guide.html#writeConcern) + * + * ####Example: + * + * // The 'majority' option means the `deleteOne()` promise won't resolve + * // until the `deleteOne()` has propagated to the majority of the replica set + * await mongoose.model('Person'). + * deleteOne({ name: 'Ned Stark' }). + * writeConcern({ w: 'majority' }); + * + * @method writeConcern + * @memberOf Query + * @instance + * @param {Object} writeConcern the write concern value to set + * @see mongodb https://mongodb.github.io/node-mongodb-native/3.1/api/global.html#WriteConcern + * @return {Query} this + * @api public + */ + +Query.prototype.writeConcern = function writeConcern(val) { + if (val == null) { + delete this.options.writeConcern; + return this; + } + this.options.writeConcern = val; + return this; +}; + +/** + * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, + * that must acknowledge this write before this write is considered successful. + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndReplace()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the schema's [`writeConcern.w` option](/docs/guide.html#writeConcern) + * + * ####Example: + * + * // The 'majority' option means the `deleteOne()` promise won't resolve + * // until the `deleteOne()` has propagated to the majority of the replica set + * await mongoose.model('Person'). + * deleteOne({ name: 'Ned Stark' }). + * w('majority'); + * + * @method w + * @memberOf Query + * @instance + * @param {String|number} val 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option). + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option + * @return {Query} this + * @api public + */ + +Query.prototype.w = function w(val) { + if (val == null) { + delete this.options.w; + } + if (this.options.writeConcern != null) { + this.options.writeConcern.w = val; + } else { + this.options.w = val; + } + return this; +}; + +/** + * Requests acknowledgement that this operation has been persisted to MongoDB's + * on-disk journal. + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndReplace()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the schema's [`writeConcern.j` option](/docs/guide.html#writeConcern) + * + * ####Example: + * + * await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true); + * + * @method j + * @memberOf Query + * @instance + * @param {boolean} val + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option + * @return {Query} this + * @api public + */ + +Query.prototype.j = function j(val) { + if (val == null) { + delete this.options.j; + } + if (this.options.writeConcern != null) { + this.options.writeConcern.j = val; + } else { + this.options.j = val; + } + return this; +}; + +/** + * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to + * wait for this write to propagate through the replica set before this + * operation fails. The default is `0`, which means no timeout. + * + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndReplace()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the schema's [`writeConcern.wtimeout` option](/docs/guide.html#writeConcern) + * + * ####Example: + * + * // The `deleteOne()` promise won't resolve until this `deleteOne()` has + * // propagated to at least `w = 2` members of the replica set. If it takes + * // longer than 1 second, this `deleteOne()` will fail. + * await mongoose.model('Person'). + * deleteOne({ name: 'Ned Stark' }). + * w(2). + * wtimeout(1000); + * + * @method wtimeout + * @memberOf Query + * @instance + * @param {number} ms number of milliseconds to wait + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout + * @return {Query} this + * @api public + */ + +Query.prototype.wtimeout = function wtimeout(ms) { + if (ms == null) { + delete this.options.wtimeout; + } + if (this.options.writeConcern != null) { + this.options.writeConcern.wtimeout = ms; + } else { + this.options.wtimeout = ms; + } + return this; +}; + +/** + * Sets the readConcern option for the query. + * + * ####Example: + * + * new Query().readConcern('local') + * new Query().readConcern('l') // same as local + * + * new Query().readConcern('available') + * new Query().readConcern('a') // same as available + * + * new Query().readConcern('majority') + * new Query().readConcern('m') // same as majority + * + * new Query().readConcern('linearizable') + * new Query().readConcern('lz') // same as linearizable + * + * new Query().readConcern('snapshot') + * new Query().readConcern('s') // same as snapshot + * + * + * ####Read Concern Level: + * + * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). + * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). + * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. + * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. + * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. + * + * Aliases + * + * l local + * a available + * m majority + * lz linearizable + * s snapshot + * + * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). + * + * @memberOf Query + * @method readConcern + * @param {String} level one of the listed read concern level or their aliases + * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ + * @return {Query} this + * @api public + */ + +/** + * Gets query options. + * + * ####Example: + * + * const query = new Query(); + * query.limit(10); + * query.setOptions({ maxTimeMS: 1000 }) + * query.getOptions(); // { limit: 10, maxTimeMS: 1000 } + * + * @return {Object} the options + * @api public + */ + +Query.prototype.getOptions = function() { + return this.options; +}; + +/** + * Sets query options. Some options only make sense for certain operations. + * + * ####Options: + * + * The following options are only for `find()`: + * + * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) + * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) + * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) + * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) + * - [allowDiskUse](https://docs.mongodb.com/manual/reference/method/cursor.allowDiskUse/) + * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) + * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference) + * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) + * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) + * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) + * - [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan) + * + * The following options are only for write operations: `update()`, `updateOne()`, `updateMany()`, `replaceOne()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`: + * + * - [upsert](https://docs.mongodb.com/manual/reference/method/db.collection.update/) + * - [writeConcern](https://docs.mongodb.com/manual/reference/method/db.collection.update/) + * - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): If `timestamps` is set in the schema, set this option to `false` to skip timestamps for that particular update. Has no effect if `timestamps` is not enabled in the schema options. + * - omitUndefined: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. + * - overwriteDiscriminatorKey: allow setting the discriminator key in the update. Will use the correct discriminator schema if the update changes the discriminator key. + * + * The following options are only for `find()`, `findOne()`, `findById()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`: + * + * - [lean](./api.html#query_Query-lean) + * - [populate](/docs/populate.html) + * - [projection](/docs/api/query.html#query_Query-projection) + * - sanitizeProjection + * + * The following options are only for all operations **except** `update()`, `updateOne()`, `updateMany()`, `remove()`, `deleteOne()`, and `deleteMany()`: + * + * - [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) + * + * The following options are for `findOneAndUpdate()` and `findOneAndRemove()` + * + * - rawResult + * + * The following options are for all operations: + * + * - [strict](/docs/guide.html#strict) + * - [collation](https://docs.mongodb.com/manual/reference/collation/) + * - [session](https://docs.mongodb.com/manual/reference/server-sessions/) + * - [explain](https://docs.mongodb.com/manual/reference/method/cursor.explain/) + * + * @param {Object} options + * @return {Query} this + * @api public + */ + +Query.prototype.setOptions = function(options, overwrite) { + // overwrite is only for internal use + if (overwrite) { + // ensure that _mongooseOptions & options are two different objects + this._mongooseOptions = (options && utils.clone(options)) || {}; + this.options = options || {}; + + if ('populate' in options) { + this.populate(this._mongooseOptions); + } + return this; + } + if (options == null) { + return this; + } + if (typeof options !== 'object') { + throw new Error('Options must be an object, got "' + options + '"'); + } + + if (Array.isArray(options.populate)) { + const populate = options.populate; + delete options.populate; + const _numPopulate = populate.length; + for (let i = 0; i < _numPopulate; ++i) { + this.populate(populate[i]); + } + } + + if ('setDefaultsOnInsert' in options) { + this._mongooseOptions.setDefaultsOnInsert = options.setDefaultsOnInsert; + delete options.setDefaultsOnInsert; + } + if ('overwriteDiscriminatorKey' in options) { + this._mongooseOptions.overwriteDiscriminatorKey = options.overwriteDiscriminatorKey; + delete options.overwriteDiscriminatorKey; + } + if ('sanitizeProjection' in options) { + if (options.sanitizeProjection && !this._mongooseOptions.sanitizeProjection) { + sanitizeProjection(this._fields); + } + + this._mongooseOptions.sanitizeProjection = options.sanitizeProjection; + delete options.sanitizeProjection; + } + if ('sanitizeFilter' in options) { + this._mongooseOptions.sanitizeFilter = options.sanitizeFilter; + delete options.sanitizeFilter; + } + + if ('defaults' in options) { + this._mongooseOptions.defaults = options.defaults; + // deleting options.defaults will cause 7287 to fail + } + + return Query.base.setOptions.call(this, options); +}; + +/** + * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/), + * which makes this query return detailed execution stats instead of the actual + * query result. This method is useful for determining what index your queries + * use. + * + * Calling `query.explain(v)` is equivalent to `query.setOptions({ explain: v })` + * + * ####Example: + * + * const query = new Query(); + * const res = await query.find({ a: 1 }).explain('queryPlanner'); + * console.log(res); + * + * @param {String} [verbose] The verbosity mode. Either 'queryPlanner', 'executionStats', or 'allPlansExecution'. The default is 'queryPlanner' + * @return {Query} this + * @api public + */ + +Query.prototype.explain = function(verbose) { + if (arguments.length === 0) { + this.options.explain = true; + } else if (verbose === false) { + delete this.options.explain; + } else { + this.options.explain = verbose; + } + return this; +}; + +/** + * Sets the [`allowDiskUse` option](https://docs.mongodb.com/manual/reference/method/cursor.allowDiskUse/), + * which allows the MongoDB server to use more than 100 MB for this query's `sort()`. This option can + * let you work around `QueryExceededMemoryLimitNoDiskUseAllowed` errors from the MongoDB server. + * + * Note that this option requires MongoDB server >= 4.4. Setting this option is a no-op for MongoDB 4.2 + * and earlier. + * + * Calling `query.allowDiskUse(v)` is equivalent to `query.setOptions({ allowDiskUse: v })` + * + * ####Example: + * + * await query.find().sort({ name: 1 }).allowDiskUse(true); + * // Equivalent: + * await query.find().sort({ name: 1 }).allowDiskUse(); + * + * @param {Boolean} [v] Enable/disable `allowDiskUse`. If called with 0 arguments, sets `allowDiskUse: true` + * @return {Query} this + * @api public + */ + +Query.prototype.allowDiskUse = function(v) { + if (arguments.length === 0) { + this.options.allowDiskUse = true; + } else if (v === false) { + delete this.options.allowDiskUse; + } else { + this.options.allowDiskUse = v; + } + return this; +}; + +/** + * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/) + * option. This will tell the MongoDB server to abort if the query or write op + * has been running for more than `ms` milliseconds. + * + * Calling `query.maxTimeMS(v)` is equivalent to `query.setOptions({ maxTimeMS: v })` + * + * ####Example: + * + * const query = new Query(); + * // Throws an error 'operation exceeded time limit' as long as there's + * // >= 1 doc in the queried collection + * const res = await query.find({ $where: 'sleep(1000) || true' }).maxTimeMS(100); + * + * @param {Number} [ms] The number of milliseconds + * @return {Query} this + * @api public + */ + +Query.prototype.maxTimeMS = function(ms) { + this.options.maxTimeMS = ms; + return this; +}; + +/** + * Returns the current query filter (also known as conditions) as a [POJO](https://masteringjs.io/tutorials/fundamentals/pojo). + * + * ####Example: + * + * const query = new Query(); + * query.find({ a: 1 }).where('b').gt(2); + * query.getFilter(); // { a: 1, b: { $gt: 2 } } + * + * @return {Object} current query filter + * @api public + */ + +Query.prototype.getFilter = function() { + return this._conditions; +}; + +/** + * Returns the current query filter. Equivalent to `getFilter()`. + * + * You should use `getFilter()` instead of `getQuery()` where possible. `getQuery()` + * will likely be deprecated in a future release. + * + * ####Example: + * + * const query = new Query(); + * query.find({ a: 1 }).where('b').gt(2); + * query.getQuery(); // { a: 1, b: { $gt: 2 } } + * + * @return {Object} current query filter + * @api public + */ + +Query.prototype.getQuery = function() { + return this._conditions; +}; + +/** + * Sets the query conditions to the provided JSON object. + * + * ####Example: + * + * const query = new Query(); + * query.find({ a: 1 }) + * query.setQuery({ a: 2 }); + * query.getQuery(); // { a: 2 } + * + * @param {Object} new query conditions + * @return {undefined} + * @api public + */ + +Query.prototype.setQuery = function(val) { + this._conditions = val; +}; + +/** + * Returns the current update operations as a JSON object. + * + * ####Example: + * + * const query = new Query(); + * query.update({}, { $set: { a: 5 } }); + * query.getUpdate(); // { $set: { a: 5 } } + * + * @return {Object} current update operations + * @api public + */ + +Query.prototype.getUpdate = function() { + return this._update; +}; + +/** + * Sets the current update operation to new value. + * + * ####Example: + * + * const query = new Query(); + * query.update({}, { $set: { a: 5 } }); + * query.setUpdate({ $set: { b: 6 } }); + * query.getUpdate(); // { $set: { b: 6 } } + * + * @param {Object} new update operation + * @return {undefined} + * @api public + */ + +Query.prototype.setUpdate = function(val) { + this._update = val; +}; + +/** + * Returns fields selection for this query. + * + * @method _fieldsForExec + * @return {Object} + * @api private + * @receiver Query + */ + +Query.prototype._fieldsForExec = function() { + return utils.clone(this._fields); +}; + + +/** + * Return an update document with corrected `$set` operations. + * + * @method _updateForExec + * @api private + * @receiver Query + */ + +Query.prototype._updateForExec = function() { + const update = utils.clone(this._update, { + transform: false, + depopulate: true + }); + const ops = Object.keys(update); + let i = ops.length; + const ret = {}; + + while (i--) { + const op = ops[i]; + + if (this.options.overwrite) { + ret[op] = update[op]; + continue; + } + + if ('$' !== op[0]) { + // fix up $set sugar + if (!ret.$set) { + if (update.$set) { + ret.$set = update.$set; + } else { + ret.$set = {}; + } + } + ret.$set[op] = update[op]; + ops.splice(i, 1); + if (!~ops.indexOf('$set')) ops.push('$set'); + } else if ('$set' === op) { + if (!ret.$set) { + ret[op] = update[op]; + } + } else { + ret[op] = update[op]; + } + } + + return ret; +}; + +/** + * Makes sure _path is set. + * + * @method _ensurePath + * @param {String} method + * @api private + * @receiver Query + */ + +/** + * Determines if `conds` can be merged using `mquery().merge()` + * + * @method canMerge + * @memberOf Query + * @instance + * @param {Object} conds + * @return {Boolean} + * @api private + */ + +/** + * Returns default options for this query. + * + * @param {Model} model + * @api private + */ + +Query.prototype._optionsForExec = function(model) { + const options = utils.clone(this.options); + delete options.populate; + model = model || this.model; + + if (!model) { + return options; + } + + // Apply schema-level `writeConcern` option + applyWriteConcern(model.schema, options); + + const readPreference = get(model, 'schema.options.read'); + if (!('readPreference' in options) && readPreference) { + options.readPreference = readPreference; + } + + if (options.upsert !== void 0) { + options.upsert = !!options.upsert; + } + if (options.writeConcern) { + if (options.j) { + options.writeConcern.j = options.j; + delete options.j; + } + if (options.w) { + options.writeConcern.w = options.w; + delete options.w; + } + if (options.wtimeout) { + options.writeConcern.wtimeout = options.wtimeout; + delete options.wtimeout; + } + } + return options; +}; + +/** + * Sets the lean option. + * + * Documents returned from queries with the `lean` option enabled are plain + * javascript objects, not [Mongoose Documents](/api/document.html). They have no + * `save` method, getters/setters, virtuals, or other Mongoose features. + * + * ####Example: + * + * new Query().lean() // true + * new Query().lean(true) + * new Query().lean(false) + * + * const docs = await Model.find().lean(); + * docs[0] instanceof mongoose.Document; // false + * + * [Lean is great for high-performance, read-only cases](/docs/tutorials/lean.html), + * especially when combined + * with [cursors](/docs/queries.html#streaming). + * + * If you need virtuals, getters/setters, or defaults with `lean()`, you need + * to use a plugin. See: + * + * - [mongoose-lean-virtuals](https://plugins.mongoosejs.io/plugins/lean-virtuals) + * - [mongoose-lean-getters](https://plugins.mongoosejs.io/plugins/lean-getters) + * - [mongoose-lean-defaults](https://www.npmjs.com/package/mongoose-lean-defaults) + * + * @param {Boolean|Object} bool defaults to true + * @return {Query} this + * @api public + */ + +Query.prototype.lean = function(v) { + this._mongooseOptions.lean = arguments.length ? v : true; + return this; +}; + +/** + * Adds a `$set` to this query's update without changing the operation. + * This is useful for query middleware so you can add an update regardless + * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc. + * + * ####Example: + * + * // Updates `{ $set: { updatedAt: new Date() } }` + * new Query().updateOne({}, {}).set('updatedAt', new Date()); + * new Query().updateMany({}, {}).set({ updatedAt: new Date() }); + * + * @param {String|Object} path path or object of key/value pairs to set + * @param {Any} [val] the value to set + * @return {Query} this + * @api public + */ + +Query.prototype.set = function(path, val) { + if (typeof path === 'object') { + const keys = Object.keys(path); + for (const key of keys) { + this.set(key, path[key]); + } + return this; + } + + this._update = this._update || {}; + this._update.$set = this._update.$set || {}; + this._update.$set[path] = val; + return this; +}; + +/** + * For update operations, returns the value of a path in the update's `$set`. + * Useful for writing getters/setters that can work with both update operations + * and `save()`. + * + * ####Example: + * + * const query = Model.updateOne({}, { $set: { name: 'Jean-Luc Picard' } }); + * query.get('name'); // 'Jean-Luc Picard' + * + * @param {String|Object} path path or object of key/value pairs to get + * @return {Query} this + * @api public + */ + +Query.prototype.get = function get(path) { + const update = this._update; + if (update == null) { + return void 0; + } + const $set = update.$set; + if ($set == null) { + return update[path]; + } + + if (utils.hasUserDefinedProperty(update, path)) { + return update[path]; + } + if (utils.hasUserDefinedProperty($set, path)) { + return $set[path]; + } + + return void 0; +}; + +/** + * Gets/sets the error flag on this query. If this flag is not null or + * undefined, the `exec()` promise will reject without executing. + * + * ####Example: + * + * Query().error(); // Get current error value + * Query().error(null); // Unset the current error + * Query().error(new Error('test')); // `exec()` will resolve with test + * Schema.pre('find', function() { + * if (!this.getQuery().userId) { + * this.error(new Error('Not allowed to query without setting userId')); + * } + * }); + * + * Note that query casting runs **after** hooks, so cast errors will override + * custom errors. + * + * ####Example: + * const TestSchema = new Schema({ num: Number }); + * const TestModel = db.model('Test', TestSchema); + * TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) { + * // `error` will be a cast error because `num` failed to cast + * }); + * + * @param {Error|null} err if set, `exec()` will fail fast before sending the query to MongoDB + * @return {Query} this + * @api public + */ + +Query.prototype.error = function error(err) { + if (arguments.length === 0) { + return this._error; + } + + this._error = err; + return this; +}; + +/*! + * ignore + */ + +Query.prototype._unsetCastError = function _unsetCastError() { + if (this._error != null && !(this._error instanceof CastError)) { + return; + } + return this.error(null); +}; + +/** + * Getter/setter around the current mongoose-specific options for this query + * Below are the current Mongoose-specific options. + * + * - `populate`: an array representing what paths will be populated. Should have one entry for each call to [`Query.prototype.populate()`](/docs/api.html#query_Query-populate) + * - `lean`: if truthy, Mongoose will not [hydrate](/docs/api.html#model_Model.hydrate) any documents that are returned from this query. See [`Query.prototype.lean()`](/docs/api.html#query_Query-lean) for more information. + * - `strict`: controls how Mongoose handles keys that aren't in the schema for updates. This option is `true` by default, which means Mongoose will silently strip any paths in the update that aren't in the schema. See the [`strict` mode docs](/docs/guide.html#strict) for more information. + * - `strictQuery`: controls how Mongoose handles keys that aren't in the schema for the query `filter`. This option is `false` by default for backwards compatibility, which means Mongoose will allow `Model.find({ foo: 'bar' })` even if `foo` is not in the schema. See the [`strictQuery` docs](/docs/guide.html#strictQuery) for more information. + * - `nearSphere`: use `$nearSphere` instead of `near()`. See the [`Query.prototype.nearSphere()` docs](/docs/api.html#query_Query-nearSphere) + * + * Mongoose maintains a separate object for internal options because + * Mongoose sends `Query.prototype.options` to the MongoDB server, and the + * above options are not relevant for the MongoDB server. + * + * @param {Object} options if specified, overwrites the current options + * @return {Object} the options + * @api public + */ + +Query.prototype.mongooseOptions = function(v) { + if (arguments.length > 0) { + this._mongooseOptions = v; + } + return this._mongooseOptions; +}; + +/*! + * ignore + */ + +Query.prototype._castConditions = function() { + let sanitizeFilterOpt = undefined; + if (this.model != null && utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeFilter')) { + sanitizeFilterOpt = this.model.db.options.sanitizeFilter; + } else if (this.model != null && utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeFilter')) { + sanitizeFilterOpt = this.model.base.options.sanitizeFilter; + } else { + sanitizeFilterOpt = this._mongooseOptions.sanitizeFilter; + } + + if (sanitizeFilterOpt) { + sanitizeFilter(this._conditions); + } + + try { + this.cast(this.model); + this._unsetCastError(); + } catch (err) { + this.error(err); + } +}; + +/*! + * ignore + */ + +function _castArrayFilters(query) { + try { + castArrayFilters(query); + } catch (err) { + query.error(err); + } +} + +/** + * Thunk around find() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._find = wrapThunk(function(callback) { + this._castConditions(); + + if (this.error() != null) { + callback(this.error()); + return null; + } + + callback = _wrapThunkCallback(this, callback); + + this._applyPaths(); + this._fields = this._castFields(this._fields); + + const fields = this._fieldsForExec(); + const mongooseOptions = this._mongooseOptions; + const _this = this; + const userProvidedFields = _this._userProvidedFields || {}; + + applyGlobalMaxTimeMS(this.options, this.model); + + // Separate options to pass down to `completeMany()` in case we need to + // set a session on the document + const completeManyOptions = Object.assign({}, { + session: get(this, 'options.session', null) + }); + + const cb = (err, docs) => { + if (err) { + return callback(err); + } + + if (docs.length === 0) { + return callback(null, docs); + } + if (this.options.explain) { + return callback(null, docs); + } + + if (!mongooseOptions.populate) { + return mongooseOptions.lean ? + callback(null, docs) : + completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback); + } + + const pop = helpers.preparePopulationOptionsMQ(_this, mongooseOptions); + + if (mongooseOptions.lean) { + return _this.model.populate(docs, pop, callback); + } + + completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, (err, docs) => { + if (err != null) { + return callback(err); + } + _this.model.populate(docs, pop, callback); + }); + }; + + const options = this._optionsForExec(); + options.projection = this._fieldsForExec(); + const filter = this._conditions; + + this._collection.collection.find(filter, options, (err, cursor) => { + if (err != null) { + return cb(err); + } + + if (options.explain) { + return cursor.explain(cb); + } + try { + return cursor.toArray(cb); + } catch (err) { + return cb(err); + } + }); +}); + +/** + * Find all documents that match `selector`. The result will be an array of documents. + * + * If there are too many documents in the result to fit in memory, use + * [`Query.prototype.cursor()`](api.html#query_Query-cursor) + * + * ####Example + * + * // Using async/await + * const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } }); + * + * // Using callbacks + * Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {}); + * + * @param {Object|ObjectId} [filter] mongodb selector. If not specified, returns all documents. + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.find = function(conditions, callback) { + this.op = 'find'; + + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + + conditions = utils.toObject(conditions); + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + + prepareDiscriminatorCriteria(this); + } else if (conditions != null) { + this.error(new ObjectParameterError(conditions, 'filter', 'find')); + } + + // if we don't have a callback, then just return the query object + if (!callback) { + return Query.base.find.call(this); + } + + this.exec(callback); + + return this; +}; + +/** + * Merges another Query or conditions object into this one. + * + * When a Query is passed, conditions, field selection and options are merged. + * + * @param {Query|Object} source + * @return {Query} this + */ + +Query.prototype.merge = function(source) { + if (!source) { + return this; + } + + const opts = { overwrite: true }; + + if (source instanceof Query) { + // if source has a feature, apply it to ourselves + + if (source._conditions) { + utils.merge(this._conditions, source._conditions, opts); + } + + if (source._fields) { + this._fields || (this._fields = {}); + utils.merge(this._fields, source._fields, opts); + } + + if (source.options) { + this.options || (this.options = {}); + utils.merge(this.options, source.options, opts); + } + + if (source._update) { + this._update || (this._update = {}); + utils.mergeClone(this._update, source._update); + } + + if (source._distinct) { + this._distinct = source._distinct; + } + + utils.merge(this._mongooseOptions, source._mongooseOptions); + + return this; + } + + // plain object + utils.merge(this._conditions, source, opts); + + return this; +}; + +/** + * Adds a collation to this op (MongoDB 3.4 and up) + * + * @param {Object} value + * @return {Query} this + * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation + * @api public + */ + +Query.prototype.collation = function(value) { + if (this.options == null) { + this.options = {}; + } + this.options.collation = value; + return this; +}; + +/** + * Hydrate a single doc from `findOne()`, `findOneAndUpdate()`, etc. + * + * @api private + */ + +Query.prototype._completeOne = function(doc, res, callback) { + if (!doc && !this.options.rawResult) { + return callback(null, null); + } + + const model = this.model; + const projection = utils.clone(this._fields); + const userProvidedFields = this._userProvidedFields || {}; + // `populate`, `lean` + const mongooseOptions = this._mongooseOptions; + // `rawResult` + const options = this.options; + + if (options.explain) { + return callback(null, doc); + } + + if (!mongooseOptions.populate) { + return mongooseOptions.lean ? + _completeOneLean(doc, res, options, callback) : + completeOne(model, doc, res, options, projection, userProvidedFields, + null, callback); + } + + const pop = helpers.preparePopulationOptionsMQ(this, this._mongooseOptions); + if (mongooseOptions.lean) { + return model.populate(doc, pop, (err, doc) => { + if (err != null) { + return callback(err); + } + _completeOneLean(doc, res, options, callback); + }); + } + + completeOne(model, doc, res, options, projection, userProvidedFields, [], (err, doc) => { + if (err != null) { + return callback(err); + } + model.populate(doc, pop, callback); + }); +}; + +/** + * Thunk around findOne() + * + * @param {Function} [callback] + * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ + * @api private + */ + +Query.prototype._findOne = wrapThunk(function(callback) { + this._castConditions(); + + if (this.error()) { + callback(this.error()); + return null; + } + + this._applyPaths(); + this._fields = this._castFields(this._fields); + + applyGlobalMaxTimeMS(this.options, this.model); + + // don't pass in the conditions because we already merged them in + Query.base.findOne.call(this, {}, (err, doc) => { + if (err) { + callback(err); + return null; + } + + this._completeOne(doc, null, _wrapThunkCallback(this, callback)); + }); +}); + +/** + * Declares the query a findOne operation. When executed, the first found document is passed to the callback. + * + * Passing a `callback` executes the query. The result of the query is a single document. + * + * * *Note:* `conditions` is optional, and if `conditions` is null or undefined, + * mongoose will send an empty `findOne` command to MongoDB, which will return + * an arbitrary document. If you're querying by `_id`, use `Model.findById()` + * instead. + * + * This function triggers the following middleware. + * + * - `findOne()` + * + * ####Example + * + * const query = Kitten.where({ color: 'white' }); + * query.findOne(function (err, kitten) { + * if (err) return handleError(err); + * if (kitten) { + * // doc may be null if no document matched + * } + * }); + * + * @param {Object} [filter] mongodb selector + * @param {Object} [projection] optional fields to return + * @param {Object} [options] see [`setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] optional params are (error, document) + * @return {Query} this + * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ + * @see Query.select #query_Query-select + * @api public + */ + +Query.prototype.findOne = function(conditions, projection, options, callback) { + this.op = 'findOne'; + this._validateOp(); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = null; + projection = null; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + options = null; + projection = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } + + // make sure we don't send in the whole Document to merge() + conditions = utils.toObject(conditions); + + if (options) { + this.setOptions(options); + } + + if (projection) { + this.select(projection); + } + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + + prepareDiscriminatorCriteria(this); + } else if (conditions != null) { + this.error(new ObjectParameterError(conditions, 'filter', 'findOne')); + } + + if (!callback) { + // already merged in the conditions, don't need to send them in. + return Query.base.findOne.call(this); + } + + this.exec(callback); + return this; +}; + +/** + * Thunk around count() + * + * @param {Function} [callback] + * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ + * @api private + */ + +Query.prototype._count = wrapThunk(function(callback) { + try { + this.cast(this.model); + } catch (err) { + this.error(err); + } + + if (this.error()) { + return callback(this.error()); + } + + applyGlobalMaxTimeMS(this.options, this.model); + + const conds = this._conditions; + const options = this._optionsForExec(); + + this._collection.count(conds, options, utils.tick(callback)); +}); + +/** + * Thunk around countDocuments() + * + * @param {Function} [callback] + * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments + * @api private + */ + +Query.prototype._countDocuments = wrapThunk(function(callback) { + try { + this.cast(this.model); + } catch (err) { + this.error(err); + } + + if (this.error()) { + return callback(this.error()); + } + + applyGlobalMaxTimeMS(this.options, this.model); + + const conds = this._conditions; + const options = this._optionsForExec(); + + this._collection.collection.countDocuments(conds, options, utils.tick(callback)); +}); + +/** + * Thunk around estimatedDocumentCount() + * + * @param {Function} [callback] + * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount + * @api private + */ + +Query.prototype._estimatedDocumentCount = wrapThunk(function(callback) { + if (this.error()) { + return callback(this.error()); + } + + const options = this._optionsForExec(); + + this._collection.collection.estimatedDocumentCount(options, utils.tick(callback)); +}); + +/** + * Specifies this query as a `count` query. + * + * This method is deprecated. If you want to count the number of documents in + * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#query_Query-estimatedDocumentCount) + * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#query_Query-countDocuments) function instead. + * + * Passing a `callback` executes the query. + * + * This function triggers the following middleware. + * + * - `count()` + * + * ####Example: + * + * const countQuery = model.where({ 'color': 'black' }).count(); + * + * query.count({ color: 'black' }).count(callback) + * + * query.count({ color: 'black' }, callback) + * + * query.where('color', 'black').count(function (err, count) { + * if (err) return handleError(err); + * console.log('there are %d kittens', count); + * }) + * + * @deprecated + * @param {Object} [filter] count documents that match this object + * @param {Function} [callback] optional params are (error, count) + * @return {Query} this + * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ + * @api public + */ + +Query.prototype.count = function(filter, callback) { + this.op = 'count'; + this._validateOp(); + if (typeof filter === 'function') { + callback = filter; + filter = undefined; + } + + filter = utils.toObject(filter); + + if (mquery.canMerge(filter)) { + this.merge(filter); + } + + if (!callback) { + return this; + } + + this.exec(callback); + + return this; +}; + +/** + * Specifies this query as a `estimatedDocumentCount()` query. Faster than + * using `countDocuments()` for large collections because + * `estimatedDocumentCount()` uses collection metadata rather than scanning + * the entire collection. + * + * `estimatedDocumentCount()` does **not** accept a filter. `Model.find({ foo: bar }).estimatedDocumentCount()` + * is equivalent to `Model.find().estimatedDocumentCount()` + * + * This function triggers the following middleware. + * + * - `estimatedDocumentCount()` + * + * ####Example: + * + * await Model.find().estimatedDocumentCount(); + * + * @param {Object} [options] passed transparently to the [MongoDB driver](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount) + * @param {Function} [callback] optional params are (error, count) + * @return {Query} this + * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount + * @api public + */ + +Query.prototype.estimatedDocumentCount = function(options, callback) { + this.op = 'estimatedDocumentCount'; + this._validateOp(); + if (typeof options === 'function') { + callback = options; + options = undefined; + } + + if (typeof options === 'object' && options != null) { + this.setOptions(options); + } + + if (!callback) { + return this; + } + + this.exec(callback); + + return this; +}; + +/** + * Specifies this query as a `countDocuments()` query. Behaves like `count()`, + * except it always does a full collection scan when passed an empty filter `{}`. + * + * There are also minor differences in how `countDocuments()` handles + * [`$where` and a couple geospatial operators](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). + * versus `count()`. + * + * Passing a `callback` executes the query. + * + * This function triggers the following middleware. + * + * - `countDocuments()` + * + * ####Example: + * + * const countQuery = model.where({ 'color': 'black' }).countDocuments(); + * + * query.countDocuments({ color: 'black' }).count(callback); + * + * query.countDocuments({ color: 'black' }, callback); + * + * query.where('color', 'black').countDocuments(function(err, count) { + * if (err) return handleError(err); + * console.log('there are %d kittens', count); + * }); + * + * The `countDocuments()` function is similar to `count()`, but there are a + * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). + * Below are the operators that `count()` supports but `countDocuments()` does not, + * and the suggested replacement: + * + * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/) + * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center) + * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere) + * + * @param {Object} [filter] mongodb selector + * @param {Function} [callback] optional params are (error, count) + * @return {Query} this + * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments + * @api public + */ + +Query.prototype.countDocuments = function(conditions, callback) { + this.op = 'countDocuments'; + this._validateOp(); + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + } + + conditions = utils.toObject(conditions); + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + if (!callback) { + return this; + } + + this.exec(callback); + + return this; +}; + +/** + * Thunk around distinct() + * + * @param {Function} [callback] + * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ + * @api private + */ + +Query.prototype.__distinct = wrapThunk(function __distinct(callback) { + this._castConditions(); + + if (this.error()) { + callback(this.error()); + return null; + } + + applyGlobalMaxTimeMS(this.options, this.model); + + const options = this._optionsForExec(); + + // don't pass in the conditions because we already merged them in + this._collection.collection. + distinct(this._distinct, this._conditions, options, callback); +}); + +/** + * Declares or executes a distinct() operation. + * + * Passing a `callback` executes the query. + * + * This function does not trigger any middleware. + * + * ####Example + * + * distinct(field, conditions, callback) + * distinct(field, conditions) + * distinct(field, callback) + * distinct(field) + * distinct(callback) + * distinct() + * + * @param {String} [field] + * @param {Object|Query} [filter] + * @param {Function} [callback] optional params are (error, arr) + * @return {Query} this + * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ + * @api public + */ + +Query.prototype.distinct = function(field, conditions, callback) { + this.op = 'distinct'; + this._validateOp(); + if (!callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + } else if (typeof field === 'function') { + callback = field; + field = undefined; + conditions = undefined; + } + } + + conditions = utils.toObject(conditions); + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + + prepareDiscriminatorCriteria(this); + } else if (conditions != null) { + this.error(new ObjectParameterError(conditions, 'filter', 'distinct')); + } + + if (field != null) { + this._distinct = field; + } + + if (callback != null) { + this.exec(callback); + } + + return this; +}; + +/** + * Sets the sort order + * + * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + * + * If a string is passed, it must be a space delimited list of path names. The + * sort order of each path is ascending unless the path name is prefixed with `-` + * which will be treated as descending. + * + * ####Example + * + * // sort by "field" ascending and "test" descending + * query.sort({ field: 'asc', test: -1 }); + * + * // equivalent + * query.sort('field -test'); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/ + * @api public + */ + +Query.prototype.sort = function(arg) { + if (arguments.length > 1) { + throw new Error('sort() only takes 1 Argument'); + } + + return Query.base.sort.call(this, arg); +}; + +/** + * Declare and/or execute this query as a remove() operation. `remove()` is + * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne) + * or [`deleteMany()`](#query_Query-deleteMany) instead. + * + * This function does not trigger any middleware + * + * ####Example + * + * Character.remove({ name: /Stark/ }, callback); + * + * This function calls the MongoDB driver's [`Collection#remove()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove). + * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an + * object that contains 3 properties: + * + * - `ok`: `1` if no errors occurred + * - `deletedCount`: the number of documents deleted + * - `n`: the number of documents deleted. Equal to `deletedCount`. + * + * ####Example + * + * const res = await Character.remove({ name: /Stark/ }); + * // Number of docs deleted + * res.deletedCount; + * + * ####Note + * + * Calling `remove()` creates a [Mongoose query](./queries.html), and a query + * does not execute until you either pass a callback, call [`Query#then()`](#query_Query-then), + * or call [`Query#exec()`](#query_Query-exec). + * + * // not executed + * const query = Character.remove({ name: /Stark/ }); + * + * // executed + * Character.remove({ name: /Stark/ }, callback); + * Character.remove({ name: /Stark/ }).remove(callback); + * + * // executed without a callback + * Character.exec(); + * + * @param {Object|Query} [filter] mongodb selector + * @param {Function} [callback] optional params are (error, mongooseDeleteResult) + * @return {Query} this + * @deprecated + * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult + * @see MongoDB driver remove http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove + * @api public + */ + +Query.prototype.remove = function(filter, callback) { + this.op = 'remove'; + if (typeof filter === 'function') { + callback = filter; + filter = null; + } + + filter = utils.toObject(filter); + + if (mquery.canMerge(filter)) { + this.merge(filter); + + prepareDiscriminatorCriteria(this); + } else if (filter != null) { + this.error(new ObjectParameterError(filter, 'filter', 'remove')); + } + + if (!callback) { + return Query.base.remove.call(this); + } + + this.exec(callback); + return this; +}; + +/*! + * ignore + */ + +Query.prototype._remove = wrapThunk(function(callback) { + this._castConditions(); + + if (this.error() != null) { + callback(this.error()); + return this; + } + + callback = _wrapThunkCallback(this, callback); + + return Query.base.remove.call(this, helpers.handleDeleteWriteOpResult(callback)); +}); + +/** + * Declare and/or execute this query as a `deleteOne()` operation. Works like + * remove, except it deletes at most one document regardless of the `single` + * option. + * + * This function triggers `deleteOne` middleware. + * + * ####Example + * + * await Character.deleteOne({ name: 'Eddard Stark' }); + * + * // Using callbacks: + * Character.deleteOne({ name: 'Eddard Stark' }, callback); + * + * This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne). + * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an + * object that contains 3 properties: + * + * - `ok`: `1` if no errors occurred + * - `deletedCount`: the number of documents deleted + * - `n`: the number of documents deleted. Equal to `deletedCount`. + * + * ####Example + * + * const res = await Character.deleteOne({ name: 'Eddard Stark' }); + * // `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }` + * res.deletedCount; + * + * @param {Object|Query} [filter] mongodb selector + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] optional params are (error, mongooseDeleteResult) + * @return {Query} this + * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult + * @see MongoDB Driver deleteOne http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne + * @api public + */ + +Query.prototype.deleteOne = function(filter, options, callback) { + this.op = 'deleteOne'; + if (typeof filter === 'function') { + callback = filter; + filter = null; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } else { + this.setOptions(options); + } + + filter = utils.toObject(filter); + + if (mquery.canMerge(filter)) { + this.merge(filter); + + prepareDiscriminatorCriteria(this); + } else if (filter != null) { + this.error(new ObjectParameterError(filter, 'filter', 'deleteOne')); + } + + if (!callback) { + return Query.base.deleteOne.call(this); + } + + this.exec.call(this, callback); + + return this; +}; + +/*! + * Internal thunk for `deleteOne()` + */ + +Query.prototype._deleteOne = wrapThunk(function(callback) { + this._castConditions(); + + if (this.error() != null) { + callback(this.error()); + return this; + } + + callback = _wrapThunkCallback(this, callback); + + return Query.base.deleteOne.call(this, helpers.handleDeleteWriteOpResult(callback)); +}); + +/** + * Declare and/or execute this query as a `deleteMany()` operation. Works like + * remove, except it deletes _every_ document that matches `filter` in the + * collection, regardless of the value of `single`. + * + * This function triggers `deleteMany` middleware. + * + * ####Example + * + * await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); + * + * // Using callbacks: + * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback); + * + * This function calls the MongoDB driver's [`Collection#deleteMany()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany). + * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an + * object that contains 3 properties: + * + * - `ok`: `1` if no errors occurred + * - `deletedCount`: the number of documents deleted + * - `n`: the number of documents deleted. Equal to `deletedCount`. + * + * ####Example + * + * const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); + * // `0` if no docs matched the filter, number of docs deleted otherwise + * res.deletedCount; + * + * @param {Object|Query} [filter] mongodb selector + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] optional params are (error, mongooseDeleteResult) + * @return {Query} this + * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult + * @see MongoDB Driver deleteMany http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany + * @api public + */ + +Query.prototype.deleteMany = function(filter, options, callback) { + this.op = 'deleteMany'; + if (typeof filter === 'function') { + callback = filter; + filter = null; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } else { + this.setOptions(options); + } + + filter = utils.toObject(filter); + + if (mquery.canMerge(filter)) { + this.merge(filter); + + prepareDiscriminatorCriteria(this); + } else if (filter != null) { + this.error(new ObjectParameterError(filter, 'filter', 'deleteMany')); + } + + if (!callback) { + return Query.base.deleteMany.call(this); + } + + this.exec.call(this, callback); + + return this; +}; + +/*! + * Internal thunk around `deleteMany()` + */ + +Query.prototype._deleteMany = wrapThunk(function(callback) { + this._castConditions(); + + if (this.error() != null) { + callback(this.error()); + return this; + } + + callback = _wrapThunkCallback(this, callback); + + return Query.base.deleteMany.call(this, helpers.handleDeleteWriteOpResult(callback)); +}); + +/*! + * hydrates a document + * + * @param {Model} model + * @param {Document} doc + * @param {Object} res 3rd parameter to callback + * @param {Object} fields + * @param {Query} self + * @param {Array} [pop] array of paths used in population + * @param {Function} callback + */ + +function completeOne(model, doc, res, options, fields, userProvidedFields, pop, callback) { + const opts = pop ? + { populated: pop } + : undefined; + + if (options.rawResult && doc == null) { + _init(null); + return null; + } + + const casted = helpers.createModel(model, doc, fields, userProvidedFields, options); + try { + casted.$init(doc, opts, _init); + } catch (error) { + _init(error); + } + + function _init(err) { + if (err) { + return immediate(() => callback(err)); + } + + + if (options.rawResult) { + if (doc && casted) { + if (options.session != null) { + casted.$session(options.session); + } + res.value = casted; + } else { + res.value = null; + } + return immediate(() => callback(null, res)); + } + if (options.session != null) { + casted.$session(options.session); + } + immediate(() => callback(null, casted)); + } +} + +/*! + * If the model is a discriminator type and not root, then add the key & value to the criteria. + */ + +function prepareDiscriminatorCriteria(query) { + if (!query || !query.model || !query.model.schema) { + return; + } + + const schema = query.model.schema; + + if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { + query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; + } +} + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found + * document (if any) to the callback. The query executes if + * `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndUpdate()` + * + * ####Available options + * + * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * - `setDefaultsOnInsert`: `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * } + * + * ####Examples + * + * query.findOneAndUpdate(conditions, update, options, callback) // executes + * query.findOneAndUpdate(conditions, update, options) // returns Query + * query.findOneAndUpdate(conditions, update, callback) // executes + * query.findOneAndUpdate(conditions, update) // returns Query + * query.findOneAndUpdate(update, callback) // returns Query + * query.findOneAndUpdate(update) // returns Query + * query.findOneAndUpdate(callback) // executes + * query.findOneAndUpdate() // returns Query + * + * @method findOneAndUpdate + * @memberOf Query + * @instance + * @param {Object|Query} [filter] + * @param {Object} [doc] + * @param {Object} [options] + * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. + * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. + * @param {Function} [callback] optional params are (error, doc), _unless_ `rawResult` is used, in which case params are (error, writeOpResult) + * @see Tutorial /docs/tutorials/findoneandupdate.html + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @return {Query} this + * @api public + */ + +Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) { + this.op = 'findOneAndUpdate'; + this._validateOp(); + this._validate(); + + switch (arguments.length) { + case 3: + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 2: + if (typeof doc === 'function') { + callback = doc; + doc = criteria; + criteria = undefined; + } + options = undefined; + break; + case 1: + if (typeof criteria === 'function') { + callback = criteria; + criteria = options = doc = undefined; + } else { + doc = criteria; + criteria = options = undefined; + } + } + + if (mquery.canMerge(criteria)) { + this.merge(criteria); + } + + // apply doc + if (doc) { + this._mergeUpdate(doc); + } + + options = options ? utils.clone(options) : {}; + + if (options.projection) { + this.select(options.projection); + delete options.projection; + } + if (options.fields) { + this.select(options.fields); + delete options.fields; + } + + + const returnOriginal = get(this, 'model.base.options.returnOriginal'); + if (options.new == null && options.returnDocument == null && options.returnOriginal == null && returnOriginal != null) { + options.returnOriginal = returnOriginal; + } + + this.setOptions(options); + + if (!callback) { + return this; + } + + this.exec(callback); + + return this; +}; + +/*! + * Thunk around findOneAndUpdate() + * + * @param {Function} [callback] + * @api private + */ + +Query.prototype._findOneAndUpdate = wrapThunk(function(callback) { + if (this.error() != null) { + return callback(this.error()); + } + + this._findAndModify('update', callback); +}); + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to + * the callback. Executes if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndRemove()` + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * } + * + * ####Examples + * + * A.where().findOneAndRemove(conditions, options, callback) // executes + * A.where().findOneAndRemove(conditions, options) // return Query + * A.where().findOneAndRemove(conditions, callback) // executes + * A.where().findOneAndRemove(conditions) // returns Query + * A.where().findOneAndRemove(callback) // executes + * A.where().findOneAndRemove() // returns Query + * + * @method findOneAndRemove + * @memberOf Query + * @instance + * @param {Object} [conditions] + * @param {Object} [options] + * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Function} [callback] optional params are (error, document) + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Query.prototype.findOneAndRemove = function(conditions, options, callback) { + this.op = 'findOneAndRemove'; + this._validateOp(); + this._validate(); + + switch (arguments.length) { + case 2: + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 1: + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + options = undefined; + } + break; + } + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + options && this.setOptions(options); + + if (!callback) { + return this; + } + + this.exec(callback); + + return this; +}; + +/** + * Issues a MongoDB [findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/) command. + * + * Finds a matching document, removes it, and passes the found document (if any) + * to the callback. Executes if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndDelete()` + * + * This function differs slightly from `Model.findOneAndRemove()` in that + * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), + * as opposed to a `findOneAndDelete()` command. For most mongoose use cases, + * this distinction is purely pedantic. You should use `findOneAndDelete()` + * unless you have a good reason not to. + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * } + * + * ####Examples + * + * A.where().findOneAndDelete(conditions, options, callback) // executes + * A.where().findOneAndDelete(conditions, options) // return Query + * A.where().findOneAndDelete(conditions, callback) // executes + * A.where().findOneAndDelete(conditions) // returns Query + * A.where().findOneAndDelete(callback) // executes + * A.where().findOneAndDelete() // returns Query + * + * @method findOneAndDelete + * @memberOf Query + * @param {Object} [conditions] + * @param {Object} [options] + * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Function} [callback] optional params are (error, document) + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Query.prototype.findOneAndDelete = function(conditions, options, callback) { + this.op = 'findOneAndDelete'; + this._validateOp(); + this._validate(); + + switch (arguments.length) { + case 2: + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 1: + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + options = undefined; + } + break; + } + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + options && this.setOptions(options); + + if (!callback) { + return this; + } + + this.exec(callback); + + return this; +}; + +/*! + * Thunk around findOneAndDelete() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._findOneAndDelete = wrapThunk(function(callback) { + this._castConditions(); + + if (this.error() != null) { + callback(this.error()); + return null; + } + + const filter = this._conditions; + const options = this._optionsForExec(); + let fields = null; + + if (this._fields != null) { + options.projection = this._castFields(utils.clone(this._fields)); + fields = options.projection; + if (fields instanceof Error) { + callback(fields); + return null; + } + } + + this._collection.collection.findOneAndDelete(filter, options, _wrapThunkCallback(this, (err, res) => { + if (err) { + return callback(err); + } + + const doc = res.value; + + return this._completeOne(doc, res, callback); + })); +}); + +/** + * Issues a MongoDB [findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/) command. + * + * Finds a matching document, removes it, and passes the found document (if any) + * to the callback. Executes if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndReplace()` + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * } + * + * ####Examples + * + * A.where().findOneAndReplace(filter, replacement, options, callback); // executes + * A.where().findOneAndReplace(filter, replacement, options); // return Query + * A.where().findOneAndReplace(filter, replacement, callback); // executes + * A.where().findOneAndReplace(filter); // returns Query + * A.where().findOneAndReplace(callback); // executes + * A.where().findOneAndReplace(); // returns Query + * + * @method findOneAndReplace + * @memberOf Query + * @param {Object} [filter] + * @param {Object} [replacement] + * @param {Object} [options] + * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. + * @param {Function} [callback] optional params are (error, document) + * @return {Query} this + * @api public + */ + +Query.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + this.op = 'findOneAndReplace'; + this._validateOp(); + this._validate(); + + switch (arguments.length) { + case 3: + if (typeof options === 'function') { + callback = options; + options = void 0; + } + break; + case 2: + if (typeof replacement === 'function') { + callback = replacement; + replacement = void 0; + } + break; + case 1: + if (typeof filter === 'function') { + callback = filter; + filter = void 0; + replacement = void 0; + options = void 0; + } + break; + } + + if (mquery.canMerge(filter)) { + this.merge(filter); + } + + if (replacement != null) { + if (hasDollarKeys(replacement)) { + throw new Error('The replacement document must not contain atomic operators.'); + } + this._mergeUpdate(replacement); + } + + options = options || {}; + + const returnOriginal = get(this, 'model.base.options.returnOriginal'); + if (options.new == null && options.returnDocument == null && options.returnOriginal == null && returnOriginal != null) { + options.returnOriginal = returnOriginal; + } + this.setOptions(options); + this.setOptions({ overwrite: true }); + + if (!callback) { + return this; + } + + this.exec(callback); + + return this; +}; + +/*! + * Thunk around findOneAndReplace() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._findOneAndReplace = wrapThunk(function(callback) { + this._castConditions(); + + if (this.error() != null) { + callback(this.error()); + return null; + } + + const filter = this._conditions; + const options = this._optionsForExec(); + convertNewToReturnDocument(options); + let fields = null; + + let castedDoc = new this.model(this._update, null, true); + this._update = castedDoc; + + this._applyPaths(); + if (this._fields != null) { + options.projection = this._castFields(utils.clone(this._fields)); + fields = options.projection; + if (fields instanceof Error) { + callback(fields); + return null; + } + } + + castedDoc.$validate(err => { + if (err != null) { + return callback(err); + } + + if (castedDoc.toBSON) { + castedDoc = castedDoc.toBSON(); + } + + this._collection.collection.findOneAndReplace(filter, castedDoc, options, _wrapThunkCallback(this, (err, res) => { + if (err) { + return callback(err); + } + + const doc = res.value; + + return this._completeOne(doc, res, callback); + })); + }); +}); + +/*! + * Support the `new` option as an alternative to `returnOriginal` for backwards + * compat. + */ + +function convertNewToReturnDocument(options) { + if ('new' in options) { + options.returnDocument = options['new'] ? 'after' : 'before'; + delete options['new']; + } + if ('returnOriginal' in options) { + options.returnDocument = options['returnOriginal'] ? 'before' : 'after'; + delete options['returnOriginal']; + } + // Temporary since driver 4.0.0-beta does not support `returnDocument` + if (typeof options.returnDocument === 'string') { + options.returnOriginal = options.returnDocument === 'before'; + } +} + +/*! + * Thunk around findOneAndRemove() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._findOneAndRemove = wrapThunk(function(callback) { + if (this.error() != null) { + callback(this.error()); + return; + } + + this._findAndModify('remove', callback); +}); + +/*! + * Get options from query opts, falling back to the base mongoose object. + */ + +function _getOption(query, option, def) { + const opts = query._optionsForExec(query.model); + + if (option in opts) { + return opts[option]; + } + if (option in query.model.base.options) { + return query.model.base.options[option]; + } + return def; +} + +/*! + * Override mquery.prototype._findAndModify to provide casting etc. + * + * @param {String} type - either "remove" or "update" + * @param {Function} callback + * @api private + */ + +Query.prototype._findAndModify = function(type, callback) { + if (typeof callback !== 'function') { + throw new Error('Expected callback in _findAndModify'); + } + + const model = this.model; + const schema = model.schema; + const _this = this; + let fields; + + const castedQuery = castQuery(this); + if (castedQuery instanceof Error) { + return callback(castedQuery); + } + + _castArrayFilters(this); + + const opts = this._optionsForExec(model); + + if ('strict' in opts) { + this._mongooseOptions.strict = opts.strict; + } + + const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update); + if (isOverwriting) { + this._update = new this.model(this._update, null, true); + } + + if (type === 'remove') { + opts.remove = true; + } else { + if (!('new' in opts) && !('returnOriginal' in opts) && !('returnDocument' in opts)) { + opts.new = false; + } + if (!('upsert' in opts)) { + opts.upsert = false; + } + if (opts.upsert || opts['new']) { + opts.remove = false; + } + + if (!isOverwriting) { + this._update = castDoc(this, opts.overwrite); + const _opts = Object.assign({}, opts, { + setDefaultsOnInsert: this._mongooseOptions.setDefaultsOnInsert + }); + this._update = setDefaultsOnInsert(this._conditions, schema, this._update, _opts); + if (!this._update || Object.keys(this._update).length === 0) { + if (opts.upsert) { + // still need to do the upsert to empty doc + const doc = utils.clone(castedQuery); + delete doc._id; + this._update = { $set: doc }; + } else { + this._executionStack = null; + this.findOne(callback); + return this; + } + } else if (this._update instanceof Error) { + return callback(this._update); + } else { + // In order to make MongoDB 2.6 happy (see + // https://jira.mongodb.org/browse/SERVER-12266 and related issues) + // if we have an actual update document but $set is empty, junk the $set. + if (this._update.$set && Object.keys(this._update.$set).length === 0) { + delete this._update.$set; + } + } + } + + if (Array.isArray(opts.arrayFilters)) { + opts.arrayFilters = removeUnusedArrayFilters(this._update, opts.arrayFilters); + } + } + + this._applyPaths(); + + if (this._fields) { + fields = utils.clone(this._fields); + opts.projection = this._castFields(fields); + if (opts.projection instanceof Error) { + return callback(opts.projection); + } + } + + if (opts.sort) convertSortToArray(opts); + + const cb = function(err, doc, res) { + if (err) { + return callback(err); + } + + _this._completeOne(doc, res, callback); + }; + + const runValidators = _getOption(this, 'runValidators', false); + + // Bypass mquery + const collection = _this._collection.collection; + convertNewToReturnDocument(opts); + + if (type === 'remove') { + collection.findOneAndDelete(castedQuery, opts, _wrapThunkCallback(_this, function(error, res) { + return cb(error, res ? res.value : res, res); + })); + + return this; + } + + // honors legacy overwrite option for backward compatibility + const updateMethod = isOverwriting ? 'findOneAndReplace' : 'findOneAndUpdate'; + + if (runValidators) { + this.validate(this._update, opts, isOverwriting, error => { + if (error) { + return callback(error); + } + if (this._update && this._update.toBSON) { + this._update = this._update.toBSON(); + } + + collection[updateMethod](castedQuery, this._update, opts, _wrapThunkCallback(_this, function(error, res) { + return cb(error, res ? res.value : res, res); + })); + }); + } else { + if (this._update && this._update.toBSON) { + this._update = this._update.toBSON(); + } + collection[updateMethod](castedQuery, this._update, opts, _wrapThunkCallback(_this, function(error, res) { + return cb(error, res ? res.value : res, res); + })); + } + + return this; +}; + +/*! + * ignore + */ + +function _completeOneLean(doc, res, opts, callback) { + if (opts.rawResult) { + return callback(null, res); + } + return callback(null, doc); +} + +/*! + * Override mquery.prototype._mergeUpdate to handle mongoose objects in + * updates. + * + * @param {Object} doc + * @api private + */ + +Query.prototype._mergeUpdate = function(doc) { + if (doc == null || (typeof doc === 'object' && Object.keys(doc).length === 0)) { + return; + } + + if (!this._update) { + this._update = Array.isArray(doc) ? [] : {}; + } + if (doc instanceof Query) { + if (Array.isArray(this._update)) { + throw new Error('Cannot mix array and object updates'); + } + if (doc._update) { + utils.mergeClone(this._update, doc._update); + } + } else if (Array.isArray(doc)) { + if (!Array.isArray(this._update)) { + throw new Error('Cannot mix array and object updates'); + } + this._update = this._update.concat(doc); + } else { + if (Array.isArray(this._update)) { + throw new Error('Cannot mix array and object updates'); + } + utils.mergeClone(this._update, doc); + } +}; + +/*! + * The mongodb driver 1.3.23 only supports the nested array sort + * syntax. We must convert it or sorting findAndModify will not work. + */ + +function convertSortToArray(opts) { + if (Array.isArray(opts.sort)) { + return; + } + if (!utils.isObject(opts.sort)) { + return; + } + + const sort = []; + + for (const key in opts.sort) { + if (utils.object.hasOwnProperty(opts.sort, key)) { + sort.push([key, opts.sort[key]]); + } + } + + opts.sort = sort; +} + +/*! + * ignore + */ + +function _updateThunk(op, callback) { + this._castConditions(); + + _castArrayFilters(this); + + if (this.error() != null) { + callback(this.error()); + return null; + } + + callback = _wrapThunkCallback(this, callback); + + const castedQuery = this._conditions; + const options = this._optionsForExec(this.model); + + this._update = utils.clone(this._update, options); + const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update); + if (isOverwriting) { + if (op === 'updateOne' || op === 'updateMany') { + return callback(new MongooseError('The MongoDB server disallows ' + + 'overwriting documents using `' + op + '`. See: ' + + 'https://mongoosejs.com/docs/deprecations.html#update')); + } + this._update = new this.model(this._update, null, true); + } else { + this._update = castDoc(this, options.overwrite); + + if (this._update instanceof Error) { + callback(this._update); + return null; + } + + if (this._update == null || Object.keys(this._update).length === 0) { + callback(null, { acknowledged: false }); + return null; + } + + const _opts = Object.assign({}, options, { + setDefaultsOnInsert: this._mongooseOptions.setDefaultsOnInsert + }); + this._update = setDefaultsOnInsert(this._conditions, this.model.schema, + this._update, _opts); + } + + if (Array.isArray(options.arrayFilters)) { + options.arrayFilters = removeUnusedArrayFilters(this._update, options.arrayFilters); + } + + const runValidators = _getOption(this, 'runValidators', false); + if (runValidators) { + this.validate(this._update, options, isOverwriting, err => { + if (err) { + return callback(err); + } + + if (this._update.toBSON) { + this._update = this._update.toBSON(); + } + this._collection[op](castedQuery, this._update, options, callback); + }); + return null; + } + + if (this._update.toBSON) { + this._update = this._update.toBSON(); + } + + this._collection[op](castedQuery, this._update, options, callback); + return null; +} + +/*! + * Mongoose calls this function internally to validate the query if + * `runValidators` is set + * + * @param {Object} castedDoc the update, after casting + * @param {Object} options the options from `_optionsForExec()` + * @param {Function} callback + * @api private + */ + +Query.prototype.validate = function validate(castedDoc, options, isOverwriting, callback) { + return promiseOrCallback(callback, cb => { + try { + if (isOverwriting) { + castedDoc.$validate(cb); + } else { + updateValidators(this, this.model.schema, castedDoc, options, cb); + } + } catch (err) { + immediate(function() { + cb(err); + }); + } + }); +}; + +/*! + * Internal thunk for .update() + * + * @param {Function} callback + * @see Model.update #model_Model.update + * @api private + */ +Query.prototype._execUpdate = wrapThunk(function(callback) { + return _updateThunk.call(this, 'update', callback); +}); + +/*! + * Internal thunk for .updateMany() + * + * @param {Function} callback + * @see Model.update #model_Model.update + * @api private + */ +Query.prototype._updateMany = wrapThunk(function(callback) { + return _updateThunk.call(this, 'updateMany', callback); +}); + +/*! + * Internal thunk for .updateOne() + * + * @param {Function} callback + * @see Model.update #model_Model.update + * @api private + */ +Query.prototype._updateOne = wrapThunk(function(callback) { + return _updateThunk.call(this, 'updateOne', callback); +}); + +/*! + * Internal thunk for .replaceOne() + * + * @param {Function} callback + * @see Model.replaceOne #model_Model.replaceOne + * @api private + */ +Query.prototype._replaceOne = wrapThunk(function(callback) { + return _updateThunk.call(this, 'replaceOne', callback); +}); + +/** + * Declare and/or execute this query as an update() operation. + * + * _All paths passed that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operations will become `$set` ops._ + * + * This function triggers the following middleware. + * + * - `update()` + * + * ####Example + * + * Model.where({ _id: id }).update({ title: 'words' }) + * + * // becomes + * + * Model.where({ _id: id }).update({ $set: { title: 'words' }}) + * + * ####Valid options: + * + * - `upsert` (boolean) whether to create the doc if it doesn't match (false) + * - `multi` (boolean) whether multiple documents should be updated (false) + * - `runValidators` (boolean) if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * - `setDefaultsOnInsert` (boolean) `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. + * - `strict` (boolean) overrides the `strict` option for this update + * - `read` + * - `writeConcern` + * + * ####Note + * + * Passing an empty object `{}` as the doc will result in a no-op. The update operation will be ignored and the callback executed without sending the command to MongoDB. + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the `exec()` method. + * + * const q = Model.where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).update(); // not executed + * + * q.update({ $set: { name: 'bob' }}).exec(); // executed + * + * // keys that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) ops become `$set`. + * // this executes the same command as the previous example. + * q.update({ name: 'bob' }).exec(); + * + * // multi updates + * Model.where() + * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) + * + * // more multi updates + * Model.where() + * .setOptions({ multi: true }) + * .update({ $set: { arr: [] }}, callback) + * + * // single update by default + * Model.where({ email: 'address@example.com' }) + * .update({ $inc: { counter: 1 }}, callback) + * + * API summary + * + * update(filter, doc, options, cb) // executes + * update(filter, doc, options) + * update(filter, doc, cb) // executes + * update(filter, doc) + * update(doc, cb) // executes + * update(doc) + * update(cb) // executes + * update(true) // executes + * update() + * + * @param {Object} [filter] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] params are (error, writeOpResult) + * @return {Query} this + * @see Model.update #model_Model.update + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @api public + */ + +Query.prototype.update = function(conditions, doc, options, callback) { + if (typeof options === 'function') { + // .update(conditions, doc, callback) + callback = options; + options = null; + } else if (typeof doc === 'function') { + // .update(doc, callback); + callback = doc; + doc = conditions; + conditions = {}; + options = null; + } else if (typeof conditions === 'function') { + // .update(callback) + callback = conditions; + conditions = undefined; + doc = undefined; + options = undefined; + } else if (typeof conditions === 'object' && !doc && !options && !callback) { + // .update(doc) + doc = conditions; + conditions = undefined; + options = undefined; + callback = undefined; + } + + return _update(this, 'update', conditions, doc, options, callback); +}; + +/** + * Declare and/or execute this query as an updateMany() operation. Same as + * `update()`, except MongoDB will update _all_ documents that match + * `filter` (as opposed to just the first one) regardless of the value of + * the `multi` option. + * + * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')` + * and `post('updateMany')` instead. + * + * ####Example: + * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true }); + * res.n; // Number of documents matched + * res.nModified; // Number of documents modified + * + * This function triggers the following middleware. + * + * - `updateMany()` + * + * @param {Object} [filter] + * @param {Object|Array} [update] the update command + * @param {Object} [options] + * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] params are (error, writeOpResult) + * @return {Query} this + * @see Model.update #model_Model.update + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @api public + */ + +Query.prototype.updateMany = function(conditions, doc, options, callback) { + if (typeof options === 'function') { + // .update(conditions, doc, callback) + callback = options; + options = null; + } else if (typeof doc === 'function') { + // .update(doc, callback); + callback = doc; + doc = conditions; + conditions = {}; + options = null; + } else if (typeof conditions === 'function') { + // .update(callback) + callback = conditions; + conditions = undefined; + doc = undefined; + options = undefined; + } else if (typeof conditions === 'object' && !doc && !options && !callback) { + // .update(doc) + doc = conditions; + conditions = undefined; + options = undefined; + callback = undefined; + } + + return _update(this, 'updateMany', conditions, doc, options, callback); +}; + +/** + * Declare and/or execute this query as an updateOne() operation. Same as + * `update()`, except it does not support the `multi` option. + * + * - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option. + * - Use `replaceOne()` if you want to overwrite an entire document rather than using [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators like `$set`. + * + * **Note** updateOne will _not_ fire update middleware. Use `pre('updateOne')` + * and `post('updateOne')` instead. + * + * ####Example: + * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' }); + * res.n; // Number of documents matched + * res.nModified; // Number of documents modified + * + * This function triggers the following middleware. + * + * - `updateOne()` + * + * @param {Object} [filter] + * @param {Object|Array} [update] the update command + * @param {Object} [options] + * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] params are (error, writeOpResult) + * @return {Query} this + * @see Model.update #model_Model.update + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @api public + */ + +Query.prototype.updateOne = function(conditions, doc, options, callback) { + if (typeof options === 'function') { + // .update(conditions, doc, callback) + callback = options; + options = null; + } else if (typeof doc === 'function') { + // .update(doc, callback); + callback = doc; + doc = conditions; + conditions = {}; + options = null; + } else if (typeof conditions === 'function') { + // .update(callback) + callback = conditions; + conditions = undefined; + doc = undefined; + options = undefined; + } else if (typeof conditions === 'object' && !doc && !options && !callback) { + // .update(doc) + doc = conditions; + conditions = undefined; + options = undefined; + callback = undefined; + } + + return _update(this, 'updateOne', conditions, doc, options, callback); +}; + +/** + * Declare and/or execute this query as a replaceOne() operation. Same as + * `update()`, except MongoDB will replace the existing document and will + * not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.) + * + * **Note** replaceOne will _not_ fire update middleware. Use `pre('replaceOne')` + * and `post('replaceOne')` instead. + * + * ####Example: + * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' }); + * res.n; // Number of documents matched + * res.nModified; // Number of documents modified + * + * This function triggers the following middleware. + * + * - `replaceOne()` + * + * @param {Object} [filter] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] params are (error, writeOpResult) + * @return {Query} this + * @see Model.update #model_Model.update + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @api public + */ + +Query.prototype.replaceOne = function(conditions, doc, options, callback) { + if (typeof options === 'function') { + // .update(conditions, doc, callback) + callback = options; + options = null; + } else if (typeof doc === 'function') { + // .update(doc, callback); + callback = doc; + doc = conditions; + conditions = {}; + options = null; + } else if (typeof conditions === 'function') { + // .update(callback) + callback = conditions; + conditions = undefined; + doc = undefined; + options = undefined; + } else if (typeof conditions === 'object' && !doc && !options && !callback) { + // .update(doc) + doc = conditions; + conditions = undefined; + options = undefined; + callback = undefined; + } + + this.setOptions({ overwrite: true }); + return _update(this, 'replaceOne', conditions, doc, options, callback); +}; + +/*! + * Internal helper for update, updateMany, updateOne, replaceOne + */ + +function _update(query, op, filter, doc, options, callback) { + // make sure we don't send in the whole Document to merge() + query.op = op; + query._validateOp(); + filter = utils.toObject(filter); + doc = doc || {}; + + // strict is an option used in the update checking, make sure it gets set + if (options != null) { + if ('strict' in options) { + query._mongooseOptions.strict = options.strict; + } + } + + if (!(filter instanceof Query) && + filter != null && + filter.toString() !== '[object Object]') { + query.error(new ObjectParameterError(filter, 'filter', op)); + } else { + query.merge(filter); + } + + if (utils.isObject(options)) { + query.setOptions(options); + } + + query._mergeUpdate(doc); + + // Hooks + if (callback) { + query.exec(callback); + + return query; + } + + return Query.base[op].call(query, filter, void 0, options, callback); +} + +/** + * Runs a function `fn` and treats the return value of `fn` as the new value + * for the query to resolve to. + * + * Any functions you pass to `map()` will run **after** any post hooks. + * + * ####Example: + * + * const res = await MyModel.findOne().transform(res => { + * // Sets a `loadedAt` property on the doc that tells you the time the + * // document was loaded. + * return res == null ? + * res : + * Object.assign(res, { loadedAt: new Date() }); + * }); + * + * @method map + * @memberOf Query + * @instance + * @param {Function} fn function to run to transform the query result + * @return {Query} this + */ + +Query.prototype.transform = function(fn) { + this._transforms.push(fn); + return this; +}; + +/** + * Make this query throw an error if no documents match the given `filter`. + * This is handy for integrating with async/await, because `orFail()` saves you + * an extra `if` statement to check if no document was found. + * + * ####Example: + * + * // Throws if no doc returned + * await Model.findOne({ foo: 'bar' }).orFail(); + * + * // Throws if no document was updated + * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail(); + * + * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }` + * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!')); + * + * // Throws "Not found" error if no document was found + * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }). + * orFail(() => Error('Not found')); + * + * @method orFail + * @memberOf Query + * @instance + * @param {Function|Error} [err] optional error to throw if no docs match `filter`. If not specified, `orFail()` will throw a `DocumentNotFoundError` + * @return {Query} this + */ + +Query.prototype.orFail = function(err) { + this.transform(res => { + switch (this.op) { + case 'find': + if (res.length === 0) { + throw _orFailError(err, this); + } + break; + case 'findOne': + if (res == null) { + throw _orFailError(err, this); + } + break; + case 'update': + case 'updateMany': + case 'updateOne': + if (get(res, 'modifiedCount') === 0) { + throw _orFailError(err, this); + } + break; + case 'findOneAndDelete': + case 'findOneAndRemove': + if (get(res, 'lastErrorObject.n') === 0) { + throw _orFailError(err, this); + } + break; + case 'findOneAndUpdate': + case 'findOneAndReplace': + if (get(res, 'lastErrorObject.updatedExisting') === false) { + throw _orFailError(err, this); + } + break; + case 'deleteMany': + case 'deleteOne': + case 'remove': + if (res.deletedCount === 0) { + throw _orFailError(err, this); + } + break; + default: + break; + } + + return res; + }); + return this; +}; + +/*! + * Get the error to throw for `orFail()` + */ + +function _orFailError(err, query) { + if (typeof err === 'function') { + err = err.call(query); + } + + if (err == null) { + err = new DocumentNotFoundError(query.getQuery(), query.model.modelName); + } + + return err; +} + +/** + * Executes the query + * + * ####Examples: + * + * const promise = query.exec(); + * const promise = query.exec('update'); + * + * query.exec(callback); + * query.exec('find', callback); + * + * @param {String|Function} [operation] + * @param {Function} [callback] optional params depend on the function being called + * @return {Promise} + * @api public + */ + +Query.prototype.exec = function exec(op, callback) { + const _this = this; + // Ensure that `exec()` is the first thing that shows up in + // the stack when cast errors happen. + const castError = new CastError(); + + if (typeof op === 'function') { + callback = op; + op = null; + } else if (typeof op === 'string') { + this.op = op; + } + + if (this.op == null) { + throw new Error('Query must have `op` before executing'); + } + this._validateOp(); + + callback = this.model.$handleCallbackError(callback); + + return promiseOrCallback(callback, (cb) => { + cb = this.model.$wrapCallback(cb); + + if (!_this.op) { + cb(); + return; + } + + this._hooks.execPre('exec', this, [], (error) => { + if (error != null) { + return cb(_cleanCastErrorStack(castError, error)); + } + let thunk = '_' + this.op; + if (this.op === 'update') { + thunk = '_execUpdate'; + } else if (this.op === 'distinct') { + thunk = '__distinct'; + } + this[thunk].call(this, (error, res) => { + if (error) { + return cb(_cleanCastErrorStack(castError, error)); + } + + this._hooks.execPost('exec', this, [], {}, (error) => { + if (error) { + return cb(_cleanCastErrorStack(castError, error)); + } + + cb(null, res); + }); + }); + }); + }, this.model.events); +}; + +/*! + * ignore + */ + +function _cleanCastErrorStack(castError, error) { + if (error instanceof CastError) { + castError.copy(error); + return castError; + } + + return error; +} + +/*! + * ignore + */ + +function _wrapThunkCallback(query, cb) { + return function(error, res) { + if (error != null) { + return cb(error); + } + + for (const fn of query._transforms) { + try { + res = fn(res); + } catch (error) { + return cb(error); + } + } + + return cb(null, res); + }; +} + +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * + * More about [`then()` in JavaScript](https://masteringjs.io/tutorials/fundamentals/then). + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @return {Promise} + * @api public + */ + +Query.prototype.then = function(resolve, reject) { + return this.exec().then(resolve, reject); +}; + +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * Like `.then()`, but only takes a rejection handler. + * + * More about [Promise `catch()` in JavaScript](https://masteringjs.io/tutorials/fundamentals/catch). + * + * @param {Function} [reject] + * @return {Promise} + * @api public + */ + +Query.prototype.catch = function(reject) { + return this.exec().then(null, reject); +}; + +/** + * Add pre [middleware](/docs/middleware.html) to this query instance. Doesn't affect + * other queries. + * + * ####Example: + * + * const q1 = Question.find({ answer: 42 }); + * q1.pre(function middleware() { + * console.log(this.getFilter()); + * }); + * await q1.exec(); // Prints "{ answer: 42 }" + * + * // Doesn't print anything, because `middleware()` is only + * // registered on `q1`. + * await Question.find({ answer: 42 }); + * + * @param {Function} fn + * @return {Promise} + * @api public + */ + +Query.prototype.pre = function(fn) { + this._hooks.pre('exec', fn); + return this; +}; + +/** + * Add post [middleware](/docs/middleware.html) to this query instance. Doesn't affect + * other queries. + * + * ####Example: + * + * const q1 = Question.find({ answer: 42 }); + * q1.post(function middleware() { + * console.log(this.getFilter()); + * }); + * await q1.exec(); // Prints "{ answer: 42 }" + * + * // Doesn't print anything, because `middleware()` is only + * // registered on `q1`. + * await Question.find({ answer: 42 }); + * + * @param {Function} fn + * @return {Promise} + * @api public + */ + +Query.prototype.post = function(fn) { + this._hooks.post('exec', fn); + return this; +}; + +/*! + * Casts obj for an update command. + * + * @param {Object} obj + * @return {Object} obj after casting its values + * @api private + */ + +Query.prototype._castUpdate = function _castUpdate(obj, overwrite) { + let schema = this.schema; + + const discriminatorKey = schema.options.discriminatorKey; + const baseSchema = schema._baseSchema ? schema._baseSchema : schema; + if (this._mongooseOptions.overwriteDiscriminatorKey && + obj[discriminatorKey] != null && + baseSchema.discriminators) { + const _schema = baseSchema.discriminators[obj[discriminatorKey]]; + if (_schema != null) { + schema = _schema; + } + } + + let upsert; + if ('upsert' in this.options) { + upsert = this.options.upsert; + } + + const filter = this._conditions; + if (schema != null && + utils.hasUserDefinedProperty(filter, schema.options.discriminatorKey) && + typeof filter[schema.options.discriminatorKey] !== 'object' && + schema.discriminators != null) { + const discriminatorValue = filter[schema.options.discriminatorKey]; + const byValue = getDiscriminatorByValue(this.model.discriminators, discriminatorValue); + schema = schema.discriminators[discriminatorValue] || + (byValue && byValue.schema) || + schema; + } + + return castUpdate(schema, obj, { + overwrite: overwrite, + strict: this._mongooseOptions.strict, + upsert: upsert, + arrayFilters: this.options.arrayFilters + }, this, this._conditions); +}; + +/*! + * castQuery + * @api private + */ + +function castQuery(query) { + try { + return query.cast(query.model); + } catch (err) { + return err; + } +} + +/*! + * castDoc + * @api private + */ + +function castDoc(query, overwrite) { + try { + return query._castUpdate(query._update, overwrite); + } catch (err) { + return err; + } +} + +/** + * Specifies paths which should be populated with other documents. + * + * ####Example: + * + * let book = await Book.findOne().populate('authors'); + * book.title; // 'Node.js in Action' + * book.authors[0].name; // 'TJ Holowaychuk' + * book.authors[1].name; // 'Nathan Rajlich' + * + * let books = await Book.find().populate({ + * path: 'authors', + * // `match` and `sort` apply to the Author model, + * // not the Book model. These options do not affect + * // which documents are in `books`, just the order and + * // contents of each book document's `authors`. + * match: { name: new RegExp('.*h.*', 'i') }, + * sort: { name: -1 } + * }); + * books[0].title; // 'Node.js in Action' + * // Each book's `authors` are sorted by name, descending. + * books[0].authors[0].name; // 'TJ Holowaychuk' + * books[0].authors[1].name; // 'Marc Harter' + * + * books[1].title; // 'Professional AngularJS' + * // Empty array, no authors' name has the letter 'h' + * books[1].authors; // [] + * + * Paths are populated after the query executes and a response is received. A + * separate query is then executed for each path specified for population. After + * a response for each query has also been returned, the results are passed to + * the callback. + * + * @param {Object|String} path either the path to populate or an object specifying all parameters + * @param {Object|String} [select] Field selection for the population query + * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field. + * @param {Object} [match] Conditions for the population query + * @param {Object} [options] Options for the population query (sort, etc) + * @param {String} [options.path=null] The path to populate. + * @param {boolean} [options.retainNullValues=false] by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. + * @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). + * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. + * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. + * @param {Function} [options.transform=null] Function that Mongoose will call on every populated document that allows you to transform the populated document. + * @param {Object} [options.options=null] Additional options like `limit` and `lean`. + * @see population ./populate.html + * @see Query#select #query_Query-select + * @see Model.populate #model_Model.populate + * @return {Query} this + * @api public + */ + +Query.prototype.populate = function() { + // Bail when given no truthy arguments + if (!Array.from(arguments).some(Boolean)) { + return this; + } + + const res = utils.populate.apply(null, arguments); + + // Propagate readConcern and readPreference and lean from parent query, + // unless one already specified + if (this.options != null) { + const readConcern = this.options.readConcern; + const readPref = this.options.readPreference; + + for (const populateOptions of res) { + if (readConcern != null && get(populateOptions, 'options.readConcern') == null) { + populateOptions.options = populateOptions.options || {}; + populateOptions.options.readConcern = readConcern; + } + if (readPref != null && get(populateOptions, 'options.readPreference') == null) { + populateOptions.options = populateOptions.options || {}; + populateOptions.options.readPreference = readPref; + } + } + } + + const opts = this._mongooseOptions; + + if (opts.lean != null) { + const lean = opts.lean; + for (const populateOptions of res) { + if (get(populateOptions, 'options.lean') == null) { + populateOptions.options = populateOptions.options || {}; + populateOptions.options.lean = lean; + } + } + } + + if (!utils.isObject(opts.populate)) { + opts.populate = {}; + } + + const pop = opts.populate; + + for (const populateOptions of res) { + const path = populateOptions.path; + if (pop[path] && pop[path].populate && populateOptions.populate) { + populateOptions.populate = pop[path].populate.concat(populateOptions.populate); + } + + pop[populateOptions.path] = populateOptions; + } + return this; +}; + +/** + * Gets a list of paths to be populated by this query + * + * ####Example: + * bookSchema.pre('findOne', function() { + * let keys = this.getPopulatedPaths(); // ['author'] + * }); + * ... + * Book.findOne({}).populate('author'); + * + * ####Example: + * // Deep populate + * const q = L1.find().populate({ + * path: 'level2', + * populate: { path: 'level3' } + * }); + * q.getPopulatedPaths(); // ['level2', 'level2.level3'] + * + * @return {Array} an array of strings representing populated paths + * @api public + */ + +Query.prototype.getPopulatedPaths = function getPopulatedPaths() { + const obj = this._mongooseOptions.populate || {}; + const ret = Object.keys(obj); + for (const path of Object.keys(obj)) { + const pop = obj[path]; + if (!Array.isArray(pop.populate)) { + continue; + } + _getPopulatedPaths(ret, pop.populate, path + '.'); + } + return ret; +}; + +/*! + * ignore + */ + +function _getPopulatedPaths(list, arr, prefix) { + for (const pop of arr) { + list.push(prefix + pop.path); + if (!Array.isArray(pop.populate)) { + continue; + } + _getPopulatedPaths(list, pop.populate, prefix + pop.path + '.'); + } +} + +/** + * Casts this query to the schema of `model` + * + * ####Note + * + * If `obj` is present, it is cast instead of this query. + * + * @param {Model} [model] the model to cast to. If not set, defaults to `this.model` + * @param {Object} [obj] + * @return {Object} + * @api public + */ + +Query.prototype.cast = function(model, obj) { + obj || (obj = this._conditions); + + model = model || this.model; + const discriminatorKey = model.schema.options.discriminatorKey; + if (obj != null && + obj.hasOwnProperty(discriminatorKey)) { + model = getDiscriminatorByValue(model.discriminators, obj[discriminatorKey]) || model; + } + + try { + return cast(model.schema, obj, { + upsert: this.options && this.options.upsert, + strict: (this.options && 'strict' in this.options) ? + this.options.strict : + get(model, 'schema.options.strict', null), + strictQuery: (this.options && 'strictQuery' in this.options) ? + this.options.strictQuery : + (this.options && 'strict' in this.options) ? + this.options.strict : + get(model, 'schema.options.strictQuery', null) + }, this); + } catch (err) { + // CastError, assign model + if (typeof err.setModel === 'function') { + err.setModel(model); + } + throw err; + } +}; + +/** + * Casts selected field arguments for field selection with mongo 2.2 + * + * query.select({ ids: { $elemMatch: { $in: [hexString] }}) + * + * @param {Object} fields + * @see https://github.com/Automattic/mongoose/issues/1091 + * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ + * @api private + */ + +Query.prototype._castFields = function _castFields(fields) { + let selected, + elemMatchKeys, + keys, + key, + out, + i; + + if (fields) { + keys = Object.keys(fields); + elemMatchKeys = []; + i = keys.length; + + // collect $elemMatch args + while (i--) { + key = keys[i]; + if (fields[key].$elemMatch) { + selected || (selected = {}); + selected[key] = fields[key]; + elemMatchKeys.push(key); + } + } + } + + if (selected) { + // they passed $elemMatch, cast em + try { + out = this.cast(this.model, selected); + } catch (err) { + return err; + } + + // apply the casted field args + i = elemMatchKeys.length; + while (i--) { + key = elemMatchKeys[i]; + fields[key] = out[key]; + } + } + + return fields; +}; + +/** + * Applies schematype selected options to this query. + * @api private + */ + +Query.prototype._applyPaths = function applyPaths() { + this._fields = this._fields || {}; + helpers.applyPaths(this._fields, this.model.schema); + + let _selectPopulatedPaths = true; + + if ('selectPopulatedPaths' in this.model.base.options) { + _selectPopulatedPaths = this.model.base.options.selectPopulatedPaths; + } + if ('selectPopulatedPaths' in this.model.schema.options) { + _selectPopulatedPaths = this.model.schema.options.selectPopulatedPaths; + } + + if (_selectPopulatedPaths) { + selectPopulatedFields(this._fields, this._userProvidedFields, this._mongooseOptions.populate); + } +}; + +/** + * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html). + * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function. + * + * The `.cursor()` function triggers pre find hooks, but **not** post find hooks. + * + * ####Example + * + * // There are 2 ways to use a cursor. First, as a stream: + * Thing. + * find({ name: /^hello/ }). + * cursor(). + * on('data', function(doc) { console.log(doc); }). + * on('end', function() { console.log('Done!'); }); + * + * // Or you can use `.next()` to manually get the next doc in the stream. + * // `.next()` returns a promise, so you can use promises or callbacks. + * const cursor = Thing.find({ name: /^hello/ }).cursor(); + * cursor.next(function(error, doc) { + * console.log(doc); + * }); + * + * // Because `.next()` returns a promise, you can use co + * // to easily iterate through all documents without loading them + * // all into memory. + * const cursor = Thing.find({ name: /^hello/ }).cursor(); + * for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) { + * console.log(doc); + * } + * + * ####Valid options + * + * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`. + * + * @return {QueryCursor} + * @param {Object} [options] + * @see QueryCursor + * @api public + */ + +Query.prototype.cursor = function cursor(opts) { + this._applyPaths(); + this._fields = this._castFields(this._fields); + this.setOptions({ projection: this._fieldsForExec() }); + if (opts) { + this.setOptions(opts); + } + + const options = Object.assign({}, this._optionsForExec(), { + projection: this.projection() + }); + try { + this.cast(this.model); + } catch (err) { + return (new QueryCursor(this, options))._markError(err); + } + + return new QueryCursor(this, options); +}; + +// the rest of these are basically to support older Mongoose syntax with mquery + +/** + * _DEPRECATED_ Alias of `maxScan` + * + * @deprecated + * @see maxScan #query_Query-maxScan + * @method maxscan + * @memberOf Query + * @instance + */ + +Query.prototype.maxscan = Query.base.maxScan; + +/** + * Sets the tailable option (for use with capped collections). + * + * ####Example + * + * query.tailable() // true + * query.tailable(true) + * query.tailable(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Boolean} bool defaults to true + * @param {Object} [opts] options to set + * @param {Number} [opts.numberOfRetries] if cursor is exhausted, retry this many times before giving up + * @param {Number} [opts.tailableRetryInterval] if cursor is exhausted, wait this many milliseconds before retrying + * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/ + * @api public + */ + +Query.prototype.tailable = function(val, opts) { + // we need to support the tailable({ awaitdata : true }) as well as the + // tailable(true, {awaitdata :true}) syntax that mquery does not support + if (val != null && typeof val.constructor === 'function' && val.constructor.name === 'Object') { + opts = val; + val = true; + } + + if (val === undefined) { + val = true; + } + + if (opts && typeof opts === 'object') { + for (const key of Object.keys(opts)) { + if (key === 'awaitdata') { + // For backwards compatibility + this.options[key] = !!opts[key]; + } else { + this.options[key] = opts[key]; + } + } + } + + return Query.base.tailable.call(this, val); +}; + +/** + * Declares an intersects query for `geometry()`. + * + * ####Example + * + * query.where('path').intersects().geometry({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * query.where('path').intersects({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * ####NOTE: + * + * **MUST** be used after `where()`. + * + * ####NOTE: + * + * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). + * + * @method intersects + * @memberOf Query + * @instance + * @param {Object} [arg] + * @return {Query} this + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/ + * @api public + */ + +/** + * Specifies a `$geometry` condition + * + * ####Example + * + * const polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] + * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + * + * // or + * const polyB = [[ 0, 0 ], [ 1, 1 ]] + * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + * + * // or + * const polyC = [ 0, 0 ] + * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + * + * // or + * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + * + * The argument is assigned to the most recent path passed to `where()`. + * + * ####NOTE: + * + * `geometry()` **must** come after either `intersects()` or `within()`. + * + * The `object` argument must contain `type` and `coordinates` properties. + * - type {String} + * - coordinates {Array} + * + * @method geometry + * @memberOf Query + * @instance + * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. + * @return {Query} this + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/** + * Specifies a `$near` or `$nearSphere` condition + * + * These operators return documents sorted by distance. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10] }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); + * query.near('loc', { center: [10, 10], maxDistance: 5 }); + * + * @method near + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see $near http://docs.mongodb.org/manual/reference/operator/near/ + * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/*! + * Overwriting mquery is needed to support a couple different near() forms found in older + * versions of mongoose + * near([1,1]) + * near(1,1) + * near(field, [1,2]) + * near(field, 1, 2) + * In addition to all of the normal forms supported by mquery + */ + +Query.prototype.near = function() { + const params = []; + const sphere = this._mongooseOptions.nearSphere; + + // TODO refactor + + if (arguments.length === 1) { + if (Array.isArray(arguments[0])) { + params.push({ center: arguments[0], spherical: sphere }); + } else if (typeof arguments[0] === 'string') { + // just passing a path + params.push(arguments[0]); + } else if (utils.isObject(arguments[0])) { + if (typeof arguments[0].spherical !== 'boolean') { + arguments[0].spherical = sphere; + } + params.push(arguments[0]); + } else { + throw new TypeError('invalid argument'); + } + } else if (arguments.length === 2) { + if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') { + params.push({ center: [arguments[0], arguments[1]], spherical: sphere }); + } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) { + params.push(arguments[0]); + params.push({ center: arguments[1], spherical: sphere }); + } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) { + params.push(arguments[0]); + if (typeof arguments[1].spherical !== 'boolean') { + arguments[1].spherical = sphere; + } + params.push(arguments[1]); + } else { + throw new TypeError('invalid argument'); + } + } else if (arguments.length === 3) { + if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number' + && typeof arguments[2] === 'number') { + params.push(arguments[0]); + params.push({ center: [arguments[1], arguments[2]], spherical: sphere }); + } else { + throw new TypeError('invalid argument'); + } + } else { + throw new TypeError('invalid argument'); + } + + return Query.base.near.apply(this, params); +}; + +/** + * _DEPRECATED_ Specifies a `$nearSphere` condition + * + * ####Example + * + * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); + * + * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10], spherical: true }); + * + * @deprecated + * @see near() #query_Query-near + * @see $near http://docs.mongodb.org/manual/reference/operator/near/ + * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + */ + +Query.prototype.nearSphere = function() { + this._mongooseOptions.nearSphere = true; + this.near.apply(this, arguments); + return this; +}; + +/** + * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js) + * This function *only* works for `find()` queries. + * You do not need to call this function explicitly, the JavaScript runtime + * will call it for you. + * + * ####Example + * + * for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) { + * console.log(doc.name); + * } + * + * Node.js 10.x supports async iterators natively without any flags. You can + * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). + * + * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If + * `Symbol.asyncIterator` is undefined, that means your Node.js version does not + * support async iterators. + * + * @method Symbol.asyncIterator + * @memberOf Query + * @instance + * @api public + */ + +if (Symbol.asyncIterator != null) { + Query.prototype[Symbol.asyncIterator] = function() { + return this.cursor().transformNull()._transformForAsyncIterator(); + }; +} + +/** + * Specifies a `$polygon` condition + * + * ####Example + * + * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) + * query.polygon('loc', [10,20], [13, 25], [7,15]) + * + * @method polygon + * @memberOf Query + * @instance + * @param {String|Array} [path] + * @param {Array|Object} [coordinatePairs...] + * @return {Query} this + * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/** + * Specifies a `$box` condition + * + * ####Example + * + * const lowerLeft = [40.73083, -73.99756] + * const upperRight= [40.741404, -73.988135] + * + * query.where('loc').within().box(lowerLeft, upperRight) + * query.box({ ll : lowerLeft, ur : upperRight }) + * + * @method box + * @memberOf Query + * @instance + * @see $box http://docs.mongodb.org/manual/reference/operator/box/ + * @see within() Query#within #query_Query-within + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @param {Object} val + * @param [Array] Upper Right Coords + * @return {Query} this + * @api public + */ + +/*! + * this is needed to support the mongoose syntax of: + * box(field, { ll : [x,y], ur : [x2,y2] }) + * box({ ll : [x,y], ur : [x2,y2] }) + */ + +Query.prototype.box = function(ll, ur) { + if (!Array.isArray(ll) && utils.isObject(ll)) { + ur = ll.ur; + ll = ll.ll; + } + return Query.base.box.call(this, ll, ur); +}; + +/** + * Specifies a `$center` or `$centerSphere` condition. + * + * ####Example + * + * const area = { center: [50, 50], radius: 10, unique: true } + * query.where('loc').within().circle(area) + * // alternatively + * query.circle('loc', area); + * + * // spherical calculations + * const area = { center: [50, 50], radius: 10, unique: true, spherical: true } + * query.where('loc').within().circle(area) + * // alternatively + * query.circle('loc', area); + * + * @method circle + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Object} area + * @return {Query} this + * @see $center http://docs.mongodb.org/manual/reference/operator/center/ + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/** + * _DEPRECATED_ Alias for [circle](#query_Query-circle) + * + * **Deprecated.** Use [circle](#query_Query-circle) instead. + * + * @deprecated + * @method center + * @memberOf Query + * @instance + * @api public + */ + +Query.prototype.center = Query.base.circle; + +/** + * _DEPRECATED_ Specifies a `$centerSphere` condition + * + * **Deprecated.** Use [circle](#query_Query-circle) instead. + * + * ####Example + * + * const area = { center: [50, 50], radius: 10 }; + * query.where('loc').within().centerSphere(area); + * + * @deprecated + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @api public + */ + +Query.prototype.centerSphere = function() { + if (arguments[0] != null && typeof arguments[0].constructor === 'function' && arguments[0].constructor.name === 'Object') { + arguments[0].spherical = true; + } + + if (arguments[1] != null && typeof arguments[1].constructor === 'function' && arguments[1].constructor.name === 'Object') { + arguments[1].spherical = true; + } + + Query.base.circle.apply(this, arguments); +}; + +/** + * Determines if field selection has been made. + * + * @method selected + * @memberOf Query + * @instance + * @return {Boolean} + * @api public + */ + +/** + * Determines if inclusive field selection has been made. + * + * query.selectedInclusively() // false + * query.select('name') + * query.selectedInclusively() // true + * + * @method selectedInclusively + * @memberOf Query + * @instance + * @return {Boolean} + * @api public + */ + +Query.prototype.selectedInclusively = function selectedInclusively() { + return isInclusive(this._fields); +}; + +/** + * Determines if exclusive field selection has been made. + * + * query.selectedExclusively() // false + * query.select('-name') + * query.selectedExclusively() // true + * query.selectedInclusively() // false + * + * @method selectedExclusively + * @memberOf Query + * @instance + * @return {Boolean} + * @api public + */ + +Query.prototype.selectedExclusively = function selectedExclusively() { + return isExclusive(this._fields); +}; + +/** + * The model this query is associated with. + * + * #### Example: + * + * const q = MyModel.find(); + * q.model === MyModel; // true + * + * @api public + * @property model + * @memberOf Query + * @instance + */ + +Query.prototype.model; + +/*! + * Export + */ + +module.exports = Query; diff --git a/node_modules/mongoose/lib/queryhelpers.js b/node_modules/mongoose/lib/queryhelpers.js new file mode 100644 index 0000000..7fdebdb --- /dev/null +++ b/node_modules/mongoose/lib/queryhelpers.js @@ -0,0 +1,330 @@ +'use strict'; + +/*! + * Module dependencies + */ + +const checkEmbeddedDiscriminatorKeyProjection = + require('./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection'); +const get = require('./helpers/get'); +const getDiscriminatorByValue = + require('./helpers/discriminator/getDiscriminatorByValue'); +const isDefiningProjection = require('./helpers/projection/isDefiningProjection'); +const clone = require('./helpers/clone'); + +/*! + * Prepare a set of path options for query population. + * + * @param {Query} query + * @param {Object} options + * @return {Array} + */ + +exports.preparePopulationOptions = function preparePopulationOptions(query, options) { + const _populate = query.options.populate; + const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []); + + // lean options should trickle through all queries + if (options.lean != null) { + pop. + filter(p => get(p, 'options.lean') == null). + forEach(makeLean(options.lean)); + } + + pop.forEach(opts => { + opts._localModel = query.model; + }); + + return pop; +}; + +/*! + * Prepare a set of path options for query population. This is the MongooseQuery + * version + * + * @param {Query} query + * @param {Object} options + * @return {Array} + */ + +exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) { + const _populate = query._mongooseOptions.populate; + const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []); + + // lean options should trickle through all queries + if (options.lean != null) { + pop. + filter(p => get(p, 'options.lean') == null). + forEach(makeLean(options.lean)); + } + + const session = get(query, 'options.session', null); + if (session != null) { + pop.forEach(path => { + if (path.options == null) { + path.options = { session: session }; + return; + } + if (!('session' in path.options)) { + path.options.session = session; + } + }); + } + + const projection = query._fieldsForExec(); + pop.forEach(p => { + p._queryProjection = projection; + }); + pop.forEach(opts => { + opts._localModel = query.model; + }); + + return pop; +}; + +/*! + * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise, + * it returns an instance of the given model. + * + * @param {Model} model + * @param {Object} doc + * @param {Object} fields + * + * @return {Document} + */ +exports.createModel = function createModel(model, doc, fields, userProvidedFields, options) { + model.hooks.execPreSync('createModel', doc); + const discriminatorMapping = model.schema ? + model.schema.discriminatorMapping : + null; + + const key = discriminatorMapping && discriminatorMapping.isRoot ? + discriminatorMapping.key : + null; + + const value = doc[key]; + if (key && value && model.discriminators) { + const discriminator = model.discriminators[value] || getDiscriminatorByValue(model.discriminators, value); + if (discriminator) { + const _fields = clone(userProvidedFields); + exports.applyPaths(_fields, discriminator.schema); + return new discriminator(undefined, _fields, true); + } + } + if (typeof options === 'undefined') { + options = {}; + options.defaults = true; + } + return new model(undefined, fields, { + skipId: true, + isNew: false, + willInit: true, + defaults: options.defaults + }); +}; + +/*! + * ignore + */ + +exports.applyPaths = function applyPaths(fields, schema) { + // determine if query is selecting or excluding fields + let exclude; + let keys; + let keyIndex; + + if (fields) { + keys = Object.keys(fields); + keyIndex = keys.length; + + while (keyIndex--) { + if (keys[keyIndex][0] === '+') { + continue; + } + const field = fields[keys[keyIndex]]; + // Skip `$meta` and `$slice` + if (!isDefiningProjection(field)) { + continue; + } + exclude = !field; + break; + } + } + + // if selecting, apply default schematype select:true fields + // if excluding, apply schematype select:false fields + + const selected = []; + const excluded = []; + const stack = []; + + analyzeSchema(schema); + + switch (exclude) { + case true: + for (const fieldName of excluded) { + fields[fieldName] = 0; + } + break; + case false: + if (schema && + schema.paths['_id'] && + schema.paths['_id'].options && + schema.paths['_id'].options.select === false) { + fields._id = 0; + } + + for (const fieldName of selected) { + fields[fieldName] = fields[fieldName] || 1; + } + break; + case undefined: + if (fields == null) { + break; + } + // Any leftover plus paths must in the schema, so delete them (gh-7017) + for (const key of Object.keys(fields || {})) { + if (key.startsWith('+')) { + delete fields[key]; + } + } + + // user didn't specify fields, implies returning all fields. + // only need to apply excluded fields and delete any plus paths + for (const fieldName of excluded) { + fields[fieldName] = 0; + } + break; + } + + function analyzeSchema(schema, prefix) { + prefix || (prefix = ''); + + // avoid recursion + if (stack.indexOf(schema) !== -1) { + return []; + } + stack.push(schema); + + const addedPaths = []; + schema.eachPath(function(path, type) { + if (prefix) path = prefix + '.' + path; + + let addedPath = analyzePath(path, type); + // arrays + if (addedPath == null && type.$isMongooseArray && !type.$isMongooseDocumentArray) { + addedPath = analyzePath(path, type.caster); + } + if (addedPath != null) { + addedPaths.push(addedPath); + } + + // nested schemas + if (type.schema) { + const _addedPaths = analyzeSchema(type.schema, path); + + // Special case: if discriminator key is the only field that would + // be projected in, remove it. + if (exclude === false) { + checkEmbeddedDiscriminatorKeyProjection(fields, path, type.schema, + selected, _addedPaths); + } + } + }); + + stack.pop(); + return addedPaths; + } + + function analyzePath(path, type) { + const plusPath = '+' + path; + const hasPlusPath = fields && plusPath in fields; + if (hasPlusPath) { + // forced inclusion + delete fields[plusPath]; + } + + if (typeof type.selected !== 'boolean') return; + + if (hasPlusPath) { + // forced inclusion + delete fields[plusPath]; + + // if there are other fields being included, add this one + // if no other included fields, leave this out (implied inclusion) + if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) { + fields[path] = 1; + } + + return; + } + + // check for parent exclusions + const pieces = path.split('.'); + let cur = ''; + for (let i = 0; i < pieces.length; ++i) { + cur += cur.length ? '.' + pieces[i] : pieces[i]; + if (excluded.indexOf(cur) !== -1) { + return; + } + } + + // Special case: if user has included a parent path of a discriminator key, + // don't explicitly project in the discriminator key because that will + // project out everything else under the parent path + if (!exclude && get(type, 'options.$skipDiscriminatorCheck', false)) { + let cur = ''; + for (let i = 0; i < pieces.length; ++i) { + cur += (cur.length === 0 ? '' : '.') + pieces[i]; + const projection = get(fields, cur, false) || get(fields, cur + '.$', false); + if (projection && typeof projection !== 'object') { + return; + } + } + } + + (type.selected ? selected : excluded).push(path); + return path; + } +}; + +/*! + * Set each path query option to lean + * + * @param {Object} option + */ + +function makeLean(val) { + return function(option) { + option.options || (option.options = {}); + + if (val != null && Array.isArray(val.virtuals)) { + val = Object.assign({}, val); + val.virtuals = val.virtuals. + filter(path => typeof path === 'string' && path.startsWith(option.path + '.')). + map(path => path.slice(option.path.length + 1)); + } + + option.options.lean = val; + }; +} + +/*! + * Handle the `WriteOpResult` from the server + */ + +exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult(callback) { + return function _handleDeleteWriteOpResult(error, res) { + if (error) { + return callback(error); + } + const mongooseResult = Object.assign({}, res.result); + if (get(res, 'result.n', null) != null) { + mongooseResult.deletedCount = res.result.n; + } + if (res.deletedCount != null) { + mongooseResult.deletedCount = res.deletedCount; + } + return callback(null, mongooseResult); + }; +}; diff --git a/node_modules/mongoose/lib/schema.js b/node_modules/mongoose/lib/schema.js new file mode 100644 index 0000000..d84bee7 --- /dev/null +++ b/node_modules/mongoose/lib/schema.js @@ -0,0 +1,2241 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const EventEmitter = require('events').EventEmitter; +const Kareem = require('kareem'); +const MongooseError = require('./error/mongooseError'); +const SchemaType = require('./schematype'); +const SchemaTypeOptions = require('./options/SchemaTypeOptions'); +const VirtualOptions = require('./options/VirtualOptions'); +const VirtualType = require('./virtualtype'); +const addAutoId = require('./helpers/schema/addAutoId'); +const get = require('./helpers/get'); +const getConstructorName = require('./helpers/getConstructorName'); +const getIndexes = require('./helpers/schema/getIndexes'); +const idGetter = require('./helpers/schema/idGetter'); +const merge = require('./helpers/schema/merge'); +const mpath = require('mpath'); +const readPref = require('./driver').get().ReadPreference; +const setupTimestamps = require('./helpers/timestamps/setupTimestamps'); +const utils = require('./utils'); +const validateRef = require('./helpers/populate/validateRef'); + +let MongooseTypes; + +const queryHooks = require('./helpers/query/applyQueryMiddleware'). + middlewareFunctions; +const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions; +const hookNames = queryHooks.concat(documentHooks). + reduce((s, hook) => s.add(hook), new Set()); + +let id = 0; + +/** + * Schema constructor. + * + * ####Example: + * + * const child = new Schema({ name: String }); + * const schema = new Schema({ name: String, age: Number, children: [child] }); + * const Tree = mongoose.model('Tree', schema); + * + * // setting schema options + * new Schema({ name: String }, { _id: false, autoIndex: false }) + * + * ####Options: + * + * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option) + * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option) + * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true + * - [bufferTimeoutMS](/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out. + * - [capped](/docs/guide.html#capped): bool - defaults to false + * - [collection](/docs/guide.html#collection): string - no default + * - [discriminatorKey](/docs/guide.html#discriminatorKey): string - defaults to `__t` + * - [id](/docs/guide.html#id): bool - defaults to true + * - [_id](/docs/guide.html#_id): bool - defaults to true + * - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true + * - [read](/docs/guide.html#read): string + * - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/) + * - [shardKey](/docs/guide.html#shardKey): object - defaults to `null` + * - [strict](/docs/guide.html#strict): bool - defaults to true + * - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false + * - [toJSON](/docs/guide.html#toJSON) - object - no default + * - [toObject](/docs/guide.html#toObject) - object - no default + * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type' + * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true` + * - [versionKey](/docs/guide.html#versionKey): string or object - defaults to "__v" + * - [optimisticConcurrency](/docs/guide.html#optimisticConcurrency): bool - defaults to false. Set to true to enable [optimistic concurrency](https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html). + * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation) + * - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true` + * - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning + * - [timestamps](/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you. + * + * ####Options for Nested Schemas: + * - `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths. + * + * ####Note: + * + * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._ + * + * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas + * @param {Object} [options] + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted after the schema is compiled into a `Model`. + * @api public + */ + +function Schema(obj, options) { + if (!(this instanceof Schema)) { + return new Schema(obj, options); + } + + this.obj = obj; + this.paths = {}; + this.aliases = {}; + this.subpaths = {}; + this.virtuals = {}; + this.singleNestedPaths = {}; + this.nested = {}; + this.inherits = {}; + this.callQueue = []; + this._indexes = []; + this.methods = {}; + this.methodOptions = {}; + this.statics = {}; + this.tree = {}; + this.query = {}; + this.childSchemas = []; + this.plugins = []; + // For internal debugging. Do not use this to try to save a schema in MDB. + this.$id = ++id; + this.mapPaths = []; + + this.s = { + hooks: new Kareem() + }; + + this.options = this.defaultOptions(options); + + // build paths + if (Array.isArray(obj)) { + for (const definition of obj) { + this.add(definition); + } + } else if (obj) { + this.add(obj); + } + + // check if _id's value is a subdocument (gh-2276) + const _idSubDoc = obj && obj._id && utils.isObject(obj._id); + + // ensure the documents get an auto _id unless disabled + const auto_id = !this.paths['_id'] && + (this.options._id) && !_idSubDoc; + + if (auto_id) { + addAutoId(this); + } + + this.setupTimestamp(this.options.timestamps); +} + +/*! + * Create virtual properties with alias field + */ +function aliasFields(schema, paths) { + paths = paths || Object.keys(schema.paths); + for (const path of paths) { + const options = get(schema.paths[path], 'options'); + if (options == null) { + continue; + } + + const prop = schema.paths[path].path; + const alias = options.alias; + + if (!alias) { + continue; + } + + if (typeof alias !== 'string') { + throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias); + } + + schema.aliases[alias] = prop; + + schema. + virtual(alias). + get((function(p) { + return function() { + if (typeof this.get === 'function') { + return this.get(p); + } + return this[p]; + }; + })(prop)). + set((function(p) { + return function(v) { + return this.$set(p, v); + }; + })(prop)); + } +} + +/*! + * Inherit from EventEmitter. + */ +Schema.prototype = Object.create(EventEmitter.prototype); +Schema.prototype.constructor = Schema; +Schema.prototype.instanceOfSchema = true; + +/*! + * ignore + */ + +Object.defineProperty(Schema.prototype, '$schemaType', { + configurable: false, + enumerable: false, + writable: true +}); + +/** + * Array of child schemas (from document arrays and single nested subdocs) + * and their corresponding compiled models. Each element of the array is + * an object with 2 properties: `schema` and `model`. + * + * This property is typically only useful for plugin authors and advanced users. + * You do not need to interact with this property at all to use mongoose. + * + * @api public + * @property childSchemas + * @memberOf Schema + * @instance + */ + +Object.defineProperty(Schema.prototype, 'childSchemas', { + configurable: false, + enumerable: true, + writable: true +}); + +/** + * Object containing all virtuals defined on this schema. + * The objects' keys are the virtual paths and values are instances of `VirtualType`. + * + * This property is typically only useful for plugin authors and advanced users. + * You do not need to interact with this property at all to use mongoose. + * + * ####Example: + * const schema = new Schema({}); + * schema.virtual('answer').get(() => 42); + * + * console.log(schema.virtuals); // { answer: VirtualType { path: 'answer', ... } } + * console.log(schema.virtuals['answer'].getters[0].call()); // 42 + * + * @api public + * @property virtuals + * @memberOf Schema + * @instance + */ + +Object.defineProperty(Schema.prototype, 'virtuals', { + configurable: false, + enumerable: true, + writable: true +}); + +/** + * The original object passed to the schema constructor + * + * ####Example: + * + * const schema = new Schema({ a: String }).add({ b: String }); + * schema.obj; // { a: String } + * + * @api public + * @property obj + * @memberOf Schema + * @instance + */ + +Schema.prototype.obj; + +/** + * The paths defined on this schema. The keys are the top-level paths + * in this schema, and the values are instances of the SchemaType class. + * + * ####Example: + * const schema = new Schema({ name: String }, { _id: false }); + * schema.paths; // { name: SchemaString { ... } } + * + * schema.add({ age: Number }); + * schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } } + * + * @api public + * @property paths + * @memberOf Schema + * @instance + */ + +Schema.prototype.paths; + +/** + * Schema as a tree + * + * ####Example: + * { + * '_id' : ObjectId + * , 'nested' : { + * 'key' : String + * } + * } + * + * @api private + * @property tree + * @memberOf Schema + * @instance + */ + +Schema.prototype.tree; + +/** + * Returns a deep copy of the schema + * + * ####Example: + * + * const schema = new Schema({ name: String }); + * const clone = schema.clone(); + * clone === schema; // false + * clone.path('name'); // SchemaString { ... } + * + * @return {Schema} the cloned schema + * @api public + * @memberOf Schema + * @instance + */ + +Schema.prototype.clone = function() { + const Constructor = this.base == null ? Schema : this.base.Schema; + + const s = new Constructor({}, this._userProvidedOptions); + s.base = this.base; + s.obj = this.obj; + s.options = utils.clone(this.options); + s.callQueue = this.callQueue.map(function(f) { return f; }); + s.methods = utils.clone(this.methods); + s.methodOptions = utils.clone(this.methodOptions); + s.statics = utils.clone(this.statics); + s.query = utils.clone(this.query); + s.plugins = Array.prototype.slice.call(this.plugins); + s._indexes = utils.clone(this._indexes); + s.s.hooks = this.s.hooks.clone(); + + s.tree = utils.clone(this.tree); + s.paths = utils.clone(this.paths); + s.nested = utils.clone(this.nested); + s.subpaths = utils.clone(this.subpaths); + s.singleNestedPaths = utils.clone(this.singleNestedPaths); + s.childSchemas = gatherChildSchemas(s); + + s.virtuals = utils.clone(this.virtuals); + s.$globalPluginsApplied = this.$globalPluginsApplied; + s.$isRootDiscriminator = this.$isRootDiscriminator; + s.$implicitlyCreated = this.$implicitlyCreated; + s.$id = ++id; + s.$originalSchemaId = this.$id; + s.mapPaths = [].concat(this.mapPaths); + + if (this.discriminatorMapping != null) { + s.discriminatorMapping = Object.assign({}, this.discriminatorMapping); + } + if (this.discriminators != null) { + s.discriminators = Object.assign({}, this.discriminators); + } + + s.aliases = Object.assign({}, this.aliases); + + // Bubble up `init` for backwards compat + s.on('init', v => this.emit('init', v)); + + return s; +}; + +/** + * Returns a new schema that has the picked `paths` from this schema. + * + * This method is analagous to [Lodash's `pick()` function](https://lodash.com/docs/4.17.15#pick) for Mongoose schemas. + * + * ####Example: + * + * const schema = Schema({ name: String, age: Number }); + * // Creates a new schema with the same `name` path as `schema`, + * // but no `age` path. + * const newSchema = schema.pick(['name']); + * + * newSchema.path('name'); // SchemaString { ... } + * newSchema.path('age'); // undefined + * + * @param {Array} paths list of paths to pick + * @param {Object} [options] options to pass to the schema constructor. Defaults to `this.options` if not set. + * @return {Schema} + * @api public + */ + +Schema.prototype.pick = function(paths, options) { + const newSchema = new Schema({}, options || this.options); + if (!Array.isArray(paths)) { + throw new MongooseError('Schema#pick() only accepts an array argument, ' + + 'got "' + typeof paths + '"'); + } + + for (const path of paths) { + if (this.nested[path]) { + newSchema.add({ [path]: get(this.tree, path) }); + } else { + const schematype = this.path(path); + if (schematype == null) { + throw new MongooseError('Path `' + path + '` is not in the schema'); + } + newSchema.add({ [path]: schematype }); + } + } + + return newSchema; +}; + +/** + * Returns default options for this schema, merged with `options`. + * + * @param {Object} options + * @return {Object} + * @api private + */ + +Schema.prototype.defaultOptions = function(options) { + this._userProvidedOptions = options == null ? {} : utils.clone(options); + + const baseOptions = get(this, 'base.options', {}); + + const strict = 'strict' in baseOptions ? baseOptions.strict : true; + + options = utils.options({ + strict: strict, + strictQuery: 'strict' in this._userProvidedOptions ? + this._userProvidedOptions.strict : + 'strictQuery' in baseOptions ? + baseOptions.strictQuery : strict, + bufferCommands: true, + capped: false, // { size, max, autoIndexId } + versionKey: '__v', + optimisticConcurrency: false, + minimize: true, + autoIndex: null, + discriminatorKey: '__t', + shardKey: null, + read: null, + validateBeforeSave: true, + // the following are only applied at construction time + _id: true, + id: true, + typeKey: 'type' + }, utils.clone(options)); + + if (options.read) { + options.read = readPref(options.read); + } + + if (options.versionKey && typeof options.versionKey !== 'string') { + throw new MongooseError('`versionKey` must be falsy or string, got `' + (typeof options.versionKey) + '`'); + } + + if (options.optimisticConcurrency && !options.versionKey) { + throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`'); + } + + return options; +}; + +/** + * Adds key path / schema type pairs to this schema. + * + * ####Example: + * + * const ToySchema = new Schema(); + * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); + * + * const TurboManSchema = new Schema(); + * // You can also `add()` another schema and copy over all paths, virtuals, + * // getters, setters, indexes, methods, and statics. + * TurboManSchema.add(ToySchema).add({ year: Number }); + * + * @param {Object|Schema} obj plain object with paths to add, or another schema + * @param {String} [prefix] path to prefix the newly added paths with + * @return {Schema} the Schema instance + * @api public + */ + +Schema.prototype.add = function add(obj, prefix) { + if (obj instanceof Schema || (obj != null && obj.instanceOfSchema)) { + merge(this, obj); + + return this; + } + + // Special case: setting top-level `_id` to false should convert to disabling + // the `_id` option. This behavior never worked before 5.4.11 but numerous + // codebases use it (see gh-7516, gh-7512). + if (obj._id === false && prefix == null) { + this.options._id = false; + } + + prefix = prefix || ''; + // avoid prototype pollution + if (prefix === '__proto__.' || prefix === 'constructor.' || prefix === 'prototype.') { + return this; + } + + const keys = Object.keys(obj); + + for (const key of keys) { + const fullPath = prefix + key; + + if (obj[key] == null) { + throw new TypeError('Invalid value for schema path `' + fullPath + + '`, got value "' + obj[key] + '"'); + } + // Retain `_id: false` but don't set it as a path, re: gh-8274. + if (key === '_id' && obj[key] === false) { + continue; + } + if (obj[key] instanceof VirtualType || get(obj[key], 'constructor.name', null) === 'VirtualType') { + this.virtual(obj[key]); + continue; + } + + if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) { + throw new TypeError('Invalid value for schema Array path `' + fullPath + + '`, got value "' + obj[key][0] + '"'); + } + + if (!(utils.isPOJO(obj[key]) || obj[key] instanceof SchemaTypeOptions)) { + // Special-case: Non-options definitely a path so leaf at this node + // Examples: Schema instances, SchemaType instances + if (prefix) { + this.nested[prefix.substr(0, prefix.length - 1)] = true; + } + this.path(prefix + key, obj[key]); + } else if (Object.keys(obj[key]).length < 1) { + // Special-case: {} always interpreted as Mixed path so leaf at this node + if (prefix) { + this.nested[prefix.substr(0, prefix.length - 1)] = true; + } + this.path(fullPath, obj[key]); // mixed type + } else if (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type)) { + // Special-case: POJO with no bona-fide type key - interpret as tree of deep paths so recurse + // nested object { last: { name: String }} + this.nested[fullPath] = true; + this.add(obj[key], fullPath + '.'); + } else { + // There IS a bona-fide type key that may also be a POJO + const _typeDef = obj[key][this.options.typeKey]; + if (utils.isPOJO(_typeDef) && Object.keys(_typeDef).length > 0) { + // If a POJO is the value of a type key, make it a subdocument + if (prefix) { + this.nested[prefix.substr(0, prefix.length - 1)] = true; + } + const _schema = new Schema(_typeDef); + const schemaWrappedPath = Object.assign({}, obj[key], { type: _schema }); + this.path(prefix + key, schemaWrappedPath); + } else { + // Either the type is non-POJO or we interpret it as Mixed anyway + if (prefix) { + this.nested[prefix.substr(0, prefix.length - 1)] = true; + } + this.path(prefix + key, obj[key]); + } + } + } + + const addedKeys = Object.keys(obj). + map(key => prefix ? prefix + key : key); + aliasFields(this, addedKeys); + return this; +}; + +/** + * Reserved document keys. + * + * Keys in this object are names that are warned in schema declarations + * because they have the potential to break Mongoose/ Mongoose plugins functionality. If you create a schema + * using `new Schema()` with one of these property names, Mongoose will log a warning. + * + * - _posts + * - _pres + * - collection + * - emit + * - errors + * - get + * - init + * - isModified + * - isNew + * - listeners + * - modelName + * - on + * - once + * - populated + * - prototype + * - remove + * - removeListener + * - save + * - schema + * - toObject + * - validate + * + * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. + * + * const schema = new Schema(..); + * schema.methods.init = function () {} // potentially breaking + */ + +Schema.reserved = Object.create(null); +Schema.prototype.reserved = Schema.reserved; + +const reserved = Schema.reserved; +// Core object +reserved['prototype'] = +// EventEmitter +reserved.emit = +reserved.listeners = +reserved.on = +reserved.removeListener = + +// document properties and functions +reserved.collection = +reserved.errors = +reserved.get = +reserved.init = +reserved.isModified = +reserved.isNew = +reserved.populated = +reserved.remove = +reserved.save = +reserved.toObject = +reserved.validate = 1; +reserved.collection = 1; + +/** + * Gets/sets schema paths. + * + * Sets a path (if arity 2) + * Gets a path (if arity 1) + * + * ####Example + * + * schema.path('name') // returns a SchemaType + * schema.path('name', Number) // changes the schemaType of `name` to Number + * + * @param {String} path + * @param {Object} constructor + * @api public + */ + +Schema.prototype.path = function(path, obj) { + // Convert to '.$' to check subpaths re: gh-6405 + const cleanPath = _pathToPositionalSyntax(path); + if (obj === undefined) { + let schematype = _getPath(this, path, cleanPath); + if (schematype != null) { + return schematype; + } + + // Look for maps + const mapPath = getMapPath(this, path); + if (mapPath != null) { + return mapPath; + } + + // Look if a parent of this path is mixed + schematype = this.hasMixedParent(cleanPath); + if (schematype != null) { + return schematype; + } + + // subpaths? + return /\.\d+\.?.*$/.test(path) + ? getPositionalPath(this, path) + : undefined; + } + + // some path names conflict with document methods + const firstPieceOfPath = path.split('.')[0]; + if (reserved[firstPieceOfPath] && !this.options.supressReservedKeysWarning) { + const errorMessage = `\`${firstPieceOfPath}\` is a reserved schema pathname and may break some functionality. ` + + 'You are allowed to use it, but use at your own risk. ' + + 'To disable this warning pass `supressReservedKeysWarning` as a schema option.'; + + utils.warn(errorMessage); + } + + if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) { + validateRef(obj.ref, path); + } + + // update the tree + const subpaths = path.split(/\./); + const last = subpaths.pop(); + let branch = this.tree; + let fullPath = ''; + + for (const sub of subpaths) { + fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub; + if (!branch[sub]) { + this.nested[fullPath] = true; + branch[sub] = {}; + } + if (typeof branch[sub] !== 'object') { + const msg = 'Cannot set nested path `' + path + '`. ' + + 'Parent path `' + + fullPath + + '` already set to type ' + branch[sub].name + + '.'; + throw new Error(msg); + } + branch = branch[sub]; + } + + branch[last] = utils.clone(obj); + + this.paths[path] = this.interpretAsType(path, obj, this.options); + const schemaType = this.paths[path]; + + if (schemaType.$isSchemaMap) { + // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key" + // The '$' is to imply this path should never be stored in MongoDB so we + // can easily build a regexp out of this path, and '*' to imply "any key." + const mapPath = path + '.$*'; + + this.paths[mapPath] = schemaType.$__schemaType; + this.mapPaths.push(this.paths[mapPath]); + } + + if (schemaType.$isSingleNested) { + for (const key of Object.keys(schemaType.schema.paths)) { + this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key]; + } + for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { + this.singleNestedPaths[path + '.' + key] = + schemaType.schema.singleNestedPaths[key]; + } + for (const key of Object.keys(schemaType.schema.subpaths)) { + this.singleNestedPaths[path + '.' + key] = + schemaType.schema.subpaths[key]; + } + for (const key of Object.keys(schemaType.schema.nested)) { + this.singleNestedPaths[path + '.' + key] = 'nested'; + } + + Object.defineProperty(schemaType.schema, 'base', { + configurable: true, + enumerable: false, + writable: false, + value: this.base + }); + + schemaType.caster.base = this.base; + this.childSchemas.push({ + schema: schemaType.schema, + model: schemaType.caster + }); + } else if (schemaType.$isMongooseDocumentArray) { + Object.defineProperty(schemaType.schema, 'base', { + configurable: true, + enumerable: false, + writable: false, + value: this.base + }); + + schemaType.casterConstructor.base = this.base; + this.childSchemas.push({ + schema: schemaType.schema, + model: schemaType.casterConstructor + }); + } + + if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) { + let arrayPath = path; + let _schemaType = schemaType; + + const toAdd = []; + while (_schemaType.$isMongooseArray) { + arrayPath = arrayPath + '.$'; + + // Skip arrays of document arrays + if (_schemaType.$isMongooseDocumentArray) { + _schemaType.$embeddedSchemaType._arrayPath = arrayPath; + _schemaType.$embeddedSchemaType._arrayParentPath = path; + _schemaType = _schemaType.$embeddedSchemaType.clone(); + } else { + _schemaType.caster._arrayPath = arrayPath; + _schemaType.caster._arrayParentPath = path; + _schemaType = _schemaType.caster.clone(); + } + + _schemaType.path = arrayPath; + toAdd.push(_schemaType); + } + + for (const _schemaType of toAdd) { + this.subpaths[_schemaType.path] = _schemaType; + } + } + + if (schemaType.$isMongooseDocumentArray) { + for (const key of Object.keys(schemaType.schema.paths)) { + const _schemaType = schemaType.schema.paths[key]; + this.subpaths[path + '.' + key] = _schemaType; + if (typeof _schemaType === 'object' && _schemaType != null) { + _schemaType.$isUnderneathDocArray = true; + } + } + for (const key of Object.keys(schemaType.schema.subpaths)) { + const _schemaType = schemaType.schema.subpaths[key]; + this.subpaths[path + '.' + key] = _schemaType; + if (typeof _schemaType === 'object' && _schemaType != null) { + _schemaType.$isUnderneathDocArray = true; + } + } + for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { + const _schemaType = schemaType.schema.singleNestedPaths[key]; + this.subpaths[path + '.' + key] = _schemaType; + if (typeof _schemaType === 'object' && _schemaType != null) { + _schemaType.$isUnderneathDocArray = true; + } + } + } + + return this; +}; + +/*! + * ignore + */ + +function gatherChildSchemas(schema) { + const childSchemas = []; + + for (const path of Object.keys(schema.paths)) { + const schematype = schema.paths[path]; + if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) { + childSchemas.push({ schema: schematype.schema, model: schematype.caster }); + } + } + + return childSchemas; +} + +/*! + * ignore + */ + +function _getPath(schema, path, cleanPath) { + if (schema.paths.hasOwnProperty(path)) { + return schema.paths[path]; + } + if (schema.subpaths.hasOwnProperty(cleanPath)) { + return schema.subpaths[cleanPath]; + } + if (schema.singleNestedPaths.hasOwnProperty(cleanPath) && typeof schema.singleNestedPaths[cleanPath] === 'object') { + return schema.singleNestedPaths[cleanPath]; + } + + return null; +} + +/*! + * ignore + */ + +function _pathToPositionalSyntax(path) { + if (!/\.\d+/.test(path)) { + return path; + } + return path.replace(/\.\d+\./g, '.$.').replace(/\.\d+$/, '.$'); +} + +/*! + * ignore + */ + +function getMapPath(schema, path) { + if (schema.mapPaths.length === 0) { + return null; + } + for (const val of schema.mapPaths) { + const _path = val.path; + const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$'); + if (re.test(path)) { + return schema.paths[_path]; + } + } + + return null; +} + +/** + * The Mongoose instance this schema is associated with + * + * @property base + * @api private + */ + +Object.defineProperty(Schema.prototype, 'base', { + configurable: true, + enumerable: false, + writable: true, + value: null +}); + +/** + * Converts type arguments into Mongoose Types. + * + * @param {String} path + * @param {Object} obj constructor + * @api private + */ + +Schema.prototype.interpretAsType = function(path, obj, options) { + if (obj instanceof SchemaType) { + if (obj.path === path) { + return obj; + } + const clone = obj.clone(); + clone.path = path; + return clone; + } + + // If this schema has an associated Mongoose object, use the Mongoose object's + // copy of SchemaTypes re: gh-7158 gh-6933 + const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types; + + if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) { + const constructorName = utils.getFunctionName(obj.constructor); + if (constructorName !== 'Object') { + const oldObj = obj; + obj = {}; + obj[options.typeKey] = oldObj; + } + } + + // Get the type making sure to allow keys named "type" + // and default to mixed if not specified. + // { type: { type: String, default: 'freshcut' } } + let type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type) + ? obj[options.typeKey] + : {}; + let name; + + if (utils.isPOJO(type) || type === 'mixed') { + return new MongooseTypes.Mixed(path, obj); + } + + if (Array.isArray(type) || type === Array || type === 'array' || type === MongooseTypes.Array) { + // if it was specified through { type } look for `cast` + let cast = (type === Array || type === 'array') + ? obj.cast || obj.of + : type[0]; + + // new Schema({ path: [new Schema({ ... })] }) + if (cast && cast.instanceOfSchema) { + if (!(cast instanceof Schema)) { + throw new TypeError('Schema for array path `' + path + + '` is from a different copy of the Mongoose module. Please make sure you\'re using the same version ' + + 'of Mongoose everywhere with `npm list mongoose`.'); + } + return new MongooseTypes.DocumentArray(path, cast, obj); + } + if (cast && + cast[options.typeKey] && + cast[options.typeKey].instanceOfSchema) { + if (!(cast[options.typeKey] instanceof Schema)) { + throw new TypeError('Schema for array path `' + path + + '` is from a different copy of the Mongoose module. Please make sure you\'re using the same version ' + + 'of Mongoose everywhere with `npm list mongoose`.'); + } + return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast); + } + + if (Array.isArray(cast)) { + return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj); + } + + // Handle both `new Schema({ arr: [{ subpath: String }] })` and `new Schema({ arr: [{ type: { subpath: string } }] })` + const castFromTypeKey = (cast != null && cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)) ? + cast[options.typeKey] : + cast; + if (typeof cast === 'string') { + cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)]; + } else if (utils.isPOJO(castFromTypeKey)) { + if (Object.keys(castFromTypeKey).length) { + // The `minimize` and `typeKey` options propagate to child schemas + // declared inline, like `{ arr: [{ val: { $type: String } }] }`. + // See gh-3560 + const childSchemaOptions = { minimize: options.minimize }; + if (options.typeKey) { + childSchemaOptions.typeKey = options.typeKey; + } + // propagate 'strict' option to child schema + if (options.hasOwnProperty('strict')) { + childSchemaOptions.strict = options.strict; + } + if (this._userProvidedOptions.hasOwnProperty('_id')) { + childSchemaOptions._id = this._userProvidedOptions._id; + } else if (Schema.Types.DocumentArray.defaultOptions._id != null) { + childSchemaOptions._id = Schema.Types.DocumentArray.defaultOptions._id; + } + const childSchema = new Schema(castFromTypeKey, childSchemaOptions); + childSchema.$implicitlyCreated = true; + return new MongooseTypes.DocumentArray(path, childSchema, obj); + } else { + // Special case: empty object becomes mixed + return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj); + } + } + + if (cast) { + type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type) + ? cast[options.typeKey] + : cast; + + name = typeof type === 'string' + ? type + : type.schemaName || utils.getFunctionName(type); + + // For Jest 26+, see #10296 + if (name === 'ClockDate') { + name = 'Date'; + } + + if (name === void 0) { + throw new TypeError('Invalid schema configuration: ' + + `Could not determine the embedded type for array \`${path}\`. ` + + 'See https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.'); + } + if (!MongooseTypes.hasOwnProperty(name)) { + throw new TypeError('Invalid schema configuration: ' + + `\`${name}\` is not a valid type within the array \`${path}\`.` + + 'See http://bit.ly/mongoose-schematypes for a list of valid schema types.'); + } + } + + return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options); + } + + if (type && type.instanceOfSchema) { + return new MongooseTypes.Subdocument(type, path, obj); + } + + if (Buffer.isBuffer(type)) { + name = 'Buffer'; + } else if (typeof type === 'function' || typeof type === 'object') { + name = type.schemaName || utils.getFunctionName(type); + } else { + name = type == null ? '' + type : type.toString(); + } + + if (name) { + name = name.charAt(0).toUpperCase() + name.substring(1); + } + // Special case re: gh-7049 because the bson `ObjectID` class' capitalization + // doesn't line up with Mongoose's. + if (name === 'ObjectID') { + name = 'ObjectId'; + } + // For Jest 26+, see #10296 + if (name === 'ClockDate') { + name = 'Date'; + } + + if (name === void 0) { + throw new TypeError(`Invalid schema configuration: \`${path}\` schematype definition is ` + + 'invalid. See ' + + 'https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.'); + } + if (MongooseTypes[name] == null) { + throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` + + `a valid type at path \`${path}\`. See ` + + 'http://bit.ly/mongoose-schematypes for a list of valid schema types.'); + } + + const schemaType = new MongooseTypes[name](path, obj); + + if (schemaType.$isSchemaMap) { + createMapNestedSchemaType(this, schemaType, path, obj, options); + } + + return schemaType; +}; + +/*! + * ignore + */ + +function createMapNestedSchemaType(schema, schemaType, path, obj, options) { + const mapPath = path + '.$*'; + let _mapType = { type: {} }; + if (utils.hasUserDefinedProperty(obj, 'of')) { + const isInlineSchema = utils.isPOJO(obj.of) && + Object.keys(obj.of).length > 0 && + !utils.hasUserDefinedProperty(obj.of, schema.options.typeKey); + if (isInlineSchema) { + _mapType = { [schema.options.typeKey]: new Schema(obj.of) }; + } else if (utils.isPOJO(obj.of)) { + _mapType = Object.assign({}, obj.of); + } else { + _mapType = { [schema.options.typeKey]: obj.of }; + } + + if (utils.hasUserDefinedProperty(obj, 'ref')) { + _mapType.ref = obj.ref; + } + } + schemaType.$__schemaType = schema.interpretAsType(mapPath, _mapType, options); +} + +/** + * Iterates the schemas paths similar to Array#forEach. + * + * The callback is passed the pathname and the schemaType instance. + * + * ####Example: + * + * const userSchema = new Schema({ name: String, registeredAt: Date }); + * userSchema.eachPath((pathname, schematype) => { + * // Prints twice: + * // name SchemaString { ... } + * // registeredAt SchemaDate { ... } + * console.log(pathname, schematype); + * }); + * + * @param {Function} fn callback function + * @return {Schema} this + * @api public + */ + +Schema.prototype.eachPath = function(fn) { + const keys = Object.keys(this.paths); + const len = keys.length; + + for (let i = 0; i < len; ++i) { + fn(keys[i], this.paths[keys[i]]); + } + + return this; +}; + +/** + * Returns an Array of path strings that are required by this schema. + * + * ####Example: + * const s = new Schema({ + * name: { type: String, required: true }, + * age: { type: String, required: true }, + * notes: String + * }); + * s.requiredPaths(); // [ 'age', 'name' ] + * + * @api public + * @param {Boolean} invalidate refresh the cache + * @return {Array} + */ + +Schema.prototype.requiredPaths = function requiredPaths(invalidate) { + if (this._requiredpaths && !invalidate) { + return this._requiredpaths; + } + + const paths = Object.keys(this.paths); + let i = paths.length; + const ret = []; + + while (i--) { + const path = paths[i]; + if (this.paths[path].isRequired) { + ret.push(path); + } + } + this._requiredpaths = ret; + return this._requiredpaths; +}; + +/** + * Returns indexes from fields and schema-level indexes (cached). + * + * @api private + * @return {Array} + */ + +Schema.prototype.indexedPaths = function indexedPaths() { + if (this._indexedpaths) { + return this._indexedpaths; + } + this._indexedpaths = this.indexes(); + return this._indexedpaths; +}; + +/** + * Returns the pathType of `path` for this schema. + * + * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path. + * + * ####Example: + * const s = new Schema({ name: String, nested: { foo: String } }); + * s.virtual('foo').get(() => 42); + * s.pathType('name'); // "real" + * s.pathType('nested'); // "nested" + * s.pathType('foo'); // "virtual" + * s.pathType('fail'); // "adhocOrUndefined" + * + * @param {String} path + * @return {String} + * @api public + */ + +Schema.prototype.pathType = function(path) { + // Convert to '.$' to check subpaths re: gh-6405 + const cleanPath = _pathToPositionalSyntax(path); + + if (this.paths.hasOwnProperty(path)) { + return 'real'; + } + if (this.virtuals.hasOwnProperty(path)) { + return 'virtual'; + } + if (this.nested.hasOwnProperty(path)) { + return 'nested'; + } + if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) { + return 'real'; + } + + const singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path); + if (singleNestedPath) { + return singleNestedPath === 'nested' ? 'nested' : 'real'; + } + + // Look for maps + const mapPath = getMapPath(this, path); + if (mapPath != null) { + return 'real'; + } + + if (/\.\d+\.|\.\d+$/.test(path)) { + return getPositionalPathType(this, path); + } + return 'adhocOrUndefined'; +}; + +/** + * Returns true iff this path is a child of a mixed schema. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Schema.prototype.hasMixedParent = function(path) { + const subpaths = path.split(/\./g); + path = ''; + for (let i = 0; i < subpaths.length; ++i) { + path = i > 0 ? path + '.' + subpaths[i] : subpaths[i]; + if (this.paths.hasOwnProperty(path) && + this.paths[path] instanceof MongooseTypes.Mixed) { + return this.paths[path]; + } + } + + return null; +}; + +/** + * Setup updatedAt and createdAt timestamps to documents if enabled + * + * @param {Boolean|Object} timestamps timestamps options + * @api private + */ +Schema.prototype.setupTimestamp = function(timestamps) { + return setupTimestamps(this, timestamps); +}; + +/*! + * ignore. Deprecated re: #6405 + */ + +function getPositionalPathType(self, path) { + const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); + if (subpaths.length < 2) { + return self.paths.hasOwnProperty(subpaths[0]) ? + self.paths[subpaths[0]] : + 'adhocOrUndefined'; + } + + let val = self.path(subpaths[0]); + let isNested = false; + if (!val) { + return 'adhocOrUndefined'; + } + + const last = subpaths.length - 1; + + for (let i = 1; i < subpaths.length; ++i) { + isNested = false; + const subpath = subpaths[i]; + + if (i === last && val && !/\D/.test(subpath)) { + if (val.$isMongooseDocumentArray) { + val = val.$embeddedSchemaType; + } else if (val instanceof MongooseTypes.Array) { + // StringSchema, NumberSchema, etc + val = val.caster; + } else { + val = undefined; + } + break; + } + + // ignore if its just a position segment: path.0.subpath + if (!/\D/.test(subpath)) { + // Nested array + if (val instanceof MongooseTypes.Array && i !== last) { + val = val.caster; + } + continue; + } + + if (!(val && val.schema)) { + val = undefined; + break; + } + + const type = val.schema.pathType(subpath); + isNested = (type === 'nested'); + val = val.schema.path(subpath); + } + + self.subpaths[path] = val; + if (val) { + return 'real'; + } + if (isNested) { + return 'nested'; + } + return 'adhocOrUndefined'; +} + + +/*! + * ignore + */ + +function getPositionalPath(self, path) { + getPositionalPathType(self, path); + return self.subpaths[path]; +} + +/** + * Adds a method call to the queue. + * + * ####Example: + * + * schema.methods.print = function() { console.log(this); }; + * schema.queue('print', []); // Print the doc every one is instantiated + * + * const Model = mongoose.model('Test', schema); + * new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }' + * + * @param {String} name name of the document method to call later + * @param {Array} args arguments to pass to the method + * @api public + */ + +Schema.prototype.queue = function(name, args) { + this.callQueue.push([name, args]); + return this; +}; + +/** + * Defines a pre hook for the model. + * + * ####Example + * + * const toySchema = new Schema({ name: String, created: Date }); + * + * toySchema.pre('save', function(next) { + * if (!this.created) this.created = new Date; + * next(); + * }); + * + * toySchema.pre('validate', function(next) { + * if (this.name !== 'Woody') this.name = 'Woody'; + * next(); + * }); + * + * // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`. + * toySchema.pre(/^find/, function(next) { + * console.log(this.getFilter()); + * }); + * + * // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`. + * toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) { + * console.log(this.getFilter()); + * }); + * + * toySchema.pre('deleteOne', function() { + * // Runs when you call `Toy.deleteOne()` + * }); + * + * toySchema.pre('deleteOne', { document: true }, function() { + * // Runs when you call `doc.deleteOne()` + * }); + * + * @param {String|RegExp} The method name or regular expression to match method name + * @param {Object} [options] + * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. For example, set `options.document` to `true` to apply this hook to `Document#deleteOne()` rather than `Query#deleteOne()`. + * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. + * @param {Function} callback + * @api public + */ + +Schema.prototype.pre = function(name) { + if (name instanceof RegExp) { + const remainingArgs = Array.prototype.slice.call(arguments, 1); + for (const fn of hookNames) { + if (name.test(fn)) { + this.pre.apply(this, [fn].concat(remainingArgs)); + } + } + return this; + } + if (Array.isArray(name)) { + const remainingArgs = Array.prototype.slice.call(arguments, 1); + for (const el of name) { + this.pre.apply(this, [el].concat(remainingArgs)); + } + return this; + } + this.s.hooks.pre.apply(this.s.hooks, arguments); + return this; +}; + +/** + * Defines a post hook for the document + * + * const schema = new Schema(..); + * schema.post('save', function (doc) { + * console.log('this fired after a document was saved'); + * }); + * + * schema.post('find', function(docs) { + * console.log('this fired after you ran a find query'); + * }); + * + * schema.post(/Many$/, function(res) { + * console.log('this fired after you ran `updateMany()` or `deleteMany()`); + * }); + * + * const Model = mongoose.model('Model', schema); + * + * const m = new Model(..); + * m.save(function(err) { + * console.log('this fires after the `post` hook'); + * }); + * + * m.find(function(err, docs) { + * console.log('this fires after the post find hook'); + * }); + * + * @param {String|RegExp} The method name or regular expression to match method name + * @param {Object} [options] + * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. + * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. + * @param {Function} fn callback + * @see middleware http://mongoosejs.com/docs/middleware.html + * @see kareem http://npmjs.org/package/kareem + * @api public + */ + +Schema.prototype.post = function(name) { + if (name instanceof RegExp) { + const remainingArgs = Array.prototype.slice.call(arguments, 1); + for (const fn of hookNames) { + if (name.test(fn)) { + this.post.apply(this, [fn].concat(remainingArgs)); + } + } + return this; + } + if (Array.isArray(name)) { + const remainingArgs = Array.prototype.slice.call(arguments, 1); + for (const el of name) { + this.post.apply(this, [el].concat(remainingArgs)); + } + return this; + } + this.s.hooks.post.apply(this.s.hooks, arguments); + return this; +}; + +/** + * Registers a plugin for this schema. + * + * ####Example: + * + * const s = new Schema({ name: String }); + * s.plugin(schema => console.log(schema.path('name').path)); + * mongoose.model('Test', s); // Prints 'name' + * + * @param {Function} plugin callback + * @param {Object} [opts] + * @see plugins + * @api public + */ + +Schema.prototype.plugin = function(fn, opts) { + if (typeof fn !== 'function') { + throw new Error('First param to `schema.plugin()` must be a function, ' + + 'got "' + (typeof fn) + '"'); + } + + if (opts && opts.deduplicate) { + for (const plugin of this.plugins) { + if (plugin.fn === fn) { + return this; + } + } + } + this.plugins.push({ fn: fn, opts: opts }); + + fn(this, opts); + return this; +}; + +/** + * Adds an instance method to documents constructed from Models compiled from this schema. + * + * ####Example + * + * const schema = kittySchema = new Schema(..); + * + * schema.method('meow', function () { + * console.log('meeeeeoooooooooooow'); + * }) + * + * const Kitty = mongoose.model('Kitty', schema); + * + * const fizz = new Kitty; + * fizz.meow(); // meeeeeooooooooooooow + * + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. + * + * schema.method({ + * purr: function () {} + * , scratch: function () {} + * }); + * + * // later + * fizz.purr(); + * fizz.scratch(); + * + * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](/docs/guide.html#methods) + * + * @param {String|Object} method name + * @param {Function} [fn] + * @api public + */ + +Schema.prototype.method = function(name, fn, options) { + if (typeof name !== 'string') { + for (const i in name) { + this.methods[i] = name[i]; + this.methodOptions[i] = utils.clone(options); + } + } else { + this.methods[name] = fn; + this.methodOptions[name] = utils.clone(options); + } + return this; +}; + +/** + * Adds static "class" methods to Models compiled from this schema. + * + * ####Example + * + * const schema = new Schema(..); + * // Equivalent to `schema.statics.findByName = function(name) {}`; + * schema.static('findByName', function(name) { + * return this.find({ name: name }); + * }); + * + * const Drink = mongoose.model('Drink', schema); + * await Drink.findByName('LaCroix'); + * + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. + * + * @param {String|Object} name + * @param {Function} [fn] + * @api public + * @see Statics /docs/guide.html#statics + */ + +Schema.prototype.static = function(name, fn) { + if (typeof name !== 'string') { + for (const i in name) { + this.statics[i] = name[i]; + } + } else { + this.statics[name] = fn; + } + return this; +}; + +/** + * Defines an index (most likely compound) for this schema. + * + * ####Example + * + * schema.index({ first: 1, last: -1 }) + * + * @param {Object} fields + * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex) + * @param {String | number} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link. + * @api public + */ + +Schema.prototype.index = function(fields, options) { + fields || (fields = {}); + options || (options = {}); + + if (options.expires) { + utils.expires(options); + } + + this._indexes.push([fields, options]); + return this; +}; + +/** + * Sets a schema option. + * + * ####Example + * + * schema.set('strict'); // 'true' by default + * schema.set('strict', false); // Sets 'strict' to false + * schema.set('strict'); // 'false' + * + * @param {String} key option name + * @param {Object} [value] if not passed, the current option value is returned + * @see Schema ./ + * @api public + */ + +Schema.prototype.set = function(key, value, _tags) { + if (arguments.length === 1) { + return this.options[key]; + } + + switch (key) { + case 'read': + this.options[key] = readPref(value, _tags); + this._userProvidedOptions[key] = this.options[key]; + break; + case 'timestamps': + this.setupTimestamp(value); + this.options[key] = value; + this._userProvidedOptions[key] = this.options[key]; + break; + case '_id': + this.options[key] = value; + this._userProvidedOptions[key] = this.options[key]; + + if (value && !this.paths['_id']) { + addAutoId(this); + } else if (!value && this.paths['_id'] != null && this.paths['_id'].auto) { + this.remove('_id'); + } + break; + default: + this.options[key] = value; + this._userProvidedOptions[key] = this.options[key]; + break; + } + + return this; +}; + +/** + * Gets a schema option. + * + * ####Example: + * + * schema.get('strict'); // true + * schema.set('strict', false); + * schema.get('strict'); // false + * + * @param {String} key option name + * @api public + * @return {Any} the option's value + */ + +Schema.prototype.get = function(key) { + return this.options[key]; +}; + +/** + * The allowed index types + * + * @receiver Schema + * @static indexTypes + * @api public + */ + +const indexTypes = '2d 2dsphere hashed text'.split(' '); + +Object.defineProperty(Schema, 'indexTypes', { + get: function() { + return indexTypes; + }, + set: function() { + throw new Error('Cannot overwrite Schema.indexTypes'); + } +}); + +/** + * Returns a list of indexes that this schema declares, via `schema.index()` or by `index: true` in a path's options. + * Indexes are expressed as an array `[spec, options]`. + * + * ####Example: + * + * const userSchema = new Schema({ + * email: { type: String, required: true, unique: true }, + * registeredAt: { type: Date, index: true } + * }); + * + * // [ [ { email: 1 }, { unique: true, background: true } ], + * // [ { registeredAt: 1 }, { background: true } ] ] + * userSchema.indexes(); + * + * [Plugins](/docs/plugins.html) can use the return value of this function to modify a schema's indexes. + * For example, the below plugin makes every index unique by default. + * + * function myPlugin(schema) { + * for (const index of schema.indexes()) { + * if (index[1].unique === undefined) { + * index[1].unique = true; + * } + * } + * } + * + * @api public + * @return {Array} list of indexes defined in the schema + */ + +Schema.prototype.indexes = function() { + return getIndexes(this); +}; + +/** + * Creates a virtual type with the given name. + * + * @param {String} name + * @param {Object} [options] + * @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](populate.html#populate-virtuals). + * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. + * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. + * @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array. + * @param {Boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`. + * @param {Function|null} [options.get=null] Adds a [getter](/docs/tutorials/getters-setters.html) to this virtual to transform the populated doc. + * @return {VirtualType} + */ + +Schema.prototype.virtual = function(name, options) { + if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') { + return this.virtual(name.path, name.options); + } + + options = new VirtualOptions(options); + + if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) { + if (options.localField == null) { + throw new Error('Reference virtuals require `localField` option'); + } + + if (options.foreignField == null) { + throw new Error('Reference virtuals require `foreignField` option'); + } + + this.pre('init', function(obj) { + if (mpath.has(name, obj)) { + const _v = mpath.get(name, obj); + if (!this.$$populatedVirtuals) { + this.$$populatedVirtuals = {}; + } + + if (options.justOne || options.count) { + this.$$populatedVirtuals[name] = Array.isArray(_v) ? + _v[0] : + _v; + } else { + this.$$populatedVirtuals[name] = Array.isArray(_v) ? + _v : + _v == null ? [] : [_v]; + } + + mpath.unset(name, obj); + } + }); + + const virtual = this.virtual(name); + virtual.options = options; + + virtual. + set(function(_v) { + if (!this.$$populatedVirtuals) { + this.$$populatedVirtuals = {}; + } + + if (options.justOne || options.count) { + this.$$populatedVirtuals[name] = Array.isArray(_v) ? + _v[0] : + _v; + + if (typeof this.$$populatedVirtuals[name] !== 'object') { + this.$$populatedVirtuals[name] = options.count ? _v : null; + } + } else { + this.$$populatedVirtuals[name] = Array.isArray(_v) ? + _v : + _v == null ? [] : [_v]; + + this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) { + return doc && typeof doc === 'object'; + }); + } + }); + + if (typeof options.get === 'function') { + virtual.get(options.get); + } + + // Workaround for gh-8198: if virtual is under document array, make a fake + // virtual. See gh-8210 + const parts = name.split('.'); + let cur = parts[0]; + for (let i = 0; i < parts.length - 1; ++i) { + if (this.paths[cur] != null && this.paths[cur].$isMongooseDocumentArray) { + const remnant = parts.slice(i + 1).join('.'); + this.paths[cur].schema.virtual(remnant, options); + break; + } + + cur += '.' + parts[i + 1]; + } + + return virtual; + } + + const virtuals = this.virtuals; + const parts = name.split('.'); + + if (this.pathType(name) === 'real') { + throw new Error('Virtual path "' + name + '"' + + ' conflicts with a real path in the schema'); + } + + virtuals[name] = parts.reduce(function(mem, part, i) { + mem[part] || (mem[part] = (i === parts.length - 1) + ? new VirtualType(options, name) + : {}); + return mem[part]; + }, this.tree); + + return virtuals[name]; +}; + +/** + * Returns the virtual type with the given `name`. + * + * @param {String} name + * @return {VirtualType} + */ + +Schema.prototype.virtualpath = function(name) { + return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null; +}; + +/** + * Removes the given `path` (or [`paths`]). + * + * ####Example: + * + * const schema = new Schema({ name: String, age: Number }); + * schema.remove('name'); + * schema.path('name'); // Undefined + * schema.path('age'); // SchemaNumber { ... } + * + * @param {String|Array} path + * @return {Schema} the Schema instance + * @api public + */ +Schema.prototype.remove = function(path) { + if (typeof path === 'string') { + path = [path]; + } + if (Array.isArray(path)) { + path.forEach(function(name) { + if (this.path(name) == null && !this.nested[name]) { + return; + } + if (this.nested[name]) { + const allKeys = Object.keys(this.paths). + concat(Object.keys(this.nested)); + for (const path of allKeys) { + if (path.startsWith(name + '.')) { + delete this.paths[path]; + delete this.nested[path]; + _deletePath(this, path); + } + } + + delete this.nested[name]; + _deletePath(this, name); + return; + } + + delete this.paths[name]; + _deletePath(this, name); + }, this); + } + return this; +}; + +/*! + * ignore + */ + +function _deletePath(schema, name) { + const pieces = name.split('.'); + const last = pieces.pop(); + + let branch = schema.tree; + + for (const piece of pieces) { + branch = branch[piece]; + } + + delete branch[last]; +} + +/** + * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static), + * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions) + * to schema [virtuals](/docs/guide.html#virtuals), + * [statics](/docs/guide.html#statics), and + * [methods](/docs/guide.html#methods). + * + * ####Example: + * + * ```javascript + * const md5 = require('md5'); + * const userSchema = new Schema({ email: String }); + * class UserClass { + * // `gravatarImage` becomes a virtual + * get gravatarImage() { + * const hash = md5(this.email.toLowerCase()); + * return `https://www.gravatar.com/avatar/${hash}`; + * } + * + * // `getProfileUrl()` becomes a document method + * getProfileUrl() { + * return `https://mysite.com/${this.email}`; + * } + * + * // `findByEmail()` becomes a static + * static findByEmail(email) { + * return this.findOne({ email }); + * } + * } + * + * // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method, + * // and a `findByEmail()` static + * userSchema.loadClass(UserClass); + * ``` + * + * @param {Function} model + * @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics + */ +Schema.prototype.loadClass = function(model, virtualsOnly) { + if (model === Object.prototype || + model === Function.prototype || + model.prototype.hasOwnProperty('$isMongooseModelPrototype')) { + return this; + } + + this.loadClass(Object.getPrototypeOf(model), virtualsOnly); + + // Add static methods + if (!virtualsOnly) { + Object.getOwnPropertyNames(model).forEach(function(name) { + if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) { + return; + } + const prop = Object.getOwnPropertyDescriptor(model, name); + if (prop.hasOwnProperty('value')) { + this.static(name, prop.value); + } + }, this); + } + + // Add methods and virtuals + Object.getOwnPropertyNames(model.prototype).forEach(function(name) { + if (name.match(/^(constructor)$/)) { + return; + } + const method = Object.getOwnPropertyDescriptor(model.prototype, name); + if (!virtualsOnly) { + if (typeof method.value === 'function') { + this.method(name, method.value); + } + } + if (typeof method.get === 'function') { + if (this.virtuals[name]) { + this.virtuals[name].getters = []; + } + this.virtual(name).get(method.get); + } + if (typeof method.set === 'function') { + if (this.virtuals[name]) { + this.virtuals[name].setters = []; + } + this.virtual(name).set(method.set); + } + }, this); + + return this; +}; + +/*! + * ignore + */ + +Schema.prototype._getSchema = function(path) { + const _this = this; + const pathschema = _this.path(path); + const resultPath = []; + + if (pathschema) { + pathschema.$fullPath = path; + return pathschema; + } + + function search(parts, schema) { + let p = parts.length + 1; + let foundschema; + let trypath; + + while (p--) { + trypath = parts.slice(0, p).join('.'); + foundschema = schema.path(trypath); + if (foundschema) { + resultPath.push(trypath); + + if (foundschema.caster) { + // array of Mixed? + if (foundschema.caster instanceof MongooseTypes.Mixed) { + foundschema.caster.$fullPath = resultPath.join('.'); + return foundschema.caster; + } + + // Now that we found the array, we need to check if there + // are remaining document paths to look up for casting. + // Also we need to handle array.$.path since schema.path + // doesn't work for that. + // If there is no foundschema.schema we are dealing with + // a path like array.$ + if (p !== parts.length) { + if (foundschema.schema) { + let ret; + if (parts[p] === '$' || isArrayFilter(parts[p])) { + if (p + 1 === parts.length) { + // comments.$ + return foundschema; + } + // comments.$.comments.$.title + ret = search(parts.slice(p + 1), foundschema.schema); + if (ret) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !foundschema.schema.$isSingleNested; + } + return ret; + } + // this is the last path of the selector + ret = search(parts.slice(p), foundschema.schema); + if (ret) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !foundschema.schema.$isSingleNested; + } + return ret; + } + } + } else if (foundschema.$isSchemaMap) { + if (p >= parts.length) { + return foundschema; + } + // Any path in the map will be an instance of the map's embedded schematype + if (p + 1 >= parts.length) { + return foundschema.$__schemaType; + } + const ret = search(parts.slice(p + 1), foundschema.$__schemaType.schema); + return ret; + } + + foundschema.$fullPath = resultPath.join('.'); + + return foundschema; + } + } + } + + // look for arrays + const parts = path.split('.'); + for (let i = 0; i < parts.length; ++i) { + if (parts[i] === '$' || isArrayFilter(parts[i])) { + // Re: gh-5628, because `schema.path()` doesn't take $ into account. + parts[i] = '0'; + } + } + return search(parts, _this); +}; + +/*! + * ignore + */ + +Schema.prototype._getPathType = function(path) { + const _this = this; + const pathschema = _this.path(path); + + if (pathschema) { + return 'real'; + } + + function search(parts, schema) { + let p = parts.length + 1, + foundschema, + trypath; + + while (p--) { + trypath = parts.slice(0, p).join('.'); + foundschema = schema.path(trypath); + if (foundschema) { + if (foundschema.caster) { + // array of Mixed? + if (foundschema.caster instanceof MongooseTypes.Mixed) { + return { schema: foundschema, pathType: 'mixed' }; + } + + // Now that we found the array, we need to check if there + // are remaining document paths to look up for casting. + // Also we need to handle array.$.path since schema.path + // doesn't work for that. + // If there is no foundschema.schema we are dealing with + // a path like array.$ + if (p !== parts.length && foundschema.schema) { + if (parts[p] === '$' || isArrayFilter(parts[p])) { + if (p === parts.length - 1) { + return { schema: foundschema, pathType: 'nested' }; + } + // comments.$.comments.$.title + return search(parts.slice(p + 1), foundschema.schema); + } + // this is the last path of the selector + return search(parts.slice(p), foundschema.schema); + } + return { + schema: foundschema, + pathType: foundschema.$isSingleNested ? 'nested' : 'array' + }; + } + return { schema: foundschema, pathType: 'real' }; + } else if (p === parts.length && schema.nested[trypath]) { + return { schema: schema, pathType: 'nested' }; + } + } + return { schema: foundschema || schema, pathType: 'undefined' }; + } + + // look for arrays + return search(path.split('.'), _this); +}; + +/*! + * ignore + */ + +function isArrayFilter(piece) { + return piece.startsWith('$[') && piece.endsWith(']'); +} + +/*! + * Called by `compile()` _right before_ compiling. Good for making any changes to + * the schema that should respect options set by plugins, like `id` + */ + +Schema.prototype._preCompile = function _preCompile() { + idGetter(this); +}; + +/*! + * Module exports. + */ + +module.exports = exports = Schema; + +// require down here because of reference issues + +/** + * The various built-in Mongoose Schema Types. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * const ObjectId = mongoose.Schema.Types.ObjectId; + * + * ####Types: + * + * - [String](/docs/schematypes.html#strings) + * - [Number](/docs/schematypes.html#numbers) + * - [Boolean](/docs/schematypes.html#booleans) | Bool + * - [Array](/docs/schematypes.html#arrays) + * - [Buffer](/docs/schematypes.html#buffers) + * - [Date](/docs/schematypes.html#dates) + * - [ObjectId](/docs/schematypes.html#objectids) | Oid + * - [Mixed](/docs/schematypes.html#mixed) + * + * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema. + * + * const Mixed = mongoose.Schema.Types.Mixed; + * new mongoose.Schema({ _user: Mixed }) + * + * @api public + */ + +Schema.Types = MongooseTypes = require('./schema/index'); + +/*! + * ignore + */ + +exports.ObjectId = MongooseTypes.ObjectId; diff --git a/node_modules/mongoose/lib/schema/SubdocumentPath.js b/node_modules/mongoose/lib/schema/SubdocumentPath.js new file mode 100644 index 0000000..bffae00 --- /dev/null +++ b/node_modules/mongoose/lib/schema/SubdocumentPath.js @@ -0,0 +1,349 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const CastError = require('../error/cast'); +const EventEmitter = require('events').EventEmitter; +const ObjectExpectedError = require('../error/objectExpected'); +const SchemaSubdocumentOptions = require('../options/SchemaSubdocumentOptions'); +const SchemaType = require('../schematype'); +const $exists = require('./operators/exists'); +const castToNumber = require('./operators/helpers').castToNumber; +const discriminator = require('../helpers/model/discriminator'); +const geospatial = require('./operators/geospatial'); +const get = require('../helpers/get'); +const getConstructor = require('../helpers/discriminator/getConstructor'); +const handleIdOption = require('../helpers/schema/handleIdOption'); +const internalToObjectOptions = require('../options').internalToObjectOptions; +const utils = require('../utils'); + +let Subdocument; + +module.exports = SubdocumentPath; + +/** + * Single nested subdocument SchemaType constructor. + * + * @param {Schema} schema + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SubdocumentPath(schema, path, options) { + schema = handleIdOption(schema, options); + + this.caster = _createConstructor(schema); + this.caster.path = path; + this.caster.prototype.$basePath = path; + this.schema = schema; + this.$isSingleNested = true; + SchemaType.call(this, path, options, 'Embedded'); +} + +/*! + * ignore + */ + +SubdocumentPath.prototype = Object.create(SchemaType.prototype); +SubdocumentPath.prototype.constructor = SubdocumentPath; +SubdocumentPath.prototype.OptionsConstructor = SchemaSubdocumentOptions; + +/*! + * ignore + */ + +function _createConstructor(schema, baseClass) { + // lazy load + Subdocument || (Subdocument = require('../types/subdocument')); + + const _embedded = function SingleNested(value, path, parent) { + const _this = this; + + this.$__parent = parent; + Subdocument.apply(this, arguments); + + this.$session(this.ownerDocument().$session()); + + if (parent) { + parent.$on('save', function() { + _this.emit('save', _this); + _this.constructor.emit('save', _this); + }); + + parent.$on('isNew', function(val) { + _this.isNew = val; + _this.emit('isNew', val); + _this.constructor.emit('isNew', val); + }); + } + }; + + schema._preCompile(); + + const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype; + _embedded.prototype = Object.create(proto); + _embedded.prototype.$__setSchema(schema); + _embedded.prototype.constructor = _embedded; + _embedded.schema = schema; + _embedded.$isSingleNested = true; + _embedded.events = new EventEmitter(); + _embedded.prototype.toBSON = function() { + return this.toObject(internalToObjectOptions); + }; + + // apply methods + for (const i in schema.methods) { + _embedded.prototype[i] = schema.methods[i]; + } + + // apply statics + for (const i in schema.statics) { + _embedded[i] = schema.statics[i]; + } + + for (const i in EventEmitter.prototype) { + _embedded[i] = EventEmitter.prototype[i]; + } + + return _embedded; +} + +/*! + * Special case for when users use a common location schema to represent + * locations for use with $geoWithin. + * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/ + * + * @param {Object} val + * @api private + */ + +SubdocumentPath.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val) { + return { $geometry: this.castForQuery(val.$geometry) }; +}; + +/*! + * ignore + */ + +SubdocumentPath.prototype.$conditionalHandlers.$near = +SubdocumentPath.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near; + +SubdocumentPath.prototype.$conditionalHandlers.$within = +SubdocumentPath.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within; + +SubdocumentPath.prototype.$conditionalHandlers.$geoIntersects = + geospatial.cast$geoIntersects; + +SubdocumentPath.prototype.$conditionalHandlers.$minDistance = castToNumber; +SubdocumentPath.prototype.$conditionalHandlers.$maxDistance = castToNumber; + +SubdocumentPath.prototype.$conditionalHandlers.$exists = $exists; + +/** + * Casts contents + * + * @param {Object} value + * @api private + */ + +SubdocumentPath.prototype.cast = function(val, doc, init, priorVal, options) { + if (val && val.$isSingleNested && val.parent === doc) { + return val; + } + + if (val != null && (typeof val !== 'object' || Array.isArray(val))) { + throw new ObjectExpectedError(this.path, val); + } + + const Constructor = getConstructor(this.caster, val); + + let subdoc; + + // Only pull relevant selected paths and pull out the base path + const parentSelected = get(doc, '$__.selected', {}); + const path = this.path; + const selected = Object.keys(parentSelected).reduce((obj, key) => { + if (key.startsWith(path + '.')) { + obj[key.substr(path.length + 1)] = parentSelected[key]; + } + return obj; + }, {}); + options = Object.assign({}, options, { priorDoc: priorVal }); + if (init) { + subdoc = new Constructor(void 0, selected, doc); + subdoc.$init(val); + } else { + if (Object.keys(val).length === 0) { + return new Constructor({}, selected, doc, undefined, options); + } + + return new Constructor(val, selected, doc, undefined, options); + } + + return subdoc; +}; + +/** + * Casts contents for query + * + * @param {string} [$conditional] optional query operator (like `$eq` or `$in`) + * @param {any} value + * @api private + */ + +SubdocumentPath.prototype.castForQuery = function($conditional, val, options) { + let handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional); + } + return handler.call(this, val); + } + val = $conditional; + if (val == null) { + return val; + } + + if (this.options.runSetters) { + val = this._applySetters(val); + } + + const Constructor = getConstructor(this.caster, val); + const overrideStrict = options != null && options.strict != null ? + options.strict : + void 0; + + try { + val = new Constructor(val, overrideStrict); + } catch (error) { + // Make sure we always wrap in a CastError (gh-6803) + if (!(error instanceof CastError)) { + throw new CastError('Embedded', val, this.path, error, this); + } + throw error; + } + return val; +}; + +/** + * Async validation on this single nested doc. + * + * @api private + */ + +SubdocumentPath.prototype.doValidate = function(value, fn, scope, options) { + const Constructor = getConstructor(this.caster, value); + + if (options && options.skipSchemaValidators) { + if (!(value instanceof Constructor)) { + value = new Constructor(value, null, scope); + } + return value.validate(fn); + } + + SchemaType.prototype.doValidate.call(this, value, function(error) { + if (error) { + return fn(error); + } + if (!value) { + return fn(null); + } + + value.validate(fn); + }, scope, options); +}; + +/** + * Synchronously validate this single nested doc + * + * @api private + */ + +SubdocumentPath.prototype.doValidateSync = function(value, scope, options) { + if (!options || !options.skipSchemaValidators) { + const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope); + if (schemaTypeError) { + return schemaTypeError; + } + } + if (!value) { + return; + } + return value.validateSync(); +}; + +/** + * Adds a discriminator to this single nested subdocument. + * + * ####Example: + * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); + * const schema = Schema({ shape: shapeSchema }); + * + * const singleNestedPath = parentSchema.path('shape'); + * singleNestedPath.discriminator('Circle', Schema({ radius: Number })); + * + * @param {String} name + * @param {Schema} schema fields to add to the schema for instances of this sub-class + * @param {Object|string} [options] If string, same as `options.value`. + * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. + * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning. + * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model + * @see discriminators /docs/discriminators.html + * @api public + */ + +SubdocumentPath.prototype.discriminator = function(name, schema, options) { + options = options || {}; + const value = utils.isPOJO(options) ? options.value : options; + const clone = get(options, 'clone', true); + + if (schema.instanceOfSchema && clone) { + schema = schema.clone(); + } + + schema = discriminator(this.caster, name, schema, value); + + this.caster.discriminators[name] = _createConstructor(schema, this.caster); + + return this.caster.discriminators[name]; +}; + +/** + * Sets a default option for all SubdocumentPath instances. + * + * ####Example: + * + * // Make all numbers have option `min` equal to 0. + * mongoose.Schema.Embedded.set('required', true); + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ + +SubdocumentPath.defaultOptions = {}; + +SubdocumentPath.set = SchemaType.set; + +/*! + * ignore + */ + +SubdocumentPath.prototype.clone = function() { + const options = Object.assign({}, this.options); + const schematype = new this.constructor(this.schema, this.path, options); + schematype.validators = this.validators.slice(); + if (this.requiredValidator !== undefined) { + schematype.requiredValidator = this.requiredValidator; + } + schematype.caster.discriminators = Object.assign({}, this.caster.discriminators); + return schematype; +}; diff --git a/node_modules/mongoose/lib/schema/array.js b/node_modules/mongoose/lib/schema/array.js new file mode 100644 index 0000000..9529186 --- /dev/null +++ b/node_modules/mongoose/lib/schema/array.js @@ -0,0 +1,651 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const $exists = require('./operators/exists'); +const $type = require('./operators/type'); +const MongooseError = require('../error/mongooseError'); +const SchemaArrayOptions = require('../options/SchemaArrayOptions'); +const SchemaType = require('../schematype'); +const CastError = SchemaType.CastError; +const Mixed = require('./mixed'); +const arrayDepth = require('../helpers/arrayDepth'); +const cast = require('../cast'); +const get = require('../helpers/get'); +const isOperator = require('../helpers/query/isOperator'); +const util = require('util'); +const utils = require('../utils'); +const castToNumber = require('./operators/helpers').castToNumber; +const geospatial = require('./operators/geospatial'); +const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue'); + +let MongooseArray; +let EmbeddedDoc; + +const isNestedArraySymbol = Symbol('mongoose#isNestedArray'); +const emptyOpts = Object.freeze({}); + +/** + * Array SchemaType constructor + * + * @param {String} key + * @param {SchemaType} cast + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaArray(key, cast, options, schemaOptions) { + // lazy load + EmbeddedDoc || (EmbeddedDoc = require('../types').Embedded); + + let typeKey = 'type'; + if (schemaOptions && schemaOptions.typeKey) { + typeKey = schemaOptions.typeKey; + } + this.schemaOptions = schemaOptions; + + if (cast) { + let castOptions = {}; + + if (utils.isPOJO(cast)) { + if (cast[typeKey]) { + // support { type: Woot } + castOptions = utils.clone(cast); // do not alter user arguments + delete castOptions[typeKey]; + cast = cast[typeKey]; + } else { + cast = Mixed; + } + } + + if (options != null && options.ref != null && castOptions.ref == null) { + castOptions.ref = options.ref; + } + + if (cast === Object) { + cast = Mixed; + } + + // support { type: 'String' } + const name = typeof cast === 'string' + ? cast + : utils.getFunctionName(cast); + + const Types = require('./index.js'); + const caster = Types.hasOwnProperty(name) ? Types[name] : cast; + + this.casterConstructor = caster; + + if (this.casterConstructor instanceof SchemaArray) { + this.casterConstructor[isNestedArraySymbol] = true; + } + + if (typeof caster === 'function' && + !caster.$isArraySubdocument && + !caster.$isSchemaMap) { + const path = this.caster instanceof EmbeddedDoc ? null : key; + this.caster = new caster(path, castOptions); + } else { + this.caster = caster; + if (!(this.caster instanceof EmbeddedDoc)) { + this.caster.path = key; + } + } + + this.$embeddedSchemaType = this.caster; + } + + this.$isMongooseArray = true; + + SchemaType.call(this, key, options, 'Array'); + + let defaultArr; + let fn; + + if (this.defaultValue != null) { + defaultArr = this.defaultValue; + fn = typeof defaultArr === 'function'; + } + + if (!('defaultValue' in this) || this.defaultValue !== void 0) { + const defaultFn = function() { + let arr = []; + if (fn) { + arr = defaultArr.call(this); + } else if (defaultArr != null) { + arr = arr.concat(defaultArr); + } + // Leave it up to `cast()` to convert the array + return arr; + }; + defaultFn.$runBeforeSetters = !fn; + this.default(defaultFn); + } +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaArray.schemaName = 'Array'; + + +/** + * Options for all arrays. + * + * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. + * + * @static options + * @api public + */ + +SchemaArray.options = { castNonArrays: true }; + +/*! + * ignore + */ + +SchemaArray.defaultOptions = {}; + +/** + * Sets a default option for all Array instances. + * + * ####Example: + * + * // Make all Array instances have `required` of true by default. + * mongoose.Schema.Array.set('required', true); + * + * const User = mongoose.model('User', new Schema({ test: Array })); + * new User({ }).validateSync().errors.test.message; // Path `test` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @api public + */ +SchemaArray.set = SchemaType.set; + +/*! + * Inherits from SchemaType. + */ +SchemaArray.prototype = Object.create(SchemaType.prototype); +SchemaArray.prototype.constructor = SchemaArray; +SchemaArray.prototype.OptionsConstructor = SchemaArrayOptions; + +/*! + * ignore + */ + +SchemaArray._checkRequired = SchemaType.prototype.checkRequired; + +/** + * Override the function the required validator uses to check whether an array + * passes the `required` check. + * + * ####Example: + * + * // Require non-empty array to pass `required` check + * mongoose.Schema.Types.Array.checkRequired(v => Array.isArray(v) && v.length); + * + * const M = mongoose.model({ arr: { type: Array, required: true } }); + * new M({ arr: [] }).validateSync(); // `null`, validation fails! + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @api public + */ + +SchemaArray.checkRequired = SchemaType.checkRequired; + +/** + * Check if the given value satisfies the `required` validator. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ + +SchemaArray.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + SchemaArray.checkRequired(); + + return _checkRequired(value); +}; + +/** + * Adds an enum validator if this is an array of strings or numbers. Equivalent to + * `SchemaString.prototype.enum()` or `SchemaNumber.prototype.enum()` + * + * @param {String|Object} [args...] enumeration values + * @return {SchemaArray} this + */ + +SchemaArray.prototype.enum = function() { + let arr = this; + while (true) { + const instance = get(arr, 'caster.instance'); + if (instance === 'Array') { + arr = arr.caster; + continue; + } + if (instance !== 'String' && instance !== 'Number') { + throw new Error('`enum` can only be set on an array of strings or numbers ' + + ', not ' + instance); + } + break; + } + + let enumArray = arguments; + if (!Array.isArray(arguments) && utils.isObject(arguments)) { + enumArray = utils.object.vals(enumArray); + } + + arr.caster.enum.apply(arr.caster, enumArray); + return this; +}; + +/** + * Overrides the getters application for the population special-case + * + * @param {Object} value + * @param {Object} scope + * @api private + */ + +SchemaArray.prototype.applyGetters = function(value, scope) { + if (scope != null && scope.$__ != null && scope.$populated(this.path)) { + // means the object id was populated + return value; + } + + const ret = SchemaType.prototype.applyGetters.call(this, value, scope); + if (Array.isArray(ret)) { + const rawValue = ret.isMongooseArrayProxy ? ret.__array : ret; + const len = rawValue.length; + for (let i = 0; i < len; ++i) { + rawValue[i] = this.caster.applyGetters(rawValue[i], scope); + } + } + return ret; +}; + +SchemaArray.prototype._applySetters = function(value, scope, init, priorVal) { + if (this.casterConstructor.$isMongooseArray && + SchemaArray.options.castNonArrays && + !this[isNestedArraySymbol]) { + // Check nesting levels and wrap in array if necessary + let depth = 0; + let arr = this; + while (arr != null && + arr.$isMongooseArray && + !arr.$isMongooseDocumentArray) { + ++depth; + arr = arr.casterConstructor; + } + + // No need to wrap empty arrays + if (value != null && value.length > 0) { + const valueDepth = arrayDepth(value); + if (valueDepth.min === valueDepth.max && valueDepth.max < depth && valueDepth.containsNonArrayItem) { + for (let i = valueDepth.max; i < depth; ++i) { + value = [value]; + } + } + } + } + + return SchemaType.prototype._applySetters.call(this, value, scope, init, priorVal); +}; + +/** + * Casts values for set(). + * + * @param {Object} value + * @param {Document} doc document that triggers the casting + * @param {Boolean} init whether this is an initialization cast + * @api private + */ + +SchemaArray.prototype.cast = function(value, doc, init, prev, options) { + // lazy load + MongooseArray || (MongooseArray = require('../types').Array); + + let i; + let l; + + if (Array.isArray(value)) { + const len = value.length; + if (!len && doc) { + const indexes = doc.schema.indexedPaths(); + + const arrayPath = this.path; + for (i = 0, l = indexes.length; i < l; ++i) { + const pathIndex = indexes[i][0][arrayPath]; + if (pathIndex === '2dsphere' || pathIndex === '2d') { + return; + } + } + + // Special case: if this index is on the parent of what looks like + // GeoJSON, skip setting the default to empty array re: #1668, #3233 + const arrayGeojsonPath = this.path.endsWith('.coordinates') ? + this.path.substr(0, this.path.lastIndexOf('.')) : null; + if (arrayGeojsonPath != null) { + for (i = 0, l = indexes.length; i < l; ++i) { + const pathIndex = indexes[i][0][arrayGeojsonPath]; + if (pathIndex === '2dsphere') { + return; + } + } + } + } + + options = options || emptyOpts; + + let rawValue = value.isMongooseArrayProxy ? value.__array : value; + value = MongooseArray(rawValue, options.path || this._arrayPath || this.path, doc, this); + rawValue = value.__array; + + if (init && doc != null && doc.$__ != null && doc.$populated(this.path)) { + return value; + } + + const caster = this.caster; + const isMongooseArray = caster.$isMongooseArray; + if (caster && this.casterConstructor !== Mixed) { + try { + const len = rawValue.length; + for (i = 0; i < len; i++) { + const opts = {}; + // Perf: creating `arrayPath` is expensive for large arrays. + // We only need `arrayPath` if this is a nested array, so + // skip if possible. + if (isMongooseArray) { + if (options.arrayPath != null) { + opts.arrayPathIndex = i; + } else if (caster._arrayParentPath != null) { + opts.arrayPathIndex = i; + } + } + rawValue[i] = caster.applySetters(rawValue[i], doc, init, void 0, opts); + } + } catch (e) { + // rethrow + throw new CastError('[' + e.kind + ']', util.inspect(value), this.path + '.' + i, e, this); + } + } + + return value; + } + + if (init || SchemaArray.options.castNonArrays) { + // gh-2442: if we're loading this from the db and its not an array, mark + // the whole array as modified. + if (!!doc && !!init) { + doc.markModified(this.path); + } + return this.cast([value], doc, init); + } + + throw new CastError('Array', util.inspect(value), this.path, null, this); +}; + +/*! + * ignore + */ + +SchemaArray.prototype._castForPopulate = function _castForPopulate(value, doc) { + // lazy load + MongooseArray || (MongooseArray = require('../types').Array); + + if (Array.isArray(value)) { + let i; + const rawValue = value.__array ? value.__array : value; + const len = rawValue.length; + + const caster = this.caster; + if (caster && this.casterConstructor !== Mixed) { + try { + for (i = 0; i < len; i++) { + const opts = {}; + // Perf: creating `arrayPath` is expensive for large arrays. + // We only need `arrayPath` if this is a nested array, so + // skip if possible. + if (caster.$isMongooseArray && caster._arrayParentPath != null) { + opts.arrayPathIndex = i; + } + + rawValue[i] = caster.cast(rawValue[i], doc, false, void 0, opts); + } + } catch (e) { + // rethrow + throw new CastError('[' + e.kind + ']', util.inspect(value), this.path + '.' + i, e, this); + } + } + + return value; + } + + throw new CastError('Array', util.inspect(value), this.path, null, this); +}; + +SchemaArray.prototype.$toObject = SchemaArray.prototype.toObject; + +/*! + * Ignore + */ + +SchemaArray.prototype.discriminator = function(name, schema) { + let arr = this; + while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) { + arr = arr.casterConstructor; + if (arr == null || typeof arr === 'function') { + throw new MongooseError('You can only add an embedded discriminator on ' + + 'a document array, ' + this.path + ' is a plain array'); + } + } + return arr.discriminator(name, schema); +}; + +/*! + * ignore + */ + +SchemaArray.prototype.clone = function() { + const options = Object.assign({}, this.options); + const schematype = new this.constructor(this.path, this.caster, options, this.schemaOptions); + schematype.validators = this.validators.slice(); + if (this.requiredValidator !== undefined) { + schematype.requiredValidator = this.requiredValidator; + } + return schematype; +}; + +/** + * Casts values for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaArray.prototype.castForQuery = function($conditional, value) { + let handler; + let val; + + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Array.'); + } + + val = handler.call(this, value); + } else { + val = $conditional; + let Constructor = this.casterConstructor; + + if (val && + Constructor.discriminators && + Constructor.schema && + Constructor.schema.options && + Constructor.schema.options.discriminatorKey) { + if (typeof val[Constructor.schema.options.discriminatorKey] === 'string' && + Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) { + Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]; + } else { + const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]); + if (constructorByValue) { + Constructor = constructorByValue; + } + } + } + + const proto = this.casterConstructor.prototype; + let method = proto && (proto.castForQuery || proto.cast); + if (!method && Constructor.castForQuery) { + method = Constructor.castForQuery; + } + const caster = this.caster; + + if (Array.isArray(val)) { + this.setters.reverse().forEach(setter => { + val = setter.call(this, val, this); + }); + val = val.map(function(v) { + if (utils.isObject(v) && v.$elemMatch) { + return v; + } + if (method) { + v = method.call(caster, v); + return v; + } + if (v != null) { + v = new Constructor(v); + return v; + } + return v; + }); + } else if (method) { + val = method.call(caster, val); + } else if (val != null) { + val = new Constructor(val); + } + } + + return val; +}; + +function cast$all(val) { + if (!Array.isArray(val)) { + val = [val]; + } + + val = val.map(function(v) { + if (utils.isObject(v)) { + const o = {}; + o[this.path] = v; + return cast(this.casterConstructor.schema, o)[this.path]; + } + return v; + }, this); + + return this.castForQuery(val); +} + +function cast$elemMatch(val) { + const keys = Object.keys(val); + const numKeys = keys.length; + for (let i = 0; i < numKeys; ++i) { + const key = keys[i]; + const value = val[key]; + if (isOperator(key) && value != null) { + val[key] = this.castForQuery(key, value); + } + } + + // Is this an embedded discriminator and is the discriminator key set? + // If so, use the discriminator schema. See gh-7449 + const discriminatorKey = get(this, + 'casterConstructor.schema.options.discriminatorKey'); + const discriminators = get(this, 'casterConstructor.schema.discriminators', {}); + if (discriminatorKey != null && + val[discriminatorKey] != null && + discriminators[val[discriminatorKey]] != null) { + return cast(discriminators[val[discriminatorKey]], val); + } + + return cast(this.casterConstructor.schema, val); +} + +const handle = SchemaArray.prototype.$conditionalHandlers = {}; + +handle.$all = cast$all; +handle.$options = String; +handle.$elemMatch = cast$elemMatch; +handle.$geoIntersects = geospatial.cast$geoIntersects; +handle.$or = createLogicalQueryOperatorHandler('$or'); +handle.$and = createLogicalQueryOperatorHandler('$and'); +handle.$nor = createLogicalQueryOperatorHandler('$nor'); + +function createLogicalQueryOperatorHandler(op) { + return function logicalQueryOperatorHandler(val) { + if (!Array.isArray(val)) { + throw new TypeError('conditional ' + op + ' requires an array'); + } + + const ret = []; + for (const obj of val) { + ret.push(cast(this.casterConstructor.schema, obj)); + } + + return ret; + }; +} + +handle.$near = +handle.$nearSphere = geospatial.cast$near; + +handle.$within = +handle.$geoWithin = geospatial.cast$within; + +handle.$size = +handle.$minDistance = +handle.$maxDistance = castToNumber; + +handle.$exists = $exists; +handle.$type = $type; + +handle.$eq = +handle.$gt = +handle.$gte = +handle.$lt = +handle.$lte = +handle.$ne = +handle.$regex = SchemaArray.prototype.castForQuery; + +// `$in` is special because you can also include an empty array in the query +// like `$in: [1, []]`, see gh-5913 +handle.$nin = SchemaType.prototype.$conditionalHandlers.$nin; +handle.$in = SchemaType.prototype.$conditionalHandlers.$in; + +/*! + * Module exports. + */ + +module.exports = SchemaArray; diff --git a/node_modules/mongoose/lib/schema/boolean.js b/node_modules/mongoose/lib/schema/boolean.js new file mode 100644 index 0000000..8ef7e28 --- /dev/null +++ b/node_modules/mongoose/lib/schema/boolean.js @@ -0,0 +1,270 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const CastError = require('../error/cast'); +const SchemaType = require('../schematype'); +const castBoolean = require('../cast/boolean'); +const utils = require('../utils'); + +/** + * Boolean SchemaType constructor. + * + * @param {String} path + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaBoolean(path, options) { + SchemaType.call(this, path, options, 'Boolean'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaBoolean.schemaName = 'Boolean'; + +SchemaBoolean.defaultOptions = {}; + +/*! + * Inherits from SchemaType. + */ +SchemaBoolean.prototype = Object.create(SchemaType.prototype); +SchemaBoolean.prototype.constructor = SchemaBoolean; + +/*! + * ignore + */ + +SchemaBoolean._cast = castBoolean; + +/** + * Sets a default option for all Boolean instances. + * + * ####Example: + * + * // Make all booleans have `default` of false. + * mongoose.Schema.Boolean.set('default', false); + * + * const Order = mongoose.model('Order', new Schema({ isPaid: Boolean })); + * new Order({ }).isPaid; // false + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ + +SchemaBoolean.set = SchemaType.set; + +/** + * Get/set the function used to cast arbitrary values to booleans. + * + * ####Example: + * + * // Make Mongoose cast empty string '' to false. + * const original = mongoose.Schema.Boolean.cast(); + * mongoose.Schema.Boolean.cast(v => { + * if (v === '') { + * return false; + * } + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.Schema.Boolean.cast(false); + * + * @param {Function} caster + * @return {Function} + * @function get + * @static + * @api public + */ + +SchemaBoolean.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; + + return this._cast; +}; + +/*! + * ignore + */ + +SchemaBoolean._defaultCaster = v => { + if (v != null && typeof v !== 'boolean') { + throw new Error(); + } + return v; +}; + +/*! + * ignore + */ + +SchemaBoolean._checkRequired = v => v === true || v === false; + +/** + * Override the function the required validator uses to check whether a boolean + * passes the `required` check. + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ + +SchemaBoolean.checkRequired = SchemaType.checkRequired; + +/** + * Check if the given value satisfies a required validator. For a boolean + * to satisfy a required validator, it must be strictly equal to true or to + * false. + * + * @param {Any} value + * @return {Boolean} + * @api public + */ + +SchemaBoolean.prototype.checkRequired = function(value) { + return this.constructor._checkRequired(value); +}; + +/** + * Configure which values get casted to `true`. + * + * ####Example: + * + * const M = mongoose.model('Test', new Schema({ b: Boolean })); + * new M({ b: 'affirmative' }).b; // undefined + * mongoose.Schema.Boolean.convertToTrue.add('affirmative'); + * new M({ b: 'affirmative' }).b; // true + * + * @property convertToTrue + * @type Set + * @api public + */ + +Object.defineProperty(SchemaBoolean, 'convertToTrue', { + get: () => castBoolean.convertToTrue, + set: v => { castBoolean.convertToTrue = v; } +}); + +/** + * Configure which values get casted to `false`. + * + * ####Example: + * + * const M = mongoose.model('Test', new Schema({ b: Boolean })); + * new M({ b: 'nay' }).b; // undefined + * mongoose.Schema.Types.Boolean.convertToFalse.add('nay'); + * new M({ b: 'nay' }).b; // false + * + * @property convertToFalse + * @type Set + * @api public + */ + +Object.defineProperty(SchemaBoolean, 'convertToFalse', { + get: () => castBoolean.convertToFalse, + set: v => { castBoolean.convertToFalse = v; } +}); + +/** + * Casts to boolean + * + * @param {Object} value + * @param {Object} model - this value is optional + * @api private + */ + +SchemaBoolean.prototype.cast = function(value) { + let castBoolean; + if (typeof this._castFunction === 'function') { + castBoolean = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castBoolean = this.constructor.cast(); + } else { + castBoolean = SchemaBoolean.cast(); + } + + try { + return castBoolean(value); + } catch (error) { + throw new CastError('Boolean', value, this.path, error, this); + } +}; + +SchemaBoolean.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, {}); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} val + * @api private + */ + +SchemaBoolean.prototype.castForQuery = function($conditional, val) { + let handler; + if (arguments.length === 2) { + handler = SchemaBoolean.$conditionalHandlers[$conditional]; + + if (handler) { + return handler.call(this, val); + } + + return this._castForQuery(val); + } + + return this._castForQuery($conditional); +}; + +/** + * + * @api private + */ + +SchemaBoolean.prototype._castNullish = function _castNullish(v) { + if (typeof v === 'undefined' && + this.$$context != null && + this.$$context._mongooseOptions != null && + this.$$context._mongooseOptions.omitUndefined) { + return v; + } + const castBoolean = typeof this.constructor.cast === 'function' ? + this.constructor.cast() : + SchemaBoolean.cast(); + if (castBoolean == null) { + return v; + } + if (castBoolean.convertToFalse instanceof Set && castBoolean.convertToFalse.has(v)) { + return false; + } + if (castBoolean.convertToTrue instanceof Set && castBoolean.convertToTrue.has(v)) { + return true; + } + return v; +}; + +/*! + * Module exports. + */ + +module.exports = SchemaBoolean; diff --git a/node_modules/mongoose/lib/schema/buffer.js b/node_modules/mongoose/lib/schema/buffer.js new file mode 100644 index 0000000..d835416 --- /dev/null +++ b/node_modules/mongoose/lib/schema/buffer.js @@ -0,0 +1,267 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const MongooseBuffer = require('../types/buffer'); +const SchemaBufferOptions = require('../options/SchemaBufferOptions'); +const SchemaType = require('../schematype'); +const handleBitwiseOperator = require('./operators/bitwise'); +const utils = require('../utils'); + +const Binary = MongooseBuffer.Binary; +const CastError = SchemaType.CastError; + +/** + * Buffer SchemaType constructor + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaBuffer(key, options) { + SchemaType.call(this, key, options, 'Buffer'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaBuffer.schemaName = 'Buffer'; + +SchemaBuffer.defaultOptions = {}; + +/*! + * Inherits from SchemaType. + */ +SchemaBuffer.prototype = Object.create(SchemaType.prototype); +SchemaBuffer.prototype.constructor = SchemaBuffer; +SchemaBuffer.prototype.OptionsConstructor = SchemaBufferOptions; + +/*! + * ignore + */ + +SchemaBuffer._checkRequired = v => !!(v && v.length); + +/** + * Sets a default option for all Buffer instances. + * + * ####Example: + * + * // Make all buffers have `required` of true by default. + * mongoose.Schema.Buffer.set('required', true); + * + * const User = mongoose.model('User', new Schema({ test: Buffer })); + * new User({ }).validateSync().errors.test.message; // Path `test` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ + +SchemaBuffer.set = SchemaType.set; + +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * ####Example: + * + * // Allow empty strings to pass `required` check + * mongoose.Schema.Types.String.checkRequired(v => v != null); + * + * const M = mongoose.model({ buf: { type: Buffer, required: true } }); + * new M({ buf: Buffer.from('') }).validateSync(); // validation passes! + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ + +SchemaBuffer.checkRequired = SchemaType.checkRequired; + +/** + * Check if the given value satisfies a required validator. To satisfy a + * required validator, a buffer must not be null or undefined and have + * non-zero length. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ + +SchemaBuffer.prototype.checkRequired = function(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + return this.constructor._checkRequired(value); +}; + +/** + * Casts contents + * + * @param {Object} value + * @param {Document} doc document that triggers the casting + * @param {Boolean} init + * @api private + */ + +SchemaBuffer.prototype.cast = function(value, doc, init) { + let ret; + if (SchemaType._isRef(this, value, doc, init)) { + if (value && value.isMongooseBuffer) { + return value; + } + + if (Buffer.isBuffer(value)) { + if (!value || !value.isMongooseBuffer) { + value = new MongooseBuffer(value, [this.path, doc]); + if (this.options.subtype != null) { + value._subtype = this.options.subtype; + } + } + return value; + } + + if (value instanceof Binary) { + ret = new MongooseBuffer(value.value(true), [this.path, doc]); + if (typeof value.sub_type !== 'number') { + throw new CastError('Buffer', value, this.path, null, this); + } + ret._subtype = value.sub_type; + return ret; + } + + return this._castRef(value, doc, init); + } + + // documents + if (value && value._id) { + value = value._id; + } + + if (value && value.isMongooseBuffer) { + return value; + } + + if (Buffer.isBuffer(value)) { + if (!value || !value.isMongooseBuffer) { + value = new MongooseBuffer(value, [this.path, doc]); + if (this.options.subtype != null) { + value._subtype = this.options.subtype; + } + } + return value; + } + + if (value instanceof Binary) { + ret = new MongooseBuffer(value.value(true), [this.path, doc]); + if (typeof value.sub_type !== 'number') { + throw new CastError('Buffer', value, this.path, null, this); + } + ret._subtype = value.sub_type; + return ret; + } + + if (value === null) { + return value; + } + + + const type = typeof value; + if ( + type === 'string' || type === 'number' || Array.isArray(value) || + (type === 'object' && value.type === 'Buffer' && Array.isArray(value.data)) // gh-6863 + ) { + if (type === 'number') { + value = [value]; + } + ret = new MongooseBuffer(value, [this.path, doc]); + if (this.options.subtype != null) { + ret._subtype = this.options.subtype; + } + return ret; + } + + throw new CastError('Buffer', value, this.path, null, this); +}; + +/** + * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/) + * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html). + * + * ####Example: + * + * const s = new Schema({ uuid: { type: Buffer, subtype: 4 }); + * const M = db.model('M', s); + * const m = new M({ uuid: 'test string' }); + * m.uuid._subtype; // 4 + * + * @param {Number} subtype the default subtype + * @return {SchemaType} this + * @api public + */ + +SchemaBuffer.prototype.subtype = function(subtype) { + this.options.subtype = subtype; + return this; +}; + +/*! + * ignore + */ +function handleSingle(val) { + return this.castForQuery(val); +} + +SchemaBuffer.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $bitsAllClear: handleBitwiseOperator, + $bitsAnyClear: handleBitwiseOperator, + $bitsAllSet: handleBitwiseOperator, + $bitsAnySet: handleBitwiseOperator, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaBuffer.prototype.castForQuery = function($conditional, val) { + let handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Buffer.'); + } + return handler.call(this, val); + } + val = $conditional; + const casted = this._castForQuery(val); + return casted ? casted.toObject({ transform: false, virtuals: false }) : casted; +}; + +/*! + * Module exports. + */ + +module.exports = SchemaBuffer; diff --git a/node_modules/mongoose/lib/schema/date.js b/node_modules/mongoose/lib/schema/date.js new file mode 100644 index 0000000..5ee0eb9 --- /dev/null +++ b/node_modules/mongoose/lib/schema/date.js @@ -0,0 +1,403 @@ +/*! + * Module requirements. + */ + +'use strict'; + +const MongooseError = require('../error/index'); +const SchemaDateOptions = require('../options/SchemaDateOptions'); +const SchemaType = require('../schematype'); +const castDate = require('../cast/date'); +const getConstructorName = require('../helpers/getConstructorName'); +const utils = require('../utils'); + +const CastError = SchemaType.CastError; + +/** + * Date SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaDate(key, options) { + SchemaType.call(this, key, options, 'Date'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaDate.schemaName = 'Date'; + +SchemaDate.defaultOptions = {}; + +/*! + * Inherits from SchemaType. + */ +SchemaDate.prototype = Object.create(SchemaType.prototype); +SchemaDate.prototype.constructor = SchemaDate; +SchemaDate.prototype.OptionsConstructor = SchemaDateOptions; + +/*! + * ignore + */ + +SchemaDate._cast = castDate; + +/** + * Sets a default option for all Date instances. + * + * ####Example: + * + * // Make all dates have `required` of true by default. + * mongoose.Schema.Date.set('required', true); + * + * const User = mongoose.model('User', new Schema({ test: Date })); + * new User({ }).validateSync().errors.test.message; // Path `test` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ + +SchemaDate.set = SchemaType.set; + +/** + * Get/set the function used to cast arbitrary values to dates. + * + * ####Example: + * + * // Mongoose converts empty string '' into `null` for date types. You + * // can create a custom caster to disable it. + * const original = mongoose.Schema.Types.Date.cast(); + * mongoose.Schema.Types.Date.cast(v => { + * assert.ok(v !== ''); + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.Schema.Types.Date.cast(false); + * + * @param {Function} caster + * @return {Function} + * @function get + * @static + * @api public + */ + +SchemaDate.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; + + return this._cast; +}; + +/*! + * ignore + */ + +SchemaDate._defaultCaster = v => { + if (v != null && !(v instanceof Date)) { + throw new Error(); + } + return v; +}; + +/** + * Declares a TTL index (rounded to the nearest second) for _Date_ types only. + * + * This sets the `expireAfterSeconds` index option available in MongoDB >= 2.1.2. + * This index type is only compatible with Date types. + * + * ####Example: + * + * // expire in 24 hours + * new Schema({ createdAt: { type: Date, expires: 60*60*24 }}); + * + * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax: + * + * ####Example: + * + * // expire in 24 hours + * new Schema({ createdAt: { type: Date, expires: '24h' }}); + * + * // expire in 1.5 hours + * new Schema({ createdAt: { type: Date, expires: '1.5h' }}); + * + * // expire in 7 days + * const schema = new Schema({ createdAt: Date }); + * schema.path('createdAt').expires('7d'); + * + * @param {Number|String} when + * @added 3.0.0 + * @return {SchemaType} this + * @api public + */ + +SchemaDate.prototype.expires = function(when) { + if (getConstructorName(this._index) !== 'Object') { + this._index = {}; + } + + this._index.expires = when; + utils.expires(this._index); + return this; +}; + +/*! + * ignore + */ + +SchemaDate._checkRequired = v => v instanceof Date; + +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * ####Example: + * + * // Allow empty strings to pass `required` check + * mongoose.Schema.Types.String.checkRequired(v => v != null); + * + * const M = mongoose.model({ str: { type: String, required: true } }); + * new M({ str: '' }).validateSync(); // `null`, validation passes! + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ + +SchemaDate.checkRequired = SchemaType.checkRequired; + +/** + * Check if the given value satisfies a required validator. To satisfy + * a required validator, the given value must be an instance of `Date`. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ + +SchemaDate.prototype.checkRequired = function(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + SchemaDate.checkRequired(); + return _checkRequired(value); +}; + +/** + * Sets a minimum date validator. + * + * ####Example: + * + * const s = new Schema({ d: { type: Date, min: Date('1970-01-01') }) + * const M = db.model('M', s) + * const m = new M({ d: Date('1969-12-31') }) + * m.save(function (err) { + * console.error(err) // validator error + * m.d = Date('2014-12-08'); + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MIN} token which will be replaced with the invalid value + * const min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; + * const schema = new Schema({ d: { type: Date, min: min }) + * const M = mongoose.model('M', schema); + * const s= new M({ d: Date('1969-12-31') }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01). + * }) + * + * @param {Date} value minimum date + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaDate.prototype.min = function(value, message) { + if (this.minValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minValidator; + }, this); + } + + if (value) { + let msg = message || MongooseError.messages.Date.min; + if (typeof msg === 'string') { + msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : value.toString())); + } + const _this = this; + this.validators.push({ + validator: this.minValidator = function(val) { + let _value = value; + if (typeof value === 'function' && value !== Date.now) { + _value = _value.call(this); + } + const min = (_value === Date.now ? _value() : _this.cast(_value)); + return val === null || val.valueOf() >= min.valueOf(); + }, + message: msg, + type: 'min', + min: value + }); + } + + return this; +}; + +/** + * Sets a maximum date validator. + * + * ####Example: + * + * const s = new Schema({ d: { type: Date, max: Date('2014-01-01') }) + * const M = db.model('M', s) + * const m = new M({ d: Date('2014-12-08') }) + * m.save(function (err) { + * console.error(err) // validator error + * m.d = Date('2013-12-31'); + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAX} token which will be replaced with the invalid value + * const max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; + * const schema = new Schema({ d: { type: Date, max: max }) + * const M = mongoose.model('M', schema); + * const s= new M({ d: Date('2014-12-08') }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01). + * }) + * + * @param {Date} maximum date + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaDate.prototype.max = function(value, message) { + if (this.maxValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxValidator; + }, this); + } + + if (value) { + let msg = message || MongooseError.messages.Date.max; + if (typeof msg === 'string') { + msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : value.toString())); + } + const _this = this; + this.validators.push({ + validator: this.maxValidator = function(val) { + let _value = value; + if (typeof _value === 'function' && _value !== Date.now) { + _value = _value.call(this); + } + const max = (_value === Date.now ? _value() : _this.cast(_value)); + return val === null || val.valueOf() <= max.valueOf(); + }, + message: msg, + type: 'max', + max: value + }); + } + + return this; +}; + +/** + * Casts to date + * + * @param {Object} value to cast + * @api private + */ + +SchemaDate.prototype.cast = function(value) { + let castDate; + if (typeof this._castFunction === 'function') { + castDate = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castDate = this.constructor.cast(); + } else { + castDate = SchemaDate.cast(); + } + + try { + return castDate(value); + } catch (error) { + throw new CastError('date', value, this.path, error, this); + } +}; + +/*! + * Date Query casting. + * + * @api private + */ + +function handleSingle(val) { + return this.cast(val); +} + +SchemaDate.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); + + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaDate.prototype.castForQuery = function($conditional, val) { + if (arguments.length !== 2) { + return this._castForQuery($conditional); + } + + const handler = this.$conditionalHandlers[$conditional]; + + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Date.'); + } + + return handler.call(this, val); +}; + +/*! + * Module exports. + */ + +module.exports = SchemaDate; diff --git a/node_modules/mongoose/lib/schema/decimal128.js b/node_modules/mongoose/lib/schema/decimal128.js new file mode 100644 index 0000000..9c0e1d4 --- /dev/null +++ b/node_modules/mongoose/lib/schema/decimal128.js @@ -0,0 +1,210 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const SchemaType = require('../schematype'); +const CastError = SchemaType.CastError; +const Decimal128Type = require('../types/decimal128'); +const castDecimal128 = require('../cast/decimal128'); +const utils = require('../utils'); + +/** + * Decimal128 SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function Decimal128(key, options) { + SchemaType.call(this, key, options, 'Decimal128'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +Decimal128.schemaName = 'Decimal128'; + +Decimal128.defaultOptions = {}; + +/*! + * Inherits from SchemaType. + */ +Decimal128.prototype = Object.create(SchemaType.prototype); +Decimal128.prototype.constructor = Decimal128; + +/*! + * ignore + */ + +Decimal128._cast = castDecimal128; + +/** + * Sets a default option for all Decimal128 instances. + * + * ####Example: + * + * // Make all decimal 128s have `required` of true by default. + * mongoose.Schema.Decimal128.set('required', true); + * + * const User = mongoose.model('User', new Schema({ test: mongoose.Decimal128 })); + * new User({ }).validateSync().errors.test.message; // Path `test` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ + +Decimal128.set = SchemaType.set; + +/** + * Get/set the function used to cast arbitrary values to decimals. + * + * ####Example: + * + * // Make Mongoose only refuse to cast numbers as decimal128 + * const original = mongoose.Schema.Types.Decimal128.cast(); + * mongoose.Decimal128.cast(v => { + * assert.ok(typeof v !== 'number'); + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.Decimal128.cast(false); + * + * @param {Function} [caster] + * @return {Function} + * @function get + * @static + * @api public + */ + +Decimal128.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; + + return this._cast; +}; + +/*! + * ignore + */ + +Decimal128._defaultCaster = v => { + if (v != null && !(v instanceof Decimal128Type)) { + throw new Error(); + } + return v; +}; + +/*! + * ignore + */ + +Decimal128._checkRequired = v => v instanceof Decimal128Type; + +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ + +Decimal128.checkRequired = SchemaType.checkRequired; + +/** + * Check if the given value satisfies a required validator. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ + +Decimal128.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + Decimal128.checkRequired(); + + return _checkRequired(value); +}; + +/** + * Casts to Decimal128 + * + * @param {Object} value + * @param {Object} doc + * @param {Boolean} init whether this is an initialization cast + * @api private + */ + +Decimal128.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + if (value instanceof Decimal128Type) { + return value; + } + + return this._castRef(value, doc, init); + } + + let castDecimal128; + if (typeof this._castFunction === 'function') { + castDecimal128 = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castDecimal128 = this.constructor.cast(); + } else { + castDecimal128 = Decimal128.cast(); + } + + try { + return castDecimal128(value); + } catch (error) { + throw new CastError('Decimal128', value, this.path, error, this); + } +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.cast(val); +} + +Decimal128.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); + +/*! + * Module exports. + */ + +module.exports = Decimal128; diff --git a/node_modules/mongoose/lib/schema/documentarray.js b/node_modules/mongoose/lib/schema/documentarray.js new file mode 100644 index 0000000..80a3747 --- /dev/null +++ b/node_modules/mongoose/lib/schema/documentarray.js @@ -0,0 +1,583 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const ArrayType = require('./array'); +const CastError = require('../error/cast'); +const EventEmitter = require('events').EventEmitter; +const SchemaDocumentArrayOptions = + require('../options/SchemaDocumentArrayOptions'); +const SchemaType = require('../schematype'); +const discriminator = require('../helpers/model/discriminator'); +const get = require('../helpers/get'); +const handleIdOption = require('../helpers/schema/handleIdOption'); +const util = require('util'); +const utils = require('../utils'); +const getConstructor = require('../helpers/discriminator/getConstructor'); + +const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol; +const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; +const documentArrayParent = require('../helpers/symbols').documentArrayParent; + +let MongooseDocumentArray; +let Subdocument; + +/** + * SubdocsArray SchemaType constructor + * + * @param {String} key + * @param {Schema} schema + * @param {Object} options + * @inherits SchemaArray + * @api public + */ + +function DocumentArrayPath(key, schema, options, schemaOptions) { + if (schemaOptions != null && schemaOptions._id != null) { + schema = handleIdOption(schema, schemaOptions); + } else if (options != null && options._id != null) { + schema = handleIdOption(schema, options); + } + + const EmbeddedDocument = _createConstructor(schema, options); + EmbeddedDocument.prototype.$basePath = key; + + ArrayType.call(this, key, EmbeddedDocument, options); + + this.schema = schema; + this.schemaOptions = schemaOptions || {}; + this.$isMongooseDocumentArray = true; + this.Constructor = EmbeddedDocument; + + EmbeddedDocument.base = schema.base; + + const fn = this.defaultValue; + + if (!('defaultValue' in this) || fn !== void 0) { + this.default(function() { + let arr = fn.call(this); + if (!Array.isArray(arr)) { + arr = [arr]; + } + // Leave it up to `cast()` to convert this to a documentarray + return arr; + }); + } + + const parentSchemaType = this; + this.$embeddedSchemaType = new SchemaType(key + '.$', { + required: get(this, 'schemaOptions.required', false) + }); + this.$embeddedSchemaType.cast = function(value, doc, init) { + return parentSchemaType.cast(value, doc, init)[0]; + }; + this.$embeddedSchemaType.$isMongooseDocumentArrayElement = true; + this.$embeddedSchemaType.caster = this.Constructor; + this.$embeddedSchemaType.schema = this.schema; +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +DocumentArrayPath.schemaName = 'DocumentArray'; + +/** + * Options for all document arrays. + * + * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. + * + * @api public + */ + +DocumentArrayPath.options = { castNonArrays: true }; + +/*! + * Inherits from ArrayType. + */ +DocumentArrayPath.prototype = Object.create(ArrayType.prototype); +DocumentArrayPath.prototype.constructor = DocumentArrayPath; +DocumentArrayPath.prototype.OptionsConstructor = SchemaDocumentArrayOptions; + +/*! + * Ignore + */ + +function _createConstructor(schema, options, baseClass) { + Subdocument || (Subdocument = require('../types/ArraySubdocument')); + + // compile an embedded document for this schema + function EmbeddedDocument() { + Subdocument.apply(this, arguments); + + this.$session(this.ownerDocument().$session()); + } + + schema._preCompile(); + + const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype; + EmbeddedDocument.prototype = Object.create(proto); + EmbeddedDocument.prototype.$__setSchema(schema); + EmbeddedDocument.schema = schema; + EmbeddedDocument.prototype.constructor = EmbeddedDocument; + EmbeddedDocument.$isArraySubdocument = true; + EmbeddedDocument.events = new EventEmitter(); + + // apply methods + for (const i in schema.methods) { + EmbeddedDocument.prototype[i] = schema.methods[i]; + } + + // apply statics + for (const i in schema.statics) { + EmbeddedDocument[i] = schema.statics[i]; + } + + for (const i in EventEmitter.prototype) { + EmbeddedDocument[i] = EventEmitter.prototype[i]; + } + + EmbeddedDocument.options = options; + + return EmbeddedDocument; +} + +/** + * Adds a discriminator to this document array. + * + * ####Example: + * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); + * const schema = Schema({ shapes: [shapeSchema] }); + * + * const docArrayPath = parentSchema.path('shapes'); + * docArrayPath.discriminator('Circle', Schema({ radius: Number })); + * + * @param {String} name + * @param {Schema} schema fields to add to the schema for instances of this sub-class + * @param {Object|string} [options] If string, same as `options.value`. + * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. + * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning. + * @see discriminators /docs/discriminators.html + * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model + * @api public + */ + +DocumentArrayPath.prototype.discriminator = function(name, schema, options) { + if (typeof name === 'function') { + name = utils.getFunctionName(name); + } + + options = options || {}; + const tiedValue = utils.isPOJO(options) ? options.value : options; + const clone = get(options, 'clone', true); + + if (schema.instanceOfSchema && clone) { + schema = schema.clone(); + } + + schema = discriminator(this.casterConstructor, name, schema, tiedValue); + + const EmbeddedDocument = _createConstructor(schema, null, this.casterConstructor); + EmbeddedDocument.baseCasterConstructor = this.casterConstructor; + + try { + Object.defineProperty(EmbeddedDocument, 'name', { + value: name + }); + } catch (error) { + // Ignore error, only happens on old versions of node + } + + this.casterConstructor.discriminators[name] = EmbeddedDocument; + + return this.casterConstructor.discriminators[name]; +}; + +/** + * Performs local validations first, then validations on each embedded doc + * + * @api private + */ + +DocumentArrayPath.prototype.doValidate = function(array, fn, scope, options) { + // lazy load + MongooseDocumentArray || (MongooseDocumentArray = require('../types/DocumentArray')); + + const _this = this; + try { + SchemaType.prototype.doValidate.call(this, array, cb, scope); + } catch (err) { + return fn(err); + } + + function cb(err) { + if (err) { + return fn(err); + } + + let count = array && array.length; + let error; + + if (!count) { + return fn(); + } + if (options && options.updateValidator) { + return fn(); + } + if (!array.isMongooseDocumentArray) { + array = new MongooseDocumentArray(array, _this.path, scope); + } + + // handle sparse arrays, do not use array.forEach which does not + // iterate over sparse elements yet reports array.length including + // them :( + + function callback(err) { + if (err != null) { + error = err; + } + --count || fn(error); + } + + for (let i = 0, len = count; i < len; ++i) { + // sidestep sparse entries + let doc = array[i]; + if (doc == null) { + --count || fn(error); + continue; + } + + // If you set the array index directly, the doc might not yet be + // a full fledged mongoose subdoc, so make it into one. + if (!(doc instanceof Subdocument)) { + const Constructor = getConstructor(_this.casterConstructor, array[i]); + doc = array[i] = new Constructor(doc, array, undefined, undefined, i); + } + + if (options != null && options.validateModifiedOnly && !doc.$isModified()) { + --count || fn(error); + continue; + } + + doc.$__validate(callback); + } + } +}; + +/** + * Performs local validations first, then validations on each embedded doc. + * + * ####Note: + * + * This method ignores the asynchronous validators. + * + * @return {MongooseError|undefined} + * @api private + */ + +DocumentArrayPath.prototype.doValidateSync = function(array, scope, options) { + const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope); + if (schemaTypeError != null) { + return schemaTypeError; + } + + const count = array && array.length; + let resultError = null; + + if (!count) { + return; + } + + // handle sparse arrays, do not use array.forEach which does not + // iterate over sparse elements yet reports array.length including + // them :( + + for (let i = 0, len = count; i < len; ++i) { + // sidestep sparse entries + let doc = array[i]; + if (!doc) { + continue; + } + + // If you set the array index directly, the doc might not yet be + // a full fledged mongoose subdoc, so make it into one. + if (!(doc instanceof Subdocument)) { + const Constructor = getConstructor(this.casterConstructor, array[i]); + doc = array[i] = new Constructor(doc, array, undefined, undefined, i); + } + + if (options != null && options.validateModifiedOnly && !doc.$isModified()) { + continue; + } + + const subdocValidateError = doc.validateSync(); + + if (subdocValidateError && resultError == null) { + resultError = subdocValidateError; + } + } + + return resultError; +}; + +/*! + * ignore + */ + +DocumentArrayPath.prototype.getDefault = function(scope) { + let ret = typeof this.defaultValue === 'function' + ? this.defaultValue.call(scope) + : this.defaultValue; + + if (ret == null) { + return ret; + } + + // lazy load + MongooseDocumentArray || (MongooseDocumentArray = require('../types/DocumentArray')); + + if (!Array.isArray(ret)) { + ret = [ret]; + } + + ret = new MongooseDocumentArray(ret, this.path, scope); + + for (let i = 0; i < ret.length; ++i) { + const Constructor = getConstructor(this.casterConstructor, ret[i]); + const _subdoc = new Constructor({}, ret, undefined, + undefined, i); + _subdoc.$init(ret[i]); + _subdoc.isNew = true; + + // Make sure all paths in the subdoc are set to `default` instead + // of `init` since we used `init`. + Object.assign(_subdoc.$__.activePaths.default, _subdoc.$__.activePaths.init); + _subdoc.$__.activePaths.init = {}; + + ret[i] = _subdoc; + } + + return ret; +}; + +/** + * Casts contents + * + * @param {Object} value + * @param {Document} document that triggers the casting + * @api private + */ + +DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) { + // lazy load + MongooseDocumentArray || (MongooseDocumentArray = require('../types/DocumentArray')); + + // Skip casting if `value` is the same as the previous value, no need to cast. See gh-9266 + if (value != null && value[arrayPathSymbol] != null && value === prev) { + return value; + } + + let selected; + let subdoc; + const _opts = { transform: false, virtuals: false }; + options = options || {}; + + if (!Array.isArray(value)) { + if (!init && !DocumentArrayPath.options.castNonArrays) { + throw new CastError('DocumentArray', util.inspect(value), this.path, null, this); + } + // gh-2442 mark whole array as modified if we're initializing a doc from + // the db and the path isn't an array in the document + if (!!doc && init) { + doc.markModified(this.path); + } + return this.cast([value], doc, init, prev, options); + } + + if (!(value && value.isMongooseDocumentArray) && + !options.skipDocumentArrayCast) { + value = new MongooseDocumentArray(value, this.path, doc); + } else if (value && value.isMongooseDocumentArray) { + // We need to create a new array, otherwise change tracking will + // update the old doc (gh-4449) + value = new MongooseDocumentArray(value, this.path, doc); + } + + if (prev != null) { + value[arrayAtomicsSymbol] = prev[arrayAtomicsSymbol] || {}; + } + + if (options.arrayPathIndex != null) { + value[arrayPathSymbol] = this.path + '.' + options.arrayPathIndex; + } + + const rawArray = value.isMongooseDocumentArrayProxy ? value.__array : value; + + const len = rawArray.length; + const initDocumentOptions = { skipId: true, willInit: true }; + + for (let i = 0; i < len; ++i) { + if (!rawArray[i]) { + continue; + } + + const Constructor = getConstructor(this.casterConstructor, value[i]); + + // Check if the document has a different schema (re gh-3701) + if (rawArray[i].$__ && !(rawArray[i] instanceof Constructor)) { + rawArray[i] = rawArray[i].toObject({ + transform: false, + // Special case: if different model, but same schema, apply virtuals + // re: gh-7898 + virtuals: rawArray[i].schema === Constructor.schema + }); + } + + if (rawArray[i] instanceof Subdocument) { + if (rawArray[i][documentArrayParent] !== doc) { + if (init) { + const subdoc = new Constructor(null, value, initDocumentOptions, selected, i); + rawArray[i] = subdoc.$init(rawArray[i]); + } else { + const subdoc = new Constructor(rawArray[i], value, undefined, undefined, i); + rawArray[i] = subdoc; + } + } + // Might not have the correct index yet, so ensure it does. + if (rawArray[i].__index == null) { + rawArray[i].$setIndex(i); + } + } else if (rawArray[i] != null) { + if (init) { + if (doc) { + selected || (selected = scopePaths(this, doc.$__.selected, init)); + } else { + selected = true; + } + + subdoc = new Constructor(null, value, initDocumentOptions, selected, i); + rawArray[i] = subdoc.$init(rawArray[i]); + } else { + if (prev && typeof prev.id === 'function') { + subdoc = prev.id(rawArray[i]._id); + } + + if (prev && subdoc && utils.deepEqual(subdoc.toObject(_opts), rawArray[i])) { + // handle resetting doc with existing id and same data + subdoc.set(rawArray[i]); + // if set() is hooked it will have no return value + // see gh-746 + rawArray[i] = subdoc; + } else { + try { + subdoc = new Constructor(rawArray[i], value, undefined, + undefined, i); + // if set() is hooked it will have no return value + // see gh-746 + rawArray[i] = subdoc; + } catch (error) { + const valueInErrorMessage = util.inspect(rawArray[i]); + throw new CastError('embedded', valueInErrorMessage, + value[arrayPathSymbol], error, this); + } + } + } + } + } + + return value; +}; + +/*! + * ignore + */ + +DocumentArrayPath.prototype.clone = function() { + const options = Object.assign({}, this.options); + const schematype = new this.constructor(this.path, this.schema, options, this.schemaOptions); + schematype.validators = this.validators.slice(); + if (this.requiredValidator !== undefined) { + schematype.requiredValidator = this.requiredValidator; + } + schematype.Constructor.discriminators = Object.assign({}, + this.Constructor.discriminators); + return schematype; +}; + +/*! + * ignore + */ + +DocumentArrayPath.prototype.applyGetters = function(value, scope) { + return SchemaType.prototype.applyGetters.call(this, value, scope); +}; + +/*! + * Scopes paths selected in a query to this array. + * Necessary for proper default application of subdocument values. + * + * @param {DocumentArrayPath} array - the array to scope `fields` paths + * @param {Object|undefined} fields - the root fields selected in the query + * @param {Boolean|undefined} init - if we are being created part of a query result + */ + +function scopePaths(array, fields, init) { + if (!(init && fields)) { + return undefined; + } + + const path = array.path + '.'; + const keys = Object.keys(fields); + let i = keys.length; + const selected = {}; + let hasKeys; + let key; + let sub; + + while (i--) { + key = keys[i]; + if (key.startsWith(path)) { + sub = key.substring(path.length); + if (sub === '$') { + continue; + } + if (sub.startsWith('$.')) { + sub = sub.substr(2); + } + hasKeys || (hasKeys = true); + selected[sub] = fields[key]; + } + } + + return hasKeys && selected || undefined; +} + +/** + * Sets a default option for all DocumentArray instances. + * + * ####Example: + * + * // Make all numbers have option `min` equal to 0. + * mongoose.Schema.DocumentArray.set('_id', false); + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ + +DocumentArrayPath.defaultOptions = {}; + +DocumentArrayPath.set = SchemaType.set; + +/*! + * Module exports. + */ + +module.exports = DocumentArrayPath; diff --git a/node_modules/mongoose/lib/schema/index.js b/node_modules/mongoose/lib/schema/index.js new file mode 100644 index 0000000..999bef7 --- /dev/null +++ b/node_modules/mongoose/lib/schema/index.js @@ -0,0 +1,37 @@ + +/*! + * Module exports. + */ + +'use strict'; + +exports.String = require('./string'); + +exports.Number = require('./number'); + +exports.Boolean = require('./boolean'); + +exports.DocumentArray = require('./documentarray'); + +exports.Subdocument = require('./SubdocumentPath'); + +exports.Array = require('./array'); + +exports.Buffer = require('./buffer'); + +exports.Date = require('./date'); + +exports.ObjectId = require('./objectid'); + +exports.Mixed = require('./mixed'); + +exports.Decimal128 = exports.Decimal = require('./decimal128'); + +exports.Map = require('./map'); + +// alias + +exports.Oid = exports.ObjectId; +exports.Object = exports.Mixed; +exports.Bool = exports.Boolean; +exports.ObjectID = exports.ObjectId; diff --git a/node_modules/mongoose/lib/schema/map.js b/node_modules/mongoose/lib/schema/map.js new file mode 100644 index 0000000..e81dccf --- /dev/null +++ b/node_modules/mongoose/lib/schema/map.js @@ -0,0 +1,76 @@ +'use strict'; + +/*! + * ignore + */ + +const MongooseMap = require('../types/map'); +const SchemaMapOptions = require('../options/SchemaMapOptions'); +const SchemaType = require('../schematype'); +/*! + * ignore + */ + +class Map extends SchemaType { + constructor(key, options) { + super(key, options, 'Map'); + this.$isSchemaMap = true; + } + + set(option, value) { + return SchemaType.set(option, value); + } + + cast(val, doc, init) { + if (val instanceof MongooseMap) { + return val; + } + + const path = this.path; + + if (init) { + const map = new MongooseMap({}, path, doc, this.$__schemaType); + + if (val instanceof global.Map) { + for (const key of val.keys()) { + let _val = val.get(key); + if (_val == null) { + _val = map.$__schemaType._castNullish(_val); + } else { + _val = map.$__schemaType.cast(_val, doc, true, null, { path: path + '.' + key }); + } + map.$init(key, _val); + } + } else { + for (const key of Object.keys(val)) { + let _val = val[key]; + if (_val == null) { + _val = map.$__schemaType._castNullish(_val); + } else { + _val = map.$__schemaType.cast(_val, doc, true, null, { path: path + '.' + key }); + } + map.$init(key, _val); + } + } + + return map; + } + + return new MongooseMap(val, path, doc, this.$__schemaType); + } + + clone() { + const schematype = super.clone(); + + if (this.$__schemaType != null) { + schematype.$__schemaType = this.$__schemaType.clone(); + } + return schematype; + } +} + +Map.prototype.OptionsConstructor = SchemaMapOptions; + +Map.defaultOptions = {}; + +module.exports = Map; diff --git a/node_modules/mongoose/lib/schema/mixed.js b/node_modules/mongoose/lib/schema/mixed.js new file mode 100644 index 0000000..09944bf --- /dev/null +++ b/node_modules/mongoose/lib/schema/mixed.js @@ -0,0 +1,132 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const SchemaType = require('../schematype'); +const symbols = require('./symbols'); +const isObject = require('../helpers/isObject'); +const utils = require('../utils'); + +/** + * Mixed SchemaType constructor. + * + * @param {String} path + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function Mixed(path, options) { + if (options && options.default) { + const def = options.default; + if (Array.isArray(def) && def.length === 0) { + // make sure empty array defaults are handled + options.default = Array; + } else if (!options.shared && isObject(def) && Object.keys(def).length === 0) { + // prevent odd "shared" objects between documents + options.default = function() { + return {}; + }; + } + } + + SchemaType.call(this, path, options, 'Mixed'); + + this[symbols.schemaMixedSymbol] = true; +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +Mixed.schemaName = 'Mixed'; + +Mixed.defaultOptions = {}; + +/*! + * Inherits from SchemaType. + */ +Mixed.prototype = Object.create(SchemaType.prototype); +Mixed.prototype.constructor = Mixed; + +/** + * Attaches a getter for all Mixed paths. + * + * ####Example: + * + * // Hide the 'hidden' path + * mongoose.Schema.Mixed.get(v => Object.assign({}, v, { hidden: null })); + * + * const Model = mongoose.model('Test', new Schema({ test: {} })); + * new Model({ test: { hidden: 'Secret!' } }).test.hidden; // null + * + * @param {Function} getter + * @return {this} + * @function get + * @static + * @api public + */ + +Mixed.get = SchemaType.get; + +/** + * Sets a default option for all Mixed instances. + * + * ####Example: + * + * // Make all mixed instances have `required` of true by default. + * mongoose.Schema.Mixed.set('required', true); + * + * const User = mongoose.model('User', new Schema({ test: mongoose.Mixed })); + * new User({ }).validateSync().errors.test.message; // Path `test` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ + +Mixed.set = SchemaType.set; + +/** + * Casts `val` for Mixed. + * + * _this is a no-op_ + * + * @param {Object} value to cast + * @api private + */ + +Mixed.prototype.cast = function(val) { + if (val instanceof Error) { + return utils.errorToPOJO(val); + } + return val; +}; + +/** + * Casts contents for queries. + * + * @param {String} $cond + * @param {any} [val] + * @api private + */ + +Mixed.prototype.castForQuery = function($cond, val) { + if (arguments.length === 2) { + return val; + } + return $cond; +}; + +/*! + * Module exports. + */ + +module.exports = Mixed; diff --git a/node_modules/mongoose/lib/schema/number.js b/node_modules/mongoose/lib/schema/number.js new file mode 100644 index 0000000..77e51bb --- /dev/null +++ b/node_modules/mongoose/lib/schema/number.js @@ -0,0 +1,440 @@ +'use strict'; + +/*! + * Module requirements. + */ + +const MongooseError = require('../error/index'); +const SchemaNumberOptions = require('../options/SchemaNumberOptions'); +const SchemaType = require('../schematype'); +const castNumber = require('../cast/number'); +const handleBitwiseOperator = require('./operators/bitwise'); +const utils = require('../utils'); + +const CastError = SchemaType.CastError; + +/** + * Number SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaNumber(key, options) { + SchemaType.call(this, key, options, 'Number'); +} + +/** + * Attaches a getter for all Number instances. + * + * ####Example: + * + * // Make all numbers round down + * mongoose.Number.get(function(v) { return Math.floor(v); }); + * + * const Model = mongoose.model('Test', new Schema({ test: Number })); + * new Model({ test: 3.14 }).test; // 3 + * + * @param {Function} getter + * @return {this} + * @function get + * @static + * @api public + */ + +SchemaNumber.get = SchemaType.get; + +/** + * Sets a default option for all Number instances. + * + * ####Example: + * + * // Make all numbers have option `min` equal to 0. + * mongoose.Schema.Number.set('min', 0); + * + * const Order = mongoose.model('Order', new Schema({ amount: Number })); + * new Order({ amount: -10 }).validateSync().errors.amount.message; // Path `amount` must be larger than 0. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ + +SchemaNumber.set = SchemaType.set; + +/*! + * ignore + */ + +SchemaNumber._cast = castNumber; + +/** + * Get/set the function used to cast arbitrary values to numbers. + * + * ####Example: + * + * // Make Mongoose cast empty strings '' to 0 for paths declared as numbers + * const original = mongoose.Number.cast(); + * mongoose.Number.cast(v => { + * if (v === '') { return 0; } + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.Number.cast(false); + * + * @param {Function} caster + * @return {Function} + * @function get + * @static + * @api public + */ + +SchemaNumber.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; + + return this._cast; +}; + +/*! + * ignore + */ + +SchemaNumber._defaultCaster = v => { + if (typeof v !== 'number') { + throw new Error(); + } + return v; +}; + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaNumber.schemaName = 'Number'; + +SchemaNumber.defaultOptions = {}; + +/*! + * Inherits from SchemaType. + */ +SchemaNumber.prototype = Object.create(SchemaType.prototype); +SchemaNumber.prototype.constructor = SchemaNumber; +SchemaNumber.prototype.OptionsConstructor = SchemaNumberOptions; + +/*! + * ignore + */ + +SchemaNumber._checkRequired = v => typeof v === 'number' || v instanceof Number; + +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ + +SchemaNumber.checkRequired = SchemaType.checkRequired; + +/** + * Check if the given value satisfies a required validator. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ + +SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + SchemaNumber.checkRequired(); + + return _checkRequired(value); +}; + +/** + * Sets a minimum number validator. + * + * ####Example: + * + * const s = new Schema({ n: { type: Number, min: 10 }) + * const M = db.model('M', s) + * const m = new M({ n: 9 }) + * m.save(function (err) { + * console.error(err) // validator error + * m.n = 10; + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MIN} token which will be replaced with the invalid value + * const min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; + * const schema = new Schema({ n: { type: Number, min: min }) + * const M = mongoose.model('Measurement', schema); + * const s= new M({ n: 4 }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10). + * }) + * + * @param {Number} value minimum number + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaNumber.prototype.min = function(value, message) { + if (this.minValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minValidator; + }, this); + } + + if (value !== null && value !== undefined) { + let msg = message || MongooseError.messages.Number.min; + msg = msg.replace(/{MIN}/, value); + this.validators.push({ + validator: this.minValidator = function(v) { + return v == null || v >= value; + }, + message: msg, + type: 'min', + min: value + }); + } + + return this; +}; + +/** + * Sets a maximum number validator. + * + * ####Example: + * + * const s = new Schema({ n: { type: Number, max: 10 }) + * const M = db.model('M', s) + * const m = new M({ n: 11 }) + * m.save(function (err) { + * console.error(err) // validator error + * m.n = 10; + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAX} token which will be replaced with the invalid value + * const max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; + * const schema = new Schema({ n: { type: Number, max: max }) + * const M = mongoose.model('Measurement', schema); + * const s= new M({ n: 4 }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10). + * }) + * + * @param {Number} maximum number + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaNumber.prototype.max = function(value, message) { + if (this.maxValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxValidator; + }, this); + } + + if (value !== null && value !== undefined) { + let msg = message || MongooseError.messages.Number.max; + msg = msg.replace(/{MAX}/, value); + this.validators.push({ + validator: this.maxValidator = function(v) { + return v == null || v <= value; + }, + message: msg, + type: 'max', + max: value + }); + } + + return this; +}; + +/** + * Sets a enum validator + * + * ####Example: + * + * const s = new Schema({ n: { type: Number, enum: [1, 2, 3] }); + * const M = db.model('M', s); + * + * const m = new M({ n: 4 }); + * await m.save(); // throws validation error + * + * m.n = 3; + * await m.save(); // succeeds + * + * @param {Array} values allowed values + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaNumber.prototype.enum = function(values, message) { + if (this.enumValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.enumValidator; + }, this); + } + + + if (!Array.isArray(values)) { + const isObjectSyntax = utils.isPOJO(values) && values.values != null; + if (isObjectSyntax) { + message = values.message; + values = values.values; + } else if (typeof values === 'number') { + values = Array.prototype.slice.call(arguments); + message = null; + } + + if (utils.isPOJO(values)) { + values = Object.values(values); + } + message = message || MongooseError.messages.Number.enum; + } + + message = message == null ? MongooseError.messages.Number.enum : message; + + this.enumValidator = v => v == null || values.indexOf(v) !== -1; + this.validators.push({ + validator: this.enumValidator, + message: message, + type: 'enum', + enumValues: values + }); + + return this; +}; + +/** + * Casts to number + * + * @param {Object} value value to cast + * @param {Document} doc document that triggers the casting + * @param {Boolean} init + * @api private + */ + +SchemaNumber.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + if (typeof value === 'number') { + return value; + } + + return this._castRef(value, doc, init); + } + + const val = value && typeof value._id !== 'undefined' ? + value._id : // documents + value; + + let castNumber; + if (typeof this._castFunction === 'function') { + castNumber = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castNumber = this.constructor.cast(); + } else { + castNumber = SchemaNumber.cast(); + } + + try { + return castNumber(val); + } catch (err) { + throw new CastError('Number', val, this.path, err, this); + } +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.cast(val); +} + +function handleArray(val) { + const _this = this; + if (!Array.isArray(val)) { + return [this.cast(val)]; + } + return val.map(function(m) { + return _this.cast(m); + }); +} + +SchemaNumber.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $bitsAllClear: handleBitwiseOperator, + $bitsAnyClear: handleBitwiseOperator, + $bitsAllSet: handleBitwiseOperator, + $bitsAnySet: handleBitwiseOperator, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle, + $mod: handleArray + }); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaNumber.prototype.castForQuery = function($conditional, val) { + let handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new CastError('number', val, this.path, null, this); + } + return handler.call(this, val); + } + val = this._castForQuery($conditional); + return val; +}; + +/*! + * Module exports. + */ + +module.exports = SchemaNumber; diff --git a/node_modules/mongoose/lib/schema/objectid.js b/node_modules/mongoose/lib/schema/objectid.js new file mode 100644 index 0000000..9e481f1 --- /dev/null +++ b/node_modules/mongoose/lib/schema/objectid.js @@ -0,0 +1,297 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const SchemaObjectIdOptions = require('../options/SchemaObjectIdOptions'); +const SchemaType = require('../schematype'); +const castObjectId = require('../cast/objectid'); +const getConstructorName = require('../helpers/getConstructorName'); +const oid = require('../types/objectid'); +const utils = require('../utils'); + +const CastError = SchemaType.CastError; +let Document; + +/** + * ObjectId SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function ObjectId(key, options) { + const isKeyHexStr = typeof key === 'string' && key.length === 24 && /^[a-f0-9]+$/i.test(key); + const suppressWarning = options && options.suppressWarning; + if ((isKeyHexStr || typeof key === 'undefined') && !suppressWarning) { + utils.warn('mongoose: To create a new ObjectId please try ' + + '`Mongoose.Types.ObjectId` instead of using ' + + '`Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if ' + + 'you\'re trying to create a hex char path in your schema.'); + } + SchemaType.call(this, key, options, 'ObjectID'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +ObjectId.schemaName = 'ObjectId'; + +ObjectId.defaultOptions = {}; + +/*! + * Inherits from SchemaType. + */ +ObjectId.prototype = Object.create(SchemaType.prototype); +ObjectId.prototype.constructor = ObjectId; +ObjectId.prototype.OptionsConstructor = SchemaObjectIdOptions; + +/** + * Attaches a getter for all ObjectId instances + * + * ####Example: + * + * // Always convert to string when getting an ObjectId + * mongoose.ObjectId.get(v => v.toString()); + * + * const Model = mongoose.model('Test', new Schema({})); + * typeof (new Model({})._id); // 'string' + * + * @param {Function} getter + * @return {this} + * @function get + * @static + * @api public + */ + +ObjectId.get = SchemaType.get; + +/** + * Sets a default option for all ObjectId instances. + * + * ####Example: + * + * // Make all object ids have option `required` equal to true. + * mongoose.Schema.ObjectId.set('required', true); + * + * const Order = mongoose.model('Order', new Schema({ userId: ObjectId })); + * new Order({ }).validateSync().errors.userId.message; // Path `userId` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ + +ObjectId.set = SchemaType.set; + +/** + * Adds an auto-generated ObjectId default if turnOn is true. + * @param {Boolean} turnOn auto generated ObjectId defaults + * @api public + * @return {SchemaType} this + */ + +ObjectId.prototype.auto = function(turnOn) { + if (turnOn) { + this.default(defaultId); + this.set(resetId); + } + + return this; +}; + +/*! + * ignore + */ + +ObjectId._checkRequired = v => v instanceof oid; + +/*! + * ignore + */ + +ObjectId._cast = castObjectId; + +/** + * Get/set the function used to cast arbitrary values to objectids. + * + * ####Example: + * + * // Make Mongoose only try to cast length 24 strings. By default, any 12 + * // char string is a valid ObjectId. + * const original = mongoose.ObjectId.cast(); + * mongoose.ObjectId.cast(v => { + * assert.ok(typeof v !== 'string' || v.length === 24); + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.ObjectId.cast(false); + * + * @param {Function} caster + * @return {Function} + * @function get + * @static + * @api public + */ + +ObjectId.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; + + return this._cast; +}; + +/*! + * ignore + */ + +ObjectId._defaultCaster = v => { + if (!(v instanceof oid)) { + throw new Error(v + ' is not an instance of ObjectId'); + } + return v; +}; + +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * ####Example: + * + * // Allow empty strings to pass `required` check + * mongoose.Schema.Types.String.checkRequired(v => v != null); + * + * const M = mongoose.model({ str: { type: String, required: true } }); + * new M({ str: '' }).validateSync(); // `null`, validation passes! + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ + +ObjectId.checkRequired = SchemaType.checkRequired; + +/** + * Check if the given value satisfies a required validator. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ + +ObjectId.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + ObjectId.checkRequired(); + + return _checkRequired(value); +}; + +/** + * Casts to ObjectId + * + * @param {Object} value + * @param {Object} doc + * @param {Boolean} init whether this is an initialization cast + * @api private + */ + +ObjectId.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + // wait! we may need to cast this to a document + if (value instanceof oid) { + return value; + } else if ((getConstructorName(value) || '').toLowerCase() === 'objectid') { + return new oid(value.toHexString()); + } + + return this._castRef(value, doc, init); + } + + let castObjectId; + if (typeof this._castFunction === 'function') { + castObjectId = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castObjectId = this.constructor.cast(); + } else { + castObjectId = ObjectId.cast(); + } + + try { + return castObjectId(value); + } catch (error) { + throw new CastError('ObjectId', value, this.path, error, this); + } +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.cast(val); +} + +ObjectId.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); + +/*! + * ignore + */ + +function defaultId() { + return new oid(); +} + +defaultId.$runBeforeSetters = true; + +function resetId(v) { + Document || (Document = require('./../document')); + + if (this instanceof Document) { + if (v === void 0) { + const _v = new oid; + this.$__._id = _v; + return _v; + } + + this.$__._id = v; + } + + return v; +} + +/*! + * Module exports. + */ + +module.exports = ObjectId; diff --git a/node_modules/mongoose/lib/schema/operators/bitwise.js b/node_modules/mongoose/lib/schema/operators/bitwise.js new file mode 100644 index 0000000..07e18cd --- /dev/null +++ b/node_modules/mongoose/lib/schema/operators/bitwise.js @@ -0,0 +1,38 @@ +/*! + * Module requirements. + */ + +'use strict'; + +const CastError = require('../../error/cast'); + +/*! + * ignore + */ + +function handleBitwiseOperator(val) { + const _this = this; + if (Array.isArray(val)) { + return val.map(function(v) { + return _castNumber(_this.path, v); + }); + } else if (Buffer.isBuffer(val)) { + return val; + } + // Assume trying to cast to number + return _castNumber(_this.path, val); +} + +/*! + * ignore + */ + +function _castNumber(path, num) { + const v = Number(num); + if (isNaN(v)) { + throw new CastError('number', num, path); + } + return v; +} + +module.exports = handleBitwiseOperator; diff --git a/node_modules/mongoose/lib/schema/operators/exists.js b/node_modules/mongoose/lib/schema/operators/exists.js new file mode 100644 index 0000000..916b4cb --- /dev/null +++ b/node_modules/mongoose/lib/schema/operators/exists.js @@ -0,0 +1,12 @@ +'use strict'; + +const castBoolean = require('../../cast/boolean'); + +/*! + * ignore + */ + +module.exports = function(val) { + const path = this != null ? this.path : null; + return castBoolean(val, path); +}; diff --git a/node_modules/mongoose/lib/schema/operators/geospatial.js b/node_modules/mongoose/lib/schema/operators/geospatial.js new file mode 100644 index 0000000..80a6052 --- /dev/null +++ b/node_modules/mongoose/lib/schema/operators/geospatial.js @@ -0,0 +1,107 @@ +/*! + * Module requirements. + */ + +'use strict'; + +const castArraysOfNumbers = require('./helpers').castArraysOfNumbers; +const castToNumber = require('./helpers').castToNumber; + +/*! + * ignore + */ + +exports.cast$geoIntersects = cast$geoIntersects; +exports.cast$near = cast$near; +exports.cast$within = cast$within; + +function cast$near(val) { + const SchemaArray = require('../array'); + + if (Array.isArray(val)) { + castArraysOfNumbers(val, this); + return val; + } + + _castMinMaxDistance(this, val); + + if (val && val.$geometry) { + return cast$geometry(val, this); + } + + if (!Array.isArray(val)) { + throw new TypeError('$near must be either an array or an object ' + + 'with a $geometry property'); + } + + return SchemaArray.prototype.castForQuery.call(this, val); +} + +function cast$geometry(val, self) { + switch (val.$geometry.type) { + case 'Polygon': + case 'LineString': + case 'Point': + castArraysOfNumbers(val.$geometry.coordinates, self); + break; + default: + // ignore unknowns + break; + } + + _castMinMaxDistance(self, val); + + return val; +} + +function cast$within(val) { + _castMinMaxDistance(this, val); + + if (val.$box || val.$polygon) { + const type = val.$box ? '$box' : '$polygon'; + val[type].forEach(arr => { + if (!Array.isArray(arr)) { + const msg = 'Invalid $within $box argument. ' + + 'Expected an array, received ' + arr; + throw new TypeError(msg); + } + arr.forEach((v, i) => { + arr[i] = castToNumber.call(this, v); + }); + }); + } else if (val.$center || val.$centerSphere) { + const type = val.$center ? '$center' : '$centerSphere'; + val[type].forEach((item, i) => { + if (Array.isArray(item)) { + item.forEach((v, j) => { + item[j] = castToNumber.call(this, v); + }); + } else { + val[type][i] = castToNumber.call(this, item); + } + }); + } else if (val.$geometry) { + cast$geometry(val, this); + } + + return val; +} + +function cast$geoIntersects(val) { + const geo = val.$geometry; + if (!geo) { + return; + } + + cast$geometry(val, this); + return val; +} + +function _castMinMaxDistance(self, val) { + if (val.$maxDistance) { + val.$maxDistance = castToNumber.call(self, val.$maxDistance); + } + if (val.$minDistance) { + val.$minDistance = castToNumber.call(self, val.$minDistance); + } +} diff --git a/node_modules/mongoose/lib/schema/operators/helpers.js b/node_modules/mongoose/lib/schema/operators/helpers.js new file mode 100644 index 0000000..a17951c --- /dev/null +++ b/node_modules/mongoose/lib/schema/operators/helpers.js @@ -0,0 +1,32 @@ +'use strict'; + +/*! + * Module requirements. + */ + +const SchemaNumber = require('../number'); + +/*! + * @ignore + */ + +exports.castToNumber = castToNumber; +exports.castArraysOfNumbers = castArraysOfNumbers; + +/*! + * @ignore + */ + +function castToNumber(val) { + return SchemaNumber.cast()(val); +} + +function castArraysOfNumbers(arr, self) { + arr.forEach(function(v, i) { + if (Array.isArray(v)) { + castArraysOfNumbers(v, self); + } else { + arr[i] = castToNumber.call(self, v); + } + }); +} diff --git a/node_modules/mongoose/lib/schema/operators/text.js b/node_modules/mongoose/lib/schema/operators/text.js new file mode 100644 index 0000000..4b95916 --- /dev/null +++ b/node_modules/mongoose/lib/schema/operators/text.js @@ -0,0 +1,39 @@ +'use strict'; + +const CastError = require('../../error/cast'); +const castBoolean = require('../../cast/boolean'); +const castString = require('../../cast/string'); + +/*! + * Casts val to an object suitable for `$text`. Throws an error if the object + * can't be casted. + * + * @param {Any} val value to cast + * @param {String} [path] path to associate with any errors that occured + * @return {Object} casted object + * @see https://docs.mongodb.com/manual/reference/operator/query/text/ + * @api private + */ + +module.exports = function(val, path) { + if (val == null || typeof val !== 'object') { + throw new CastError('$text', val, path); + } + + if (val.$search != null) { + val.$search = castString(val.$search, path + '.$search'); + } + if (val.$language != null) { + val.$language = castString(val.$language, path + '.$language'); + } + if (val.$caseSensitive != null) { + val.$caseSensitive = castBoolean(val.$caseSensitive, + path + '.$castSensitive'); + } + if (val.$diacriticSensitive != null) { + val.$diacriticSensitive = castBoolean(val.$diacriticSensitive, + path + '.$diacriticSensitive'); + } + + return val; +}; diff --git a/node_modules/mongoose/lib/schema/operators/type.js b/node_modules/mongoose/lib/schema/operators/type.js new file mode 100644 index 0000000..952c790 --- /dev/null +++ b/node_modules/mongoose/lib/schema/operators/type.js @@ -0,0 +1,20 @@ +'use strict'; + +/*! + * ignore + */ + +module.exports = function(val) { + if (Array.isArray(val)) { + if (!val.every(v => typeof v === 'number' || typeof v === 'string')) { + throw new Error('$type array values must be strings or numbers'); + } + return val; + } + + if (typeof val !== 'number' && typeof val !== 'string') { + throw new Error('$type parameter must be number, string, or array of numbers and strings'); + } + + return val; +}; diff --git a/node_modules/mongoose/lib/schema/string.js b/node_modules/mongoose/lib/schema/string.js new file mode 100644 index 0000000..8db63d7 --- /dev/null +++ b/node_modules/mongoose/lib/schema/string.js @@ -0,0 +1,672 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const SchemaType = require('../schematype'); +const MongooseError = require('../error/index'); +const SchemaStringOptions = require('../options/SchemaStringOptions'); +const castString = require('../cast/string'); +const utils = require('../utils'); + +const CastError = SchemaType.CastError; + +/** + * String SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaString(key, options) { + this.enumValues = []; + this.regExp = null; + SchemaType.call(this, key, options, 'String'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaString.schemaName = 'String'; + +SchemaString.defaultOptions = {}; + +/*! + * Inherits from SchemaType. + */ +SchemaString.prototype = Object.create(SchemaType.prototype); +SchemaString.prototype.constructor = SchemaString; +Object.defineProperty(SchemaString.prototype, 'OptionsConstructor', { + configurable: false, + enumerable: false, + writable: false, + value: SchemaStringOptions +}); + +/*! + * ignore + */ + +SchemaString._cast = castString; + +/** + * Get/set the function used to cast arbitrary values to strings. + * + * ####Example: + * + * // Throw an error if you pass in an object. Normally, Mongoose allows + * // objects with custom `toString()` functions. + * const original = mongoose.Schema.Types.String.cast(); + * mongoose.Schema.Types.String.cast(v => { + * assert.ok(v == null || typeof v !== 'object'); + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.Schema.Types.String.cast(false); + * + * @param {Function} caster + * @return {Function} + * @function get + * @static + * @api public + */ + +SchemaString.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; + + return this._cast; +}; + +/*! + * ignore + */ + +SchemaString._defaultCaster = v => { + if (v != null && typeof v !== 'string') { + throw new Error(); + } + return v; +}; + +/** + * Attaches a getter for all String instances. + * + * ####Example: + * + * // Make all numbers round down + * mongoose.Schema.String.get(v => v.toLowerCase()); + * + * const Model = mongoose.model('Test', new Schema({ test: String })); + * new Model({ test: 'FOO' }).test; // 'foo' + * + * @param {Function} getter + * @return {this} + * @function get + * @static + * @api public + */ + +SchemaString.get = SchemaType.get; + +/** + * Sets a default option for all String instances. + * + * ####Example: + * + * // Make all strings have option `trim` equal to true. + * mongoose.Schema.String.set('trim', true); + * + * const User = mongoose.model('User', new Schema({ name: String })); + * new User({ name: ' John Doe ' }).name; // 'John Doe' + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ + +SchemaString.set = SchemaType.set; + +/*! + * ignore + */ + +SchemaString._checkRequired = v => (v instanceof String || typeof v === 'string') && v.length; + +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * ####Example: + * + * // Allow empty strings to pass `required` check + * mongoose.Schema.Types.String.checkRequired(v => v != null); + * + * const M = mongoose.model({ str: { type: String, required: true } }); + * new M({ str: '' }).validateSync(); // `null`, validation passes! + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ + +SchemaString.checkRequired = SchemaType.checkRequired; + +/** + * Adds an enum validator + * + * ####Example: + * + * const states = ['opening', 'open', 'closing', 'closed'] + * const s = new Schema({ state: { type: String, enum: states }}) + * const M = db.model('M', s) + * const m = new M({ state: 'invalid' }) + * m.save(function (err) { + * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`. + * m.state = 'open' + * m.save(callback) // success + * }) + * + * // or with custom error messages + * const enum = { + * values: ['opening', 'open', 'closing', 'closed'], + * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' + * } + * const s = new Schema({ state: { type: String, enum: enum }) + * const M = db.model('M', s) + * const m = new M({ state: 'invalid' }) + * m.save(function (err) { + * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid` + * m.state = 'open' + * m.save(callback) // success + * }) + * + * @param {String|Object} [args...] enumeration values + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.enum = function() { + if (this.enumValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.enumValidator; + }, this); + this.enumValidator = false; + } + + if (arguments[0] === void 0 || arguments[0] === false) { + return this; + } + + let values; + let errorMessage; + + if (utils.isObject(arguments[0])) { + if (Array.isArray(arguments[0].values)) { + values = arguments[0].values; + errorMessage = arguments[0].message; + } else { + values = utils.object.vals(arguments[0]); + errorMessage = MongooseError.messages.String.enum; + } + } else { + values = arguments; + errorMessage = MongooseError.messages.String.enum; + } + + for (const value of values) { + if (value !== undefined) { + this.enumValues.push(this.cast(value)); + } + } + + const vals = this.enumValues; + this.enumValidator = function(v) { + return undefined === v || ~vals.indexOf(v); + }; + this.validators.push({ + validator: this.enumValidator, + message: errorMessage, + type: 'enum', + enumValues: vals + }); + + return this; +}; + +/** + * Adds a lowercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). + * + * ####Example: + * + * const s = new Schema({ email: { type: String, lowercase: true }}) + * const M = db.model('M', s); + * const m = new M({ email: 'SomeEmail@example.COM' }); + * console.log(m.email) // someemail@example.com + * M.find({ email: 'SomeEmail@example.com' }); // Queries by 'someemail@example.com' + * + * Note that `lowercase` does **not** affect regular expression queries: + * + * ####Example: + * // Still queries for documents whose `email` matches the regular + * // expression /SomeEmail/. Mongoose does **not** convert the RegExp + * // to lowercase. + * M.find({ email: /SomeEmail/ }); + * + * @api public + * @return {SchemaType} this + */ + +SchemaString.prototype.lowercase = function(shouldApply) { + if (arguments.length > 0 && !shouldApply) { + return this; + } + return this.set(v => { + if (typeof v !== 'string') { + v = this.cast(v); + } + if (v) { + return v.toLowerCase(); + } + return v; + }); +}; + +/** + * Adds an uppercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). + * + * ####Example: + * + * const s = new Schema({ caps: { type: String, uppercase: true }}) + * const M = db.model('M', s); + * const m = new M({ caps: 'an example' }); + * console.log(m.caps) // AN EXAMPLE + * M.find({ caps: 'an example' }) // Matches documents where caps = 'AN EXAMPLE' + * + * Note that `uppercase` does **not** affect regular expression queries: + * + * ####Example: + * // Mongoose does **not** convert the RegExp to uppercase. + * M.find({ email: /an example/ }); + * + * @api public + * @return {SchemaType} this + */ + +SchemaString.prototype.uppercase = function(shouldApply) { + if (arguments.length > 0 && !shouldApply) { + return this; + } + return this.set(v => { + if (typeof v !== 'string') { + v = this.cast(v); + } + if (v) { + return v.toUpperCase(); + } + return v; + }); +}; + +/** + * Adds a trim [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). + * + * The string value will be [trimmed](https://masteringjs.io/tutorials/fundamentals/trim-string) when set. + * + * ####Example: + * + * const s = new Schema({ name: { type: String, trim: true }}); + * const M = db.model('M', s); + * const string = ' some name '; + * console.log(string.length); // 11 + * const m = new M({ name: string }); + * console.log(m.name.length); // 9 + * + * // Equivalent to `findOne({ name: string.trim() })` + * M.findOne({ name: string }); + * + * Note that `trim` does **not** affect regular expression queries: + * + * ####Example: + * // Mongoose does **not** trim whitespace from the RegExp. + * M.find({ name: / some name / }); + * + * @api public + * @return {SchemaType} this + */ + +SchemaString.prototype.trim = function(shouldTrim) { + if (arguments.length > 0 && !shouldTrim) { + return this; + } + return this.set(v => { + if (typeof v !== 'string') { + v = this.cast(v); + } + if (v) { + return v.trim(); + } + return v; + }); +}; + +/** + * Sets a minimum length validator. + * + * ####Example: + * + * const schema = new Schema({ postalCode: { type: String, minlength: 5 }) + * const Address = db.model('Address', schema) + * const address = new Address({ postalCode: '9512' }) + * address.save(function (err) { + * console.error(err) // validator error + * address.postalCode = '95125'; + * address.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length + * const minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).']; + * const schema = new Schema({ postalCode: { type: String, minlength: minlength }) + * const Address = mongoose.model('Address', schema); + * const address = new Address({ postalCode: '9512' }); + * address.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5). + * }) + * + * @param {Number} value minimum string length + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.minlength = function(value, message) { + if (this.minlengthValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minlengthValidator; + }, this); + } + + if (value !== null && value !== undefined) { + let msg = message || MongooseError.messages.String.minlength; + msg = msg.replace(/{MINLENGTH}/, value); + this.validators.push({ + validator: this.minlengthValidator = function(v) { + return v === null || v.length >= value; + }, + message: msg, + type: 'minlength', + minlength: value + }); + } + + return this; +}; + +SchemaString.prototype.minLength = SchemaString.prototype.minlength; + +/** + * Sets a maximum length validator. + * + * ####Example: + * + * const schema = new Schema({ postalCode: { type: String, maxlength: 9 }) + * const Address = db.model('Address', schema) + * const address = new Address({ postalCode: '9512512345' }) + * address.save(function (err) { + * console.error(err) // validator error + * address.postalCode = '95125'; + * address.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length + * const maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).']; + * const schema = new Schema({ postalCode: { type: String, maxlength: maxlength }) + * const Address = mongoose.model('Address', schema); + * const address = new Address({ postalCode: '9512512345' }); + * address.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9). + * }) + * + * @param {Number} value maximum string length + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.maxlength = function(value, message) { + if (this.maxlengthValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxlengthValidator; + }, this); + } + + if (value !== null && value !== undefined) { + let msg = message || MongooseError.messages.String.maxlength; + msg = msg.replace(/{MAXLENGTH}/, value); + this.validators.push({ + validator: this.maxlengthValidator = function(v) { + return v === null || v.length <= value; + }, + message: msg, + type: 'maxlength', + maxlength: value + }); + } + + return this; +}; + +SchemaString.prototype.maxLength = SchemaString.prototype.maxlength; + +/** + * Sets a regexp validator. + * + * Any value that does not pass `regExp`.test(val) will fail validation. + * + * ####Example: + * + * const s = new Schema({ name: { type: String, match: /^a/ }}) + * const M = db.model('M', s) + * const m = new M({ name: 'I am invalid' }) + * m.validate(function (err) { + * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)." + * m.name = 'apples' + * m.validate(function (err) { + * assert.ok(err) // success + * }) + * }) + * + * // using a custom error message + * const match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ]; + * const s = new Schema({ file: { type: String, match: match }}) + * const M = db.model('M', s); + * const m = new M({ file: 'invalid' }); + * m.validate(function (err) { + * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)" + * }) + * + * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also. + * + * const s = new Schema({ name: { type: String, match: /^a/, required: true }}) + * + * @param {RegExp} regExp regular expression to test against + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.match = function match(regExp, message) { + // yes, we allow multiple match validators + + const msg = message || MongooseError.messages.String.match; + + const matchValidator = function(v) { + if (!regExp) { + return false; + } + + // In case RegExp happens to have `/g` flag set, we need to reset the + // `lastIndex`, otherwise `match` will intermittently fail. + regExp.lastIndex = 0; + + const ret = ((v != null && v !== '') + ? regExp.test(v) + : true); + return ret; + }; + + this.validators.push({ + validator: matchValidator, + message: msg, + type: 'regexp', + regexp: regExp + }); + return this; +}; + +/** + * Check if the given value satisfies the `required` validator. The value is + * considered valid if it is a string (that is, not `null` or `undefined`) and + * has positive length. The `required` validator **will** fail for empty + * strings. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ + +SchemaString.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + SchemaString.checkRequired(); + + return _checkRequired(value); +}; + +/** + * Casts to String + * + * @api private + */ + +SchemaString.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + if (typeof value === 'string') { + return value; + } + + return this._castRef(value, doc, init); + } + + let castString; + if (typeof this._castFunction === 'function') { + castString = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castString = this.constructor.cast(); + } else { + castString = SchemaString.cast(); + } + + try { + return castString(value); + } catch (error) { + throw new CastError('string', value, this.path, null, this); + } +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.castForQuery(val); +} + +function handleArray(val) { + const _this = this; + if (!Array.isArray(val)) { + return [this.castForQuery(val)]; + } + return val.map(function(m) { + return _this.castForQuery(m); + }); +} + +const $conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { + $all: handleArray, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle, + $options: String, + $regex: handleSingle, + $not: handleSingle +}); + +Object.defineProperty(SchemaString.prototype, '$conditionalHandlers', { + configurable: false, + enumerable: false, + writable: false, + value: Object.freeze($conditionalHandlers) +}); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [val] + * @api private + */ + +SchemaString.prototype.castForQuery = function($conditional, val) { + let handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with String.'); + } + return handler.call(this, val); + } + val = $conditional; + if (Object.prototype.toString.call(val) === '[object RegExp]') { + return val; + } + + return this._castForQuery(val); +}; + +/*! + * Module exports. + */ + +module.exports = SchemaString; diff --git a/node_modules/mongoose/lib/schema/symbols.js b/node_modules/mongoose/lib/schema/symbols.js new file mode 100644 index 0000000..08d1d27 --- /dev/null +++ b/node_modules/mongoose/lib/schema/symbols.js @@ -0,0 +1,5 @@ +'use strict'; + +exports.schemaMixedSymbol = Symbol.for('mongoose:schema_mixed'); + +exports.builtInMiddleware = Symbol.for('mongoose:built-in-middleware'); \ No newline at end of file diff --git a/node_modules/mongoose/lib/schematype.js b/node_modules/mongoose/lib/schematype.js new file mode 100644 index 0000000..85ab264 --- /dev/null +++ b/node_modules/mongoose/lib/schematype.js @@ -0,0 +1,1638 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const MongooseError = require('./error/index'); +const SchemaTypeOptions = require('./options/SchemaTypeOptions'); +const $exists = require('./schema/operators/exists'); +const $type = require('./schema/operators/type'); +const get = require('./helpers/get'); +const handleImmutable = require('./helpers/schematype/handleImmutable'); +const isAsyncFunction = require('./helpers/isAsyncFunction'); +const immediate = require('./helpers/immediate'); +const schemaTypeSymbol = require('./helpers/symbols').schemaTypeSymbol; +const utils = require('./utils'); +const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol; +const documentIsModified = require('./helpers/symbols').documentIsModified; + +const populateModelSymbol = require('./helpers/symbols').populateModelSymbol; + +const CastError = MongooseError.CastError; +const ValidatorError = MongooseError.ValidatorError; + +/** + * SchemaType constructor. Do **not** instantiate `SchemaType` directly. + * Mongoose converts your schema paths into SchemaTypes automatically. + * + * ####Example: + * + * const schema = new Schema({ name: String }); + * schema.path('name') instanceof SchemaType; // true + * + * @param {String} path + * @param {SchemaTypeOptions} [options] See [SchemaTypeOptions docs](/docs/api/schematypeoptions.html) + * @param {String} [instance] + * @api public + */ + +function SchemaType(path, options, instance) { + this[schemaTypeSymbol] = true; + this.path = path; + this.instance = instance; + this.validators = []; + this.getters = this.constructor.hasOwnProperty('getters') ? + this.constructor.getters.slice() : + []; + this.setters = []; + + this.splitPath(); + + options = options || {}; + const defaultOptions = this.constructor.defaultOptions || {}; + const defaultOptionsKeys = Object.keys(defaultOptions); + + for (const option of defaultOptionsKeys) { + if (defaultOptions.hasOwnProperty(option) && !options.hasOwnProperty(option)) { + options[option] = defaultOptions[option]; + } + } + + if (options.select == null) { + delete options.select; + } + + const Options = this.OptionsConstructor || SchemaTypeOptions; + this.options = new Options(options); + this._index = null; + + + if (utils.hasUserDefinedProperty(this.options, 'immutable')) { + this.$immutable = this.options.immutable; + + handleImmutable(this); + } + + const keys = Object.keys(this.options); + for (const prop of keys) { + if (prop === 'cast') { + this.castFunction(this.options[prop]); + continue; + } + if (utils.hasUserDefinedProperty(this.options, prop) && typeof this[prop] === 'function') { + // { unique: true, index: true } + if (prop === 'index' && this._index) { + if (options.index === false) { + const index = this._index; + if (typeof index === 'object' && index != null) { + if (index.unique) { + throw new Error('Path "' + this.path + '" may not have `index` ' + + 'set to false and `unique` set to true'); + } + if (index.sparse) { + throw new Error('Path "' + this.path + '" may not have `index` ' + + 'set to false and `sparse` set to true'); + } + } + + this._index = false; + } + continue; + } + + const val = options[prop]; + // Special case so we don't screw up array defaults, see gh-5780 + if (prop === 'default') { + this.default(val); + continue; + } + + const opts = Array.isArray(val) ? val : [val]; + + this[prop].apply(this, opts); + } + } + + Object.defineProperty(this, '$$context', { + enumerable: false, + configurable: false, + writable: true, + value: null + }); +} + +/*! + * The class that Mongoose uses internally to instantiate this SchemaType's `options` property. + */ + +SchemaType.prototype.OptionsConstructor = SchemaTypeOptions; + +/*! + * ignore + */ + +SchemaType.prototype.splitPath = function() { + if (this._presplitPath != null) { + return this._presplitPath; + } + if (this.path == null) { + return undefined; + } + + this._presplitPath = this.path.indexOf('.') === -1 ? [this.path] : this.path.split('.'); + return this._presplitPath; +}; + +/** + * Get/set the function used to cast arbitrary values to this type. + * + * ####Example: + * + * // Disallow `null` for numbers, and don't try to cast any values to + * // numbers, so even strings like '123' will cause a CastError. + * mongoose.Number.cast(function(v) { + * assert.ok(v === undefined || typeof v === 'number'); + * return v; + * }); + * + * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed + * @return {Function} + * @static + * @receiver SchemaType + * @function cast + * @api public + */ + +SchemaType.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = v => v; + } + this._cast = caster; + + return this._cast; +}; + +/** + * Get/set the function used to cast arbitrary values to this particular schematype instance. + * Overrides `SchemaType.cast()`. + * + * ####Example: + * + * // Disallow `null` for numbers, and don't try to cast any values to + * // numbers, so even strings like '123' will cause a CastError. + * const number = new mongoose.Number('mypath', {}); + * number.cast(function(v) { + * assert.ok(v === undefined || typeof v === 'number'); + * return v; + * }); + * + * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed + * @return {Function} + * @static + * @receiver SchemaType + * @function cast + * @api public + */ + +SchemaType.prototype.castFunction = function castFunction(caster) { + if (arguments.length === 0) { + return this._castFunction; + } + if (caster === false) { + caster = this.constructor._defaultCaster || (v => v); + } + this._castFunction = caster; + + return this._castFunction; +}; + +/** + * The function that Mongoose calls to cast arbitrary values to this SchemaType. + * + * @param {Object} value value to cast + * @param {Document} doc document that triggers the casting + * @param {Boolean} init + * @api public + */ + +SchemaType.prototype.cast = function cast() { + throw new Error('Base SchemaType class does not implement a `cast()` function'); +}; + +/** + * Sets a default option for this schema type. + * + * ####Example: + * + * // Make all strings be trimmed by default + * mongoose.SchemaTypes.String.set('trim', true); + * + * @param {String} option The name of the option you'd like to set (e.g. trim, lowercase, etc...) + * @param {*} value The value of the option you'd like to set. + * @return {void} + * @static + * @receiver SchemaType + * @function set + * @api public + */ + +SchemaType.set = function set(option, value) { + if (!this.hasOwnProperty('defaultOptions')) { + this.defaultOptions = Object.assign({}, this.defaultOptions); + } + this.defaultOptions[option] = value; +}; + +/** + * Attaches a getter for all instances of this schema type. + * + * ####Example: + * + * // Make all numbers round down + * mongoose.Number.get(function(v) { return Math.floor(v); }); + * + * @param {Function} getter + * @return {this} + * @static + * @receiver SchemaType + * @function get + * @api public + */ + +SchemaType.get = function(getter) { + this.getters = this.hasOwnProperty('getters') ? this.getters : []; + this.getters.push(getter); +}; + +/** + * Sets a default value for this SchemaType. + * + * ####Example: + * + * const schema = new Schema({ n: { type: Number, default: 10 }) + * const M = db.model('M', schema) + * const m = new M; + * console.log(m.n) // 10 + * + * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation. + * + * ####Example: + * + * // values are cast: + * const schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }}) + * const M = db.model('M', schema) + * const m = new M; + * console.log(m.aNumber) // 4.815162342 + * + * // default unique objects for Mixed types: + * const schema = new Schema({ mixed: Schema.Types.Mixed }); + * schema.path('mixed').default(function () { + * return {}; + * }); + * + * // if we don't use a function to return object literals for Mixed defaults, + * // each document will receive a reference to the same object literal creating + * // a "shared" object instance: + * const schema = new Schema({ mixed: Schema.Types.Mixed }); + * schema.path('mixed').default({}); + * const M = db.model('M', schema); + * const m1 = new M; + * m1.mixed.added = 1; + * console.log(m1.mixed); // { added: 1 } + * const m2 = new M; + * console.log(m2.mixed); // { added: 1 } + * + * @param {Function|any} val the default value + * @return {defaultValue} + * @api public + */ + +SchemaType.prototype.default = function(val) { + if (arguments.length === 1) { + if (val === void 0) { + this.defaultValue = void 0; + return void 0; + } + + if (val != null && val.instanceOfSchema) { + throw new MongooseError('Cannot set default value of path `' + this.path + + '` to a mongoose Schema instance.'); + } + + this.defaultValue = val; + return this.defaultValue; + } else if (arguments.length > 1) { + this.defaultValue = utils.args(arguments); + } + return this.defaultValue; +}; + +/** + * Declares the index options for this schematype. + * + * ####Example: + * + * const s = new Schema({ name: { type: String, index: true }) + * const s = new Schema({ loc: { type: [Number], index: 'hashed' }) + * const s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) + * const s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) + * const s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) + * s.path('my.path').index(true); + * s.path('my.date').index({ expires: 60 }); + * s.path('my.path').index({ unique: true, sparse: true }); + * + * ####NOTE: + * + * _Indexes are created [in the background](https://docs.mongodb.com/manual/core/index-creation/#index-creation-background) + * by default. If `background` is set to `false`, MongoDB will not execute any + * read/write operations you send until the index build. + * Specify `background: false` to override Mongoose's default._ + * + * @param {Object|Boolean|String} options + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.index = function(options) { + this._index = options; + utils.expires(this._index); + return this; +}; + +/** + * Declares an unique index. + * + * ####Example: + * + * const s = new Schema({ name: { type: String, unique: true }}); + * s.path('name').index({ unique: true }); + * + * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._ + * + * @param {Boolean} bool + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.unique = function(bool) { + if (this._index === false) { + if (!bool) { + return; + } + throw new Error('Path "' + this.path + '" may not have `index` set to ' + + 'false and `unique` set to true'); + } + + if (!this.options.hasOwnProperty('index') && bool === false) { + return this; + } + + if (this._index == null || this._index === true) { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = { type: this._index }; + } + + this._index.unique = bool; + return this; +}; + +/** + * Declares a full text index. + * + * ###Example: + * + * const s = new Schema({name : {type: String, text : true }) + * s.path('name').index({text : true}); + * @param {Boolean} bool + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.text = function(bool) { + if (this._index === false) { + if (!bool) { + return; + } + throw new Error('Path "' + this.path + '" may not have `index` set to ' + + 'false and `text` set to true'); + } + + if (!this.options.hasOwnProperty('index') && bool === false) { + return this; + } + + if (this._index === null || this._index === undefined || + typeof this._index === 'boolean') { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = { type: this._index }; + } + + this._index.text = bool; + return this; +}; + +/** + * Declares a sparse index. + * + * ####Example: + * + * const s = new Schema({ name: { type: String, sparse: true } }); + * s.path('name').index({ sparse: true }); + * + * @param {Boolean} bool + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.sparse = function(bool) { + if (this._index === false) { + if (!bool) { + return; + } + throw new Error('Path "' + this.path + '" may not have `index` set to ' + + 'false and `sparse` set to true'); + } + + if (!this.options.hasOwnProperty('index') && bool === false) { + return this; + } + + if (this._index == null || typeof this._index === 'boolean') { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = { type: this._index }; + } + + this._index.sparse = bool; + return this; +}; + +/** + * Defines this path as immutable. Mongoose prevents you from changing + * immutable paths unless the parent document has [`isNew: true`](/docs/api.html#document_Document-isNew). + * + * ####Example: + * + * const schema = new Schema({ + * name: { type: String, immutable: true }, + * age: Number + * }); + * const Model = mongoose.model('Test', schema); + * + * await Model.create({ name: 'test' }); + * const doc = await Model.findOne(); + * + * doc.isNew; // false + * doc.name = 'new name'; + * doc.name; // 'test', because `name` is immutable + * + * Mongoose also prevents changing immutable properties using `updateOne()` + * and `updateMany()` based on [strict mode](/docs/guide.html#strict). + * + * ####Example: + * + * // Mongoose will strip out the `name` update, because `name` is immutable + * Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } }); + * + * // If `strict` is set to 'throw', Mongoose will throw an error if you + * // update `name` + * const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }). + * then(() => null, err => err); + * err.name; // StrictModeError + * + * // If `strict` is `false`, Mongoose allows updating `name` even though + * // the property is immutable. + * Model.updateOne({}, { name: 'test2' }, { strict: false }); + * + * @param {Boolean} bool + * @return {SchemaType} this + * @see isNew /docs/api.html#document_Document-isNew + * @api public + */ + +SchemaType.prototype.immutable = function(bool) { + this.$immutable = bool; + handleImmutable(this); + + return this; +}; + +/** + * Defines a custom function for transforming this path when converting a document to JSON. + * + * Mongoose calls this function with one parameter: the current `value` of the path. Mongoose + * then uses the return value in the JSON output. + * + * ####Example: + * + * const schema = new Schema({ + * date: { type: Date, transform: v => v.getFullYear() } + * }); + * const Model = mongoose.model('Test', schema); + * + * await Model.create({ date: new Date('2016-06-01') }); + * const doc = await Model.findOne(); + * + * doc.date instanceof Date; // true + * + * doc.toJSON().date; // 2016 as a number + * JSON.stringify(doc); // '{"_id":...,"date":2016}' + * + * @param {Function} fn + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.transform = function(fn) { + this.options.transform = fn; + + return this; +}; + +/** + * Adds a setter to this schematype. + * + * ####Example: + * + * function capitalize (val) { + * if (typeof val !== 'string') val = ''; + * return val.charAt(0).toUpperCase() + val.substring(1); + * } + * + * // defining within the schema + * const s = new Schema({ name: { type: String, set: capitalize }}); + * + * // or with the SchemaType + * const s = new Schema({ name: String }) + * s.path('name').set(capitalize); + * + * Setters allow you to transform the data before it gets to the raw mongodb + * document or query. + * + * Suppose you are implementing user registration for a website. Users provide + * an email and password, which gets saved to mongodb. The email is a string + * that you will want to normalize to lower case, in order to avoid one email + * having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM. + * + * You can set up email lower case normalization easily via a Mongoose setter. + * + * function toLower(v) { + * return v.toLowerCase(); + * } + * + * const UserSchema = new Schema({ + * email: { type: String, set: toLower } + * }); + * + * const User = db.model('User', UserSchema); + * + * const user = new User({email: 'AVENUE@Q.COM'}); + * console.log(user.email); // 'avenue@q.com' + * + * // or + * const user = new User(); + * user.email = 'Avenue@Q.com'; + * console.log(user.email); // 'avenue@q.com' + * User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com' + * + * As you can see above, setters allow you to transform the data before it + * stored in MongoDB, or before executing a query. + * + * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ + * + * new Schema({ email: { type: String, lowercase: true }}) + * + * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. + * + * function inspector (val, schematype) { + * if (schematype.options.required) { + * return schematype.path + ' is required'; + * } else { + * return val; + * } + * } + * + * const VirusSchema = new Schema({ + * name: { type: String, required: true, set: inspector }, + * taxonomy: { type: String, set: inspector } + * }) + * + * const Virus = db.model('Virus', VirusSchema); + * const v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); + * + * console.log(v.name); // name is required + * console.log(v.taxonomy); // Parvovirinae + * + * You can also use setters to modify other properties on the document. If + * you're setting a property `name` on a document, the setter will run with + * `this` as the document. Be careful, in mongoose 5 setters will also run + * when querying by `name` with `this` as the query. + * + * ```javascript + * const nameSchema = new Schema({ name: String, keywords: [String] }); + * nameSchema.path('name').set(function(v) { + * // Need to check if `this` is a document, because in mongoose 5 + * // setters will also run on queries, in which case `this` will be a + * // mongoose query object. + * if (this instanceof Document && v != null) { + * this.keywords = v.split(' '); + * } + * return v; + * }); + * ``` + * + * @param {Function} fn + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.set = function(fn) { + if (typeof fn !== 'function') { + throw new TypeError('A setter must be a function.'); + } + this.setters.push(fn); + return this; +}; + +/** + * Adds a getter to this schematype. + * + * ####Example: + * + * function dob (val) { + * if (!val) return val; + * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); + * } + * + * // defining within the schema + * const s = new Schema({ born: { type: Date, get: dob }) + * + * // or by retreiving its SchemaType + * const s = new Schema({ born: Date }) + * s.path('born').get(dob) + * + * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. + * + * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: + * + * function obfuscate (cc) { + * return '****-****-****-' + cc.slice(cc.length-4, cc.length); + * } + * + * const AccountSchema = new Schema({ + * creditCardNumber: { type: String, get: obfuscate } + * }); + * + * const Account = db.model('Account', AccountSchema); + * + * Account.findById(id, function (err, found) { + * console.log(found.creditCardNumber); // '****-****-****-1234' + * }); + * + * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. + * + * function inspector (val, schematype) { + * if (schematype.options.required) { + * return schematype.path + ' is required'; + * } else { + * return schematype.path + ' is not'; + * } + * } + * + * const VirusSchema = new Schema({ + * name: { type: String, required: true, get: inspector }, + * taxonomy: { type: String, get: inspector } + * }) + * + * const Virus = db.model('Virus', VirusSchema); + * + * Virus.findById(id, function (err, virus) { + * console.log(virus.name); // name is required + * console.log(virus.taxonomy); // taxonomy is not + * }) + * + * @param {Function} fn + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.get = function(fn) { + if (typeof fn !== 'function') { + throw new TypeError('A getter must be a function.'); + } + this.getters.push(fn); + return this; +}; + +/** + * Adds validator(s) for this document path. + * + * Validators always receive the value to validate as their first argument and + * must return `Boolean`. Returning `false` or throwing an error means + * validation failed. + * + * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. + * + * ####Examples: + * + * // make sure every value is equal to "something" + * function validator (val) { + * return val == 'something'; + * } + * new Schema({ name: { type: String, validate: validator }}); + * + * // with a custom error message + * + * const custom = [validator, 'Uh oh, {PATH} does not equal "something".'] + * new Schema({ name: { type: String, validate: custom }}); + * + * // adding many validators at a time + * + * const many = [ + * { validator: validator, msg: 'uh oh' } + * , { validator: anotherValidator, msg: 'failed' } + * ] + * new Schema({ name: { type: String, validate: many }}); + * + * // or utilizing SchemaType methods directly: + * + * const schema = new Schema({ name: 'string' }); + * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); + * + * ####Error message templates: + * + * From the examples above, you may have noticed that error messages support + * basic templating. There are a few other template keywords besides `{PATH}` + * and `{VALUE}` too. To find out more, details are available + * [here](#error_messages_MongooseError.messages). + * + * If Mongoose's built-in error message templating isn't enough, Mongoose + * supports setting the `message` property to a function. + * + * schema.path('name').validate({ + * validator: function() { return v.length > 5; }, + * // `errors['name']` will be "name must have length 5, got 'foo'" + * message: function(props) { + * return `${props.path} must have length 5, got '${props.value}'`; + * } + * }); + * + * To bypass Mongoose's error messages and just copy the error message that + * the validator throws, do this: + * + * schema.path('name').validate({ + * validator: function() { throw new Error('Oops!'); }, + * // `errors['name']` will be "Oops!" + * message: function(props) { return props.reason.message; } + * }); + * + * ####Asynchronous validation: + * + * Mongoose supports validators that return a promise. A validator that returns + * a promise is called an _async validator_. Async validators run in + * parallel, and `validate()` will wait until all async validators have settled. + * + * schema.path('name').validate({ + * validator: function (value) { + * return new Promise(function (resolve, reject) { + * resolve(false); // validation failed + * }); + * } + * }); + * + * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. + * + * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). + * + * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. + * + * const conn = mongoose.createConnection(..); + * conn.on('error', handleError); + * + * const Product = conn.model('Product', yourSchema); + * const dvd = new Product(..); + * dvd.save(); // emits error on the `conn` above + * + * If you want to handle these errors at the Model level, add an `error` + * listener to your Model as shown below. + * + * // registering an error listener on the Model lets us handle errors more locally + * Product.on('error', handleError); + * + * @param {RegExp|Function|Object} obj validator function, or hash describing options + * @param {Function} [obj.validator] validator function. If the validator function returns `undefined` or a truthy value, validation succeeds. If it returns [falsy](https://masteringjs.io/tutorials/fundamentals/falsy) (except `undefined`) or throws an error, validation fails. + * @param {String|Function} [obj.message] optional error message. If function, should return the error message as a string + * @param {Boolean} [obj.propsParameter=false] If true, Mongoose will pass the validator properties object (with the `validator` function, `message`, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators [rely on positional args](https://github.com/chriso/validator.js#validators), so turning this on may cause unpredictable behavior in external validators. + * @param {String|Function} [errorMsg] optional error message. If function, should return the error message as a string + * @param {String} [type] optional validator type + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.validate = function(obj, message, type) { + if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') { + let properties; + if (typeof message === 'function') { + properties = { validator: obj, message: message }; + properties.type = type || 'user defined'; + } else if (message instanceof Object && !type) { + properties = utils.clone(message); + if (!properties.message) { + properties.message = properties.msg; + } + properties.validator = obj; + properties.type = properties.type || 'user defined'; + } else { + if (message == null) { + message = MongooseError.messages.general.default; + } + if (!type) { + type = 'user defined'; + } + properties = { message: message, type: type, validator: obj }; + } + + this.validators.push(properties); + return this; + } + + let i; + let length; + let arg; + + for (i = 0, length = arguments.length; i < length; i++) { + arg = arguments[i]; + if (!utils.isPOJO(arg)) { + const msg = 'Invalid validator. Received (' + typeof arg + ') ' + + arg + + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; + + throw new Error(msg); + } + this.validate(arg.validator, arg); + } + + return this; +}; + +/** + * Adds a required validator to this SchemaType. The validator gets added + * to the front of this SchemaType's validators array using `unshift()`. + * + * ####Example: + * + * const s = new Schema({ born: { type: Date, required: true }) + * + * // or with custom error message + * + * const s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) + * + * // or with a function + * + * const s = new Schema({ + * userId: ObjectId, + * username: { + * type: String, + * required: function() { return this.userId != null; } + * } + * }) + * + * // or with a function and a custom message + * const s = new Schema({ + * userId: ObjectId, + * username: { + * type: String, + * required: [ + * function() { return this.userId != null; }, + * 'username is required if id is specified' + * ] + * } + * }) + * + * // or through the path API + * + * s.path('name').required(true); + * + * // with custom error messaging + * + * s.path('name').required(true, 'grrr :( '); + * + * // or make a path conditionally required based on a function + * const isOver18 = function() { return this.age >= 18; }; + * s.path('voterRegistrationId').required(isOver18); + * + * The required validator uses the SchemaType's `checkRequired` function to + * determine whether a given value satisfies the required validator. By default, + * a value satisfies the required validator if `val != null` (that is, if + * the value is not null nor undefined). However, most built-in mongoose schema + * types override the default `checkRequired` function: + * + * @param {Boolean|Function|Object} required enable/disable the validator, or function that returns required boolean, or options object + * @param {Boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean + * @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties. + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @see SchemaArray#checkRequired #schema_array_SchemaArray.checkRequired + * @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired + * @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer.schemaName + * @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min + * @see SchemaObjectId#checkRequired #schema_objectid_ObjectId-auto + * @see SchemaString#checkRequired #schema_string_SchemaString-checkRequired + * @api public + */ + +SchemaType.prototype.required = function(required, message) { + let customOptions = {}; + + if (arguments.length > 0 && required == null) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.requiredValidator; + }, this); + + this.isRequired = false; + delete this.originalRequiredValue; + return this; + } + + if (typeof required === 'object') { + customOptions = required; + message = customOptions.message || message; + required = required.isRequired; + } + + if (required === false) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.requiredValidator; + }, this); + + this.isRequired = false; + delete this.originalRequiredValue; + return this; + } + + const _this = this; + this.isRequired = true; + + this.requiredValidator = function(v) { + const cachedRequired = get(this, '$__.cachedRequired'); + + // no validation when this path wasn't selected in the query. + if (cachedRequired != null && !this.$__isSelected(_this.path) && !this[documentIsModified](_this.path)) { + return true; + } + + // `$cachedRequired` gets set in `_evaluateRequiredFunctions()` so we + // don't call required functions multiple times in one validate call + // See gh-6801 + if (cachedRequired != null && _this.path in cachedRequired) { + const res = cachedRequired[_this.path] ? + _this.checkRequired(v, this) : + true; + delete cachedRequired[_this.path]; + return res; + } else if (typeof required === 'function') { + return required.apply(this) ? _this.checkRequired(v, this) : true; + } + + return _this.checkRequired(v, this); + }; + this.originalRequiredValue = required; + + if (typeof required === 'string') { + message = required; + required = undefined; + } + + const msg = message || MongooseError.messages.general.required; + this.validators.unshift(Object.assign({}, customOptions, { + validator: this.requiredValidator, + message: msg, + type: 'required' + })); + + return this; +}; + +/** + * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html) + * looks at to determine the foreign collection it should query. + * + * ####Example: + * const userSchema = new Schema({ name: String }); + * const User = mongoose.model('User', userSchema); + * + * const postSchema = new Schema({ user: mongoose.ObjectId }); + * postSchema.path('user').ref('User'); // Can set ref to a model name + * postSchema.path('user').ref(User); // Or a model class + * postSchema.path('user').ref(() => 'User'); // Or a function that returns the model name + * postSchema.path('user').ref(() => User); // Or a function that returns the model class + * + * // Or you can just declare the `ref` inline in your schema + * const postSchema2 = new Schema({ + * user: { type: mongoose.ObjectId, ref: User } + * }); + * + * @param {String|Model|Function} ref either a model name, a [Model](https://mongoosejs.com/docs/models.html), or a function that returns a model name or model. + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.ref = function(ref) { + this.options.ref = ref; + return this; +}; + +/** + * Gets the default value + * + * @param {Object} scope the scope which callback are executed + * @param {Boolean} init + * @api private + */ + +SchemaType.prototype.getDefault = function(scope, init) { + let ret; + if (typeof this.defaultValue === 'function') { + if ( + this.defaultValue === Date.now || + this.defaultValue === Array || + this.defaultValue.name.toLowerCase() === 'objectid' + ) { + ret = this.defaultValue.call(scope); + } else { + ret = this.defaultValue.call(scope, scope); + } + } else { + ret = this.defaultValue; + } + + + if (ret !== null && ret !== undefined) { + if (typeof ret === 'object' && (!this.options || !this.options.shared)) { + ret = utils.clone(ret); + } + + const casted = this.applySetters(ret, scope, init); + if (casted && casted.$isSingleNested) { + casted.$__parent = scope; + } + return casted; + } + return ret; +}; + +/*! + * Applies setters without casting + * + * @api private + */ + +SchemaType.prototype._applySetters = function(value, scope, init, priorVal) { + let v = value; + if (init) { + return v; + } + const setters = this.setters; + + for (let i = setters.length - 1; i >= 0; i--) { + v = setters[i].call(scope, v, priorVal, this); + } + + return v; +}; + +/*! + * ignore + */ + +SchemaType.prototype._castNullish = function _castNullish(v) { + return v; +}; + +/** + * Applies setters + * + * @param {Object} value + * @param {Object} scope + * @param {Boolean} init + * @api private + */ + +SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) { + let v = this._applySetters(value, scope, init, priorVal, options); + if (v == null) { + return this._castNullish(v); + } + + // do not cast until all setters are applied #665 + v = this.cast(v, scope, init, priorVal, options); + + return v; +}; + +/** + * Applies getters to a value + * + * @param {Object} value + * @param {Object} scope + * @api private + */ + +SchemaType.prototype.applyGetters = function(value, scope) { + let v = value; + const getters = this.getters; + const len = getters.length; + + if (len === 0) { + return v; + } + + for (let i = 0; i < len; ++i) { + v = getters[i].call(scope, v, this); + } + + return v; +}; + +/** + * Sets default `select()` behavior for this path. + * + * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level. + * + * ####Example: + * + * T = db.model('T', new Schema({ x: { type: String, select: true }})); + * T.find(..); // field x will always be selected .. + * // .. unless overridden; + * T.find().select('-x').exec(callback); + * + * @param {Boolean} val + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.select = function select(val) { + this.selected = !!val; + return this; +}; + +/** + * Performs a validation of `value` using the validators declared for this SchemaType. + * + * @param {any} value + * @param {Function} callback + * @param {Object} scope + * @api private + */ + +SchemaType.prototype.doValidate = function(value, fn, scope, options) { + let err = false; + const path = this.path; + + // Avoid non-object `validators` + const validators = this.validators. + filter(v => v != null && typeof v === 'object'); + + let count = validators.length; + + if (!count) { + return fn(null); + } + + const _this = this; + validators.forEach(function(v) { + if (err) { + return; + } + + const validator = v.validator; + let ok; + + const validatorProperties = utils.clone(v); + validatorProperties.path = options && options.path ? options.path : path; + validatorProperties.value = value; + + if (validator instanceof RegExp) { + validate(validator.test(value), validatorProperties); + return; + } + + if (typeof validator !== 'function') { + return; + } + + if (value === undefined && validator !== _this.requiredValidator) { + validate(true, validatorProperties); + return; + } + + try { + if (validatorProperties.propsParameter) { + ok = validator.call(scope, value, validatorProperties); + } else { + ok = validator.call(scope, value); + } + } catch (error) { + ok = false; + validatorProperties.reason = error; + if (error.message) { + validatorProperties.message = error.message; + } + } + + if (ok != null && typeof ok.then === 'function') { + ok.then( + function(ok) { validate(ok, validatorProperties); }, + function(error) { + validatorProperties.reason = error; + validatorProperties.message = error.message; + ok = false; + validate(ok, validatorProperties); + }); + } else { + validate(ok, validatorProperties); + } + + }); + + function validate(ok, validatorProperties) { + if (err) { + return; + } + if (ok === undefined || ok) { + if (--count <= 0) { + immediate(function() { + fn(null); + }); + } + } else { + const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; + err = new ErrorConstructor(validatorProperties); + err[validatorErrorSymbol] = true; + immediate(function() { + fn(err); + }); + } + } +}; + +/** + * Performs a validation of `value` using the validators declared for this SchemaType. + * + * ####Note: + * + * This method ignores the asynchronous validators. + * + * @param {any} value + * @param {Object} scope + * @return {MongooseError|undefined} + * @api private + */ + +SchemaType.prototype.doValidateSync = function(value, scope, options) { + const path = this.path; + const count = this.validators.length; + + if (!count) { + return null; + } + + let validators = this.validators; + if (value === void 0) { + if (this.validators.length > 0 && this.validators[0].type === 'required') { + validators = [this.validators[0]]; + } else { + return null; + } + } + + let err = null; + validators.forEach(function(v) { + if (err) { + return; + } + + if (v == null || typeof v !== 'object') { + return; + } + + const validator = v.validator; + const validatorProperties = utils.clone(v); + validatorProperties.path = options && options.path ? options.path : path; + validatorProperties.value = value; + let ok; + + // Skip any explicit async validators. Validators that return a promise + // will still run, but won't trigger any errors. + if (isAsyncFunction(validator)) { + return; + } + + if (validator instanceof RegExp) { + validate(validator.test(value), validatorProperties); + return; + } + + if (typeof validator !== 'function') { + return; + } + + try { + if (validatorProperties.propsParameter) { + ok = validator.call(scope, value, validatorProperties); + } else { + ok = validator.call(scope, value); + } + } catch (error) { + ok = false; + validatorProperties.reason = error; + } + + // Skip any validators that return a promise, we can't handle those + // synchronously + if (ok != null && typeof ok.then === 'function') { + return; + } + validate(ok, validatorProperties); + }); + + return err; + + function validate(ok, validatorProperties) { + if (err) { + return; + } + if (ok !== undefined && !ok) { + const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; + err = new ErrorConstructor(validatorProperties); + err[validatorErrorSymbol] = true; + } + } +}; + +/** + * Determines if value is a valid Reference. + * + * @param {SchemaType} self + * @param {Object} value + * @param {Document} doc + * @param {Boolean} init + * @return {Boolean} + * @api private + */ + +SchemaType._isRef = function(self, value, doc, init) { + // fast path + let ref = init && self.options && (self.options.ref || self.options.refPath); + + if (!ref && doc && doc.$__ != null) { + // checks for + // - this populated with adhoc model and no ref was set in schema OR + // - setting / pushing values after population + const path = doc.$__fullPath(self.path, true); + + const owner = doc.ownerDocument ? doc.ownerDocument() : doc; + ref = (path != null && owner.$populated(path)) || doc.$populated(self.path); + } + + if (ref) { + if (value == null) { + return true; + } + if (!Buffer.isBuffer(value) && // buffers are objects too + value._bsontype !== 'Binary' // raw binary value from the db + && utils.isObject(value) // might have deselected _id in population query + ) { + return true; + } + + return init; + } + + return false; +}; + +/*! + * ignore + */ + +SchemaType.prototype._castRef = function _castRef(value, doc, init) { + if (value == null) { + return value; + } + + if (value.$__ != null) { + value.$__.wasPopulated = true; + return value; + } + + // setting a populated path + if (Buffer.isBuffer(value) || !utils.isObject(value)) { + if (init) { + return value; + } + throw new CastError(this.instance, value, this.path, null, this); + } + + // Handle the case where user directly sets a populated + // path to a plain object; cast to the Model used in + // the population query. + const path = doc.$__fullPath(this.path, true); + const owner = doc.ownerDocument ? doc.ownerDocument() : doc; + const pop = owner.$populated(path, true); + let ret = value; + if (!doc.$__.populated || + !doc.$__.populated[path] || + !doc.$__.populated[path].options || + !doc.$__.populated[path].options.options || + !doc.$__.populated[path].options.options.lean) { + ret = new pop.options[populateModelSymbol](value); + ret.$__.wasPopulated = true; + } + + return ret; +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.castForQuery(val); +} + +/*! + * ignore + */ + +function handleArray(val) { + const _this = this; + if (!Array.isArray(val)) { + return [this.castForQuery(val)]; + } + return val.map(function(m) { + return _this.castForQuery(m); + }); +} + +/*! + * Just like handleArray, except also allows `[]` because surprisingly + * `$in: [1, []]` works fine + */ + +function handle$in(val) { + const _this = this; + if (!Array.isArray(val)) { + return [this.castForQuery(val)]; + } + return val.map(function(m) { + if (Array.isArray(m) && m.length === 0) { + return m; + } + return _this.castForQuery(m); + }); +} + +/*! + * ignore + */ + +SchemaType.prototype.$conditionalHandlers = { + $all: handleArray, + $eq: handleSingle, + $in: handle$in, + $ne: handleSingle, + $nin: handle$in, + $exists: $exists, + $type: $type +}; + +/*! + * Wraps `castForQuery` to handle context + */ + +SchemaType.prototype.castForQueryWrapper = function(params) { + this.$$context = params.context; + if ('$conditional' in params) { + const ret = this.castForQuery(params.$conditional, params.val); + this.$$context = null; + return ret; + } + if (params.$skipQueryCastForUpdate || params.$applySetters) { + const ret = this._castForQuery(params.val); + this.$$context = null; + return ret; + } + + const ret = this.castForQuery(params.val); + this.$$context = null; + return ret; +}; + +/** + * Cast the given value with the given optional query operator. + * + * @param {String} [$conditional] query operator, like `$eq` or `$in` + * @param {any} val + * @api private + */ + +SchemaType.prototype.castForQuery = function($conditional, val) { + let handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional); + } + return handler.call(this, val); + } + val = $conditional; + return this._castForQuery(val); +}; + +/*! + * Internal switch for runSetters + * + * @api private + */ + +SchemaType.prototype._castForQuery = function(val) { + return this.applySetters(val, this.$$context); +}; + +/** + * Override the function the required validator uses to check whether a value + * passes the `required` check. Override this on the individual SchemaType. + * + * ####Example: + * + * // Use this to allow empty strings to pass the `required` validator + * mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string'); + * + * @param {Function} fn + * @return {Function} + * @static + * @receiver SchemaType + * @function checkRequired + * @api public + */ + +SchemaType.checkRequired = function(fn) { + if (arguments.length > 0) { + this._checkRequired = fn; + } + + return this._checkRequired; +}; + +/** + * Default check for if this path satisfies the `required` validator. + * + * @param {any} val + * @api private + */ + +SchemaType.prototype.checkRequired = function(val) { + return val != null; +}; + +/*! + * ignore + */ + +SchemaType.prototype.clone = function() { + const options = Object.assign({}, this.options); + const schematype = new this.constructor(this.path, options, this.instance); + schematype.validators = this.validators.slice(); + if (this.requiredValidator !== undefined) schematype.requiredValidator = this.requiredValidator; + if (this.defaultValue !== undefined) schematype.defaultValue = this.defaultValue; + if (this.$immutable !== undefined && this.options.immutable === undefined) { + schematype.$immutable = this.$immutable; + + handleImmutable(schematype); + } + if (this._index !== undefined) schematype._index = this._index; + if (this.selected !== undefined) schematype.selected = this.selected; + if (this.isRequired !== undefined) schematype.isRequired = this.isRequired; + if (this.originalRequiredValue !== undefined) schematype.originalRequiredValue = this.originalRequiredValue; + schematype.getters = this.getters.slice(); + schematype.setters = this.setters.slice(); + return schematype; +}; + +/*! + * Module exports. + */ + +module.exports = exports = SchemaType; + +exports.CastError = CastError; + +exports.ValidatorError = ValidatorError; diff --git a/node_modules/mongoose/lib/statemachine.js b/node_modules/mongoose/lib/statemachine.js new file mode 100644 index 0000000..7e36dc1 --- /dev/null +++ b/node_modules/mongoose/lib/statemachine.js @@ -0,0 +1,180 @@ + +/*! + * Module dependencies. + */ + +'use strict'; + +const utils = require('./utils'); + +/*! + * StateMachine represents a minimal `interface` for the + * constructors it builds via StateMachine.ctor(...). + * + * @api private + */ + +const StateMachine = module.exports = exports = function StateMachine() { +}; + +/*! + * StateMachine.ctor('state1', 'state2', ...) + * A factory method for subclassing StateMachine. + * The arguments are a list of states. For each state, + * the constructor's prototype gets state transition + * methods named after each state. These transition methods + * place their path argument into the given state. + * + * @param {String} state + * @param {String} [state] + * @return {Function} subclass constructor + * @private + */ + +StateMachine.ctor = function() { + const states = utils.args(arguments); + + const ctor = function() { + StateMachine.apply(this, arguments); + this.paths = {}; + this.states = {}; + this.stateNames = states; + + let i = states.length, + state; + + while (i--) { + state = states[i]; + this.states[state] = {}; + } + }; + + ctor.prototype = new StateMachine(); + + states.forEach(function(state) { + // Changes the `path`'s state to `state`. + ctor.prototype[state] = function(path) { + this._changeState(path, state); + }; + }); + + return ctor; +}; + +/*! + * This function is wrapped by the state change functions: + * + * - `require(path)` + * - `modify(path)` + * - `init(path)` + * + * @api private + */ + +StateMachine.prototype._changeState = function _changeState(path, nextState) { + const prevBucket = this.states[this.paths[path]]; + if (prevBucket) delete prevBucket[path]; + + this.paths[path] = nextState; + this.states[nextState][path] = true; +}; + +/*! + * ignore + */ + +StateMachine.prototype.clear = function clear(state) { + const keys = Object.keys(this.states[state]); + let i = keys.length; + let path; + + while (i--) { + path = keys[i]; + delete this.states[state][path]; + delete this.paths[path]; + } +}; + +/*! + * Checks to see if at least one path is in the states passed in via `arguments` + * e.g., this.some('required', 'inited') + * + * @param {String} state that we want to check for. + * @private + */ + +StateMachine.prototype.some = function some() { + const _this = this; + const what = arguments.length ? arguments : this.stateNames; + return Array.prototype.some.call(what, function(state) { + return Object.keys(_this.states[state]).length; + }); +}; + +/*! + * This function builds the functions that get assigned to `forEach` and `map`, + * since both of those methods share a lot of the same logic. + * + * @param {String} iterMethod is either 'forEach' or 'map' + * @return {Function} + * @api private + */ + +StateMachine.prototype._iter = function _iter(iterMethod) { + return function() { + const numArgs = arguments.length; + let states = utils.args(arguments, 0, numArgs - 1); + const callback = arguments[numArgs - 1]; + + if (!states.length) states = this.stateNames; + + const _this = this; + + const paths = states.reduce(function(paths, state) { + return paths.concat(Object.keys(_this.states[state])); + }, []); + + return paths[iterMethod](function(path, i, paths) { + return callback(path, i, paths); + }); + }; +}; + +/*! + * Iterates over the paths that belong to one of the parameter states. + * + * The function profile can look like: + * this.forEach(state1, fn); // iterates over all paths in state1 + * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 + * this.forEach(fn); // iterates over all paths in all states + * + * @param {String} [state] + * @param {String} [state] + * @param {Function} callback + * @private + */ + +StateMachine.prototype.forEach = function forEach() { + this.forEach = this._iter('forEach'); + return this.forEach.apply(this, arguments); +}; + +/*! + * Maps over the paths that belong to one of the parameter states. + * + * The function profile can look like: + * this.forEach(state1, fn); // iterates over all paths in state1 + * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 + * this.forEach(fn); // iterates over all paths in all states + * + * @param {String} [state] + * @param {String} [state] + * @param {Function} callback + * @return {Array} + * @private + */ + +StateMachine.prototype.map = function map() { + this.map = this._iter('map'); + return this.map.apply(this, arguments); +}; diff --git a/node_modules/mongoose/lib/types/ArraySubdocument.js b/node_modules/mongoose/lib/types/ArraySubdocument.js new file mode 100644 index 0000000..73514c8 --- /dev/null +++ b/node_modules/mongoose/lib/types/ArraySubdocument.js @@ -0,0 +1,170 @@ +/* eslint no-func-assign: 1 */ + +/*! + * Module dependencies. + */ + +'use strict'; + +const EventEmitter = require('events').EventEmitter; +const Subdocument = require('./subdocument'); +const get = require('../helpers/get'); + +const documentArrayParent = require('../helpers/symbols').documentArrayParent; + +/** + * A constructor. + * + * @param {Object} obj js object returned from the db + * @param {MongooseDocumentArray} parentArr the parent array of this document + * @param {Boolean} skipId + * @inherits Document + * @api private + */ + +function ArraySubdocument(obj, parentArr, skipId, fields, index) { + if (parentArr != null && parentArr.isMongooseDocumentArray) { + this.__parentArray = parentArr; + this[documentArrayParent] = parentArr.$parent(); + } else { + this.__parentArray = undefined; + this[documentArrayParent] = undefined; + } + this.$setIndex(index); + this.$__parent = this[documentArrayParent]; + + Subdocument.call(this, obj, fields, this[documentArrayParent], void 0, { isNew: true }); +} + +/*! + * Inherit from Subdocument + */ +ArraySubdocument.prototype = Object.create(Subdocument.prototype); +ArraySubdocument.prototype.constructor = ArraySubdocument; + +Object.defineProperty(ArraySubdocument.prototype, '$isSingleNested', { + configurable: false, + writable: false, + value: false +}); + +Object.defineProperty(ArraySubdocument.prototype, '$isDocumentArrayElement', { + configurable: false, + writable: false, + value: true +}); + +for (const i in EventEmitter.prototype) { + ArraySubdocument[i] = EventEmitter.prototype[i]; +} + +/*! + * ignore + */ + +ArraySubdocument.prototype.$setIndex = function(index) { + this.__index = index; + + if (get(this, '$__.validationError', null) != null) { + const keys = Object.keys(this.$__.validationError.errors); + for (const key of keys) { + this.invalidate(key, this.$__.validationError.errors[key]); + } + } +}; + +/*! + * ignore + */ + +ArraySubdocument.prototype.populate = function() { + throw new Error('Mongoose does not support calling populate() on nested ' + + 'docs. Instead of `doc.arr[0].populate("path")`, use ' + + '`doc.populate("arr.0.path")`'); +}; + +/*! + * ignore + */ + +ArraySubdocument.prototype.$__removeFromParent = function() { + const _id = this._doc._id; + if (!_id) { + throw new Error('For your own good, Mongoose does not know ' + + 'how to remove an ArraySubdocument that has no _id'); + } + this.__parentArray.pull({ _id: _id }); +}; + +/** + * Returns the full path to this document. If optional `path` is passed, it is appended to the full path. + * + * @param {String} [path] + * @param {Boolean} [skipIndex] Skip adding the array index. For example `arr.foo` instead of `arr.0.foo`. + * @return {String} + * @api private + * @method $__fullPath + * @memberOf ArraySubdocument + * @instance + */ + +ArraySubdocument.prototype.$__fullPath = function(path, skipIndex) { + if (this.__index == null) { + return null; + } + if (!this.$__.fullPath) { + this.ownerDocument(); + } + + if (skipIndex) { + return path ? + this.$__.fullPath + '.' + path : + this.$__.fullPath; + } + + return path ? + this.$__.fullPath + '.' + this.__index + '.' + path : + this.$__.fullPath + '.' + this.__index; +}; + +/*! + * Given a path relative to this document, return the path relative + * to the top-level document. + */ + +ArraySubdocument.prototype.$__pathRelativeToParent = function(path, skipIndex) { + if (this.__index == null) { + return null; + } + if (skipIndex) { + return path == null ? this.__parentArray.$path() : this.__parentArray.$path() + '.' + path; + } + if (path == null) { + return this.__parentArray.$path() + '.' + this.__index; + } + return this.__parentArray.$path() + '.' + this.__index + '.' + path; +}; + +/*! + * Returns this sub-documents parent document. + */ + +ArraySubdocument.prototype.$parent = function() { + return this[documentArrayParent]; +}; + +/** + * Returns this sub-documents parent array. + * + * @api public + */ + +ArraySubdocument.prototype.parentArray = function() { + return this.__parentArray; +}; + +/*! + * Module exports. + */ + +module.exports = ArraySubdocument; diff --git a/node_modules/mongoose/lib/types/DocumentArray/index.js b/node_modules/mongoose/lib/types/DocumentArray/index.js new file mode 100644 index 0000000..6f428ee --- /dev/null +++ b/node_modules/mongoose/lib/types/DocumentArray/index.js @@ -0,0 +1,130 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const ArrayMethods = require('../array/methods'); +const DocumentArrayMethods = require('./methods'); +const Document = require('../../document'); + +const arrayAtomicsSymbol = require('../../helpers/symbols').arrayAtomicsSymbol; +const arrayAtomicsBackupSymbol = require('../../helpers/symbols').arrayAtomicsBackupSymbol; +const arrayParentSymbol = require('../../helpers/symbols').arrayParentSymbol; +const arrayPathSymbol = require('../../helpers/symbols').arrayPathSymbol; +const arraySchemaSymbol = require('../../helpers/symbols').arraySchemaSymbol; + +const _basePush = Array.prototype.push; + +/** + * DocumentArray constructor + * + * @param {Array} values + * @param {String} path the path to this array + * @param {Document} doc parent document + * @api private + * @return {MongooseDocumentArray} + * @inherits MongooseArray + * @see http://bit.ly/f6CnZU + */ + +function MongooseDocumentArray(values, path, doc) { + const arr = []; + + const internals = { + [arrayAtomicsSymbol]: {}, + [arrayAtomicsBackupSymbol]: void 0, + [arrayPathSymbol]: path, + [arraySchemaSymbol]: void 0, + [arrayParentSymbol]: void 0 + }; + + if (Array.isArray(values)) { + if (values[arrayPathSymbol] === path && + values[arrayParentSymbol] === doc) { + internals[arrayAtomicsSymbol] = Object.assign({}, values[arrayAtomicsSymbol]); + } + values.forEach(v => { + _basePush.call(arr, v); + }); + } + internals[arrayPathSymbol] = path; + + // Because doc comes from the context of another function, doc === global + // can happen if there was a null somewhere up the chain (see #3020 && #3034) + // RB Jun 17, 2015 updated to check for presence of expected paths instead + // to make more proof against unusual node environments + if (doc && doc instanceof Document) { + internals[arrayParentSymbol] = doc; + internals[arraySchemaSymbol] = doc.schema.path(path); + + // `schema.path()` doesn't drill into nested arrays properly yet, see + // gh-6398, gh-6602. This is a workaround because nested arrays are + // always plain non-document arrays, so once you get to a document array + // nesting is done. Matryoshka code. + while (internals[arraySchemaSymbol] != null && + internals[arraySchemaSymbol].$isMongooseArray && + !internals[arraySchemaSymbol].$isMongooseDocumentArray) { + internals[arraySchemaSymbol] = internals[arraySchemaSymbol].casterConstructor; + } + } + + const proxy = new Proxy(arr, { + get: function(target, prop) { + if (prop === 'isMongooseArray' || + prop === 'isMongooseArrayProxy' || + prop === 'isMongooseDocumentArray' || + prop === 'isMongooseDocumentArrayProxy') { + return true; + } + if (prop === '__array') { + return arr; + } + if (prop === 'set') { + return set; + } + if (internals.hasOwnProperty(prop)) { + return internals[prop]; + } + if (DocumentArrayMethods.hasOwnProperty(prop)) { + return DocumentArrayMethods[prop]; + } + if (ArrayMethods.hasOwnProperty(prop)) { + return ArrayMethods[prop]; + } + + return arr[prop]; + }, + set: function(target, prop, value) { + if (typeof prop === 'string' && /^\d+$/.test(prop)) { + set.call(proxy, prop, value); + } else if (internals.hasOwnProperty(prop)) { + internals[prop] = value; + } else { + arr[prop] = value; + } + + return true; + } + }); + + return proxy; +} + +function set(i, val, skipModified) { + const arr = this.__array; + if (skipModified) { + arr[i] = val; + return arr; + } + const value = DocumentArrayMethods._cast.call(this, val, i); + arr[i] = value; + DocumentArrayMethods._markModified.call(this, i); + return arr; +} + +/*! + * Module exports. + */ + +module.exports = MongooseDocumentArray; diff --git a/node_modules/mongoose/lib/types/DocumentArray/methods/index.js b/node_modules/mongoose/lib/types/DocumentArray/methods/index.js new file mode 100644 index 0000000..2f9e89e --- /dev/null +++ b/node_modules/mongoose/lib/types/DocumentArray/methods/index.js @@ -0,0 +1,359 @@ +'use strict'; + +const ArrayMethods = require('../../array/methods'); +const Document = require('../../../document'); +const ObjectId = require('../../objectid'); +const castObjectId = require('../../../cast/objectid'); +const getDiscriminatorByValue = require('../../../helpers/discriminator/getDiscriminatorByValue'); +const internalToObjectOptions = require('../../../options').internalToObjectOptions; +const utils = require('../../../utils'); + +const arrayParentSymbol = require('../../../helpers/symbols').arrayParentSymbol; +const arrayPathSymbol = require('../../../helpers/symbols').arrayPathSymbol; +const arraySchemaSymbol = require('../../../helpers/symbols').arraySchemaSymbol; +const documentArrayParent = require('../../../helpers/symbols').documentArrayParent; + +const methods = { + /*! + * ignore + */ + + toBSON() { + return this.toObject(internalToObjectOptions); + }, + + /** + * Overrides MongooseArray#cast + * + * @method _cast + * @api private + * @receiver MongooseDocumentArray + */ + + _cast(value, index) { + if (this[arraySchemaSymbol] == null) { + return value; + } + let Constructor = this[arraySchemaSymbol].casterConstructor; + const isInstance = Constructor.$isMongooseDocumentArray ? + value && value.isMongooseDocumentArray : + value instanceof Constructor; + if (isInstance || + // Hack re: #5001, see #5005 + (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) { + if (!(value[documentArrayParent] && value.__parentArray)) { + // value may have been created using array.create() + value[documentArrayParent] = this[arrayParentSymbol]; + value.__parentArray = this; + } + value.$setIndex(index); + return value; + } + + if (value === undefined || value === null) { + return null; + } + + // handle cast('string') or cast(ObjectId) etc. + // only objects are permitted so we can safely assume that + // non-objects are to be interpreted as _id + if (Buffer.isBuffer(value) || + value instanceof ObjectId || !utils.isObject(value)) { + value = { _id: value }; + } + + if (value && + Constructor.discriminators && + Constructor.schema && + Constructor.schema.options && + Constructor.schema.options.discriminatorKey) { + if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' && + Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) { + Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]; + } else { + const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]); + if (constructorByValue) { + Constructor = constructorByValue; + } + } + } + + if (Constructor.$isMongooseDocumentArray) { + return Constructor.cast(value, this, undefined, undefined, index); + } + const ret = new Constructor(value, this, undefined, undefined, index); + ret.isNew = true; + return ret; + }, + + /** + * Searches array items for the first document with a matching _id. + * + * ####Example: + * + * const embeddedDoc = m.array.id(some_id); + * + * @return {EmbeddedDocument|null} the subdocument or null if not found. + * @param {ObjectId|String|Number|Buffer} id + * @TODO cast to the _id based on schema for proper comparison + * @method id + * @api public + * @receiver MongooseDocumentArray + */ + + id(id) { + let casted; + let sid; + let _id; + + try { + casted = castObjectId(id).toString(); + } catch (e) { + casted = null; + } + + for (const val of this) { + if (!val) { + continue; + } + + _id = val.get('_id'); + + if (_id === null || typeof _id === 'undefined') { + continue; + } else if (_id instanceof Document) { + sid || (sid = String(id)); + if (sid == _id._id) { + return val; + } + } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) { + if (id == _id || utils.deepEqual(id, _id)) { + return val; + } + } else if (casted == _id) { + return val; + } + } + + return null; + }, + + /** + * Returns a native js Array of plain js objects + * + * ####NOTE: + * + * _Each sub-document is converted to a plain object by calling its `#toObject` method._ + * + * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion + * @return {Array} + * @method toObject + * @api public + * @receiver MongooseDocumentArray + */ + + toObject(options) { + // `[].concat` coerces the return value into a vanilla JS array, rather + // than a Mongoose array. + return [].concat(this.map(function(doc) { + if (doc == null) { + return null; + } + if (typeof doc.toObject !== 'function') { + return doc; + } + return doc.toObject(options); + })); + }, + + $toObject() { + return this.constructor.prototype.toObject.apply(this, arguments); + }, + + /** + * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. + * + * @param {Object} [args...] + * @api public + * @method push + * @memberOf MongooseDocumentArray + */ + + push() { + const ret = ArrayMethods.push.apply(this, arguments); + + _updateParentPopulated(this); + + return ret; + }, + + /** + * Pulls items from the array atomically. + * + * @param {Object} [args...] + * @api public + * @method pull + * @memberOf MongooseDocumentArray + */ + + pull() { + const ret = ArrayMethods.pull.apply(this, arguments); + + _updateParentPopulated(this); + + return ret; + }, + + /** + * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + */ + + shift() { + const ret = ArrayMethods.shift.apply(this, arguments); + + _updateParentPopulated(this); + + return ret; + }, + + /** + * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. + */ + + splice() { + const ret = ArrayMethods.splice.apply(this, arguments); + + _updateParentPopulated(this); + + return ret; + }, + + /** + * Helper for console.log + * + * @method inspect + * @api public + * @receiver MongooseDocumentArray + */ + + inspect() { + return this.toObject(); + }, + + /** + * Creates a subdocument casted to this schema. + * + * This is the same subdocument constructor used for casting. + * + * @param {Object} obj the value to cast to this arrays SubDocument schema + * @method create + * @api public + * @receiver MongooseDocumentArray + */ + + create(obj) { + let Constructor = this[arraySchemaSymbol].casterConstructor; + if (obj && + Constructor.discriminators && + Constructor.schema && + Constructor.schema.options && + Constructor.schema.options.discriminatorKey) { + if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' && + Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) { + Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]; + } else { + const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]); + if (constructorByValue) { + Constructor = constructorByValue; + } + } + } + + return new Constructor(obj, this); + }, + + /*! + * ignore + */ + + notify(event) { + const _this = this; + return function notify(val, _arr) { + _arr = _arr || _this; + let i = _arr.length; + while (i--) { + if (_arr[i] == null) { + continue; + } + switch (event) { + // only swap for save event for now, we may change this to all event types later + case 'save': + val = _this[i]; + break; + default: + // NO-OP + break; + } + + if (_arr[i].isMongooseArray) { + notify(val, _arr[i]); + } else if (_arr[i]) { + _arr[i].emit(event, val); + } + } + }; + }, + + _markModified(elem, embeddedPath) { + const parent = this[arrayParentSymbol]; + let dirtyPath; + + if (parent) { + dirtyPath = this[arrayPathSymbol]; + + if (arguments.length) { + if (embeddedPath != null) { + // an embedded doc bubbled up the change + const index = elem.__index; + dirtyPath = dirtyPath + '.' + index + '.' + embeddedPath; + } else { + // directly set an index + dirtyPath = dirtyPath + '.' + elem; + } + } + + if (dirtyPath != null && dirtyPath.endsWith('.$')) { + return this; + } + + parent.markModified(dirtyPath, arguments.length > 0 ? elem : parent); + } + + return this; + } +}; + +module.exports = methods; + +/*! + * If this is a document array, each element may contain single + * populated paths, so we need to modify the top-level document's + * populated cache. See gh-8247, gh-8265. + */ + +function _updateParentPopulated(arr) { + const parent = arr[arrayParentSymbol]; + if (!parent || parent.$__.populated == null) return; + + const populatedPaths = Object.keys(parent.$__.populated). + filter(p => p.startsWith(arr[arrayPathSymbol] + '.')); + + for (const path of populatedPaths) { + const remnant = path.slice((arr[arrayPathSymbol] + '.').length); + if (!Array.isArray(parent.$__.populated[path].value)) { + continue; + } + + parent.$__.populated[path].value = arr.map(val => val.$populated(remnant)); + } +} \ No newline at end of file diff --git a/node_modules/mongoose/lib/types/array/ArrayWrapper.js b/node_modules/mongoose/lib/types/array/ArrayWrapper.js new file mode 100644 index 0000000..90d057f --- /dev/null +++ b/node_modules/mongoose/lib/types/array/ArrayWrapper.js @@ -0,0 +1,981 @@ +'use strict'; + +const Document = require('../../document'); +const ArraySubdocument = require('../ArraySubdocument'); +const MongooseError = require('../../error/mongooseError'); +const ObjectId = require('../objectid'); +const cleanModifiedSubpaths = require('../../helpers/document/cleanModifiedSubpaths'); +const get = require('../../helpers/get'); +const internalToObjectOptions = require('../../options').internalToObjectOptions; +const utils = require('../../utils'); +const util = require('util'); + +const arrayAtomicsSymbol = require('../../helpers/symbols').arrayAtomicsSymbol; +const arrayParentSymbol = require('../../helpers/symbols').arrayParentSymbol; +const arrayPathSymbol = require('../../helpers/symbols').arrayPathSymbol; +const arraySchemaSymbol = require('../../helpers/symbols').arraySchemaSymbol; +const populateModelSymbol = require('../../helpers/symbols').populateModelSymbol; +const slicedSymbol = Symbol('mongoose#Array#sliced'); + +const _basePush = Array.prototype.push; + +const validatorsSymbol = Symbol('mongoose#MongooseCoreArray#validators'); + +/*! + * ignore + */ + +class ArrayWrapper extends Array { + get isMongooseArray() { + return true; + } + + get validators() { + return this[validatorsSymbol]; + } + + set validators(v) { + this[validatorsSymbol] = v; + } + + /** + * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. + * + * If no atomics exist, we return all array values after conversion. + * + * @return {Array} + * @method $__getAtomics + * @memberOf MongooseArray + * @instance + * @api private + */ + + $__getAtomics() { + const ret = []; + const keys = Object.keys(this[arrayAtomicsSymbol] || {}); + let i = keys.length; + + const opts = Object.assign({}, internalToObjectOptions, { _isNested: true }); + + if (i === 0) { + ret[0] = ['$set', this.toObject(opts)]; + return ret; + } + + while (i--) { + const op = keys[i]; + let val = this[arrayAtomicsSymbol][op]; + + // the atomic values which are arrays are not MongooseArrays. we + // need to convert their elements as if they were MongooseArrays + // to handle populated arrays versus DocumentArrays properly. + if (utils.isMongooseObject(val)) { + val = val.toObject(opts); + } else if (Array.isArray(val)) { + val = this.toObject.call(val, opts); + } else if (val != null && Array.isArray(val.$each)) { + val.$each = this.toObject.call(val.$each, opts); + } else if (val != null && typeof val.valueOf === 'function') { + val = val.valueOf(); + } + + if (op === '$addToSet') { + val = { $each: val }; + } + + ret.push([op, val]); + } + + return ret; + } + + /*! + * ignore + */ + + $atomics() { + return this[arrayAtomicsSymbol] || {}; + } + + /*! + * ignore + */ + + $parent() { + return this[arrayParentSymbol]; + } + + /*! + * ignore + */ + + $path() { + return this[arrayPathSymbol]; + } + + /** + * Atomically shifts the array at most one time per document `save()`. + * + * ####NOTE: + * + * _Calling this multiple times on an array before saving sends the same command as calling it once._ + * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ + * + * doc.array = [1,2,3]; + * + * const shifted = doc.array.$shift(); + * console.log(shifted); // 1 + * console.log(doc.array); // [2,3] + * + * // no affect + * shifted = doc.array.$shift(); + * console.log(doc.array); // [2,3] + * + * doc.save(function (err) { + * if (err) return handleError(err); + * + * // we saved, now $shift works again + * shifted = doc.array.$shift(); + * console.log(shifted ); // 2 + * console.log(doc.array); // [3] + * }) + * + * @api public + * @memberOf MongooseArray + * @instance + * @method $shift + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop + */ + + $shift() { + this._registerAtomic('$pop', -1); + this._markModified(); + + // only allow shifting once + if (this._shifted) { + return; + } + this._shifted = true; + + return [].shift.call(this); + } + + /** + * Pops the array atomically at most one time per document `save()`. + * + * #### NOTE: + * + * _Calling this mulitple times on an array before saving sends the same command as calling it once._ + * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ + * + * doc.array = [1,2,3]; + * + * const popped = doc.array.$pop(); + * console.log(popped); // 3 + * console.log(doc.array); // [1,2] + * + * // no affect + * popped = doc.array.$pop(); + * console.log(doc.array); // [1,2] + * + * doc.save(function (err) { + * if (err) return handleError(err); + * + * // we saved, now $pop works again + * popped = doc.array.$pop(); + * console.log(popped); // 2 + * console.log(doc.array); // [1] + * }) + * + * @api public + * @method $pop + * @memberOf MongooseArray + * @instance + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop + * @method $pop + * @memberOf MongooseArray + */ + + $pop() { + this._registerAtomic('$pop', 1); + this._markModified(); + + // only allow popping once + if (this._popped) { + return; + } + this._popped = true; + + return [].pop.call(this); + } + + /*! + * ignore + */ + + $schema() { + return this[arraySchemaSymbol]; + } + + /** + * Casts a member based on this arrays schema. + * + * @param {any} value + * @return value the casted value + * @method _cast + * @api private + * @memberOf MongooseArray + */ + + _cast(value) { + let populated = false; + let Model; + + if (this[arrayParentSymbol]) { + populated = this[arrayParentSymbol].$populated(this[arrayPathSymbol], true); + } + + if (populated && value !== null && value !== undefined) { + // cast to the populated Models schema + Model = populated.options[populateModelSymbol]; + + // only objects are permitted so we can safely assume that + // non-objects are to be interpreted as _id + if (Buffer.isBuffer(value) || + value instanceof ObjectId || !utils.isObject(value)) { + value = { _id: value }; + } + + // gh-2399 + // we should cast model only when it's not a discriminator + const isDisc = value.$__schema && value.$__schema.discriminatorMapping && + value.$__schema.discriminatorMapping.key !== undefined; + if (!isDisc) { + value = new Model(value); + } + return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], true); + } + + return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], false); + } + + /** + * Internal helper for .map() + * + * @api private + * @return {Number} + * @method _mapCast + * @memberOf MongooseArray + */ + + _mapCast(val, index) { + return this._cast(val, this.length + index); + } + + /** + * Marks this array as modified. + * + * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) + * + * @param {ArraySubdocument} subdoc the embedded doc that invoked this method on the Array + * @param {String} embeddedPath the path which changed in the subdoc + * @method _markModified + * @api private + * @memberOf MongooseArray + */ + + _markModified(elem) { + const parent = this[arrayParentSymbol]; + let dirtyPath; + + if (parent) { + dirtyPath = this[arrayPathSymbol]; + + if (arguments.length) { + dirtyPath = dirtyPath + '.' + elem; + } + + if (dirtyPath != null && dirtyPath.endsWith('.$')) { + return this; + } + + parent.markModified(dirtyPath, arguments.length > 0 ? elem : parent); + } + + return this; + } + + /** + * Register an atomic operation with the parent. + * + * @param {Array} op operation + * @param {any} val + * @method _registerAtomic + * @api private + * @memberOf MongooseArray + */ + + _registerAtomic(op, val) { + if (this[slicedSymbol]) { + return; + } + if (op === '$set') { + // $set takes precedence over all other ops. + // mark entire array modified. + this[arrayAtomicsSymbol] = { $set: val }; + cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]); + this._markModified(); + return this; + } + + this[arrayAtomicsSymbol] || (this[arrayAtomicsSymbol] = {}); + + const atomics = this[arrayAtomicsSymbol]; + + // reset pop/shift after save + if (op === '$pop' && !('$pop' in atomics)) { + const _this = this; + this[arrayParentSymbol].once('save', function() { + _this._popped = _this._shifted = null; + }); + } + + // check for impossible $atomic combos (Mongo denies more than one + // $atomic op on a single path + if (atomics.$set || Object.keys(atomics).length && !(op in atomics)) { + // a different op was previously registered. + // save the entire thing. + this[arrayAtomicsSymbol] = { $set: this }; + return this; + } + + let selector; + + if (op === '$pullAll' || op === '$addToSet') { + atomics[op] || (atomics[op] = []); + atomics[op] = atomics[op].concat(val); + } else if (op === '$pullDocs') { + const pullOp = atomics['$pull'] || (atomics['$pull'] = {}); + if (val[0] instanceof ArraySubdocument) { + selector = pullOp['$or'] || (pullOp['$or'] = []); + Array.prototype.push.apply(selector, val.map(function(v) { + return v.toObject({ transform: false, virtuals: false }); + })); + } else { + selector = pullOp['_id'] || (pullOp['_id'] = { $in: [] }); + selector['$in'] = selector['$in'].concat(val); + } + } else if (op === '$push') { + atomics.$push = atomics.$push || { $each: [] }; + if (val != null && utils.hasUserDefinedProperty(val, '$each')) { + atomics.$push = val; + } else { + atomics.$push.$each = atomics.$push.$each.concat(val); + } + } else { + atomics[op] = val; + } + + return this; + } + + /** + * Adds values to the array if not already present. + * + * ####Example: + * + * console.log(doc.array) // [2,3,4] + * const added = doc.array.addToSet(4,5); + * console.log(doc.array) // [2,3,4,5] + * console.log(added) // [5] + * + * @param {any} [args...] + * @return {Array} the values that were added + * @memberOf MongooseArray + * @api public + * @method addToSet + */ + + addToSet() { + _checkManualPopulation(this, arguments); + + let values = [].map.call(arguments, this._mapCast, this); + values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); + const added = []; + let type = ''; + if (values[0] instanceof ArraySubdocument) { + type = 'doc'; + } else if (values[0] instanceof Date) { + type = 'date'; + } + + const rawValues = values.isMongooseArrayProxy ? values.__array : this; + const rawArray = this.isMongooseArrayProxy ? this.__array : this; + + rawValues.forEach(function(v) { + let found; + const val = +v; + switch (type) { + case 'doc': + found = this.some(function(doc) { + return doc.equals(v); + }); + break; + case 'date': + found = this.some(function(d) { + return +d === val; + }); + break; + default: + found = ~this.indexOf(v); + } + + if (!found) { + rawArray.push(v); + this._registerAtomic('$addToSet', v); + this._markModified(); + [].push.call(added, v); + } + }, this); + + return added; + } + + /** + * Returns the number of pending atomic operations to send to the db for this array. + * + * @api private + * @return {Number} + * @method hasAtomics + * @memberOf MongooseArray + */ + + hasAtomics() { + if (!utils.isPOJO(this[arrayAtomicsSymbol])) { + return 0; + } + + return Object.keys(this[arrayAtomicsSymbol]).length; + } + + /** + * Return whether or not the `obj` is included in the array. + * + * @param {Object} obj the item to check + * @return {Boolean} + * @api public + * @method includes + * @memberOf MongooseArray + */ + + includes(obj, fromIndex) { + const ret = this.indexOf(obj, fromIndex); + return ret !== -1; + } + + /** + * Return the index of `obj` or `-1` if not found. + * + * @param {Object} obj the item to look for + * @return {Number} + * @api public + * @method indexOf + * @memberOf MongooseArray + */ + + indexOf(obj, fromIndex) { + if (obj instanceof ObjectId) { + obj = obj.toString(); + } + + fromIndex = fromIndex == null ? 0 : fromIndex; + const len = this.length; + for (let i = fromIndex; i < len; ++i) { + if (obj == this[i]) { + return i; + } + } + return -1; + } + + /** + * Helper for console.log + * + * @api public + * @method inspect + * @memberOf MongooseArray + */ + + inspect() { + return JSON.stringify(this); + } + + /** + * Pushes items to the array non-atomically. + * + * ####NOTE: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @param {any} [args...] + * @api public + * @method nonAtomicPush + * @memberOf MongooseArray + */ + + nonAtomicPush() { + const values = [].map.call(arguments, this._mapCast, this); + const ret = [].push.apply(this, values); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + } + + /** + * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. + * + * ####Note: + * + * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @see MongooseArray#$pop #types_array_MongooseArray-%24pop + * @api public + * @method pop + * @memberOf MongooseArray + */ + + pop() { + const ret = [].pop.call(this); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + } + + /** + * Pulls items from the array atomically. Equality is determined by casting + * the provided value to an embedded document and comparing using + * [the `Document.equals()` function.](./api.html#document_Document-equals) + * + * ####Examples: + * + * doc.array.pull(ObjectId) + * doc.array.pull({ _id: 'someId' }) + * doc.array.pull(36) + * doc.array.pull('tag 1', 'tag 2') + * + * To remove a document from a subdocument array we may pass an object with a matching `_id`. + * + * doc.subdocs.push({ _id: 4815162342 }) + * doc.subdocs.pull({ _id: 4815162342 }) // removed + * + * Or we may passing the _id directly and let mongoose take care of it. + * + * doc.subdocs.push({ _id: 4815162342 }) + * doc.subdocs.pull(4815162342); // works + * + * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime. + * + * @param {any} [args...] + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull + * @api public + * @method pull + * @memberOf MongooseArray + */ + + pull() { + const values = [].map.call(arguments, this._cast, this); + const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]); + let i = cur.length; + let mem; + + while (i--) { + mem = cur[i]; + if (mem instanceof Document) { + const some = values.some(function(v) { + return mem.equals(v); + }); + if (some) { + [].splice.call(cur, i, 1); + } + } else if (~cur.indexOf.call(values, mem)) { + [].splice.call(cur, i, 1); + } + } + + if (values[0] instanceof ArraySubdocument) { + this._registerAtomic('$pullDocs', values.map(function(v) { + return v.$__getValue('_id') || v; + })); + } else { + this._registerAtomic('$pullAll', values); + } + + this._markModified(); + + // Might have modified child paths and then pulled, like + // `doc.children[1].name = 'test';` followed by + // `doc.children.remove(doc.children[0]);`. In this case we fall back + // to a `$set` on the whole array. See #3511 + if (cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]) > 0) { + this._registerAtomic('$set', this); + } + + return this; + } + + /** + * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. + * + * ####Example: + * + * const schema = Schema({ nums: [Number] }); + * const Model = mongoose.model('Test', schema); + * + * const doc = await Model.create({ nums: [3, 4] }); + * doc.nums.push(5); // Add 5 to the end of the array + * await doc.save(); + * + * // You can also pass an object with `$each` as the + * // first parameter to use MongoDB's `$position` + * doc.nums.push({ + * $each: [1, 2], + * $position: 0 + * }); + * doc.nums; // [1, 2, 3, 4, 5] + * + * @param {Object} [args...] + * @api public + * @method push + * @memberOf MongooseArray + */ + + push() { + let values = arguments; + let atomic = values; + const isOverwrite = values[0] != null && + utils.hasUserDefinedProperty(values[0], '$each'); + const arr = this.isMongooseArrayProxy ? this.__array : this; + if (isOverwrite) { + atomic = values[0]; + values = values[0].$each; + } + + if (this[arraySchemaSymbol] == null) { + return _basePush.apply(this, values); + } + + _checkManualPopulation(this, values); + + const parent = this[arrayParentSymbol]; + values = [].map.call(values, this._mapCast, this); + values = this[arraySchemaSymbol].applySetters(values, parent, undefined, + undefined, { skipDocumentArrayCast: true }); + let ret; + const atomics = this[arrayAtomicsSymbol]; + + if (isOverwrite) { + atomic.$each = values; + + if (get(atomics, '$push.$each.length', 0) > 0 && + atomics.$push.$position != atomic.$position) { + throw new MongooseError('Cannot call `Array#push()` multiple times ' + + 'with different `$position`'); + } + + if (atomic.$position != null) { + [].splice.apply(arr, [atomic.$position, 0].concat(values)); + ret = this.length; + } else { + ret = [].push.apply(arr, values); + } + } else { + if (get(atomics, '$push.$each.length', 0) > 0 && + atomics.$push.$position != null) { + throw new MongooseError('Cannot call `Array#push()` multiple times ' + + 'with different `$position`'); + } + atomic = values; + ret = [].push.apply(arr, values); + } + + this._registerAtomic('$push', atomic); + this._markModified(); + return ret; + } + + /** + * Alias of [pull](#mongoosearray_MongooseArray-pull) + * + * @see MongooseArray#pull #types_array_MongooseArray-pull + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull + * @api public + * @memberOf MongooseArray + * @instance + * @method remove + */ + + remove() { + return this.pull.apply(this, arguments); + } + + /** + * Sets the casted `val` at index `i` and marks the array modified. + * + * ####Example: + * + * // given documents based on the following + * const Doc = mongoose.model('Doc', new Schema({ array: [Number] })); + * + * const doc = new Doc({ array: [2,3,4] }) + * + * console.log(doc.array) // [2,3,4] + * + * doc.array.set(1,"5"); + * console.log(doc.array); // [2,5,4] // properly cast to number + * doc.save() // the change is saved + * + * // VS not using array#set + * doc.array[1] = "5"; + * console.log(doc.array); // [2,"5",4] // no casting + * doc.save() // change is not saved + * + * @return {Array} this + * @api public + * @method set + * @memberOf MongooseArray + */ + + set(i, val, skipModified) { + if (skipModified) { + this[i] = val; + return this; + } + const value = this._cast(val, i); + this[i] = value; + this._markModified(i); + return this; + } + + /** + * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + * + * ####Example: + * + * doc.array = [2,3]; + * const res = doc.array.shift(); + * console.log(res) // 2 + * console.log(doc.array) // [3] + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method shift + * @memberOf MongooseArray + */ + + shift() { + const arr = this.isMongooseArrayProxy ? this.__array : this; + const ret = [].shift.call(arr); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + } + + /** + * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. + * + * ####NOTE: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method sort + * @memberOf MongooseArray + * @see https://masteringjs.io/tutorials/fundamentals/array-sort + */ + + sort() { + const arr = this.isMongooseArrayProxy ? this.__array : this; + const ret = [].sort.apply(arr, arguments); + this._registerAtomic('$set', this); + return ret; + } + + /** + * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method splice + * @memberOf MongooseArray + * @see https://masteringjs.io/tutorials/fundamentals/array-splice + */ + + splice() { + let ret; + const arr = this.isMongooseArrayProxy ? this.__array : this; + + _checkManualPopulation(this, Array.prototype.slice.call(arguments, 2)); + + if (arguments.length) { + let vals; + if (this[arraySchemaSymbol] == null) { + vals = arguments; + } else { + vals = []; + for (let i = 0; i < arguments.length; ++i) { + vals[i] = i < 2 ? + arguments[i] : + this._cast(arguments[i], arguments[0] + (i - 2)); + } + } + + ret = [].splice.apply(arr, vals); + this._registerAtomic('$set', this); + } + + return ret; + } + + /*! + * ignore + */ + + toBSON() { + return this.toObject(internalToObjectOptions); + } + + /** + * Returns a native js Array. + * + * @param {Object} options + * @return {Array} + * @api public + * @method toObject + * @memberOf MongooseArray + */ + + toObject(options) { + const arr = this.isMongooseArrayProxy ? this.__array : this; + if (options && options.depopulate) { + options = utils.clone(options); + options._isNested = true; + // Ensure return value is a vanilla array, because in Node.js 6+ `map()` + // is smart enough to use the inherited array's constructor. + return [].concat(arr).map(function(doc) { + return doc instanceof Document + ? doc.toObject(options) + : doc; + }); + } + + return [].concat(arr); + } + + $toObject() { + return this.constructor.prototype.toObject.apply(this, arguments); + } + + /** + * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method unshift + * @memberOf MongooseArray + */ + + unshift() { + _checkManualPopulation(this, arguments); + + let values; + if (this[arraySchemaSymbol] == null) { + values = arguments; + } else { + values = [].map.call(arguments, this._cast, this); + values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); + } + + const arr = this.isMongooseArrayProxy ? this.__array : this; + [].unshift.apply(arr, values); + this._registerAtomic('$set', this); + this._markModified(); + return this.length; + } +} + +if (util.inspect.custom) { + ArrayWrapper.prototype[util.inspect.custom] = + ArrayWrapper.prototype.inspect; +} + +/*! + * ignore + */ + +function _isAllSubdocs(docs, ref) { + if (!ref) { + return false; + } + + for (const arg of docs) { + if (arg == null) { + return false; + } + const model = arg.constructor; + if (!(arg instanceof Document) || + (model.modelName !== ref && model.baseModelName !== ref)) { + return false; + } + } + + return true; +} + +/*! + * ignore + */ + +function _checkManualPopulation(arr, docs) { + const ref = arr == null ? + null : + get(arr[arraySchemaSymbol], 'caster.options.ref', null); + if (arr.length === 0 && + docs.length > 0) { + if (_isAllSubdocs(docs, ref)) { + arr[arrayParentSymbol].$populated(arr[arrayPathSymbol], [], { + [populateModelSymbol]: docs[0].constructor + }); + } + } +} + +const returnVanillaArrayMethods = [ + 'filter', + 'flat', + 'flatMap', + 'map', + 'slice' +]; +for (const method of returnVanillaArrayMethods) { + if (Array.prototype[method] == null) { + continue; + } + + ArrayWrapper.prototype[method] = function() { + const _arr = this.isMongooseArrayProxy ? this.__array : this; + const arr = [].concat(_arr); + + return arr[method].apply(arr, arguments); + }; +} + +module.exports = ArrayWrapper; diff --git a/node_modules/mongoose/lib/types/array/index.js b/node_modules/mongoose/lib/types/array/index.js new file mode 100644 index 0000000..9b71bf4 --- /dev/null +++ b/node_modules/mongoose/lib/types/array/index.js @@ -0,0 +1,115 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const Document = require('../../document'); +const mongooseArrayMethods = require('./methods'); + +const arrayAtomicsSymbol = require('../../helpers/symbols').arrayAtomicsSymbol; +const arrayAtomicsBackupSymbol = require('../../helpers/symbols').arrayAtomicsBackupSymbol; +const arrayParentSymbol = require('../../helpers/symbols').arrayParentSymbol; +const arrayPathSymbol = require('../../helpers/symbols').arrayPathSymbol; +const arraySchemaSymbol = require('../../helpers/symbols').arraySchemaSymbol; + +/** + * Mongoose Array constructor. + * + * ####NOTE: + * + * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._ + * + * @param {Array} values + * @param {String} path + * @param {Document} doc parent document + * @api private + * @inherits Array + * @see http://bit.ly/f6CnZU + */ + +function MongooseArray(values, path, doc, schematype) { + let arr; + if (Array.isArray(values)) { + const len = values.length; + + // Perf optimizations for small arrays: much faster to use `...` than `for` + `push`, + // but large arrays may cause stack overflows. And for arrays of length 0/1, just + // modifying the array is faster. Seems small, but adds up when you have a document + // with thousands of nested arrays. + if (len === 0) { + arr = new Array(); + } else if (len === 1) { + arr = new Array(1); + arr[0] = values[0]; + } else if (len < 10000) { + arr = new Array(); + arr.push.apply(arr, values); + } else { + arr = new Array(); + for (let i = 0; i < len; ++i) { + arr.push(values[i]); + } + } + } else { + arr = []; + } + + const internals = { + [arrayAtomicsSymbol]: {}, + [arrayAtomicsBackupSymbol]: void 0, + [arrayPathSymbol]: path, + [arraySchemaSymbol]: schematype, + [arrayParentSymbol]: void 0, + isMongooseArray: true, + isMongooseArrayProxy: true, + __array: arr + }; + + if (values[arrayAtomicsSymbol] != null) { + internals[arrayAtomicsSymbol] = values[arrayAtomicsSymbol]; + } + + // Because doc comes from the context of another function, doc === global + // can happen if there was a null somewhere up the chain (see #3020) + // RB Jun 17, 2015 updated to check for presence of expected paths instead + // to make more proof against unusual node environments + if (doc != null && doc instanceof Document) { + internals[arrayParentSymbol] = doc; + internals[arraySchemaSymbol] = schematype || doc.schema.path(path); + } + + const proxy = new Proxy(arr, { + get: function(target, prop) { + if (internals.hasOwnProperty(prop)) { + return internals[prop]; + } + if (mongooseArrayMethods.hasOwnProperty(prop)) { + return mongooseArrayMethods[prop]; + } + + return arr[prop]; + }, + set: function(target, prop, val) { + if (typeof prop === 'string' && /^\d+$/.test(prop)) { + const value = mongooseArrayMethods._cast.call(proxy, val, prop); + arr[prop] = value; + mongooseArrayMethods._markModified.call(proxy, prop); + } else if (internals.hasOwnProperty(prop)) { + internals[prop] = val; + } else { + arr[prop] = val; + } + + return true; + } + }); + + return proxy; +} + +/*! + * Module exports. + */ + +module.exports = exports = MongooseArray; diff --git a/node_modules/mongoose/lib/types/array/methods/index.js b/node_modules/mongoose/lib/types/array/methods/index.js new file mode 100644 index 0000000..154f578 --- /dev/null +++ b/node_modules/mongoose/lib/types/array/methods/index.js @@ -0,0 +1,960 @@ +'use strict'; + +const Document = require('../../../document'); +const ArraySubdocument = require('../../ArraySubdocument'); +const MongooseError = require('../../../error/mongooseError'); +const ObjectId = require('../../objectid'); +const cleanModifiedSubpaths = require('../../../helpers/document/cleanModifiedSubpaths'); +const get = require('../../../helpers/get'); +const internalToObjectOptions = require('../../../options').internalToObjectOptions; +const utils = require('../../../utils'); + +const arrayAtomicsSymbol = require('../../../helpers/symbols').arrayAtomicsSymbol; +const arrayParentSymbol = require('../../../helpers/symbols').arrayParentSymbol; +const arrayPathSymbol = require('../../../helpers/symbols').arrayPathSymbol; +const arraySchemaSymbol = require('../../../helpers/symbols').arraySchemaSymbol; +const populateModelSymbol = require('../../../helpers/symbols').populateModelSymbol; +const slicedSymbol = Symbol('mongoose#Array#sliced'); + +const _basePush = Array.prototype.push; + +/*! + * ignore + */ + +const methods = { + /** + * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. + * + * If no atomics exist, we return all array values after conversion. + * + * @return {Array} + * @method $__getAtomics + * @memberOf MongooseArray + * @instance + * @api private + */ + + $__getAtomics() { + const ret = []; + const keys = Object.keys(this[arrayAtomicsSymbol] || {}); + let i = keys.length; + + const opts = Object.assign({}, internalToObjectOptions, { _isNested: true }); + + if (i === 0) { + ret[0] = ['$set', this.toObject(opts)]; + return ret; + } + + while (i--) { + const op = keys[i]; + let val = this[arrayAtomicsSymbol][op]; + + // the atomic values which are arrays are not MongooseArrays. we + // need to convert their elements as if they were MongooseArrays + // to handle populated arrays versus DocumentArrays properly. + if (utils.isMongooseObject(val)) { + val = val.toObject(opts); + } else if (Array.isArray(val)) { + val = this.toObject.call(val, opts); + } else if (val != null && Array.isArray(val.$each)) { + val.$each = this.toObject.call(val.$each, opts); + } else if (val != null && typeof val.valueOf === 'function') { + val = val.valueOf(); + } + + if (op === '$addToSet') { + val = { $each: val }; + } + + ret.push([op, val]); + } + + return ret; + }, + + /*! + * ignore + */ + + $atomics() { + return this[arrayAtomicsSymbol]; + }, + + /*! + * ignore + */ + + $parent() { + return this[arrayParentSymbol]; + }, + + /*! + * ignore + */ + + $path() { + return this[arrayPathSymbol]; + }, + + /** + * Atomically shifts the array at most one time per document `save()`. + * + * ####NOTE: + * + * _Calling this multiple times on an array before saving sends the same command as calling it once._ + * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ + * + * doc.array = [1,2,3]; + * + * const shifted = doc.array.$shift(); + * console.log(shifted); // 1 + * console.log(doc.array); // [2,3] + * + * // no affect + * shifted = doc.array.$shift(); + * console.log(doc.array); // [2,3] + * + * doc.save(function (err) { + * if (err) return handleError(err); + * + * // we saved, now $shift works again + * shifted = doc.array.$shift(); + * console.log(shifted ); // 2 + * console.log(doc.array); // [3] + * }) + * + * @api public + * @memberOf MongooseArray + * @instance + * @method $shift + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop + */ + + $shift() { + this._registerAtomic('$pop', -1); + this._markModified(); + + // only allow shifting once + if (this._shifted) { + return; + } + this._shifted = true; + + return [].shift.call(this); + }, + + /** + * Pops the array atomically at most one time per document `save()`. + * + * #### NOTE: + * + * _Calling this mulitple times on an array before saving sends the same command as calling it once._ + * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ + * + * doc.array = [1,2,3]; + * + * const popped = doc.array.$pop(); + * console.log(popped); // 3 + * console.log(doc.array); // [1,2] + * + * // no affect + * popped = doc.array.$pop(); + * console.log(doc.array); // [1,2] + * + * doc.save(function (err) { + * if (err) return handleError(err); + * + * // we saved, now $pop works again + * popped = doc.array.$pop(); + * console.log(popped); // 2 + * console.log(doc.array); // [1] + * }) + * + * @api public + * @method $pop + * @memberOf MongooseArray + * @instance + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop + * @method $pop + * @memberOf MongooseArray + */ + + $pop() { + this._registerAtomic('$pop', 1); + this._markModified(); + + // only allow popping once + if (this._popped) { + return; + } + this._popped = true; + + return [].pop.call(this); + }, + + /*! + * ignore + */ + + $schema() { + return this[arraySchemaSymbol]; + }, + + /** + * Casts a member based on this arrays schema. + * + * @param {any} value + * @return value the casted value + * @method _cast + * @api private + * @memberOf MongooseArray + */ + + _cast(value) { + let populated = false; + let Model; + + const parent = this[arrayParentSymbol]; + if (parent) { + populated = parent.$populated(this[arrayPathSymbol], true); + } + + if (populated && value !== null && value !== undefined) { + // cast to the populated Models schema + Model = populated.options[populateModelSymbol]; + + // only objects are permitted so we can safely assume that + // non-objects are to be interpreted as _id + if (Buffer.isBuffer(value) || + value instanceof ObjectId || !utils.isObject(value)) { + value = { _id: value }; + } + + // gh-2399 + // we should cast model only when it's not a discriminator + const isDisc = value.schema && value.schema.discriminatorMapping && + value.schema.discriminatorMapping.key !== undefined; + if (!isDisc) { + value = new Model(value); + } + return this[arraySchemaSymbol].caster.applySetters(value, parent, true); + } + + return this[arraySchemaSymbol].caster.applySetters(value, parent, false); + }, + + /** + * Internal helper for .map() + * + * @api private + * @return {Number} + * @method _mapCast + * @memberOf MongooseArray + */ + + _mapCast(val, index) { + return this._cast(val, this.length + index); + }, + + /** + * Marks this array as modified. + * + * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) + * + * @param {ArraySubdocument} subdoc the embedded doc that invoked this method on the Array + * @param {String} embeddedPath the path which changed in the subdoc + * @method _markModified + * @api private + * @memberOf MongooseArray + */ + + _markModified(elem) { + const parent = this[arrayParentSymbol]; + let dirtyPath; + + if (parent) { + dirtyPath = this[arrayPathSymbol]; + + if (arguments.length) { + dirtyPath = dirtyPath + '.' + elem; + } + + if (dirtyPath != null && dirtyPath.endsWith('.$')) { + return this; + } + + parent.markModified(dirtyPath, arguments.length > 0 ? elem : parent); + } + + return this; + }, + + /** + * Register an atomic operation with the parent. + * + * @param {Array} op operation + * @param {any} val + * @method _registerAtomic + * @api private + * @memberOf MongooseArray + */ + + _registerAtomic(op, val) { + if (this[slicedSymbol]) { + return; + } + if (op === '$set') { + // $set takes precedence over all other ops. + // mark entire array modified. + this[arrayAtomicsSymbol] = { $set: val }; + cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]); + this._markModified(); + return this; + } + + const atomics = this[arrayAtomicsSymbol]; + + // reset pop/shift after save + if (op === '$pop' && !('$pop' in atomics)) { + const _this = this; + this[arrayParentSymbol].once('save', function() { + _this._popped = _this._shifted = null; + }); + } + + // check for impossible $atomic combos (Mongo denies more than one + // $atomic op on a single path + if (atomics.$set || Object.keys(atomics).length && !(op in atomics)) { + // a different op was previously registered. + // save the entire thing. + this[arrayAtomicsSymbol] = { $set: this }; + return this; + } + + let selector; + + if (op === '$pullAll' || op === '$addToSet') { + atomics[op] || (atomics[op] = []); + atomics[op] = atomics[op].concat(val); + } else if (op === '$pullDocs') { + const pullOp = atomics['$pull'] || (atomics['$pull'] = {}); + if (val[0] instanceof ArraySubdocument) { + selector = pullOp['$or'] || (pullOp['$or'] = []); + Array.prototype.push.apply(selector, val.map(function(v) { + return v.toObject({ transform: false, virtuals: false }); + })); + } else { + selector = pullOp['_id'] || (pullOp['_id'] = { $in: [] }); + selector['$in'] = selector['$in'].concat(val); + } + } else if (op === '$push') { + atomics.$push = atomics.$push || { $each: [] }; + if (val != null && utils.hasUserDefinedProperty(val, '$each')) { + atomics.$push = val; + } else { + atomics.$push.$each = atomics.$push.$each.concat(val); + } + } else { + atomics[op] = val; + } + + return this; + }, + + /** + * Adds values to the array if not already present. + * + * ####Example: + * + * console.log(doc.array) // [2,3,4] + * const added = doc.array.addToSet(4,5); + * console.log(doc.array) // [2,3,4,5] + * console.log(added) // [5] + * + * @param {any} [args...] + * @return {Array} the values that were added + * @memberOf MongooseArray + * @api public + * @method addToSet + */ + + addToSet() { + _checkManualPopulation(this, arguments); + + let values = [].map.call(arguments, this._mapCast, this); + values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); + const added = []; + let type = ''; + if (values[0] instanceof ArraySubdocument) { + type = 'doc'; + } else if (values[0] instanceof Date) { + type = 'date'; + } + + const rawValues = values.isMongooseArrayProxy ? values.__array : this; + const rawArray = this.isMongooseArrayProxy ? this.__array : this; + + rawValues.forEach(function(v) { + let found; + const val = +v; + switch (type) { + case 'doc': + found = this.some(function(doc) { + return doc.equals(v); + }); + break; + case 'date': + found = this.some(function(d) { + return +d === val; + }); + break; + default: + found = ~this.indexOf(v); + } + + if (!found) { + rawArray.push(v); + this._registerAtomic('$addToSet', v); + this._markModified(); + [].push.call(added, v); + } + }, this); + + return added; + }, + + /** + * Returns the number of pending atomic operations to send to the db for this array. + * + * @api private + * @return {Number} + * @method hasAtomics + * @memberOf MongooseArray + */ + + hasAtomics() { + if (!utils.isPOJO(this[arrayAtomicsSymbol])) { + return 0; + } + + return Object.keys(this[arrayAtomicsSymbol]).length; + }, + + /** + * Return whether or not the `obj` is included in the array. + * + * @param {Object} obj the item to check + * @return {Boolean} + * @api public + * @method includes + * @memberOf MongooseArray + */ + + includes(obj, fromIndex) { + const ret = this.indexOf(obj, fromIndex); + return ret !== -1; + }, + + /** + * Return the index of `obj` or `-1` if not found. + * + * @param {Object} obj the item to look for + * @return {Number} + * @api public + * @method indexOf + * @memberOf MongooseArray + */ + + indexOf(obj, fromIndex) { + if (obj instanceof ObjectId) { + obj = obj.toString(); + } + + fromIndex = fromIndex == null ? 0 : fromIndex; + const len = this.length; + for (let i = fromIndex; i < len; ++i) { + if (obj == this[i]) { + return i; + } + } + return -1; + }, + + /** + * Helper for console.log + * + * @api public + * @method inspect + * @memberOf MongooseArray + */ + + inspect() { + return JSON.stringify(this); + }, + + /** + * Pushes items to the array non-atomically. + * + * ####NOTE: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @param {any} [args...] + * @api public + * @method nonAtomicPush + * @memberOf MongooseArray + */ + + nonAtomicPush() { + const values = [].map.call(arguments, this._mapCast, this); + const ret = [].push.apply(this, values); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. + * + * ####Note: + * + * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @see MongooseArray#$pop #types_array_MongooseArray-%24pop + * @api public + * @method pop + * @memberOf MongooseArray + */ + + pop() { + const ret = [].pop.call(this); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Pulls items from the array atomically. Equality is determined by casting + * the provided value to an embedded document and comparing using + * [the `Document.equals()` function.](./api.html#document_Document-equals) + * + * ####Examples: + * + * doc.array.pull(ObjectId) + * doc.array.pull({ _id: 'someId' }) + * doc.array.pull(36) + * doc.array.pull('tag 1', 'tag 2') + * + * To remove a document from a subdocument array we may pass an object with a matching `_id`. + * + * doc.subdocs.push({ _id: 4815162342 }) + * doc.subdocs.pull({ _id: 4815162342 }) // removed + * + * Or we may passing the _id directly and let mongoose take care of it. + * + * doc.subdocs.push({ _id: 4815162342 }) + * doc.subdocs.pull(4815162342); // works + * + * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime. + * + * @param {any} [args...] + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull + * @api public + * @method pull + * @memberOf MongooseArray + */ + + pull() { + const values = [].map.call(arguments, this._cast, this); + const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]); + let i = cur.length; + let mem; + + while (i--) { + mem = cur[i]; + if (mem instanceof Document) { + const some = values.some(function(v) { + return mem.equals(v); + }); + if (some) { + [].splice.call(cur, i, 1); + } + } else if (~cur.indexOf.call(values, mem)) { + [].splice.call(cur, i, 1); + } + } + + if (values[0] instanceof ArraySubdocument) { + this._registerAtomic('$pullDocs', values.map(function(v) { + return v.$__getValue('_id') || v; + })); + } else { + this._registerAtomic('$pullAll', values); + } + + this._markModified(); + + // Might have modified child paths and then pulled, like + // `doc.children[1].name = 'test';` followed by + // `doc.children.remove(doc.children[0]);`. In this case we fall back + // to a `$set` on the whole array. See #3511 + if (cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]) > 0) { + this._registerAtomic('$set', this); + } + + return this; + }, + + /** + * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. + * + * ####Example: + * + * const schema = Schema({ nums: [Number] }); + * const Model = mongoose.model('Test', schema); + * + * const doc = await Model.create({ nums: [3, 4] }); + * doc.nums.push(5); // Add 5 to the end of the array + * await doc.save(); + * + * // You can also pass an object with `$each` as the + * // first parameter to use MongoDB's `$position` + * doc.nums.push({ + * $each: [1, 2], + * $position: 0 + * }); + * doc.nums; // [1, 2, 3, 4, 5] + * + * @param {Object} [args...] + * @api public + * @method push + * @memberOf MongooseArray + */ + + push() { + let values = arguments; + let atomic = values; + const isOverwrite = values[0] != null && + utils.hasUserDefinedProperty(values[0], '$each'); + const arr = this.isMongooseArrayProxy ? this.__array : this; + if (isOverwrite) { + atomic = values[0]; + values = values[0].$each; + } + + if (this[arraySchemaSymbol] == null) { + return _basePush.apply(this, values); + } + + _checkManualPopulation(this, values); + + const parent = this[arrayParentSymbol]; + values = [].map.call(values, this._mapCast, this); + values = this[arraySchemaSymbol].applySetters(values, parent, undefined, + undefined, { skipDocumentArrayCast: true }); + let ret; + const atomics = this[arrayAtomicsSymbol]; + + if (isOverwrite) { + atomic.$each = values; + + if (get(atomics, '$push.$each.length', 0) > 0 && + atomics.$push.$position != atomic.$position) { + throw new MongooseError('Cannot call `Array#push()` multiple times ' + + 'with different `$position`'); + } + + if (atomic.$position != null) { + [].splice.apply(arr, [atomic.$position, 0].concat(values)); + ret = this.length; + } else { + ret = [].push.apply(arr, values); + } + } else { + if (get(atomics, '$push.$each.length', 0) > 0 && + atomics.$push.$position != null) { + throw new MongooseError('Cannot call `Array#push()` multiple times ' + + 'with different `$position`'); + } + atomic = values; + ret = [].push.apply(arr, values); + } + + this._registerAtomic('$push', atomic); + this._markModified(); + return ret; + }, + + /** + * Alias of [pull](#mongoosearray_MongooseArray-pull) + * + * @see MongooseArray#pull #types_array_MongooseArray-pull + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull + * @api public + * @memberOf MongooseArray + * @instance + * @method remove + */ + + remove() { + return this.pull.apply(this, arguments); + }, + + /** + * Sets the casted `val` at index `i` and marks the array modified. + * + * ####Example: + * + * // given documents based on the following + * const Doc = mongoose.model('Doc', new Schema({ array: [Number] })); + * + * const doc = new Doc({ array: [2,3,4] }) + * + * console.log(doc.array) // [2,3,4] + * + * doc.array.set(1,"5"); + * console.log(doc.array); // [2,5,4] // properly cast to number + * doc.save() // the change is saved + * + * // VS not using array#set + * doc.array[1] = "5"; + * console.log(doc.array); // [2,"5",4] // no casting + * doc.save() // change is not saved + * + * @return {Array} this + * @api public + * @method set + * @memberOf MongooseArray + */ + + set(i, val, skipModified) { + const arr = this.__array; + if (skipModified) { + arr[i] = val; + return this; + } + const value = methods._cast.call(this, val, i); + arr[i] = value; + methods._markModified.call(this, i); + return this; + }, + + /** + * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + * + * ####Example: + * + * doc.array = [2,3]; + * const res = doc.array.shift(); + * console.log(res) // 2 + * console.log(doc.array) // [3] + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method shift + * @memberOf MongooseArray + */ + + shift() { + const arr = this.isMongooseArrayProxy ? this.__array : this; + const ret = [].shift.call(arr); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. + * + * ####NOTE: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method sort + * @memberOf MongooseArray + * @see https://masteringjs.io/tutorials/fundamentals/array-sort + */ + + sort() { + const arr = this.isMongooseArrayProxy ? this.__array : this; + const ret = [].sort.apply(arr, arguments); + this._registerAtomic('$set', this); + return ret; + }, + + /** + * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method splice + * @memberOf MongooseArray + * @see https://masteringjs.io/tutorials/fundamentals/array-splice + */ + + splice() { + let ret; + const arr = this.isMongooseArrayProxy ? this.__array : this; + + _checkManualPopulation(this, Array.prototype.slice.call(arguments, 2)); + + if (arguments.length) { + let vals; + if (this[arraySchemaSymbol] == null) { + vals = arguments; + } else { + vals = []; + for (let i = 0; i < arguments.length; ++i) { + vals[i] = i < 2 ? + arguments[i] : + this._cast(arguments[i], arguments[0] + (i - 2)); + } + } + + ret = [].splice.apply(arr, vals); + this._registerAtomic('$set', this); + } + + return ret; + }, + + /*! + * ignore + */ + + toBSON() { + return this.toObject(internalToObjectOptions); + }, + + /** + * Returns a native js Array. + * + * @param {Object} options + * @return {Array} + * @api public + * @method toObject + * @memberOf MongooseArray + */ + + toObject(options) { + const arr = this.isMongooseArrayProxy ? this.__array : this; + if (options && options.depopulate) { + options = utils.clone(options); + options._isNested = true; + // Ensure return value is a vanilla array, because in Node.js 6+ `map()` + // is smart enough to use the inherited array's constructor. + return [].concat(arr).map(function(doc) { + return doc instanceof Document + ? doc.toObject(options) + : doc; + }); + } + + return [].concat(arr); + }, + + $toObject() { + return this.constructor.prototype.toObject.apply(this, arguments); + }, + /** + * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method unshift + * @memberOf MongooseArray + */ + + unshift() { + _checkManualPopulation(this, arguments); + + let values; + if (this[arraySchemaSymbol] == null) { + values = arguments; + } else { + values = [].map.call(arguments, this._cast, this); + values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); + } + + const arr = this.isMongooseArrayProxy ? this.__array : this; + [].unshift.apply(arr, values); + this._registerAtomic('$set', this); + this._markModified(); + return this.length; + } +}; + +/*! + * ignore + */ + +function _isAllSubdocs(docs, ref) { + if (!ref) { + return false; + } + + for (const arg of docs) { + if (arg == null) { + return false; + } + const model = arg.constructor; + if (!(arg instanceof Document) || + (model.modelName !== ref && model.baseModelName !== ref)) { + return false; + } + } + + return true; +} + +/*! + * ignore + */ + +function _checkManualPopulation(arr, docs) { + const ref = arr == null ? + null : + get(arr[arraySchemaSymbol], 'caster.options.ref', null); + if (arr.length === 0 && + docs.length > 0) { + if (_isAllSubdocs(docs, ref)) { + arr[arrayParentSymbol].$populated(arr[arrayPathSymbol], [], { + [populateModelSymbol]: docs[0].constructor + }); + } + } +} + +const returnVanillaArrayMethods = [ + 'filter', + 'flat', + 'flatMap', + 'map', + 'slice' +]; +for (const method of returnVanillaArrayMethods) { + if (Array.prototype[method] == null) { + continue; + } + + methods[method] = function() { + const _arr = this.isMongooseArrayProxy ? this.__array : this; + const arr = [].concat(_arr); + + return arr[method].apply(arr, arguments); + }; +} + +module.exports = methods; diff --git a/node_modules/mongoose/lib/types/buffer.js b/node_modules/mongoose/lib/types/buffer.js new file mode 100644 index 0000000..41ba166 --- /dev/null +++ b/node_modules/mongoose/lib/types/buffer.js @@ -0,0 +1,273 @@ +/*! + * Module dependencies. + */ + +'use strict'; + +const Binary = require('../driver').get().Binary; +const utils = require('../utils'); + +/** + * Mongoose Buffer constructor. + * + * Values always have to be passed to the constructor to initialize. + * + * @param {Buffer} value + * @param {String} encode + * @param {Number} offset + * @api private + * @inherits Buffer + * @see http://bit.ly/f6CnZU + */ + +function MongooseBuffer(value, encode, offset) { + let val = value; + if (value == null) { + val = 0; + } + + let encoding; + let path; + let doc; + + if (Array.isArray(encode)) { + // internal casting + path = encode[0]; + doc = encode[1]; + } else { + encoding = encode; + } + + let buf; + if (typeof val === 'number' || val instanceof Number) { + buf = Buffer.alloc(val); + } else { // string, array or object { type: 'Buffer', data: [...] } + buf = Buffer.from(val, encoding, offset); + } + utils.decorate(buf, MongooseBuffer.mixin); + buf.isMongooseBuffer = true; + + // make sure these internal props don't show up in Object.keys() + buf[MongooseBuffer.pathSymbol] = path; + buf[parentSymbol] = doc; + + buf._subtype = 0; + return buf; +} + +const pathSymbol = Symbol.for('mongoose#Buffer#_path'); +const parentSymbol = Symbol.for('mongoose#Buffer#_parent'); +MongooseBuffer.pathSymbol = pathSymbol; + +/*! + * Inherit from Buffer. + */ + +MongooseBuffer.mixin = { + + /** + * Default subtype for the Binary representing this Buffer + * + * @api private + * @property _subtype + * @receiver MongooseBuffer + */ + + _subtype: undefined, + + /** + * Marks this buffer as modified. + * + * @api private + * @method _markModified + * @receiver MongooseBuffer + */ + + _markModified: function() { + const parent = this[parentSymbol]; + + if (parent) { + parent.markModified(this[MongooseBuffer.pathSymbol]); + } + return this; + }, + + /** + * Writes the buffer. + * + * @api public + * @method write + * @receiver MongooseBuffer + */ + + write: function() { + const written = Buffer.prototype.write.apply(this, arguments); + + if (written > 0) { + this._markModified(); + } + + return written; + }, + + /** + * Copies the buffer. + * + * ####Note: + * + * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. + * + * @return {Number} The number of bytes copied. + * @param {Buffer} target + * @method copy + * @receiver MongooseBuffer + */ + + copy: function(target) { + const ret = Buffer.prototype.copy.apply(this, arguments); + + if (target && target.isMongooseBuffer) { + target._markModified(); + } + + return ret; + } +}; + +/*! + * Compile other Buffer methods marking this buffer as modified. + */ + +( +// node < 0.5 + ('writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' + + 'writeFloat writeDouble fill ' + + 'utf8Write binaryWrite asciiWrite set ' + + + // node >= 0.5 + 'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' + + 'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' + 'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE') +).split(' ').forEach(function(method) { + if (!Buffer.prototype[method]) { + return; + } + MongooseBuffer.mixin[method] = function() { + const ret = Buffer.prototype[method].apply(this, arguments); + this._markModified(); + return ret; + }; +}); + +/** + * Converts this buffer to its Binary type representation. + * + * ####SubTypes: + * + * const bson = require('bson') + * bson.BSON_BINARY_SUBTYPE_DEFAULT + * bson.BSON_BINARY_SUBTYPE_FUNCTION + * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY + * bson.BSON_BINARY_SUBTYPE_UUID + * bson.BSON_BINARY_SUBTYPE_MD5 + * bson.BSON_BINARY_SUBTYPE_USER_DEFINED + * + * doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED); + * + * @see http://bsonspec.org/#/specification + * @param {Hex} [subtype] + * @return {Binary} + * @api public + * @method toObject + * @receiver MongooseBuffer + */ + +MongooseBuffer.mixin.toObject = function(options) { + const subtype = typeof options === 'number' + ? options + : (this._subtype || 0); + return new Binary(Buffer.from(this), subtype); +}; + +MongooseBuffer.mixin.$toObject = MongooseBuffer.mixin.toObject; + +/** + * Converts this buffer for storage in MongoDB, including subtype + * + * @return {Binary} + * @api public + * @method toBSON + * @receiver MongooseBuffer + */ + +MongooseBuffer.mixin.toBSON = function() { + return new Binary(this, this._subtype || 0); +}; + +/** + * Determines if this buffer is equals to `other` buffer + * + * @param {Buffer} other + * @return {Boolean} + * @method equals + * @receiver MongooseBuffer + */ + +MongooseBuffer.mixin.equals = function(other) { + if (!Buffer.isBuffer(other)) { + return false; + } + + if (this.length !== other.length) { + return false; + } + + for (let i = 0; i < this.length; ++i) { + if (this[i] !== other[i]) { + return false; + } + } + + return true; +}; + +/** + * Sets the subtype option and marks the buffer modified. + * + * ####SubTypes: + * + * const bson = require('bson') + * bson.BSON_BINARY_SUBTYPE_DEFAULT + * bson.BSON_BINARY_SUBTYPE_FUNCTION + * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY + * bson.BSON_BINARY_SUBTYPE_UUID + * bson.BSON_BINARY_SUBTYPE_MD5 + * bson.BSON_BINARY_SUBTYPE_USER_DEFINED + * + * doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID); + * + * @see http://bsonspec.org/#/specification + * @param {Hex} subtype + * @api public + * @method subtype + * @receiver MongooseBuffer + */ + +MongooseBuffer.mixin.subtype = function(subtype) { + if (typeof subtype !== 'number') { + throw new TypeError('Invalid subtype. Expected a number'); + } + + if (this._subtype !== subtype) { + this._markModified(); + } + + this._subtype = subtype; +}; + +/*! + * Module exports. + */ + +MongooseBuffer.Binary = Binary; + +module.exports = MongooseBuffer; diff --git a/node_modules/mongoose/lib/types/decimal128.js b/node_modules/mongoose/lib/types/decimal128.js new file mode 100644 index 0000000..cb08861 --- /dev/null +++ b/node_modules/mongoose/lib/types/decimal128.js @@ -0,0 +1,13 @@ +/** + * ObjectId type constructor + * + * ####Example + * + * const id = new mongoose.Types.ObjectId; + * + * @constructor ObjectId + */ + +'use strict'; + +module.exports = require('../driver').get().Decimal128; diff --git a/node_modules/mongoose/lib/types/index.js b/node_modules/mongoose/lib/types/index.js new file mode 100644 index 0000000..fbfb89a --- /dev/null +++ b/node_modules/mongoose/lib/types/index.js @@ -0,0 +1,20 @@ + +/*! + * Module exports. + */ + +'use strict'; + +exports.Array = require('./array'); +exports.Buffer = require('./buffer'); + +exports.Document = // @deprecate +exports.Embedded = require('./ArraySubdocument'); + +exports.DocumentArray = require('./DocumentArray'); +exports.Decimal128 = require('./decimal128'); +exports.ObjectId = require('./objectid'); + +exports.Map = require('./map'); + +exports.Subdocument = require('./subdocument'); diff --git a/node_modules/mongoose/lib/types/map.js b/node_modules/mongoose/lib/types/map.js new file mode 100644 index 0000000..d6f3fb3 --- /dev/null +++ b/node_modules/mongoose/lib/types/map.js @@ -0,0 +1,244 @@ +'use strict'; + +const Mixed = require('../schema/mixed'); +const ObjectId = require('./objectid'); +const clone = require('../helpers/clone'); +const deepEqual = require('../utils').deepEqual; +const get = require('../helpers/get'); +const getConstructorName = require('../helpers/getConstructorName'); +const handleSpreadDoc = require('../helpers/document/handleSpreadDoc'); +const util = require('util'); +const specialProperties = require('../helpers/specialProperties'); + +const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; + +/*! + * ignore + */ + +class MongooseMap extends Map { + constructor(v, path, doc, schemaType) { + if (getConstructorName(v) === 'Object') { + v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []); + } + super(v); + this.$__parent = doc != null && doc.$__ != null ? doc : null; + this.$__path = path; + this.$__schemaType = schemaType == null ? new Mixed(path) : schemaType; + + this.$__runDeferred(); + } + + $init(key, value) { + checkValidKey(key); + + super.set(key, value); + + if (value != null && value.$isSingleNested) { + value.$basePath = this.$__path + '.' + key; + } + } + + $__set(key, value) { + super.set(key, value); + } + + get(key, options) { + if (key instanceof ObjectId) { + key = key.toString(); + } + + options = options || {}; + if (options.getters === false) { + return super.get(key); + } + return this.$__schemaType.applyGetters(super.get(key), this.$__parent); + } + + set(key, value) { + if (key instanceof ObjectId) { + key = key.toString(); + } + + checkValidKey(key); + value = handleSpreadDoc(value); + + // Weird, but because you can't assign to `this` before calling `super()` + // you can't get access to `$__schemaType` to cast in the initial call to + // `set()` from the `super()` constructor. + + if (this.$__schemaType == null) { + this.$__deferred = this.$__deferred || []; + this.$__deferred.push({ key: key, value: value }); + return; + } + + const fullPath = this.$__path + '.' + key; + const populated = this.$__parent != null && this.$__parent.$__ ? + this.$__parent.$populated(fullPath) || this.$__parent.$populated(this.$__path) : + null; + const priorVal = this.get(key); + + if (populated != null) { + if (value.$__ == null) { + value = new populated.options[populateModelSymbol](value); + } + value.$__.wasPopulated = true; + } else { + try { + value = this.$__schemaType. + applySetters(value, this.$__parent, false, this.get(key), { path: fullPath }); + } catch (error) { + if (this.$__parent != null && this.$__parent.$__ != null) { + this.$__parent.invalidate(fullPath, error); + return; + } + throw error; + } + } + + super.set(key, value); + + if (value != null && value.$isSingleNested) { + value.$basePath = this.$__path + '.' + key; + } + + const parent = this.$__parent; + if (parent != null && parent.$__ != null && !deepEqual(value, priorVal)) { + parent.markModified(this.$__path + '.' + key); + } + } + + clear() { + super.clear(); + const parent = this.$__parent; + if (parent != null) { + parent.markModified(this.$__path); + } + } + + delete(key) { + if (key instanceof ObjectId) { + key = key.toString(); + } + + this.set(key, undefined); + super.delete(key); + } + + toBSON() { + return new Map(this); + } + + toObject(options) { + if (get(options, 'flattenMaps')) { + const ret = {}; + const keys = this.keys(); + for (const key of keys) { + ret[key] = clone(this.get(key), options); + } + return ret; + } + + return new Map(this); + } + + $toObject() { + return this.constructor.prototype.toObject.apply(this, arguments); + } + + toJSON() { + const ret = {}; + const keys = this.keys(); + for (const key of keys) { + ret[key] = this.get(key); + } + return ret; + } + + inspect() { + return new Map(this); + } + + $__runDeferred() { + if (!this.$__deferred) { + return; + } + + for (const keyValueObject of this.$__deferred) { + this.set(keyValueObject.key, keyValueObject.value); + } + + this.$__deferred = null; + } +} + +if (util.inspect.custom) { + Object.defineProperty(MongooseMap.prototype, util.inspect.custom, { + enumerable: false, + writable: false, + configurable: false, + value: MongooseMap.prototype.inspect + }); +} + +Object.defineProperty(MongooseMap.prototype, '$__set', { + enumerable: false, + writable: true, + configurable: false +}); + +Object.defineProperty(MongooseMap.prototype, '$__parent', { + enumerable: false, + writable: true, + configurable: false +}); + +Object.defineProperty(MongooseMap.prototype, '$__path', { + enumerable: false, + writable: true, + configurable: false +}); + +Object.defineProperty(MongooseMap.prototype, '$__schemaType', { + enumerable: false, + writable: true, + configurable: false +}); + +Object.defineProperty(MongooseMap.prototype, '$isMongooseMap', { + enumerable: false, + writable: false, + configurable: false, + value: true +}); + +Object.defineProperty(MongooseMap.prototype, '$__deferredCalls', { + enumerable: false, + writable: false, + configurable: false, + value: true +}); + +/*! + * Since maps are stored as objects under the hood, keys must be strings + * and can't contain any invalid characters + */ + +function checkValidKey(key) { + const keyType = typeof key; + if (keyType !== 'string') { + throw new TypeError(`Mongoose maps only support string keys, got ${keyType}`); + } + if (key.startsWith('$')) { + throw new Error(`Mongoose maps do not support keys that start with "$", got "${key}"`); + } + if (key.includes('.')) { + throw new Error(`Mongoose maps do not support keys that contain ".", got "${key}"`); + } + if (specialProperties.has(key)) { + throw new Error(`Mongoose maps do not support reserved key name "${key}"`); + } +} + +module.exports = MongooseMap; diff --git a/node_modules/mongoose/lib/types/objectid.js b/node_modules/mongoose/lib/types/objectid.js new file mode 100644 index 0000000..e4237c2 --- /dev/null +++ b/node_modules/mongoose/lib/types/objectid.js @@ -0,0 +1,41 @@ +/** + * ObjectId type constructor + * + * ####Example + * + * const id = new mongoose.Types.ObjectId; + * + * @constructor ObjectId + */ + +'use strict'; + +const ObjectId = require('../driver').get().ObjectId; +const objectIdSymbol = require('../helpers/symbols').objectIdSymbol; + +/*! + * Getter for convenience with populate, see gh-6115 + */ + +Object.defineProperty(ObjectId.prototype, '_id', { + enumerable: false, + configurable: true, + get: function() { + return this; + } +}); + +/*! + * Convenience `valueOf()` to allow comparing ObjectIds using double equals re: gh-7299 + */ + + +if (!ObjectId.prototype.hasOwnProperty('valueOf')) { + ObjectId.prototype.valueOf = function objectIdValueOf() { + return this.toString(); + }; +} + +ObjectId.prototype[objectIdSymbol] = true; + +module.exports = ObjectId; diff --git a/node_modules/mongoose/lib/types/subdocument.js b/node_modules/mongoose/lib/types/subdocument.js new file mode 100644 index 0000000..2693357 --- /dev/null +++ b/node_modules/mongoose/lib/types/subdocument.js @@ -0,0 +1,372 @@ +'use strict'; + +const Document = require('../document'); +const immediate = require('../helpers/immediate'); +const internalToObjectOptions = require('../options').internalToObjectOptions; +const promiseOrCallback = require('../helpers/promiseOrCallback'); +const util = require('util'); +const utils = require('../utils'); + +module.exports = Subdocument; + +/** + * Subdocument constructor. + * + * @inherits Document + * @api private + */ + +function Subdocument(value, fields, parent, skipId, options) { + if (parent != null) { + // If setting a nested path, should copy isNew from parent re: gh-7048 + const parentOptions = { isNew: parent.isNew, defaults: 'defaults' in parent.$__ ? parent.$__.defaults : true }; + options = Object.assign({}, parentOptions, options); + } + if (options != null && options.path != null) { + this.$basePath = options.path; + } + Document.call(this, value, fields, skipId, options); + + delete this.$__.priorDoc; +} + +Subdocument.prototype = Object.create(Document.prototype); + +Object.defineProperty(Subdocument.prototype, '$isSingleNested', { + configurable: false, + writable: false, + value: true +}); + +/*! + * ignore + */ + +Subdocument.prototype.toBSON = function() { + return this.toObject(internalToObjectOptions); +}; + +/** + * Used as a stub for middleware + * + * ####NOTE: + * + * _This is a no-op. Does not actually save the doc to the db._ + * + * @param {Function} [fn] + * @return {Promise} resolved Promise + * @api private + */ + +Subdocument.prototype.save = function(options, fn) { + if (typeof options === 'function') { + fn = options; + options = {}; + } + options = options || {}; + + if (!options.suppressWarning) { + utils.warn('mongoose: calling `save()` on a subdoc does **not** save ' + + 'the document to MongoDB, it only runs save middleware. ' + + 'Use `subdoc.save({ suppressWarning: true })` to hide this warning ' + + 'if you\'re sure this behavior is right for your app.'); + } + + return promiseOrCallback(fn, cb => { + this.$__save(cb); + }); +}; + +/*! + * Given a path relative to this document, return the path relative + * to the top-level document. + */ + +Subdocument.prototype.$__fullPath = function(path) { + if (!this.$__.fullPath) { + this.ownerDocument(); + } + + return path ? + this.$__.fullPath + '.' + path : + this.$__.fullPath; +}; + +/*! + * Given a path relative to this document, return the path relative + * to the top-level document. + */ + +Subdocument.prototype.$__pathRelativeToParent = function(p) { + if (p == null) { + return this.$basePath; + } + return [this.$basePath, p].join('.'); +}; + +/** + * Used as a stub for middleware + * + * ####NOTE: + * + * _This is a no-op. Does not actually save the doc to the db._ + * + * @param {Function} [fn] + * @method $__save + * @api private + */ + +Subdocument.prototype.$__save = function(fn) { + return immediate(() => fn(null, this)); +}; + +/*! + * ignore + */ + +Subdocument.prototype.$isValid = function(path) { + const parent = this.$parent(); + const fullPath = this.$__pathRelativeToParent(path); + if (parent != null && fullPath != null) { + return parent.$isValid(fullPath); + } + return Document.prototype.$isValid.call(this, path); +}; + +/*! + * ignore + */ + +Subdocument.prototype.markModified = function(path) { + Document.prototype.markModified.call(this, path); + const parent = this.$parent(); + const fullPath = this.$__pathRelativeToParent(path); + + if (parent == null || fullPath == null) { + return; + } + + const myPath = this.$__pathRelativeToParent().replace(/\.$/, ''); + if (parent.isDirectModified(myPath) || this.isNew) { + return; + } + this.$__parent.markModified(fullPath, this); +}; + +/*! + * ignore + */ + +Subdocument.prototype.isModified = function(paths, modifiedPaths) { + const parent = this.$parent(); + if (parent != null) { + if (Array.isArray(paths) || typeof paths === 'string') { + paths = (Array.isArray(paths) ? paths : paths.split(' ')); + paths = paths.map(p => this.$__pathRelativeToParent(p)).filter(p => p != null); + } else if (!paths) { + paths = this.$__pathRelativeToParent(); + } + + return parent.$isModified(paths, modifiedPaths); + } + + return Document.prototype.isModified.call(this, paths, modifiedPaths); +}; + +/** + * Marks a path as valid, removing existing validation errors. + * + * @param {String} path the field to mark as valid + * @api private + * @method $markValid + * @receiver Subdocument + */ + +Subdocument.prototype.$markValid = function(path) { + Document.prototype.$markValid.call(this, path); + const parent = this.$parent(); + const fullPath = this.$__pathRelativeToParent(path); + if (parent != null && fullPath != null) { + parent.$markValid(fullPath); + } +}; + +/*! + * ignore + */ + +Subdocument.prototype.invalidate = function(path, err, val) { + Document.prototype.invalidate.call(this, path, err, val); + + const parent = this.$parent(); + const fullPath = this.$__pathRelativeToParent(path); + if (parent != null && fullPath != null) { + parent.invalidate(fullPath, err, val); + } else if (err.kind === 'cast' || err.name === 'CastError' || fullPath == null) { + throw err; + } + + return this.ownerDocument().$__.validationError; +}; + +/*! + * ignore + */ + +Subdocument.prototype.$ignore = function(path) { + Document.prototype.$ignore.call(this, path); + const parent = this.$parent(); + const fullPath = this.$__pathRelativeToParent(path); + if (parent != null && fullPath != null) { + parent.$ignore(fullPath); + } +}; + +/** + * Returns the top level document of this sub-document. + * + * @return {Document} + */ + +Subdocument.prototype.ownerDocument = function() { + if (this.$__.ownerDocument) { + return this.$__.ownerDocument; + } + + let parent = this; // eslint-disable-line consistent-this + + const paths = []; + const seenDocs = new Set([parent]); + + while (true) { + if (typeof parent.$__pathRelativeToParent !== 'function') { + break; + } + paths.unshift(parent.$__pathRelativeToParent(void 0, true)); + const _parent = parent.$parent(); + if (_parent == null) { + break; + } + parent = _parent; + if (seenDocs.has(parent)) { + throw new Error('Infinite subdocument loop: subdoc with _id ' + parent._id + ' is a parent of itself'); + } + + seenDocs.add(parent); + } + + this.$__.fullPath = paths.join('.'); + + this.$__.ownerDocument = parent; + return this.$__.ownerDocument; +}; + +/** + * Returns this sub-documents parent document. + * + * @api public + */ + +Subdocument.prototype.parent = function() { + return this.$__parent; +}; + +/** + * Returns this sub-documents parent document. + * + * @api public + */ + +Subdocument.prototype.$parent = Subdocument.prototype.parent; + +/*! + * no-op for hooks + */ + +Subdocument.prototype.$__remove = function(cb) { + if (cb == null) { + return; + } + return cb(null, this); +}; + +Subdocument.prototype.$__removeFromParent = function() { + this.$__parent.set(this.$basePath, null); +}; + +/** + * Null-out this subdoc + * + * @param {Object} [options] + * @param {Function} [callback] optional callback for compatibility with Document.prototype.remove + */ + +Subdocument.prototype.remove = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = null; + } + registerRemoveListener(this); + + // If removing entire doc, no need to remove subdoc + if (!options || !options.noop) { + this.$__removeFromParent(); + } + + return this.$__remove(callback); +}; + +/*! + * ignore + */ + +Subdocument.prototype.populate = function() { + throw new Error('Mongoose does not support calling populate() on nested ' + + 'docs. Instead of `doc.nested.populate("path")`, use ' + + '`doc.populate("nested.path")`'); +}; + +/** + * Helper for console.log + * + * @api public + */ + +Subdocument.prototype.inspect = function() { + return this.toObject({ + transform: false, + virtuals: false, + flattenDecimals: false + }); +}; + +if (util.inspect.custom) { + /*! + * Avoid Node deprecation warning DEP0079 + */ + + Subdocument.prototype[util.inspect.custom] = Subdocument.prototype.inspect; +} + +/*! + * Registers remove event listeners for triggering + * on subdocuments. + * + * @param {Subdocument} sub + * @api private + */ + +function registerRemoveListener(sub) { + let owner = sub.ownerDocument(); + + function emitRemove() { + owner.$removeListener('save', emitRemove); + owner.$removeListener('remove', emitRemove); + sub.emit('remove', sub); + sub.constructor.emit('remove', sub); + owner = sub = null; + } + + owner.$on('save', emitRemove); + owner.$on('remove', emitRemove); +} diff --git a/node_modules/mongoose/lib/utils.js b/node_modules/mongoose/lib/utils.js new file mode 100644 index 0000000..5d1d85a --- /dev/null +++ b/node_modules/mongoose/lib/utils.js @@ -0,0 +1,961 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const ms = require('ms'); +const mpath = require('mpath'); +const sliced = require('sliced'); +const Decimal = require('./types/decimal128'); +const ObjectId = require('./types/objectid'); +const PopulateOptions = require('./options/PopulateOptions'); +const clone = require('./helpers/clone'); +const immediate = require('./helpers/immediate'); +const isObject = require('./helpers/isObject'); +const isBsonType = require('./helpers/isBsonType'); +const getFunctionName = require('./helpers/getFunctionName'); +const isMongooseObject = require('./helpers/isMongooseObject'); +const promiseOrCallback = require('./helpers/promiseOrCallback'); +const schemaMerge = require('./helpers/schema/merge'); +const specialProperties = require('./helpers/specialProperties'); +const { trustedSymbol } = require('./helpers/query/trusted'); + +let Document; + +exports.specialProperties = specialProperties; + +/*! + * Produces a collection name from model `name`. By default, just returns + * the model name + * + * @param {String} name a model name + * @param {Function} pluralize function that pluralizes the collection name + * @return {String} a collection name + * @api private + */ + +exports.toCollectionName = function(name, pluralize) { + if (name === 'system.profile') { + return name; + } + if (name === 'system.indexes') { + return name; + } + if (typeof pluralize === 'function') { + return pluralize(name); + } + return name; +}; + +/*! + * Determines if `a` and `b` are deep equal. + * + * Modified from node/lib/assert.js + * + * @param {any} a a value to compare to `b` + * @param {any} b a value to compare to `a` + * @return {Boolean} + * @api private + */ + +exports.deepEqual = function deepEqual(a, b) { + if (a === b) { + return true; + } + + if (typeof a !== 'object' && typeof b !== 'object') { + return a === b; + } + + if (a instanceof Date && b instanceof Date) { + return a.getTime() === b.getTime(); + } + + if ((isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID')) || + (isBsonType(a, 'Decimal128') && isBsonType(b, 'Decimal128'))) { + return a.toString() === b.toString(); + } + + if (a instanceof RegExp && b instanceof RegExp) { + return a.source === b.source && + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline && + a.global === b.global; + } + + if (a == null || b == null) { + return false; + } + + if (a.prototype !== b.prototype) { + return false; + } + + if (a instanceof Map && b instanceof Map) { + return deepEqual(Array.from(a.keys()), Array.from(b.keys())) && + deepEqual(Array.from(a.values()), Array.from(b.values())); + } + + // Handle MongooseNumbers + if (a instanceof Number && b instanceof Number) { + return a.valueOf() === b.valueOf(); + } + + if (Buffer.isBuffer(a)) { + return exports.buffer.areEqual(a, b); + } + + if (Array.isArray(a) && Array.isArray(b)) { + const len = a.length; + if (len !== b.length) { + return false; + } + for (let i = 0; i < len; ++i) { + if (!deepEqual(a[i], b[i])) { + return false; + } + } + return true; + } + + if (a.$__ != null) { + a = a._doc; + } else if (isMongooseObject(a)) { + a = a.toObject(); + } + + if (b.$__ != null) { + b = b._doc; + } else if (isMongooseObject(b)) { + b = b.toObject(); + } + + const ka = Object.keys(a); + const kb = Object.keys(b); + const kaLength = ka.length; + + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (kaLength !== kb.length) { + return false; + } + + // ~~~cheap key test + for (let i = kaLength - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) { + return false; + } + } + + // equivalent values for every corresponding key, and + // ~~~possibly expensive deep test + for (const key of ka) { + if (!deepEqual(a[key], b[key])) { + return false; + } + } + + return true; +}; + +/*! + * Get the last element of an array + */ + +exports.last = function(arr) { + if (arr.length > 0) { + return arr[arr.length - 1]; + } + return void 0; +}; + +exports.clone = clone; + +/*! + * ignore + */ + +exports.promiseOrCallback = promiseOrCallback; + +/*! + * ignore + */ + +exports.omit = function omit(obj, keys) { + if (keys == null) { + return Object.assign({}, obj); + } + if (!Array.isArray(keys)) { + keys = [keys]; + } + + const ret = Object.assign({}, obj); + for (const key of keys) { + delete ret[key]; + } + return ret; +}; + + +/*! + * Shallow copies defaults into options. + * + * @param {Object} defaults + * @param {Object} options + * @return {Object} the merged object + * @api private + */ + +exports.options = function(defaults, options) { + const keys = Object.keys(defaults); + let i = keys.length; + let k; + + options = options || {}; + + while (i--) { + k = keys[i]; + if (!(k in options)) { + options[k] = defaults[k]; + } + } + + return options; +}; + +/*! + * Generates a random string + * + * @api private + */ + +exports.random = function() { + return Math.random().toString().substr(3); +}; + +/*! + * Merges `from` into `to` without overwriting existing properties. + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +exports.merge = function merge(to, from, options, path) { + options = options || {}; + + const keys = Object.keys(from); + let i = 0; + const len = keys.length; + let key; + + if (from[trustedSymbol]) { + to[trustedSymbol] = from[trustedSymbol]; + } + + path = path || ''; + const omitNested = options.omitNested || {}; + + while (i < len) { + key = keys[i++]; + if (options.omit && options.omit[key]) { + continue; + } + if (omitNested[path]) { + continue; + } + if (specialProperties.has(key)) { + continue; + } + if (to[key] == null) { + to[key] = from[key]; + } else if (exports.isObject(from[key])) { + if (!exports.isObject(to[key])) { + to[key] = {}; + } + if (from[key] != null) { + // Skip merging schemas if we're creating a discriminator schema and + // base schema has a given path as a single nested but discriminator schema + // has the path as a document array, or vice versa (gh-9534) + if (options.isDiscriminatorSchemaMerge && + (from[key].$isSingleNested && to[key].$isMongooseDocumentArray) || + (from[key].$isMongooseDocumentArray && to[key].$isSingleNested)) { + continue; + } else if (from[key].instanceOfSchema) { + if (to[key].instanceOfSchema) { + schemaMerge(to[key], from[key].clone(), options.isDiscriminatorSchemaMerge); + } else { + to[key] = from[key].clone(); + } + continue; + } else if (from[key] instanceof ObjectId) { + to[key] = new ObjectId(from[key]); + continue; + } + } + merge(to[key], from[key], options, path ? path + '.' + key : key); + } else if (options.overwrite) { + to[key] = from[key]; + } + } +}; + +/*! + * Applies toObject recursively. + * + * @param {Document|Array|Object} obj + * @return {Object} + * @api private + */ + +exports.toObject = function toObject(obj) { + Document || (Document = require('./document')); + let ret; + + if (obj == null) { + return obj; + } + + if (obj instanceof Document) { + return obj.toObject(); + } + + if (Array.isArray(obj)) { + ret = []; + + for (const doc of obj) { + ret.push(toObject(doc)); + } + + return ret; + } + + if (exports.isPOJO(obj)) { + ret = {}; + + if (obj[trustedSymbol]) { + ret[trustedSymbol] = obj[trustedSymbol]; + } + + for (const k of Object.keys(obj)) { + if (specialProperties.has(k)) { + continue; + } + ret[k] = toObject(obj[k]); + } + + return ret; + } + + return obj; +}; + +exports.isObject = isObject; + +/*! + * Determines if `arg` is a plain old JavaScript object (POJO). Specifically, + * `arg` must be an object but not an instance of any special class, like String, + * ObjectId, etc. + * + * `Object.getPrototypeOf()` is part of ES5: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @api private + * @return {Boolean} + */ + +exports.isPOJO = function isPOJO(arg) { + if (arg == null || typeof arg !== 'object') { + return false; + } + const proto = Object.getPrototypeOf(arg); + // Prototype may be null if you used `Object.create(null)` + // Checking `proto`'s constructor is safe because `getPrototypeOf()` + // explicitly crosses the boundary from object data to object metadata + return !proto || proto.constructor.name === 'Object'; +}; + +/*! + * Determines if `arg` is an object that isn't an instance of a built-in value + * class, like Array, Buffer, ObjectId, etc. + */ + +exports.isNonBuiltinObject = function isNonBuiltinObject(val) { + return typeof val === 'object' && + !exports.isNativeObject(val) && + !exports.isMongooseType(val) && + val != null; +}; + +/*! + * Determines if `obj` is a built-in object like an array, date, boolean, + * etc. + */ + +exports.isNativeObject = function(arg) { + return Array.isArray(arg) || + arg instanceof Date || + arg instanceof Boolean || + arg instanceof Number || + arg instanceof String; +}; + +/*! + * Determines if `val` is an object that has no own keys + */ + +exports.isEmptyObject = function(val) { + return val != null && + typeof val === 'object' && + Object.keys(val).length === 0; +}; + +/*! + * Search if `obj` or any POJOs nested underneath `obj` has a property named + * `key` + */ + +exports.hasKey = function hasKey(obj, key) { + const props = Object.keys(obj); + for (const prop of props) { + if (prop === key) { + return true; + } + if (exports.isPOJO(obj[prop]) && exports.hasKey(obj[prop], key)) { + return true; + } + } + return false; +}; + +/*! + * A faster Array.prototype.slice.call(arguments) alternative + * @api private + */ + +exports.args = sliced; + +/*! + * process.nextTick helper. + * + * Wraps `callback` in a try/catch + nextTick. + * + * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. + * + * @param {Function} callback + * @api private + */ + +exports.tick = function tick(callback) { + if (typeof callback !== 'function') { + return; + } + return function() { + try { + callback.apply(this, arguments); + } catch (err) { + // only nextTick on err to get out of + // the event loop and avoid state corruption. + immediate(function() { + throw err; + }); + } + }; +}; + +/*! + * Returns true if `v` is an object that can be serialized as a primitive in + * MongoDB + */ + +exports.isMongooseType = function(v) { + return v instanceof ObjectId || v instanceof Decimal || v instanceof Buffer; +}; + +exports.isMongooseObject = isMongooseObject; + +/*! + * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB. + * + * @param {Object} object + * @api private + */ + +exports.expires = function expires(object) { + if (!(object && object.constructor.name === 'Object')) { + return; + } + if (!('expires' in object)) { + return; + } + + let when; + if (typeof object.expires !== 'string') { + when = object.expires; + } else { + when = Math.round(ms(object.expires) / 1000); + } + object.expireAfterSeconds = when; + delete object.expires; +}; + +/*! + * populate helper + */ + +exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) { + // might have passed an object specifying all arguments + let obj = null; + if (arguments.length === 1) { + if (path instanceof PopulateOptions) { + return [path]; + } + + if (Array.isArray(path)) { + const singles = makeSingles(path); + return singles.map(o => exports.populate(o)[0]); + } + + if (exports.isObject(path)) { + obj = Object.assign({}, path); + } else { + obj = { path: path }; + } + } else if (typeof model === 'object') { + obj = { + path: path, + select: select, + match: model, + options: match + }; + } else { + obj = { + path: path, + select: select, + model: model, + match: match, + options: options, + populate: subPopulate, + justOne: justOne, + count: count + }; + } + + if (typeof obj.path !== 'string') { + throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); + } + + return _populateObj(obj); + + // The order of select/conditions args is opposite Model.find but + // necessary to keep backward compatibility (select could be + // an array, string, or object literal). + function makeSingles(arr) { + const ret = []; + arr.forEach(function(obj) { + if (/[\s]/.test(obj.path)) { + const paths = obj.path.split(' '); + paths.forEach(function(p) { + const copy = Object.assign({}, obj); + copy.path = p; + ret.push(copy); + }); + } else { + ret.push(obj); + } + }); + + return ret; + } +}; + +function _populateObj(obj) { + if (Array.isArray(obj.populate)) { + const ret = []; + obj.populate.forEach(function(obj) { + if (/[\s]/.test(obj.path)) { + const copy = Object.assign({}, obj); + const paths = copy.path.split(' '); + paths.forEach(function(p) { + copy.path = p; + ret.push(exports.populate(copy)[0]); + }); + } else { + ret.push(exports.populate(obj)[0]); + } + }); + obj.populate = exports.populate(ret); + } else if (obj.populate != null && typeof obj.populate === 'object') { + obj.populate = exports.populate(obj.populate); + } + + const ret = []; + const paths = obj.path.split(' '); + if (obj.options != null) { + obj.options = exports.clone(obj.options); + } + + for (const path of paths) { + ret.push(new PopulateOptions(Object.assign({}, obj, { path: path }))); + } + + return ret; +} + +/*! + * Return the value of `obj` at the given `path`. + * + * @param {String} path + * @param {Object} obj + */ + +exports.getValue = function(path, obj, map) { + return mpath.get(path, obj, '_doc', map); +}; + +/*! + * Sets the value of `obj` at the given `path`. + * + * @param {String} path + * @param {Anything} val + * @param {Object} obj + */ + +exports.setValue = function(path, val, obj, map, _copying) { + mpath.set(path, val, obj, '_doc', map, _copying); +}; + +/*! + * Returns an array of values from object `o`. + * + * @param {Object} o + * @return {Array} + * @private + */ + +exports.object = {}; +exports.object.vals = function vals(o) { + const keys = Object.keys(o); + let i = keys.length; + const ret = []; + + while (i--) { + ret.push(o[keys[i]]); + } + + return ret; +}; + +/*! + * @see exports.options + */ + +exports.object.shallowCopy = exports.options; + +/*! + * Safer helper for hasOwnProperty checks + * + * @param {Object} obj + * @param {String} prop + */ + +const hop = Object.prototype.hasOwnProperty; +exports.object.hasOwnProperty = function(obj, prop) { + return hop.call(obj, prop); +}; + +/*! + * Determine if `val` is null or undefined + * + * @return {Boolean} + */ + +exports.isNullOrUndefined = function(val) { + return val === null || val === undefined; +}; + +/*! + * ignore + */ + +exports.array = {}; + +/*! + * Flattens an array. + * + * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4] + * + * @param {Array} arr + * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsy value, the item will not be included in the results. + * @return {Array} + * @private + */ + +exports.array.flatten = function flatten(arr, filter, ret) { + ret || (ret = []); + + arr.forEach(function(item) { + if (Array.isArray(item)) { + flatten(item, filter, ret); + } else { + if (!filter || filter(item)) { + ret.push(item); + } + } + }); + + return ret; +}; + +/*! + * ignore + */ + +const _hasOwnProperty = Object.prototype.hasOwnProperty; + +exports.hasUserDefinedProperty = function(obj, key) { + if (obj == null) { + return false; + } + + if (Array.isArray(key)) { + for (const k of key) { + if (exports.hasUserDefinedProperty(obj, k)) { + return true; + } + } + return false; + } + + if (_hasOwnProperty.call(obj, key)) { + return true; + } + if (typeof obj === 'object' && key in obj) { + const v = obj[key]; + return v !== Object.prototype[key] && v !== Array.prototype[key]; + } + + return false; +}; + +/*! + * ignore + */ + +const MAX_ARRAY_INDEX = Math.pow(2, 32) - 1; + +exports.isArrayIndex = function(val) { + if (typeof val === 'number') { + return val >= 0 && val <= MAX_ARRAY_INDEX; + } + if (typeof val === 'string') { + if (!/^\d+$/.test(val)) { + return false; + } + val = +val; + return val >= 0 && val <= MAX_ARRAY_INDEX; + } + + return false; +}; + +/*! + * Removes duplicate values from an array + * + * [1, 2, 3, 3, 5] => [1, 2, 3, 5] + * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ] + * => [ObjectId("550988ba0c19d57f697dc45e")] + * + * @param {Array} arr + * @return {Array} + * @private + */ + +exports.array.unique = function(arr) { + const primitives = new Set(); + const ids = new Set(); + const ret = []; + + for (const item of arr) { + if (typeof item === 'number' || typeof item === 'string' || item == null) { + if (primitives.has(item)) { + continue; + } + ret.push(item); + primitives.add(item); + } else if (item instanceof ObjectId) { + if (ids.has(item.toString())) { + continue; + } + ret.push(item); + ids.add(item.toString()); + } else { + ret.push(item); + } + } + + return ret; +}; + +/*! + * Determines if two buffers are equal. + * + * @param {Buffer} a + * @param {Object} b + */ + +exports.buffer = {}; +exports.buffer.areEqual = function(a, b) { + if (!Buffer.isBuffer(a)) { + return false; + } + if (!Buffer.isBuffer(b)) { + return false; + } + if (a.length !== b.length) { + return false; + } + for (let i = 0, len = a.length; i < len; ++i) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +}; + +exports.getFunctionName = getFunctionName; +/*! + * Decorate buffers + */ + +exports.decorate = function(destination, source) { + for (const key in source) { + if (specialProperties.has(key)) { + continue; + } + destination[key] = source[key]; + } +}; + +/** + * merges to with a copy of from + * + * @param {Object} to + * @param {Object} fromObj + * @api private + */ + +exports.mergeClone = function(to, fromObj) { + if (isMongooseObject(fromObj)) { + fromObj = fromObj.toObject({ + transform: false, + virtuals: false, + depopulate: true, + getters: false, + flattenDecimals: false + }); + } + const keys = Object.keys(fromObj); + const len = keys.length; + let i = 0; + let key; + + while (i < len) { + key = keys[i++]; + if (specialProperties.has(key)) { + continue; + } + if (typeof to[key] === 'undefined') { + to[key] = exports.clone(fromObj[key], { + transform: false, + virtuals: false, + depopulate: true, + getters: false, + flattenDecimals: false + }); + } else { + let val = fromObj[key]; + if (val != null && val.valueOf && !(val instanceof Date)) { + val = val.valueOf(); + } + if (exports.isObject(val)) { + let obj = val; + if (isMongooseObject(val) && !val.isMongooseBuffer) { + obj = obj.toObject({ + transform: false, + virtuals: false, + depopulate: true, + getters: false, + flattenDecimals: false + }); + } + if (val.isMongooseBuffer) { + obj = Buffer.from(obj); + } + exports.mergeClone(to[key], obj); + } else { + to[key] = exports.clone(val, { + flattenDecimals: false + }); + } + } + } +}; + +/** + * Executes a function on each element of an array (like _.each) + * + * @param {Array} arr + * @param {Function} fn + * @api private + */ + +exports.each = function(arr, fn) { + for (const item of arr) { + fn(item); + } +}; + +/*! + * ignore + */ + +exports.getOption = function(name) { + const sources = Array.prototype.slice.call(arguments, 1); + + for (const source of sources) { + if (source[name] != null) { + return source[name]; + } + } + + return null; +}; + +/*! + * ignore + */ + +exports.noop = function() {}; + +exports.errorToPOJO = function errorToPOJO(error) { + const isError = error instanceof Error; + if (!isError) { + throw new Error('`error` must be `instanceof Error`.'); + } + + const ret = {}; + for (const properyName of Object.getOwnPropertyNames(error)) { + ret[properyName] = error[properyName]; + } + return ret; +}; + +/*! + * ignore + */ + +exports.warn = function warn(message) { + return process.emitWarning(message, { code: 'MONGOOSE' }); +}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/validoptions.js b/node_modules/mongoose/lib/validoptions.js new file mode 100644 index 0000000..c64894d --- /dev/null +++ b/node_modules/mongoose/lib/validoptions.js @@ -0,0 +1,32 @@ + +/*! + * Valid mongoose options + */ + +'use strict'; + +const VALID_OPTIONS = Object.freeze([ + 'applyPluginsToChildSchemas', + 'applyPluginsToDiscriminators', + 'autoCreate', + 'autoIndex', + 'bufferCommands', + 'bufferTimeoutMS', + 'cloneSchemas', + 'debug', + 'maxTimeMS', + 'objectIdGetter', + 'overwriteModels', + 'returnOriginal', + 'runValidators', + 'sanitizeFilter', + 'sanitizeProjection', + 'selectPopulatedPaths', + 'setDefaultsOnInsert', + 'strict', + 'strictQuery', + 'toJSON', + 'toObject' +]); + +module.exports = VALID_OPTIONS; diff --git a/node_modules/mongoose/lib/virtualtype.js b/node_modules/mongoose/lib/virtualtype.js new file mode 100644 index 0000000..58a44b5 --- /dev/null +++ b/node_modules/mongoose/lib/virtualtype.js @@ -0,0 +1,176 @@ +'use strict'; + +const utils = require('./utils'); + +/** + * VirtualType constructor + * + * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. + * + * ####Example: + * + * const fullname = schema.virtual('fullname'); + * fullname instanceof mongoose.VirtualType // true + * + * @param {Object} options + * @param {string|function} [options.ref] if `ref` is not nullish, this becomes a [populated virtual](/docs/populate.html#populate-virtuals) + * @param {string|function} [options.localField] the local field to populate on if this is a populated virtual. + * @param {string|function} [options.foreignField] the foreign field to populate on if this is a populated virtual. + * @param {boolean} [options.justOne=false] by default, a populated virtual is an array. If you set `justOne`, the populated virtual will be a single doc or `null`. + * @param {boolean} [options.getters=false] if you set this to `true`, Mongoose will call any custom getters you defined on this virtual + * @param {boolean} [options.count=false] if you set this to `true`, `populate()` will set this virtual to the number of populated documents, as opposed to the documents themselves, using [`Query#countDocuments()`](./api.html#query_Query-countDocuments) + * @param {Object|Function} [options.match=null] add an extra match condition to `populate()` + * @param {Number} [options.limit=null] add a default `limit` to the `populate()` query + * @param {Number} [options.skip=null] add a default `skip` to the `populate()` query + * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents. + * @param {Object} [options.options=null] Additional options like `limit` and `lean`. + * @api public + */ + +function VirtualType(options, name) { + this.path = name; + this.getters = []; + this.setters = []; + this.options = Object.assign({}, options); +} + +/** + * If no getters/getters, add a default + * + * @param {Function} fn + * @return {VirtualType} this + * @api private + */ + +VirtualType.prototype._applyDefaultGetters = function() { + if (this.getters.length > 0 || this.setters.length > 0) { + return; + } + + const path = this.path; + const internalProperty = '$' + path; + this.getters.push(function() { + return this[internalProperty]; + }); + this.setters.push(function(v) { + this[internalProperty] = v; + }); +}; + +/*! + * ignore + */ + +VirtualType.prototype.clone = function() { + const clone = new VirtualType(this.options, this.path); + clone.getters = [].concat(this.getters); + clone.setters = [].concat(this.setters); + return clone; +}; + +/** + * Adds a custom getter to this virtual. + * + * Mongoose calls the getter function with the below 3 parameters. + * + * - `value`: the value returned by the previous getter. If there is only one getter, `value` will be `undefined`. + * - `virtual`: the virtual object you called `.get()` on + * - `doc`: the document this virtual is attached to. Equivalent to `this`. + * + * ####Example: + * + * const virtual = schema.virtual('fullname'); + * virtual.get(function(value, virtual, doc) { + * return this.name.first + ' ' + this.name.last; + * }); + * + * @param {Function(Any, VirtualType, Document)} fn + * @return {VirtualType} this + * @api public + */ + +VirtualType.prototype.get = function(fn) { + this.getters.push(fn); + return this; +}; + +/** + * Adds a custom setter to this virtual. + * + * Mongoose calls the setter function with the below 3 parameters. + * + * - `value`: the value being set + * - `virtual`: the virtual object you're calling `.set()` on + * - `doc`: the document this virtual is attached to. Equivalent to `this`. + * + * ####Example: + * + * const virtual = schema.virtual('fullname'); + * virtual.set(function(value, virtual, doc) { + * const parts = value.split(' '); + * this.name.first = parts[0]; + * this.name.last = parts[1]; + * }); + * + * const Model = mongoose.model('Test', schema); + * const doc = new Model(); + * // Calls the setter with `value = 'Jean-Luc Picard'` + * doc.fullname = 'Jean-Luc Picard'; + * doc.name.first; // 'Jean-Luc' + * doc.name.last; // 'Picard' + * + * @param {Function(Any, VirtualType, Document)} fn + * @return {VirtualType} this + * @api public + */ + +VirtualType.prototype.set = function(fn) { + this.setters.push(fn); + return this; +}; + +/** + * Applies getters to `value`. + * + * @param {Object} value + * @param {Document} doc The document this virtual is attached to + * @return {any} the value after applying all getters + * @api public + */ + +VirtualType.prototype.applyGetters = function(value, doc) { + if (utils.hasUserDefinedProperty(this.options, ['ref', 'refPath']) && + doc.$$populatedVirtuals && + doc.$$populatedVirtuals.hasOwnProperty(this.path)) { + value = doc.$$populatedVirtuals[this.path]; + } + + let v = value; + for (const getter of this.getters) { + v = getter.call(doc, v, this, doc); + } + return v; +}; + +/** + * Applies setters to `value`. + * + * @param {Object} value + * @param {Document} doc + * @return {any} the value after applying all setters + * @api public + */ + +VirtualType.prototype.applySetters = function(value, doc) { + let v = value; + for (const setter of this.setters) { + v = setter.call(doc, v, this, doc); + } + return v; +}; + +/*! + * exports + */ + +module.exports = VirtualType; diff --git a/node_modules/mongoose/node_modules/ms/index.js b/node_modules/mongoose/node_modules/ms/index.js new file mode 100644 index 0000000..c4498bc --- /dev/null +++ b/node_modules/mongoose/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/mongoose/node_modules/ms/license.md b/node_modules/mongoose/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/mongoose/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/mongoose/node_modules/ms/package.json b/node_modules/mongoose/node_modules/ms/package.json new file mode 100644 index 0000000..eea666e --- /dev/null +++ b/node_modules/mongoose/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.1.2", + "description": "Tiny millisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.12.1", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1" + } +} diff --git a/node_modules/mongoose/node_modules/ms/readme.md b/node_modules/mongoose/node_modules/ms/readme.md new file mode 100644 index 0000000..9a1996b --- /dev/null +++ b/node_modules/mongoose/node_modules/ms/readme.md @@ -0,0 +1,60 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/mongoose/package.json b/node_modules/mongoose/package.json new file mode 100644 index 0000000..6105fbd --- /dev/null +++ b/node_modules/mongoose/package.json @@ -0,0 +1,250 @@ +{ + "name": "mongoose", + "description": "Mongoose MongoDB ODM", + "version": "6.0.11", + "author": "Guillermo Rauch ", + "keywords": [ + "mongodb", + "document", + "model", + "schema", + "database", + "odm", + "data", + "datastore", + "query", + "nosql", + "orm", + "db" + ], + "license": "MIT", + "dependencies": { + "bson": "^4.2.2", + "kareem": "2.3.2", + "mongodb": "4.1.2", + "mpath": "0.8.4", + "mquery": "4.0.0", + "ms": "2.1.2", + "regexp-clone": "1.0.0", + "sift": "13.5.2", + "sliced": "1.0.1" + }, + "devDependencies": { + "@babel/core": "7.10.5", + "@babel/preset-env": "7.10.4", + "@typescript-eslint/eslint-plugin": "4.33.0", + "@typescript-eslint/parser": "4.33.0", + "acquit": "1.x", + "acquit-ignore": "0.1.x", + "acquit-require": "0.1.x", + "babel-loader": "8.1.0", + "benchmark": "2.1.4", + "bluebird": "3.5.5", + "chalk": "2.4.2", + "cheerio": "1.0.0-rc.2", + "dox": "0.3.1", + "eslint": "7.1.0", + "eslint-plugin-mocha-no-only": "1.1.0", + "highlight.js": "9.18.2", + "lodash.isequal": "4.5.0", + "lodash.isequalwith": "4.4.0", + "marked": "1.1.1", + "mkdirp": "0.5.5", + "mocha": "5.x", + "moment": "2.x", + "mongoose-long": "0.2.1", + "node-static": "0.7.11", + "object-sizeof": "1.3.0", + "pug": "2.0.3", + "q": "1.5.1", + "rimraf": "2.6.3", + "semver": "5.5.0", + "typescript": "4.1.x", + "uuid": "2.0.3", + "uuid-parse": "1.0.0", + "validator": "10.8.0", + "webpack": "4.44.0" + }, + "directories": { + "lib": "./lib/mongoose" + }, + "scripts": { + "lint": "eslint .", + "build-browser": "node build-browser.js", + "prepublishOnly": "npm run build-browser", + "release": "git pull && git push origin master --tags && npm publish", + "release-legacy": "git pull origin 5.x && git push origin 5.x --tags && npm publish --tag legacy", + "test": "mocha --exit ./test/*.test.js ./test/typescript/main.test.js", + "tdd": "mocha ./test/*.test.js ./test/typescript/main.test.js --inspect --watch --recursive --watch-files ./**/*.js", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "main": "./index.js", + "types": "./index.d.ts", + "engines": { + "node": ">=12.0.0" + }, + "bugs": { + "url": "https://github.com/Automattic/mongoose/issues/new" + }, + "repository": { + "type": "git", + "url": "git://github.com/Automattic/mongoose.git" + }, + "homepage": "https://mongoosejs.com", + "browser": "./dist/browser.umd.js", + "mocha": { + "extension": [ + "test.js" + ], + "watch-files": [ + "test/**/*.js" + ] + }, + "eslintConfig": { + "extends": [ + "eslint:recommended" + ], + "overrides": [ + { + "files": [ + "**/*.{ts,tsx}" + ], + "extends": [ + "plugin:@typescript-eslint/eslint-recommended", + "plugin:@typescript-eslint/recommended" + ], + "plugins": [ + "@typescript-eslint" + ], + "rules": { + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/ban-types": "off", + "@typescript-eslint/no-unused-vars": "off", + "@typescript-eslint/explicit-module-boundary-types": "off" + } + } + ], + "plugins": [ + "mocha-no-only" + ], + "parserOptions": { + "ecmaVersion": 2020 + }, + "env": { + "node": true, + "es6": true + }, + "rules": { + "comma-style": "error", + "indent": [ + "error", + 2, + { + "SwitchCase": 1, + "VariableDeclarator": 2 + } + ], + "keyword-spacing": "error", + "no-whitespace-before-property": "error", + "no-buffer-constructor": "warn", + "no-console": "off", + "no-multi-spaces": "error", + "no-constant-condition": "off", + "func-call-spacing": "error", + "no-trailing-spaces": "error", + "no-undef": "error", + "no-unneeded-ternary": "error", + "no-const-assign": "error", + "no-useless-rename": "error", + "no-dupe-keys": "error", + "space-in-parens": [ + "error", + "never" + ], + "spaced-comment": [ + "error", + "always", + { + "block": { + "markers": [ + "!" + ], + "balanced": true + } + } + ], + "key-spacing": [ + "error", + { + "beforeColon": false, + "afterColon": true + } + ], + "comma-spacing": [ + "error", + { + "before": false, + "after": true + } + ], + "array-bracket-spacing": 1, + "arrow-spacing": [ + "error", + { + "before": true, + "after": true + } + ], + "object-curly-spacing": [ + "error", + "always" + ], + "comma-dangle": [ + "error", + "never" + ], + "no-unreachable": "error", + "quotes": [ + "error", + "single" + ], + "quote-props": [ + "error", + "as-needed" + ], + "semi": "error", + "no-extra-semi": "error", + "semi-spacing": "error", + "no-spaced-func": "error", + "no-throw-literal": "error", + "space-before-blocks": "error", + "space-before-function-paren": [ + "error", + "never" + ], + "space-infix-ops": "error", + "space-unary-ops": "error", + "no-var": "warn", + "prefer-const": "warn", + "strict": [ + "error", + "global" + ], + "no-restricted-globals": [ + "error", + { + "name": "context", + "message": "Don't use Mocha's global context" + } + ], + "no-prototype-builtins": "off", + "mocha-no-only/mocha-no-only": [ + "error" + ] + } + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } +} diff --git a/node_modules/mongoose/tools/auth.js b/node_modules/mongoose/tools/auth.js new file mode 100644 index 0000000..2fddafa --- /dev/null +++ b/node_modules/mongoose/tools/auth.js @@ -0,0 +1,31 @@ +'use strict'; + +const Server = require('mongodb-topology-manager').Server; +const mongodb = require('mongodb'); + +run().catch(error => { + console.error(error); + process.exit(-1); +}); + +async function run() { + // Create new instance + const server = new Server('mongod', { + auth: null, + dbpath: '/data/db/27017' + }); + + // Purge the directory + await server.purge(); + + // Start process + await server.start(); + + const db = await mongodb.MongoClient.connect('mongodb://localhost:27017/admin'); + + await db.addUser('passwordIsTaco', 'taco', { + roles: ['dbOwner'] + }); + + console.log('done'); +} \ No newline at end of file diff --git a/node_modules/mongoose/tools/repl.js b/node_modules/mongoose/tools/repl.js new file mode 100644 index 0000000..a2ff645 --- /dev/null +++ b/node_modules/mongoose/tools/repl.js @@ -0,0 +1,36 @@ +'use strict'; + +run().catch(error => { + console.error(error); + process.exit(-1); +}); + +async function run () { + const ReplSet = require('mongodb-topology-manager').ReplSet; + + // Create new instance + const topology = new ReplSet('mongod', [{ + // mongod process options + options: { + bind_ip: 'localhost', port: 31000, dbpath: `/data/db/31000` + } + }, { + // mongod process options + options: { + bind_ip: 'localhost', port: 31001, dbpath: `/data/db/31001` + } + }, { + // Type of node + arbiterOnly: true, + // mongod process options + options: { + bind_ip: 'localhost', port: 31002, dbpath: `/data/db/31002` + } + }], { + replSet: 'rs' + }); + + await topology.start(); + + console.log('done'); +} diff --git a/node_modules/mongoose/tools/sharded.js b/node_modules/mongoose/tools/sharded.js new file mode 100644 index 0000000..cfab884 --- /dev/null +++ b/node_modules/mongoose/tools/sharded.js @@ -0,0 +1,46 @@ +'use strict'; + +run().catch(error => { + console.error(error); + process.exit(-1); +}); + + +async function run () { + const Sharded = require('mongodb-topology-manager').Sharded; + + // Create new instance + const topology = new Sharded({ + mongod: 'mongod', + mongos: 'mongos' + }); + + await topology.addShard([{ + options: { + bind_ip: 'localhost', port: 31000, dbpath: `/data/db/31000`, shardsvr: null + } + }], { replSet: 'rs1' }); + + await topology.addConfigurationServers([{ + options: { + bind_ip: 'localhost', port: 35000, dbpath: `/data/db/35000` + } + }], { replSet: 'rs0' }); + + await topology.addProxies([{ + bind_ip: 'localhost', port: 51000, configdb: 'localhost:35000' + }], { + binary: 'mongos' + }); + + console.log('Start...'); + // Start up topology + await topology.start(); + + console.log('Started'); + + // Shard db + await topology.enableSharding('test'); + + console.log('done'); +} \ No newline at end of file diff --git a/node_modules/mpath/.travis.yml b/node_modules/mpath/.travis.yml new file mode 100644 index 0000000..9bdf212 --- /dev/null +++ b/node_modules/mpath/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - "4" + - "5" + - "6" + - "7" + - "8" + - "9" + - "10" diff --git a/node_modules/mpath/History.md b/node_modules/mpath/History.md new file mode 100644 index 0000000..58fea96 --- /dev/null +++ b/node_modules/mpath/History.md @@ -0,0 +1,84 @@ +0.8.4 / 2021-09-01 +================== + * fix: throw error if `parts` contains an element that isn't a string or number #13 + +0.8.3 / 2020-12-30 +================== + * fix: use var instead of let/const for Node.js 4.x support + +0.8.2 / 2020-12-30 +================== + * fix(stringToParts): fall back to legacy treatment for square brackets if square brackets contents aren't a number Automattic/mongoose#9640 + * chore: add eslint + +0.8.1 / 2020-12-10 +================== + * fix(stringToParts): handle empty string and trailing dot the same way that `split()` does for backwards compat + +0.8.0 / 2020-11-14 +================== + * feat: support square bracket indexing for `get()`, `set()`, `has()`, and `unset()` + +0.7.0 / 2020-03-24 +================== + * BREAKING CHANGE: remove `component.json` #9 [AlexeyGrigorievBoost](https://github.com/AlexeyGrigorievBoost) + +0.6.0 / 2019-05-01 +================== + * feat: support setting dotted paths within nested arrays + +0.5.2 / 2019-04-25 +================== + * fix: avoid using subclassed array constructor when doing `map()` + +0.5.1 / 2018-08-30 +================== + * fix: prevent writing to constructor and prototype as well as __proto__ + +0.5.0 / 2018-08-30 +================== + * BREAKING CHANGE: disallow setting/unsetting __proto__ properties + * feat: re-add support for Node < 4 for this release + +0.4.1 / 2018-04-08 +================== + * fix: allow opting out of weird `$` set behavior re: Automattic/mongoose#6273 + +0.4.0 / 2018-03-27 +================== + * feat: add support for ES6 maps + * BREAKING CHANGE: drop support for Node < 4 + +0.3.0 / 2017-06-05 +================== + * feat: add has() and unset() functions + +0.2.1 / 2013-03-22 +================== + + * test; added for #5 + * fix typo that breaks set #5 [Contra](https://github.com/Contra) + +0.2.0 / 2013-03-15 +================== + + * added; adapter support for set + * added; adapter support for get + * add basic benchmarks + * add support for using module as a component #2 [Contra](https://github.com/Contra) + +0.1.1 / 2012-12-21 +================== + + * added; map support + +0.1.0 / 2012-12-13 +================== + + * added; set('array.property', val, object) support + * added; get('array.property', object) support + +0.0.1 / 2012-11-03 +================== + + * initial release diff --git a/node_modules/mpath/LICENSE b/node_modules/mpath/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/node_modules/mpath/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mpath/Makefile b/node_modules/mpath/Makefile new file mode 100644 index 0000000..8d6a79c --- /dev/null +++ b/node_modules/mpath/Makefile @@ -0,0 +1,4 @@ +bench: + node bench.js + +.PHONY: test diff --git a/node_modules/mpath/README.md b/node_modules/mpath/README.md new file mode 100644 index 0000000..9831dd0 --- /dev/null +++ b/node_modules/mpath/README.md @@ -0,0 +1,278 @@ +#mpath + +{G,S}et javascript object values using MongoDB-like path notation. + +###Getting + +```js +var mpath = require('mpath'); + +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.1.title', obj) // 'exciting!' +``` + +`mpath.get` supports array property notation as well. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.title', obj) // ['funny', 'exciting!'] +``` + +Array property and indexing syntax, when used together, are very powerful. + +```js +var obj = { + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} + +var found = mpath.get('array.o.array.x.b.1', obj); + +console.log(found); // prints.. + + [ [6, undefined] + , [2, undefined, undefined] + , [null, 1] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + +``` + +#####Field selection rules: + +The following rules are iteratively applied to each `segment` in the passed `path`. For example: + +```js +var path = 'one.two.14'; // path +'one' // segment 0 +'two' // segment 1 +14 // segment 2 +``` + +- 1) when value of the segment parent is not an array, return the value of `parent.segment` +- 2) when value of the segment parent is an array + - a) if the segment is an integer, replace the parent array with the value at `parent[segment]` + - b) if not an integer, keep the array but replace each array `item` with the value returned from calling `get(remainingSegments, item)` or undefined if falsey. + +#####Maps + +`mpath.get` also accepts an optional `map` argument which receives each individual found value. The value returned from the `map` function will be used in the original found values place. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.title', obj, function (val) { + return 'funny' == val + ? 'amusing' + : val; +}); +// ['amusing', 'exciting!'] +``` + +###Setting + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.1.title', 'hilarious', obj) +console.log(obj.comments[1].title) // 'hilarious' +``` + +`mpath.set` supports the same array property notation as `mpath.get`. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: 'hilarious' }, + { title: 'fruity' } + ]} +``` + +Array property and indexing syntax can be used together also when setting. + +```js +var obj = { + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ] +} + +mpath.set('array.1.o', 'this was changed', obj); + +console.log(require('util').inspect(obj, false, 1000)); // prints.. + +{ + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: 'this was changed' } + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} + +mpath.set('array.o.array.x', 'this was changed too', obj); + +console.log(require('util').inspect(obj, false, 1000)); // prints.. + +{ + array: [ + { o: { array: [{x: 'this was changed too'}, { y: 10, x: 'this was changed too'} ] }} + , { o: 'this was changed' } + , { o: { array: [{x: 'this was changed too'}, { x: 'this was changed too'}] }} + , { o: { array: [{x: 'this was changed too'}] }} + , { o: { array: [{x: 'this was changed too', y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} +``` + +####Setting arrays + +By default, setting a property within an array to another array results in each element of the new array being set to the item in the destination array at the matching index. An example is helpful. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: 'hilarious' }, + { title: 'fruity' } + ]} +``` + +If we do not desire this destructuring-like assignment behavior we may instead specify the `$` operator in the path being set to force the array to be copied directly. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.$.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: ['hilarious', 'fruity'] }, + { title: ['hilarious', 'fruity'] } + ]} +``` + +####Field assignment rules + +The rules utilized mirror those used on `mpath.get`, meaning we can take values returned from `mpath.get`, update them, and reassign them using `mpath.set`. Note that setting nested arrays of arrays can get unweildy quickly. Check out the [tests](https://github.com/aheckmann/mpath/blob/master/test/index.js) for more extreme examples. + +#####Maps + +`mpath.set` also accepts an optional `map` argument which receives each individual value being set. The value returned from the `map` function will be used in the original values place. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj, function (val) { + return val.length; +}); + +console.log(obj); // prints.. + + { comments: [ + { title: 9 }, + { title: 6 } + ]} +``` + +### Custom object types + +Sometimes you may want to enact the same functionality on custom object types that store all their real data internally, say for an ODM type object. No fear, `mpath` has you covered. Simply pass the name of the property being used to store the internal data and it will be traversed instead: + +```js +var mpath = require('mpath'); + +var obj = { + comments: [ + { title: 'exciting!', _doc: { title: 'great!' }} + ] +} + +mpath.get('comments.0.title', obj, '_doc') // 'great!' +mpath.set('comments.0.title', 'nov 3rd', obj, '_doc') +mpath.get('comments.0.title', obj, '_doc') // 'nov 3rd' +mpath.get('comments.0.title', obj) // 'exciting' +``` + +When used with a `map`, the `map` argument comes last. + +```js +mpath.get(path, obj, '_doc', map); +mpath.set(path, val, obj, '_doc', map); +``` + +[LICENSE](https://github.com/aheckmann/mpath/blob/master/LICENSE) + diff --git a/node_modules/mpath/SECURITY.md b/node_modules/mpath/SECURITY.md new file mode 100644 index 0000000..1c916a3 --- /dev/null +++ b/node_modules/mpath/SECURITY.md @@ -0,0 +1,5 @@ +# Reporting a Vulnerability + +Please report suspected security vulnerabilities to val [at] karpov [dot] io. +You will receive a response from us within 72 hours. +If the issue is confirmed, we will release a patch as soon as possible depending on complexity. diff --git a/node_modules/mpath/bench.js b/node_modules/mpath/bench.js new file mode 100644 index 0000000..9503cf2 --- /dev/null +++ b/node_modules/mpath/bench.js @@ -0,0 +1,110 @@ +'use strict'; + +const mpath = require('./'); +const Bench = require('benchmark'); +require('child_process').exec('git log --pretty=format:\'%h\' -n 1', function(err, sha) { + if (err) throw err; + + const fs = require('fs'); + const filename = __dirname + '/bench.out'; + const out = fs.createWriteStream(filename, { flags: 'a', encoding: 'utf8' }); + + /** + * test doc creator + */ + + function doc() { + const o = { first: { second: { third: [3, { name: 'aaron' }, 9] } } }; + o.comments = [ + { name: 'one' }, + { name: 'two', _doc: { name: '2' } }, + { name: 'three', + comments: [{}, { comments: [{ val: 'twoo' }] }], + _doc: { name: '3', comments: [{}, { _doc: { comments: [{ val: 2 }] } }] } } + ]; + o.name = 'jiro'; + o.array = [ + { o: { array: [{ x: { b: [4, 6, 8] } }, { y: 10 }] } }, + { o: { array: [{ x: { b: [1, 2, 3] } }, { x: { z: 10 } }, { x: { b: 'hi' } }] } }, + { o: { array: [{ x: { b: null } }, { x: { b: [null, 1] } }] } }, + { o: { array: [{ x: null }] } }, + { o: { array: [{ y: 3 }] } }, + { o: { array: [3, 0, null] } }, + { o: { name: 'ha' } } + ]; + o.arr = [ + { arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: true } + ]; + return o; + } + + const o = doc(); + + const s = new Bench.Suite; + s.add('mpath.get("first", obj)', function() { + mpath.get('first', o); + }); + s.add('mpath.get("first.second", obj)', function() { + mpath.get('first.second', o); + }); + s.add('mpath.get("first.second.third.1.name", obj)', function() { + mpath.get('first.second.third.1.name', o); + }); + s.add('mpath.get("comments", obj)', function() { + mpath.get('comments', o); + }); + s.add('mpath.get("comments.1", obj)', function() { + mpath.get('comments.1', o); + }); + s.add('mpath.get("comments.2.name", obj)', function() { + mpath.get('comments.2.name', o); + }); + s.add('mpath.get("comments.2.comments.1.comments.0.val", obj)', function() { + mpath.get('comments.2.comments.1.comments.0.val', o); + }); + s.add('mpath.get("comments.name", obj)', function() { + mpath.get('comments.name', o); + }); + + s.add('mpath.set("first", obj, val)', function() { + mpath.set('first', o, 1); + }); + s.add('mpath.set("first.second", obj, val)', function() { + mpath.set('first.second', o, 1); + }); + s.add('mpath.set("first.second.third.1.name", obj, val)', function() { + mpath.set('first.second.third.1.name', o, 1); + }); + s.add('mpath.set("comments", obj, val)', function() { + mpath.set('comments', o, 1); + }); + s.add('mpath.set("comments.1", obj, val)', function() { + mpath.set('comments.1', o, 1); + }); + s.add('mpath.set("comments.2.name", obj, val)', function() { + mpath.set('comments.2.name', o, 1); + }); + s.add('mpath.set("comments.2.comments.1.comments.0.val", obj, val)', function() { + mpath.set('comments.2.comments.1.comments.0.val', o, 1); + }); + s.add('mpath.set("comments.name", obj, val)', function() { + mpath.set('comments.name', o, 1); + }); + + s.on('start', function() { + console.log('starting...'); + out.write('*' + sha + ': ' + String(new Date()) + '\n'); + }); + s.on('cycle', function(e) { + const s = String(e.target); + console.log(s); + out.write(s + '\n'); + }); + s.on('complete', function() { + console.log('done'); + out.end(''); + }); + s.run(); +}); + diff --git a/node_modules/mpath/bench.log b/node_modules/mpath/bench.log new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mpath/bench.out b/node_modules/mpath/bench.out new file mode 100644 index 0000000..b9b0371 --- /dev/null +++ b/node_modules/mpath/bench.out @@ -0,0 +1,52 @@ +*b566c26: Fri Mar 15 2013 14:14:04 GMT-0700 (PDT) +mpath.get("first", obj) x 3,827,405 ops/sec ±0.91% (90 runs sampled) +mpath.get("first.second", obj) x 4,930,222 ops/sec ±1.92% (91 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,070,837 ops/sec ±1.45% (97 runs sampled) +mpath.get("comments", obj) x 3,649,771 ops/sec ±1.71% (93 runs sampled) +mpath.get("comments.1", obj) x 3,846,728 ops/sec ±0.86% (94 runs sampled) +mpath.get("comments.2.name", obj) x 3,527,680 ops/sec ±0.95% (96 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,046,982 ops/sec ±0.80% (96 runs sampled) +mpath.get("comments.name", obj) x 625,546 ops/sec ±2.02% (82 runs sampled) +*e42bdb1: Fri Mar 15 2013 14:19:28 GMT-0700 (PDT) +mpath.get("first", obj) x 3,700,783 ops/sec ±1.30% (95 runs sampled) +mpath.get("first.second", obj) x 4,621,795 ops/sec ±0.86% (95 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,012,671 ops/sec ±1.21% (100 runs sampled) +mpath.get("comments", obj) x 3,677,694 ops/sec ±0.80% (96 runs sampled) +mpath.get("comments.1", obj) x 3,798,862 ops/sec ±0.81% (91 runs sampled) +mpath.get("comments.2.name", obj) x 3,489,356 ops/sec ±0.66% (98 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,004,076 ops/sec ±0.85% (99 runs sampled) +mpath.get("comments.name", obj) x 613,270 ops/sec ±1.33% (83 runs sampled) +*0521aac: Fri Mar 15 2013 16:37:16 GMT-0700 (PDT) +mpath.get("first", obj) x 3,834,755 ops/sec ±0.70% (100 runs sampled) +mpath.get("first.second", obj) x 4,999,965 ops/sec ±1.01% (98 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,125,953 ops/sec ±0.97% (100 runs sampled) +mpath.get("comments", obj) x 3,759,233 ops/sec ±0.81% (97 runs sampled) +mpath.get("comments.1", obj) x 3,894,893 ops/sec ±0.76% (96 runs sampled) +mpath.get("comments.2.name", obj) x 3,576,929 ops/sec ±0.68% (98 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,149,610 ops/sec ±0.67% (97 runs sampled) +mpath.get("comments.name", obj) x 629,259 ops/sec ±1.30% (87 runs sampled) +mpath.set("first", obj, val) x 2,869,477 ops/sec ±0.63% (97 runs sampled) +mpath.set("first.second", obj, val) x 2,418,751 ops/sec ±0.62% (98 runs sampled) +mpath.set("first.second.third.1.name", obj, val) x 2,313,099 ops/sec ±0.69% (94 runs sampled) +mpath.set("comments", obj, val) x 2,680,882 ops/sec ±0.76% (99 runs sampled) +mpath.set("comments.1", obj, val) x 2,401,829 ops/sec ±0.68% (98 runs sampled) +mpath.set("comments.2.name", obj, val) x 2,335,081 ops/sec ±1.07% (96 runs sampled) +mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,245,436 ops/sec ±0.76% (92 runs sampled) +mpath.set("comments.name", obj, val) x 2,356,278 ops/sec ±1.15% (100 runs sampled) +*97e85d3: Fri Mar 15 2013 16:39:21 GMT-0700 (PDT) +mpath.get("first", obj) x 3,837,614 ops/sec ±0.74% (99 runs sampled) +mpath.get("first.second", obj) x 4,991,779 ops/sec ±1.01% (94 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,078,455 ops/sec ±1.17% (96 runs sampled) +mpath.get("comments", obj) x 3,770,961 ops/sec ±0.45% (101 runs sampled) +mpath.get("comments.1", obj) x 3,832,814 ops/sec ±0.67% (92 runs sampled) +mpath.get("comments.2.name", obj) x 3,536,436 ops/sec ±0.49% (100 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,141,947 ops/sec ±0.72% (98 runs sampled) +mpath.get("comments.name", obj) x 667,898 ops/sec ±1.62% (85 runs sampled) +mpath.set("first", obj, val) x 2,642,517 ops/sec ±0.72% (98 runs sampled) +mpath.set("first.second", obj, val) x 2,502,124 ops/sec ±1.28% (99 runs sampled) +mpath.set("first.second.third.1.name", obj, val) x 2,426,804 ops/sec ±0.55% (99 runs sampled) +mpath.set("comments", obj, val) x 2,699,478 ops/sec ±0.85% (98 runs sampled) +mpath.set("comments.1", obj, val) x 2,494,454 ops/sec ±1.05% (96 runs sampled) +mpath.set("comments.2.name", obj, val) x 2,463,894 ops/sec ±0.86% (98 runs sampled) +mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,320,398 ops/sec ±0.82% (95 runs sampled) +mpath.set("comments.name", obj, val) x 2,512,408 ops/sec ±0.77% (95 runs sampled) diff --git a/node_modules/mpath/index.js b/node_modules/mpath/index.js new file mode 100644 index 0000000..47c17cd --- /dev/null +++ b/node_modules/mpath/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = exports = require('./lib'); diff --git a/node_modules/mpath/lib/index.js b/node_modules/mpath/lib/index.js new file mode 100644 index 0000000..c9e7e5f --- /dev/null +++ b/node_modules/mpath/lib/index.js @@ -0,0 +1,326 @@ +/* eslint strict:off */ +/* eslint no-var: off */ +/* eslint no-redeclare: off */ + +var stringToParts = require('./stringToParts'); + +// These properties are special and can open client libraries to security +// issues +var ignoreProperties = ['__proto__', 'constructor', 'prototype']; + +/** + * Returns the value of object `o` at the given `path`. + * + * ####Example: + * + * var obj = { + * comments: [ + * { title: 'exciting!', _doc: { title: 'great!' }} + * , { title: 'number dos' } + * ] + * } + * + * mpath.get('comments.0.title', o) // 'exciting!' + * mpath.get('comments.0.title', o, '_doc') // 'great!' + * mpath.get('comments.title', o) // ['exciting!', 'number dos'] + * + * // summary + * mpath.get(path, o) + * mpath.get(path, o, special) + * mpath.get(path, o, map) + * mpath.get(path, o, special, map) + * + * @param {String} path + * @param {Object} o + * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. + * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place. + */ + +exports.get = function(path, o, special, map) { + var lookup; + + if ('function' == typeof special) { + if (special.length < 2) { + map = special; + special = undefined; + } else { + lookup = special; + special = undefined; + } + } + + map || (map = K); + + var parts = 'string' == typeof path + ? stringToParts(path) + : path; + + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } + + var obj = o, + part; + + for (var i = 0; i < parts.length; ++i) { + part = parts[i]; + if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') { + throw new TypeError('Each segment of path to `get()` must be a string or number, got ' + typeof parts[i]); + } + + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + // reading a property from the array items + var paths = parts.slice(i); + + // Need to `concat()` to avoid `map()` calling a constructor of an array + // subclass + return [].concat(obj).map(function(item) { + return item + ? exports.get(paths, item, special || lookup, map) + : map(undefined); + }); + } + + if (lookup) { + obj = lookup(obj, part); + } else { + var _from = special && obj[special] ? obj[special] : obj; + obj = _from instanceof Map ? + _from.get(part) : + _from[part]; + } + + if (!obj) return map(obj); + } + + return map(obj); +}; + +/** + * Returns true if `in` returns true for every piece of the path + * + * @param {String} path + * @param {Object} o + */ + +exports.has = function(path, o) { + var parts = typeof path === 'string' ? + stringToParts(path) : + path; + + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } + + var len = parts.length; + var cur = o; + for (var i = 0; i < len; ++i) { + if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') { + throw new TypeError('Each segment of path to `has()` must be a string or number, got ' + typeof parts[i]); + } + if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { + return false; + } + cur = cur[parts[i]]; + } + + return true; +}; + +/** + * Deletes the last piece of `path` + * + * @param {String} path + * @param {Object} o + */ + +exports.unset = function(path, o) { + var parts = typeof path === 'string' ? + stringToParts(path) : + path; + + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } + + var len = parts.length; + var cur = o; + for (var i = 0; i < len; ++i) { + if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { + return false; + } + if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') { + throw new TypeError('Each segment of path to `unset()` must be a string or number, got ' + typeof parts[i]); + } + // Disallow any updates to __proto__ or special properties. + if (ignoreProperties.indexOf(parts[i]) !== -1) { + return false; + } + if (i === len - 1) { + delete cur[parts[i]]; + return true; + } + cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]]; + } + + return true; +}; + +/** + * Sets the `val` at the given `path` of object `o`. + * + * @param {String} path + * @param {Anything} val + * @param {Object} o + * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. + * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place. + */ + +exports.set = function(path, val, o, special, map, _copying) { + var lookup; + + if ('function' == typeof special) { + if (special.length < 2) { + map = special; + special = undefined; + } else { + lookup = special; + special = undefined; + } + } + + map || (map = K); + + var parts = 'string' == typeof path + ? stringToParts(path) + : path; + + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } + + if (null == o) return; + + for (var i = 0; i < parts.length; ++i) { + if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') { + throw new TypeError('Each segment of path to `set()` must be a string or number, got ' + typeof parts[i]); + } + // Silently ignore any updates to `__proto__`, these are potentially + // dangerous if using mpath with unsanitized data. + if (ignoreProperties.indexOf(parts[i]) !== -1) { + return; + } + } + + // the existance of $ in a path tells us if the user desires + // the copying of an array instead of setting each value of + // the array to the one by one to matching positions of the + // current array. Unless the user explicitly opted out by passing + // false, see Automattic/mongoose#6273 + var copy = _copying || (/\$/.test(path) && _copying !== false), + obj = o, + part; + + for (var i = 0, len = parts.length - 1; i < len; ++i) { + part = parts[i]; + + if ('$' == part) { + if (i == len - 1) { + break; + } else { + continue; + } + } + + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + var paths = parts.slice(i); + if (!copy && Array.isArray(val)) { + for (var j = 0; j < obj.length && j < val.length; ++j) { + // assignment of single values of array + exports.set(paths, val[j], obj[j], special || lookup, map, copy); + } + } else { + for (var j = 0; j < obj.length; ++j) { + // assignment of entire value + exports.set(paths, val, obj[j], special || lookup, map, copy); + } + } + return; + } + + if (lookup) { + obj = lookup(obj, part); + } else { + var _to = special && obj[special] ? obj[special] : obj; + obj = _to instanceof Map ? + _to.get(part) : + _to[part]; + } + + if (!obj) return; + } + + // process the last property of the path + + part = parts[len]; + + // use the special property if exists + if (special && obj[special]) { + obj = obj[special]; + } + + // set the value on the last branch + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + if (!copy && Array.isArray(val)) { + _setArray(obj, val, part, lookup, special, map); + } else { + for (var j = 0; j < obj.length; ++j) { + var item = obj[j]; + if (item) { + if (lookup) { + lookup(item, part, map(val)); + } else { + if (item[special]) item = item[special]; + item[part] = map(val); + } + } + } + } + } else { + if (lookup) { + lookup(obj, part, map(val)); + } else if (obj instanceof Map) { + obj.set(part, map(val)); + } else { + obj[part] = map(val); + } + } +}; + +/*! + * Recursively set nested arrays + */ + +function _setArray(obj, val, part, lookup, special, map) { + for (var item, j = 0; j < obj.length && j < val.length; ++j) { + item = obj[j]; + if (Array.isArray(item) && Array.isArray(val[j])) { + _setArray(item, val[j], part, lookup, special, map); + } else if (item) { + if (lookup) { + lookup(item, part, map(val[j])); + } else { + if (item[special]) item = item[special]; + item[part] = map(val[j]); + } + } + } +} + +/*! + * Returns the value passed to it. + */ + +function K(v) { + return v; +} \ No newline at end of file diff --git a/node_modules/mpath/lib/stringToParts.js b/node_modules/mpath/lib/stringToParts.js new file mode 100644 index 0000000..f70f333 --- /dev/null +++ b/node_modules/mpath/lib/stringToParts.js @@ -0,0 +1,48 @@ +'use strict'; + +module.exports = function stringToParts(str) { + const result = []; + + let curPropertyName = ''; + let state = 'DEFAULT'; + for (let i = 0; i < str.length; ++i) { + // Fall back to treating as property name rather than bracket notation if + // square brackets contains something other than a number. + if (state === 'IN_SQUARE_BRACKETS' && !/\d/.test(str[i]) && str[i] !== ']') { + state = 'DEFAULT'; + curPropertyName = result[result.length - 1] + '[' + curPropertyName; + result.splice(result.length - 1, 1); + } + + if (str[i] === '[') { + if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') { + result.push(curPropertyName); + curPropertyName = ''; + } + state = 'IN_SQUARE_BRACKETS'; + } else if (str[i] === ']') { + if (state === 'IN_SQUARE_BRACKETS') { + state = 'IMMEDIATELY_AFTER_SQUARE_BRACKETS'; + result.push(curPropertyName); + curPropertyName = ''; + } else { + state = 'DEFAULT'; + curPropertyName += str[i]; + } + } else if (str[i] === '.') { + if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') { + result.push(curPropertyName); + curPropertyName = ''; + } + state = 'DEFAULT'; + } else { + curPropertyName += str[i]; + } + } + + if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') { + result.push(curPropertyName); + } + + return result; +}; \ No newline at end of file diff --git a/node_modules/mpath/package.json b/node_modules/mpath/package.json new file mode 100644 index 0000000..039a94a --- /dev/null +++ b/node_modules/mpath/package.json @@ -0,0 +1,144 @@ +{ + "name": "mpath", + "version": "0.8.4", + "description": "{G,S}et object values using MongoDB-like path notation", + "main": "index.js", + "scripts": { + "lint": "eslint .", + "test": "mocha test/*" + }, + "engines": { + "node": ">=4.0.0" + }, + "repository": "git://github.com/aheckmann/mpath.git", + "keywords": [ + "mongodb", + "path", + "get", + "set" + ], + "author": "Aaron Heckmann ", + "license": "MIT", + "devDependencies": { + "mocha": "5.x", + "benchmark": "~1.0.0", + "eslint": "7.16.0" + }, + "eslintConfig": { + "extends": [ + "eslint:recommended" + ], + "parserOptions": { + "ecmaVersion": 2015 + }, + "env": { + "node": true, + "es6": true + }, + "rules": { + "comma-style": "error", + "indent": [ + "error", + 2, + { + "SwitchCase": 1, + "VariableDeclarator": 2 + } + ], + "keyword-spacing": "error", + "no-whitespace-before-property": "error", + "no-buffer-constructor": "warn", + "no-console": "off", + "no-multi-spaces": "error", + "no-constant-condition": "off", + "func-call-spacing": "error", + "no-trailing-spaces": "error", + "no-undef": "error", + "no-unneeded-ternary": "error", + "no-const-assign": "error", + "no-useless-rename": "error", + "no-dupe-keys": "error", + "space-in-parens": [ + "error", + "never" + ], + "spaced-comment": [ + "error", + "always", + { + "block": { + "markers": [ + "!" + ], + "balanced": true + } + } + ], + "key-spacing": [ + "error", + { + "beforeColon": false, + "afterColon": true + } + ], + "comma-spacing": [ + "error", + { + "before": false, + "after": true + } + ], + "array-bracket-spacing": 1, + "arrow-spacing": [ + "error", + { + "before": true, + "after": true + } + ], + "object-curly-spacing": [ + "error", + "always" + ], + "comma-dangle": [ + "error", + "never" + ], + "no-unreachable": "error", + "quotes": [ + "error", + "single" + ], + "quote-props": [ + "error", + "as-needed" + ], + "semi": "error", + "no-extra-semi": "error", + "semi-spacing": "error", + "no-spaced-func": "error", + "no-throw-literal": "error", + "space-before-blocks": "error", + "space-before-function-paren": [ + "error", + "never" + ], + "space-infix-ops": "error", + "space-unary-ops": "error", + "no-var": "warn", + "prefer-const": "warn", + "strict": [ + "error", + "global" + ], + "no-restricted-globals": [ + "error", + { + "name": "context", + "message": "Don't use Mocha's global context" + } + ], + "no-prototype-builtins": "off" + } + } +} diff --git a/node_modules/mpath/test/.eslintrc.yml b/node_modules/mpath/test/.eslintrc.yml new file mode 100644 index 0000000..c0c6803 --- /dev/null +++ b/node_modules/mpath/test/.eslintrc.yml @@ -0,0 +1,4 @@ +env: + mocha: true +rules: + no-unused-vars: off \ No newline at end of file diff --git a/node_modules/mpath/test/index.js b/node_modules/mpath/test/index.js new file mode 100644 index 0000000..ce07b19 --- /dev/null +++ b/node_modules/mpath/test/index.js @@ -0,0 +1,1879 @@ +'use strict'; + +/** + * Test dependencies. + */ + +const mpath = require('../'); +const assert = require('assert'); + +/** + * logging helper + */ + +function log(o) { + console.log(); + console.log(require('util').inspect(o, false, 1000)); +} + +/** + * special path for override tests + */ + +const special = '_doc'; + +/** + * Tests + */ + +describe('mpath', function() { + + /** + * test doc creator + */ + + function doc() { + const o = { first: { second: { third: [3, { name: 'aaron' }, 9] } } }; + o.comments = [ + { name: 'one' }, + { name: 'two', _doc: { name: '2' } }, + { name: 'three', + comments: [{}, { comments: [{ val: 'twoo' }] }], + _doc: { name: '3', comments: [{}, { _doc: { comments: [{ val: 2 }] } }] } } + ]; + o.name = 'jiro'; + o.array = [ + { o: { array: [{ x: { b: [4, 6, 8] } }, { y: 10 }] } }, + { o: { array: [{ x: { b: [1, 2, 3] } }, { x: { z: 10 } }, { x: { b: 'hi' } }] } }, + { o: { array: [{ x: { b: null } }, { x: { b: [null, 1] } }] } }, + { o: { array: [{ x: null }] } }, + { o: { array: [{ y: 3 }] } }, + { o: { array: [3, 0, null] } }, + { o: { name: 'ha' } } + ]; + o.arr = [ + { arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: true } + ]; + return o; + } + + describe('get', function() { + const o = doc(); + + it('`path` must be a string or array', function(done) { + assert.throws(function() { + mpath.get({}, o); + }, /Must be either string or array/); + assert.throws(function() { + mpath.get(4, o); + }, /Must be either string or array/); + assert.throws(function() { + mpath.get(function() {}, o); + }, /Must be either string or array/); + assert.throws(function() { + mpath.get(/asdf/, o); + }, /Must be either string or array/); + assert.throws(function() { + mpath.get(Math, o); + }, /Must be either string or array/); + assert.throws(function() { + mpath.get(Buffer, o); + }, /Must be either string or array/); + assert.doesNotThrow(function() { + mpath.get('string', o); + }); + assert.doesNotThrow(function() { + mpath.get([], o); + }); + done(); + }); + + describe('without `special`', function() { + it('works', function(done) { + assert.equal('jiro', mpath.get('name', o)); + + assert.deepEqual( + { second: { third: [3, { name: 'aaron' }, 9] } } + , mpath.get('first', o) + ); + + assert.deepEqual( + { third: [3, { name: 'aaron' }, 9] } + , mpath.get('first.second', o) + ); + + assert.deepEqual( + [3, { name: 'aaron' }, 9] + , mpath.get('first.second.third', o) + ); + + assert.deepEqual( + 3 + , mpath.get('first.second.third.0', o) + ); + + assert.deepEqual( + 9 + , mpath.get('first.second.third.2', o) + ); + + assert.deepEqual( + { name: 'aaron' } + , mpath.get('first.second.third.1', o) + ); + + assert.deepEqual( + 'aaron' + , mpath.get('first.second.third.1.name', o) + ); + + assert.deepEqual([ + { name: 'one' }, + { name: 'two', _doc: { name: '2' } }, + { name: 'three', + comments: [{}, { comments: [{ val: 'twoo' }] }], + _doc: { name: '3', comments: [{}, { _doc: { comments: [{ val: 2 }] } }] } }], + mpath.get('comments', o)); + + assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o)); + assert.deepEqual('one', mpath.get('comments.0.name', o)); + assert.deepEqual('two', mpath.get('comments.1.name', o)); + assert.deepEqual('three', mpath.get('comments.2.name', o)); + + assert.deepEqual([{}, { comments: [{ val: 'twoo' }] }] + , mpath.get('comments.2.comments', o)); + + assert.deepEqual({ comments: [{ val: 'twoo' }] } + , mpath.get('comments.2.comments.1', o)); + + assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o)); + + done(); + }); + + it('handles array.property dot-notation', function(done) { + assert.deepEqual( + ['one', 'two', 'three'] + , mpath.get('comments.name', o) + ); + done(); + }); + + it('handles array.array notation', function(done) { + assert.deepEqual( + [undefined, undefined, [{}, { comments: [{ val: 'twoo' }] }]] + , mpath.get('comments.comments', o) + ); + done(); + }); + + it('handles prop.prop.prop.arrayProperty notation', function(done) { + assert.deepEqual( + [undefined, 'aaron', undefined] + , mpath.get('first.second.third.name', o) + ); + assert.deepEqual( + [1, 'aaron', 1] + , mpath.get('first.second.third.name', o, function(v) { + return undefined === v ? 1 : v; + }) + ); + done(); + }); + + it('handles array.prop.array', function(done) { + assert.deepEqual( + [[{ x: { b: [4, 6, 8] } }, { y: 10 }], + [{ x: { b: [1, 2, 3] } }, { x: { z: 10 } }, { x: { b: 'hi' } }], + [{ x: { b: null } }, { x: { b: [null, 1] } }], + [{ x: null }], + [{ y: 3 }], + [3, 0, null], + undefined + ] + , mpath.get('array.o.array', o) + ); + done(); + }); + + it('handles array.prop.array.index', function(done) { + assert.deepEqual( + [{ x: { b: [4, 6, 8] } }, + { x: { b: [1, 2, 3] } }, + { x: { b: null } }, + { x: null }, + { y: 3 }, + 3, + undefined + ] + , mpath.get('array.o.array.0', o) + ); + done(); + }); + + it('handles array.prop.array.index.prop', function(done) { + assert.deepEqual( + [{ b: [4, 6, 8] }, + { b: [1, 2, 3] }, + { b: null }, + null, + undefined, + undefined, + undefined + ] + , mpath.get('array.o.array.0.x', o) + ); + done(); + }); + + it('handles array.prop.array.prop', function(done) { + assert.deepEqual( + [[undefined, 10], + [undefined, undefined, undefined], + [undefined, undefined], + [undefined], + [3], + [undefined, undefined, undefined], + undefined + ] + , mpath.get('array.o.array.y', o) + ); + assert.deepEqual( + [[{ b: [4, 6, 8] }, undefined], + [{ b: [1, 2, 3] }, { z: 10 }, { b: 'hi' }], + [{ b: null }, { b: [null, 1] }], + [null], + [undefined], + [undefined, undefined, undefined], + undefined + ] + , mpath.get('array.o.array.x', o) + ); + done(); + }); + + it('handles array.prop.array.prop.prop', function(done) { + assert.deepEqual( + [[[4, 6, 8], undefined], + [[1, 2, 3], undefined, 'hi'], + [null, [null, 1]], + [null], + [undefined], + [undefined, undefined, undefined], + undefined + ] + , mpath.get('array.o.array.x.b', o) + ); + done(); + }); + + it('handles array.prop.array.prop.prop.index', function(done) { + assert.deepEqual( + [[6, undefined], + [2, undefined, 'i'], // undocumented feature (string indexing) + [null, 1], + [null], + [undefined], + [undefined, undefined, undefined], + undefined + ] + , mpath.get('array.o.array.x.b.1', o) + ); + assert.deepEqual( + [[6, 0], + [2, 0, 'i'], // undocumented feature (string indexing) + [null, 1], + [null], + [0], + [0, 0, 0], + 0 + ] + , mpath.get('array.o.array.x.b.1', o, function(v) { + return undefined === v ? 0 : v; + }) + ); + done(); + }); + + it('handles array.index.prop.prop', function(done) { + assert.deepEqual( + [{ x: { b: [1, 2, 3] } }, { x: { z: 10 } }, { x: { b: 'hi' } }] + , mpath.get('array.1.o.array', o) + ); + assert.deepEqual( + ['hi', 'hi', 'hi'] + , mpath.get('array.1.o.array', o, function(v) { + if (Array.isArray(v)) { + return v.map(function(val) { + return 'hi'; + }); + } + return v; + }) + ); + done(); + }); + + it('handles array.array.index', function(done) { + assert.deepEqual( + [{ a: { c: 48 } }, undefined] + , mpath.get('arr.arr.1', o) + ); + assert.deepEqual( + ['woot', undefined] + , mpath.get('arr.arr.1', o, function(v) { + if (v && v.a && v.a.c) return 'woot'; + return v; + }) + ); + done(); + }); + + it('handles array.array.index.prop', function(done) { + assert.deepEqual( + [{ c: 48 }, 'woot'] + , mpath.get('arr.arr.1.a', o, function(v) { + if (undefined === v) return 'woot'; + return v; + }) + ); + assert.deepEqual( + [{ c: 48 }, undefined] + , mpath.get('arr.arr.1.a', o) + ); + mpath.set('arr.arr.1.a', [{ c: 49 }, undefined], o); + assert.deepEqual( + [{ c: 49 }, undefined] + , mpath.get('arr.arr.1.a', o) + ); + mpath.set('arr.arr.1.a', [{ c: 48 }, undefined], o); + done(); + }); + + it('handles array.array.index.prop.prop', function(done) { + assert.deepEqual( + [48, undefined] + , mpath.get('arr.arr.1.a.c', o) + ); + assert.deepEqual( + [48, 'woot'] + , mpath.get('arr.arr.1.a.c', o, function(v) { + if (undefined === v) return 'woot'; + return v; + }) + ); + done(); + }); + + }); + + describe('with `special`', function() { + describe('that is a string', function() { + it('works', function(done) { + assert.equal('jiro', mpath.get('name', o, special)); + + assert.deepEqual( + { second: { third: [3, { name: 'aaron' }, 9] } } + , mpath.get('first', o, special) + ); + + assert.deepEqual( + { third: [3, { name: 'aaron' }, 9] } + , mpath.get('first.second', o, special) + ); + + assert.deepEqual( + [3, { name: 'aaron' }, 9] + , mpath.get('first.second.third', o, special) + ); + + assert.deepEqual( + 3 + , mpath.get('first.second.third.0', o, special) + ); + + assert.deepEqual( + 4 + , mpath.get('first.second.third.0', o, special, function(v) { + return 3 === v ? 4 : v; + }) + ); + + assert.deepEqual( + 9 + , mpath.get('first.second.third.2', o, special) + ); + + assert.deepEqual( + { name: 'aaron' } + , mpath.get('first.second.third.1', o, special) + ); + + assert.deepEqual( + 'aaron' + , mpath.get('first.second.third.1.name', o, special) + ); + + assert.deepEqual([ + { name: 'one' }, + { name: 'two', _doc: { name: '2' } }, + { name: 'three', + comments: [{}, { comments: [{ val: 'twoo' }] }], + _doc: { name: '3', comments: [{}, { _doc: { comments: [{ val: 2 }] } }] } }], + mpath.get('comments', o, special)); + + assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o, special)); + assert.deepEqual('one', mpath.get('comments.0.name', o, special)); + assert.deepEqual('2', mpath.get('comments.1.name', o, special)); + assert.deepEqual('3', mpath.get('comments.2.name', o, special)); + assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function(v) { + return '3' === v ? 'nice' : v; + })); + + assert.deepEqual([{}, { _doc: { comments: [{ val: 2 }] } }] + , mpath.get('comments.2.comments', o, special)); + + assert.deepEqual({ _doc: { comments: [{ val: 2 }] } } + , mpath.get('comments.2.comments.1', o, special)); + + assert.deepEqual(2, mpath.get('comments.2.comments.1.comments.0.val', o, special)); + done(); + }); + + it('handles array.property dot-notation', function(done) { + assert.deepEqual( + ['one', '2', '3'] + , mpath.get('comments.name', o, special) + ); + assert.deepEqual( + ['one', 2, '3'] + , mpath.get('comments.name', o, special, function(v) { + return '2' === v ? 2 : v; + }) + ); + done(); + }); + + it('handles array.array notation', function(done) { + assert.deepEqual( + [undefined, undefined, [{}, { _doc: { comments: [{ val: 2 }] } }]] + , mpath.get('comments.comments', o, special) + ); + done(); + }); + + it('handles array.array.index.array', function(done) { + assert.deepEqual( + [undefined, undefined, [{ val: 2 }]] + , mpath.get('comments.comments.1.comments', o, special) + ); + done(); + }); + + it('handles array.array.index.array.prop', function(done) { + assert.deepEqual( + [undefined, undefined, [2]] + , mpath.get('comments.comments.1.comments.val', o, special) + ); + assert.deepEqual( + ['nil', 'nil', [2]] + , mpath.get('comments.comments.1.comments.val', o, special, function(v) { + return undefined === v ? 'nil' : v; + }) + ); + done(); + }); + }); + + describe('that is a function', function() { + const special = function(obj, key) { + return obj[key]; + }; + + it('works', function(done) { + assert.equal('jiro', mpath.get('name', o, special)); + + assert.deepEqual( + { second: { third: [3, { name: 'aaron' }, 9] } } + , mpath.get('first', o, special) + ); + + assert.deepEqual( + { third: [3, { name: 'aaron' }, 9] } + , mpath.get('first.second', o, special) + ); + + assert.deepEqual( + [3, { name: 'aaron' }, 9] + , mpath.get('first.second.third', o, special) + ); + + assert.deepEqual( + 3 + , mpath.get('first.second.third.0', o, special) + ); + + assert.deepEqual( + 4 + , mpath.get('first.second.third.0', o, special, function(v) { + return 3 === v ? 4 : v; + }) + ); + + assert.deepEqual( + 9 + , mpath.get('first.second.third.2', o, special) + ); + + assert.deepEqual( + { name: 'aaron' } + , mpath.get('first.second.third.1', o, special) + ); + + assert.deepEqual( + 'aaron' + , mpath.get('first.second.third.1.name', o, special) + ); + + assert.deepEqual([ + { name: 'one' }, + { name: 'two', _doc: { name: '2' } }, + { name: 'three', + comments: [{}, { comments: [{ val: 'twoo' }] }], + _doc: { name: '3', comments: [{}, { _doc: { comments: [{ val: 2 }] } }] } }], + mpath.get('comments', o, special)); + + assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o, special)); + assert.deepEqual('one', mpath.get('comments.0.name', o, special)); + assert.deepEqual('two', mpath.get('comments.1.name', o, special)); + assert.deepEqual('three', mpath.get('comments.2.name', o, special)); + assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function(v) { + return 'three' === v ? 'nice' : v; + })); + + assert.deepEqual([{}, { comments: [{ val: 'twoo' }] }] + , mpath.get('comments.2.comments', o, special)); + + assert.deepEqual({ comments: [{ val: 'twoo' }] } + , mpath.get('comments.2.comments.1', o, special)); + + assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o, special)); + + let overide = false; + assert.deepEqual('twoo', mpath.get('comments.8.comments.1.comments.0.val', o, function(obj, path) { + if (Array.isArray(obj) && 8 == path) { + overide = true; + return obj[2]; + } + return obj[path]; + })); + assert.ok(overide); + + done(); + }); + + it('in combination with map', function(done) { + const special = function(obj, key) { + if (Array.isArray(obj)) return obj[key]; + return obj.mpath; + }; + const map = function(val) { + return 'convert' == val + ? 'mpath' + : val; + }; + const o = { mpath: [{ mpath: 'converse' }, { mpath: 'convert' }] }; + + assert.equal('mpath', mpath.get('something.1.kewl', o, special, map)); + done(); + }); + }); + }); + }); + + describe('set', function() { + it('prevents writing to __proto__', function() { + const obj = {}; + mpath.set('__proto__.x', 'foobar', obj); + assert.ok(!({}.x)); + + mpath.set('constructor.prototype.x', 'foobar', obj); + assert.ok(!({}.x)); + }); + + describe('without `special`', function() { + const o = doc(); + + it('works', function(done) { + mpath.set('name', 'a new val', o, function(v) { + return 'a new val' === v ? 'changed' : v; + }); + assert.deepEqual('changed', o.name); + + mpath.set('name', 'changed', o); + assert.deepEqual('changed', o.name); + + mpath.set('first.second.third', [1, { name: 'x' }, 9], o); + assert.deepEqual([1, { name: 'x' }, 9], o.first.second.third); + + mpath.set('first.second.third.1.name', 'y', o); + assert.deepEqual([1, { name: 'y' }, 9], o.first.second.third); + + mpath.set('comments.1.name', 'ttwwoo', o); + assert.deepEqual({ name: 'ttwwoo', _doc: { name: '2' } }, o.comments[1]); + + mpath.set('comments.2.comments.1.comments.0.expand', 'added', o); + assert.deepEqual( + { val: 'twoo', expand: 'added' } + , o.comments[2].comments[1].comments[0]); + + mpath.set('comments.2.comments.1.comments.2', 'added', o); + assert.equal(3, o.comments[2].comments[1].comments.length); + assert.deepEqual( + { val: 'twoo', expand: 'added' } + , o.comments[2].comments[1].comments[0]); + assert.deepEqual( + undefined + , o.comments[2].comments[1].comments[1]); + assert.deepEqual( + 'added' + , o.comments[2].comments[1].comments[2]); + + done(); + }); + + describe('array.path', function() { + describe('with single non-array value', function() { + it('works', function(done) { + mpath.set('arr.yep', false, o, function(v) { + return false === v ? true : v; + }); + assert.deepEqual([ + { yep: true, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: true } + ], o.arr); + + mpath.set('arr.yep', false, o); + + assert.deepEqual([ + { yep: false, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: false } + ], o.arr); + + done(); + }); + }); + describe('with array of values', function() { + it('that are equal in length', function(done) { + mpath.set('arr.yep', ['one', 2], o, function(v) { + return 'one' === v ? 1 : v; + }); + assert.deepEqual([ + { yep: 1, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: 2 } + ], o.arr); + mpath.set('arr.yep', ['one', 2], o); + + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: 2 } + ], o.arr); + + done(); + }); + + it('that is less than length', function(done) { + mpath.set('arr.yep', [47], o, function(v) { + return 47 === v ? 4 : v; + }); + assert.deepEqual([ + { yep: 4, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: 2 } + ], o.arr); + + mpath.set('arr.yep', [47], o); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: 2 } + ], o.arr); + + done(); + }); + + it('that is greater than length', function(done) { + mpath.set('arr.yep', [5, 6, 7], o, function(v) { + return 5 === v ? 'five' : v; + }); + assert.deepEqual([ + { yep: 'five', arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: 6 } + ], o.arr); + + mpath.set('arr.yep', [5, 6, 7], o); + assert.deepEqual([ + { yep: 5, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: 6 } + ], o.arr); + + done(); + }); + }); + }); + + describe('array.$.path', function() { + describe('with single non-array value', function() { + it('copies the value to each item in array', function(done) { + mpath.set('arr.$.yep', { xtra: 'double good' }, o, function(v) { + return v && v.xtra ? 'hi' : v; + }); + assert.deepEqual([ + { yep: 'hi', arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: 'hi' } + ], o.arr); + + mpath.set('arr.$.yep', { xtra: 'double good' }, o); + assert.deepEqual([ + { yep: { xtra: 'double good' }, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: { xtra: 'double good' } } + ], o.arr); + + done(); + }); + }); + describe('with array of values', function() { + it('copies the value to each item in array', function(done) { + mpath.set('arr.$.yep', [15], o, function(v) { + return v.length === 1 ? [] : v; + }); + assert.deepEqual([ + { yep: [], arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: [] } + ], o.arr); + + mpath.set('arr.$.yep', [15], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: [15] } + ], o.arr); + + done(); + }); + }); + }); + + describe('array.index.path', function() { + it('works', function(done) { + mpath.set('arr.1.yep', 0, o, function(v) { + return 0 === v ? 'zero' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: 'zero' } + ], o.arr); + + mpath.set('arr.1.yep', 0, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: 0 } + ], o.arr); + + done(); + }); + }); + + describe('array.index.array.path', function() { + it('with single value', function(done) { + mpath.set('arr.0.arr.e', 35, o, function(v) { + return 35 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 3 }, { a: { c: 48 }, e: 3 }, { d: 'yep', e: 3 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.e', 35, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 35 }, { a: { c: 48 }, e: 35 }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + done(); + }); + it('with array', function(done) { + mpath.set('arr.0.arr.e', ['a', 'b'], o, function(v) { + return 'a' === v ? 'x' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 'x' }, { a: { c: 48 }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.e', ['a', 'b'], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 'a' }, { a: { c: 48 }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + done(); + }); + }); + + describe('array.index.array.path.path', function() { + it('with single value', function(done) { + mpath.set('arr.0.arr.a.b', 36, o, function(v) { + return 36 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 3 }, e: 'a' }, { a: { c: 48, b: 3 }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.a.b', 36, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 36 }, e: 'a' }, { a: { c: 48, b: 36 }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + done(); + }); + it('with array', function(done) { + mpath.set('arr.0.arr.a.b', [1, 2, 3, 4], o, function(v) { + return 2 === v ? 'two' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 1 }, e: 'a' }, { a: { c: 48, b: 'two' }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.a.b', [1, 2, 3, 4], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 1 }, e: 'a' }, { a: { c: 48, b: 2 }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + done(); + }); + }); + + describe('array.index.array.$.path.path', function() { + it('with single value', function(done) { + mpath.set('arr.0.arr.$.a.b', '$', o, function(v) { + return '$' === v ? 'dolla billz' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 'dolla billz' }, e: 'a' }, { a: { c: 48, b: 'dolla billz' }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', '$', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: '$' }, e: 'a' }, { a: { c: 48, b: '$' }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + done(); + }); + it('with array', function(done) { + mpath.set('arr.0.arr.$.a.b', [1], o, function(v) { + return Array.isArray(v) ? {} : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: {} }, e: 'a' }, { a: { c: 48, b: {} }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', [1], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: [1] }, e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + done(); + }); + }); + + describe('array.array.index.path', function() { + it('with single value', function(done) { + mpath.set('arr.arr.0.a', 'single', o, function(v) { + return 'single' === v ? 'double' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'double', e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('arr.arr.0.a', 'single', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'single', e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + done(); + }); + it('with array', function(done) { + mpath.set('arr.arr.0.a', [4, 8, 15, 16, 23, 42], o, function(v) { + return 4 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 3, e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: false } + ], o.arr); + + mpath.set('arr.arr.0.a', [4, 8, 15, 16, 23, 42], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 4, e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: false } + ], o.arr); + + done(); + }); + }); + + describe('array.array.$.index.path', function() { + it('with single value', function(done) { + mpath.set('arr.arr.$.0.a', 'singles', o, function(v) { + return 0; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 0, e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('arr.arr.$.0.a', 'singles', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'singles', e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('$.arr.arr.0.a', 'single', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'single', e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + done(); + }); + it('with array', function(done) { + mpath.set('arr.arr.$.0.a', [4, 8, 15, 16, 23, 42], o, function(v) { + return 'nope'; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'nope', e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('arr.arr.$.0.a', [4, 8, 15, 16, 23, 42], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4, 8, 15, 16, 23, 42], e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('arr.$.arr.0.a', [4, 8, 15, 16, 23, 42, 108], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4, 8, 15, 16, 23, 42, 108], e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + done(); + }); + }); + + describe('array.array.path.index', function() { + it('with single value', function(done) { + mpath.set('arr.arr.a.7', 47, o, function(v) { + return 1; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4, 8, 15, 16, 23, 42, 108, 1], e: 'a' }, { a: { c: 48, b: [1], 7: 1 }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + mpath.set('arr.arr.a.7', 47, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4, 8, 15, 16, 23, 42, 108, 47], e: 'a' }, { a: { c: 48, b: [1], 7: 47 }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0 } + ], o.arr); + + done(); + }); + it('with array', function(done) { + o.arr[1].arr = [{ a: [] }, { a: [] }, { a: null }]; + mpath.set('arr.arr.a.7', [[null, 46], [undefined, 'woot']], o); + + const a1 = []; + const a2 = []; + a1[7] = undefined; + a2[7] = 'woot'; + + assert.deepEqual([ + { yep: [15], arr: [{ a: [4, 8, 15, 16, 23, 42, 108, null], e: 'a' }, { a: { c: 48, b: [1], 7: 46 }, e: 'b' }, { d: 'yep', e: 35 }] }, + { yep: 0, arr: [{ a: a1 }, { a: a2 }, { a: null }] } + ], o.arr); + + done(); + }); + }); + + describe('handles array.array.path', function() { + it('with single', function(done) { + o.arr[1].arr = [{}, {}]; + assert.deepEqual([{}, {}], o.arr[1].arr); + o.arr.push({ arr: 'something else' }); + o.arr.push({ arr: ['something else'] }); + o.arr.push({ arr: [[]] }); + o.arr.push({ arr: [5] }); + + const weird = []; + weird.e = 'xmas'; + + // test + mpath.set('arr.arr.e', 47, o, function(v) { + return 'xmas'; + }); + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4, 8, 15, 16, 23, 42, 108, null], e: 'xmas' }, + { a: { c: 48, b: [1], 7: 46 }, e: 'xmas' }, + { d: 'yep', e: 'xmas' } + ] + }, + { yep: 0, arr: [{ e: 'xmas' }, { e: 'xmas' }] }, + { arr: 'something else' }, + { arr: ['something else'] }, + { arr: [weird] }, + { arr: [5] } + ] + , o.arr); + + weird.e = 47; + + mpath.set('arr.arr.e', 47, o); + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4, 8, 15, 16, 23, 42, 108, null], e: 47 }, + { a: { c: 48, b: [1], 7: 46 }, e: 47 }, + { d: 'yep', e: 47 } + ] + }, + { yep: 0, arr: [{ e: 47 }, { e: 47 }] }, + { arr: 'something else' }, + { arr: ['something else'] }, + { arr: [weird] }, + { arr: [5] } + ] + , o.arr); + + done(); + }); + it('with arrays', function(done) { + mpath.set('arr.arr.e', [[1, 2, 3], [4, 5], null, [], [6], [7, 8, 9]], o, function(v) { + return 10; + }); + + const weird = []; + weird.e = 10; + + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4, 8, 15, 16, 23, 42, 108, null], e: 10 }, + { a: { c: 48, b: [1], 7: 46 }, e: 10 }, + { d: 'yep', e: 10 } + ] + }, + { yep: 0, arr: [{ e: 10 }, { e: 10 }] }, + { arr: 'something else' }, + { arr: ['something else'] }, + { arr: [weird] }, + { arr: [5] } + ] + , o.arr); + + mpath.set('arr.arr.e', [[1, 2, 3], [4, 5], null, [], [6], [7, 8, 9]], o); + + weird.e = 6; + + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4, 8, 15, 16, 23, 42, 108, null], e: 1 }, + { a: { c: 48, b: [1], 7: 46 }, e: 2 }, + { d: 'yep', e: 3 } + ] + }, + { yep: 0, arr: [{ e: 4 }, { e: 5 }] }, + { arr: 'something else' }, + { arr: ['something else'] }, + { arr: [weird] }, + { arr: [5] } + ] + , o.arr); + + done(); + }); + }); + }); + + describe('with `special`', function() { + const o = doc(); + + it('works', function(done) { + mpath.set('name', 'chan', o, special, function(v) { + return 'hi'; + }); + assert.deepEqual('hi', o.name); + + mpath.set('name', 'changer', o, special); + assert.deepEqual('changer', o.name); + + mpath.set('first.second.third', [1, { name: 'y' }, 9], o, special); + assert.deepEqual([1, { name: 'y' }, 9], o.first.second.third); + + mpath.set('first.second.third.1.name', 'z', o, special); + assert.deepEqual([1, { name: 'z' }, 9], o.first.second.third); + + mpath.set('comments.1.name', 'ttwwoo', o, special); + assert.deepEqual({ name: 'two', _doc: { name: 'ttwwoo' } }, o.comments[1]); + + mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special, function(v) { + return 'super'; + }); + assert.deepEqual( + { val: 2, expander: 'super' } + , o.comments[2]._doc.comments[1]._doc.comments[0]); + + mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special); + assert.deepEqual( + { val: 2, expander: 'adder' } + , o.comments[2]._doc.comments[1]._doc.comments[0]); + + mpath.set('comments.2.comments.1.comments.2', 'set', o, special); + assert.equal(3, o.comments[2]._doc.comments[1]._doc.comments.length); + assert.deepEqual( + { val: 2, expander: 'adder' } + , o.comments[2]._doc.comments[1]._doc.comments[0]); + assert.deepEqual( + undefined + , o.comments[2]._doc.comments[1]._doc.comments[1]); + assert.deepEqual( + 'set' + , o.comments[2]._doc.comments[1]._doc.comments[2]); + done(); + }); + + describe('array.path', function() { + describe('with single non-array value', function() { + it('works', function(done) { + o.arr[1]._doc = { special: true }; + + mpath.set('arr.yep', false, o, special, function(v) { + return 'yes'; + }); + assert.deepEqual([ + { yep: 'yes', arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: true, _doc: { special: true, yep: 'yes' } } + ], o.arr); + + mpath.set('arr.yep', false, o, special); + assert.deepEqual([ + { yep: false, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: true, _doc: { special: true, yep: false } } + ], o.arr); + + done(); + }); + }); + describe('with array of values', function() { + it('that are equal in length', function(done) { + mpath.set('arr.yep', ['one', 2], o, special, function(v) { + return 2 === v ? 20 : v; + }); + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: true, _doc: { special: true, yep: 20 } } + ], o.arr); + + mpath.set('arr.yep', ['one', 2], o, special); + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: true, _doc: { special: true, yep: 2 } } + ], o.arr); + + done(); + }); + + it('that is less than length', function(done) { + mpath.set('arr.yep', [47], o, special, function(v) { + return 80; + }); + assert.deepEqual([ + { yep: 80, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: true, _doc: { special: true, yep: 2 } } + ], o.arr); + + mpath.set('arr.yep', [47], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }, + { yep: true, _doc: { special: true, yep: 2 } } + ], o.arr); + + // add _doc to first element + o.arr[0]._doc = { yep: 46, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] }; + + mpath.set('arr.yep', [20], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], _doc: { yep: 20, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] } }, + { yep: true, _doc: { special: true, yep: 2 } } + ], o.arr); + + done(); + }); + + it('that is greater than length', function(done) { + mpath.set('arr.yep', [5, 6, 7], o, special, function() { + return 'x'; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], _doc: { yep: 'x', arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] } }, + { yep: true, _doc: { special: true, yep: 'x' } } + ], o.arr); + + mpath.set('arr.yep', [5, 6, 7], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], _doc: { yep: 5, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] } }, + { yep: true, _doc: { special: true, yep: 6 } } + ], o.arr); + + done(); + }); + }); + }); + + describe('array.$.path', function() { + describe('with single non-array value', function() { + it('copies the value to each item in array', function(done) { + mpath.set('arr.$.yep', { xtra: 'double good' }, o, special, function(v) { + return 9; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: 9, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] } }, + { yep: true, _doc: { special: true, yep: 9 } } + ], o.arr); + + mpath.set('arr.$.yep', { xtra: 'double good' }, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: { xtra: 'double good' }, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] } }, + { yep: true, _doc: { special: true, yep: { xtra: 'double good' } } } + ], o.arr); + + done(); + }); + }); + describe('with array of values', function() { + it('copies the value to each item in array', function(done) { + mpath.set('arr.$.yep', [15], o, special, function(v) { + return 'array'; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: 'array', arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] } }, + { yep: true, _doc: { special: true, yep: 'array' } } + ], o.arr); + + mpath.set('arr.$.yep', [15], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] } }, + { yep: true, _doc: { special: true, yep: [15] } } + ], o.arr); + + done(); + }); + }); + }); + + describe('array.index.path', function() { + it('works', function(done) { + mpath.set('arr.1.yep', 0, o, special, function(v) { + return 1; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] } }, + { yep: true, _doc: { special: true, yep: 1 } } + ], o.arr); + + mpath.set('arr.1.yep', 0, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + }); + + describe('array.index.array.path', function() { + it('with single value', function(done) { + mpath.set('arr.0.arr.e', 35, o, special, function(v) { + return 30; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 30 }, { a: { c: 48 }, e: 30 }, { d: 'yep', e: 30 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.0.arr.e', 35, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 35 }, { a: { c: 48 }, e: 35 }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + it('with array', function(done) { + mpath.set('arr.0.arr.e', ['a', 'b'], o, special, function(v) { + return 'a' === v ? 'A' : v; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'A' }, { a: { c: 48 }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.0.arr.e', ['a', 'b'], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'a' }, { a: { c: 48 }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + }); + + describe('array.index.array.path.path', function() { + it('with single value', function(done) { + mpath.set('arr.0.arr.a.b', 36, o, special, function(v) { + return 20; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 20 }, e: 'a' }, { a: { c: 48, b: 20 }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.0.arr.a.b', 36, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 36 }, e: 'a' }, { a: { c: 48, b: 36 }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + it('with array', function(done) { + mpath.set('arr.0.arr.a.b', [1, 2, 3, 4], o, special, function(v) { + return v * 2; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 2 }, e: 'a' }, { a: { c: 48, b: 4 }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.0.arr.a.b', [1, 2, 3, 4], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 1 }, e: 'a' }, { a: { c: 48, b: 2 }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + }); + + describe('array.index.array.$.path.path', function() { + it('with single value', function(done) { + mpath.set('arr.0.arr.$.a.b', '$', o, special, function(v) { + return 'dollaz'; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: 'dollaz' }, e: 'a' }, { a: { c: 48, b: 'dollaz' }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', '$', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: '$' }, e: 'a' }, { a: { c: 48, b: '$' }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + it('with array', function(done) { + mpath.set('arr.0.arr.$.a.b', [1], o, special, function(v) { + return {}; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: {} }, e: 'a' }, { a: { c: 48, b: {} }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', [1], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: { b: [1] }, e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + }); + + describe('array.array.index.path', function() { + it('with single value', function(done) { + mpath.set('arr.arr.0.a', 'single', o, special, function(v) { + return 88; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: 88, e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.arr.0.a', 'single', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: 'single', e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + it('with array', function(done) { + mpath.set('arr.arr.0.a', [4, 8, 15, 16, 23, 42], o, special, function(v) { + return v * 2; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: 8, e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.arr.0.a', [4, 8, 15, 16, 23, 42], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: 4, e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + }); + + describe('array.array.$.index.path', function() { + it('with single value', function(done) { + mpath.set('arr.arr.$.0.a', 'singles', o, special, function(v) { + return v.toUpperCase(); + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: 'SINGLES', e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.arr.$.0.a', 'singles', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: 'singles', e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('$.arr.arr.0.a', 'single', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: 'single', e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + it('with array', function(done) { + mpath.set('arr.arr.$.0.a', [4, 8, 15, 16, 23, 42], o, special, function(v) { + return Array; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: Array, e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.arr.$.0.a', [4, 8, 15, 16, 23, 42], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: [4, 8, 15, 16, 23, 42], e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.$.arr.0.a', [4, 8, 15, 16, 23, 42, 108], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: [4, 8, 15, 16, 23, 42, 108], e: 'a' }, { a: { c: 48, b: [1] }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + }); + + describe('array.array.path.index', function() { + it('with single value', function(done) { + mpath.set('arr.arr.a.7', 47, o, special, function(v) { + return Object; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: [4, 8, 15, 16, 23, 42, 108, Object], e: 'a' }, { a: { c: 48, b: [1], 7: Object }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.arr.a.7', 47, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: [4, 8, 15, 16, 23, 42, 108, 47], e: 'a' }, { a: { c: 48, b: [1], 7: 47 }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { special: true, yep: 0 } } + ], o.arr); + + done(); + }); + it('with array', function(done) { + o.arr[1]._doc.arr = [{ a: [] }, { a: [] }, { a: null }]; + mpath.set('arr.arr.a.7', [[null, 46], [undefined, 'woot']], o, special, function(v) { + return undefined === v ? 'nope' : v; + }); + + const a1 = []; + const a2 = []; + a1[7] = 'nope'; + a2[7] = 'woot'; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: [4, 8, 15, 16, 23, 42, 108, null], e: 'a' }, { a: { c: 48, b: [1], 7: 46 }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { arr: [{ a: a1 }, { a: a2 }, { a: null }], special: true, yep: 0 } } + ], o.arr); + + mpath.set('arr.arr.a.7', [[null, 46], [undefined, 'woot']], o, special); + + a1[7] = undefined; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { yep: [15], arr: [{ a: [4, 8, 15, 16, 23, 42, 108, null], e: 'a' }, { a: { c: 48, b: [1], 7: 46 }, e: 'b' }, { d: 'yep', e: 35 }] } }, + { yep: true, _doc: { arr: [{ a: a1 }, { a: a2 }, { a: null }], special: true, yep: 0 } } + ], o.arr); + + done(); + }); + }); + + describe('handles array.array.path', function() { + it('with single', function(done) { + o.arr[1]._doc.arr = [{}, {}]; + assert.deepEqual([{}, {}], o.arr[1]._doc.arr); + o.arr.push({ _doc: { arr: 'something else' } }); + o.arr.push({ _doc: { arr: ['something else'] } }); + o.arr.push({ _doc: { arr: [[]] } }); + o.arr.push({ _doc: { arr: [5] } }); + + // test + mpath.set('arr.arr.e', 47, o, special); + + const weird = []; + weird.e = 47; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { + yep: [15], + arr: [ + { a: [4, 8, 15, 16, 23, 42, 108, null], e: 47 }, + { a: { c: 48, b: [1], 7: 46 }, e: 47 }, + { d: 'yep', e: 47 } + ] + } + }, + { yep: true, + _doc: { + arr: [ + { e: 47 }, + { e: 47 } + ], + special: true, + yep: 0 + } + }, + { _doc: { arr: 'something else' } }, + { _doc: { arr: ['something else'] } }, + { _doc: { arr: [weird] } }, + { _doc: { arr: [5] } } + ] + , o.arr); + + done(); + }); + it('with arrays', function(done) { + mpath.set('arr.arr.e', [[1, 2, 3], [4, 5], null, [], [6], [7, 8, 9]], o, special); + + const weird = []; + weird.e = 6; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 } }, { a: { c: 48 } }, { d: 'yep' }], + _doc: { + yep: [15], + arr: [ + { a: [4, 8, 15, 16, 23, 42, 108, null], e: 1 }, + { a: { c: 48, b: [1], 7: 46 }, e: 2 }, + { d: 'yep', e: 3 } + ] + } + }, + { yep: true, + _doc: { + arr: [ + { e: 4 }, + { e: 5 } + ], + special: true, + yep: 0 + } + }, + { _doc: { arr: 'something else' } }, + { _doc: { arr: ['something else'] } }, + { _doc: { arr: [weird] } }, + { _doc: { arr: [5] } } + ] + , o.arr); + + done(); + }); + }); + + describe('that is a function', function() { + describe('without map', function() { + it('works on array value', function(done) { + const o = { hello: { world: [{ how: 'are' }, { you: '?' }] } }; + const special = function(obj, key, val) { + if (val) { + obj[key] = val; + } else { + return 'thing' == key + ? obj.world + : obj[key]; + } + }; + mpath.set('hello.thing.how', 'arrrr', o, special); + assert.deepEqual(o, { hello: { world: [{ how: 'arrrr' }, { you: '?', how: 'arrrr' }] } }); + done(); + }); + it('works on non-array value', function(done) { + const o = { hello: { world: { how: 'are you' } } }; + const special = function(obj, key, val) { + if (val) { + obj[key] = val; + } else { + return 'thing' == key + ? obj.world + : obj[key]; + } + }; + mpath.set('hello.thing.how', 'RU', o, special); + assert.deepEqual(o, { hello: { world: { how: 'RU' } } }); + done(); + }); + }); + it('works with map', function(done) { + const o = { hello: { world: [{ how: 'are' }, { you: '?' }] } }; + const special = function(obj, key, val) { + if (val) { + obj[key] = val; + } else { + return 'thing' == key + ? obj.world + : obj[key]; + } + }; + const map = function(val) { + return 'convert' == val + ? 'ºº' + : val; + }; + mpath.set('hello.thing.how', 'convert', o, special, map); + assert.deepEqual(o, { hello: { world: [{ how: 'ºº' }, { you: '?', how: 'ºº' }] } }); + done(); + }); + }); + + }); + + describe('get/set integration', function() { + const o = doc(); + + it('works', function(done) { + const vals = mpath.get('array.o.array.x.b', o); + + vals[0][0][2] = 10; + vals[1][0][1] = 0; + vals[1][1] = 'Rambaldi'; + vals[1][2] = [12, 14]; + vals[2] = [{ changed: true }, [null, ['changed', 'to', 'array']]]; + + mpath.set('array.o.array.x.b', vals, o); + + const t = [ + { o: { array: [{ x: { b: [4, 6, 10] } }, { y: 10 }] } }, + { o: { array: [{ x: { b: [1, 0, 3] } }, { x: { b: 'Rambaldi', z: 10 } }, { x: { b: [12, 14] } }] } }, + { o: { array: [{ x: { b: { changed: true } } }, { x: { b: [null, ['changed', 'to', 'array']] } }] } }, + { o: { array: [{ x: null }] } }, + { o: { array: [{ y: 3 }] } }, + { o: { array: [3, 0, null] } }, + { o: { name: 'ha' } } + ]; + assert.deepEqual(t, o.array); + done(); + }); + + it('array.prop', function(done) { + mpath.set('comments.name', ['this', 'was', 'changed'], o); + + assert.deepEqual([ + { name: 'this' }, + { name: 'was', _doc: { name: '2' } }, + { name: 'changed', + comments: [{}, { comments: [{ val: 'twoo' }] }], + _doc: { name: '3', comments: [{}, { _doc: { comments: [{ val: 2 }] } }] } } + ], o.comments); + + mpath.set('comments.name', ['also', 'changed', 'this'], o, special); + + assert.deepEqual([ + { name: 'also' }, + { name: 'was', _doc: { name: 'changed' } }, + { name: 'changed', + comments: [{}, { comments: [{ val: 'twoo' }] }], + _doc: { name: 'this', comments: [{}, { _doc: { comments: [{ val: 2 }] } }] } } + ], o.comments); + + done(); + }); + + it('nested array', function(done) { + const obj = { arr: [[{ test: 41 }]] }; + mpath.set('arr.test', [[42]], obj); + assert.deepEqual(obj.arr, [[{ test: 42 }]]); + done(); + }); + }); + + describe('multiple $ use', function() { + const o = doc(); + it('is ok', function(done) { + assert.doesNotThrow(function() { + mpath.set('arr.$.arr.$.a', 35, o); + }); + done(); + }); + }); + + it('has', function(done) { + assert.ok(mpath.has('a', { a: 1 })); + assert.ok(mpath.has('a', { a: undefined })); + assert.ok(!mpath.has('a', {})); + assert.ok(!mpath.has('a', null)); + + assert.ok(mpath.has('a.b', { a: { b: 1 } })); + assert.ok(mpath.has('a.b', { a: { b: undefined } })); + assert.ok(!mpath.has('a.b', { a: 1 })); + assert.ok(!mpath.has('a.b', { a: null })); + + done(); + }); + + it('underneath a map', function(done) { + if (!global.Map) { + done(); + return; + } + assert.equal(mpath.get('a.b', { a: new Map([['b', 1]]) }), 1); + + const m = new Map([['b', 1]]); + const obj = { a: m }; + mpath.set('a.c', 2, obj); + assert.equal(m.get('c'), 2); + + done(); + }); + + it('unset', function(done) { + let o = { a: 1 }; + mpath.unset('a', o); + assert.deepEqual(o, {}); + + o = { a: { b: 1 } }; + mpath.unset('a.b', o); + assert.deepEqual(o, { a: {} }); + + o = { a: null }; + mpath.unset('a.b', o); + assert.deepEqual(o, { a: null }); + + done(); + }); + + it('unset with __proto__', function(done) { + // Should refuse to set __proto__ + function Clazz() {} + Clazz.prototype.foobar = true; + + mpath.unset('__proto__.foobar', new Clazz()); + assert.ok(Clazz.prototype.foobar); + + mpath.unset('constructor.prototype.foobar', new Clazz()); + assert.ok(Clazz.prototype.foobar); + + done(); + }); + + it('get() underneath subclassed array', function(done) { + class MyArray extends Array {} + + const obj = { + arr: new MyArray() + }; + obj.arr.push({ test: 2 }); + + const arr = mpath.get('arr.test', obj); + assert.equal(arr.constructor.name, 'Array'); + assert.ok(!(arr instanceof MyArray)); + + done(); + }); + + it('ignores setting a nested path that doesnt exist', function(done) { + const o = doc(); + assert.doesNotThrow(function() { + mpath.set('thing.that.is.new', 10, o); + }); + done(); + }); + }); +}); diff --git a/node_modules/mpath/test/stringToParts.js b/node_modules/mpath/test/stringToParts.js new file mode 100644 index 0000000..09940df --- /dev/null +++ b/node_modules/mpath/test/stringToParts.js @@ -0,0 +1,30 @@ +'use strict'; + +const assert = require('assert'); +const stringToParts = require('../lib/stringToParts'); + +describe('stringToParts', function() { + it('handles brackets for numbers', function() { + assert.deepEqual(stringToParts('list[0].name'), ['list', '0', 'name']); + assert.deepEqual(stringToParts('list[0][1].name'), ['list', '0', '1', 'name']); + }); + + it('handles dot notation', function() { + assert.deepEqual(stringToParts('a.b.c'), ['a', 'b', 'c']); + assert.deepEqual(stringToParts('a..b.d'), ['a', '', 'b', 'd']); + }); + + it('ignores invalid numbers in square brackets', function() { + assert.deepEqual(stringToParts('foo[1mystring]'), ['foo[1mystring]']); + assert.deepEqual(stringToParts('foo[1mystring].bar[1]'), ['foo[1mystring]', 'bar', '1']); + assert.deepEqual(stringToParts('foo[1mystring][2]'), ['foo[1mystring]', '2']); + }); + + it('handles empty string', function() { + assert.deepEqual(stringToParts(''), ['']); + }); + + it('handles trailing dot', function() { + assert.deepEqual(stringToParts('a.b.'), ['a', 'b', '']); + }); +}); \ No newline at end of file diff --git a/node_modules/mquery/.eslintignore b/node_modules/mquery/.eslintignore new file mode 100644 index 0000000..4b4d863 --- /dev/null +++ b/node_modules/mquery/.eslintignore @@ -0,0 +1 @@ +coverage/ \ No newline at end of file diff --git a/node_modules/mquery/.eslintrc.json b/node_modules/mquery/.eslintrc.json new file mode 100644 index 0000000..8dabf1a --- /dev/null +++ b/node_modules/mquery/.eslintrc.json @@ -0,0 +1,123 @@ +{ + "extends": [ + "eslint:recommended" + ], + "plugins": [ + "mocha-no-only" + ], + "parserOptions": { + "ecmaVersion": 2017 + }, + "env": { + "node": true, + "es6": true + }, + "rules": { + "comma-style": "error", + "indent": [ + "error", + 2, + { + "SwitchCase": 1, + "VariableDeclarator": 2 + } + ], + "keyword-spacing": "error", + "no-whitespace-before-property": "error", + "no-buffer-constructor": "warn", + "no-console": "off", + "no-multi-spaces": "error", + "no-constant-condition": "off", + "func-call-spacing": "error", + "no-trailing-spaces": "error", + "no-undef": "error", + "no-unneeded-ternary": "error", + "no-const-assign": "error", + "no-useless-rename": "error", + "no-dupe-keys": "error", + "space-in-parens": [ + "error", + "never" + ], + "spaced-comment": [ + "error", + "always", + { + "block": { + "markers": [ + "!" + ], + "balanced": true + } + } + ], + "key-spacing": [ + "error", + { + "beforeColon": false, + "afterColon": true + } + ], + "comma-spacing": [ + "error", + { + "before": false, + "after": true + } + ], + "array-bracket-spacing": 1, + "arrow-spacing": [ + "error", + { + "before": true, + "after": true + } + ], + "object-curly-spacing": [ + "error", + "always" + ], + "comma-dangle": [ + "error", + "never" + ], + "no-unreachable": "error", + "quotes": [ + "error", + "single" + ], + "quote-props": [ + "error", + "as-needed" + ], + "semi": "error", + "no-extra-semi": "error", + "semi-spacing": "error", + "no-spaced-func": "error", + "no-throw-literal": "error", + "space-before-blocks": "error", + "space-before-function-paren": [ + "error", + "never" + ], + "space-infix-ops": "error", + "space-unary-ops": "error", + "no-var": "warn", + "prefer-const": "warn", + "strict": [ + "error", + "global" + ], + "no-restricted-globals": [ + "error", + { + "name": "context", + "message": "Don't use Mocha's global context" + } + ], + "no-prototype-builtins": "off", + "mocha-no-only/mocha-no-only": [ + "error" + ] + } +} \ No newline at end of file diff --git a/node_modules/mquery/.travis.yml b/node_modules/mquery/.travis.yml new file mode 100644 index 0000000..3d207e1 --- /dev/null +++ b/node_modules/mquery/.travis.yml @@ -0,0 +1,17 @@ +language: node_js +node_js: + - "8" + - "10" + - "12" +matrix: + include: + - node_js: "13" + env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly" + allow_failures: + # Allow the nightly installs to fail + - env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly" +script: + - npm test + - npm run lint +services: + - mongodb diff --git a/node_modules/mquery/History.md b/node_modules/mquery/History.md new file mode 100644 index 0000000..6b40aa9 --- /dev/null +++ b/node_modules/mquery/History.md @@ -0,0 +1,363 @@ +4.0.0 / 2021-08-24 + +4.0.0-rc0 / 2021-08-19 +====================== + * BREAKING CHANGE: drop support for Node < 12 #123 + * BREAKING CHANGE: upgrade to mongodb driver 4.x: drop support for `findAndModify()`, use native `findOneAndUpdate/Delete` #124 + * BREAKING CHANGE: rename findStream -> findCursor #124 + * BREAKING CHANGE: use native ES6 promises by default, remove bluebird dependency #123 + +3.2.5 / 2021-03-29 +================== + * fix(utils): make `mergeClone()` skip special properties like `__proto__` #121 [zpbrent](https://github.com/zpbrent) + +3.2.4 / 2021-02-12 +================== + * fix(utils): make clone() only copy own properties Automattic/mongoose#9876 + +3.2.3 / 2020-12-10 +================== + * fix(utils): avoid copying special properties like `__proto__` when merging and cloning. Fix CVE-2020-35149 + +3.2.2 / 2019-09-22 +================== + * fix: dont re-call setOptions() when pulling base class options Automattic/mongoose#8159 + +3.2.1 / 2018-08-24 +================== + * chore: upgrade deps + +3.2.0 / 2018-08-24 +================== + * feat: add $useProjection to opt in to using `projection` instead of `fields` re: MongoDB deprecation warnings Automattic/mongoose#6880 + +3.1.2 / 2018-08-01 +================== + * chore: move eslint to devDependencies #110 [jakesjews](https://github.com/jakesjews) + +3.1.1 / 2018-07-30 +================== + * chore: add eslint #107 [Fonger](https://github.com/Fonger) + * docs: clean up readConcern docs #106 [Fonger](https://github.com/Fonger) + +3.1.0 / 2018-07-29 +================== + * feat: add `readConcern()` helper #105 [Fonger](https://github.com/Fonger) + * feat: add `maxTimeMS()` as alias of `maxTime()` #105 [Fonger](https://github.com/Fonger) + * feat: add `collation()` helper #105 [Fonger](https://github.com/Fonger) + +3.0.1 / 2018-07-02 +================== + * fix: parse sort array options correctly #103 #102 [Fonger](https://github.com/Fonger) + +3.0.0 / 2018-01-20 +================== + * chore: upgrade deps and add nsp + +3.0.0-rc0 / 2017-12-06 +====================== + * BREAKING CHANGE: remove support for node < 4 + * BREAKING CHANGE: remove support for retainKeyOrder, will always be true by default re: Automattic/mongoose#2749 + +2.3.3 / 2017-11-19 +================== + * fixed; catch sync errors in cursor.toArray() re: Automattic/mongoose#5812 + +2.3.2 / 2017-09-27 +================== + * fixed; bumped debug -> 2.6.9 re: #89 + +2.3.1 / 2017-05-22 +================== + * fixed; bumped debug -> 2.6.7 re: #86 + +2.3.0 / 2017-03-05 +================== + * added; replaceOne function + * added; deleteOne and deleteMany functions + +2.2.3 / 2017-01-31 +================== + * fixed; throw correct error when passing incorrectly formatted array to sort() + +2.2.2 / 2017-01-31 +================== + * fixed; allow passing maps to sort() + +2.2.1 / 2017-01-29 +================== + * fixed; allow passing string to hint() + +2.2.0 / 2017-01-08 +================== + * added; updateOne and updateMany functions + +2.1.0 / 2016-12-22 +================== + * added; ability to pass an array to select() #81 [dciccale](https://github.com/dciccale) + +2.0.0 / 2016-09-25 +================== + * added; support for mongodb driver 2.0 streams + +1.12.0 / 2016-09-25 +=================== + * added; `retainKeyOrder` option re: Automattic/mongoose#4542 + +1.11.0 / 2016-06-04 +=================== + * added; `.minDistance()` helper and minDistance for `.near()` Automattic/mongoose#4179 + +1.10.1 / 2016-04-26 +=================== + * fixed; ensure conditions is an object before assigning #75 + +1.10.0 / 2016-03-16 +================== + + * updated; bluebird to latest 2.10.2 version #74 [matskiv](https://github.com/matskiv) + +1.9.0 / 2016-03-15 +================== + * added; `.eq` as a shortcut for `.equals` #72 [Fonger](https://github.com/Fonger) + * added; ability to use array syntax for sort re: https://jira.mongodb.org/browse/NODE-578 #67 + +1.8.0 / 2016-03-01 +================== + * fixed; dont throw an error if count used with sort or select Automattic/mongoose#3914 + +1.7.0 / 2016-02-23 +================== + * fixed; don't treat objects with a length property as argument objects #70 + * added; `.findCursor()` method #69 [nswbmw](https://github.com/nswbmw) + * added; `_compiledUpdate` property #68 [nswbmw](https://github.com/nswbmw) + +1.6.2 / 2015-07-12 +================== + + * fixed; support exec cb being called synchronously #66 + +1.6.1 / 2015-06-16 +================== + + * fixed; do not treat $meta projection as inclusive [vkarpov15](https://github.com/vkarpov15) + +1.6.0 / 2015-05-27 +================== + + * update dependencies #65 [bachp](https://github.com/bachp) + +1.5.0 / 2015-03-31 +================== + + * fixed; debug output + * fixed; allow hint usage with count #61 [trueinsider](https://github.com/trueinsider) + +1.4.0 / 2015-03-29 +================== + + * added; object support to slice() #60 [vkarpov15](https://github.com/vkarpov15) + * debug; improved output #57 [flyvictor](https://github.com/flyvictor) + +1.3.0 / 2014-11-06 +================== + + * added; setTraceFunction() #53 from [jlai](https://github.com/jlai) + +1.2.1 / 2014-09-26 +================== + + * fixed; distinct assignment in toConstructor() #51 from [esco](https://github.com/esco) + +1.2.0 / 2014-09-18 +================== + + * added; stream() support for find() + +1.1.0 / 2014-09-15 +================== + + * add #then for co / koa support + * start checking code coverage + +1.0.0 / 2014-07-07 +================== + + * Remove broken require() calls until they're actually implemented #48 [vkarpov15](https://github.com/vkarpov15) + +0.9.0 / 2014-05-22 +================== + + * added; thunk() support + * release 0.8.0 + +0.8.0 / 2014-05-15 +================== + + * added; support for maxTimeMS #44 [yoitsro](https://github.com/yoitsro) + * updated; devDependency (driver to 1.4.4) + +0.7.0 / 2014-05-02 +================== + + * fixed; pass $maxDistance in $near object as described in docs #43 [vkarpov15](https://github.com/vkarpov15) + * fixed; cloning buffers #42 [gjohnson](https://github.com/gjohnson) + * tests; a little bit more `mongodb` agnostic #34 [refack](https://github.com/refack) + +0.6.0 / 2014-04-01 +================== + + * fixed; Allow $meta args in sort() so text search sorting works #37 [vkarpov15](https://github.com/vkarpov15) + +0.5.3 / 2014-02-22 +================== + + * fixed; cloning mongodb.Binary + +0.5.2 / 2014-01-30 +================== + + * fixed; cloning ObjectId constructors + * fixed; cloning of ReadPreferences #30 [ashtuchkin](https://github.com/ashtuchkin) + * tests; use specific mongodb version #29 [AvianFlu](https://github.com/AvianFlu) + * tests; remove dependency on ObjectId #28 [refack](https://github.com/refack) + * tests; add failing ReadPref test + +0.5.1 / 2014-01-17 +================== + + * added; deprecation notice to tags parameter #27 [ashtuchkin](https://github.com/ashtuchkin) + * readme; add links + +0.5.0 / 2014-01-16 +================== + + * removed; mongodb driver dependency #26 [ashtuchkin](https://github.com/ashtuchkin) + * removed; first class support of read preference tags #26 (still supported though) [ashtuchkin](https://github.com/ashtuchkin) + * added; better ObjectId clone support + * fixed; cloning objects that have no constructor #21 + * docs; cleaned up [ashtuchkin](https://github.com/ashtuchkin) + +0.4.2 / 2014-01-08 +================== + + * updated; debug module 0.7.4 [refack](https://github.com/refack) + +0.4.1 / 2014-01-07 +================== + + * fixed; inclusive/exclusive logic + +0.4.0 / 2014-01-06 +================== + + * added; selected() + * added; selectedInclusively() + * added; selectedExclusively() + +0.3.3 / 2013-11-14 +================== + + * Fix Mongo DB Dependency #20 [rschmukler](https://github.com/rschmukler) + +0.3.2 / 2013-09-06 +================== + + * added; geometry support for near() + +0.3.1 / 2013-08-22 +================== + + * fixed; update retains key order #19 + +0.3.0 / 2013-08-22 +================== + + * less hardcoded isNode env detection #18 [vshulyak](https://github.com/vshulyak) + * added; validation of findAndModify varients + * clone update doc before execution + * stricter env checks + +0.2.7 / 2013-08-2 +================== + + * Now support GeoJSON point values for Query#near + +0.2.6 / 2013-07-30 +================== + + * internally, 'asc' and 'desc' for sorts are now converted into 1 and -1, respectively + +0.2.5 / 2013-07-30 +================== + + * updated docs + * changed internal representation of `sort` to use objects instead of arrays + +0.2.4 / 2013-07-25 +================== + + * updated; sliced to 0.0.5 + +0.2.3 / 2013-07-09 +================== + + * now using a callback in collection.find instead of directly calling toArray() on the cursor [ebensing](https://github.com/ebensing) + +0.2.2 / 2013-07-09 +================== + + * now exposing mongodb export to allow for better testing [ebensing](https://github.com/ebensing) + +0.2.1 / 2013-07-08 +================== + + * select no longer accepts arrays as parameters [ebensing](https://github.com/ebensing) + +0.2.0 / 2013-07-05 +================== + + * use $geoWithin by default + +0.1.2 / 2013-07-02 +================== + + * added use$geoWithin flag [ebensing](https://github.com/ebensing) + * fix read preferences typo [ebensing](https://github.com/ebensing) + * fix reference to old param name in exists() [ebensing](https://github.com/ebensing) + +0.1.1 / 2013-06-24 +================== + + * fixed; $intersects -> $geoIntersects #14 [ebensing](https://github.com/ebensing) + * fixed; Retain key order when copying objects #15 [ebensing](https://github.com/ebensing) + * bump mongodb dev dep + +0.1.0 / 2013-05-06 +================== + + * findAndModify; return the query + * move mquery.proto.canMerge to mquery.canMerge + * overwrite option now works with non-empty objects + * use strict mode + * validate count options + * validate distinct options + * add aggregate to base collection methods + * clone merge arguments + * clone merged update arguments + * move subclass to mquery.prototype.toConstructor + * fixed; maxScan casing + * use regexp-clone + * added; geometry/intersects support + * support $and + * near: do not use "radius" + * callbacks always fire on next turn of loop + * defined collection interface + * remove time from tests + * clarify goals + * updated docs; + +0.0.1 / 2012-12-15 +================== + + * initial release diff --git a/node_modules/mquery/LICENSE b/node_modules/mquery/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/node_modules/mquery/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mquery/Makefile b/node_modules/mquery/Makefile new file mode 100644 index 0000000..587655d --- /dev/null +++ b/node_modules/mquery/Makefile @@ -0,0 +1,26 @@ + +test: + @NODE_ENV=test ./node_modules/.bin/mocha $(T) $(TESTS) + +test-cov: + @NODE_ENV=test node \ + node_modules/.bin/istanbul cover \ + ./node_modules/.bin/_mocha \ + -- -u exports \ + +open-cov: + open coverage/lcov-report/index.html + +lint: + @NODE_ENV=test node ./node_modules/eslint/bin/eslint.js . + +test-travis: + @NODE_ENV=test node \ + node_modules/.bin/istanbul cover \ + ./node_modules/.bin/_mocha \ + --report lcovonly \ + --bail + @NODE_ENV=test node \ + ./node_modules/eslint/bin/eslint.js . + +.PHONY: test test-cov open-cov lint test-travis diff --git a/node_modules/mquery/README.md b/node_modules/mquery/README.md new file mode 100644 index 0000000..8e21369 --- /dev/null +++ b/node_modules/mquery/README.md @@ -0,0 +1,1373 @@ +# mquery + +`mquery` is a fluent mongodb query builder designed to run in multiple environments. + +[![Build Status](https://travis-ci.org/aheckmann/mquery.svg?branch=master)](https://travis-ci.org/aheckmann/mquery) +[![NPM version](https://badge.fury.io/js/mquery.svg)](http://badge.fury.io/js/mquery) + +[![npm](https://nodei.co/npm/mquery.png)](https://www.npmjs.com/package/mquery) + +## Features + + - fluent query builder api + - custom base query support + - MongoDB 2.4 geoJSON support + - method + option combinations validation + - node.js driver compatibility + - environment detection + - [debug](https://github.com/visionmedia/debug) support + - separated collection implementations for maximum flexibility + +## Use + +```js +require('mongodb').connect(uri, function (err, db) { + if (err) return handleError(err); + + // get a collection + var collection = db.collection('artists'); + + // pass it to the constructor + mquery(collection).find({..}, callback); + + // or pass it to the collection method + mquery().find({..}).collection(collection).exec(callback) + + // or better yet, create a custom query constructor that has it always set + var Artist = mquery(collection).toConstructor(); + Artist().find(..).where(..).exec(callback) +}) +``` + +`mquery` requires a collection object to work with. In the example above we just pass the collection object created using the official [MongoDB driver](https://github.com/mongodb/node-mongodb-native). + + +## Fluent API + +- [find](#find) +- [findOne](#findOne) +- [count](#count) +- [remove](#remove) +- [update](#update) +- [findOneAndUpdate](#findoneandupdate) +- [findOneAndDelete, findOneAndRemove](#findoneandremove) +- [distinct](#distinct) +- [exec](#exec) +- [stream](#stream) +- [all](#all) +- [and](#and) +- [box](#box) +- [circle](#circle) +- [elemMatch](#elemmatch) +- [equals](#equals) +- [exists](#exists) +- [geometry](#geometry) +- [gt](#gt) +- [gte](#gte) +- [in](#in) +- [intersects](#intersects) +- [lt](#lt) +- [lte](#lte) +- [maxDistance](#maxdistance) +- [mod](#mod) +- [ne](#ne) +- [nin](#nin) +- [nor](#nor) +- [near](#near) +- [or](#or) +- [polygon](#polygon) +- [regex](#regex) +- [select](#select) +- [selected](#selected) +- [selectedInclusively](#selectedinclusively) +- [selectedExclusively](#selectedexclusively) +- [size](#size) +- [slice](#slice) +- [within](#within) +- [where](#where) +- [$where](#where-1) +- [batchSize](#batchsize) +- [collation](#collation) +- [comment](#comment) +- [hint](#hint) +- [j](#j) +- [limit](#limit) +- [maxScan](#maxscan) +- [maxTime, maxTimeMS](#maxtime) +- [skip](#skip) +- [sort](#sort) +- [read, setReadPreference](#read) +- [readConcern, r](#readconcern) +- [slaveOk](#slaveok) +- [snapshot](#snapshot) +- [tailable](#tailable) +- [writeConcern, w](#writeconcern) +- [wtimeout, wTimeout](#wtimeout) + +## Helpers + +- [collection](#collection) +- [then](#then) +- [thunk](#thunk) +- [merge](#mergeobject) +- [setOptions](#setoptionsoptions) +- [setTraceFunction](#settracefunctionfunc) +- [mquery.setGlobalTraceFunction](#mquerysetglobaltracefunctionfunc) +- [mquery.canMerge](#mquerycanmerge) +- [mquery.use$geoWithin](#mqueryusegeowithin) + +### find() + +Declares this query a _find_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().find() +mquery().find(match) +mquery().find(callback) +mquery().find(match, function (err, docs) { + assert(Array.isArray(docs)); +}) +``` + +### findOne() + +Declares this query a _findOne_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().findOne() +mquery().findOne(match) +mquery().findOne(callback) +mquery().findOne(match, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) +``` + +### count() + +Declares this query a _count_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().count() +mquery().count(match) +mquery().count(callback) +mquery().count(match, function (err, number){ + console.log('we found %d matching documents', number); +}) +``` + +### remove() + +Declares this query a _remove_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().remove() +mquery().remove(match) +mquery().remove(callback) +mquery().remove(match, function (err){}) +``` + +### update() + +Declares this query an _update_ query. Optionally pass an update document, match clause, options or callback. If a callback is passed, the query is executed. To force execution without passing a callback, run `update(true)`. + +```js +mquery().update() +mquery().update(match, updateDocument) +mquery().update(match, updateDocument, options) + +// the following all execute the command +mquery().update(callback) +mquery().update({$set: updateDocument, callback) +mquery().update(match, updateDocument, callback) +mquery().update(match, updateDocument, options, function (err, result){}) +mquery().update(true) // executes (unsafe write) +``` + +##### the update document + +All paths passed that are not `$atomic` operations will become `$set` ops. For example: + +```js +mquery(collection).where({ _id: id }).update({ title: 'words' }, callback) +``` + +becomes + +```js +collection.update({ _id: id }, { $set: { title: 'words' }}, callback) +``` + +This behavior can be overridden using the `overwrite` option (see below). + +##### options + +Options are passed to the `setOptions()` method. + +- overwrite + +Passing an empty object `{ }` as the update document will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option, the update operation will be ignored and the callback executed without sending the command to MongoDB to prevent accidently overwritting documents in the collection. + +```js +var q = mquery(collection).where({ _id: id }).setOptions({ overwrite: true }); +q.update({ }, callback); // overwrite with an empty doc +``` + +The `overwrite` option isn't just for empty objects, it also provides a means to override the default `$set` conversion and send the update document as is. + +```js +// create a base query +var base = mquery({ _id: 108 }).collection(collection).toConstructor(); + +base().findOne(function (err, doc) { + console.log(doc); // { _id: 108, name: 'cajon' }) + + base().setOptions({ overwrite: true }).update({ changed: true }, function (err) { + base.findOne(function (err, doc) { + console.log(doc); // { _id: 108, changed: true }) - the doc was overwritten + }); + }); +}) +``` + +- multi + +Updates only modify a single document by default. To update multiple documents, set the `multi` option to `true`. + +```js +mquery() + .collection(coll) + .update({ name: /^match/ }, { $addToSet: { arr: 4 }}, { multi: true }, callback) + +// another way of doing it +mquery({ name: /^match/ }) + .collection(coll) + .setOptions({ multi: true }) + .update({ $addToSet: { arr: 4 }}, callback) + +// update multiple documents with an empty doc +var q = mquery(collection).where({ name: /^match/ }); +q.setOptions({ multi: true, overwrite: true }) +q.update({ }); +q.update(function (err, result) { + console.log(arguments); +}); +``` + +### findOneAndUpdate() + +Declares this query a _findAndModify_ with update query. Optionally pass a match clause, update document, options, or callback. If a callback is passed, the query is executed. + +When executed, the first matching document (if found) is modified according to the update document and passed back to the callback. + +##### options + +Options are passed to the `setOptions()` method. + +- `returnDocument`: string - `'after'` to return the modified document rather than the original. defaults to `'before'` +- `upsert`: boolean - creates the object if it doesn't exist. defaults to false +- `sort`: if multiple docs are found by the match condition, sets the sort order to choose which doc to update + +```js +query.findOneAndUpdate() +query.findOneAndUpdate(updateDocument) +query.findOneAndUpdate(match, updateDocument) +query.findOneAndUpdate(match, updateDocument, options) + +// the following all execute the command +query.findOneAndUpdate(callback) +query.findOneAndUpdate(updateDocument, callback) +query.findOneAndUpdate(match, updateDocument, callback) +query.findOneAndUpdate(match, updateDocument, options, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) + ``` + +### findOneAndRemove() + +Declares this query a _findAndModify_ with remove query. Alias of findOneAndDelete. +Optionally pass a match clause, options, or callback. If a callback is passed, the query is executed. + +When executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed to the callback. + +##### options + +Options are passed to the `setOptions()` method. + +- `sort`: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove + +```js +A.where().findOneAndDelete() +A.where().findOneAndRemove() +A.where().findOneAndRemove(match) +A.where().findOneAndRemove(match, options) + +// the following all execute the command +A.where().findOneAndRemove(callback) +A.where().findOneAndRemove(match, callback) +A.where().findOneAndRemove(match, options, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) + ``` + +### distinct() + +Declares this query a _distinct_ query. Optionally pass the distinct field, a match clause or callback. If a callback is passed the query is executed. + +```js +mquery().distinct() +mquery().distinct(match) +mquery().distinct(match, field) +mquery().distinct(field) + +// the following all execute the command +mquery().distinct(callback) +mquery().distinct(field, callback) +mquery().distinct(match, callback) +mquery().distinct(match, field, function (err, result) { + console.log(result); +}) +``` + +### exec() + +Executes the query. + +```js +mquery().findOne().where('route').intersects(polygon).exec(function (err, docs){}) +``` + +### stream() + +Executes the query and returns a stream. + +```js +var stream = mquery().find().stream(options); +stream.on('data', cb); +stream.on('close', fn); +``` + +Note: this only works with `find()` operations. + +Note: returns the stream object directly from the node-mongodb-native driver. (currently streams1 type stream). Any options will be passed along to the [driver method](http://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#stream). + +------------- + +### all() + +Specifies an `$all` query condition + +```js +mquery().where('permission').all(['read', 'write']) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/all/) + +### and() + +Specifies arguments for an `$and` condition + +```js +mquery().and([{ color: 'green' }, { status: 'ok' }]) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/and/) + +### box() + +Specifies a `$box` condition + +```js +var lowerLeft = [40.73083, -73.99756] +var upperRight= [40.741404, -73.988135] + +mquery().where('location').within().box(lowerLeft, upperRight) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/box/) + +### circle() + +Specifies a `$center` or `$centerSphere` condition. + +```js +var area = { center: [50, 50], radius: 10, unique: true } +query.where('loc').within().circle(area) +query.circle('loc', area); + +// for spherical calculations +var area = { center: [50, 50], radius: 10, unique: true, spherical: true } +query.where('loc').within().circle(area) +query.circle('loc', area); +``` + +- [MongoDB Documentation - center](http://docs.mongodb.org/manual/reference/operator/center/) +- [MongoDB Documentation - centerSphere](http://docs.mongodb.org/manual/reference/operator/centerSphere/) + +### elemMatch() + +Specifies an `$elemMatch` condition + +```js +query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + +query.elemMatch('comment', function (elem) { + elem.where('author').equals('autobot'); + elem.where('votes').gte(5); +}) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/elemMatch/) + +### equals() + +Specifies the complementary comparison value for the path specified with `where()`. + +```js +mquery().where('age').equals(49); + +// is the same as + +mquery().where({ 'age': 49 }); +``` + +### exists() + +Specifies an `$exists` condition + +```js +// { name: { $exists: true }} +mquery().where('name').exists() +mquery().where('name').exists(true) +mquery().exists('name') + +// { name: { $exists: false }} +mquery().where('name').exists(false); +mquery().exists('name', false); +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/exists/) + +### geometry() + +Specifies a `$geometry` condition + +```js +var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] +query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + +// or +var polyB = [[ 0, 0 ], [ 1, 1 ]] +query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + +// or +var polyC = [ 0, 0 ] +query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + +// or +query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + +// or +query.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] }) +``` + +`geometry()` **must** come after `intersects()`, `within()`, or `near()`. + +The `object` argument must contain `type` and `coordinates` properties. + +- type `String` +- coordinates `Array` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geometry/) + +### gt() + +Specifies a `$gt` query condition. + +```js +mquery().where('clicks').gt(999) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gt/) + +### gte() + +Specifies a `$gte` query condition. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gte/) + +```js +mquery().where('clicks').gte(1000) +``` + +### in() + +Specifies an `$in` query condition. + +```js +mquery().where('author_id').in([3, 48901, 761]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/in/) + +### intersects() + +Declares an `$geoIntersects` query for `geometry()`. + +```js +query.where('path').intersects().geometry({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}) + +// geometry arguments are supported +query.where('path').intersects({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}) +``` + +**Must** be used after `where()`. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoIntersects/) + +### lt() + +Specifies a `$lt` query condition. + +```js +mquery().where('clicks').lt(50) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lt/) + +### lte() + +Specifies a `$lte` query condition. + +```js +mquery().where('clicks').lte(49) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lte/) + +### maxDistance() + +Specifies a `$maxDistance` query condition. + +```js +mquery().where('location').near({ center: [139, 74.3] }).maxDistance(5) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/maxDistance/) + +### mod() + +Specifies a `$mod` condition + +```js +mquery().where('count').mod(2, 0) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/mod/) + +### ne() + +Specifies a `$ne` query condition. + +```js +mquery().where('status').ne('ok') +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/ne/) + +### nin() + +Specifies an `$nin` query condition. + +```js +mquery().where('author_id').nin([3, 48901, 761]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nin/) + +### nor() + +Specifies arguments for an `$nor` condition. + +```js +mquery().nor([{ color: 'green' }, { status: 'ok' }]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nor/) + +### near() + +Specifies arguments for a `$near` or `$nearSphere` condition. + +These operators return documents sorted by distance. + +#### Example + +```js +query.where('loc').near({ center: [10, 10] }); +query.where('loc').near({ center: [10, 10], maxDistance: 5 }); +query.near('loc', { center: [10, 10], maxDistance: 5 }); + +// GeoJSON +query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }}); +query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true }); +query.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] }); + +// For a $nearSphere condition, pass the `spherical` option. +query.near({ center: [10, 10], maxDistance: 5, spherical: true }); +``` + +[MongoDB Documentation](http://www.mongodb.org/display/DOCS/Geospatial+Indexing) + +### or() + +Specifies arguments for an `$or` condition. + +```js +mquery().or([{ color: 'red' }, { status: 'emergency' }]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/or/) + +### polygon() + +Specifies a `$polygon` condition + +```js +mquery().where('loc').within().polygon([10,20], [13, 25], [7,15]) +mquery().polygon('loc', [10,20], [13, 25], [7,15]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/polygon/) + +### regex() + +Specifies a `$regex` query condition. + +```js +mquery().where('name').regex(/^sixstepsrecords/) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/regex/) + +### select() + +Specifies which document fields to include or exclude + +```js +// 1 means include, 0 means exclude +mquery().select({ name: 1, address: 1, _id: 0 }) + +// or + +mquery().select('name address -_id') +``` + +##### String syntax + +When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. + +```js +// include a and b, exclude c +query.select('a b -c'); + +// or you may use object notation, useful when +// you have keys already prefixed with a "-" +query.select({a: 1, b: 1, c: 0}); +``` + +_Cannot be used with `distinct()`._ + +### selected() + +Determines if the query has selected any fields. + +```js +var query = mquery(); +query.selected() // false +query.select('-name'); +query.selected() // true +``` + +### selectedInclusively() + +Determines if the query has selected any fields inclusively. + +```js +var query = mquery().select('name'); +query.selectedInclusively() // true + +var query = mquery(); +query.selected() // false +query.select('-name'); +query.selectedInclusively() // false +query.selectedExclusively() // true +``` + +### selectedExclusively() + +Determines if the query has selected any fields exclusively. + +```js +var query = mquery().select('-name'); +query.selectedExclusively() // true + +var query = mquery(); +query.selected() // false +query.select('name'); +query.selectedExclusively() // false +query.selectedInclusively() // true +``` + +### size() + +Specifies a `$size` query condition. + +```js +mquery().where('someArray').size(6) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/size/) + +### slice() + +Specifies a `$slice` projection for a `path` + +```js +mquery().where('comments').slice(5) +mquery().where('comments').slice(-5) +mquery().where('comments').slice([-10, 5]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/projection/slice/) + +### within() + +Sets a `$geoWithin` or `$within` argument for geo-spatial queries. + +```js +mquery().within().box() +mquery().within().circle() +mquery().within().geometry() + +mquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); +mquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); +mquery().where('loc').within({ polygon: [[],[],[],[]] }); + +mquery().where('loc').within([], [], []) // polygon +mquery().where('loc').within([], []) // box +mquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry +``` + +As of mquery 2.0, `$geoWithin` is used by default. This impacts you if running MongoDB < 2.4. To alter this behavior, see [mquery.use$geoWithin](#mqueryusegeowithin). + +**Must** be used after `where()`. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoWithin/) + +### where() + +Specifies a `path` for use with chaining + +```js +// instead of writing: +mquery().find({age: {$gte: 21, $lte: 65}}); + +// we can instead write: +mquery().where('age').gte(21).lte(65); + +// passing query conditions is permitted too +mquery().find().where({ name: 'vonderful' }) + +// chaining +mquery() +.where('age').gte(21).lte(65) +.where({ 'name': /^vonderful/i }) +.where('friends').slice(10) +.exec(callback) +``` + +### $where() + +Specifies a `$where` condition. + +Use `$where` when you need to select documents using a JavaScript expression. + +```js +query.$where('this.comments.length > 10 || this.name.length > 5').exec(callback) + +query.$where(function () { + return this.comments.length > 10 || this.name.length > 5; +}) +``` + +Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using. + +----------- + +### batchSize() + +Specifies the batchSize option. + +```js +query.batchSize(100) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.batchSize/) + +### collation() + +Specifies the collation option. + +```js +query.collation({ locale: "en_US", strength: 1 }) +``` + +[MongoDB documentation](https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation) + +### comment() + +Specifies the comment option. + +```js +query.comment('login query'); +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/) + +### hint() + +Sets query hints. + +```js +mquery().hint({ indexA: 1, indexB: -1 }) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/hint/) + +### j() + +Requests acknowledgement that this operation has been persisted to MongoDB's on-disk journal. + +This option is only valid for operations that write to the database: + +- `deleteOne()` +- `deleteMany()` +- `findOneAndDelete()` +- `findOneAndUpdate()` +- `remove()` +- `update()` +- `updateOne()` +- `updateMany()` + +Defaults to the `j` value if it is specified in [writeConcern](#writeconcern) + +```js +mquery().j(true); +``` + +### limit() + +Specifies the limit option. + +```js +query.limit(20) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.limit/) + +### maxScan() + +Specifies the maxScan option. + +```js +query.maxScan(100) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/maxScan/) + +### maxTime() + +Specifies the maxTimeMS option. + +```js +query.maxTime(100) +query.maxTimeMS(100) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.maxTimeMS/) + + +### skip() + +Specifies the skip option. + +```js +query.skip(100).limit(20) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.skip/) + +### sort() + +Sets the query sort order. + +If an object is passed, key values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + +If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + +```js +// these are equivalent +query.sort({ field: 'asc', test: -1 }); +query.sort('field -test'); +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.sort/) + +### read() + +Sets the readPreference option for the query. + +```js +mquery().read('primary') +mquery().read('p') // same as primary + +mquery().read('primaryPreferred') +mquery().read('pp') // same as primaryPreferred + +mquery().read('secondary') +mquery().read('s') // same as secondary + +mquery().read('secondaryPreferred') +mquery().read('sp') // same as secondaryPreferred + +mquery().read('nearest') +mquery().read('n') // same as nearest + +mquery().setReadPreference('primary') // alias of .read() +``` + +##### Preferences: + +- `primary` - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. +- `secondary` - Read from secondary if available, otherwise error. +- `primaryPreferred` - Read from primary if available, otherwise a secondary. +- `secondaryPreferred` - Read from a secondary if available, otherwise read from the primary. +- `nearest` - All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + +Aliases + +- `p` primary +- `pp` primaryPreferred +- `s` secondary +- `sp` secondaryPreferred +- `n` nearest + +##### Preference Tags: + +To keep the separation of concerns between `mquery` and your driver +clean, `mquery#read()` no longer handles specifying a second `tags` argument as of version 0.5. +If you need to specify tags, pass any non-string argument as the first argument. +`mquery` will pass this argument untouched to your collections methods later. +For example: + +```js +// example of specifying tags using the Node.js driver +var ReadPref = require('mongodb').ReadPreference; +var preference = new ReadPref('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]); +mquery(..).read(preference).exec(); +``` + +Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + + +### readConcern() + +Sets the readConcern option for the query. + +```js +// local +mquery().readConcern('local') +mquery().readConcern('l') +mquery().r('l') + +// available +mquery().readConcern('available') +mquery().readConcern('a') +mquery().r('a') + +// majority +mquery().readConcern('majority') +mquery().readConcern('m') +mquery().r('m') + +// linearizable +mquery().readConcern('linearizable') +mquery().readConcern('lz') +mquery().r('lz') + +// snapshot +mquery().readConcern('snapshot') +mquery().readConcern('s') +mquery().r('s') +``` + +##### Read Concern Level: + +- `local` - The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). (MongoDB 3.2+) +- `available` - The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). (MongoDB 3.6+) +- `majority` - The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. (MongoDB 3.2+) +- `linearizable` - The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. (MongoDB 3.4+) +- `snapshot` - Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. (MongoDB 4.0+) + +Aliases + +- `l` local +- `a` available +- `m` majority +- `lz` linearizable +- `s` snapshot + +Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). + +### writeConcern() + +Sets the writeConcern option for the query. + +This option is only valid for operations that write to the database: + +- `deleteOne()` +- `deleteMany()` +- `findOneAndDelete()` +- `findOneAndUpdate()` +- `remove()` +- `update()` +- `updateOne()` +- `updateMany()` + +```js +mquery().writeConcern(0) +mquery().writeConcern(1) +mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 }) +mquery().writeConcern('majority') +mquery().writeConcern('m') // same as majority +mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead +mquery().w(1) // w is alias of writeConcern +``` + +##### Write Concern: + +writeConcern({ w: ``, j: ``, wtimeout: `` }`) + +- the w option to request acknowledgement that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags +- the j option to request acknowledgement that the write operation has been written to the journal +- the wtimeout option to specify a time limit to prevent write operations from blocking indefinitely + +Can be break down to use the following syntax: + +mquery().w(``).j(``).wtimeout(``) + +Read more about how to use write concern [here](https://docs.mongodb.com/manual/reference/write-concern/) + +### slaveOk() + +Sets the slaveOk option. `true` allows reading from secondaries. + +**deprecated** use [read()](#read) preferences instead if on mongodb >= 2.2 + +```js +query.slaveOk() // true +query.slaveOk(true) +query.slaveOk(false) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/rs.slaveOk/) + +### snapshot() + +Specifies this query as a snapshot query. + +```js +mquery().snapshot() // true +mquery().snapshot(true) +mquery().snapshot(false) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/snapshot/) + +### tailable() + +Sets tailable option. + +```js +mquery().tailable() <== true +mquery().tailable(true) +mquery().tailable(false) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB Documentation](http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/) + +### wtimeout() + +Specifies a time limit, in milliseconds, for the write concern. If `w > 1`, it is maximum amount of time to +wait for this write to propagate through the replica set before this operation fails. The default is `0`, which means no timeout. + +This option is only valid for operations that write to the database: + +- `deleteOne()` +- `deleteMany()` +- `findOneAndDelete()` +- `findOneAndUpdate()` +- `remove()` +- `update()` +- `updateOne()` +- `updateMany()` + +Defaults to `wtimeout` value if it is specified in [writeConcern](#writeconcern) + +```js +mquery().wtimeout(2000) +mquery().wTimeout(2000) +``` + +## Helpers + +### collection() + +Sets the querys collection. + +```js +mquery().collection(aCollection) +``` + +### then() + +Executes the query and returns a promise which will be resolved with the query results or rejected if the query responds with an error. + +```js +mquery().find(..).then(success, error); +``` + +This is very useful when combined with [co](https://github.com/visionmedia/co) or [koa](https://github.com/koajs/koa), which automatically resolve promise-like objects for you. + +```js +co(function*(){ + var doc = yield mquery().findOne({ _id: 499 }); + console.log(doc); // { _id: 499, name: 'amazing', .. } +})(); +``` + +_NOTE_: +The returned promise is a [bluebird](https://github.com/petkaantonov/bluebird/) promise but this is customizable. If you want to +use your favorite promise library, simply set `mquery.Promise = YourPromiseConstructor`. +Your `Promise` must be [promises A+](http://promisesaplus.com/) compliant. + +### thunk() + +Returns a thunk which when called runs the query's `exec` method passing the results to the callback. + +```js +var thunk = mquery(collection).find({..}).thunk(); + +thunk(function(err, results) { + +}) +``` + +### merge(object) + +Merges other mquery or match condition objects into this one. When an mquery instance is passed, its match conditions, field selection and options are merged. + +```js +var drum = mquery({ type: 'drum' }).collection(instruments); +var redDrum = mquery({ color: 'red' }).merge(drum); +redDrum.count(function (err, n) { + console.log('there are %d red drums', n); +}) +``` + +Internally uses `mquery.canMerge` to determine validity. + +### setOptions(options) + +Sets query options. + +```js +mquery().setOptions({ collection: coll, limit: 20 }) +``` + +##### options + +- [tailable](#tailable) * +- [sort](#sort) * +- [limit](#limit) * +- [skip](#skip) * +- [maxScan](#maxscan) * +- [maxTime](#maxtime) * +- [batchSize](#batchSize) * +- [comment](#comment) * +- [snapshot](#snapshot) * +- [hint](#hint) * +- [collection](#collection): the collection to query against + +_* denotes a query helper method is also available_ + +### setTraceFunction(func) + +Set a function to trace this query. Useful for profiling or logging. + +```js +function traceFunction (method, queryInfo, query) { + console.log('starting ' + method + ' query'); + + return function (err, result, millis) { + console.log('finished ' + method + ' query in ' + millis + 'ms'); + }; +} + +mquery().setTraceFunction(traceFunction).findOne({name: 'Joe'}, cb); +``` + +The trace function is passed (method, queryInfo, query) + +- method is the name of the method being called (e.g. findOne) +- queryInfo contains information about the query: + - conditions: query conditions/criteria + - options: options such as sort, fields, etc + - doc: document being updated +- query is the query object + +The trace function should return a callback function which accepts: +- err: error, if any +- result: result, if any +- millis: time spent waiting for query result + +NOTE: stream requests are not traced. + +### mquery.setGlobalTraceFunction(func) + +Similar to `setTraceFunction()` but automatically applied to all queries. + +```js +mquery.setTraceFunction(traceFunction); +``` + +### mquery.canMerge(conditions) + +Determines if `conditions` can be merged using `mquery().merge()`. + +```js +var query = mquery({ type: 'drum' }); +var okToMerge = mquery.canMerge(anObject) +if (okToMerge) { + query.merge(anObject); +} +``` + +## mquery.use$geoWithin + +MongoDB 2.4 introduced the `$geoWithin` operator which replaces and is 100% backward compatible with `$within`. As of mquery 0.2, we default to using `$geoWithin` for all `within()` calls. + +If you are running MongoDB < 2.4 this will be problematic. To force `mquery` to be backward compatible and always use `$within`, set the `mquery.use$geoWithin` flag to `false`. + +```js +mquery.use$geoWithin = false; +``` + +## Custom Base Queries + +Often times we want custom base queries that encapsulate predefined criteria. With `mquery` this is easy. First create the query you want to reuse and call its `toConstructor()` method which returns a new subclass of `mquery` that retains all options and criteria of the original. + +```js +var greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor(); + +// use it! +greatMovies().count(function (err, n) { + console.log('There are %d great movies', n); +}); + +greatMovies().where({ name: /^Life/ }).select('name').find(function (err, docs) { + console.log(docs); +}); +``` + +## Validation + +Method and options combinations are checked for validity at runtime to prevent creation of invalid query constructs. For example, a `distinct` query does not support specifying options like `hint` or field selection. In this case an error will be thrown so you can catch these mistakes in development. + +## Debug support + +Debug mode is provided through the use of the [debug](https://github.com/visionmedia/debug) module. To enable: + + DEBUG=mquery node yourprogram.js + +Read the debug module documentation for more details. + +## General compatibility + +#### ObjectIds + +`mquery` clones query arguments before passing them to a `collection` method for execution. +This prevents accidental side-affects to the objects you pass. +To clone `ObjectIds` we need to make some assumptions. + +First, to check if an object is an `ObjectId`, we check its constructors name. If it matches either +`ObjectId` or `ObjectID` we clone it. + +To clone `ObjectIds`, we call its optional `clone` method. If a `clone` method does not exist, we fall +back to calling `new obj.constructor(obj.id)`. We assume, for compatibility with the +Node.js driver, that the `ObjectId` instance has a public `id` property and that +when creating an `ObjectId` instance we can pass that `id` as an argument. + +#### Read Preferences + +`mquery` supports specifying [Read Preferences]() to control from which MongoDB node your query will read. +The Read Preferences spec also support specifying tags. To pass tags, some +drivers (Node.js driver) require passing a special constructor that handles both the read preference and its tags. +If you need to specify tags, pass an instance of your drivers ReadPreference constructor or roll your own. `mquery` will store whatever you provide and pass later to your collection during execution. + +## Future goals + + - mongo shell compatibility + - browser compatibility + +## Installation + + $ npm install mquery + +## License + +[MIT](https://github.com/aheckmann/mquery/blob/master/LICENSE) + diff --git a/node_modules/mquery/SECURITY.md b/node_modules/mquery/SECURITY.md new file mode 100644 index 0000000..41b89d8 --- /dev/null +++ b/node_modules/mquery/SECURITY.md @@ -0,0 +1 @@ +Please follow the instructions on [Tidelift's security page](https://tidelift.com/docs/security) to report a security issue. diff --git a/node_modules/mquery/lib/collection/collection.js b/node_modules/mquery/lib/collection/collection.js new file mode 100644 index 0000000..28b6982 --- /dev/null +++ b/node_modules/mquery/lib/collection/collection.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * methods a collection must implement + */ + +const methods = [ + 'find', + 'findOne', + 'update', + 'updateMany', + 'updateOne', + 'replaceOne', + 'remove', + 'count', + 'distinct', + 'findOneAndDelete', + 'findOneAndUpdate', + 'aggregate', + 'findCursor', + 'deleteOne', + 'deleteMany' +]; + +/** + * Collection base class from which implementations inherit + */ + +function Collection() {} + +for (let i = 0, len = methods.length; i < len; ++i) { + const method = methods[i]; + Collection.prototype[method] = notImplemented(method); +} + +module.exports = exports = Collection; +Collection.methods = methods; + +/** + * creates a function which throws an implementation error + */ + +function notImplemented(method) { + return function() { + throw new Error('collection.' + method + ' not implemented'); + }; +} diff --git a/node_modules/mquery/lib/collection/index.js b/node_modules/mquery/lib/collection/index.js new file mode 100644 index 0000000..4faa032 --- /dev/null +++ b/node_modules/mquery/lib/collection/index.js @@ -0,0 +1,13 @@ +'use strict'; + +const env = require('../env'); + +if ('unknown' == env.type) { + throw new Error('Unknown environment'); +} + +module.exports = + env.isNode ? require('./node') : + env.isMongo ? require('./collection') : + require('./collection'); + diff --git a/node_modules/mquery/lib/collection/node.js b/node_modules/mquery/lib/collection/node.js new file mode 100644 index 0000000..7c6b6f8 --- /dev/null +++ b/node_modules/mquery/lib/collection/node.js @@ -0,0 +1,148 @@ +'use strict'; + +/** + * Module dependencies + */ + +const Collection = require('./collection'); +const utils = require('../utils'); + +function NodeCollection(col) { + this.collection = col; + this.collectionName = col.collectionName; +} + +/** + * inherit from collection base class + */ + +utils.inherits(NodeCollection, Collection); + +/** + * find(match, options, function(err, docs)) + */ + +NodeCollection.prototype.find = function(match, options, cb) { + const cursor = this.collection.find(match, options); + + try { + cursor.toArray(cb); + } catch (error) { + cb(error); + } +}; + +/** + * findOne(match, options, function(err, doc)) + */ + +NodeCollection.prototype.findOne = function(match, options, cb) { + this.collection.findOne(match, options, cb); +}; + +/** + * count(match, options, function(err, count)) + */ + +NodeCollection.prototype.count = function(match, options, cb) { + this.collection.count(match, options, cb); +}; + +/** + * distinct(prop, match, options, function(err, count)) + */ + +NodeCollection.prototype.distinct = function(prop, match, options, cb) { + this.collection.distinct(prop, match, options, cb); +}; + +/** + * update(match, update, options, function(err[, result])) + */ + +NodeCollection.prototype.update = function(match, update, options, cb) { + this.collection.update(match, update, options, cb); +}; + +/** + * update(match, update, options, function(err[, result])) + */ + +NodeCollection.prototype.updateMany = function(match, update, options, cb) { + this.collection.updateMany(match, update, options, cb); +}; + +/** + * update(match, update, options, function(err[, result])) + */ + +NodeCollection.prototype.updateOne = function(match, update, options, cb) { + this.collection.updateOne(match, update, options, cb); +}; + +/** + * replaceOne(match, update, options, function(err[, result])) + */ + +NodeCollection.prototype.replaceOne = function(match, update, options, cb) { + this.collection.replaceOne(match, update, options, cb); +}; + +/** + * deleteOne(match, options, function(err[, result]) + */ + +NodeCollection.prototype.deleteOne = function(match, options, cb) { + this.collection.deleteOne(match, options, cb); +}; + +/** + * deleteMany(match, options, function(err[, result]) + */ + +NodeCollection.prototype.deleteMany = function(match, options, cb) { + this.collection.deleteMany(match, options, cb); +}; + +/** + * remove(match, options, function(err[, result]) + */ + +NodeCollection.prototype.remove = function(match, options, cb) { + this.collection.remove(match, options, cb); +}; + +/** + * findOneAndDelete(match, options, function(err[, result]) + */ + +NodeCollection.prototype.findOneAndDelete = function(match, options, cb) { + this.collection.findOneAndDelete(match, options, cb); +}; + +/** + * findOneAndUpdate(match, update, options, function(err[, result]) + */ + +NodeCollection.prototype.findOneAndUpdate = function(match, update, options, cb) { + this.collection.findOneAndUpdate(match, update, options, cb); +}; + +/** + * var cursor = findCursor(match, options) + */ + +NodeCollection.prototype.findCursor = function(match, options) { + return this.collection.find(match, options); +}; + +/** + * aggregation(operators..., function(err, doc)) + * TODO + */ + +/** + * Expose + */ + +module.exports = exports = NodeCollection; diff --git a/node_modules/mquery/lib/env.js b/node_modules/mquery/lib/env.js new file mode 100644 index 0000000..d3d225b --- /dev/null +++ b/node_modules/mquery/lib/env.js @@ -0,0 +1,22 @@ +'use strict'; + +exports.isNode = 'undefined' != typeof process + && 'object' == typeof module + && 'object' == typeof global + && 'function' == typeof Buffer + && process.argv; + +exports.isMongo = !exports.isNode + && 'function' == typeof printjson + && 'function' == typeof ObjectId + && 'function' == typeof rs + && 'function' == typeof sh; + +exports.isBrowser = !exports.isNode + && !exports.isMongo + && 'undefined' != typeof window; + +exports.type = exports.isNode ? 'node' + : exports.isMongo ? 'mongo' + : exports.isBrowser ? 'browser' + : 'unknown'; diff --git a/node_modules/mquery/lib/mquery.js b/node_modules/mquery/lib/mquery.js new file mode 100644 index 0000000..628f3e1 --- /dev/null +++ b/node_modules/mquery/lib/mquery.js @@ -0,0 +1,3201 @@ +'use strict'; + +/** + * Dependencies + */ + +const slice = require('sliced'); +const assert = require('assert'); +const util = require('util'); +const utils = require('./utils'); +const debug = require('debug')('mquery'); + +/* global Map */ + +/** + * Query constructor used for building queries. + * + * ####Example: + * + * var query = new Query({ name: 'mquery' }); + * query.setOptions({ collection: moduleCollection }) + * query.where('age').gte(21).exec(callback); + * + * @param {Object} [criteria] + * @param {Object} [options] + * @api public + */ + +function Query(criteria, options) { + if (!(this instanceof Query)) + return new Query(criteria, options); + + const proto = this.constructor.prototype; + + this.op = proto.op || undefined; + + this.options = Object.assign({}, proto.options); + + this._conditions = proto._conditions + ? utils.clone(proto._conditions) + : {}; + + this._fields = proto._fields + ? utils.clone(proto._fields) + : undefined; + + this._update = proto._update + ? utils.clone(proto._update) + : undefined; + + this._path = proto._path || undefined; + this._distinct = proto._distinct || undefined; + this._collection = proto._collection || undefined; + this._traceFunction = proto._traceFunction || undefined; + + if (options) { + this.setOptions(options); + } + + if (criteria) { + if (criteria.find && criteria.remove && criteria.update) { + // quack quack! + this.collection(criteria); + } else { + this.find(criteria); + } + } +} + +/** + * This is a parameter that the user can set which determines if mquery + * uses $within or $geoWithin for queries. It defaults to true which + * means $geoWithin will be used. If using MongoDB < 2.4 you should + * set this to false. + * + * @api public + * @property use$geoWithin + */ + +let $withinCmd = '$geoWithin'; +Object.defineProperty(Query, 'use$geoWithin', { + get: function() { return $withinCmd == '$geoWithin'; }, + set: function(v) { + if (true === v) { + // mongodb >= 2.4 + $withinCmd = '$geoWithin'; + } else { + $withinCmd = '$within'; + } + } +}); + +/** + * Converts this query to a constructor function with all arguments and options retained. + * + * ####Example + * + * // Create a query that will read documents with a "video" category from + * // `aCollection` on the primary node in the replica-set unless it is down, + * // in which case we'll read from a secondary node. + * var query = mquery({ category: 'video' }) + * query.setOptions({ collection: aCollection, read: 'primaryPreferred' }); + * + * // create a constructor based off these settings + * var Video = query.toConstructor(); + * + * // Video is now a subclass of mquery() and works the same way but with the + * // default query parameters and options set. + * + * // run a query with the previous settings but filter for movies with names + * // that start with "Life". + * Video().where({ name: /^Life/ }).exec(cb); + * + * @return {Query} new Query + * @api public + */ + +Query.prototype.toConstructor = function toConstructor() { + function CustomQuery(criteria, options) { + if (!(this instanceof CustomQuery)) + return new CustomQuery(criteria, options); + Query.call(this, criteria, options); + } + + utils.inherits(CustomQuery, Query); + + // set inherited defaults + const p = CustomQuery.prototype; + + p.options = {}; + p.setOptions(this.options); + + p.op = this.op; + p._conditions = utils.clone(this._conditions); + p._fields = utils.clone(this._fields); + p._update = utils.clone(this._update); + p._path = this._path; + p._distinct = this._distinct; + p._collection = this._collection; + p._traceFunction = this._traceFunction; + + return CustomQuery; +}; + +/** + * Sets query options. + * + * ####Options: + * + * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * + * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * + * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * + * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * + * - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * + * - [maxTime](http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS) * + * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * + * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * + * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * + * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * + * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * + * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) + * - collection the collection to query against + * + * _* denotes a query helper method is also available_ + * + * @param {Object} options + * @api public + */ + +Query.prototype.setOptions = function(options) { + if (!(options && utils.isObject(options))) + return this; + + // set arbitrary options + const methods = utils.keys(options); + let method; + + for (let i = 0; i < methods.length; ++i) { + method = methods[i]; + + // use methods if exist (safer option manipulation) + if ('function' == typeof this[method]) { + const args = utils.isArray(options[method]) + ? options[method] + : [options[method]]; + this[method].apply(this, args); + } else { + this.options[method] = options[method]; + } + } + + return this; +}; + +/** + * Sets this Querys collection. + * + * @param {Collection} coll + * @return {Query} this + */ + +Query.prototype.collection = function collection(coll) { + this._collection = new Query.Collection(coll); + + return this; +}; + +/** + * Adds a collation to this op (MongoDB 3.4 and up) + * + * ####Example + * + * query.find().collation({ locale: "en_US", strength: 1 }) + * + * @param {Object} value + * @return {Query} this + * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation + * @api public + */ + +Query.prototype.collation = function(value) { + this.options.collation = value; + return this; +}; + +/** + * Specifies a `$where` condition + * + * Use `$where` when you need to select documents using a JavaScript expression. + * + * ####Example + * + * query.$where('this.comments.length > 10 || this.name.length > 5') + * + * query.$where(function () { + * return this.comments.length > 10 || this.name.length > 5; + * }) + * + * @param {String|Function} js javascript string or function + * @return {Query} this + * @memberOf Query + * @method $where + * @api public + */ + +Query.prototype.$where = function(js) { + this._conditions.$where = js; + return this; +}; + +/** + * Specifies a `path` for use with chaining. + * + * ####Example + * + * // instead of writing: + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * // we can instead write: + * User.where('age').gte(21).lte(65); + * + * // passing query conditions is permitted + * User.find().where({ name: 'vonderful' }) + * + * // chaining + * User + * .where('age').gte(21).lte(65) + * .where('name', /^vonderful/i) + * .where('friends').slice(10) + * .exec(callback) + * + * @param {String} [path] + * @param {Object} [val] + * @return {Query} this + * @api public + */ + +Query.prototype.where = function() { + if (!arguments.length) return this; + if (!this.op) this.op = 'find'; + + const type = typeof arguments[0]; + + if ('string' == type) { + this._path = arguments[0]; + + if (2 === arguments.length) { + this._conditions[this._path] = arguments[1]; + } + + return this; + } + + if ('object' == type && !Array.isArray(arguments[0])) { + return this.merge(arguments[0]); + } + + throw new TypeError('path must be a string or object'); +}; + +/** + * Specifies the complementary comparison value for paths specified with `where()` + * + * ####Example + * + * User.where('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @param {Object} val + * @return {Query} this + * @api public + */ + +Query.prototype.equals = function equals(val) { + this._ensurePath('equals'); + const path = this._path; + this._conditions[path] = val; + return this; +}; + +/** + * Specifies the complementary comparison value for paths specified with `where()` + * This is alias of `equals` + * + * ####Example + * + * User.where('age').eq(49); + * + * // is the same as + * + * User.shere('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @param {Object} val + * @return {Query} this + * @api public + */ + +Query.prototype.eq = function eq(val) { + this._ensurePath('eq'); + const path = this._path; + this._conditions[path] = val; + return this; +}; + +/** + * Specifies arguments for an `$or` condition. + * + * ####Example + * + * query.or([{ color: 'red' }, { status: 'emergency' }]) + * + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.or = function or(array) { + const or = this._conditions.$or || (this._conditions.$or = []); + if (!utils.isArray(array)) array = [array]; + or.push.apply(or, array); + return this; +}; + +/** + * Specifies arguments for a `$nor` condition. + * + * ####Example + * + * query.nor([{ color: 'green' }, { status: 'ok' }]) + * + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.nor = function nor(array) { + const nor = this._conditions.$nor || (this._conditions.$nor = []); + if (!utils.isArray(array)) array = [array]; + nor.push.apply(nor, array); + return this; +}; + +/** + * Specifies arguments for a `$and` condition. + * + * ####Example + * + * query.and([{ color: 'green' }, { status: 'ok' }]) + * + * @see $and http://docs.mongodb.org/manual/reference/operator/and/ + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.and = function and(array) { + const and = this._conditions.$and || (this._conditions.$and = []); + if (!Array.isArray(array)) array = [array]; + and.push.apply(and, array); + return this; +}; + +/** + * Specifies a $gt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * Thing.find().where('age').gt(21) + * + * // or + * Thing.find().gt('age', 21) + * + * @method gt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $gte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method gte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $lt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $lte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $ne query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method ne + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $in query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method in + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $nin query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method nin + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $all query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method all + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $size query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method size + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $regex query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method regex + * @memberOf Query + * @param {String} [path] + * @param {String|RegExp} val + * @api public + */ + +/** + * Specifies a $maxDistance query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method maxDistance + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/*! + * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance + * + * Thing.where('type').nin(array) + */ + +'gt gte lt lte ne in nin all regex size maxDistance minDistance'.split(' ').forEach(function($conditional) { + Query.prototype[$conditional] = function() { + let path, val; + + if (1 === arguments.length) { + this._ensurePath($conditional); + val = arguments[0]; + path = this._path; + } else { + val = arguments[1]; + path = arguments[0]; + } + + const conds = this._conditions[path] === null || typeof this._conditions[path] === 'object' ? + this._conditions[path] : + (this._conditions[path] = {}); + conds['$' + $conditional] = val; + return this; + }; +}); + +/** + * Specifies a `$mod` condition + * + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @api public + */ + +Query.prototype.mod = function() { + let val, path; + + if (1 === arguments.length) { + this._ensurePath('mod'); + val = arguments[0]; + path = this._path; + } else if (2 === arguments.length && !utils.isArray(arguments[1])) { + this._ensurePath('mod'); + val = slice(arguments); + path = this._path; + } else if (3 === arguments.length) { + val = slice(arguments, 1); + path = arguments[0]; + } else { + val = arguments[1]; + path = arguments[0]; + } + + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$mod = val; + return this; +}; + +/** + * Specifies an `$exists` condition + * + * ####Example + * + * // { name: { $exists: true }} + * Thing.where('name').exists() + * Thing.where('name').exists(true) + * Thing.find().exists('name') + * + * // { name: { $exists: false }} + * Thing.where('name').exists(false); + * Thing.find().exists('name', false); + * + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @api public + */ + +Query.prototype.exists = function() { + let path, val; + + if (0 === arguments.length) { + this._ensurePath('exists'); + path = this._path; + val = true; + } else if (1 === arguments.length) { + if ('boolean' === typeof arguments[0]) { + this._ensurePath('exists'); + path = this._path; + val = arguments[0]; + } else { + path = arguments[0]; + val = true; + } + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } + + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$exists = val; + return this; +}; + +/** + * Specifies an `$elemMatch` condition + * + * ####Example + * + * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) + * + * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + * + * query.elemMatch('comment', function (elem) { + * elem.where('author').equals('autobot'); + * elem.where('votes').gte(5); + * }) + * + * query.where('comment').elemMatch(function (elem) { + * elem.where({ author: 'autobot' }); + * elem.where('votes').gte(5); + * }) + * + * @param {String|Object|Function} path + * @param {Object|Function} criteria + * @return {Query} this + * @api public + */ + +Query.prototype.elemMatch = function() { + if (null == arguments[0]) + throw new TypeError('Invalid argument'); + + let fn, path, criteria; + + if ('function' === typeof arguments[0]) { + this._ensurePath('elemMatch'); + path = this._path; + fn = arguments[0]; + } else if (utils.isObject(arguments[0])) { + this._ensurePath('elemMatch'); + path = this._path; + criteria = arguments[0]; + } else if ('function' === typeof arguments[1]) { + path = arguments[0]; + fn = arguments[1]; + } else if (arguments[1] && utils.isObject(arguments[1])) { + path = arguments[0]; + criteria = arguments[1]; + } else { + throw new TypeError('Invalid argument'); + } + + if (fn) { + criteria = new Query; + fn(criteria); + criteria = criteria._conditions; + } + + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$elemMatch = criteria; + return this; +}; + +// Spatial queries + +/** + * Sugar for geo-spatial queries. + * + * ####Example + * + * query.within().box() + * query.within().circle() + * query.within().geometry() + * + * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); + * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); + * query.where('loc').within({ polygon: [[],[],[],[]] }); + * + * query.where('loc').within([], [], []) // polygon + * query.where('loc').within([], []) // box + * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry + * + * ####NOTE: + * + * Must be used after `where()`. + * + * @memberOf Query + * @return {Query} this + * @api public + */ + +Query.prototype.within = function within() { + // opinionated, must be used after where + this._ensurePath('within'); + this._geoComparison = $withinCmd; + + if (0 === arguments.length) { + return this; + } + + if (2 === arguments.length) { + return this.box.apply(this, arguments); + } else if (2 < arguments.length) { + return this.polygon.apply(this, arguments); + } + + const area = arguments[0]; + + if (!area) + throw new TypeError('Invalid argument'); + + if (area.center) + return this.circle(area); + + if (area.box) + return this.box.apply(this, area.box); + + if (area.polygon) + return this.polygon.apply(this, area.polygon); + + if (area.type && area.coordinates) + return this.geometry(area); + + throw new TypeError('Invalid argument'); +}; + +/** + * Specifies a $box condition + * + * ####Example + * + * var lowerLeft = [40.73083, -73.99756] + * var upperRight= [40.741404, -73.988135] + * + * query.where('loc').within().box(lowerLeft, upperRight) + * query.box('loc', lowerLeft, upperRight ) + * + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see Query#within #query_Query-within + * @param {String} path + * @param {Object} val + * @return {Query} this + * @api public + */ + +Query.prototype.box = function() { + let path, box; + + if (3 === arguments.length) { + // box('loc', [], []) + path = arguments[0]; + box = [arguments[1], arguments[2]]; + } else if (2 === arguments.length) { + // box([], []) + this._ensurePath('box'); + path = this._path; + box = [arguments[0], arguments[1]]; + } else { + throw new TypeError('Invalid argument'); + } + + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison || $withinCmd] = { $box: box }; + return this; +}; + +/** + * Specifies a $polygon condition + * + * ####Example + * + * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) + * query.polygon('loc', [10,20], [13, 25], [7,15]) + * + * @param {String|Array} [path] + * @param {Array|Object} [val] + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.polygon = function() { + let val, path; + + if ('string' == typeof arguments[0]) { + // polygon('loc', [],[],[]) + path = arguments[0]; + val = slice(arguments, 1); + } else { + // polygon([],[],[]) + this._ensurePath('polygon'); + path = this._path; + val = slice(arguments); + } + + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison || $withinCmd] = { $polygon: val }; + return this; +}; + +/** + * Specifies a $center or $centerSphere condition. + * + * ####Example + * + * var area = { center: [50, 50], radius: 10, unique: true } + * query.where('loc').within().circle(area) + * query.center('loc', area); + * + * // for spherical calculations + * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } + * query.where('loc').within().circle(area) + * query.center('loc', area); + * + * @param {String} [path] + * @param {Object} area + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.circle = function() { + let path, val; + + if (1 === arguments.length) { + this._ensurePath('circle'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } else { + throw new TypeError('Invalid argument'); + } + + if (!('radius' in val && val.center)) + throw new Error('center and radius are required'); + + const conds = this._conditions[path] || (this._conditions[path] = {}); + + const type = val.spherical + ? '$centerSphere' + : '$center'; + + const wKey = this._geoComparison || $withinCmd; + conds[wKey] = {}; + conds[wKey][type] = [val.center, val.radius]; + + if ('unique' in val) + conds[wKey].$uniqueDocs = !!val.unique; + + return this; +}; + +/** + * Specifies a `$near` or `$nearSphere` condition + * + * These operators return documents sorted by distance. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10] }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); + * query.near('loc', { center: [10, 10], maxDistance: 5 }); + * query.near({ center: { type: 'Point', coordinates: [..] }}) + * query.near().geometry({ type: 'Point', coordinates: [..] }) + * + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.near = function near() { + let path, val; + + this._geoComparison = '$near'; + + if (0 === arguments.length) { + return this; + } else if (1 === arguments.length) { + this._ensurePath('near'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } else { + throw new TypeError('Invalid argument'); + } + + if (!val.center) { + throw new Error('center is required'); + } + + const conds = this._conditions[path] || (this._conditions[path] = {}); + + const type = val.spherical + ? '$nearSphere' + : '$near'; + + // center could be a GeoJSON object or an Array + if (Array.isArray(val.center)) { + conds[type] = val.center; + + const radius = 'maxDistance' in val + ? val.maxDistance + : null; + + if (null != radius) { + conds.$maxDistance = radius; + } + if (null != val.minDistance) { + conds.$minDistance = val.minDistance; + } + } else { + // GeoJSON? + if (val.center.type != 'Point' || !Array.isArray(val.center.coordinates)) { + throw new Error(util.format('Invalid GeoJSON specified for %s', type)); + } + conds[type] = { $geometry: val.center }; + + // MongoDB 2.6 insists on maxDistance being in $near / $nearSphere + if ('maxDistance' in val) { + conds[type]['$maxDistance'] = val.maxDistance; + } + if ('minDistance' in val) { + conds[type]['$minDistance'] = val.minDistance; + } + } + + return this; +}; + +/** + * Declares an intersects query for `geometry()`. + * + * ####Example + * + * query.where('path').intersects().geometry({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * query.where('path').intersects({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * @param {Object} [arg] + * @return {Query} this + * @api public + */ + +Query.prototype.intersects = function intersects() { + // opinionated, must be used after where + this._ensurePath('intersects'); + + this._geoComparison = '$geoIntersects'; + + if (0 === arguments.length) { + return this; + } + + const area = arguments[0]; + + if (null != area && area.type && area.coordinates) + return this.geometry(area); + + throw new TypeError('Invalid argument'); +}; + +/** + * Specifies a `$geometry` condition + * + * ####Example + * + * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] + * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + * + * // or + * var polyB = [[ 0, 0 ], [ 1, 1 ]] + * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + * + * // or + * var polyC = [ 0, 0 ] + * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + * + * // or + * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + * + * ####NOTE: + * + * `geometry()` **must** come after either `intersects()` or `within()`. + * + * The `object` argument must contain `type` and `coordinates` properties. + * - type {String} + * - coordinates {Array} + * + * The most recent path passed to `where()` is used. + * + * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. + * @return {Query} this + * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @api public + */ + +Query.prototype.geometry = function geometry() { + if (!('$within' == this._geoComparison || + '$geoWithin' == this._geoComparison || + '$near' == this._geoComparison || + '$geoIntersects' == this._geoComparison)) { + throw new Error('geometry() must come after `within()`, `intersects()`, or `near()'); + } + + let val, path; + + if (1 === arguments.length) { + this._ensurePath('geometry'); + path = this._path; + val = arguments[0]; + } else { + throw new TypeError('Invalid argument'); + } + + if (!(val.type && Array.isArray(val.coordinates))) { + throw new TypeError('Invalid argument'); + } + + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison] = { $geometry: val }; + + return this; +}; + +// end spatial + +/** + * Specifies which document fields to include or exclude + * + * ####String syntax + * + * When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. + * + * ####Example + * + * // include a and b, exclude c + * query.select('a b -c'); + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * query.select({a: 1, b: 1, c: 0}); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @see SchemaType + * @api public + */ + +Query.prototype.select = function select() { + let arg = arguments[0]; + if (!arg) return this; + + if (arguments.length !== 1) { + throw new Error('Invalid select: select only takes 1 argument'); + } + + this._validate('select'); + + const fields = this._fields || (this._fields = {}); + const type = typeof arg; + let i, len; + + if (('string' == type || utils.isArgumentsObject(arg)) && + 'number' == typeof arg.length || Array.isArray(arg)) { + if ('string' == type) + arg = arg.split(/\s+/); + + for (i = 0, len = arg.length; i < len; ++i) { + let field = arg[i]; + if (!field) continue; + const include = '-' == field[0] ? 0 : 1; + if (include === 0) field = field.substring(1); + fields[field] = include; + } + + return this; + } + + if (utils.isObject(arg)) { + const keys = utils.keys(arg); + for (i = 0; i < keys.length; ++i) { + fields[keys[i]] = arg[keys[i]]; + } + return this; + } + + throw new TypeError('Invalid select() argument. Must be string or object.'); +}; + +/** + * Specifies a $slice condition for a `path` + * + * ####Example + * + * query.slice('comments', 5) + * query.slice('comments', -5) + * query.slice('comments', [10, 5]) + * query.where('comments').slice(5) + * query.where('comments').slice([-10, 5]) + * + * @param {String} [path] + * @param {Number} val number/range of elements to slice + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements + * @api public + */ + +Query.prototype.slice = function() { + if (0 === arguments.length) + return this; + + this._validate('slice'); + + let path, val; + + if (1 === arguments.length) { + const arg = arguments[0]; + if (typeof arg === 'object' && !Array.isArray(arg)) { + const keys = Object.keys(arg); + const numKeys = keys.length; + for (let i = 0; i < numKeys; ++i) { + this.slice(keys[i], arg[keys[i]]); + } + return this; + } + this._ensurePath('slice'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + if ('number' === typeof arguments[0]) { + this._ensurePath('slice'); + path = this._path; + val = slice(arguments); + } else { + path = arguments[0]; + val = arguments[1]; + } + } else if (3 === arguments.length) { + path = arguments[0]; + val = slice(arguments, 1); + } + + const myFields = this._fields || (this._fields = {}); + myFields[path] = { $slice: val }; + return this; +}; + +/** + * Sets the sort order + * + * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1. + * + * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + * + * ####Example + * + * // these are equivalent + * query.sort({ field: 'asc', test: -1 }); + * query.sort('field -test'); + * query.sort([['field', 1], ['test', -1]]); + * + * ####Note + * + * - The array syntax `.sort([['field', 1], ['test', -1]])` can only be used with [mongodb driver >= 2.0.46](https://github.com/mongodb/node-mongodb-native/blob/2.1/HISTORY.md#2046-2015-10-15). + * - Cannot be used with `distinct()` + * + * @param {Object|String|Array} arg + * @return {Query} this + * @api public + */ + +Query.prototype.sort = function(arg) { + if (!arg) return this; + let i, len, field; + + this._validate('sort'); + + const type = typeof arg; + + // .sort([['field', 1], ['test', -1]]) + if (Array.isArray(arg)) { + len = arg.length; + for (i = 0; i < arg.length; ++i) { + if (!Array.isArray(arg[i])) { + throw new Error('Invalid sort() argument, must be array of arrays'); + } + _pushArr(this.options, arg[i][0], arg[i][1]); + } + return this; + } + + // .sort('field -test') + if (1 === arguments.length && 'string' == type) { + arg = arg.split(/\s+/); + len = arg.length; + for (i = 0; i < len; ++i) { + field = arg[i]; + if (!field) continue; + const ascend = '-' == field[0] ? -1 : 1; + if (ascend === -1) field = field.substring(1); + push(this.options, field, ascend); + } + + return this; + } + + // .sort({ field: 1, test: -1 }) + if (utils.isObject(arg)) { + const keys = utils.keys(arg); + for (i = 0; i < keys.length; ++i) { + field = keys[i]; + push(this.options, field, arg[field]); + } + + return this; + } + + if (typeof Map !== 'undefined' && arg instanceof Map) { + _pushMap(this.options, arg); + return this; + } + throw new TypeError('Invalid sort() argument. Must be a string, object, or array.'); +}; + +/*! + * @ignore + */ + +const _validSortValue = { + 1: 1, + '-1': -1, + asc: 1, + ascending: 1, + desc: -1, + descending: -1 +}; + +function push(opts, field, value) { + if (Array.isArray(opts.sort)) { + throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' + + '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' + + '\n- `.sort({ field: 1, test: -1 })`'); + } + + let s; + if (value && value.$meta) { + s = opts.sort || (opts.sort = {}); + s[field] = { $meta: value.$meta }; + return; + } + + s = opts.sort || (opts.sort = {}); + let val = String(value || 1).toLowerCase(); + val = _validSortValue[val]; + if (!val) throw new TypeError('Invalid sort value: { ' + field + ': ' + value + ' }'); + + s[field] = val; +} + +function _pushArr(opts, field, value) { + opts.sort = opts.sort || []; + if (!Array.isArray(opts.sort)) { + throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' + + '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' + + '\n- `.sort({ field: 1, test: -1 })`'); + } + + let val = String(value || 1).toLowerCase(); + val = _validSortValue[val]; + if (!val) throw new TypeError('Invalid sort value: [ ' + field + ', ' + value + ' ]'); + + opts.sort.push([field, val]); +} + +function _pushMap(opts, map) { + opts.sort = opts.sort || new Map(); + if (!(opts.sort instanceof Map)) { + throw new TypeError('Can\'t mix sort syntaxes. Use either array or ' + + 'object or map consistently'); + } + map.forEach(function(value, key) { + let val = String(value || 1).toLowerCase(); + val = _validSortValue[val]; + if (!val) throw new TypeError('Invalid sort value: < ' + key + ': ' + value + ' >'); + + opts.sort.set(key, val); + }); +} + + + +/** + * Specifies the limit option. + * + * ####Example + * + * query.limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method limit + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D + * @api public + */ +/** + * Specifies the skip option. + * + * ####Example + * + * query.skip(100).limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method skip + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D + * @api public + */ +/** + * Specifies the maxScan option. + * + * ####Example + * + * query.maxScan(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method maxScan + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan + * @api public + */ +/** + * Specifies the batchSize option. + * + * ####Example + * + * query.batchSize(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method batchSize + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D + * @api public + */ +/** + * Specifies the `comment` option. + * + * ####Example + * + * query.comment('login query') + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method comment + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment + * @api public + */ + +/*! + * limit, skip, maxScan, batchSize, comment + * + * Sets these associated options. + * + * query.comment('feed query'); + */ + +['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function(method) { + Query.prototype[method] = function(v) { + this._validate(method); + this.options[method] = v; + return this; + }; +}); + +/** + * Specifies the maxTimeMS option. + * + * ####Example + * + * query.maxTime(100) + * query.maxTimeMS(100) + * + * @method maxTime + * @memberOf Query + * @param {Number} ms + * @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS + * @api public + */ + +Query.prototype.maxTime = Query.prototype.maxTimeMS = function(ms) { + this._validate('maxTime'); + this.options.maxTimeMS = ms; + return this; +}; + +/** + * Specifies this query as a `snapshot` query. + * + * ####Example + * + * mquery().snapshot() // true + * mquery().snapshot(true) + * mquery().snapshot(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D + * @return {Query} this + * @api public + */ + +Query.prototype.snapshot = function() { + this._validate('snapshot'); + + this.options.snapshot = arguments.length + ? !!arguments[0] + : true; + + return this; +}; + +/** + * Sets query hints. + * + * ####Example + * + * query.hint({ indexA: 1, indexB: -1}); + * query.hint('indexA_1_indexB_1'); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|string} val a hint object or the index name + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint + * @api public + */ + +Query.prototype.hint = function() { + if (0 === arguments.length) return this; + + this._validate('hint'); + + const arg = arguments[0]; + if (utils.isObject(arg)) { + const hint = this.options.hint || (this.options.hint = {}); + + // must keep object keys in order so don't use Object.keys() + for (const k in arg) { + hint[k] = arg[k]; + } + + return this; + } + if (typeof arg === 'string') { + this.options.hint = arg; + return this; + } + + throw new TypeError('Invalid hint. ' + arg); +}; + +/** + * Requests acknowledgement that this operation has been persisted to MongoDB's + * on-disk journal. + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the `j` value if it is specified in writeConcern options + * + * ####Example: + * + * mquery().w(2).j(true).wtimeout(2000); + * + * @method j + * @memberOf Query + * @instance + * @param {boolean} val + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option + * @return {Query} this + * @api public + */ + +Query.prototype.j = function j(val) { + this.options.j = val; + return this; +}; + +/** + * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences. + * + * ####Example: + * + * query.slaveOk() // true + * query.slaveOk(true) + * query.slaveOk(false) + * + * @deprecated use read() preferences instead if on mongodb >= 2.2 + * @param {Boolean} v defaults to true + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see read() + * @return {Query} this + * @api public + */ + +Query.prototype.slaveOk = function(v) { + this.options.slaveOk = arguments.length ? !!v : true; + return this; +}; + +/** + * Sets the readPreference option for the query. + * + * ####Example: + * + * new Query().read('primary') + * new Query().read('p') // same as primary + * + * new Query().read('primaryPreferred') + * new Query().read('pp') // same as primaryPreferred + * + * new Query().read('secondary') + * new Query().read('s') // same as secondary + * + * new Query().read('secondaryPreferred') + * new Query().read('sp') // same as secondaryPreferred + * + * new Query().read('nearest') + * new Query().read('n') // same as nearest + * + * // you can also use mongodb.ReadPreference class to also specify tags + * new Query().read(mongodb.ReadPreference('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])) + * + * new Query().setReadPreference('primary') // alias of .read() + * + * ####Preferences: + * + * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. + * secondary Read from secondary if available, otherwise error. + * primaryPreferred Read from primary if available, otherwise a secondary. + * secondaryPreferred Read from a secondary if available, otherwise read from the primary. + * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + * + * Aliases + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + * + * @param {String|ReadPreference} pref one of the listed preference options or their aliases + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + * @return {Query} this + * @api public + */ + +Query.prototype.read = Query.prototype.setReadPreference = function(pref) { + if (arguments.length > 1 && !Query.prototype.read.deprecationWarningIssued) { + console.error('Deprecation warning: \'tags\' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead.'); + Query.prototype.read.deprecationWarningIssued = true; + } + this.options.readPreference = utils.readPref(pref); + return this; +}; + +/** + * Sets the readConcern option for the query. + * + * ####Example: + * + * new Query().readConcern('local') + * new Query().readConcern('l') // same as local + * + * new Query().readConcern('available') + * new Query().readConcern('a') // same as available + * + * new Query().readConcern('majority') + * new Query().readConcern('m') // same as majority + * + * new Query().readConcern('linearizable') + * new Query().readConcern('lz') // same as linearizable + * + * new Query().readConcern('snapshot') + * new Query().readConcern('s') // same as snapshot + * + * new Query().r('s') // r is alias of readConcern + * + * + * ####Read Concern Level: + * + * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). + * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). + * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. + * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. + * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. + + + * + * + * Aliases + * + * l local + * a available + * m majority + * lz linearizable + * s snapshot + * + * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). + * + * @param {String} level one of the listed read concern level or their aliases + * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ + * @return {Query} this + * @api public + */ + +Query.prototype.readConcern = Query.prototype.r = function(level) { + this.options.readConcern = utils.readConcern(level); + return this; +}; + +/** + * Sets tailable option. + * + * ####Example + * + * query.tailable() <== true + * query.tailable(true) + * query.tailable(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Boolean} v defaults to true + * @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors + * @api public + */ + +Query.prototype.tailable = function() { + this._validate('tailable'); + + this.options.tailable = arguments.length + ? !!arguments[0] + : true; + + return this; +}; + +/** + * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, + * that must acknowledge this write before this write is considered successful. + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the `w` value if it is specified in writeConcern options + * + * ####Example: + * + * mquery().writeConcern(0) + * mquery().writeConcern(1) + * mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 }) + * mquery().writeConcern('majority') + * mquery().writeConcern('m') // same as majority + * mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead + * mquery().w(1) // w is alias of writeConcern + * + * @method writeConcern + * @memberOf Query + * @instance + * @param {String|number|object} concern 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option). + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option + * @return {Query} this + * @api public + */ + +Query.prototype.writeConcern = Query.prototype.w = function writeConcern(concern) { + if ('object' === typeof concern) { + if ('undefined' !== typeof concern.j) this.options.j = concern.j; + if ('undefined' !== typeof concern.w) this.options.w = concern.w; + if ('undefined' !== typeof concern.wtimeout) this.options.wtimeout = concern.wtimeout; + } else { + this.options.w = 'm' === concern ? 'majority' : concern; + } + return this; +}; + +/** + * Specifies a time limit, in milliseconds, for the write concern. + * If `ms > 1`, it is maximum amount of time to wait for this write + * to propagate through the replica set before this operation fails. + * The default is `0`, which means no timeout. + * + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to `wtimeout` value if it is specified in writeConcern + * + * ####Example: + * + * mquery().w(2).j(true).wtimeout(2000) + * + * @method wtimeout + * @memberOf Query + * @instance + * @param {number} ms number of milliseconds to wait + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout + * @return {Query} this + * @api public + */ + +Query.prototype.wtimeout = Query.prototype.wTimeout = function wtimeout(ms) { + this.options.wtimeout = ms; + return this; +}; + +/** + * Merges another Query or conditions object into this one. + * + * When a Query is passed, conditions, field selection and options are merged. + * + * @param {Query|Object} source + * @return {Query} this + */ + +Query.prototype.merge = function(source) { + if (!source) + return this; + + if (!Query.canMerge(source)) + throw new TypeError('Invalid argument. Expected instanceof mquery or plain object'); + + if (source instanceof Query) { + // if source has a feature, apply it to ourselves + + if (source._conditions) { + utils.merge(this._conditions, source._conditions); + } + + if (source._fields) { + this._fields || (this._fields = {}); + utils.merge(this._fields, source._fields); + } + + if (source.options) { + this.options || (this.options = {}); + utils.merge(this.options, source.options); + } + + if (source._update) { + this._update || (this._update = {}); + utils.mergeClone(this._update, source._update); + } + + if (source._distinct) { + this._distinct = source._distinct; + } + + return this; + } + + // plain object + utils.merge(this._conditions, source); + + return this; +}; + +/** + * Finds documents. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.find() + * query.find(callback) + * query.find({ name: 'Burning Lights' }, callback) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.find = function(criteria, callback) { + this.op = 'find'; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + const conds = this._conditions; + const options = this._optionsForExec(); + + if (this.$useProjection) { + options.projection = this._fieldsForExec(); + } else { + options.fields = this._fieldsForExec(); + } + + debug('find', this._collection.collectionName, conds, options); + callback = this._wrapCallback('find', callback, { + conditions: conds, + options: options + }); + + this._collection.find(conds, options, utils.tick(callback)); + return this; +}; + +/** + * Returns the query cursor + * + * ####Examples + * + * query.find().cursor(); + * query.cursor({ name: 'Burning Lights' }); + * + * @param {Object} [criteria] mongodb selector + * @return {Object} cursor + * @api public + */ + +Query.prototype.cursor = function cursor(criteria) { + if (this.op) { + if (this.op !== 'find') { + throw new TypeError('.cursor only support .find method'); + } + } else { + this.find(criteria); + } + + const conds = this._conditions; + const options = this._optionsForExec(); + + if (this.$useProjection) { + options.projection = this._fieldsForExec(); + } else { + options.fields = this._fieldsForExec(); + } + + debug('findCursor', this._collection.collectionName, conds, options); + return this._collection.findCursor(conds, options); +}; + +/** + * Executes the query as a findOne() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.findOne().where('name', /^Burning/); + * + * query.findOne({ name: /^Burning/ }) + * + * query.findOne({ name: /^Burning/ }, callback); // executes + * + * query.findOne(function (err, doc) { + * if (err) return handleError(err); + * if (doc) { + * // doc may be null if no document matched + * + * } + * }); + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.findOne = function(criteria, callback) { + this.op = 'findOne'; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + const conds = this._conditions; + const options = this._optionsForExec(); + + if (this.$useProjection) { + options.projection = this._fieldsForExec(); + } else { + options.fields = this._fieldsForExec(); + } + + debug('findOne', this._collection.collectionName, conds, options); + callback = this._wrapCallback('findOne', callback, { + conditions: conds, + options: options + }); + + this._collection.findOne(conds, options, utils.tick(callback)); + + return this; +}; + +/** + * Exectues the query as a count() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.count().where('color', 'black').exec(callback); + * + * query.count({ color: 'black' }).count(callback) + * + * query.count({ color: 'black' }, callback) + * + * query.where('color', 'black').count(function (err, count) { + * if (err) return handleError(err); + * console.log('there are %d kittens', count); + * }) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count + * @api public + */ + +Query.prototype.count = function(criteria, callback) { + this.op = 'count'; + this._validate(); + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + const conds = this._conditions, + options = this._optionsForExec(); + + debug('count', this._collection.collectionName, conds, options); + callback = this._wrapCallback('count', callback, { + conditions: conds, + options: options + }); + + this._collection.count(conds, options, utils.tick(callback)); + return this; +}; + +/** + * Declares or executes a distinct() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * distinct(criteria, field, fn) + * distinct(criteria, field) + * distinct(field, fn) + * distinct(field) + * distinct(fn) + * distinct() + * + * @param {Object|Query} [criteria] + * @param {String} [field] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct + * @api public + */ + +Query.prototype.distinct = function(criteria, field, callback) { + this.op = 'distinct'; + this._validate(); + + if (!callback) { + switch (typeof field) { + case 'function': + callback = field; + if ('string' == typeof criteria) { + field = criteria; + criteria = undefined; + } + break; + case 'undefined': + case 'string': + break; + default: + throw new TypeError('Invalid `field` argument. Must be string or function'); + } + + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = field = undefined; + break; + case 'string': + field = criteria; + criteria = undefined; + break; + } + } + + if ('string' == typeof field) { + this._distinct = field; + } + + if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) { + return this; + } + + if (!this._distinct) { + throw new Error('No value for `distinct` has been declared'); + } + + const conds = this._conditions, + options = this._optionsForExec(); + + debug('distinct', this._collection.collectionName, conds, options); + callback = this._wrapCallback('distinct', callback, { + conditions: conds, + options: options + }); + + this._collection.distinct(this._distinct, conds, options, utils.tick(callback)); + + return this; +}; + +/** + * Declare and/or execute this query as an update() operation. By default, + * `update()` only modifies the _first_ document that matches `criteria`. + * + * _All paths passed that are not $atomic operations will become $set ops._ + * + * ####Example + * + * mquery({ _id: id }).update({ title: 'words' }, ...) + * + * becomes + * + * collection.update({ _id: id }, { $set: { title: 'words' }}, ...) + * + * ####Note + * + * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. + * + * var q = mquery(collection).where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).update(); // not executed + * + * var q = mquery(collection).where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe + * + * // keys that are not $atomic ops become $set. + * // this executes the same command as the previous example. + * q.update({ name: 'bob' }).where({ _id: id }).exec(); + * + * var q = mquery(collection).update(); // not executed + * + * // overwriting with empty docs + * var q.where({ _id: id }).setOptions({ overwrite: true }) + * q.update({ }, callback); // executes + * + * // multi update with overwrite to empty doc + * var q = mquery(collection).where({ _id: id }); + * q.setOptions({ multi: true, overwrite: true }) + * q.update({ }); + * q.update(callback); // executed + * + * // multi updates + * mquery() + * .collection(coll) + * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) + * // more multi updates + * mquery({ }) + * .collection(coll) + * .setOptions({ multi: true }) + * .update({ $set: { arr: [] }}, callback) + * + * // single update by default + * mquery({ email: 'address@example.com' }) + * .collection(coll) + * .update({ $inc: { counter: 1 }}, callback) + * + * // summary + * update(criteria, doc, opts, cb) // executes + * update(criteria, doc, opts) + * update(criteria, doc, cb) // executes + * update(criteria, doc) + * update(doc, cb) // executes + * update(doc) + * update(cb) // executes + * update(true) // executes (unsafe write) + * update() + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.update = function update(criteria, doc, options, callback) { + var force; + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = undefined; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + break; + case 1: + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = options = doc = undefined; + break; + case 'boolean': + // execution with no callback (unsafe write) + force = criteria; + criteria = undefined; + break; + default: + doc = criteria; + criteria = options = undefined; + break; + } + } + + return _update(this, 'update', criteria, doc, options, force, callback); +}; + +/** + * Declare and/or execute this query as an `updateMany()` operation. Identical + * to `update()` except `updateMany()` will update _all_ documents that match + * `criteria`, rather than just the first one. + * + * _All paths passed that are not $atomic operations will become $set ops._ + * + * ####Example + * + * // Update every document whose `title` contains 'test' + * mquery().updateMany({ title: /test/ }, { year: 2017 }) + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.updateMany = function updateMany(criteria, doc, options, callback) { + let force; + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = undefined; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + break; + case 1: + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = options = doc = undefined; + break; + case 'boolean': + // execution with no callback (unsafe write) + force = criteria; + criteria = undefined; + break; + default: + doc = criteria; + criteria = options = undefined; + break; + } + } + + return _update(this, 'updateMany', criteria, doc, options, force, callback); +}; + +/** + * Declare and/or execute this query as an `updateOne()` operation. Identical + * to `update()` except `updateOne()` will _always_ update just one document, + * regardless of the `multi` option. + * + * _All paths passed that are not $atomic operations will become $set ops._ + * + * ####Example + * + * // Update the first document whose `title` contains 'test' + * mquery().updateMany({ title: /test/ }, { year: 2017 }) + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.updateOne = function updateOne(criteria, doc, options, callback) { + let force; + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = undefined; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + break; + case 1: + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = options = doc = undefined; + break; + case 'boolean': + // execution with no callback (unsafe write) + force = criteria; + criteria = undefined; + break; + default: + doc = criteria; + criteria = options = undefined; + break; + } + } + + return _update(this, 'updateOne', criteria, doc, options, force, callback); +}; + +/** + * Declare and/or execute this query as an `replaceOne()` operation. Similar + * to `updateOne()`, except `replaceOne()` is not allowed to use atomic + * modifiers (`$set`, `$push`, etc.). Calling `replaceOne()` will always + * replace the existing doc. + * + * ####Example + * + * // Replace the document with `_id` 1 with `{ _id: 1, year: 2017 }` + * mquery().replaceOne({ _id: 1 }, { year: 2017 }) + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.replaceOne = function replaceOne(criteria, doc, options, callback) { + let force; + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = undefined; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + break; + case 1: + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = options = doc = undefined; + break; + case 'boolean': + // execution with no callback (unsafe write) + force = criteria; + criteria = undefined; + break; + default: + doc = criteria; + criteria = options = undefined; + break; + } + } + + this.setOptions({ overwrite: true }); + return _update(this, 'replaceOne', criteria, doc, options, force, callback); +}; + + +/*! + * Internal helper for update, updateMany, updateOne + */ + +function _update(query, op, criteria, doc, options, force, callback) { + query.op = op; + + if (Query.canMerge(criteria)) { + query.merge(criteria); + } + + if (doc) { + query._mergeUpdate(doc); + } + + if (utils.isObject(options)) { + // { overwrite: true } + query.setOptions(options); + } + + // we are done if we don't have callback and they are + // not forcing an unsafe write. + if (!(force || callback)) { + return query; + } + + if (!query._update || + !query.options.overwrite && 0 === utils.keys(query._update).length) { + callback && utils.soon(callback.bind(null, null, 0)); + return query; + } + + options = query._optionsForExec(); + if (!callback) options.safe = false; + + criteria = query._conditions; + doc = query._updateForExec(); + + debug('update', query._collection.collectionName, criteria, doc, options); + callback = query._wrapCallback(op, callback, { + conditions: criteria, + doc: doc, + options: options + }); + + query._collection[op](criteria, doc, options, utils.tick(callback)); + + return query; +} + +/** + * Declare and/or execute this query as a remove() operation. + * + * ####Example + * + * mquery(collection).remove({ artist: 'Anne Murray' }, callback) + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. + * + * // not executed + * var query = mquery(collection).remove({ name: 'Anne Murray' }) + * + * // executed + * mquery(collection).remove({ name: 'Anne Murray' }, callback) + * mquery(collection).remove({ name: 'Anne Murray' }).remove(callback) + * + * // executed without a callback (unsafe write) + * query.exec() + * + * // summary + * query.remove(conds, fn); // executes + * query.remove(conds) + * query.remove(fn) // executes + * query.remove() + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.remove = function(criteria, callback) { + this.op = 'remove'; + let force; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } else if (true === criteria) { + force = criteria; + criteria = undefined; + } + + if (!(force || callback)) + return this; + + const options = this._optionsForExec(); + if (!callback) options.safe = false; + + const conds = this._conditions; + + debug('remove', this._collection.collectionName, conds, options); + callback = this._wrapCallback('remove', callback, { + conditions: conds, + options: options + }); + + this._collection.remove(conds, options, utils.tick(callback)); + + return this; +}; + +/** + * Declare and/or execute this query as a `deleteOne()` operation. Behaves like + * `remove()`, except for ignores the `justOne` option and always deletes at + * most one document. + * + * ####Example + * + * mquery(collection).deleteOne({ artist: 'Anne Murray' }, callback) + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.deleteOne = function(criteria, callback) { + this.op = 'deleteOne'; + let force; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } else if (true === criteria) { + force = criteria; + criteria = undefined; + } + + if (!(force || callback)) + return this; + + const options = this._optionsForExec(); + if (!callback) options.safe = false; + delete options.justOne; + + const conds = this._conditions; + + debug('deleteOne', this._collection.collectionName, conds, options); + callback = this._wrapCallback('deleteOne', callback, { + conditions: conds, + options: options + }); + + this._collection.deleteOne(conds, options, utils.tick(callback)); + + return this; +}; + +/** + * Declare and/or execute this query as a `deleteMany()` operation. Behaves like + * `remove()`, except for ignores the `justOne` option and always deletes + * _every_ document that matches `criteria`. + * + * ####Example + * + * mquery(collection).deleteMany({ artist: 'Anne Murray' }, callback) + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.deleteMany = function(criteria, callback) { + this.op = 'deleteMany'; + let force; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } else if (true === criteria) { + force = criteria; + criteria = undefined; + } + + if (!(force || callback)) + return this; + + const options = this._optionsForExec(); + if (!callback) options.safe = false; + delete options.justOne; + + const conds = this._conditions; + + debug('deleteOne', this._collection.collectionName, conds, options); + callback = this._wrapCallback('deleteOne', callback, { + conditions: conds, + options: options + }); + + this._collection.deleteMany(conds, options, utils.tick(callback)); + + return this; +}; + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. + * + * ####Available options + * + * - `new`: bool - true to return the modified document rather than the original. defaults to true + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * + * ####Examples + * + * query.findOneAndUpdate(conditions, update, options, callback) // executes + * query.findOneAndUpdate(conditions, update, options) // returns Query + * query.findOneAndUpdate(conditions, update, callback) // executes + * query.findOneAndUpdate(conditions, update) // returns Query + * query.findOneAndUpdate(update, callback) // returns Query + * query.findOneAndUpdate(update) // returns Query + * query.findOneAndUpdate(callback) // executes + * query.findOneAndUpdate() // returns Query + * + * @param {Object|Query} [query] + * @param {Object} [doc] + * @param {Object} [options] + * @param {Function} [callback] + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @return {Query} this + * @api public + */ + +Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) { + this.op = 'findOneAndUpdate'; + this._validate(); + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = {}; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + options = undefined; + break; + case 1: + if ('function' == typeof criteria) { + callback = criteria; + criteria = options = doc = undefined; + } else { + doc = criteria; + criteria = options = undefined; + } + } + + if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + // apply doc + if (doc) { + this._mergeUpdate(doc); + } + + options && this.setOptions(options); + + if (!callback) return this; + + const conds = this._conditions; + const update = this._updateForExec(); + options = this._optionsForExec(); + + return this._collection.findOneAndUpdate(conds, update, options, utils.tick(callback)); +}; + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * + * ####Examples + * + * A.where().findOneAndRemove(conditions, options, callback) // executes + * A.where().findOneAndRemove(conditions, options) // return Query + * A.where().findOneAndRemove(conditions, callback) // executes + * A.where().findOneAndRemove(conditions) // returns Query + * A.where().findOneAndRemove(callback) // executes + * A.where().findOneAndRemove() // returns Query + * A.where().findOneAndDelete() // alias of .findOneAndRemove() + * + * @param {Object} [conditions] + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Query.prototype.findOneAndRemove = Query.prototype.findOneAndDelete = function(conditions, options, callback) { + this.op = 'findOneAndRemove'; + this._validate(); + + if ('function' == typeof options) { + callback = options; + options = undefined; + } else if ('function' == typeof conditions) { + callback = conditions; + conditions = undefined; + } + + // apply conditions + if (Query.canMerge(conditions)) { + this.merge(conditions); + } + + // apply options + options && this.setOptions(options); + + if (!callback) return this; + + options = this._optionsForExec(); + const conds = this._conditions; + + return this._collection.findOneAndDelete(conds, options, utils.tick(callback)); +}; + +/** + * Wrap callback to add tracing + * + * @param {Function} callback + * @param {Object} [queryInfo] + * @api private + */ +Query.prototype._wrapCallback = function(method, callback, queryInfo) { + const traceFunction = this._traceFunction || Query.traceFunction; + + if (traceFunction) { + queryInfo.collectionName = this._collection.collectionName; + + const traceCallback = traceFunction && + traceFunction.call(null, method, queryInfo, this); + + const startTime = new Date().getTime(); + + return function wrapperCallback(err, result) { + if (traceCallback) { + const millis = new Date().getTime() - startTime; + traceCallback.call(null, err, result, millis); + } + + if (callback) { + callback.apply(null, arguments); + } + }; + } + + return callback; +}; + +/** + * Add trace function that gets called when the query is executed. + * The function will be called with (method, queryInfo, query) and + * should return a callback function which will be called + * with (err, result, millis) when the query is complete. + * + * queryInfo is an object containing: { + * collectionName: , + * conditions: , + * options: , + * doc: [document to update, if applicable] + * } + * + * NOTE: Does not trace stream queries. + * + * @param {Function} traceFunction + * @return {Query} this + * @api public + */ +Query.prototype.setTraceFunction = function(traceFunction) { + this._traceFunction = traceFunction; + return this; +}; + +/** + * Executes the query + * + * ####Examples + * + * query.exec(); + * query.exec(callback); + * query.exec('update'); + * query.exec('find', callback); + * + * @param {String|Function} [operation] + * @param {Function} [callback] + * @api public + */ + +Query.prototype.exec = function exec(op, callback) { + switch (typeof op) { + case 'function': + callback = op; + op = null; + break; + case 'string': + this.op = op; + break; + } + + assert.ok(this.op, 'Missing query type: (find, update, etc)'); + + if ('update' == this.op || 'remove' == this.op) { + callback || (callback = true); + } + + const _this = this; + + if ('function' == typeof callback) { + this[this.op](callback); + } else { + return new Query.Promise(function(success, error) { + _this[_this.op](function(err, val) { + if (err) error(err); + else success(val); + success = error = null; + }); + }); + } +}; + +/** + * Returns a thunk which when called runs this.exec() + * + * The thunk receives a callback function which will be + * passed to `this.exec()` + * + * @return {Function} + * @api public + */ + +Query.prototype.thunk = function() { + const _this = this; + return function(cb) { + _this.exec(cb); + }; +}; + +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @return {Promise} + * @api public + */ + +Query.prototype.then = function(resolve, reject) { + const _this = this; + const promise = new Query.Promise(function(success, error) { + _this.exec(function(err, val) { + if (err) error(err); + else success(val); + success = error = null; + }); + }); + return promise.then(resolve, reject); +}; + +/** + * Returns a cursor for the given `find` query. + * + * @throws Error if operation is not a find + * @returns {Cursor} MongoDB driver cursor + */ + +Query.prototype.cursor = function() { + if ('find' != this.op) + throw new Error('cursor() is only available for find'); + + const conds = this._conditions; + + const options = this._optionsForExec(); + if (this.$useProjection) { + options.projection = this._fieldsForExec(); + } else { + options.fields = this._fieldsForExec(); + } + + debug('cursor', this._collection.collectionName, conds, options); + + return this._collection.findCursor(conds, options); +}; + +/** + * Determines if field selection has been made. + * + * @return {Boolean} + * @api public + */ + +Query.prototype.selected = function selected() { + return !!(this._fields && Object.keys(this._fields).length > 0); +}; + +/** + * Determines if inclusive field selection has been made. + * + * query.selectedInclusively() // false + * query.select('name') + * query.selectedInclusively() // true + * query.selectedExlusively() // false + * + * @returns {Boolean} + */ + +Query.prototype.selectedInclusively = function selectedInclusively() { + if (!this._fields) return false; + + const keys = Object.keys(this._fields); + if (0 === keys.length) return false; + + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (0 === this._fields[key]) return false; + if (this._fields[key] && + typeof this._fields[key] === 'object' && + this._fields[key].$meta) { + return false; + } + } + + return true; +}; + +/** + * Determines if exclusive field selection has been made. + * + * query.selectedExlusively() // false + * query.select('-name') + * query.selectedExlusively() // true + * query.selectedInclusively() // false + * + * @returns {Boolean} + */ + +Query.prototype.selectedExclusively = function selectedExclusively() { + if (!this._fields) return false; + + const keys = Object.keys(this._fields); + if (0 === keys.length) return false; + + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (0 === this._fields[key]) return true; + } + + return false; +}; + +/** + * Merges `doc` with the current update object. + * + * @param {Object} doc + */ + +Query.prototype._mergeUpdate = function(doc) { + if (!this._update) this._update = {}; + if (doc instanceof Query) { + if (doc._update) { + utils.mergeClone(this._update, doc._update); + } + } else { + utils.mergeClone(this._update, doc); + } +}; + +/** + * Returns default options. + * + * @return {Object} + * @api private + */ + +Query.prototype._optionsForExec = function() { + const options = utils.clone(this.options); + return options; +}; + +/** + * Returns fields selection for this query. + * + * @return {Object} + * @api private + */ + +Query.prototype._fieldsForExec = function() { + return utils.clone(this._fields); +}; + +/** + * Return an update document with corrected $set operations. + * + * @api private + */ + +Query.prototype._updateForExec = function() { + const update = utils.clone(this._update); + const ops = utils.keys(update); + const ret = {}; + + for (const op of ops) { + if (this.options.overwrite) { + ret[op] = update[op]; + continue; + } + + if ('$' !== op[0]) { + // fix up $set sugar + if (!ret.$set) { + if (update.$set) { + ret.$set = update.$set; + } else { + ret.$set = {}; + } + } + ret.$set[op] = update[op]; + if (!~ops.indexOf('$set')) ops.push('$set'); + } else if ('$set' === op) { + if (!ret.$set) { + ret[op] = update[op]; + } + } else { + ret[op] = update[op]; + } + } + + this._compiledUpdate = ret; + return ret; +}; + +/** + * Make sure _path is set. + * + * @parmam {String} method + */ + +Query.prototype._ensurePath = function(method) { + if (!this._path) { + const msg = method + '() must be used after where() ' + + 'when called with these arguments'; + throw new Error(msg); + } +}; + +/*! + * Permissions + */ + +Query.permissions = require('./permissions'); + +Query._isPermitted = function(a, b) { + const denied = Query.permissions[b]; + if (!denied) return true; + return true !== denied[a]; +}; + +Query.prototype._validate = function(action) { + let fail; + let validator; + + if (undefined === action) { + + validator = Query.permissions[this.op]; + if ('function' != typeof validator) return true; + + fail = validator(this); + + } else if (!Query._isPermitted(action, this.op)) { + fail = action; + } + + if (fail) { + throw new Error(fail + ' cannot be used with ' + this.op); + } +}; + +/** + * Determines if `conds` can be merged using `mquery().merge()` + * + * @param {Object} conds + * @return {Boolean} + */ + +Query.canMerge = function(conds) { + return conds instanceof Query || utils.isObject(conds); +}; + +/** + * Set a trace function that will get called whenever a + * query is executed. + * + * See `setTraceFunction()` for details. + * + * @param {Object} conds + * @return {Boolean} + */ +Query.setGlobalTraceFunction = function(traceFunction) { + Query.traceFunction = traceFunction; +}; + +/*! + * Exports. + */ + +Query.utils = utils; +Query.env = require('./env'); +Query.Collection = require('./collection'); +Query.BaseCollection = require('./collection/collection'); +Query.Promise = Promise; +module.exports = exports = Query; + +// TODO +// test utils diff --git a/node_modules/mquery/lib/permissions.js b/node_modules/mquery/lib/permissions.js new file mode 100644 index 0000000..09b0590 --- /dev/null +++ b/node_modules/mquery/lib/permissions.js @@ -0,0 +1,88 @@ +'use strict'; + +const denied = exports; + +denied.distinct = function(self) { + if (self._fields && Object.keys(self._fields).length > 0) { + return 'field selection and slice'; + } + + const keys = Object.keys(denied.distinct); + let err; + + keys.every(function(option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +}; +denied.distinct.select = +denied.distinct.slice = +denied.distinct.sort = +denied.distinct.limit = +denied.distinct.skip = +denied.distinct.batchSize = +denied.distinct.comment = +denied.distinct.maxScan = +denied.distinct.snapshot = +denied.distinct.hint = +denied.distinct.tailable = true; + + +// aggregation integration + + +denied.findOneAndUpdate = +denied.findOneAndRemove = function(self) { + const keys = Object.keys(denied.findOneAndUpdate); + let err; + + keys.every(function(option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +}; +denied.findOneAndUpdate.limit = +denied.findOneAndUpdate.skip = +denied.findOneAndUpdate.batchSize = +denied.findOneAndUpdate.maxScan = +denied.findOneAndUpdate.snapshot = +denied.findOneAndUpdate.hint = +denied.findOneAndUpdate.tailable = +denied.findOneAndUpdate.comment = true; + + +denied.count = function(self) { + if (self._fields && Object.keys(self._fields).length > 0) { + return 'field selection and slice'; + } + + const keys = Object.keys(denied.count); + let err; + + keys.every(function(option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +}; + +denied.count.slice = +denied.count.batchSize = +denied.count.comment = +denied.count.maxScan = +denied.count.snapshot = +denied.count.tailable = true; diff --git a/node_modules/mquery/lib/utils.js b/node_modules/mquery/lib/utils.js new file mode 100644 index 0000000..63e8284 --- /dev/null +++ b/node_modules/mquery/lib/utils.js @@ -0,0 +1,359 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +const RegExpClone = require('regexp-clone'); + +const specialProperties = ['__proto__', 'constructor', 'prototype']; + +/** + * Clones objects + * + * @param {Object} obj the object to clone + * @param {Object} options + * @return {Object} the cloned object + * @api private + */ + +const clone = exports.clone = function clone(obj, options) { + if (obj === undefined || obj === null) + return obj; + + if (Array.isArray(obj)) + return exports.cloneArray(obj, options); + + if (obj.constructor) { + if (/ObjectI[dD]$/.test(obj.constructor.name)) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.id); + } + + if (obj.constructor.name === 'ReadPreference') { + return new obj.constructor(obj.mode, clone(obj.tags, options)); + } + + if ('Binary' == obj._bsontype && obj.buffer && obj.value) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.value(true), obj.sub_type); + } + + if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name) + return new obj.constructor(+obj); + + if ('RegExp' === obj.constructor.name) + return RegExpClone(obj); + + if ('Buffer' === obj.constructor.name) + return exports.cloneBuffer(obj); + } + + if (isObject(obj)) + return exports.cloneObject(obj, options); + + if (obj.valueOf) + return obj.valueOf(); +}; + +/*! + * ignore + */ + +exports.cloneObject = function cloneObject(obj, options) { + const minimize = options && options.minimize; + const ret = {}; + let hasKeys; + let val; + const keys = Object.keys(obj); + let k; + + for (let i = 0; i < keys.length; ++i) { + k = keys[i]; + // Not technically prototype pollution because this wouldn't merge properties + // onto `Object.prototype`, but avoid properties like __proto__ as a precaution. + if (specialProperties.indexOf(k) !== -1) { + continue; + } + + val = clone(obj[k], options); + + if (!minimize || ('undefined' !== typeof val)) { + hasKeys || (hasKeys = true); + ret[k] = val; + } + } + + return minimize + ? hasKeys && ret + : ret; +}; + +exports.cloneArray = function cloneArray(arr, options) { + const ret = []; + for (let i = 0, l = arr.length; i < l; i++) + ret.push(clone(arr[i], options)); + return ret; +}; + +/** + * process.nextTick helper. + * + * Wraps the given `callback` in a try/catch. If an error is + * caught it will be thrown on nextTick. + * + * node-mongodb-native had a habit of state corruption when + * an error was immediately thrown from within a collection + * method (find, update, etc) callback. + * + * @param {Function} [callback] + * @api private + */ + +exports.tick = function tick(callback) { + if ('function' !== typeof callback) return; + return function() { + // callbacks should always be fired on the next + // turn of the event loop. A side benefit is + // errors thrown from executing the callback + // will not cause drivers state to be corrupted + // which has historically been a problem. + const args = arguments; + soon(function() { + callback.apply(this, args); + }); + }; +}; + +/** + * Merges `from` into `to` without overwriting existing properties. + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +exports.merge = function merge(to, from) { + const keys = Object.keys(from); + + for (const key of keys) { + if (specialProperties.indexOf(key) !== -1) { + continue; + } + if ('undefined' === typeof to[key]) { + to[key] = from[key]; + } else { + if (exports.isObject(from[key])) { + merge(to[key], from[key]); + } else { + to[key] = from[key]; + } + } + } +}; + +/** + * Same as merge but clones the assigned values. + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +exports.mergeClone = function mergeClone(to, from) { + const keys = Object.keys(from); + + for (const key of keys) { + if (specialProperties.indexOf(key) !== -1) { + continue; + } + if ('undefined' === typeof to[key]) { + to[key] = clone(from[key]); + } else { + if (exports.isObject(from[key])) { + mergeClone(to[key], from[key]); + } else { + to[key] = clone(from[key]); + } + } + } +}; + +/** + * Read pref helper (mongo 2.2 drivers support this) + * + * Allows using aliases instead of full preference names: + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * @param {String} pref + */ + +exports.readPref = function readPref(pref) { + switch (pref) { + case 'p': + pref = 'primary'; + break; + case 'pp': + pref = 'primaryPreferred'; + break; + case 's': + pref = 'secondary'; + break; + case 'sp': + pref = 'secondaryPreferred'; + break; + case 'n': + pref = 'nearest'; + break; + } + + return pref; +}; + + +/** + * Read Concern helper (mongo 3.2 drivers support this) + * + * Allows using string to specify read concern level: + * + * local 3.2+ + * available 3.6+ + * majority 3.2+ + * linearizable 3.4+ + * snapshot 4.0+ + * + * @param {String|Object} concern + */ + +exports.readConcern = function readConcern(concern) { + if ('string' === typeof concern) { + switch (concern) { + case 'l': + concern = 'local'; + break; + case 'a': + concern = 'available'; + break; + case 'm': + concern = 'majority'; + break; + case 'lz': + concern = 'linearizable'; + break; + case 's': + concern = 'snapshot'; + break; + } + concern = { level: concern }; + } + return concern; +}; + +/** + * Object.prototype.toString.call helper + */ + +const _toString = Object.prototype.toString; +exports.toString = function(arg) { + return _toString.call(arg); +}; + +/** + * Determines if `arg` is an object. + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @return {Boolean} + */ + +const isObject = exports.isObject = function(arg) { + return '[object Object]' == exports.toString(arg); +}; + +/** + * Determines if `arg` is an array. + * + * @param {Object} + * @return {Boolean} + * @see nodejs utils + */ + +exports.isArray = function(arg) { + return Array.isArray(arg) || + 'object' == typeof arg && '[object Array]' == exports.toString(arg); +}; + +/** + * Object.keys helper + */ + +exports.keys = Object.keys; + +/** + * Basic Object.create polyfill. + * Only one argument is supported. + * + * Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create + */ + +exports.create = 'function' == typeof Object.create + ? Object.create + : create; + +function create(proto) { + if (arguments.length > 1) { + throw new Error('Adding properties is not supported'); + } + + function F() {} + F.prototype = proto; + return new F; +} + +/** + * inheritance + */ + +exports.inherits = function(ctor, superCtor) { + ctor.prototype = exports.create(superCtor.prototype); + ctor.prototype.constructor = ctor; +}; + +/** + * nextTick helper + * compat with node 0.10 which behaves differently than previous versions + */ + +const soon = exports.soon = 'function' == typeof setImmediate + ? setImmediate + : process.nextTick; + +/** + * Clones the contents of a buffer. + * + * @param {Buffer} buff + * @return {Buffer} + */ + +exports.cloneBuffer = function(buff) { + const dupe = Buffer.alloc(buff.length); + buff.copy(dupe, 0, 0, buff.length); + return dupe; +}; + +/** + * Check if this object is an arguments object + * + * @param {Any} v + * @return {Boolean} + */ + +exports.isArgumentsObject = function(v) { + return Object.prototype.toString.call(v) === '[object Arguments]'; +}; diff --git a/node_modules/mquery/node_modules/debug/LICENSE b/node_modules/mquery/node_modules/debug/LICENSE new file mode 100644 index 0000000..658c933 --- /dev/null +++ b/node_modules/mquery/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +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/mquery/node_modules/debug/README.md b/node_modules/mquery/node_modules/debug/README.md new file mode 100644 index 0000000..88dae35 --- /dev/null +++ b/node_modules/mquery/node_modules/debug/README.md @@ -0,0 +1,455 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny JavaScript debugging utility modelled after Node.js core's debugging +technique. Works in Node.js and web browsers. + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example [_app.js_](./examples/node/app.js): + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %o', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example [_worker.js_](./examples/node/worker.js): + +```js +var a = require('debug')('worker:a') + , b = require('debug')('worker:b'); + +function work() { + a('doing lots of uninteresting work'); + setTimeout(work, Math.random() * 1000); +} + +work(); + +function workb() { + b('doing some work'); + setTimeout(workb, Math.random() * 2000); +} + +workb(); +``` + +The `DEBUG` environment variable is then used to enable these based on space or +comma-delimited names. + +Here are some examples: + +screen shot 2017-08-08 at 12 53 04 pm +screen shot 2017-08-08 at 12 53 38 pm +screen shot 2017-08-08 at 12 53 25 pm + +#### Windows command prompt notes + +##### CMD + +On Windows the environment variable is set using the `set` command. + +```cmd +set DEBUG=*,-not_this +``` + +Example: + +```cmd +set DEBUG=* & node app.js +``` + +##### PowerShell (VS Code default) + +PowerShell uses different syntax to set environment variables. + +```cmd +$env:DEBUG = "*,-not_this" +``` + +Example: + +```cmd +$env:DEBUG='app';node app.js +``` + +Then, run the program to be debugged as usual. + +npm script example: +```js + "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", +``` + +## Namespace Colors + +Every debug instance has a color generated for it based on its namespace name. +This helps when visually parsing the debug output to identify which debug instance +a debug line belongs to. + +#### Node.js + +In Node.js, colors are enabled when stderr is a TTY. You also _should_ install +the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, +otherwise debug will only use a small handful of basic colors. + + + +#### Web Browser + +Colors are also enabled on "Web Inspectors" that understand the `%c` formatting +option. These are WebKit web inspectors, Firefox ([since version +31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) +and the Firebug plugin for Firefox (any version). + + + + +## Millisecond diff + +When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + + +When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: + + + + +## Conventions + +If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. + +## Wildcards + +The `*` character may be used as a wildcard. Suppose for example your library has +debuggers named "connect:bodyParser", "connect:compress", "connect:session", +instead of listing all three with +`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do +`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + +You can also exclude specific debuggers by prefixing them with a "-" character. +For example, `DEBUG=*,-connect:*` would include all debuggers except those +starting with "connect:". + +## Environment Variables + +When running through Node.js, you can set a few environment variables that will +change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + +__Note:__ The environment variables beginning with `DEBUG_` end up being +converted into an Options object that gets used with `%o`/`%O` formatters. +See the Node.js documentation for +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +## Formatters + +Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. +Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + + +### Custom formatters + +You can add custom formatters by extending the `debug.formatters` object. +For example, if you wanted to add support for rendering a Buffer as hex with +`%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + + +## Browser Support + +You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), +or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), +if you don't want to build it yourself. + +Debug's enable state is currently persisted by `localStorage`. +Consider the situation shown below where you have `worker:a` and `worker:b`, +and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example [_stdout.js_](./examples/node/stdout.js): + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + +## Extend +You can simply extend debugger +```js +const log = require('debug')('auth'); + +//creates new debug instance with extended namespace +const logSign = log.extend('sign'); +const logLogin = log.extend('login'); + +log('hello'); // auth hello +logSign('hello'); //auth:sign hello +logLogin('hello'); //auth:login hello +``` + +## Set dynamically + +You can also enable debug dynamically by calling the `enable()` method : + +```js +let debug = require('debug'); + +console.log(1, debug.enabled('test')); + +debug.enable('test'); +console.log(2, debug.enabled('test')); + +debug.disable(); +console.log(3, debug.enabled('test')); + +``` + +print : +``` +1 false +2 true +3 false +``` + +Usage : +`enable(namespaces)` +`namespaces` can include modes separated by a colon and wildcards. + +Note that calling `enable()` completely overrides previously set DEBUG variable : + +``` +$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' +=> false +``` + +`disable()` + +Will disable all namespaces. The functions returns the namespaces currently +enabled (and skipped). This can be useful if you want to disable debugging +temporarily without knowing what was enabled to begin with. + +For example: + +```js +let debug = require('debug'); +debug.enable('foo:*,-foo:bar'); +let namespaces = debug.disable(); +debug.enable(namespaces); +``` + +Note: There is no guarantee that the string will be identical to the initial +enable string, but semantically they will be identical. + +## Checking whether a debug target is enabled + +After you've created a debug instance, you can determine whether or not it is +enabled by checking the `enabled` property: + +```javascript +const debug = require('debug')('http'); + +if (debug.enabled) { + // do stuff... +} +``` + +You can also manually toggle this property to force the debug instance to be +enabled or disabled. + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> + +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/mquery/node_modules/debug/package.json b/node_modules/mquery/node_modules/debug/package.json new file mode 100644 index 0000000..b7d70ac --- /dev/null +++ b/node_modules/mquery/node_modules/debug/package.json @@ -0,0 +1,59 @@ +{ + "name": "debug", + "version": "4.3.2", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "files": [ + "src", + "LICENSE", + "README.md" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne ", + "Josh Junon " + ], + "license": "MIT", + "scripts": { + "lint": "xo", + "test": "npm run test:node && npm run test:browser && npm run lint", + "test:node": "istanbul cover _mocha -- test.js", + "test:browser": "karma start --single-run", + "test:coverage": "cat ./coverage/lcov.info | coveralls" + }, + "dependencies": { + "ms": "2.1.2" + }, + "devDependencies": { + "brfs": "^2.0.1", + "browserify": "^16.2.3", + "coveralls": "^3.0.2", + "istanbul": "^0.4.5", + "karma": "^3.1.4", + "karma-browserify": "^6.0.0", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "mocha": "^5.2.0", + "mocha-lcov-reporter": "^1.2.0", + "xo": "^0.23.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "engines": { + "node": ">=6.0" + } +} diff --git a/node_modules/mquery/node_modules/debug/src/browser.js b/node_modules/mquery/node_modules/debug/src/browser.js new file mode 100644 index 0000000..cd0fc35 --- /dev/null +++ b/node_modules/mquery/node_modules/debug/src/browser.js @@ -0,0 +1,269 @@ +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; diff --git a/node_modules/mquery/node_modules/debug/src/common.js b/node_modules/mquery/node_modules/debug/src/common.js new file mode 100644 index 0000000..50ce292 --- /dev/null +++ b/node_modules/mquery/node_modules/debug/src/common.js @@ -0,0 +1,274 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; diff --git a/node_modules/mquery/node_modules/debug/src/index.js b/node_modules/mquery/node_modules/debug/src/index.js new file mode 100644 index 0000000..bf4c57f --- /dev/null +++ b/node_modules/mquery/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/mquery/node_modules/debug/src/node.js b/node_modules/mquery/node_modules/debug/src/node.js new file mode 100644 index 0000000..79bc085 --- /dev/null +++ b/node_modules/mquery/node_modules/debug/src/node.js @@ -0,0 +1,263 @@ +/** + * Module dependencies. + */ + +const tty = require('tty'); +const util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; diff --git a/node_modules/mquery/node_modules/ms/index.js b/node_modules/mquery/node_modules/ms/index.js new file mode 100644 index 0000000..c4498bc --- /dev/null +++ b/node_modules/mquery/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/mquery/node_modules/ms/license.md b/node_modules/mquery/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/mquery/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/mquery/node_modules/ms/package.json b/node_modules/mquery/node_modules/ms/package.json new file mode 100644 index 0000000..eea666e --- /dev/null +++ b/node_modules/mquery/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.1.2", + "description": "Tiny millisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.12.1", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1" + } +} diff --git a/node_modules/mquery/node_modules/ms/readme.md b/node_modules/mquery/node_modules/ms/readme.md new file mode 100644 index 0000000..9a1996b --- /dev/null +++ b/node_modules/mquery/node_modules/ms/readme.md @@ -0,0 +1,60 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/mquery/package.json b/node_modules/mquery/package.json new file mode 100644 index 0000000..808727c --- /dev/null +++ b/node_modules/mquery/package.json @@ -0,0 +1,40 @@ +{ + "name": "mquery", + "version": "4.0.0", + "description": "Expressive query building for MongoDB", + "main": "lib/mquery.js", + "scripts": { + "test": "mocha test/index.js test/*.test.js", + "fix-lint": "eslint . --fix", + "lint": "eslint ." + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mquery.git" + }, + "engines": { + "node": ">=12.0.0" + }, + "dependencies": { + "debug": "4.x", + "regexp-clone": "^1.0.0", + "sliced": "1.0.1" + }, + "devDependencies": { + "eslint": "5.x", + "eslint-plugin-mocha-no-only": "1.1.0", + "mocha": "9.x", + "mongodb": "4.x" + }, + "bugs": { + "url": "https://github.com/aheckmann/mquery/issues/new" + }, + "author": "Aaron Heckmann ", + "license": "MIT", + "keywords": [ + "mongodb", + "query", + "builder" + ], + "homepage": "https://github.com/aheckmann/mquery/" +} diff --git a/node_modules/mquery/test/.eslintrc.yml b/node_modules/mquery/test/.eslintrc.yml new file mode 100644 index 0000000..7e104db --- /dev/null +++ b/node_modules/mquery/test/.eslintrc.yml @@ -0,0 +1,2 @@ +env: + mocha: true \ No newline at end of file diff --git a/node_modules/mquery/test/collection/browser.js b/node_modules/mquery/test/collection/browser.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mquery/test/collection/mongo.js b/node_modules/mquery/test/collection/mongo.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mquery/test/collection/node.js b/node_modules/mquery/test/collection/node.js new file mode 100644 index 0000000..a5eb875 --- /dev/null +++ b/node_modules/mquery/test/collection/node.js @@ -0,0 +1,29 @@ +'use strict'; + +const assert = require('assert'); +const mongo = require('mongodb'); + +const uri = process.env.MQUERY_URI || 'mongodb://localhost/mquery'; +let client; +let db; + +exports.getCollection = function(cb) { + mongo.MongoClient.connect(uri, function(err, _client) { + assert.ifError(err); + client = _client; + db = client.db(); + + const collection = db.collection('stuff'); + + // clean test db before starting + db.dropDatabase(function() { + cb(null, collection); + }); + }); +}; + +exports.dropCollection = function(cb) { + db.dropDatabase(function() { + client.close(cb); + }); +}; diff --git a/node_modules/mquery/test/env.js b/node_modules/mquery/test/env.js new file mode 100644 index 0000000..0bf8cf9 --- /dev/null +++ b/node_modules/mquery/test/env.js @@ -0,0 +1,22 @@ +'use strict'; + +const env = require('../').env; + +console.log('environment: %s', env.type); + +let col; +switch (env.type) { + case 'node': + col = require('./collection/node'); + break; + case 'mongo': + col = require('./collection/mongo'); + break; + case 'browser': + col = require('./collection/browser'); + break; + default: + throw new Error('missing collection implementation for environment: ' + env.type); +} + +module.exports = exports = col; diff --git a/node_modules/mquery/test/index.js b/node_modules/mquery/test/index.js new file mode 100644 index 0000000..1f0524b --- /dev/null +++ b/node_modules/mquery/test/index.js @@ -0,0 +1,2956 @@ +'use strict'; + +const mquery = require('../'); +const assert = require('assert'); + +/* global Map */ + +describe('mquery', function() { + let col; + + before(function(done) { + // get the env specific collection interface + require('./env').getCollection(function(err, collection) { + assert.ifError(err); + col = collection; + done(); + }); + }); + + after(function(done) { + require('./env').dropCollection(done); + }); + + describe('mquery', function() { + it('is a function', function() { + assert.equal('function', typeof mquery); + }); + it('creates instances with the `new` keyword', function() { + assert.ok(mquery() instanceof mquery); + }); + describe('defaults', function() { + it('are set', function() { + const m = mquery(); + assert.strictEqual(undefined, m.op); + assert.deepEqual({}, m.options); + }); + }); + describe('criteria', function() { + it('if collection-like is used as collection', function() { + const m = mquery(col); + assert.equal(col, m._collection.collection); + }); + it('non-collection-like is used as criteria', function() { + const m = mquery({ works: true }); + assert.ok(!m._collection); + assert.deepEqual({ works: true }, m._conditions); + }); + }); + describe('options', function() { + it('are merged when passed', function() { + let m; + m = mquery(col, { w: 'majority' }); + assert.deepEqual({ w: 'majority' }, m.options); + m = mquery({ name: 'mquery' }, { w: 'majority' }); + assert.deepEqual({ w: 'majority' }, m.options); + }); + }); + }); + + describe('toConstructor', function() { + it('creates subclasses of mquery', function() { + const opts = { safe: { w: 'majority' }, readPreference: 'p' }; + const match = { name: 'test', count: { $gt: 101 } }; + const select = { name: 1, count: 0 }; + const update = { $set: { x: true } }; + const path = 'street'; + + const q = mquery().setOptions(opts); + q.where(match); + q.select(select); + q.updateOne(update); + q.where(path); + q.find(); + + const M = q.toConstructor(); + const m = M(); + + assert.ok(m instanceof mquery); + assert.deepEqual(opts, m.options); + assert.deepEqual(match, m._conditions); + assert.deepEqual(select, m._fields); + assert.deepEqual(update, m._update); + assert.equal(path, m._path); + assert.equal('find', m.op); + }); + }); + + describe('setOptions', function() { + it('calls associated methods', function() { + const m = mquery(); + assert.equal(m._collection, null); + m.setOptions({ collection: col }); + assert.equal(m._collection.collection, col); + }); + it('directly sets option when no method exists', function() { + const m = mquery(); + assert.equal(m.options.woot, null); + m.setOptions({ woot: 'yay' }); + assert.equal(m.options.woot, 'yay'); + }); + it('is chainable', function() { + const m = mquery(); + let n; + + n = m.setOptions(); + assert.equal(m, n); + n = m.setOptions({ x: 1 }); + assert.equal(m, n); + }); + }); + + describe('collection', function() { + it('sets the _collection', function() { + const m = mquery(); + m.collection(col); + assert.equal(m._collection.collection, col); + }); + it('is chainable', function() { + const m = mquery(); + const n = m.collection(col); + assert.equal(m, n); + }); + }); + + describe('$where', function() { + it('sets the $where condition', function() { + const m = mquery(); + function go() {} + m.$where(go); + assert.ok(go === m._conditions.$where); + }); + it('is chainable', function() { + const m = mquery(); + const n = m.$where('x'); + assert.equal(m, n); + }); + }); + + describe('where', function() { + it('without arguments', function() { + const m = mquery(); + m.where(); + assert.deepEqual({}, m._conditions); + }); + it('with non-string/object argument', function() { + const m = mquery(); + + assert.throws(function() { + m.where([]); + }, /path must be a string or object/); + }); + describe('with one argument', function() { + it('that is an object', function() { + const m = mquery(); + m.where({ name: 'flawed' }); + assert.strictEqual(m._conditions.name, 'flawed'); + }); + it('that is a query', function() { + const m = mquery({ name: 'first' }); + const n = mquery({ name: 'changed' }); + m.where(n); + assert.strictEqual(m._conditions.name, 'changed'); + }); + it('that is a string', function() { + const m = mquery(); + m.where('name'); + assert.equal('name', m._path); + assert.strictEqual(m._conditions.name, undefined); + }); + }); + it('with two arguments', function() { + const m = mquery(); + m.where('name', 'The Great Pumpkin'); + assert.equal('name', m._path); + assert.strictEqual(m._conditions.name, 'The Great Pumpkin'); + }); + it('is chainable', function() { + const m = mquery(); + + let n = m.where('x', 'y'); + assert.equal(m, n); + n = m.where(); + assert.equal(m, n); + }); + }); + describe('equals', function() { + it('must be called after where()', function() { + const m = mquery(); + assert.throws(function() { + m.equals(); + }, /must be used after where/); + }); + it('sets value of path set with where()', function() { + const m = mquery(); + m.where('age').equals(1000); + assert.deepEqual({ age: 1000 }, m._conditions); + }); + it('is chainable', function() { + const m = mquery(); + const n = m.where('x').equals(3); + assert.equal(m, n); + }); + }); + describe('eq', function() { + it('is alias of equals', function() { + const m = mquery(); + m.where('age').eq(1000); + assert.deepEqual({ age: 1000 }, m._conditions); + }); + }); + describe('or', function() { + it('pushes onto the internal $or condition', function() { + const m = mquery(); + m.or({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{ 'Nightmare Before Christmas': true }], m._conditions.$or); + }); + it('allows passing arrays', function() { + const m = mquery(); + const arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.or(arg); + assert.deepEqual(arg, m._conditions.$or); + }); + it('allows calling multiple times', function() { + const m = mquery(); + const arg = [{ looper: true }, { x: 1 }]; + m.or(arg); + m.or({ y: 1 }); + m.or([{ w: 'oo' }, { z: 'oo' }]); + assert.deepEqual([{ looper: true }, { x: 1 }, { y: 1 }, { w: 'oo' }, { z: 'oo' }], m._conditions.$or); + }); + it('is chainable', function() { + const m = mquery(); + m.or({ o: 'k' }).where('name', 'table'); + assert.deepEqual({ name: 'table', $or: [{ o: 'k' }] }, m._conditions); + }); + }); + + describe('nor', function() { + it('pushes onto the internal $nor condition', function() { + const m = mquery(); + m.nor({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{ 'Nightmare Before Christmas': true }], m._conditions.$nor); + }); + it('allows passing arrays', function() { + const m = mquery(); + const arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.nor(arg); + assert.deepEqual(arg, m._conditions.$nor); + }); + it('allows calling multiple times', function() { + const m = mquery(); + const arg = [{ looper: true }, { x: 1 }]; + m.nor(arg); + m.nor({ y: 1 }); + m.nor([{ w: 'oo' }, { z: 'oo' }]); + assert.deepEqual([{ looper: true }, { x: 1 }, { y: 1 }, { w: 'oo' }, { z: 'oo' }], m._conditions.$nor); + }); + it('is chainable', function() { + const m = mquery(); + m.nor({ o: 'k' }).where('name', 'table'); + assert.deepEqual({ name: 'table', $nor: [{ o: 'k' }] }, m._conditions); + }); + }); + + describe('and', function() { + it('pushes onto the internal $and condition', function() { + const m = mquery(); + m.and({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{ 'Nightmare Before Christmas': true }], m._conditions.$and); + }); + it('allows passing arrays', function() { + const m = mquery(); + const arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.and(arg); + assert.deepEqual(arg, m._conditions.$and); + }); + it('allows calling multiple times', function() { + const m = mquery(); + const arg = [{ looper: true }, { x: 1 }]; + m.and(arg); + m.and({ y: 1 }); + m.and([{ w: 'oo' }, { z: 'oo' }]); + assert.deepEqual([{ looper: true }, { x: 1 }, { y: 1 }, { w: 'oo' }, { z: 'oo' }], m._conditions.$and); + }); + it('is chainable', function() { + const m = mquery(); + m.and({ o: 'k' }).where('name', 'table'); + assert.deepEqual({ name: 'table', $and: [{ o: 'k' }] }, m._conditions); + }); + }); + + function generalCondition(type) { + return function() { + it('accepts 2 args', function() { + const m = mquery()[type]('count', 3); + const check = {}; + check['$' + type] = 3; + assert.deepEqual(m._conditions.count, check); + }); + it('uses previously set `where` path if 1 arg passed', function() { + const m = mquery().where('count')[type](3); + const check = {}; + check['$' + type] = 3; + assert.deepEqual(m._conditions.count, check); + }); + it('throws if 1 arg was passed but no previous `where` was used', function() { + assert.throws(function() { + mquery()[type](3); + }, /must be used after where/); + }); + it('is chainable', function() { + const m = mquery().where('count')[type](3).where('x', 8); + const check = { x: 8, count: {} }; + check.count['$' + type] = 3; + assert.deepEqual(m._conditions, check); + }); + it('overwrites previous value', function() { + const m = mquery().where('count')[type](3)[type](8); + const check = {}; + check['$' + type] = 8; + assert.deepEqual(m._conditions.count, check); + }); + }; + } + + 'gt gte lt lte ne in nin regex size maxDistance minDistance'.split(' ').forEach(function(type) { + describe(type, generalCondition(type)); + }); + + describe('mod', function() { + describe('with 1 argument', function() { + it('requires a previous where()', function() { + assert.throws(function() { + mquery().mod([30, 10]); + }, /must be used after where/); + }); + it('works', function() { + const m = mquery().where('madmen').mod([10, 20]); + assert.deepEqual(m._conditions, { madmen: { $mod: [10, 20] } }); + }); + }); + + describe('with 2 arguments and second is non-Array', function() { + it('requires a previous where()', function() { + assert.throws(function() { + mquery().mod('x', 10); + }, /must be used after where/); + }); + it('works', function() { + const m = mquery().where('madmen').mod(10, 20); + assert.deepEqual(m._conditions, { madmen: { $mod: [10, 20] } }); + }); + }); + + it('with 2 arguments and second is an array', function() { + const m = mquery().mod('madmen', [10, 20]); + assert.deepEqual(m._conditions, { madmen: { $mod: [10, 20] } }); + }); + + it('with 3 arguments', function() { + const m = mquery().mod('madmen', 10, 20); + assert.deepEqual(m._conditions, { madmen: { $mod: [10, 20] } }); + }); + + it('is chainable', function() { + const m = mquery().mod('madmen', 10, 20).where('x', 8); + const check = { madmen: { $mod: [10, 20] }, x: 8 }; + assert.deepEqual(m._conditions, check); + }); + }); + + describe('exists', function() { + it('with 0 args', function() { + it('throws if not used after where()', function() { + assert.throws(function() { + mquery().exists(); + }, /must be used after where/); + }); + it('works', function() { + const m = mquery().where('name').exists(); + const check = { name: { $exists: true } }; + assert.deepEqual(m._conditions, check); + }); + }); + + describe('with 1 arg', function() { + describe('that is boolean', function() { + it('throws if not used after where()', function() { + assert.throws(function() { + mquery().exists(); + }, /must be used after where/); + }); + it('works', function() { + const m = mquery().exists('name', false); + const check = { name: { $exists: false } }; + assert.deepEqual(m._conditions, check); + }); + }); + describe('that is not boolean', function() { + it('sets the value to `true`', function() { + const m = mquery().where('name').exists('yummy'); + const check = { yummy: { $exists: true } }; + assert.deepEqual(m._conditions, check); + }); + }); + }); + + describe('with 2 args', function() { + it('works', function() { + const m = mquery().exists('yummy', false); + const check = { yummy: { $exists: false } }; + assert.deepEqual(m._conditions, check); + }); + }); + + it('is chainable', function() { + const m = mquery().where('name').exists().find({ x: 1 }); + const check = { name: { $exists: true }, x: 1 }; + assert.deepEqual(m._conditions, check); + }); + }); + + describe('elemMatch', function() { + describe('with null/undefined first argument', function() { + assert.throws(function() { + mquery().elemMatch(); + }, /Invalid argument/); + assert.throws(function() { + mquery().elemMatch(null); + }, /Invalid argument/); + assert.doesNotThrow(function() { + mquery().elemMatch('', {}); + }); + }); + + describe('with 1 argument', function() { + it('throws if not a function or object', function() { + assert.throws(function() { + mquery().elemMatch([]); + }, /Invalid argument/); + }); + + describe('that is an object', function() { + it('throws if no previous `where` was used', function() { + assert.throws(function() { + mquery().elemMatch({}); + }, /must be used after where/); + }); + it('works', function() { + const m = mquery().where('comment').elemMatch({ author: 'joe', votes: { $gte: 3 } }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: { $gte: 3 } } } }, m._conditions); + }); + }); + describe('that is a function', function() { + it('throws if no previous `where` was used', function() { + assert.throws(function() { + mquery().elemMatch(function() {}); + }, /must be used after where/); + }); + it('works', function() { + const m = mquery().where('comment').elemMatch(function(query) { + query.where({ author: 'joe', votes: { $gte: 3 } }); + }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: { $gte: 3 } } } }, m._conditions); + }); + }); + }); + + describe('with 2 arguments', function() { + describe('and the 2nd is an object', function() { + it('works', function() { + const m = mquery().elemMatch('comment', { author: 'joe', votes: { $gte: 3 } }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: { $gte: 3 } } } }, m._conditions); + }); + }); + describe('and the 2nd is a function', function() { + it('works', function() { + const m = mquery().elemMatch('comment', function(query) { + query.where({ author: 'joe', votes: { $gte: 3 } }); + }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: { $gte: 3 } } } }, m._conditions); + }); + }); + it('and the 2nd is not a function or object', function() { + assert.throws(function() { + mquery().elemMatch('comment', []); + }, /Invalid argument/); + }); + }); + }); + + describe('within', function() { + it('is chainable', function() { + const m = mquery(); + assert.equal(m.where('a').within(), m); + }); + describe('when called with arguments', function() { + it('must follow where()', function() { + assert.throws(function() { + mquery().within([]); + }, /must be used after where/); + }); + + describe('of length 1', function() { + it('throws if not a recognized shape', function() { + assert.throws(function() { + mquery().where('loc').within({}); + }, /Invalid argument/); + assert.throws(function() { + mquery().where('loc').within(null); + }, /Invalid argument/); + }); + it('delegates to circle when center exists', function() { + const m = mquery().where('loc').within({ center: [10, 10], radius: 3 }); + assert.deepEqual({ $geoWithin: { $center: [[10, 10], 3] } }, m._conditions.loc); + }); + it('delegates to box when exists', function() { + const m = mquery().where('loc').within({ box: [[10, 10], [11, 14]] }); + assert.deepEqual({ $geoWithin: { $box: [[10, 10], [11, 14]] } }, m._conditions.loc); + }); + it('delegates to polygon when exists', function() { + const m = mquery().where('loc').within({ polygon: [[10, 10], [11, 14], [10, 9]] }); + assert.deepEqual({ $geoWithin: { $polygon: [[10, 10], [11, 14], [10, 9]] } }, m._conditions.loc); + }); + it('delegates to geometry when exists', function() { + const m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10, 10], [11, 14], [10, 9]] }); + assert.deepEqual({ $geoWithin: { $geometry: { type: 'Polygon', coordinates: [[10, 10], [11, 14], [10, 9]] } } }, m._conditions.loc); + }); + }); + + describe('of length 2', function() { + it('delegates to box()', function() { + const m = mquery().where('loc').within([1, 2], [2, 5]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1, 2], [2, 5]] } }); + }); + }); + + describe('of length > 2', function() { + it('delegates to polygon()', function() { + const m = mquery().where('loc').within([1, 2], [2, 5], [2, 4], [1, 3]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $polygon: [[1, 2], [2, 5], [2, 4], [1, 3]] } }); + }); + }); + }); + }); + + describe('geoWithin', function() { + before(function() { + mquery.use$geoWithin = false; + }); + after(function() { + mquery.use$geoWithin = true; + }); + describe('when called with arguments', function() { + describe('of length 1', function() { + it('delegates to circle when center exists', function() { + const m = mquery().where('loc').within({ center: [10, 10], radius: 3 }); + assert.deepEqual({ $within: { $center: [[10, 10], 3] } }, m._conditions.loc); + }); + it('delegates to box when exists', function() { + const m = mquery().where('loc').within({ box: [[10, 10], [11, 14]] }); + assert.deepEqual({ $within: { $box: [[10, 10], [11, 14]] } }, m._conditions.loc); + }); + it('delegates to polygon when exists', function() { + const m = mquery().where('loc').within({ polygon: [[10, 10], [11, 14], [10, 9]] }); + assert.deepEqual({ $within: { $polygon: [[10, 10], [11, 14], [10, 9]] } }, m._conditions.loc); + }); + it('delegates to geometry when exists', function() { + const m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10, 10], [11, 14], [10, 9]] }); + assert.deepEqual({ $within: { $geometry: { type: 'Polygon', coordinates: [[10, 10], [11, 14], [10, 9]] } } }, m._conditions.loc); + }); + }); + + describe('of length 2', function() { + it('delegates to box()', function() { + const m = mquery().where('loc').within([1, 2], [2, 5]); + assert.deepEqual(m._conditions.loc, { $within: { $box: [[1, 2], [2, 5]] } }); + }); + }); + + describe('of length > 2', function() { + it('delegates to polygon()', function() { + const m = mquery().where('loc').within([1, 2], [2, 5], [2, 4], [1, 3]); + assert.deepEqual(m._conditions.loc, { $within: { $polygon: [[1, 2], [2, 5], [2, 4], [1, 3]] } }); + }); + }); + }); + }); + + describe('box', function() { + describe('with 1 argument', function() { + it('throws', function() { + assert.throws(function() { + mquery().box('sometihng'); + }, /Invalid argument/); + }); + }); + describe('with > 3 arguments', function() { + it('throws', function() { + assert.throws(function() { + mquery().box(1, 2, 3, 4); + }, /Invalid argument/); + }); + }); + + describe('with 2 arguments', function() { + it('throws if not used after where()', function() { + assert.throws(function() { + mquery().box([], []); + }, /must be used after where/); + }); + it('works', function() { + const m = mquery().where('loc').box([1, 2], [3, 4]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1, 2], [3, 4]] } }); + }); + }); + + describe('with 3 arguments', function() { + it('works', function() { + const m = mquery().box('loc', [1, 2], [3, 4]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1, 2], [3, 4]] } }); + }); + }); + }); + + describe('polygon', function() { + describe('when first argument is not a string', function() { + it('throws if not used after where()', function() { + assert.throws(function() { + mquery().polygon({}); + }, /must be used after where/); + + assert.doesNotThrow(function() { + mquery().where('loc').polygon([1, 2], [2, 3], [3, 6]); + }); + }); + + it('assigns arguments to within polygon condition', function() { + const m = mquery().where('loc').polygon([1, 2], [2, 3], [3, 6]); + assert.deepEqual(m._conditions, { loc: { $geoWithin: { $polygon: [[1, 2], [2, 3], [3, 6]] } } }); + }); + }); + + describe('when first arg is a string', function() { + it('assigns remaining arguments to within polygon condition', function() { + const m = mquery().polygon('loc', [1, 2], [2, 3], [3, 6]); + assert.deepEqual(m._conditions, { loc: { $geoWithin: { $polygon: [[1, 2], [2, 3], [3, 6]] } } }); + }); + }); + }); + + describe('circle', function() { + describe('with one arg', function() { + it('must follow where()', function() { + assert.throws(function() { + mquery().circle('x'); + }, /must be used after where/); + assert.doesNotThrow(function() { + mquery().where('loc').circle({ center: [0, 0], radius: 3 }); + }); + }); + it('works', function() { + const m = mquery().where('loc').circle({ center: [0, 0], radius: 3 }); + assert.deepEqual(m._conditions, { loc: { $geoWithin: { $center: [[0, 0], 3] } } }); + }); + }); + describe('with 3 args', function() { + it('throws', function() { + assert.throws(function() { + mquery().where('loc').circle(1, 2, 3); + }, /Invalid argument/); + }); + }); + describe('requires radius and center', function() { + assert.throws(function() { + mquery().circle('loc', { center: 1 }); + }, /center and radius are required/); + assert.throws(function() { + mquery().circle('loc', { radius: 1 }); + }, /center and radius are required/); + assert.doesNotThrow(function() { + mquery().circle('loc', { center: [1, 2], radius: 1 }); + }); + }); + }); + + describe('geometry', function() { + // within + intersects + const point = { type: 'Point', coordinates: [[0, 0], [1, 1]] }; + + it('must be called after within or intersects', function(done) { + assert.throws(function() { + mquery().where('a').geometry(point); + }, /must come after/); + + assert.doesNotThrow(function() { + mquery().where('a').within().geometry(point); + }); + + assert.doesNotThrow(function() { + mquery().where('a').intersects().geometry(point); + }); + + done(); + }); + + describe('when called with one argument', function() { + describe('after within()', function() { + it('and arg quacks like geoJSON', function(done) { + const m = mquery().where('a').within().geometry(point); + assert.deepEqual({ a: { $geoWithin: { $geometry: point } } }, m._conditions); + done(); + }); + }); + + describe('after intersects()', function() { + it('and arg quacks like geoJSON', function(done) { + const m = mquery().where('a').intersects().geometry(point); + assert.deepEqual({ a: { $geoIntersects: { $geometry: point } } }, m._conditions); + done(); + }); + }); + + it('and arg does not quack like geoJSON', function(done) { + assert.throws(function() { + mquery().where('b').within().geometry({ type: 1, coordinates: 2 }); + }, /Invalid argument/); + done(); + }); + }); + + describe('when called with zero arguments', function() { + it('throws', function(done) { + assert.throws(function() { + mquery().where('a').within().geometry(); + }, /Invalid argument/); + + done(); + }); + }); + + describe('when called with more than one arguments', function() { + it('throws', function(done) { + assert.throws(function() { + mquery().where('a').within().geometry({ type: 'a', coordinates: [] }, 2); + }, /Invalid argument/); + done(); + }); + }); + }); + + describe('intersects', function() { + it('must be used after where()', function(done) { + const m = mquery(); + assert.throws(function() { + m.intersects(); + }, /must be used after where/); + done(); + }); + + it('sets geo comparison to "$intersects"', function(done) { + const n = mquery().where('a').intersects(); + assert.equal('$geoIntersects', n._geoComparison); + done(); + }); + + it('is chainable', function() { + const m = mquery(); + assert.equal(m.where('a').intersects(), m); + }); + + it('calls geometry if argument quacks like geojson', function(done) { + const m = mquery(); + const o = { type: 'LineString', coordinates: [[0, 1], [3, 40]] }; + let ran = false; + + m.geometry = function(arg) { + ran = true; + assert.deepEqual(o, arg); + }; + + m.where('a').intersects(o); + assert.ok(ran); + + done(); + }); + + it('throws if argument is not geometry-like', function(done) { + const m = mquery().where('a'); + + assert.throws(function() { + m.intersects(null); + }, /Invalid argument/); + + assert.throws(function() { + m.intersects(undefined); + }, /Invalid argument/); + + assert.throws(function() { + m.intersects(false); + }, /Invalid argument/); + + assert.throws(function() { + m.intersects({}); + }, /Invalid argument/); + + assert.throws(function() { + m.intersects([]); + }, /Invalid argument/); + + assert.throws(function() { + m.intersects(function() {}); + }, /Invalid argument/); + + assert.throws(function() { + m.intersects(NaN); + }, /Invalid argument/); + + done(); + }); + }); + + describe('near', function() { + // near nearSphere + describe('with 0 args', function() { + it('is compatible with geometry()', function(done) { + const q = mquery().where('x').near().geometry({ type: 'Point', coordinates: [180, 11] }); + assert.deepEqual({ $near: { $geometry: { type: 'Point', coordinates: [180, 11] } } }, q._conditions.x); + done(); + }); + }); + + describe('with 1 arg', function() { + it('throws if not used after where()', function() { + assert.throws(function() { + mquery().near(1); + }, /must be used after where/); + }); + it('does not throw if used after where()', function() { + assert.doesNotThrow(function() { + mquery().where('loc').near({ center: [1, 1] }); + }); + }); + }); + describe('with > 2 args', function() { + it('throws', function() { + assert.throws(function() { + mquery().near(1, 2, 3); + }, /Invalid argument/); + }); + }); + + it('creates $geometry args for GeoJSON', function() { + const m = mquery().where('loc').near({ center: { type: 'Point', coordinates: [10, 10] } }); + assert.deepEqual({ $near: { $geometry: { type: 'Point', coordinates: [10, 10] } } }, m._conditions.loc); + }); + + it('expects `center`', function() { + assert.throws(function() { + mquery().near('loc', { maxDistance: 3 }); + }, /center is required/); + assert.doesNotThrow(function() { + mquery().near('loc', { center: [3, 4] }); + }); + }); + + it('accepts spherical conditions', function() { + const m = mquery().where('loc').near({ center: [1, 2], spherical: true }); + assert.deepEqual(m._conditions, { loc: { $nearSphere: [1, 2] } }); + }); + + it('is non-spherical by default', function() { + const m = mquery().where('loc').near({ center: [1, 2] }); + assert.deepEqual(m._conditions, { loc: { $near: [1, 2] } }); + }); + + it('supports maxDistance', function() { + const m = mquery().where('loc').near({ center: [1, 2], maxDistance: 4 }); + assert.deepEqual(m._conditions, { loc: { $near: [1, 2], $maxDistance: 4 } }); + }); + + it('supports minDistance', function() { + const m = mquery().where('loc').near({ center: [1, 2], minDistance: 4 }); + assert.deepEqual(m._conditions, { loc: { $near: [1, 2], $minDistance: 4 } }); + }); + + it('is chainable', function() { + const m = mquery().where('loc').near({ center: [1, 2], maxDistance: 4 }).find({ x: 1 }); + assert.deepEqual(m._conditions, { loc: { $near: [1, 2], $maxDistance: 4 }, x: 1 }); + }); + + describe('supports passing GeoJSON, gh-13', function() { + it('with center', function() { + const m = mquery().where('loc').near({ + center: { type: 'Point', coordinates: [1, 1] }, + maxDistance: 2 + }); + + const expect = { + loc: { + $near: { + $geometry: { + type: 'Point', + coordinates: [1, 1] + }, + $maxDistance: 2 + } + } + }; + + assert.deepEqual(m._conditions, expect); + }); + }); + }); + + // fields + + describe('select', function() { + describe('with 0 args', function() { + it('is chainable', function() { + const m = mquery(); + assert.equal(m, m.select()); + }); + }); + + it('accepts an object', function() { + const o = { x: 1, y: 1 }; + const m = mquery().select(o); + assert.deepEqual(m._fields, o); + }); + + it('accepts a string', function() { + const o = 'x -y'; + const m = mquery().select(o); + assert.deepEqual(m._fields, { x: 1, y: 0 }); + }); + + it('does accept an array', function() { + const o = ['x', '-y']; + const m = mquery().select(o); + assert.deepEqual(m._fields, { x: 1, y: 0 }); + }); + + it('merges previous arguments', function() { + const o = { x: 1, y: 0, a: 1 }; + const m = mquery().select(o); + m.select('z -u w').select({ x: 0 }); + assert.deepEqual(m._fields, { + x: 0, + y: 0, + z: 1, + u: 0, + w: 1, + a: 1 + }); + }); + + it('rejects non-string, object, arrays', function() { + assert.throws(function() { + mquery().select(function() {}); + }, /Invalid select\(\) argument/); + }); + + it('accepts arguments objects', function() { + const m = mquery(); + function t() { + m.select(arguments); + assert.deepEqual(m._fields, { x: 1, y: 0 }); + } + t('x', '-y'); + }); + + noDistinct('select'); + }); + + describe('selected', function() { + it('returns true when fields have been selected', function(done) { + let m; + + m = mquery().select({ name: 1 }); + assert.ok(m.selected()); + + m = mquery().select('name'); + assert.ok(m.selected()); + + done(); + }); + + it('returns false when no fields have been selected', function(done) { + const m = mquery(); + assert.strictEqual(false, m.selected()); + done(); + }); + }); + + describe('selectedInclusively', function() { + describe('returns false', function() { + it('when no fields have been selected', function(done) { + assert.strictEqual(false, mquery().selectedInclusively()); + assert.equal(false, mquery().select({}).selectedInclusively()); + done(); + }); + it('when any fields have been excluded', function(done) { + assert.strictEqual(false, mquery().select('-name').selectedInclusively()); + assert.strictEqual(false, mquery().select({ name: 0 }).selectedInclusively()); + assert.strictEqual(false, mquery().select('name bio -_id').selectedInclusively()); + assert.strictEqual(false, mquery().select({ name: 1, _id: 0 }).selectedInclusively()); + done(); + }); + it('when using $meta', function(done) { + assert.strictEqual(false, mquery().select({ name: { $meta: 'textScore' } }).selectedInclusively()); + done(); + }); + }); + + describe('returns true', function() { + it('when fields have been included', function(done) { + assert.equal(true, mquery().select('name').selectedInclusively()); + assert.equal(true, mquery().select({ name: 1 }).selectedInclusively()); + done(); + }); + }); + }); + + describe('selectedExclusively', function() { + describe('returns false', function() { + it('when no fields have been selected', function(done) { + assert.equal(false, mquery().selectedExclusively()); + assert.equal(false, mquery().select({}).selectedExclusively()); + done(); + }); + it('when fields have only been included', function(done) { + assert.equal(false, mquery().select('name').selectedExclusively()); + assert.equal(false, mquery().select({ name: 1 }).selectedExclusively()); + done(); + }); + }); + + describe('returns true', function() { + it('when any field has been excluded', function(done) { + assert.equal(true, mquery().select('-name').selectedExclusively()); + assert.equal(true, mquery().select({ name: 0 }).selectedExclusively()); + assert.equal(true, mquery().select('-_id').selectedExclusively()); + assert.strictEqual(true, mquery().select('name bio -_id').selectedExclusively()); + assert.strictEqual(true, mquery().select({ name: 1, _id: 0 }).selectedExclusively()); + done(); + }); + }); + }); + + describe('slice', function() { + describe('with 0 args', function() { + it('is chainable', function() { + const m = mquery(); + assert.equal(m, m.slice()); + }); + it('is a noop', function() { + const m = mquery().slice(); + assert.deepEqual(m._fields, undefined); + }); + }); + + describe('with 1 arg', function() { + it('throws if not called after where()', function() { + assert.throws(function() { + mquery().slice(1); + }, /must be used after where/); + assert.doesNotThrow(function() { + mquery().where('a').slice(1); + }); + }); + it('that is a number', function() { + const query = mquery(); + query.where('collection').slice(5); + assert.deepEqual(query._fields, { collection: { $slice: 5 } }); + }); + it('that is an array', function() { + const query = mquery(); + query.where('collection').slice([5, 10]); + assert.deepEqual(query._fields, { collection: { $slice: [5, 10] } }); + }); + it('that is an object', function() { + const query = mquery(); + query.slice({ collection: [5, 10] }); + assert.deepEqual(query._fields, { collection: { $slice: [5, 10] } }); + }); + }); + + describe('with 2 args', function() { + describe('and first is a number', function() { + it('throws if not called after where', function() { + assert.throws(function() { + mquery().slice(2, 3); + }, /must be used after where/); + }); + it('does not throw if used after where', function() { + const query = mquery(); + query.where('collection').slice(2, 3); + assert.deepEqual(query._fields, { collection: { $slice: [2, 3] } }); + }); + }); + it('and first is not a number', function() { + const query = mquery().slice('collection', [-5, 2]); + assert.deepEqual(query._fields, { collection: { $slice: [-5, 2] } }); + }); + }); + + describe('with 3 args', function() { + it('works', function() { + const query = mquery(); + query.slice('collection', 14, 10); + assert.deepEqual(query._fields, { collection: { $slice: [14, 10] } }); + }); + }); + + noDistinct('slice'); + no('count', 'slice'); + }); + + // options + + describe('sort', function() { + describe('with 0 args', function() { + it('chains', function() { + const m = mquery(); + assert.equal(m, m.sort()); + }); + it('has no affect', function() { + const m = mquery(); + assert.equal(m.options.sort, undefined); + }); + }); + + it('works', function() { + let query = mquery(); + query.sort('a -c b'); + assert.deepEqual(query.options.sort, { a: 1, b: 1, c: -1 }); + + query = mquery(); + query.sort({ a: 1, c: -1, b: 'asc', e: 'descending', f: 'ascending' }); + assert.deepEqual(query.options.sort, { a: 1, c: -1, b: 1, e: -1, f: 1 }); + + query = mquery(); + query.sort([['a', -1], ['c', 1], ['b', 'desc'], ['e', 'ascending'], ['f', 'descending']]); + assert.deepEqual(query.options.sort, [['a', -1], ['c', 1], ['b', -1], ['e', 1], ['f', -1]]); + + query = mquery(); + let e = undefined; + try { + query.sort([['a', 1], { b: 5 }]); + } catch (err) { + e = err; + } + assert.ok(e, 'uh oh. no error was thrown'); + assert.equal(e.message, 'Invalid sort() argument, must be array of arrays'); + + query = mquery(); + e = undefined; + + try { + query.sort('a', 1, 'c', -1, 'b', 1); + } catch (err) { + e = err; + } + assert.ok(e, 'uh oh. no error was thrown'); + assert.equal(e.message, 'Invalid sort() argument. Must be a string, object, or array.'); + }); + + it('handles $meta sort options', function() { + const query = mquery(); + query.sort({ score: { $meta: 'textScore' } }); + assert.deepEqual(query.options.sort, { score: { $meta: 'textScore' } }); + }); + + it('array syntax', function() { + const query = mquery(); + query.sort([['field', 1], ['test', -1]]); + assert.deepEqual(query.options.sort, [['field', 1], ['test', -1]]); + }); + + it('throws with mixed array/object syntax', function() { + const query = mquery(); + assert.throws(function() { + query.sort({ field: 1 }).sort([['test', -1]]); + }, /Can't mix sort syntaxes/); + assert.throws(function() { + query.sort([['field', 1]]).sort({ test: 1 }); + }, /Can't mix sort syntaxes/); + }); + + it('works with maps', function() { + if (typeof Map === 'undefined') { + return this.skip(); + } + const query = mquery(); + query.sort(new Map().set('field', 1).set('test', -1)); + assert.deepEqual(query.options.sort, new Map().set('field', 1).set('test', -1)); + }); + }); + + function simpleOption(type, options) { + describe(type, function() { + it('sets the ' + type + ' option', function() { + const m = mquery()[type](2); + const optionName = options.name || type; + assert.equal(2, m.options[optionName]); + }); + it('is chainable', function() { + const m = mquery(); + assert.equal(m[type](3), m); + }); + + if (!options.distinct) noDistinct(type); + if (!options.count) no('count', type); + }); + } + + const negated = { + limit: { distinct: false, count: true }, + skip: { distinct: false, count: true }, + maxScan: { distinct: false, count: false }, + batchSize: { distinct: false, count: false }, + maxTime: { distinct: true, count: true, name: 'maxTimeMS' }, + comment: { distinct: false, count: false } + }; + Object.keys(negated).forEach(function(key) { + simpleOption(key, negated[key]); + }); + + describe('snapshot', function() { + it('works', function() { + let query; + + query = mquery(); + query.snapshot(); + assert.equal(true, query.options.snapshot); + + query = mquery(); + query.snapshot(true); + assert.equal(true, query.options.snapshot); + + query = mquery(); + query.snapshot(false); + assert.equal(false, query.options.snapshot); + }); + noDistinct('snapshot'); + no('count', 'snapshot'); + }); + + describe('hint', function() { + it('accepts an object', function() { + const query2 = mquery(); + query2.hint({ a: 1, b: -1 }); + assert.deepEqual(query2.options.hint, { a: 1, b: -1 }); + }); + + it('accepts a string', function() { + const query2 = mquery(); + query2.hint('a'); + assert.deepEqual(query2.options.hint, 'a'); + }); + + it('rejects everything else', function() { + assert.throws(function() { + mquery().hint(['c']); + }, /Invalid hint./); + assert.throws(function() { + mquery().hint(1); + }, /Invalid hint./); + }); + + describe('does not have side affects', function() { + it('on invalid arg', function() { + const m = mquery(); + try { + m.hint(1); + } catch (err) { + // ignore + } + assert.equal(undefined, m.options.hint); + }); + it('on missing arg', function() { + const m = mquery().hint(); + assert.equal(undefined, m.options.hint); + }); + }); + + noDistinct('hint'); + }); + + describe('j', function() { + it('works', function() { + const m = mquery().j(true); + assert.equal(true, m.options.j); + }); + }); + + describe('slaveOk', function() { + it('works', function() { + let query; + + query = mquery(); + query.slaveOk(); + assert.equal(true, query.options.slaveOk); + + query = mquery(); + query.slaveOk(true); + assert.equal(true, query.options.slaveOk); + + query = mquery(); + query.slaveOk(false); + assert.equal(false, query.options.slaveOk); + }); + }); + + describe('read', function() { + it('sets associated readPreference option', function() { + const m = mquery(); + m.read('p'); + assert.equal('primary', m.options.readPreference); + }); + it('is chainable', function() { + const m = mquery(); + assert.equal(m, m.read('sp')); + }); + }); + + describe('readConcern', function() { + it('sets associated readConcern option', function() { + let m; + + m = mquery(); + m.readConcern('s'); + assert.deepEqual({ level: 'snapshot' }, m.options.readConcern); + + m = mquery(); + m.r('local'); + assert.deepEqual({ level: 'local' }, m.options.readConcern); + }); + it('is chainable', function() { + const m = mquery(); + assert.equal(m, m.readConcern('lz')); + }); + }); + + describe('tailable', function() { + it('works', function() { + let query; + + query = mquery(); + query.tailable(); + assert.equal(true, query.options.tailable); + + query = mquery(); + query.tailable(true); + assert.equal(true, query.options.tailable); + + query = mquery(); + query.tailable(false); + assert.equal(false, query.options.tailable); + }); + it('is chainable', function() { + const m = mquery(); + assert.equal(m, m.tailable()); + }); + noDistinct('tailable'); + no('count', 'tailable'); + }); + + describe('writeConcern', function() { + it('sets associated writeConcern option', function() { + let m; + m = mquery(); + m.writeConcern('majority'); + assert.equal('majority', m.options.w); + + m = mquery(); + m.writeConcern('m'); // m is alias of majority + assert.equal('majority', m.options.w); + + m = mquery(); + m.writeConcern(1); + assert.equal(1, m.options.w); + }); + it('accepts object', function() { + let m; + + m = mquery().writeConcern({ w: 'm', j: true, wtimeout: 1000 }); + assert.equal('m', m.options.w); // check it does not convert m to majority + assert.equal(true, m.options.j); + assert.equal(1000, m.options.wtimeout); + + m = mquery().w('m').w({ j: false, wtimeout: 0 }); + assert.equal('majority', m.options.w); + assert.strictEqual(false, m.options.j); + assert.strictEqual(0, m.options.wtimeout); + }); + it('is chainable', function() { + const m = mquery(); + assert.equal(m, m.writeConcern('majority')); + }); + }); + + // query utilities + + describe('merge', function() { + describe('with falsy arg', function() { + it('returns itself', function() { + const m = mquery(); + assert.equal(m, m.merge()); + assert.equal(m, m.merge(null)); + assert.equal(m, m.merge(0)); + }); + }); + describe('with an argument', function() { + describe('that is not a query or plain object', function() { + it('throws', function() { + assert.throws(function() { + mquery().merge([]); + }, /Invalid argument/); + assert.throws(function() { + mquery().merge('merge'); + }, /Invalid argument/); + assert.doesNotThrow(function() { + mquery().merge({}); + }, /Invalid argument/); + }); + }); + + describe('that is a query', function() { + it('merges conditions, field selection, and options', function() { + const m = mquery({ x: 'hi' }, { select: 'x y', another: true }); + const n = mquery().merge(m); + assert.deepEqual(n._conditions, m._conditions); + assert.deepEqual(n._fields, m._fields); + assert.deepEqual(n.options, m.options); + }); + it('clones update arguments', function(done) { + const original = { $set: { iTerm: true } }; + const m = mquery().updateOne(original); + const n = mquery().merge(m); + m.updateOne({ $set: { x: 2 } }); + assert.notDeepEqual(m._update, n._update); + done(); + }); + it('is chainable', function() { + const m = mquery({ x: 'hi' }); + const n = mquery(); + assert.equal(n, n.merge(m)); + }); + }); + + describe('that is an object', function() { + it('merges', function() { + const m = { x: 'hi' }; + const n = mquery().merge(m); + assert.deepEqual(n._conditions, { x: 'hi' }); + }); + it('clones update arguments', function(done) { + const original = { $set: { iTerm: true } }; + const m = mquery().updateOne(original); + const n = mquery().merge(original); + m.updateOne({ $set: { x: 2 } }); + assert.notDeepEqual(m._update, n._update); + done(); + }); + it('is chainable', function() { + const m = { x: 'hi' }; + const n = mquery(); + assert.equal(n, n.merge(m)); + }); + }); + }); + }); + + // queries + + describe('find', function() { + describe('with no callback', function() { + it('does not execute', function() { + const m = mquery(); + assert.doesNotThrow(function() { + m.find(); + }); + assert.doesNotThrow(function() { + m.find({ x: 1 }); + }); + }); + }); + + it('is chainable', function() { + const m = mquery().find({ x: 1 }).find().find({ y: 2 }); + assert.deepEqual(m._conditions, { x: 1, y: 2 }); + }); + + it('merges other queries', function() { + const m = mquery({ name: 'mquery' }); + m.tailable(); + m.select('_id'); + const a = mquery().find(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }); + + describe('executes', function() { + before(function(done) { + col.insertOne({ name: 'mquery' }, done); + }); + + after(function(done) { + col.remove({ name: 'mquery' }, done); + }); + + it('when criteria is passed with a callback', function(done) { + mquery(col).find({ name: 'mquery' }, function(err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }); + }); + it('when Query is passed with a callback', function(done) { + const m = mquery({ name: 'mquery' }); + mquery(col).find(m, function(err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }); + }); + it('when just a callback is passed', function(done) { + mquery({ name: 'mquery' }).collection(col).find(function(err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }); + }); + }); + }); + + describe('findOne', function() { + describe('with no callback', function() { + it('does not execute', function() { + const m = mquery(); + assert.doesNotThrow(function() { + m.findOne(); + }); + assert.doesNotThrow(function() { + m.findOne({ x: 1 }); + }); + }); + }); + + it('is chainable', function() { + const m = mquery(); + const n = m.findOne({ x: 1 }).findOne().findOne({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(m._conditions, { x: 1, y: 2 }); + assert.equal('findOne', m.op); + }); + + it('merges other queries', function() { + const m = mquery({ name: 'mquery' }); + m.read('nearest'); + m.select('_id'); + const a = mquery().findOne(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }); + + describe('executes', function() { + before(function(done) { + col.insertOne({ name: 'mquery findone' }, done); + }); + + after(function(done) { + col.remove({ name: 'mquery findone' }, done); + }); + + it('when criteria is passed with a callback', function(done) { + mquery(col).findOne({ name: 'mquery findone' }, function(err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }); + }); + it('when Query is passed with a callback', function(done) { + const m = mquery(col).where({ name: 'mquery findone' }); + mquery(col).findOne(m, function(err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }); + }); + it('when just a callback is passed', function(done) { + mquery({ name: 'mquery findone' }).collection(col).findOne(function(err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }); + }); + }); + }); + + describe('count', function() { + describe('with no callback', function() { + it('does not execute', function() { + const m = mquery(); + assert.doesNotThrow(function() { + m.count(); + }); + assert.doesNotThrow(function() { + m.count({ x: 1 }); + }); + }); + }); + + it('is chainable', function() { + const m = mquery(); + const n = m.count({ x: 1 }).count().count({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(m._conditions, { x: 1, y: 2 }); + assert.equal('count', m.op); + }); + + it('merges other queries', function() { + const m = mquery({ name: 'mquery' }); + m.read('nearest'); + m.select('_id'); + const a = mquery().count(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }); + + describe('executes', function() { + before(function(done) { + col.insertOne({ name: 'mquery count' }, done); + }); + + after(function(done) { + col.remove({ name: 'mquery count' }, done); + }); + + it('when criteria is passed with a callback', function(done) { + mquery(col).count({ name: 'mquery count' }, function(err, count) { + assert.ifError(err); + assert.ok(count); + assert.ok(1 === count); + done(); + }); + }); + it('when Query is passed with a callback', function(done) { + const m = mquery({ name: 'mquery count' }); + mquery(col).count(m, function(err, count) { + assert.ifError(err); + assert.ok(count); + assert.ok(1 === count); + done(); + }); + }); + it('when just a callback is passed', function(done) { + mquery({ name: 'mquery count' }).collection(col).count(function(err, count) { + assert.ifError(err); + assert.ok(1 === count); + done(); + }); + }); + }); + + describe('validates its option', function() { + it('sort', function(done) { + assert.doesNotThrow(function() { + mquery().sort('x').count(); + }); + done(); + }); + + it('select', function(done) { + assert.throws(function() { + mquery().select('x').count(); + }, /field selection and slice cannot be used with count/); + done(); + }); + + it('slice', function(done) { + assert.throws(function() { + mquery().where('x').slice(-3).count(); + }, /field selection and slice cannot be used with count/); + done(); + }); + + it('limit', function(done) { + assert.doesNotThrow(function() { + mquery().limit(3).count(); + }); + done(); + }); + + it('skip', function(done) { + assert.doesNotThrow(function() { + mquery().skip(3).count(); + }); + done(); + }); + + it('batchSize', function(done) { + assert.throws(function() { + mquery({}, { batchSize: 3 }).count(); + }, /batchSize cannot be used with count/); + done(); + }); + + it('comment', function(done) { + assert.throws(function() { + mquery().comment('mquery').count(); + }, /comment cannot be used with count/); + done(); + }); + + it('maxScan', function(done) { + assert.throws(function() { + mquery().maxScan(300).count(); + }, /maxScan cannot be used with count/); + done(); + }); + + it('snapshot', function(done) { + assert.throws(function() { + mquery().snapshot().count(); + }, /snapshot cannot be used with count/); + done(); + }); + + it('tailable', function(done) { + assert.throws(function() { + mquery().tailable().count(); + }, /tailable cannot be used with count/); + done(); + }); + }); + }); + + describe('distinct', function() { + describe('with no callback', function() { + it('does not execute', function() { + const m = mquery(); + assert.doesNotThrow(function() { + m.distinct(); + }); + assert.doesNotThrow(function() { + m.distinct('name'); + }); + assert.doesNotThrow(function() { + m.distinct({ name: 'mquery distinct' }); + }); + assert.doesNotThrow(function() { + m.distinct({ name: 'mquery distinct' }, 'name'); + }); + }); + }); + + it('is chainable', function() { + const m = mquery({ x: 1 }).distinct('name'); + const n = m.distinct({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(n._conditions, { x: 1, y: 2 }); + assert.equal('name', n._distinct); + assert.equal('distinct', n.op); + }); + + it('overwrites field', function() { + const m = mquery({ name: 'mquery' }).distinct('name'); + m.distinct('rename'); + assert.equal(m._distinct, 'rename'); + m.distinct({ x: 1 }, 'renamed'); + assert.equal(m._distinct, 'renamed'); + }); + + it('merges other queries', function() { + const m = mquery().distinct({ name: 'mquery' }, 'age'); + m.read('nearest'); + const a = mquery().distinct(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + assert.deepEqual(a._distinct, m._distinct); + }); + + describe('executes', function() { + before(function(done) { + col.insertOne({ name: 'mquery distinct', age: 1 }, done); + }); + + after(function(done) { + col.remove({ name: 'mquery distinct' }, done); + }); + + it('when distinct arg is passed with a callback', function(done) { + mquery(col).distinct('distinct', function(err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }); + }); + describe('when criteria is passed with a callback', function() { + it('if distinct arg was declared', function(done) { + mquery(col).distinct('age').distinct({ name: 'mquery distinct' }, function(err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }); + }); + it('but not if distinct arg was not declared', function() { + assert.throws(function() { + mquery(col).distinct({ name: 'mquery distinct' }, function() {}); + }, /No value for `distinct`/); + }); + }); + describe('when Query is passed with a callback', function() { + const m = mquery({ name: 'mquery distinct' }); + it('if distinct arg was declared', function(done) { + mquery(col).distinct('age').distinct(m, function(err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }); + }); + it('but not if distinct arg was not declared', function() { + assert.throws(function() { + mquery(col).distinct(m, function() {}); + }, /No value for `distinct`/); + }); + }); + describe('when just a callback is passed', function() { + it('if distinct arg was declared', function(done) { + const m = mquery({ name: 'mquery distinct' }); + m.collection(col); + m.distinct('age'); + m.distinct(function(err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }); + }); + it('but not if no distinct arg was declared', function() { + const m = mquery(); + m.collection(col); + assert.throws(function() { + m.distinct(function() {}); + }, /No value for `distinct`/); + }); + }); + }); + + describe('validates its option', function() { + it('sort', function(done) { + assert.throws(function() { + mquery().sort('x').distinct(); + }, /sort cannot be used with distinct/); + done(); + }); + + it('select', function(done) { + assert.throws(function() { + mquery().select('x').distinct(); + }, /field selection and slice cannot be used with distinct/); + done(); + }); + + it('slice', function(done) { + assert.throws(function() { + mquery().where('x').slice(-3).distinct(); + }, /field selection and slice cannot be used with distinct/); + done(); + }); + + it('limit', function(done) { + assert.throws(function() { + mquery().limit(3).distinct(); + }, /limit cannot be used with distinct/); + done(); + }); + + it('skip', function(done) { + assert.throws(function() { + mquery().skip(3).distinct(); + }, /skip cannot be used with distinct/); + done(); + }); + + it('batchSize', function(done) { + assert.throws(function() { + mquery({}, { batchSize: 3 }).distinct(); + }, /batchSize cannot be used with distinct/); + done(); + }); + + it('comment', function(done) { + assert.throws(function() { + mquery().comment('mquery').distinct(); + }, /comment cannot be used with distinct/); + done(); + }); + + it('maxScan', function(done) { + assert.throws(function() { + mquery().maxScan(300).distinct(); + }, /maxScan cannot be used with distinct/); + done(); + }); + + it('snapshot', function(done) { + assert.throws(function() { + mquery().snapshot().distinct(); + }, /snapshot cannot be used with distinct/); + done(); + }); + + it('hint', function(done) { + assert.throws(function() { + mquery().hint({ x: 1 }).distinct(); + }, /hint cannot be used with distinct/); + done(); + }); + + it('tailable', function(done) { + assert.throws(function() { + mquery().tailable().distinct(); + }, /tailable cannot be used with distinct/); + done(); + }); + }); + }); + + describe('update', function() { + describe('with no callback', function() { + it('does not execute', function() { + const m = mquery(); + assert.doesNotThrow(function() { + m.updateOne({ name: 'old' }, { name: 'updated' }, { multi: true }); + }); + assert.doesNotThrow(function() { + m.updateOne({ name: 'old' }, { name: 'updated' }); + }); + assert.doesNotThrow(function() { + m.updateOne({ name: 'updated' }); + }); + assert.doesNotThrow(function() { + m.updateOne(); + }); + }); + }); + + it('is chainable', function() { + const m = mquery({ x: 1 }).updateOne({ y: 2 }); + const n = m.where({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(n._conditions, { x: 1, y: 2 }); + assert.deepEqual({ y: 2 }, n._update); + assert.equal('updateOne', n.op); + }); + + it('merges update doc arg', function() { + const a = [1, 2]; + const m = mquery().where({ name: 'mquery' }).updateOne({ x: 'stuff', a: a }); + m.updateOne({ z: 'stuff' }); + assert.deepEqual(m._update, { z: 'stuff', x: 'stuff', a: a }); + assert.deepEqual(m._conditions, { name: 'mquery' }); + assert.ok(!m.options.overwrite); + m.updateOne({}, { z: 'renamed' }, { overwrite: true }); + assert.ok(m.options.overwrite === true); + assert.deepEqual(m._conditions, { name: 'mquery' }); + assert.deepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); + a.push(3); + assert.notDeepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); + }); + + describe('executes', function() { + let id; + before(function(done) { + col.insertOne({ name: 'mquery update', age: 1 }, function(err, res) { + id = res.insertedId; + done(); + }); + }); + + after(function(done) { + col.remove({ _id: id }, done); + }); + + describe('when conds + doc + opts + callback passed', function() { + it('works', function(done) { + const m = mquery(col).where({ _id: id }); + m.updateOne({}, { name: 'Sparky' }, {}, function(err, res) { + assert.ifError(err); + assert.equal(res.modifiedCount, 1); + m.findOne(function(err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'Sparky'); + done(); + }); + }); + }); + }); + + describe('when conds + doc + callback passed', function() { + it('works', function(done) { + const m = mquery(col).updateOne({ _id: id }, { name: 'fairgrounds' }, function(err, num) { + assert.ifError(err); + assert.ok(1, num); + m.findOne(function(err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'fairgrounds'); + done(); + }); + }); + }); + }); + + describe('when doc + callback passed', function() { + it('works', function(done) { + const m = mquery(col).where({ _id: id }).updateOne({ name: 'changed' }, function(err, num) { + assert.ifError(err); + assert.ok(1, num); + m.findOne(function(err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'changed'); + done(); + }); + }); + }); + }); + + describe('when just callback passed', function() { + it('works', function(done) { + const m = mquery(col).where({ _id: id }); + m.updateOne({ name: 'Frankenweenie' }); + m.updateOne(function(err, res) { + assert.ifError(err); + assert.equal(res.modifiedCount, 1); + m.findOne(function(err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'Frankenweenie'); + done(); + }); + }); + }); + }); + + describe('without a callback', function() { + it('when forced by exec()', function(done) { + const m = mquery(col).where({ _id: id }); + m.setOptions({ w: 'majority' }); + m.updateOne({ name: 'forced' }); + + const update = m._collection.update; + m._collection.updateOne = function(conds, doc, opts) { + m._collection.update = update; + + assert.equal(opts.w, 'majority'); + assert.equal('forced', doc.$set.name); + done(); + }; + + m.exec(); + }); + }); + + describe('except when update doc is empty and missing overwrite flag', function() { + it('works', function(done) { + const m = mquery(col).where({ _id: id }); + m.updateOne({}, function(err, num) { + assert.ifError(err); + assert.ok(0 === num); + setTimeout(function() { + m.findOne(function(err, doc) { + assert.ifError(err); + assert.equal(3, mquery.utils.keys(doc).length); + assert.equal(id, doc._id.toString()); + assert.equal('Frankenweenie', doc.name); + done(); + }); + }, 300); + }); + }); + }); + + describe('when boolean (true) - exec()', function() { + it('works', function(done) { + const m = mquery(col).where({ _id: id }); + m.updateOne({ name: 'bool' }).updateOne(true); + setTimeout(function() { + m.findOne(function(err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('bool', doc.name); + done(); + }); + }, 300); + }); + }); + }); + }); + + describe('remove', function() { + describe('with 0 args', function() { + const name = 'remove: no args test'; + before(function(done) { + col.insertOne({ name: name }, done); + }); + after(function(done) { + col.remove({ name: name }, done); + }); + + it('does not execute', function(done) { + const remove = col.remove; + col.remove = function() { + col.remove = remove; + done(new Error('remove executed!')); + }; + + mquery(col).where({ name: name }).remove(); + setTimeout(function() { + col.remove = remove; + done(); + }, 10); + }); + + it('chains', function() { + const m = mquery(); + assert.equal(m, m.remove()); + }); + }); + + describe('with 1 argument', function() { + const name = 'remove: 1 arg test'; + before(function(done) { + col.insertOne({ name: name }, done); + }); + after(function(done) { + col.remove({ name: name }, done); + }); + + describe('that is a', function() { + it('plain object', function() { + const m = mquery(col).remove({ name: 'Whiskers' }); + m.remove({ color: '#fff' }); + assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); + }); + + it('query', function() { + const q = mquery({ color: '#fff' }); + const m = mquery(col).remove({ name: 'Whiskers' }); + m.remove(q); + assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); + }); + + it('function', function(done) { + mquery(col).where({ name: name }).remove(function(err) { + assert.ifError(err); + mquery(col).findOne({ name: name }, function(err, doc) { + assert.ifError(err); + assert.equal(null, doc); + done(); + }); + }); + }); + + it('boolean (true) - execute', function(done) { + col.insertOne({ name: name }, function(err) { + assert.ifError(err); + mquery(col).findOne({ name: name }, function(err, doc) { + assert.ifError(err); + assert.ok(doc); + mquery(col).remove(true); + setTimeout(function() { + mquery(col).find(function(err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(0, docs.length); + done(); + }); + }, 300); + }); + }); + }); + }); + }); + + describe('with 2 arguments', function() { + const name = 'remove: 2 arg test'; + beforeEach(function(done) { + col.remove({}, function(err) { + assert.ifError(err); + col.insertMany([{ name: 'shelly' }, { name: name }], function(err) { + assert.ifError(err); + mquery(col).find(function(err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }); + }); + }); + }); + + describe('plain object + callback', function() { + it('works', function(done) { + mquery(col).remove({ name: name }, function(err) { + assert.ifError(err); + mquery(col).find(function(err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(1, docs.length); + assert.equal('shelly', docs[0].name); + done(); + }); + }); + }); + }); + + describe('mquery + callback', function() { + it('works', function(done) { + const m = mquery({ name: name }); + mquery(col).remove(m, function(err) { + assert.ifError(err); + mquery(col).find(function(err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(1, docs.length); + assert.equal('shelly', docs[0].name); + done(); + }); + }); + }); + }); + }); + }); + + function validateFindAndModifyOptions(method) { + describe('validates its option', function() { + it('sort', function(done) { + assert.doesNotThrow(function() { + mquery().sort('x')[method](); + }); + done(); + }); + + it('select', function(done) { + assert.doesNotThrow(function() { + mquery().select('x')[method](); + }); + done(); + }); + + it('limit', function(done) { + assert.throws(function() { + mquery().limit(3)[method](); + }, new RegExp('limit cannot be used with ' + method)); + done(); + }); + + it('skip', function(done) { + assert.throws(function() { + mquery().skip(3)[method](); + }, new RegExp('skip cannot be used with ' + method)); + done(); + }); + + it('batchSize', function(done) { + assert.throws(function() { + mquery({}, { batchSize: 3 })[method](); + }, new RegExp('batchSize cannot be used with ' + method)); + done(); + }); + + it('maxScan', function(done) { + assert.throws(function() { + mquery().maxScan(300)[method](); + }, new RegExp('maxScan cannot be used with ' + method)); + done(); + }); + + it('snapshot', function(done) { + assert.throws(function() { + mquery().snapshot()[method](); + }, new RegExp('snapshot cannot be used with ' + method)); + done(); + }); + + it('hint', function(done) { + assert.throws(function() { + mquery().hint({ x: 1 })[method](); + }, new RegExp('hint cannot be used with ' + method)); + done(); + }); + + it('tailable', function(done) { + assert.throws(function() { + mquery().tailable()[method](); + }, new RegExp('tailable cannot be used with ' + method)); + done(); + }); + + it('comment', function(done) { + assert.throws(function() { + mquery().comment('mquery')[method](); + }, new RegExp('comment cannot be used with ' + method)); + done(); + }); + }); + } + + describe('findOneAndUpdate', function() { + let name = 'findOneAndUpdate + fn'; + + validateFindAndModifyOptions('findOneAndUpdate'); + + describe('with 0 args', function() { + it('makes no changes', function() { + const m = mquery(); + const n = m.findOneAndUpdate(); + assert.deepEqual(m, n); + }); + }); + describe('with 1 arg', function() { + describe('that is an object', function() { + it('updates the doc', function() { + const m = mquery(); + const n = m.findOneAndUpdate({ $set: { name: '1 arg' } }); + assert.deepEqual(n._update, { $set: { name: '1 arg' } }); + }); + }); + describe('that is a query', function() { + it('updates the doc', function() { + const m = mquery({ name: name }).updateOne({ x: 1 }); + const n = mquery().findOneAndUpdate(m); + assert.deepEqual(n._update, { x: 1 }); + }); + }); + it('that is a function', function(done) { + col.insertOne({ name: name }, function(err) { + assert.ifError(err); + const m = mquery({ name: name }).collection(col); + name = '1 arg'; + const n = m.updateOne({ $set: { name: name } }).setOptions({ returnDocument: 'after' }); + n.findOneAndUpdate(function(err, res) { + assert.ifError(err); + assert.ok(res.value); + assert.equal(res.value.name, name); + done(); + }); + }); + }); + }); + describe('with 2 args', function() { + it('conditions + update', function() { + const m = mquery(col); + m.findOneAndUpdate({ name: name }, { age: 100 }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ age: 100 }, m._update); + }); + it('query + update', function() { + const n = mquery({ name: name }); + const m = mquery(col); + m.findOneAndUpdate(n, { age: 100 }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ age: 100 }, m._update); + }); + it('update + callback', function(done) { + const m = mquery(col).where({ name: name }); + m.findOneAndUpdate({}, { $inc: { age: 10 } }, { returnDocument: 'after' }, function(err, res) { + assert.ifError(err); + assert.equal(10, res.value.age); + done(); + }); + }); + }); + describe('with 3 args', function() { + it('conditions + update + options', function() { + const m = mquery(); + const n = m.findOneAndUpdate({ name: name }, { works: true }, { returnDocument: 'before' }); + assert.deepEqual({ name: name }, n._conditions); + assert.deepEqual({ works: true }, n._update); + assert.deepEqual({ returnDocument: 'before' }, n.options); + }); + it('conditions + update + callback', function(done) { + const m = mquery(col); + m.findOneAndUpdate({ name: name }, { works: true }, { returnDocument: 'after' }, function(err, res) { + assert.ifError(err); + assert.ok(res.value); + assert.equal(name, res.value.name); + assert.ok(true === res.value.works); + done(); + }); + }); + }); + describe('with 4 args', function() { + it('conditions + update + options + callback', function(done) { + const m = mquery(col); + m.findOneAndUpdate({ name: name }, { works: false }, {}, function(err, res) { + assert.ifError(err); + assert.ok(res.value); + assert.equal(name, res.value.name); + assert.ok(true === res.value.works); + done(); + }); + }); + }); + }); + + describe('findOneAndRemove', function() { + let name = 'findOneAndRemove'; + + validateFindAndModifyOptions('findOneAndRemove'); + + describe('with 0 args', function() { + it('makes no changes', function() { + const m = mquery(); + const n = m.findOneAndRemove(); + assert.deepEqual(m, n); + }); + }); + describe('with 1 arg', function() { + describe('that is an object', function() { + it('updates the doc', function() { + const m = mquery(); + const n = m.findOneAndRemove({ name: '1 arg' }); + assert.deepEqual(n._conditions, { name: '1 arg' }); + }); + }); + describe('that is a query', function() { + it('updates the doc', function() { + const m = mquery({ name: name }); + const n = m.findOneAndRemove(m); + assert.deepEqual(n._conditions, { name: name }); + }); + }); + it('that is a function', function(done) { + col.insertOne({ name: name }, function(err) { + assert.ifError(err); + const m = mquery({ name: name }).collection(col); + m.findOneAndRemove(function(err, res) { + assert.ifError(err); + assert.ok(res.value); + assert.equal(name, res.value.name); + done(); + }); + }); + }); + }); + describe('with 2 args', function() { + it('conditions + options', function() { + const m = mquery(col); + m.findOneAndRemove({ name: name }, { returnDocument: 'after' }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ returnDocument: 'after' }, m.options); + }); + it('query + options', function() { + const n = mquery({ name: name }); + const m = mquery(col); + m.findOneAndRemove(n, { sort: { x: 1 } }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ sort: { x: 1 } }, m.options); + }); + it('conditions + callback', function(done) { + col.insertOne({ name: name }, function(err) { + assert.ifError(err); + const m = mquery(col); + m.findOneAndRemove({ name: name }, function(err, res) { + assert.ifError(err); + assert.equal(name, res.value.name); + done(); + }); + }); + }); + it('query + callback', function(done) { + col.insertOne({ name: name }, function(err) { + assert.ifError(err); + const n = mquery({ name: name }); + const m = mquery(col); + m.findOneAndRemove(n, function(err, res) { + assert.ifError(err); + assert.equal(name, res.value.name); + done(); + }); + }); + }); + }); + describe('with 3 args', function() { + it('conditions + options + callback', function(done) { + name = 'findOneAndRemove + conds + options + cb'; + col.insertMany([{ name: name }, { name: 'a' }], function(err) { + assert.ifError(err); + const m = mquery(col); + m.findOneAndRemove({ name: name }, { sort: { name: 1 } }, function(err, res) { + assert.ifError(err); + assert.ok(res.value); + assert.equal(name, res.value.name); + done(); + }); + }); + }); + }); + }); + + describe('exec', function() { + beforeEach(function(done) { + col.insertMany([{ name: 'exec', age: 1 }, { name: 'exec', age: 2 }], done); + }); + + afterEach(function(done) { + mquery(col).remove(done); + }); + + it('requires an op', function() { + assert.throws(function() { + mquery().exec(); + }, /Missing query type/); + }); + + describe('find', function() { + it('works', function(done) { + const m = mquery(col).find({ name: 'exec' }); + m.exec(function(err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }); + }); + + it('works with readPreferences', function(done) { + const m = mquery(col).find({ name: 'exec' }); + try { + const ReadPreference = require('mongodb').ReadPreference; + const rp = new ReadPreference('primary'); + m.read(rp); + } catch (e) { + done(e.code === 'MODULE_NOT_FOUND' ? null : e); + return; + } + m.exec(function(err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }); + }); + + it('works with hint', function(done) { + mquery(col).hint({ _id: 1 }).find({ name: 'exec' }).exec(function(err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + + mquery(col).hint('_id_').find({ age: 1 }).exec(function(err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }); + }); + }); + + it('works with readConcern', function(done) { + const m = mquery(col).find({ name: 'exec' }); + m.readConcern('l'); + m.exec(function(err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }); + }); + + it('works with collation', function(done) { + const m = mquery(col).find({ name: 'EXEC' }); + m.collation({ locale: 'en_US', strength: 1 }); + m.exec(function(err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }); + }); + }); + + it('findOne', function(done) { + const m = mquery(col).findOne({ age: 2 }); + m.exec(function(err, doc) { + assert.ifError(err); + assert.equal(2, doc.age); + done(); + }); + }); + + it('count', function(done) { + const m = mquery(col).count({ name: 'exec' }); + m.exec(function(err, count) { + assert.ifError(err); + assert.equal(2, count); + done(); + }); + }); + + it('distinct', function(done) { + const m = mquery({ name: 'exec' }); + m.collection(col); + m.distinct('age'); + m.exec(function(err, array) { + assert.ifError(err); + assert.ok(Array.isArray(array)); + assert.equal(2, array.length); + assert(~array.indexOf(1)); + assert(~array.indexOf(2)); + done(); + }); + }); + + describe('update', function() { + describe('updateMany', function() { + it('works', function(done) { + mquery(col).updateMany({ name: 'exec' }, { name: 'test' }). + exec(function(error) { + assert.ifError(error); + mquery(col).count({ name: 'test' }).exec(function(error, res) { + assert.ifError(error); + assert.equal(res, 2); + done(); + }); + }); + }); + it('works with write concern', function(done) { + mquery(col).updateMany({ name: 'exec' }, { name: 'test' }) + .w(1).j(true).wtimeout(1000) + .exec(function(error) { + assert.ifError(error); + mquery(col).count({ name: 'test' }).exec(function(error, res) { + assert.ifError(error); + assert.equal(res, 2); + done(); + }); + }); + }); + }); + + describe('updateOne', function() { + it('works', function(done) { + mquery(col).updateOne({ name: 'exec' }, { name: 'test' }). + exec(function(error) { + assert.ifError(error); + mquery(col).count({ name: 'test' }).exec(function(error, res) { + assert.ifError(error); + assert.equal(res, 1); + done(); + }); + }); + }); + }); + + describe('replaceOne', function() { + it('works', function(done) { + mquery(col).replaceOne({ name: 'exec' }, { name: 'test' }). + exec(function(error) { + assert.ifError(error); + mquery(col).findOne({ name: 'test' }).exec(function(error, res) { + assert.ifError(error); + assert.equal(res.name, 'test'); + assert.ok(res.age == null); + done(); + }); + }); + }); + }); + }); + + describe('remove', function() { + it('with a callback', function(done) { + const m = mquery(col).where({ age: 2 }).remove(); + m.exec(function(err, res) { + assert.ifError(err); + assert.equal(1, res.deletedCount); + done(); + }); + }); + + it('without a callback', function(done) { + const m = mquery(col).where({ age: 1 }).remove(); + m.exec(); + + setTimeout(function() { + mquery(col).where('name', 'exec').count(function(err, num) { + assert.equal(1, num); + done(); + }); + }, 200); + }); + }); + + describe('deleteOne', function() { + it('with a callback', function(done) { + const m = mquery(col).where({ age: { $gte: 0 } }).deleteOne(); + m.exec(function(err, res) { + assert.ifError(err); + assert.equal(res.deletedCount, 1); + done(); + }); + }); + + it('with justOne set', function(done) { + const m = mquery(col).where({ age: { $gte: 0 } }). + // Should ignore `justOne` + setOptions({ justOne: false }). + deleteOne(); + m.exec(function(err, res) { + assert.ifError(err); + assert.equal(res.deletedCount, 1); + done(); + }); + }); + }); + + describe('deleteMany', function() { + it('with a callback', function(done) { + const m = mquery(col).where({ age: { $gte: 0 } }).deleteMany(); + m.exec(function(err, res) { + assert.ifError(err); + assert.equal(res.deletedCount, 2); + done(); + }); + }); + }); + + describe('findOneAndUpdate', function() { + it('with a callback', function(done) { + const m = mquery(col); + m.findOneAndUpdate({ name: 'exec', age: 1 }, { $set: { name: 'findOneAndUpdate' } }, { returnDocument: 'after' }); + m.exec(function(err, res) { + assert.ifError(err); + assert.equal('findOneAndUpdate', res.value.name); + done(); + }); + }); + }); + + describe('findOneAndRemove', function() { + it('with a callback', function(done) { + const m = mquery(col); + m.findOneAndRemove({ name: 'exec', age: 2 }); + m.exec(function(err, res) { + assert.ifError(err); + assert.equal('exec', res.value.name); + assert.equal(2, res.value.age); + mquery(col).count({ name: 'exec' }, function(err, num) { + assert.ifError(err); + assert.equal(1, num); + done(); + }); + }); + }); + }); + }); + + describe('setTraceFunction', function() { + beforeEach(function(done) { + col.insertMany([{ name: 'trace', age: 93 }], done); + }); + + it('calls trace function when executing query', function(done) { + const m = mquery(col); + + let resultTraceCalled; + + m.setTraceFunction(function(method, queryInfo) { + try { + assert.equal('findOne', method); + assert.equal('trace', queryInfo.conditions.name); + } catch (e) { + done(e); + } + + return function(err, result, millis) { + try { + assert.equal(93, result.age); + assert.ok(typeof millis === 'number'); + } catch (e) { + done(e); + } + resultTraceCalled = true; + }; + }); + + m.findOne({ name: 'trace' }, function(err, doc) { + assert.ifError(err); + assert.equal(resultTraceCalled, true); + assert.equal(93, doc.age); + done(); + }); + }); + + it('inherits trace function when calling toConstructor', function(done) { + function traceFunction() { return function() {}; } + + const tracedQuery = mquery().setTraceFunction(traceFunction).toConstructor(); + + const query = tracedQuery(); + assert.equal(traceFunction, query._traceFunction); + + done(); + }); + }); + + describe('thunk', function() { + it('returns a function', function(done) { + assert.equal('function', typeof mquery().thunk()); + done(); + }); + + it('passes the fn arg to `exec`', function(done) { + function cb() {} + const m = mquery(); + + m.exec = function testing(fn) { + assert.equal(this, m); + assert.equal(cb, fn); + done(); + }; + + m.thunk()(cb); + }); + }); + + describe('then', function() { + before(function(done) { + col.insertMany([{ name: 'then', age: 1 }, { name: 'then', age: 2 }], done); + }); + + after(function(done) { + mquery(col).remove({ name: 'then' }).exec(done); + }); + + it('returns a promise A+ compat object', function(done) { + const m = mquery(col).find(); + assert.equal('function', typeof m.then); + done(); + }); + + it('creates a promise that is resolved on success', function(done) { + const promise = mquery(col).count({ name: 'then' }).then(); + promise.then(function(count) { + assert.equal(2, count); + done(); + }, done); + }); + + it('supports exec() cb being called synchronously #66', function(done) { + const query = mquery(col).count({ name: 'then' }); + query.exec = function(cb) { + cb(null, 66); + }; + + query.then(success, done); + function success(count) { + assert.equal(66, count); + done(); + } + }); + }); + + describe('stream', function() { + before(function(done) { + col.insertMany([{ name: 'stream', age: 1 }, { name: 'stream', age: 2 }], done); + }); + + after(function(done) { + mquery(col).remove({ name: 'stream' }).exec(done); + }); + + describe('throws', function() { + describe('if used with non-find operations', function() { + const ops = ['update', 'findOneAndUpdate', 'remove', 'count', 'distinct']; + + ops.forEach(function(op) { + assert.throws(function() { + mquery(col)[op]().stream(); + }); + }); + }); + }); + + it('returns a stream', function(done) { + const stream = mquery(col).find({ name: 'stream' }).cursor().stream(); + let count = 0; + let err; + + stream.on('data', function(doc) { + assert.equal('stream', doc.name); + ++count; + }); + + stream.on('error', function(er) { + err = er; + }); + + stream.on('end', function() { + if (err) return done(err); + assert.equal(2, count); + done(); + }); + }); + }); + + function noDistinct(type) { + it('cannot be used with distinct()', function(done) { + assert.throws(function() { + mquery().distinct('name')[type](4); + }, new RegExp(type + ' cannot be used with distinct')); + done(); + }); + } + + function no(method, type) { + it('cannot be used with ' + method + '()', function(done) { + assert.throws(function() { + mquery()[method]()[type](4); + }, new RegExp(type + ' cannot be used with ' + method)); + done(); + }); + } + + // query internal + + describe('_updateForExec', function() { + it('returns a clone of the update object with same key order #19', function(done) { + const update = {}; + update.$push = { n: { $each: [{ x: 10 }], $slice: -1, $sort: { x: 1 } } }; + + const q = mquery().updateOne({ x: 1 }, update); + + // capture original key order + const order = []; + let key; + for (key in q._update.$push.n) { + order.push(key); + } + + // compare output + const doc = q._updateForExec(); + let i = 0; + for (key in doc.$push.n) { + assert.equal(key, order[i]); + i++; + } + + done(); + }); + }); +}); diff --git a/node_modules/mquery/test/utils.test.js b/node_modules/mquery/test/utils.test.js new file mode 100644 index 0000000..8e358e4 --- /dev/null +++ b/node_modules/mquery/test/utils.test.js @@ -0,0 +1,161 @@ +'use strict'; + +const utils = require('../lib/utils'); +const assert = require('assert'); +const debug = require('debug'); + +let mongo; +try { + mongo = new require('mongodb'); +} catch (e) { + debug('mongo', 'cannot construct mongodb instance'); +} + +describe('lib/utils', function() { + describe('clone', function() { + it('clones constructors named ObjectId', function(done) { + function ObjectId(id) { + this.id = id; + } + + const o1 = new ObjectId('1234'); + const o2 = utils.clone(o1); + assert.ok(o2 instanceof ObjectId); + + done(); + }); + + it('clones constructors named ObjectID', function(done) { + function ObjectID(id) { + this.id = id; + } + + const o1 = new ObjectID('1234'); + const o2 = utils.clone(o1); + + assert.ok(o2 instanceof ObjectID); + done(); + }); + + it('does not clone constructors named ObjectIdd', function(done) { + function ObjectIdd(id) { + this.id = id; + } + + const o1 = new ObjectIdd('1234'); + const o2 = utils.clone(o1); + assert.ok(!(o2 instanceof ObjectIdd)); + + done(); + }); + + it('optionally clones ObjectId constructors using its clone method', function(done) { + function ObjectID(id) { + this.id = id; + this.cloned = false; + } + + ObjectID.prototype.clone = function() { + const ret = new ObjectID(this.id); + ret.cloned = true; + return ret; + }; + + const id = 1234; + const o1 = new ObjectID(id); + assert.equal(id, o1.id); + assert.equal(false, o1.cloned); + + const o2 = utils.clone(o1); + assert.ok(o2 instanceof ObjectID); + assert.equal(id, o2.id); + assert.ok(o2.cloned); + done(); + }); + + it('clones mongodb.ReadPreferences', function(done) { + if (!mongo) return done(); + + const tags = [ + { dc: 'tag1' } + ]; + const prefs = [ + new mongo.ReadPreference('primary'), + new mongo.ReadPreference(mongo.ReadPreference.PRIMARY_PREFERRED), + new mongo.ReadPreference('secondary', tags) + ]; + + const prefsCloned = utils.clone(prefs); + + for (let i = 0; i < prefsCloned.length; i++) { + assert.notEqual(prefs[i], prefsCloned[i]); + if (prefs[i].tags) { + assert.ok(prefsCloned[i].tags); + assert.notEqual(prefs[i].tags, prefsCloned[i].tags); + assert.notEqual(prefs[i].tags[0], prefsCloned[i].tags[0]); + } else { + assert.equal(prefsCloned[i].tags, null); + } + } + + done(); + }); + + it('clones mongodb.Binary', function(done) { + if (!mongo) return done(); + const buf = Buffer.from('hi'); + const binary = new mongo.Binary(buf, 2); + const clone = utils.clone(binary); + assert.equal(binary.sub_type, clone.sub_type); + assert.equal(String(binary.buffer), String(buf)); + assert.ok(binary !== clone); + done(); + }); + + it('handles objects with no constructor', function(done) { + const name = '335'; + + const o = Object.create(null); + o.name = name; + + let clone; + assert.doesNotThrow(function() { + clone = utils.clone(o); + }); + + assert.equal(name, clone.name); + assert.ok(o != clone); + done(); + }); + + it('handles buffers', function(done) { + const buff = Buffer.alloc(10); + buff.fill(1); + const clone = utils.clone(buff); + + for (let i = 0; i < buff.length; i++) { + assert.equal(buff[i], clone[i]); + } + + done(); + }); + + it('skips __proto__', function() { + const payload = JSON.parse('{"__proto__": {"polluted": "vulnerable"}}'); + const res = utils.clone(payload); + + assert.strictEqual({}.polluted, void 0); + assert.strictEqual(res.__proto__, Object.prototype); + }); + }); + + describe('merge', function() { + it('avoids prototype pollution', function() { + const payload = JSON.parse('{"__proto__": {"polluted": "vulnerable"}}'); + const obj = {}; + utils.merge(obj, payload); + + assert.strictEqual({}.polluted, void 0); + }); + }); +}); diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..6a522b1 --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,152 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..6a31c81 --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.0.0", + "description": "Tiny milisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "3.19.0", + "expect.js": "0.3.1", + "husky": "0.13.3", + "lint-staged": "3.4.1", + "mocha": "3.4.1" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..84a9974 --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,51 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +``` + +### Convert from milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +### Time format written-out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [node](https://nodejs.org) and in the browser. +- If a number is supplied to `ms`, a string with a unit is returned. +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). +- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. + +## Caught a bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/negotiator/HISTORY.md b/node_modules/negotiator/HISTORY.md new file mode 100644 index 0000000..6d06c76 --- /dev/null +++ b/node_modules/negotiator/HISTORY.md @@ -0,0 +1,103 @@ +0.6.2 / 2019-04-29 +================== + + * Fix sorting charset, encoding, and language with extra parameters + +0.6.1 / 2016-05-02 +================== + + * perf: improve `Accept` parsing speed + * perf: improve `Accept-Charset` parsing speed + * perf: improve `Accept-Encoding` parsing speed + * perf: improve `Accept-Language` parsing speed + +0.6.0 / 2015-09-29 +================== + + * Fix including type extensions in parameters in `Accept` parsing + * Fix parsing `Accept` parameters with quoted equals + * Fix parsing `Accept` parameters with quoted semicolons + * Lazy-load modules from main entry point + * perf: delay type concatenation until needed + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove closures getting spec properties + * perf: remove a closure from media type parsing + * perf: remove property delete from media type parsing + +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/node_modules/negotiator/LICENSE b/node_modules/negotiator/LICENSE new file mode 100644 index 0000000..ea6b9e2 --- /dev/null +++ b/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Federico Romero +Copyright (c) 2012-2014 Isaac Z. Schlueter +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/negotiator/README.md b/node_modules/negotiator/README.md new file mode 100644 index 0000000..04a67ff --- /dev/null +++ b/node_modules/negotiator/README.md @@ -0,0 +1,203 @@ +# negotiator + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +Returns the most preferred media type from a list of available media types. + +##### mediaTypes() + +Returns an array of preferred media types ordered by the client preference. + +##### mediaTypes(availableMediaTypes) + +Returns an array of preferred media types ordered by priority from a list of +available media types. + +### Accept-Language Negotiation + +```js +negotiator = new Negotiator(request) + +availableLanguages = ['en', 'es', 'fr'] + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +Returns the most preferred language from a list of available languages. + +##### languages() + +Returns an array of preferred languages ordered by the client preference. + +##### languages(availableLanguages) + +Returns an array of preferred languages ordered by priority from a list of +available languages. + +### Accept-Charset Negotiation + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +Returns the most preferred charset from a list of available charsets. + +##### charsets() + +Returns an array of preferred charsets ordered by the client preference. + +##### charsets(availableCharsets) + +Returns an array of preferred charsets ordered by priority from a list of +available charsets. + +### Accept-Encoding Negotiation + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +Returns the most preferred encoding from a list of available encodings. + +##### encodings() + +Returns an array of preferred encodings ordered by the client preference. + +##### encodings(availableEncodings) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings. + +## See Also + +The [accepts](https://npmjs.org/package/accepts#readme) module builds on +this module and provides an alternative interface, mime type validation, +and more. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/negotiator.svg +[npm-url]: https://npmjs.org/package/negotiator +[node-version-image]: https://img.shields.io/node/v/negotiator.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/negotiator/master.svg +[travis-url]: https://travis-ci.org/jshttp/negotiator +[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master +[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg +[downloads-url]: https://npmjs.org/package/negotiator diff --git a/node_modules/negotiator/index.js b/node_modules/negotiator/index.js new file mode 100644 index 0000000..8d4f6a2 --- /dev/null +++ b/node_modules/negotiator/index.js @@ -0,0 +1,124 @@ +/*! + * negotiator + * Copyright(c) 2012 Federico Romero + * Copyright(c) 2012-2014 Isaac Z. Schlueter + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Cached loaded submodules. + * @private + */ + +var modules = Object.create(null); + +/** + * Module exports. + * @public + */ + +module.exports = Negotiator; +module.exports.Negotiator = Negotiator; + +/** + * Create a Negotiator instance from a request. + * @param {object} request + * @public + */ + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + var preferredCharsets = loadModule('charset').preferredCharsets; + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available) { + var set = this.encodings(available); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available) { + var preferredEncodings = loadModule('encoding').preferredEncodings; + return preferredEncodings(this.request.headers['accept-encoding'], available); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + var preferredLanguages = loadModule('language').preferredLanguages; + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + var preferredMediaTypes = loadModule('mediaType').preferredMediaTypes; + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; + +/** + * Load the given module. + * @private + */ + +function loadModule(moduleName) { + var module = modules[moduleName]; + + if (module !== undefined) { + return module; + } + + // This uses a switch for static require analysis + switch (moduleName) { + case 'charset': + module = require('./lib/charset'); + break; + case 'encoding': + module = require('./lib/encoding'); + break; + case 'language': + module = require('./lib/language'); + break; + case 'mediaType': + module = require('./lib/mediaType'); + break; + default: + throw new Error('Cannot find module \'' + moduleName + '\''); + } + + // Store to prevent invoking require() + modules[moduleName] = module; + + return module; +} diff --git a/node_modules/negotiator/lib/charset.js b/node_modules/negotiator/lib/charset.js new file mode 100644 index 0000000..cdd0148 --- /dev/null +++ b/node_modules/negotiator/lib/charset.js @@ -0,0 +1,169 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredCharsets; +module.exports.preferredCharsets = preferredCharsets; + +/** + * Module variables. + * @private + */ + +var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Charset header. + * @private + */ + +function parseAcceptCharset(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); + + if (charset) { + accepts[j++] = charset; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a charset from the Accept-Charset header. + * @private + */ + +function parseCharset(str, i) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +/** + * Get the priority of a charset. + * @private + */ + +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the charset. + * @private + */ + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +/** + * Get the preferred charsets from an Accept-Charset header. + * @public + */ + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all charsets + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullCharset); + } + + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); + + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full charset string. + * @private + */ + +function getFullCharset(spec) { + return spec.charset; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/encoding.js b/node_modules/negotiator/lib/encoding.js new file mode 100644 index 0000000..8432cd7 --- /dev/null +++ b/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,184 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredEncodings; +module.exports.preferredEncodings = preferredEncodings; + +/** + * Module variables. + * @private + */ + +var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Encoding header. + * @private + */ + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); + + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } + } + + if (!hasIdentity) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse an encoding from the Accept-Encoding header. + * @private + */ + +function parseEncoding(str, i) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +/** + * Get the priority of an encoding. + * @private + */ + +function getEncodingPriority(encoding, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the encoding. + * @private + */ + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred encodings from an Accept-Encoding header. + * @public + */ + +function preferredEncodings(accept, provided) { + var accepts = parseAcceptEncoding(accept || ''); + + if (!provided) { + // sorted list of all encodings + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullEncoding); + } + + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); + + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full encoding string. + * @private + */ + +function getFullEncoding(spec) { + return spec.encoding; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/language.js b/node_modules/negotiator/lib/language.js new file mode 100644 index 0000000..62f737f --- /dev/null +++ b/node_modules/negotiator/lib/language.js @@ -0,0 +1,179 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredLanguages; +module.exports.preferredLanguages = preferredLanguages; + +/** + * Module variables. + * @private + */ + +var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Language header. + * @private + */ + +function parseAcceptLanguage(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var language = parseLanguage(accepts[i].trim(), i); + + if (language) { + accepts[j++] = language; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a language from the Accept-Language header. + * @private + */ + +function parseLanguage(str, i) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; + + var prefix = match[1], + suffix = match[2], + full = prefix; + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +/** + * Get the priority of a language. + * @private + */ + +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the language. + * @private + */ + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred languages from an Accept-Language header. + * @public + */ + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all languages + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullLanguage); + } + + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); + + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full language string. + * @private + */ + +function getFullLanguage(spec) { + return spec.full; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/mediaType.js b/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 0000000..67309dd --- /dev/null +++ b/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,294 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredMediaTypes; +module.exports.preferredMediaTypes = preferredMediaTypes; + +/** + * Module variables. + * @private + */ + +var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept header. + * @private + */ + +function parseAccept(accept) { + var accepts = splitMediaTypes(accept); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); + + if (mediaType) { + accepts[j++] = mediaType; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a media type from the Accept header. + * @private + */ + +function parseMediaType(str, i) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; + + var params = Object.create(null); + var q = 1; + var subtype = match[2]; + var type = match[1]; + + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); + + for (var j = 0; j < kvps.length; j++) { + var pair = kvps[j]; + var key = pair[0].toLowerCase(); + var val = pair[1]; + + // get the value, unwrapping quotes + var value = val && val[0] === '"' && val[val.length - 1] === '"' + ? val.substr(1, val.length - 2) + : val; + + if (key === 'q') { + q = parseFloat(value); + break; + } + + // store parameter + params[key] = value; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i + }; +} + +/** + * Get the priority of a media type. + * @private + */ + +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the media type. + * @private + */ + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } +} + +/** + * Get the preferred media types from an Accept header. + * @public + */ + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + if (!provided) { + // sorted list of all types + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullType); + } + + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); + + // sorted list of accepted types + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full type string. + * @private + */ + +function getFullType(spec) { + return spec.type + '/' + spec.subtype; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} + +/** + * Count the number of quotes in a string. + * @private + */ + +function quoteCount(string) { + var count = 0; + var index = 0; + + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} + +/** + * Split a key value pair. + * @private + */ + +function splitKeyValuePair(str) { + var index = str.indexOf('='); + var key; + var val; + + if (index === -1) { + key = str; + } else { + key = str.substr(0, index); + val = str.substr(index + 1); + } + + return [key, val]; +} + +/** + * Split an Accept header into media types. + * @private + */ + +function splitMediaTypes(accept) { + var accepts = accept.split(','); + + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; + } + } + + // trim accepts + accepts.length = j + 1; + + return accepts; +} + +/** + * Split a string of parameters. + * @private + */ + +function splitParameters(str) { + var parameters = str.split(';'); + + for (var i = 1, j = 0; i < parameters.length; i++) { + if (quoteCount(parameters[j]) % 2 == 0) { + parameters[++j] = parameters[i]; + } else { + parameters[j] += ';' + parameters[i]; + } + } + + // trim parameters + parameters.length = j + 1; + + for (var i = 0; i < parameters.length; i++) { + parameters[i] = parameters[i].trim(); + } + + return parameters; +} diff --git a/node_modules/negotiator/package.json b/node_modules/negotiator/package.json new file mode 100644 index 0000000..0c7ff3c --- /dev/null +++ b/node_modules/negotiator/package.json @@ -0,0 +1,42 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "version": "0.6.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Federico Romero ", + "Isaac Z. Schlueter (http://blog.izs.me/)" + ], + "license": "MIT", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "repository": "jshttp/negotiator", + "devDependencies": { + "eslint": "5.16.0", + "eslint-plugin-markdown": "1.0.0", + "mocha": "6.1.4", + "nyc": "14.0.0" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + } +} diff --git a/node_modules/node-addon-api/CHANGELOG.md b/node_modules/node-addon-api/CHANGELOG.md new file mode 100644 index 0000000..12b04f2 --- /dev/null +++ b/node_modules/node-addon-api/CHANGELOG.md @@ -0,0 +1,722 @@ +# node-addon-api Changelog + +## 2021-05-28 Version 3.2.1, @NickNaso + +### Notable changes: + +#### Documentation + +- Fixed documentation about the oldest Node.js version supported. + +### Commits + +* [[`6d41ee5a3a`](https://github.com/nodejs/node-addon-api/commit/6d41ee5a3a)] - Fixed readme for new release. (NickNaso) + +## 2021-05-17 Version 3.2.0, @NickNaso + +### Notable changes: + +#### API + +- Remove unnecessary symbol exposure. +- Fixed leak in `Napi::ObjectWrap` instance for getter and setter method. +- Added `Napi::Object::Freeze` and `Napi::object::Seal` methods. +- `Napi::Reference` is now copyable. + +#### Documentation + +- Added docuemtnation for `Napi::Object::PropertyLValue`. +- Changed all N-API references to Node-API. +- Some minor corrections all over the documentation. + +#### TEST + +- Added tests relating to fetch property from Global Object. +- Added addtiona tests for `Napi::Object`. +- Added test for `Napi::Function` contructors. +- Fixed intermittent failure for `Napi::ThreadSafeFunction` test. +- Some minor corrections all over the test suite. + +### TOOL + +- Added Node.js v16.x to CI. +- Added CI configuration for Windows. +- Some fixex on linter command. + +### Commits + +* [[`52721312f6`](https://github.com/nodejs/node-addon-api/commit/52721312f6)] - **docs**: add napi-rs iin Other Bindings section (#999) (LongYinan) +* [[`78a6570a42`](https://github.com/nodejs/node-addon-api/commit/78a6570a42)] - **doc**: fix typo in code example (#997) (Tobias Nießen) +* [[`da3bd5778f`](https://github.com/nodejs/node-addon-api/commit/da3bd5778f)] - **test**: fix undoc assumptions about the timing of tsfn calls (legendecas) [#995](https://github.com/nodejs/node-addon-api/pull/995) +* [[`410cf6a81e`](https://github.com/nodejs/node-addon-api/commit/410cf6a81e)] - **src**: return bool on object freeze and seal (#991) (legendecas) +* [[`93f1898312`](https://github.com/nodejs/node-addon-api/commit/93f1898312)] - **src**: return bool on object set and define property (#977) (legendecas) +* [[`331c2ee274`](https://github.com/nodejs/node-addon-api/commit/331c2ee274)] - **build**: add Node.js v16.x to CI (#983) (legendecas) +* [[`b6f5eb15e6`](https://github.com/nodejs/node-addon-api/commit/b6f5eb15e6)] - **test**: run test suites with helpers (legendecas) [#976](https://github.com/nodejs/node-addon-api/pull/976) +* [[`fbcdf00ea0`](https://github.com/nodejs/node-addon-api/commit/fbcdf00ea0)] - **test**: rename misspelled parameters (Tobias Nießen) [#973](https://github.com/nodejs/node-addon-api/pull/973) +* [[`63a6c32e80`](https://github.com/nodejs/node-addon-api/commit/63a6c32e80)] - **test**: fix intermittent TSFN crashes (Kevin Eady) [#974](https://github.com/nodejs/node-addon-api/pull/974) +* [[`8f120b033f`](https://github.com/nodejs/node-addon-api/commit/8f120b033f)] - **fix**: key for wapping drawing's system condition (#970) (Kévin VOYER) +* [[`1c9d528d66`](https://github.com/nodejs/node-addon-api/commit/1c9d528d66)] - **doc**: correct struct definition (#969) (Darshan Sen) +* [[`5e64d1fa61`](https://github.com/nodejs/node-addon-api/commit/5e64d1fa61)] - Added badges for Node-API v7 and v8. (#954) (Nicola Del Gobbo) +* [[`6ce629b3fa`](https://github.com/nodejs/node-addon-api/commit/6ce629b3fa)] - **src**: add pull request template (#967) (Michael Dawson) +* [[`98126661af`](https://github.com/nodejs/node-addon-api/commit/98126661af)] - Update CONTRIBUTING.md (#966) (Michael Dawson) +* [[`77350eee98`](https://github.com/nodejs/node-addon-api/commit/77350eee98)] - **src**: added Freeze and Seal method to Object class. (NickNaso) [#955](https://github.com/nodejs/node-addon-api/pull/955) +* [[`bc5147cc4a`](https://github.com/nodejs/node-addon-api/commit/bc5147cc4a)] - Finished tests relating to fetch property from Global Object (JckXia) +* [[`0127813111`](https://github.com/nodejs/node-addon-api/commit/0127813111)] - **doc**: unambiguously mark deprecated signatures (Tobias Nießen) [#942](https://github.com/nodejs/node-addon-api/pull/942) +* [[`787e216105`](https://github.com/nodejs/node-addon-api/commit/787e216105)] - **doc**: rename N-API with Node-API (Darshan Sen) [#951](https://github.com/nodejs/node-addon-api/pull/951) +* [[`628023689a`](https://github.com/nodejs/node-addon-api/commit/628023689a)] - **src**: rename N-API with Node-API on comments (NickNaso) [#953](https://github.com/nodejs/node-addon-api/pull/953) +* [[`5c6391578f`](https://github.com/nodejs/node-addon-api/commit/5c6391578f)] - **build**: add CI configuration for Windows (NickNaso) [#948](https://github.com/nodejs/node-addon-api/pull/948) +* [[`8ef07251ec`](https://github.com/nodejs/node-addon-api/commit/8ef07251ec)] - **doc**: added some warnings for buffer and array buffer factory method. (#929) (Nicola Del Gobbo) +* [[`6490b1f730`](https://github.com/nodejs/node-addon-api/commit/6490b1f730)] - **doc**: sync Object::Set value arg with Value::From (#933) (Tobias Nießen) +* [[`7319a0d7a2`](https://github.com/nodejs/node-addon-api/commit/7319a0d7a2)] - Fix tab indent (#938) (Tobias Nießen) +* [[`1916cb937e`](https://github.com/nodejs/node-addon-api/commit/1916cb937e)] - **chore**: fixup linter commands (#940) (legendecas) +* [[`fc4585fa23`](https://github.com/nodejs/node-addon-api/commit/fc4585fa23)] - **test**: dd tests for Function constructors (JoseExposito) [#937](https://github.com/nodejs/node-addon-api/pull/937) +* [[`87b7aae469`](https://github.com/nodejs/node-addon-api/commit/87b7aae469)] - **doc**: warn about SuppressDestruct() (#926) (Anna Henningsen) +* [[`71494a49a3`](https://github.com/nodejs/node-addon-api/commit/71494a49a3)] - **src,doc**: refactor to replace typedefs with usings (Darshan Sen) [#910](https://github.com/nodejs/node-addon-api/pull/910) +* [[`298ff8d9d2`](https://github.com/nodejs/node-addon-api/commit/298ff8d9d2)] - **test**: add additional tests for Object (JoseExposito) [#923](https://github.com/nodejs/node-addon-api/pull/923) +* [[`8a1147b430`](https://github.com/nodejs/node-addon-api/commit/8a1147b430)] - **revert**: src: add additional tests for Function (Michael Dawson) +* [[`bb56ffaa6f`](https://github.com/nodejs/node-addon-api/commit/bb56ffaa6f)] - **doc**: fix documentation for object api (Nicola Del Gobbo) [#931](https://github.com/nodejs/node-addon-api/pull/931) +* [[`3b8bddab49`](https://github.com/nodejs/node-addon-api/commit/3b8bddab49)] - **src**: add additional tests for Function (José Expósito) [#928](https://github.com/nodejs/node-addon-api/pull/928) +* [[`74ab50c775`](https://github.com/nodejs/node-addon-api/commit/74ab50c775)] - **src**: allow references to be copyable in APIs (legendecas) [#915](https://github.com/nodejs/node-addon-api/pull/915) +* [[`929709d0fe`](https://github.com/nodejs/node-addon-api/commit/929709d0fe)] - **doc**: add propertylvalue.md (#925) (Gabriel Schulhof) +* [[`69d0d98be4`](https://github.com/nodejs/node-addon-api/commit/69d0d98be4)] - fixup (Anna Henningsen) +* [[`46e41d961b`](https://github.com/nodejs/node-addon-api/commit/46e41d961b)] - fixup (Anna Henningsen) +* [[`1af1642fb7`](https://github.com/nodejs/node-addon-api/commit/1af1642fb7)] - **doc**: warn about SuppressDestruct() (Anna Henningsen) +* [[`12c548b2ff`](https://github.com/nodejs/node-addon-api/commit/12c548b2ff)] - **tools**: fix error detection (#914) (Darshan Sen) +* [[`458d895d5b`](https://github.com/nodejs/node-addon-api/commit/458d895d5b)] - **packaging**: list files to be published to npm (Lovell Fuller) [#889](https://github.com/nodejs/node-addon-api/pull/889) +* [[`f7ed2490d4`](https://github.com/nodejs/node-addon-api/commit/f7ed2490d4)] - **test**: remove outdated V8 flag (Darshan Sen) [#895](https://github.com/nodejs/node-addon-api/pull/895) +* [[`a575a6ec60`](https://github.com/nodejs/node-addon-api/commit/a575a6ec60)] - **src**: fix leak in ObjectWrap instance set/getters (Kevin Eady) [#899](https://github.com/nodejs/node-addon-api/pull/899) +* [[`b6e844e0b0`](https://github.com/nodejs/node-addon-api/commit/b6e844e0b0)] - **doc**: fix spelling of "targeted" and "targeting" (#904) (Tobias Nießen) +* [[`4d856f6e91`](https://github.com/nodejs/node-addon-api/commit/4d856f6e91)] - **src**: remove unnecessary symbol exposure (Gabriel Schulhof) [#896](https://github.com/nodejs/node-addon-api/pull/896) +* [[`f35bb7d0d7`](https://github.com/nodejs/node-addon-api/commit/f35bb7d0d7)] - **doc**: Update GitHub URL references from 'master' to 'HEAD' (#898) (Jim Schlight) +* [[`286ae215d1`](https://github.com/nodejs/node-addon-api/commit/286ae215d1)] - Add warning about branch rename (Michael Dawson) +* [[`a4a7b28288`](https://github.com/nodejs/node-addon-api/commit/a4a7b28288)] - Update branch references from master to main (#886) (Jim Schlight) +* [[`a2ad0a107a`](https://github.com/nodejs/node-addon-api/commit/a2ad0a107a)] - **docs**: add NAN to N-API resource link (#880) (kidneysolo) +* [[`1c040eeb63`](https://github.com/nodejs/node-addon-api/commit/1c040eeb63)] - **test**: load testModules automatically (raisinten) [#876](https://github.com/nodejs/node-addon-api/pull/876) +* [[`bf478e4496`](https://github.com/nodejs/node-addon-api/commit/bf478e4496)] - **src**: use NAPI\_NOEXCEPT macro instead of noexcept (NickNaso) [#864](https://github.com/nodejs/node-addon-api/pull/864) +* [[`744705f2eb`](https://github.com/nodejs/node-addon-api/commit/744705f2eb)] - **test**: refactor remove repeated execution index.js (raisinten) [#839](https://github.com/nodejs/node-addon-api/pull/839) +* [[`db62e3c811`](https://github.com/nodejs/node-addon-api/commit/db62e3c811)] - Update team members (Michael Dawson) + +## 2020-12-17 Version 3.1.0, @NickNaso + +### Notable changes: + +#### API + +- Added `Napi::TypedThreadSafeFunction` class that is a new implementation for +thread-safe functions. +- Fixed leak on `Napi::AsyncProgressWorkerBase`. +- Fixed empty data on `Napi::AsyncProgressWorker::OnProgress` caused by race +conditions of `Napi::AsyncProgressWorker`. +- Added `Napi::ArrayBuffer::Detach()` and `Napi::ArrayBuffer::IsDetached()`. +- Fixed problem on `Napi::FinalizeCallback` it needs to create a +`Napi::HandleScope` when it calls `Napi::ObjectWrap::~ObjectWrap()`. + +#### Documentation + +- Added documentation for `Napi::TypedThreadSafeFunction`. +- Removed unsued Doxygen file. +- Clarified when to use N-API. +- Added support information. +- Some minor corrections all over the documentation. + +#### TEST + +- Added test for `Napi::TypedThreadSafeFunction`. +- Fixed testing for specific N-API version. +- Some minor corrections all over the test suite. + +### TOOL + +- Setup github actions for tests. +- Added stale action. +- Removed `sudo` tag from Travis CI. +- Added clang-format. +- Added pre-commit package for linting. + +### Commits + +* [[`ff642c5b85`](https://github.com/nodejs/node-addon-api/commit/ff642c5b85)] - **doc**: fix tsfn docs to reflect true implementation (#860) (Kevin Eady) +* [[`86feeebf54`](https://github.com/nodejs/node-addon-api/commit/86feeebf54)] - **src**: empty data OnProgress in AsyncProgressWorker (legendecas) [#853](https://github.com/nodejs/node-addon-api/pull/853) +* [[`a7fb5fb31c`](https://github.com/nodejs/node-addon-api/commit/a7fb5fb31c)] - **action**: add stale action (#856) (Michael Dawson) +* [[`fd44609885`](https://github.com/nodejs/node-addon-api/commit/fd44609885)] - **chore**: setup github actions for tests (#854) (legendecas) [#854](https://github.com/nodejs/node-addon-api/pull/854) +* [[`c52ace4813`](https://github.com/nodejs/node-addon-api/commit/c52ace4813)] - **script**: fix complains that js files are not supported on npm run lint:fix (#852) (legendecas) +* [[`b4a3364ad5`](https://github.com/nodejs/node-addon-api/commit/b4a3364ad5)] - **doc**: remove unused Doxygen file (#851) (Michael Dawson) +* [[`b810466ae2`](https://github.com/nodejs/node-addon-api/commit/b810466ae2)] - **doc**: clarify when to use N-API (#849) (Michael Dawson) +* [[`528b9f6832`](https://github.com/nodejs/node-addon-api/commit/528b9f6832)] - **test**: remove sudo from travis (#850) (Michael Dawson) +* [[`4bb680de4e`](https://github.com/nodejs/node-addon-api/commit/4bb680de4e)] - Remove misleading sentence (#847) (Nikolai Vavilov) [#847](https://github.com/nodejs/node-addon-api/pull/847) +* [[`48e6b584a3`](https://github.com/nodejs/node-addon-api/commit/48e6b584a3)] - Merge pull request #742 from KevinEady/contexted-tsfn-api-gcc-4 (Gabriel Schulhof) +* [[`d5e37210cc`](https://github.com/nodejs/node-addon-api/commit/d5e37210cc)] - **tools**: print more instructions on clang-format check failed (#846) (legendecas) [#846](https://github.com/nodejs/node-addon-api/pull/846) +* [[`d9e11ff2c9`](https://github.com/nodejs/node-addon-api/commit/d9e11ff2c9)] - **doc**: add support info (#843) (Michael Dawson) [#843](https://github.com/nodejs/node-addon-api/pull/843) +* [[`356e93d69a`](https://github.com/nodejs/node-addon-api/commit/356e93d69a)] - **test**: fixup testing for specific N-API version (#840) (Michael Dawson) [#840](https://github.com/nodejs/node-addon-api/pull/840) +* [[`5e5b9ce1b7`](https://github.com/nodejs/node-addon-api/commit/5e5b9ce1b7)] - Apply formatting changes (Kevin Eady) +* [[`559ad8c0c0`](https://github.com/nodejs/node-addon-api/commit/559ad8c0c0)] - Merge remote-tracking branch 'upstream/master' into contexted-tsfn-api-gcc-4 (Kevin Eady) +* [[`c24c455ced`](https://github.com/nodejs/node-addon-api/commit/c24c455ced)] - Rename to TypedThreadSafeFunction (Kevin Eady) +* [[`63b43f4125`](https://github.com/nodejs/node-addon-api/commit/63b43f4125)] - **test**: fix buildType bug objectwrap\_worker\_thread (raisinten) [#837](https://github.com/nodejs/node-addon-api/pull/837) +* [[`6321f2ba1a`](https://github.com/nodejs/node-addon-api/commit/6321f2ba1a)] - **test**: fix typos in addon\_build/index.js (raisinten) [#838](https://github.com/nodejs/node-addon-api/pull/838) +* [[`59c6a6aeb0`](https://github.com/nodejs/node-addon-api/commit/59c6a6aeb0)] - **fix**: git-clang-format doesn't recognize no changes requested on given files (#835) (legendecas) +* [[`1427b3ef78`](https://github.com/nodejs/node-addon-api/commit/1427b3ef78)] - **src**: create a HandleScope in FinalizeCallback (blagoev) [#832](https://github.com/nodejs/node-addon-api/pull/832) +* [[`8fb5820557`](https://github.com/nodejs/node-addon-api/commit/8fb5820557)] - **build**: add incremental clang-format checks (legendecas) [#819](https://github.com/nodejs/node-addon-api/pull/819) +* [[`2c02d317e5`](https://github.com/nodejs/node-addon-api/commit/2c02d317e5)] - **build**: add pre-commit package for linting (#823) (Kevin Eady) +* [[`1b52c28eb8`](https://github.com/nodejs/node-addon-api/commit/1b52c28eb8)] - Clean up AsyncProgressWorker documentation (#831) (mastergberry) +* [[`4abe7cfe30`](https://github.com/nodejs/node-addon-api/commit/4abe7cfe30)] - **test**: rename tsfnex test files (Kevin Eady) +* [[`c9563caa25`](https://github.com/nodejs/node-addon-api/commit/c9563caa25)] - **src**: add ArrayBuffer::Detach() and ::IsDetached() (Tobias Nießen) [#659](https://github.com/nodejs/node-addon-api/pull/659) +* [[`c79cabaed2`](https://github.com/nodejs/node-addon-api/commit/c79cabaed2)] - **doc**: avoid directing users to HTTP (#828) (Tobias Nießen) +* [[`7a13f861ab`](https://github.com/nodejs/node-addon-api/commit/7a13f861ab)] - **doc**: fix additional typo (Kevin Eady) +* [[`7ec9741dd2`](https://github.com/nodejs/node-addon-api/commit/7ec9741dd2)] - Merge remote-tracking branch 'upstream/master' into contexted-tsfn-api-gcc-4 (Kevin Eady) +* [[`f5fad239fa`](https://github.com/nodejs/node-addon-api/commit/f5fad239fa)] - Update object\_reference.md (#827) (kidneysolo) +* [[`35b65712c2`](https://github.com/nodejs/node-addon-api/commit/35b65712c2)] - **Fix**: some typos in documentation (#826) (Helio Frota) +* [[`8983383000`](https://github.com/nodejs/node-addon-api/commit/8983383000)] - **Fix**: some typos in the document (#825) (Ziqiu Zhao) +* [[`826e466ef6`](https://github.com/nodejs/node-addon-api/commit/826e466ef6)] - Fixed example in addon.md. (#820) (nempoBu4) [#820](https://github.com/nodejs/node-addon-api/pull/820) +* [[`b54f5eb788`](https://github.com/nodejs/node-addon-api/commit/b54f5eb788)] - Additional changes from review (Kevin Eady) +* [[`59f27dac9a`](https://github.com/nodejs/node-addon-api/commit/59f27dac9a)] - Fix common.gypi (Kevin Eady) +* [[`151a914c99`](https://github.com/nodejs/node-addon-api/commit/151a914c99)] - Apply documentation suggestions from code review (Kevin Eady) +* [[`ceb27d4949`](https://github.com/nodejs/node-addon-api/commit/ceb27d4949)] - **src**: fix leak in AsyncProgressWorkerBase\ (Ferdinand Holzer) [#795](https://github.com/nodejs/node-addon-api/pull/795) + +## 2020-09-18 Version 3.0.2, @NickNaso + +### Notable changes: + +#### API + +- Introduced `include_dir` for use with **gyp** in a scalar context. +- Added `Napi::Addon` to help handle the loading of a native add-on into +multiple threads and or multiple times in the same thread. +- Concentrate callbacks provided to core N-API. +- Make sure wrapcallback is used. + +#### Documentation + +- Added documentation for `Napi::Addon`. +- Added documentation that reports the full class hierarchy. +- Added link to N-API tutorial website. +- Some minor corrections all over the documentation. + +#### TEST + +- Added tests to check the build process. +- Refactored test for threasfafe function using async/await. +- Converted tests that gc into async functions that await 10 ticks after +each gc. +- Some minor corrections all over the test suite. + +### Commits + +* [[`51e25f7c39`](https://github.com/nodejs/node-addon-api/commit/51e25f7c39)] - **doc**: remove a file (#815) (Gabriel Schulhof) +* [[`8c9f1809a2`](https://github.com/nodejs/node-addon-api/commit/8c9f1809a2)] - **doc**: add inheritance links and other changes (Gabriel Schulhof) [#798](https://github.com/nodejs/node-addon-api/pull/798) +* [[`6562e6b0ab`](https://github.com/nodejs/node-addon-api/commit/6562e6b0ab)] - **test**: added tests to check the build process (NickNaso) [#808](https://github.com/nodejs/node-addon-api/pull/808) +* [[`a13b36c96e`](https://github.com/nodejs/node-addon-api/commit/a13b36c96e)] - **test**: fix the threasfafe function test (NickNaso) [#807](https://github.com/nodejs/node-addon-api/pull/807) +* [[`f27623ff61`](https://github.com/nodejs/node-addon-api/commit/f27623ff61)] - **build**: introduce include\_dir (Lovell Fuller) [#766](https://github.com/nodejs/node-addon-api/pull/766) +* [[`9aceea71fc`](https://github.com/nodejs/node-addon-api/commit/9aceea71fc)] - **src**: concentrate callbacks provided to core N-API (Gabriel Schulhof) [#786](https://github.com/nodejs/node-addon-api/pull/786) +* [[`2bc45bbffd`](https://github.com/nodejs/node-addon-api/commit/2bc45bbffd)] - **test**: refactor test to use async/await (Velmisov) [#787](https://github.com/nodejs/node-addon-api/pull/787) +* [[`518cfdcdc1`](https://github.com/nodejs/node-addon-api/commit/518cfdcdc1)] - **test**: test ObjectWrap destructor - no HandleScope (David Halls) [#729](https://github.com/nodejs/node-addon-api/pull/729) +* [[`c2cbbd9191`](https://github.com/nodejs/node-addon-api/commit/c2cbbd9191)] - **doc**: add link to n-api tutorial website (#794) (Jim Schlight) [#794](https://github.com/nodejs/node-addon-api/pull/794) +* [[`1c2a8d59b5`](https://github.com/nodejs/node-addon-api/commit/1c2a8d59b5)] - **doc**: Added required return to example (#793) (pacop) [#793](https://github.com/nodejs/node-addon-api/pull/793) +* [[`cec2c76941`](https://github.com/nodejs/node-addon-api/commit/cec2c76941)] - **src**: wrap finalizer callback (Gabriel Schulhof) [#762](https://github.com/nodejs/node-addon-api/pull/762) +* [[`4ce40d22a6`](https://github.com/nodejs/node-addon-api/commit/4ce40d22a6)] - **test**: use assert.strictEqual() (Koki Nishihara) [#777](https://github.com/nodejs/node-addon-api/pull/777) +* [[`461e3640c6`](https://github.com/nodejs/node-addon-api/commit/461e3640c6)] - **test**: string tests together (Gabriel Schulhof) [#773](https://github.com/nodejs/node-addon-api/pull/773) +* [[`5af645f649`](https://github.com/nodejs/node-addon-api/commit/5af645f649)] - **src**: add Addon\ class (Gabriel Schulhof) [#749](https://github.com/nodejs/node-addon-api/pull/749) +* [[`6148fb4bcc`](https://github.com/nodejs/node-addon-api/commit/6148fb4bcc)] - Synchronise Node.js versions in Appveyor Windows CI with Travis (#768) (Lovell Fuller) + +## 2020-07-13 Version 3.0.1, @NickNaso + +### Notable changes: + +#### API + +- Fixed the usage of `Napi::Reference` with `Napi::TypedArray`. +- Fixed `Napi::ObjectWrap` inheritance. + +#### Documentation + +- Updated the example for `Napi::ObjectWrap`. +- Added documentation for instance data APIs. +- Some minor corrections all over the documentation. + +#### TEST + +- Fixed test for `Napi::ArrayBuffer` and `Napi::Buffer`. +- Some minor corrections all over the test suite. + +### Commits + +* [[`40c7926342`](https://github.com/nodejs/node-addon-api/commit/40c7926342)] - **build**: ensure paths with spaces can be used (Lovell Fuller) [#757](https://github.com/nodejs/node-addon-api/pull/757) +* [[`ef16dfb4a2`](https://github.com/nodejs/node-addon-api/commit/ef16dfb4a2)] - **doc**: update ObjectWrap example (Gabriel Schulhof) [#754](https://github.com/nodejs/node-addon-api/pull/754) +* [[`48f6762bf6`](https://github.com/nodejs/node-addon-api/commit/48f6762bf6)] - **src**: add \_\_wasm32\_\_ guards (Gus Caplan) +* [[`bd2c5ec502`](https://github.com/nodejs/node-addon-api/commit/bd2c5ec502)] - Fixes issue 745. (#748) (Nicola Del Gobbo) +* [[`4c01af2d87`](https://github.com/nodejs/node-addon-api/commit/4c01af2d87)] - Fix typo in CHANGELOG (#715) (Kasumi Hanazuki) +* [[`36e1af96d5`](https://github.com/nodejs/node-addon-api/commit/36e1af96d5)] - **src**: fix use of Reference with typed arrays (Michael Dawson) [#726](https://github.com/nodejs/node-addon-api/pull/726) +* [[`d463f02bc7`](https://github.com/nodejs/node-addon-api/commit/d463f02bc7)] - **src**: fix testEnumerables on ObjectWrap (Ferdinand Holzer) [#736](https://github.com/nodejs/node-addon-api/pull/736) +* [[`ba7ad37d44`](https://github.com/nodejs/node-addon-api/commit/ba7ad37d44)] - **src**: fix ObjectWrap inheritance (David Halls) [#732](https://github.com/nodejs/node-addon-api/pull/732) +* [[`31504c862b`](https://github.com/nodejs/node-addon-api/commit/31504c862b)] - **doc**: fix minor typo in object\_wrap.md (#741) (Daniel Bevenius) [#741](https://github.com/nodejs/node-addon-api/pull/741) +* [[`beccf2145d`](https://github.com/nodejs/node-addon-api/commit/beccf2145d)] - **test**: fix up delays for array buffer test (Michael Dawson) [#737](https://github.com/nodejs/node-addon-api/pull/737) +* [[`45cb1d9748`](https://github.com/nodejs/node-addon-api/commit/45cb1d9748)] - Correct AsyncProgressWorker link in README (#716) (Jeroen Janssen) +* [[`381c0da60c`](https://github.com/nodejs/node-addon-api/commit/381c0da60c)] - **doc**: add instance data APIs (Gabriel Schulhof) [#708](https://github.com/nodejs/node-addon-api/pull/708) + +## 2020-04-30 Version 3.0.0, @NickNaso + +### Notable changes: + +#### API + +- `Napi::Object` added templated property descriptors. +- `Napi::ObjectWrap` added templated methods. +- `Napi::ObjectWrap` the wrap is removed only on failure. +- `Napi::ObjectWrap` the constructor's exceptions are gracefully handled. +- `Napi::Function` added templated factory functions. +- Added `Env::RunScript` method to run JavaScript code contained in a string. +- Added templated version of `Napi::Function`. +- Added benchmarking framework. +- Added support for native addon instance data. +- Added `Napi::AsyncProgressQueueWorker` api. +- Changed the guards to `NAPI_VERSION > 5`. +- Removed N-API implementation (v6.x and v8.x support). +- `Napi::AsyncWorker::OnWorkComplete` and `Napi::AsyncWorker::OnExecute` methods +are override-able. +- Removed erroneous finalizer cleanup in `Napi::ThreadSafeFunction`. +- Disabled caching in `Napi::ArrayBuffer`. +- Explicitly disallow assign and copy operator. +- Some minor corrections and improvements. + +#### Documentation + +- Updated documentation for `Napi::Object`. +- Updated documentation for `Napi::Function`. +- Updated documentation for `Napi::ObjectWrap`. +- Added documentation on how to add benchmark. +- Added documentation for `Napi::AsyncProgressQueueWorker`. +- Added suggestion about tags to use on NPM. +- Added reference to N-API badges. +- Some minor corrections all over the documentation. + +#### TEST + +- Updated test cases for `Napi::Object`. +- Updated test cases for `Napi::Function`. +- Updated test cases for `Napi::ObjectWrap`. +- Updated test cases for `Napi::Env`. +- Added test cases for `Napi::AsyncProgressQueueWorker`. +- Some minor corrections all over the test suite. + +### Commits + +* [[`187318e37f`](https://github.com/nodejs/node-addon-api/commit/187318e37f)] - **doc**: Removed references to Node.js lower than 10.x. (#709) (Nicola Del Gobbo) +* [[`9c9accfbbe`](https://github.com/nodejs/node-addon-api/commit/9c9accfbbe)] - **src**: add support for addon instance data (Gabriel Schulhof) [#663](https://github.com/nodejs/node-addon-api/pull/663) +* [[`82a96502a4`](https://github.com/nodejs/node-addon-api/commit/82a96502a4)] - **src**: change guards to NAPI\_VERSION \> 5 (Gabriel Schulhof) [#697](https://github.com/nodejs/node-addon-api/pull/697) +* [[`a64e8a5641`](https://github.com/nodejs/node-addon-api/commit/a64e8a5641)] - **ci**: move travis from 13 to 14 (#707) (Gabriel Schulhof) +* [[`4de23c9d6b`](https://github.com/nodejs/node-addon-api/commit/4de23c9d6b)] - **doc**: fix support bigint64/biguint64 guards (Yulong Wang) [#705](https://github.com/nodejs/node-addon-api/pull/705) +* [[`fedc8195e3`](https://github.com/nodejs/node-addon-api/commit/fedc8195e3)] - **doc**: fix semicolon missing in async\_worker.md (Azlan Mukhtar) [#701](https://github.com/nodejs/node-addon-api/pull/701) +* [[`cdb662506c`](https://github.com/nodejs/node-addon-api/commit/cdb662506c)] - **doc**: fix typo in bigint.md (#700) (Kelvin) +* [[`e1a827ae29`](https://github.com/nodejs/node-addon-api/commit/e1a827ae29)] - **src**: fix AsyncProgressQueueWorker compilation (#696) (Gabriel Schulhof) [#696](https://github.com/nodejs/node-addon-api/pull/696) +* [[`2c3d5df463`](https://github.com/nodejs/node-addon-api/commit/2c3d5df463)] - Merge pull request #692 from kelvinhammond/patch-1 (Nicola Del Gobbo) +* [[`623e876949`](https://github.com/nodejs/node-addon-api/commit/623e876949)] - Merge pull request #688 from NickNaso/badges (Nicola Del Gobbo) +* [[`6c97913d1f`](https://github.com/nodejs/node-addon-api/commit/6c97913d1f)] - Fix minor typo in object\_lifetime\_management.md (Kelvin) +* [[`6b8dd47c55`](https://github.com/nodejs/node-addon-api/commit/6b8dd47c55)] - Added badge section to documentation. (NickNaso) +* [[`89e62a9154`](https://github.com/nodejs/node-addon-api/commit/89e62a9154)] - **doc**: recommend tags of addon helpers (legendecas) [#683](https://github.com/nodejs/node-addon-api/pull/683) +* [[`ab018444ae`](https://github.com/nodejs/node-addon-api/commit/ab018444ae)] - **src**: implement AsyncProgressQueueWorker (legendecas) [#585](https://github.com/nodejs/node-addon-api/pull/585) +* [[`d43da6ac2b`](https://github.com/nodejs/node-addon-api/commit/d43da6ac2b)] - **doc**: add @legendecas to active member list (legendecas) +* [[`cb498bbe7f`](https://github.com/nodejs/node-addon-api/commit/cb498bbe7f)] - **doc**: Add Napi::BigInt::New() overload for uint64\_t (ikokostya) +* [[`baaaa8452c`](https://github.com/nodejs/node-addon-api/commit/baaaa8452c)] - **doc**: link threadsafe function from JS function (legendecas) +* [[`7f56a78ff7`](https://github.com/nodejs/node-addon-api/commit/7f56a78ff7)] - **objectwrap**: remove wrap only on failure (Gabriel Schulhof) +* [[`4d816183da`](https://github.com/nodejs/node-addon-api/commit/4d816183da)] - **doc**: fix example code (András Timár, Dr) [#657](https://github.com/nodejs/node-addon-api/pull/657) +* [[`7ac6e21801`](https://github.com/nodejs/node-addon-api/commit/7ac6e21801)] - **gyp**: fix gypfile name in index.js (Anna Henningsen) [#658](https://github.com/nodejs/node-addon-api/pull/658) +* [[`46484202ca`](https://github.com/nodejs/node-addon-api/commit/46484202ca)] - **test**: user data in function property descriptor (Kevin Eady) [#652](https://github.com/nodejs/node-addon-api/pull/652) +* [[`0f8d730483`](https://github.com/nodejs/node-addon-api/commit/0f8d730483)] - **doc**: fix syntax error in example (András Timár, Dr) [#650](https://github.com/nodejs/node-addon-api/pull/650) +* [[`4e885069f1`](https://github.com/nodejs/node-addon-api/commit/4e885069f1)] - **src**: call `napi\_remove\_wrap()` in `ObjectWrap` dtor (Anna Henningsen) [#475](https://github.com/nodejs/node-addon-api/pull/475) +* [[`2fde5c3ca3`](https://github.com/nodejs/node-addon-api/commit/2fde5c3ca3)] - **test**: update BigInt test for recent change in core (Michael Dawson) [#649](https://github.com/nodejs/node-addon-api/pull/649) +* [[`e8935bd8d9`](https://github.com/nodejs/node-addon-api/commit/e8935bd8d9)] - **test**: add test for own properties on ObjectWrap (Guenter Sandner) [#645](https://github.com/nodejs/node-addon-api/pull/645) +* [[`23ff7f0b24`](https://github.com/nodejs/node-addon-api/commit/23ff7f0b24)] - **src**: make OnWorkComplete and OnExecute override-able (legendecas) [#589](https://github.com/nodejs/node-addon-api/pull/589) +* [[`86384f94d3`](https://github.com/nodejs/node-addon-api/commit/86384f94d3)] - **objectwrap**: gracefully handle constructor exceptions (Gabriel Schulhof) +* [[`9af69da01f`](https://github.com/nodejs/node-addon-api/commit/9af69da01f)] - remove N-API implementation, v6.x and v8.x support (Gabriel Schulhof) [#643](https://github.com/nodejs/node-addon-api/pull/643) +* [[`920d544779`](https://github.com/nodejs/node-addon-api/commit/920d544779)] - **benchmark**: add templated version of Function (Gabriel Schulhof) [#637](https://github.com/nodejs/node-addon-api/pull/637) +* [[`03759f7759`](https://github.com/nodejs/node-addon-api/commit/03759f7759)] - ignore benchmark built archives (legendecas) [#631](https://github.com/nodejs/node-addon-api/pull/631) +* [[`5eeabb0214`](https://github.com/nodejs/node-addon-api/commit/5eeabb0214)] - **tsfn**: Remove erroneous finalizer cleanup (Kevin Eady) [#636](https://github.com/nodejs/node-addon-api/pull/636) +* [[`9e0e0f31e4`](https://github.com/nodejs/node-addon-api/commit/9e0e0f31e4)] - **src**: remove unnecessary forward declarations (Gabriel Schulhof) [#633](https://github.com/nodejs/node-addon-api/pull/633) +* [[`79deefb6f3`](https://github.com/nodejs/node-addon-api/commit/79deefb6f3)] - **src**: explicitly disallow assign and copy (legendecas) [#590](https://github.com/nodejs/node-addon-api/pull/590) +* [[`af50ac281b`](https://github.com/nodejs/node-addon-api/commit/af50ac281b)] - **error**: do not replace pending exception (Gabriel Schulhof) [#629](https://github.com/nodejs/node-addon-api/pull/629) +* [[`b72f1d6978`](https://github.com/nodejs/node-addon-api/commit/b72f1d6978)] - Disable caching in ArrayBuffer (Tobias Nießen) [#611](https://github.com/nodejs/node-addon-api/pull/611) +* [[`0e7483eb7b`](https://github.com/nodejs/node-addon-api/commit/0e7483eb7b)] - Fix code format in tests (Tobias Nießen) [#617](https://github.com/nodejs/node-addon-api/pull/617) +* [[`6a0646356d`](https://github.com/nodejs/node-addon-api/commit/6a0646356d)] - add benchmarking framework (Gabriel Schulhof) [#623](https://github.com/nodejs/node-addon-api/pull/623) +* [[`ffc71edd54`](https://github.com/nodejs/node-addon-api/commit/ffc71edd54)] - Add Env::RunScript (Tobias Nießen) [#616](https://github.com/nodejs/node-addon-api/pull/616) +* [[`a1b106066e`](https://github.com/nodejs/node-addon-api/commit/a1b106066e)] - **src**: add templated function factories (Gabriel Schulhof) [#608](https://github.com/nodejs/node-addon-api/pull/608) +* [[`c584343217`](https://github.com/nodejs/node-addon-api/commit/c584343217)] - Add GetPropertyNames, HasOwnProperty, Delete (#615) (Tobias Nießen) [#615](https://github.com/nodejs/node-addon-api/pull/615) +* [[`3acc4b32f5`](https://github.com/nodejs/node-addon-api/commit/3acc4b32f5)] - Fix std::string encoding (#619) (Tobias Nießen) [#619](https://github.com/nodejs/node-addon-api/pull/619) +* [[`e71d0eadcc`](https://github.com/nodejs/node-addon-api/commit/e71d0eadcc)] - \[doc\] Fixed links to array documentation (#613) (Nicola Del Gobbo) +* [[`3dfb1f0591`](https://github.com/nodejs/node-addon-api/commit/3dfb1f0591)] - Change "WG" to "team" (Tobias Nießen) +* [[`ce91e14860`](https://github.com/nodejs/node-addon-api/commit/ce91e14860)] - **objectwrap**: add template methods (Dmitry Ashkadov) [#604](https://github.com/nodejs/node-addon-api/pull/604) +* [[`cfa71b60f7`](https://github.com/nodejs/node-addon-api/commit/cfa71b60f7)] - **object**: add templated property descriptors (Gabriel Schulhof) [#610](https://github.com/nodejs/node-addon-api/pull/610) +* [[`734725e971`](https://github.com/nodejs/node-addon-api/commit/734725e971)] - Correctly define copy assignment operators. (Rolf Timmermans) + +## 2019-11-21 Version 2.0.0, @NickNaso + +### Notable changes: + +#### API + +- Added `Napi::AsyncProgressWorker` api. +- Added error checking on `Napi::ThreadSafeFunction::GetContext`. +- Added copy constructor to `Napi::ThreadSafeFunction`. +- Added `Napi::ThreadSafeFunction::Ref` and `Napi::ThreadSafeFunction::Unref` to `Napi::ThreadSafeFunction`. +- Added `Napi::Object::AddFinalizer` method. +- Use `napi_add_finalizer()` to attach data when building against N-API 5. +- Added `Napi::Date` api. +- Added `Napi::ObjectWrap::Finalize` method. + +#### Documentation + +- Added documentation for `Napi::AsyncProgressWorker`. +- Improve `Napi::AsyncWorker` documentation. +- Added documentation for `Napi::Object::AddFinalizer` method. +- Improved documentation for `Napi::ThreadSafeFunction`. +- Improved documentation about the usage of CMake as build tool. +- Some minor corrections all over the documentation. + +#### TEST + +- Added test cases for `Napi::AsyncProgressWorker` api. +- Added test cases for `Napi::Date` api. +- Added test cases for new features added to `Napi::ThreadSafeFunction`. + +### Commits + +* [[`c881168d49`](https://github.com/nodejs/node-addon-api/commit/c881168d49)] - **tsfn**: add error checking on GetContext (#583) (Kevin Eady) [#583](https://github.com/nodejs/node-addon-api/pull/583) +* [[`24d75dd82f`](https://github.com/nodejs/node-addon-api/commit/24d75dd82f)] - Merge pull request #588 from NickNaso/add-asyncprogress-worker-readme (Nicola Del Gobbo) +* [[`aa79e37b62`](https://github.com/nodejs/node-addon-api/commit/aa79e37b62)] - Merge pull request #587 from timrach/patch-1 (Nicola Del Gobbo) +* [[`df75e08c2b`](https://github.com/nodejs/node-addon-api/commit/df75e08c2b)] - **tsfn**: support direct calls to underlying napi\_tsfn (Kevin Eady) [#58](https://github.com/nodejs/node-addon-api/pull/58) +* [[`2298dfae58`](https://github.com/nodejs/node-addon-api/commit/2298dfae58)] - **doc**: Added AsyncProgressWorker to readme (NickNaso) +* [[`b3609d33b6`](https://github.com/nodejs/node-addon-api/commit/b3609d33b6)] - Fix return type and declaration of setter callback (Tim Rach) +* [[`295e560f55`](https://github.com/nodejs/node-addon-api/commit/295e560f55)] - **test**: improve guards for experimental features (legendecas) +* [[`2e71842f63`](https://github.com/nodejs/node-addon-api/commit/2e71842f63)] - **tsfn**: Implement copy constructor (Kevin Eady) [#546](https://github.com/nodejs/node-addon-api/pull/546) +* [[`650562cab9`](https://github.com/nodejs/node-addon-api/commit/650562cab9)] - **src**: implement AsyncProgressWorker (legendecas) [#529](https://github.com/nodejs/node-addon-api/pull/529) +* [[`bdfd14101f`](https://github.com/nodejs/node-addon-api/commit/bdfd14101f)] - **src**: attach data with napi\_add\_finalizer (Gabriel Schulhof) [#577](https://github.com/nodejs/node-addon-api/pull/577) +* [[`9e955a802b`](https://github.com/nodejs/node-addon-api/commit/9e955a802b)] - **doc**: change node.js to Node.js per guideline (#579) (Tobias Nießen) [#579](https://github.com/nodejs/node-addon-api/pull/579) +* [[`b42e21e3a9`](https://github.com/nodejs/node-addon-api/commit/b42e21e3a9)] - **build**: move node/6 to travis allowed failures and add node/13 (#573) (Gabriel Schulhof) +* [[`8d6132f609`](https://github.com/nodejs/node-addon-api/commit/8d6132f609)] - **doc**: improve AsyncWorker docs (#571) (legendecas) [#571](https://github.com/nodejs/node-addon-api/pull/571) +* [[`bc8fc23627`](https://github.com/nodejs/node-addon-api/commit/bc8fc23627)] - **test**: do not run TSFN tests on NAPI\_VERSION \< 4 (legendecas) [#576](https://github.com/nodejs/node-addon-api/pull/576) +* [[`bcc1d58fc4`](https://github.com/nodejs/node-addon-api/commit/bcc1d58fc4)] - implement Object::AddFinalizer (Gabriel Schulhof) +* [[`e9a4bcd52a`](https://github.com/nodejs/node-addon-api/commit/e9a4bcd52a)] - **doc**: updates Make.js doc to current best practices (Jim Schlight) [#558](https://github.com/nodejs/node-addon-api/pull/558) +* [[`b513d1aa7a`](https://github.com/nodejs/node-addon-api/commit/b513d1aa7a)] - **doc**: fix return type of ArrayBuffer::Data (Tobias Nießen) [#552](https://github.com/nodejs/node-addon-api/pull/552) +* [[`34c11cf0a4`](https://github.com/nodejs/node-addon-api/commit/34c11cf0a4)] - **src**: disallow copying, double close of scopes (legendecas) [#566](https://github.com/nodejs/node-addon-api/pull/566) +* [[`ce139a05e8`](https://github.com/nodejs/node-addon-api/commit/ce139a05e8)] - **src**: make failure of closing scopes fatal (legendecas) [#566](https://github.com/nodejs/node-addon-api/pull/566) +* [[`740c79823e`](https://github.com/nodejs/node-addon-api/commit/740c79823e)] - **src**: add Env() to AsyncContext (Rolf Timmermans) [#568](https://github.com/nodejs/node-addon-api/pull/568) +* [[`ea9ce1c801`](https://github.com/nodejs/node-addon-api/commit/ea9ce1c801)] - **tsfn**: add wrappers for Ref and Unref (Kevin Eady) [#561](https://github.com/nodejs/node-addon-api/pull/561) +* [[`2e1769e1a3`](https://github.com/nodejs/node-addon-api/commit/2e1769e1a3)] - **error**: remove unnecessary if condition (legendecas) [#562](https://github.com/nodejs/node-addon-api/pull/562) +* [[`828f223a87`](https://github.com/nodejs/node-addon-api/commit/828f223a87)] - **doc**: fix spelling in ObjectWrap doc (#563) (Tobias Nießen) [#563](https://github.com/nodejs/node-addon-api/pull/563) +* [[`dd9fa8a4a8`](https://github.com/nodejs/node-addon-api/commit/dd9fa8a4a8)] - **doc**: move Arunesh and Taylor to Emeritus (#540) (Michael Dawson) [#540](https://github.com/nodejs/node-addon-api/pull/540) +* [[`cf8b8415df`](https://github.com/nodejs/node-addon-api/commit/cf8b8415df)] - **doc**: add Kevin to the list of collaborators (#539) (Michael Dawson) [#539](https://github.com/nodejs/node-addon-api/pull/539) +* [[`5d6aeae7b5`](https://github.com/nodejs/node-addon-api/commit/5d6aeae7b5)] - **build**: enable travis for fast PR check (legendecas) +* [[`6192e705cd`](https://github.com/nodejs/node-addon-api/commit/6192e705cd)] - **src**: add napi\_date (Mathias Küsel) [#497](https://github.com/nodejs/node-addon-api/pull/497) +* [[`7b1ee96d52`](https://github.com/nodejs/node-addon-api/commit/7b1ee96d52)] - **doc**: update prebuild\_tools.md (Nurbol Alpysbayev) [#527](https://github.com/nodejs/node-addon-api/pull/527) +* [[`0b4f3a5b8c`](https://github.com/nodejs/node-addon-api/commit/0b4f3a5b8c)] - **tsfn**: fix crash on releasing tsfn (legendecas) [#532](https://github.com/nodejs/node-addon-api/pull/532) +* [[`c3c8814d2f`](https://github.com/nodejs/node-addon-api/commit/c3c8814d2f)] - implement virutal ObjectWrap::Finalize (Michael Price) [#515](https://github.com/nodejs/node-addon-api/pull/515) + +## 2019-07-23 Version 1.7.1, @NickNaso + +### Notable changes: + +#### API + +- Fixed compilation problems that happen on Node.js with N-API version less than 4. + +### Commits + +* [[`c20bcbd069`](https://github.com/nodejs/node-addon-api/commit/c20bcbd069)] - Merge pull request #518 from NickNaso/master (Nicola Del Gobbo) +* [[`6720d57253`](https://github.com/nodejs/node-addon-api/commit/6720d57253)] - Create the native threadsafe\_function for test only for N-API greater than 3. (NickNaso) +* [[`37b6c185ad`](https://github.com/nodejs/node-addon-api/commit/37b6c185ad)] - Fix compilation breakage on 1.7.0 (NickNaso) + +## 2019-07-23 Version 1.7.0, @NickNaso + +### Notable changes: + +#### API + +- Added `Napi::ThreadSafeFunction` api. +- Added `Napi::AsyncWorker::GetResult()` method to `Napi::AsyncWorker`. +- Added `Napi::AsyncWorker::Destroy()()` method to `Napi::AsyncWorker`. +- Use full namespace on macros that create the errors. + +#### Documentation + +- Added documentation about contribution philosophy. +- Added documentation for `Napi::ThreadSafeFunction`. +- Some minor corrections all over the documentation. + +#### TEST + +- Added test case for bool operator. +- Fixed test case for `Napi::ObjectWrap`. + +### Commits + +* [[`717c9ab163`](https://github.com/nodejs/node-addon-api/commit/717c9ab163)] - **AsyncWorker**: add GetResult() method (Kevin Eady) [#512](https://github.com/nodejs/node-addon-api/pull/512) +* [[`d9d991bbc9`](https://github.com/nodejs/node-addon-api/commit/d9d991bbc9)] - **doc**: add ThreadSafeFunction to main README (#513) (Kevin Eady) [#513](https://github.com/nodejs/node-addon-api/pull/513) +* [[`ac6000d0fd`](https://github.com/nodejs/node-addon-api/commit/ac6000d0fd)] - **doc**: fix minor typo (Yohei Kishimoto) [#510](https://github.com/nodejs/node-addon-api/pull/510) +* [[`e9fa1eaa86`](https://github.com/nodejs/node-addon-api/commit/e9fa1eaa86)] - **doc**: document ThreadSafeFunction (#494) (Kevin Eady) [#494](https://github.com/nodejs/node-addon-api/pull/494) +* [[`cab3b1e2a2`](https://github.com/nodejs/node-addon-api/commit/cab3b1e2a2)] - **doc**: ClassPropertyDescriptor example (Ross Weir) [#507](https://github.com/nodejs/node-addon-api/pull/507) +* [[`c32d7dbdcf`](https://github.com/nodejs/node-addon-api/commit/c32d7dbdcf)] - **macros**: create errors fully namespaced (Gabriel Schulhof) [#506](https://github.com/nodejs/node-addon-api/pull/506) +* [[`0a90df2fcb`](https://github.com/nodejs/node-addon-api/commit/0a90df2fcb)] - Implement ThreadSafeFunction class (Jinho Bang) +* [[`1fb540eeb5`](https://github.com/nodejs/node-addon-api/commit/1fb540eeb5)] - Use curly brackets to include node\_api.h (NickNaso) [#493](https://github.com/nodejs/node-addon-api/pull/493) +* [[`b2b08122ea`](https://github.com/nodejs/node-addon-api/commit/b2b08122ea)] - **AsyncWorker**: make callback optional (Kevin Eady) [#489](https://github.com/nodejs/node-addon-api/pull/489) +* [[`a0cac77c82`](https://github.com/nodejs/node-addon-api/commit/a0cac77c82)] - Added test for bool operator (NickNaso) [#490](https://github.com/nodejs/node-addon-api/pull/490) +* [[`ab7d8fcc48`](https://github.com/nodejs/node-addon-api/commit/ab7d8fcc48)] - **src**: fix objectwrap test case (Michael Dawson) [#495](https://github.com/nodejs/node-addon-api/pull/495) +* [[`3b6b9eb88a`](https://github.com/nodejs/node-addon-api/commit/3b6b9eb88a)] - **AsyncWorker**: introduce Destroy() method (Gabriel Schulhof) [#488](https://github.com/nodejs/node-addon-api/pull/488) +* [[`f633fbd95d`](https://github.com/nodejs/node-addon-api/commit/f633fbd95d)] - string.md: Document existing New(env, value, length) APIs (Tux3) [#486](https://github.com/nodejs/node-addon-api/pull/486) +* [[`aaea55eda9`](https://github.com/nodejs/node-addon-api/commit/aaea55eda9)] - Little fix on code example (Nicola Del Gobbo) [#470](https://github.com/nodejs/node-addon-api/pull/470) +* [[`e1cf9a35a1`](https://github.com/nodejs/node-addon-api/commit/e1cf9a35a1)] - Use `Value::IsEmpty` to check for empty value (NickNaso) [#478](https://github.com/nodejs/node-addon-api/pull/478) +* [[`3ad5dfc7d9`](https://github.com/nodejs/node-addon-api/commit/3ad5dfc7d9)] - Fix link (Alba Mendez) [#481](https://github.com/nodejs/node-addon-api/pull/481) +* [[`a3b4d99c45`](https://github.com/nodejs/node-addon-api/commit/a3b4d99c45)] - **doc**: Add contribution philosophy doc (Hitesh Kanwathirtha) +* [[`36863f087b`](https://github.com/nodejs/node-addon-api/commit/36863f087b)] - **doc**: refer to TypedArray and ArrayBuffer from Array (Gabriel "_|Nix|_" Schulhof) [#465](https://github.com/nodejs/node-addon-api/pull/465) + +## 2019-04-03 Version 1.6.3, @NickNaso + +### Notable changes: + +#### API + +- Added `SuppressDestruct` method to `Napi::AsyncWorker`. +- Added new build targets for debug. +- Exposed macros that throw errors. +- Fixed memory leaks caused by callback data when a napi error occurs. +- Fixed missing `void *data` usage in `Napi::PropertyDescriptors`. + +#### Documentation + +- Some minor corrections all over the documentation. + +### Commits + +* [[`83b41c2fe4`](https://github.com/nodejs/node-addon-api/commit/83b41c2fe4)] - Document adding -fvisibility=hidden flag for macOS users (Nicola Del Gobbo) [#460](https://github.com/nodejs/node-addon-api/pull/460) +* [[`1ed7ad8769`](https://github.com/nodejs/node-addon-api/commit/1ed7ad8769)] - **doc**: correct return type of Int32Value to int32\_t (Bill Gallafent) [#459](https://github.com/nodejs/node-addon-api/pull/459) +* [[`b0f6b601aa`](https://github.com/nodejs/node-addon-api/commit/b0f6b601aa)] - **src**: add AsyncWorker destruction suppression (Gabriel Schulhof) [#407](https://github.com/nodejs/node-addon-api/pull/407) +* [[`72b1975cff`](https://github.com/nodejs/node-addon-api/commit/72b1975cff)] - **doc**: fix links to the Property Descriptor docs (Ryuichi Okumura) [#458](https://github.com/nodejs/node-addon-api/pull/458) +* [[`fcfc612728`](https://github.com/nodejs/node-addon-api/commit/fcfc612728)] - **build**: new build targets for debug purposes (Jinho Bang) [#186](https://github.com/nodejs/node-addon-api/pull/186) +* [[`c629553cd7`](https://github.com/nodejs/node-addon-api/commit/c629553cd7)] - **doc**: minor doc corrections and clarifications (Bruce A. MacNaughton) [#426](https://github.com/nodejs/node-addon-api/pull/426) +* [[`7b87e0b999`](https://github.com/nodejs/node-addon-api/commit/7b87e0b999)] - **doc**: update number.md (Bernardo Heynemann) [#436](https://github.com/nodejs/node-addon-api/pull/436) +* [[`fcf173d2a1`](https://github.com/nodejs/node-addon-api/commit/fcf173d2a1)] - **src**: expose macros that throw errors (Gabriel Schulhof) [#448](https://github.com/nodejs/node-addon-api/pull/448) +* [[`b409a2f987`](https://github.com/nodejs/node-addon-api/commit/b409a2f987)] - **package**: add npm search keywords (Sam Roberts) [#452](https://github.com/nodejs/node-addon-api/pull/452) +* [[`0bc7987806`](https://github.com/nodejs/node-addon-api/commit/0bc7987806)] - **doc**: fix references to Weak and Persistent (Jake Barnes) [#428](https://github.com/nodejs/node-addon-api/pull/428) +* [[`ad6f569f85`](https://github.com/nodejs/node-addon-api/commit/ad6f569f85)] - **doc**: dix typo (Abhishek Kumar Singh) [#435](https://github.com/nodejs/node-addon-api/pull/435) +* [[`28df833a49`](https://github.com/nodejs/node-addon-api/commit/28df833a49)] - Merge pull request #441 from jschlight/master (Jim Schlight) +* [[`4921e74d83`](https://github.com/nodejs/node-addon-api/commit/4921e74d83)] - Rearranges names to be alphabetical (Jim Schlight) +* [[`48220335b0`](https://github.com/nodejs/node-addon-api/commit/48220335b0)] - Membership review update (Jim Schlight) +* [[`44f0695533`](https://github.com/nodejs/node-addon-api/commit/44f0695533)] - Merge pull request #394 from NickNaso/create\_release (Nicola DelGobbo) +* [[`fa49d68416`](https://github.com/nodejs/node-addon-api/commit/fa49d68416)] - **doc**: fix some `Finalizer` signatures (Philipp Renoth) [#414](https://github.com/nodejs/node-addon-api/pull/414) +* [[`020ac4a628`](https://github.com/nodejs/node-addon-api/commit/020ac4a628)] - **src**: make `Object::GetPropertyNames()` const (Philipp Renoth)[#415](https://github.com/nodejs/node-addon-api/pull/415) +* [[`91eaa6f4cb`](https://github.com/nodejs/node-addon-api/commit/91eaa6f4cb)] - **src**: fix callbackData leaks on error napi status (Philipp Renoth) [#417](https://github.com/nodejs/node-addon-api/pull/417) +* [[`0b40275752`](https://github.com/nodejs/node-addon-api/commit/0b40275752)] - **src**: fix noexcept control flow issues (Philipp Renoth) [#420](https://github.com/nodejs/node-addon-api/pull/420) +* [[`c1ff2936f9`](https://github.com/nodejs/node-addon-api/commit/c1ff2936f9)] - **src**: fix missing void\*data usage in PropertyDescriptors (Luciano Martorella) [#374](https://github.com/nodejs/node-addon-api/pull/374) + +## 2018-11-29 Version 1.6.2, @NickNaso + +### Notable changes: + +#### API + +- Fixed selection logic for version 6.x. + +### Commmits + +* [[`07a0fc4e95`](https://github.com/nodejs/node-addon-api/commit/07a0fc4e95)] - **src**: fix selection logic for 6.x (Michael Dawson) [#402](https://github.com/nodejs/node-addon-api/pull/402) + +## 2018-11-14 Version 1.6.1, @NickNaso + +### Notable changes: + +#### Documentation + +- Updated links for examples to point to node-addon-examples repo. +- Fixed typos on some parts of documentation. + +#### API + +- Removed unused member on `Napi::CallbackScope`. +- Enabled `Napi::CallbackScope` only with N-API v3. + +### Commits + +* [[`e7cd292a74`](https://github.com/nodejs/node-addon-api/commit/e7cd292a74)] - **src**: remove unused CallbackScope member (Gabriel Schulhof) [#391](https://github.com/nodejs/node-addon-api/pull/391) +* [[`d47399fe25`](https://github.com/nodejs/node-addon-api/commit/d47399fe25)] - **src**: guard CallbackScope with N-API v3 (Michael Dawson) [#395](https://github.com/nodejs/node-addon-api/pull/395) +* [[`29a0262ab9`](https://github.com/nodejs/node-addon-api/commit/29a0262ab9)] - **doc**: fix typo (Dongjin Na) [#385](https://github.com/nodejs/node-addon-api/pull/385) +* [[`b6dc15b88d`](https://github.com/nodejs/node-addon-api/commit/b6dc15b88d)] - **doc**: make links point to node-addon-examples repo (Nicola Del Gobbo) [#389](https://github.com/nodejs/node-addon-api/pull/389) + +## 2018-11-02 Version 1.6.0, @NickNaso + +### Notable changes: + +#### Documentation + +- Improved documentation about ABI stability. + +#### API + +- Add `Napi::CallbackScope` class that help to have the equivalent of the scope +associated with a callback in place when making certain N-API calls + +#### TEST + +- Added tests for `Napi::Array` class. +- Added tests for `Napi::ArrayBuffer` class. + +### Commits + +* [[`8ce605c657`](https://github.com/nodejs/node-addon-api/commit/8ce605c657)] - **build**: avoid using package-lock.json (Jaeseok Yoon) [#359](https://github.com/nodejs/node-addon-api/pull/359) +* [[`fa3a6150b3`](https://github.com/nodejs/node-addon-api/commit/fa3a6150b3)] - **src**: use MakeCallback() -\> Call() in AsyncWorker (Jinho Bang) [#361](https://github.com/nodejs/node-addon-api/pull/361) +* [[`2342415463`](https://github.com/nodejs/node-addon-api/commit/2342415463)] - **test**: create test objects in the stack instead of the heap (Dongjin Na) [#371](https://github.com/nodejs/node-addon-api/pull/371) +* [[`67b7db0a6f`](https://github.com/nodejs/node-addon-api/commit/67b7db0a6f)] - **test**: write tests for Array class (Jaeseok Yoon) [#363](https://github.com/nodejs/node-addon-api/pull/363) +* [[`729f6dc4ee`](https://github.com/nodejs/node-addon-api/commit/729f6dc4ee)] - **test**: add arraybuffer tests (Dongjin Na) [#369](https://github.com/nodejs/node-addon-api/pull/369) +* [[`405f3e5b5b`](https://github.com/nodejs/node-addon-api/commit/405f3e5b5b)] - **src**: implement CallbackScope class (Jinho Bang) [#362](https://github.com/nodejs/node-addon-api/pull/362) +* [[`015d95312f`](https://github.com/nodejs/node-addon-api/commit/015d95312f)] - **doc**: fix Napi::Reference link (Gentilhomme) [#365](https://github.com/nodejs/node-addon-api/pull/365) +* [[`fd65078e3c`](https://github.com/nodejs/node-addon-api/commit/fd65078e3c)] - README.md: link to new ABI stability guide (Gabriel Schulhof) [#367](https://github.com/nodejs/node-addon-api/pull/367) +* [[`ffebf9ba9a`](https://github.com/nodejs/node-addon-api/commit/ffebf9ba9a)] - Updates for release 1.5.0 (NickNaso) + +## 2018-10-03 Version 1.5.0, @NickNaso + +### Notable changes: + +#### Documentation + +- Completed the documentation to cover all the API surface. +- Numerous fixes to make documentation more consistent in all of its parts. + +#### API + +- Add `Napi::AsyncContext` class to handle asynchronous operation. +- Add `Napi::BigInt` class to work with BigInt type. +- Add `Napi::VersionManagement` class to retrieve the versions of Node.js and N-API. +- Fix potential memory leaks. +- DataView feature is enabled by default +- Add descriptor for Symbols +- Add new methods on `Napi::FunctionReference`. +- Add the possibility to retrieve the environment on `Napi::Promise::Deferred` + +#### TOOL + +- Add tool to check if a native add-on is built using N-API + +#### TEST + +- Start to increase the test coverage +- Fix in the test suite to better handle the experimental features that are not +yet backported in the previous Node.js version. + +### Commits + +* [[`2009c019af`](https://github.com/nodejs/node-addon-api/commit/2009c019af)] - Merge pull request #292 from devsnek/feature/bigint (Gus Caplan) +* [[`e44aca985e`](https://github.com/nodejs/node-addon-api/commit/e44aca985e)] - add bigint class (Gus Caplan) +* [[`a3951ab973`](https://github.com/nodejs/node-addon-api/commit/a3951ab973)] - Add documentation for Env(). (Rolf Timmermans) [#318](https://github.com/nodejs/node-addon-api/pull/318) +* [[`a6f7a6ad51`](https://github.com/nodejs/node-addon-api/commit/a6f7a6ad51)] - Add Env() to Promise::Deferred. (Rolf Timmermans) +* [[`0097e96b92`](https://github.com/nodejs/node-addon-api/commit/0097e96b92)] - Fixed broken links for Symbol and String (NickNaso) +* [[`b0ecd38d76`](https://github.com/nodejs/node-addon-api/commit/b0ecd38d76)] - Fix Code of conduct link properly (#323) (Jake Yoon) [#323](https://github.com/nodejs/node-addon-api/pull/323) +* [[`223474900f`](https://github.com/nodejs/node-addon-api/commit/223474900f)] - **doc**: update Version management (Dongjin Na) [#360](https://github.com/nodejs/node-addon-api/pull/360) +* [[`4f76262a10`](https://github.com/nodejs/node-addon-api/commit/4f76262a10)] - **doc**: some fix on `Napi::Boolean` documentation (NickNaso) [#354](https://github.com/nodejs/node-addon-api/pull/354) +* [[`78374f72d2`](https://github.com/nodejs/node-addon-api/commit/78374f72d2)] - **doc**: number documentation (NickNaso) [#356](https://github.com/nodejs/node-addon-api/pull/356) +* [[`51ffe453f8`](https://github.com/nodejs/node-addon-api/commit/51ffe453f8)] - **doc**: doc cleanup (NickNaso) [#353](https://github.com/nodejs/node-addon-api/pull/353) +* [[`fc11c944b2`](https://github.com/nodejs/node-addon-api/commit/fc11c944b2)] - **doc**: major doc cleanup (NickNaso) [#335](https://github.com/nodejs/node-addon-api/pull/335) +* [[`100d0a7cb2`](https://github.com/nodejs/node-addon-api/commit/100d0a7cb2)] - **doc**: first pass on objectwrap documentation (NickNaso) [#321](https://github.com/nodejs/node-addon-api/pull/321) +* [[`c7d54180ff`](https://github.com/nodejs/node-addon-api/commit/c7d54180ff)] - **doc**: the Napi::ObjectWrap example does not compile (Arnaud Botella) [#339](https://github.com/nodejs/node-addon-api/pull/339) +* [[`7cdd78726a`](https://github.com/nodejs/node-addon-api/commit/7cdd78726a)] - **doc**: added cpp highlight for string.md (Jaeseok Yoon) [#329](https://github.com/nodejs/node-addon-api/pull/329) +* [[`8ed29f547c`](https://github.com/nodejs/node-addon-api/commit/8ed29f547c)] - **doc**: add blurb about ABI stability (Gabriel Schulhof) [#326](https://github.com/nodejs/node-addon-api/pull/326) +* [[`757eb1f5a3`](https://github.com/nodejs/node-addon-api/commit/757eb1f5a3)] - **doc**: add function and function reference doc (NickNaso) [#299](https://github.com/nodejs/node-addon-api/pull/299) +* [[`2885c18591`](https://github.com/nodejs/node-addon-api/commit/2885c18591)] - **doc**: Create changelog for release 1.4.0 (Nicola Del Gobbo) +* [[`917bd60baa`](https://github.com/nodejs/node-addon-api/commit/917bd60baa)] - **src**: remove TODOs by fixing memory leaks (Gabriel Schulhof) [#343](https://github.com/nodejs/node-addon-api/pull/343) +* [[`dfcb93945f`](https://github.com/nodejs/node-addon-api/commit/dfcb93945f)] - **src**: implement AsyncContext class (Jinho Bang) [#252](https://github.com/nodejs/node-addon-api/pull/252) +* [[`211ed38d0d`](https://github.com/nodejs/node-addon-api/commit/211ed38d0d)] - **src**: make 'nothing' target a static library (Gabriel Schulhof) [#348](https://github.com/nodejs/node-addon-api/pull/348) +* [[`97c4ab5cf2`](https://github.com/nodejs/node-addon-api/commit/97c4ab5cf2)] - **src**: add Call and MakeCallback that accept cargs (NickNaso) [#344](https://github.com/nodejs/node-addon-api/pull/344) +* [[`b6e2d92c09`](https://github.com/nodejs/node-addon-api/commit/b6e2d92c09)] - **src**: enable DataView feature by default (Jinho) [#331](https://github.com/nodejs/node-addon-api/pull/331) +* [[`0a00e7c97b`](https://github.com/nodejs/node-addon-api/commit/0a00e7c97b)] - **src**: implement missing descriptor defs for symbols (Philipp Renoth) [#280](https://github.com/nodejs/node-addon-api/pull/280) +* [[`38e01b7e3b`](https://github.com/nodejs/node-addon-api/commit/38e01b7e3b)] - **src**: first pass on adding version management apis (NickNaso) [#325](https://github.com/nodejs/node-addon-api/pull/325) +* [[`79ee8381d2`](https://github.com/nodejs/node-addon-api/commit/79ee8381d2)] - **src**: fix compile failure in test (Michael Dawson) [#345](https://github.com/nodejs/node-addon-api/pull/345) +* [[`4d92a6066f`](https://github.com/nodejs/node-addon-api/commit/4d92a6066f)] - **src**: Add ObjectReference test case (Anisha Rohra) [#212](https://github.com/nodejs/node-addon-api/pull/212) +* [[`779560f397`](https://github.com/nodejs/node-addon-api/commit/779560f397)] - **test**: add operator overloading tests in Number (Your Name) [#355](https://github.com/nodejs/node-addon-api/pull/355) +* [[`73fed84ceb`](https://github.com/nodejs/node-addon-api/commit/73fed84ceb)] - **test**: add ability to control experimental tests (Michael Dawson) [#350](https://github.com/nodejs/node-addon-api/pull/350) +* [[`14c69abd46`](https://github.com/nodejs/node-addon-api/commit/14c69abd46)] - **test**: write tests for Boolean class (Jaeseok Yoon) [#328](https://github.com/nodejs/node-addon-api/pull/328) +* [[`2ad47a83b1`](https://github.com/nodejs/node-addon-api/commit/2ad47a83b1)] - **test**: explicitly cast to uint32\_t in test (Gabriel Schulhof) [#341](https://github.com/nodejs/node-addon-api/pull/341) +* [[`622ffaea76`](https://github.com/nodejs/node-addon-api/commit/622ffaea76)] - **test**: Tighten up compiler warnings (Mikhail Cheshkov) [#315](https://github.com/nodejs/node-addon-api/pull/315) +* [[`fd3c37b0f2`](https://github.com/nodejs/node-addon-api/commit/fd3c37b0f2)] - **tools**: add tool to check for N-API modules (Gabriel Schulhof) [#346](https://github.com/nodejs/node-addon-api/pull/346) + +## 2018-07-19 Version 1.4.0, @NickNaso + +### Notable changes: + +#### Documentation + +- Numerous additions to the documentation, filling out coverage + of API surface + +#### API + +- Add resource parameters to AsyncWorker constructor +- Add memory management feature + +### Commits + +* [[`7dc5ac8bc3`](https://github.com/nodejs/node-addon-api/commit/7dc5ac8bc3)] - **doc**: update metadata for release (Nicola Del Gobbo) +* [[`d68e86adb4`](https://github.com/nodejs/node-addon-api/commit/d68e86adb4)] - **doc**: Added documentation for PropertyDescriptor (Anisha Rohra) [#309](https://github.com/nodejs/node-addon-api/pull/309) +* [[`968a5f2000`](https://github.com/nodejs/node-addon-api/commit/968a5f2000)] - **doc**: Add documentation for ObjectReference.md (Anisha Rohra) [#307](https://github.com/nodejs/node-addon-api/pull/307) +* [[`908cdc314c`](https://github.com/nodejs/node-addon-api/commit/908cdc314c)] - **doc**: add `TypedArray` and `TypedArrayOf` (Kyle Farnung) [#305](https://github.com/nodejs/node-addon-api/pull/305) +* [[`2ff776ffe3`](https://github.com/nodejs/node-addon-api/commit/2ff776ffe3)] - backport node::Persistent (Gabriel Schulhof) [#300](https://github.com/nodejs/node-addon-api/pull/300) +* [[`98161970c9`](https://github.com/nodejs/node-addon-api/commit/98161970c9)] - Backport perf, crash and exception handling fixes (Gabriel Schulhof) [#295](https://github.com/nodejs/node-addon-api/pull/295) +* [[`dd1191e086`](https://github.com/nodejs/node-addon-api/commit/dd1191e086)] - **test**: fix asyncworker test so it runs on 6.x (Michael Dawson) [#298](https://github.com/nodejs/node-addon-api/pull/298) +* [[`11697fcecd`](https://github.com/nodejs/node-addon-api/commit/11697fcecd)] - **doc**: ArrayBuffer and Buffer documentation (Kyle Farnung) [#256](https://github.com/nodejs/node-addon-api/pull/256) +* [[`605aa2babf`](https://github.com/nodejs/node-addon-api/commit/605aa2babf)] - Add memory management feature (NickNaso) [#286](https://github.com/nodejs/node-addon-api/pull/286) +* [[`86be13a611`](https://github.com/nodejs/node-addon-api/commit/86be13a611)] - **doc**: Fix HandleScope docs (Ben Berman) [#287](https://github.com/nodejs/node-addon-api/pull/287) +* [[`90f92c4dc0`](https://github.com/nodejs/node-addon-api/commit/90f92c4dc0)] - **doc**: Update broken links in README.md (Hitesh Kanwathirtha) [#290](https://github.com/nodejs/node-addon-api/pull/290) +* [[`c2a620dc11`](https://github.com/nodejs/node-addon-api/commit/c2a620dc11)] - **doc**: Clarify positioning versus N-API (Michael Dawson) [#288](https://github.com/nodejs/node-addon-api/pull/288) +* [[`6cff890ee5`](https://github.com/nodejs/node-addon-api/commit/6cff890ee5)] - **doc**: Fix typo in docs (Ben Berman) [#284](https://github.com/nodejs/node-addon-api/pull/284) +* [[`7394bfd154`](https://github.com/nodejs/node-addon-api/commit/7394bfd154)] - **doc**: Fix typo in docs (Ben Berman) [#285](https://github.com/nodejs/node-addon-api/pull/285) +* [[`12b2cdeed3`](https://github.com/nodejs/node-addon-api/commit/12b2cdeed3)] - fix test files (Kyle Farnung) [#257](https://github.com/nodejs/node-addon-api/pull/257) +* [[`9ab6607242`](https://github.com/nodejs/node-addon-api/commit/9ab6607242)] - **doc**: Update Doc Version Number (joshgarde) [#277](https://github.com/nodejs/node-addon-api/pull/277) +* [[`e029a076c6`](https://github.com/nodejs/node-addon-api/commit/e029a076c6)] - **doc**: First pass at basic Node Addon API docs (Hitesh Kanwathirtha) [#268](https://github.com/nodejs/node-addon-api/pull/268) +* [[`74ff79717e`](https://github.com/nodejs/node-addon-api/commit/74ff79717e)] - **doc**: fix link to async\_worker.md (Michael Dawson) +* [[`5a63f45eda`](https://github.com/nodejs/node-addon-api/commit/5a63f45eda)] - **doc**: First step of error and async doc (NickNaso) [#272](https://github.com/nodejs/node-addon-api/pull/272) +* [[`9d38f61afb`](https://github.com/nodejs/node-addon-api/commit/9d38f61afb)] - **doc**: New Promise and Reference docs (Jim Schlight) [#243](https://github.com/nodejs/node-addon-api/pull/243) +* [[`43ff9fa836`](https://github.com/nodejs/node-addon-api/commit/43ff9fa836)] - **doc**: Updated Object documentation (Anisha Rohra) [#254](https://github.com/nodejs/node-addon-api/pull/254) +* [[`b197f7cc8b`](https://github.com/nodejs/node-addon-api/commit/b197f7cc8b)] - **doc**: minor typos (Nick Soggin) [#248](https://github.com/nodejs/node-addon-api/pull/248) +* [[`4b8918b352`](https://github.com/nodejs/node-addon-api/commit/4b8918b352)] - Add resource parameters to AsyncWorker constructor (Jinho Bang) [#253](https://github.com/nodejs/node-addon-api/pull/253) +* [[`1ecf7c19b6`](https://github.com/nodejs/node-addon-api/commit/1ecf7c19b6)] - **doc**: fix wrong link in readme (miloas) [#255](https://github.com/nodejs/node-addon-api/pull/255) +* [[`a750ed1932`](https://github.com/nodejs/node-addon-api/commit/a750ed1932)] - **release**: updates to metadata for next release (Michael Dawson) + +## 2018-05-08 Version 1.3.0, @mhdawson + +### Notable changes: + +#### Documentation +- Added documentation for Scopes +- Added documentation for migration from NAN +- Update documentation to better explain the use of NODE_ADDON_API + +#### API +- Implement data manipulation methods for dataview +- Use built-in N-API on Node.js >= 6.14.2 +- Value + - Added IsExternal() + - IsObject() allow functions +- String + - Fixed initialization of std::string to nullptr + +#### Tests +- Fix test failures on linuxOne and AIX +- Added basic tests for Scopes +- Fix MSVC warning C4244 in tests + +### Commits + +* [386c2aeb74] - test: remove dep on later C++ feature (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/267 +* [10697734da] - Use built-in N-API on Node.js >= 6.14.2 (Gabriel Schulhof) +* [75086da273] - test: add basic tests and doc for scopes (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/250 +* [341dbd25d5] - doc: update blurb explaining NODE_ADDON_API (Gabriel Schulhof) https://github.com/nodejs/node-addon-api/pull/251 +* [cf6c93e4ee] - don't try to escape null (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/245 +* [15e4b35fc2] - test: fix MSVC warning C4244 in tests (Kyle Farnung) https://github.com/nodejs/node-addon-api/pull/236 +* [7f3ca03b8e] - Create a doc for migration (Sampson Gao) https://github.com/nodejs/node-addon-api/pull/118 +* [0a2177debe] - Fix test failures on linuxOne and AIX (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/232 +* [d567f4b6b5] - Added Napi::Value::IsExternal() (Eric Bickle) https://github.com/nodejs/node-addon-api/pull/227 +* [1b0f0e004a] - Update node-gyp.md (Michele Campus) https://github.com/nodejs/node-addon-api/pull/226 +* [faf19c4f7a] - Fixed initialization of std::string to nullptr (Eric Bickle) https://github.com/nodejs/node-addon-api/pull/228 +* [9c4d321b57] - Implement data manipulation methods for dataview (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/218 +* [5a39fdca6f] - n-api: throw RangeError napi_create_typedarray() (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/216 +* [1376377202] - Make IsObject() allow functions (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/217 +* [673b59d319] - src: Initial implementation of DataView class (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/205 +* [0a899bf1c5] - doc: update indication of latest version (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/211 +* [17c74e5a5e] - n-api: RangeError in napi_create_dataview() (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/214 +* [4058a29989] - n-api: fix memory leak in napi_async_destroy() (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/213 + + diff --git a/node_modules/node-addon-api/LICENSE.md b/node_modules/node-addon-api/LICENSE.md new file mode 100644 index 0000000..e2fad66 --- /dev/null +++ b/node_modules/node-addon-api/LICENSE.md @@ -0,0 +1,13 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2017 Node.js API collaborators +----------------------------------- + +*Node.js API collaborators listed at * + +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. \ No newline at end of file diff --git a/node_modules/node-addon-api/README.md b/node_modules/node-addon-api/README.md new file mode 100644 index 0000000..46f0ee5 --- /dev/null +++ b/node_modules/node-addon-api/README.md @@ -0,0 +1,293 @@ +NOTE: The default branch has been renamed! +master is now named main + +If you have a local clone, you can update it by running: + +```shell +git branch -m master main +git fetch origin +git branch -u origin/main main +``` + +# **node-addon-api module** +This module contains **header-only C++ wrapper classes** which simplify +the use of the C based [Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) +provided by Node.js when using C++. It provides a C++ object model +and exception handling semantics with low overhead. + +There are three options for implementing addons: Node-API, nan, or direct +use of internal V8, libuv and Node.js libraries. Unless there is a need for +direct access to functionality which is not exposed by Node-API as outlined +in [C/C++ addons](https://nodejs.org/dist/latest/docs/api/addons.html) +in Node.js core, use Node-API. Refer to +[C/C++ addons with Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) +for more information on Node-API. + +Node-API is an ABI stable C interface provided by Node.js for building native +addons. It is independent from the underlying JavaScript runtime (e.g. V8 or ChakraCore) +and is maintained as part of Node.js itself. It is intended to insulate +native addons from changes in the underlying JavaScript engine and allow +modules compiled for one version to run on later versions of Node.js without +recompilation. + +The `node-addon-api` module, which is not part of Node.js, preserves the benefits +of the Node-API as it consists only of inline code that depends only on the stable API +provided by Node-API. As such, modules built against one version of Node.js +using node-addon-api should run without having to be rebuilt with newer versions +of Node.js. + +It is important to remember that *other* Node.js interfaces such as +`libuv` (included in a project via `#include `) are not ABI-stable across +Node.js major versions. Thus, an addon must use Node-API and/or `node-addon-api` +exclusively and build against a version of Node.js that includes an +implementation of Node-API (meaning an active LTS version of Node.js) in +order to benefit from ABI stability across Node.js major versions. Node.js +provides an [ABI stability guide][] containing a detailed explanation of ABI +stability in general, and the Node-API ABI stability guarantee in particular. + +As new APIs are added to Node-API, node-addon-api must be updated to provide +wrappers for those new APIs. For this reason node-addon-api provides +methods that allow callers to obtain the underlying Node-API handles so +direct calls to Node-API and the use of the objects/methods provided by +node-addon-api can be used together. For example, in order to be able +to use an API for which the node-addon-api does not yet provide a wrapper. + +APIs exposed by node-addon-api are generally used to create and +manipulate JavaScript values. Concepts and operations generally map +to ideas specified in the **ECMA262 Language Specification**. + +The [Node-API Resource](https://nodejs.github.io/node-addon-examples/) offers an +excellent orientation and tips for developers just getting started with Node-API +and node-addon-api. + +- **[Setup](#setup)** +- **[API Documentation](#api)** +- **[Examples](#examples)** +- **[Tests](#tests)** +- **[More resource and info about native Addons](#resources)** +- **[Badges](#badges)** +- **[Code of Conduct](CODE_OF_CONDUCT.md)** +- **[Contributors](#contributors)** +- **[License](#license)** + +## **Current version: 3.2.1** + +(See [CHANGELOG.md](CHANGELOG.md) for complete Changelog) + +[![NPM](https://nodei.co/npm/node-addon-api.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-addon-api/) [![NPM](https://nodei.co/npm-dl/node-addon-api.png?months=6&height=1)](https://nodei.co/npm/node-addon-api/) + + + +node-addon-api is based on [Node-API](https://nodejs.org/api/n-api.html) and supports using different Node-API versions. +This allows addons built with it to run with Node.js versions which support the targeted Node-API version. +**However** the node-addon-api support model is to support only the active LTS Node.js versions. This means that +every year there will be a new major which drops support for the Node.js LTS version which has gone out of service. + +The oldest Node.js version supported by the current version of node-addon-api is Node.js 10.x. + +## Setup + - [Installation and usage](doc/setup.md) + - [node-gyp](doc/node-gyp.md) + - [cmake-js](doc/cmake-js.md) + - [Conversion tool](doc/conversion-tool.md) + - [Checker tool](doc/checker-tool.md) + - [Generator](doc/generator.md) + - [Prebuild tools](doc/prebuild_tools.md) + + + +### **API Documentation** + +The following is the documentation for node-addon-api. + + - [Full Class Hierarchy](doc/hierarchy.md) + - [Addon Structure](doc/addon.md) + - Data Types: + - [Env](doc/env.md) + - [CallbackInfo](doc/callbackinfo.md) + - [Reference](doc/reference.md) + - [Value](doc/value.md) + - [Name](doc/name.md) + - [Symbol](doc/symbol.md) + - [String](doc/string.md) + - [Number](doc/number.md) + - [Date](doc/date.md) + - [BigInt](doc/bigint.md) + - [Boolean](doc/boolean.md) + - [External](doc/external.md) + - [Object](doc/object.md) + - [Array](doc/array.md) + - [ObjectReference](doc/object_reference.md) + - [PropertyDescriptor](doc/property_descriptor.md) + - [Function](doc/function.md) + - [FunctionReference](doc/function_reference.md) + - [ObjectWrap](doc/object_wrap.md) + - [ClassPropertyDescriptor](doc/class_property_descriptor.md) + - [Buffer](doc/buffer.md) + - [ArrayBuffer](doc/array_buffer.md) + - [TypedArray](doc/typed_array.md) + - [TypedArrayOf](doc/typed_array_of.md) + - [DataView](doc/dataview.md) + - [Error Handling](doc/error_handling.md) + - [Error](doc/error.md) + - [TypeError](doc/type_error.md) + - [RangeError](doc/range_error.md) + - [Object Lifetime Management](doc/object_lifetime_management.md) + - [HandleScope](doc/handle_scope.md) + - [EscapableHandleScope](doc/escapable_handle_scope.md) + - [Memory Management](doc/memory_management.md) + - [Async Operations](doc/async_operations.md) + - [AsyncWorker](doc/async_worker.md) + - [AsyncContext](doc/async_context.md) + - [AsyncWorker Variants](doc/async_worker_variants.md) + - [Thread-safe Functions](doc/threadsafe.md) + - [ThreadSafeFunction](doc/threadsafe_function.md) + - [TypedThreadSafeFunction](doc/typed_threadsafe_function.md) + - [Promises](doc/promises.md) + - [Version management](doc/version_management.md) + + + +### **Examples** + +Are you new to **node-addon-api**? Take a look at our **[examples](https://github.com/nodejs/node-addon-examples)** + +- **[Hello World](https://github.com/nodejs/node-addon-examples/tree/HEAD/1_hello_world/node-addon-api)** +- **[Pass arguments to a function](https://github.com/nodejs/node-addon-examples/tree/HEAD/2_function_arguments/node-addon-api)** +- **[Callbacks](https://github.com/nodejs/node-addon-examples/tree/HEAD/3_callbacks/node-addon-api)** +- **[Object factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/4_object_factory/node-addon-api)** +- **[Function factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/5_function_factory/node-addon-api)** +- **[Wrapping C++ Object](https://github.com/nodejs/node-addon-examples/tree/HEAD/6_object_wrap/node-addon-api)** +- **[Factory of wrapped object](https://github.com/nodejs/node-addon-examples/tree/HEAD/7_factory_wrap/node-addon-api)** +- **[Passing wrapped object around](https://github.com/nodejs/node-addon-examples/tree/HEAD/8_passing_wrapped/node-addon-api)** + + + +### **Tests** + +To run the **node-addon-api** tests do: + +``` +npm install +npm test +``` + +To avoid testing the deprecated portions of the API run +``` +npm install +npm test --disable-deprecated +``` + +To run the tests targeting a specific version of Node-API run +``` +npm install +export NAPI_VERSION=X +npm test --NAPI_VERSION=X +``` + +where X is the version of Node-API you want to target. + +### **Debug** + +To run the **node-addon-api** tests with `--debug` option: + +``` +npm run-script dev +``` + +If you want faster build, you might use the following option: + +``` +npm run-script dev:incremental +``` + +Take a look and get inspired by our **[test suite](https://github.com/nodejs/node-addon-api/tree/HEAD/test)** + +### **Benchmarks** + +You can run the available benchmarks using the following command: + +``` +npm run-script benchmark +``` + +See [benchmark/README.md](benchmark/README.md) for more details about running and adding benchmarks. + + + +### **More resource and info about native Addons** +- **[C++ Addons](https://nodejs.org/dist/latest/docs/api/addons.html)** +- **[Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html)** +- **[Node-API - Next Generation Node API for Native Modules](https://youtu.be/-Oniup60Afs)** +- **[How We Migrated Realm JavaScript From NAN to Node-API](https://developer.mongodb.com/article/realm-javascript-nan-to-n-api)** + +As node-addon-api's core mission is to expose the plain C Node-API as C++ +wrappers, tools that facilitate n-api/node-addon-api providing more +convenient patterns on developing a Node.js add-ons with n-api/node-addon-api +can be published to NPM as standalone packages. It is also recommended to tag +such packages with `node-addon-api` to provide more visibility to the community. + +Quick links to NPM searches: [keywords:node-addon-api](https://www.npmjs.com/search?q=keywords%3Anode-addon-api). + + + +### **Other bindings** + +- **[napi-rs](https://napi.rs)** - (`Rust`) + + + +### **Badges** + +The use of badges is recommended to indicate the minimum version of Node-API +required for the module. This helps to determine which Node.js major versions are +supported. Addon maintainers can consult the [Node-API support matrix][] to determine +which Node.js versions provide a given Node-API version. The following badges are +available: + +![Node-API v1 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v1%20Badge.svg) +![Node-API v2 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v2%20Badge.svg) +![Node-API v3 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v3%20Badge.svg) +![Node-API v4 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v4%20Badge.svg) +![Node-API v5 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v5%20Badge.svg) +![Node-API v6 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v6%20Badge.svg) +![Node-API v7 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v7%20Badge.svg) +![Node-API v8 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v8%20Badge.svg) +![Node-API Experimental Version Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20Experimental%20Version%20Badge.svg) + +## **Contributing** + +We love contributions from the community to **node-addon-api**! +See [CONTRIBUTING.md](CONTRIBUTING.md) for more details on our philosophy around extending this module. + + + +## Team members + +### Active +| Name | GitHub Link | +| ------------------- | ----------------------------------------------------- | +| Anna Henningsen | [addaleax](https://github.com/addaleax) | +| Chengzhong Wu | [legendecas](https://github.com/legendecas) | +| Gabriel Schulhof | [gabrielschulhof](https://github.com/gabrielschulhof) | +| Jim Schlight | [jschlight](https://github.com/jschlight) | +| Michael Dawson | [mhdawson](https://github.com/mhdawson) | +| Kevin Eady | [KevinEady](https://github.com/KevinEady) +| Nicola Del Gobbo | [NickNaso](https://github.com/NickNaso) | + +### Emeritus +| Name | GitHub Link | +| ------------------- | ----------------------------------------------------- | +| Arunesh Chandra | [aruneshchandra](https://github.com/aruneshchandra) | +| Benjamin Byholm | [kkoopa](https://github.com/kkoopa) | +| Jason Ginchereau | [jasongin](https://github.com/jasongin) | +| Hitesh Kanwathirtha | [digitalinfinity](https://github.com/digitalinfinity) | +| Sampson Gao | [sampsongao](https://github.com/sampsongao) | +| Taylor Woll | [boingoing](https://github.com/boingoing) | + + + +Licensed under [MIT](./LICENSE.md) + +[ABI stability guide]: https://nodejs.org/en/docs/guides/abi-stability/ +[Node-API support matrix]: https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix diff --git a/node_modules/node-addon-api/common.gypi b/node_modules/node-addon-api/common.gypi new file mode 100644 index 0000000..9be254f --- /dev/null +++ b/node_modules/node-addon-api/common.gypi @@ -0,0 +1,21 @@ +{ + 'variables': { + 'NAPI_VERSION%': " +inline PropertyDescriptor +PropertyDescriptor::Accessor(const char* utf8name, + Getter getter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({ getter, nullptr }); + + return PropertyDescriptor({ + utf8name, + nullptr, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(const std::string& utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), getter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(napi_value name, + Getter getter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({ getter, nullptr }); + + return PropertyDescriptor({ + nullptr, + name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Name name, + Getter getter, + napi_property_attributes attributes, + void* data) { + napi_value nameValue = name; + return PropertyDescriptor::Accessor(nameValue, getter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::AccessorCallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({ getter, setter, nullptr }); + + return PropertyDescriptor({ + utf8name, + nullptr, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), getter, setter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(napi_value name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::AccessorCallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({ getter, setter, nullptr }); + + return PropertyDescriptor({ + nullptr, + name, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + napi_value nameValue = name; + return PropertyDescriptor::Accessor(nameValue, getter, setter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function(const char* utf8name, + Callable cb, + napi_property_attributes attributes, + void* /*data*/) { + using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({ cb, nullptr }); + + return PropertyDescriptor({ + utf8name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function(const std::string& utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return Function(utf8name.c_str(), cb, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function(napi_value name, + Callable cb, + napi_property_attributes attributes, + void* /*data*/) { + using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({ cb, nullptr }); + + return PropertyDescriptor({ + nullptr, + name, + CbData::Wrapper, + nullptr, + nullptr, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function(Name name, + Callable cb, + napi_property_attributes attributes, + void* data) { + napi_value nameValue = name; + return PropertyDescriptor::Function(nameValue, cb, attributes, data); +} + +#endif // !SRC_NAPI_INL_DEPRECATED_H_ diff --git a/node_modules/node-addon-api/napi-inl.h b/node_modules/node-addon-api/napi-inl.h new file mode 100644 index 0000000..7e9dd72 --- /dev/null +++ b/node_modules/node-addon-api/napi-inl.h @@ -0,0 +1,5671 @@ +#ifndef SRC_NAPI_INL_H_ +#define SRC_NAPI_INL_H_ + +//////////////////////////////////////////////////////////////////////////////// +// Node-API C++ Wrapper Classes +// +// Inline header-only implementations for "Node-API" ABI-stable C APIs for +// Node.js. +//////////////////////////////////////////////////////////////////////////////// + +// Note: Do not include this file directly! Include "napi.h" instead. + +#include +#include +#include +#include + +namespace Napi { + +// Helpers to handle functions exposed from C++. +namespace details { + +// Attach a data item to an object and delete it when the object gets +// garbage-collected. +// TODO: Replace this code with `napi_add_finalizer()` whenever it becomes +// available on all supported versions of Node.js. +template +static inline napi_status AttachData(napi_env env, + napi_value obj, + FreeType* data, + napi_finalize finalizer = nullptr, + void* hint = nullptr) { + napi_status status; + if (finalizer == nullptr) { + finalizer = [](napi_env /*env*/, void* data, void* /*hint*/) { + delete static_cast(data); + }; + } +#if (NAPI_VERSION < 5) + napi_value symbol, external; + status = napi_create_symbol(env, nullptr, &symbol); + if (status == napi_ok) { + status = napi_create_external(env, + data, + finalizer, + hint, + &external); + if (status == napi_ok) { + napi_property_descriptor desc = { + nullptr, + symbol, + nullptr, + nullptr, + nullptr, + external, + napi_default, + nullptr + }; + status = napi_define_properties(env, obj, 1, &desc); + } + } +#else // NAPI_VERSION >= 5 + status = napi_add_finalizer(env, obj, data, finalizer, hint, nullptr); +#endif + return status; +} + +// For use in JS to C++ callback wrappers to catch any Napi::Error exceptions +// and rethrow them as JavaScript exceptions before returning from the callback. +template +inline napi_value WrapCallback(Callable callback) { +#ifdef NAPI_CPP_EXCEPTIONS + try { + return callback(); + } catch (const Error& e) { + e.ThrowAsJavaScriptException(); + return nullptr; + } +#else // NAPI_CPP_EXCEPTIONS + // When C++ exceptions are disabled, errors are immediately thrown as JS + // exceptions, so there is no need to catch and rethrow them here. + return callback(); +#endif // NAPI_CPP_EXCEPTIONS +} + +// For use in JS to C++ void callback wrappers to catch any Napi::Error +// exceptions and rethrow them as JavaScript exceptions before returning from the +// callback. +template +inline void WrapVoidCallback(Callable callback) { +#ifdef NAPI_CPP_EXCEPTIONS + try { + callback(); + } catch (const Error& e) { + e.ThrowAsJavaScriptException(); + } +#else // NAPI_CPP_EXCEPTIONS + // When C++ exceptions are disabled, errors are immediately thrown as JS + // exceptions, so there is no need to catch and rethrow them here. + callback(); +#endif // NAPI_CPP_EXCEPTIONS +} + +template +struct CallbackData { + static inline + napi_value Wrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + CallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->callback(callbackInfo); + }); + } + + Callable callback; + void* data; +}; + +template +struct CallbackData { + static inline + napi_value Wrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + CallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->callback(callbackInfo); + return nullptr; + }); + } + + Callable callback; + void* data; +}; + +template +static napi_value +TemplatedVoidCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback([&] { + CallbackInfo cbInfo(env, info); + Callback(cbInfo); + return nullptr; + }); +} + +template +static napi_value +TemplatedCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback([&] { + CallbackInfo cbInfo(env, info); + return Callback(cbInfo); + }); +} + +template +static napi_value +TemplatedInstanceCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback([&] { + CallbackInfo cbInfo(env, info); + T* instance = T::Unwrap(cbInfo.This().As()); + return (instance->*UnwrapCallback)(cbInfo); + }); +} + +template +static napi_value +TemplatedInstanceVoidCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback([&] { + CallbackInfo cbInfo(env, info); + T* instance = T::Unwrap(cbInfo.This().As()); + (instance->*UnwrapCallback)(cbInfo); + return nullptr; + }); +} + +template +struct FinalizeData { + static inline void Wrapper(napi_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback([&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(Env(env), static_cast(data)); + delete finalizeData; + }); + } + + static inline void WrapperWithHint(napi_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback([&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(Env(env), static_cast(data), finalizeData->hint); + delete finalizeData; + }); + } + + Finalizer callback; + Hint* hint; +}; + +#if (NAPI_VERSION > 3 && !defined(__wasm32__)) +template , + typename FinalizerDataType=void> +struct ThreadSafeFinalize { + static inline + void Wrapper(napi_env env, void* rawFinalizeData, void* /* rawContext */) { + if (rawFinalizeData == nullptr) + return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback(Env(env)); + delete finalizeData; + } + + static inline + void FinalizeWrapperWithData(napi_env env, + void* rawFinalizeData, + void* /* rawContext */) { + if (rawFinalizeData == nullptr) + return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback(Env(env), finalizeData->data); + delete finalizeData; + } + + static inline + void FinalizeWrapperWithContext(napi_env env, + void* rawFinalizeData, + void* rawContext) { + if (rawFinalizeData == nullptr) + return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback(Env(env), static_cast(rawContext)); + delete finalizeData; + } + + static inline + void FinalizeFinalizeWrapperWithDataAndContext(napi_env env, + void* rawFinalizeData, + void* rawContext) { + if (rawFinalizeData == nullptr) + return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback(Env(env), finalizeData->data, + static_cast(rawContext)); + delete finalizeData; + } + + FinalizerDataType* data; + Finalizer callback; +}; + +template +typename std::enable_if::type static inline CallJsWrapper( + napi_env env, napi_value jsCallback, void* context, void* data) { + call(env, + Function(env, jsCallback), + static_cast(context), + static_cast(data)); +} + +template +typename std::enable_if::type static inline CallJsWrapper( + napi_env env, napi_value jsCallback, void* /*context*/, void* /*data*/) { + if (jsCallback != nullptr) { + Function(env, jsCallback).Call(0, nullptr); + } +} + +#if NAPI_VERSION > 4 + +template +napi_value DefaultCallbackWrapper(napi_env /*env*/, std::nullptr_t /*cb*/) { + return nullptr; +} + +template +napi_value DefaultCallbackWrapper(napi_env /*env*/, Napi::Function cb) { + return cb; +} + +#else +template +napi_value DefaultCallbackWrapper(napi_env env, Napi::Function cb) { + if (cb.IsEmpty()) { + return TSFN::EmptyFunctionFactory(env); + } + return cb; +} +#endif // NAPI_VERSION > 4 +#endif // NAPI_VERSION > 3 && !defined(__wasm32__) + +template +struct AccessorCallbackData { + static inline + napi_value GetterWrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + AccessorCallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->getterCallback(callbackInfo); + }); + } + + static inline + napi_value SetterWrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + AccessorCallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->setterCallback(callbackInfo); + return nullptr; + }); + } + + Getter getterCallback; + Setter setterCallback; + void* data; +}; + +} // namespace details + +#ifndef NODE_ADDON_API_DISABLE_DEPRECATED +# include "napi-inl.deprecated.h" +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED + +//////////////////////////////////////////////////////////////////////////////// +// Module registration +//////////////////////////////////////////////////////////////////////////////// + +// Register an add-on based on an initializer function. +#define NODE_API_MODULE(modname, regfunc) \ + static napi_value __napi_##regfunc(napi_env env, napi_value exports) { \ + return Napi::RegisterModule(env, exports, regfunc); \ + } \ + NAPI_MODULE(modname, __napi_##regfunc) + +// Register an add-on based on a subclass of `Addon` with a custom Node.js +// module name. +#define NODE_API_NAMED_ADDON(modname, classname) \ + static napi_value __napi_ ## classname(napi_env env, \ + napi_value exports) { \ + return Napi::RegisterModule(env, exports, &classname::Init); \ + } \ + NAPI_MODULE(modname, __napi_ ## classname) + +// Register an add-on based on a subclass of `Addon` with the Node.js module +// name given by node-gyp from the `target_name` in binding.gyp. +#define NODE_API_ADDON(classname) \ + NODE_API_NAMED_ADDON(NODE_GYP_MODULE_NAME, classname) + +// Adapt the NAPI_MODULE registration function: +// - Wrap the arguments in NAPI wrappers. +// - Catch any NAPI errors and rethrow as JS exceptions. +inline napi_value RegisterModule(napi_env env, + napi_value exports, + ModuleRegisterCallback registerCallback) { + return details::WrapCallback([&] { + return napi_value(registerCallback(Napi::Env(env), + Napi::Object(env, exports))); + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// Env class +//////////////////////////////////////////////////////////////////////////////// + +inline Env::Env(napi_env env) : _env(env) { +} + +inline Env::operator napi_env() const { + return _env; +} + +inline Object Env::Global() const { + napi_value value; + napi_status status = napi_get_global(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Object()); + return Object(*this, value); +} + +inline Value Env::Undefined() const { + napi_value value; + napi_status status = napi_get_undefined(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Value()); + return Value(*this, value); +} + +inline Value Env::Null() const { + napi_value value; + napi_status status = napi_get_null(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Value()); + return Value(*this, value); +} + +inline bool Env::IsExceptionPending() const { + bool result; + napi_status status = napi_is_exception_pending(_env, &result); + if (status != napi_ok) result = false; // Checking for a pending exception shouldn't throw. + return result; +} + +inline Error Env::GetAndClearPendingException() { + napi_value value; + napi_status status = napi_get_and_clear_last_exception(_env, &value); + if (status != napi_ok) { + // Don't throw another exception when failing to get the exception! + return Error(); + } + return Error(_env, value); +} + +inline Value Env::RunScript(const char* utf8script) { + String script = String::New(_env, utf8script); + return RunScript(script); +} + +inline Value Env::RunScript(const std::string& utf8script) { + return RunScript(utf8script.c_str()); +} + +inline Value Env::RunScript(String script) { + napi_value result; + napi_status status = napi_run_script(_env, script, &result); + NAPI_THROW_IF_FAILED(_env, status, Undefined()); + return Value(_env, result); +} + +#if NAPI_VERSION > 5 +template fini> +inline void Env::SetInstanceData(T* data) { + napi_status status = + napi_set_instance_data(_env, data, [](napi_env env, void* data, void*) { + fini(env, static_cast(data)); + }, nullptr); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +template fini> +inline void Env::SetInstanceData(DataType* data, HintType* hint) { + napi_status status = + napi_set_instance_data(_env, data, + [](napi_env env, void* data, void* hint) { + fini(env, static_cast(data), static_cast(hint)); + }, hint); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +template +inline T* Env::GetInstanceData() { + void* data = nullptr; + + napi_status status = napi_get_instance_data(_env, &data); + NAPI_THROW_IF_FAILED(_env, status, nullptr); + + return static_cast(data); +} + +template void Env::DefaultFini(Env, T* data) { + delete data; +} + +template +void Env::DefaultFiniWithHint(Env, DataType* data, HintType*) { + delete data; +} +#endif // NAPI_VERSION > 5 + +//////////////////////////////////////////////////////////////////////////////// +// Value class +//////////////////////////////////////////////////////////////////////////////// + +inline Value::Value() : _env(nullptr), _value(nullptr) { +} + +inline Value::Value(napi_env env, napi_value value) : _env(env), _value(value) { +} + +inline Value::operator napi_value() const { + return _value; +} + +inline bool Value::operator ==(const Value& other) const { + return StrictEquals(other); +} + +inline bool Value::operator !=(const Value& other) const { + return !this->operator ==(other); +} + +inline bool Value::StrictEquals(const Value& other) const { + bool result; + napi_status status = napi_strict_equals(_env, *this, other, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline Napi::Env Value::Env() const { + return Napi::Env(_env); +} + +inline bool Value::IsEmpty() const { + return _value == nullptr; +} + +inline napi_valuetype Value::Type() const { + if (IsEmpty()) { + return napi_undefined; + } + + napi_valuetype type; + napi_status status = napi_typeof(_env, _value, &type); + NAPI_THROW_IF_FAILED(_env, status, napi_undefined); + return type; +} + +inline bool Value::IsUndefined() const { + return Type() == napi_undefined; +} + +inline bool Value::IsNull() const { + return Type() == napi_null; +} + +inline bool Value::IsBoolean() const { + return Type() == napi_boolean; +} + +inline bool Value::IsNumber() const { + return Type() == napi_number; +} + +#if NAPI_VERSION > 5 +inline bool Value::IsBigInt() const { + return Type() == napi_bigint; +} +#endif // NAPI_VERSION > 5 + +#if (NAPI_VERSION > 4) +inline bool Value::IsDate() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_date(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} +#endif + +inline bool Value::IsString() const { + return Type() == napi_string; +} + +inline bool Value::IsSymbol() const { + return Type() == napi_symbol; +} + +inline bool Value::IsArray() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_array(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsArrayBuffer() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_arraybuffer(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsTypedArray() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_typedarray(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsObject() const { + return Type() == napi_object || IsFunction(); +} + +inline bool Value::IsFunction() const { + return Type() == napi_function; +} + +inline bool Value::IsPromise() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_promise(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsDataView() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_dataview(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsBuffer() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_buffer(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsExternal() const { + return Type() == napi_external; +} + +template +inline T Value::As() const { + return T(_env, _value); +} + +inline Boolean Value::ToBoolean() const { + napi_value result; + napi_status status = napi_coerce_to_bool(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, Boolean()); + return Boolean(_env, result); +} + +inline Number Value::ToNumber() const { + napi_value result; + napi_status status = napi_coerce_to_number(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, Number()); + return Number(_env, result); +} + +inline String Value::ToString() const { + napi_value result; + napi_status status = napi_coerce_to_string(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, String()); + return String(_env, result); +} + +inline Object Value::ToObject() const { + napi_value result; + napi_status status = napi_coerce_to_object(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, Object()); + return Object(_env, result); +} + +//////////////////////////////////////////////////////////////////////////////// +// Boolean class +//////////////////////////////////////////////////////////////////////////////// + +inline Boolean Boolean::New(napi_env env, bool val) { + napi_value value; + napi_status status = napi_get_boolean(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, Boolean()); + return Boolean(env, value); +} + +inline Boolean::Boolean() : Napi::Value() { +} + +inline Boolean::Boolean(napi_env env, napi_value value) : Napi::Value(env, value) { +} + +inline Boolean::operator bool() const { + return Value(); +} + +inline bool Boolean::Value() const { + bool result; + napi_status status = napi_get_value_bool(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// Number class +//////////////////////////////////////////////////////////////////////////////// + +inline Number Number::New(napi_env env, double val) { + napi_value value; + napi_status status = napi_create_double(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, Number()); + return Number(env, value); +} + +inline Number::Number() : Value() { +} + +inline Number::Number(napi_env env, napi_value value) : Value(env, value) { +} + +inline Number::operator int32_t() const { + return Int32Value(); +} + +inline Number::operator uint32_t() const { + return Uint32Value(); +} + +inline Number::operator int64_t() const { + return Int64Value(); +} + +inline Number::operator float() const { + return FloatValue(); +} + +inline Number::operator double() const { + return DoubleValue(); +} + +inline int32_t Number::Int32Value() const { + int32_t result; + napi_status status = napi_get_value_int32(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline uint32_t Number::Uint32Value() const { + uint32_t result; + napi_status status = napi_get_value_uint32(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline int64_t Number::Int64Value() const { + int64_t result; + napi_status status = napi_get_value_int64(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline float Number::FloatValue() const { + return static_cast(DoubleValue()); +} + +inline double Number::DoubleValue() const { + double result; + napi_status status = napi_get_value_double(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +#if NAPI_VERSION > 5 +//////////////////////////////////////////////////////////////////////////////// +// BigInt Class +//////////////////////////////////////////////////////////////////////////////// + +inline BigInt BigInt::New(napi_env env, int64_t val) { + napi_value value; + napi_status status = napi_create_bigint_int64(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline BigInt BigInt::New(napi_env env, uint64_t val) { + napi_value value; + napi_status status = napi_create_bigint_uint64(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline BigInt BigInt::New(napi_env env, int sign_bit, size_t word_count, const uint64_t* words) { + napi_value value; + napi_status status = napi_create_bigint_words(env, sign_bit, word_count, words, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline BigInt::BigInt() : Value() { +} + +inline BigInt::BigInt(napi_env env, napi_value value) : Value(env, value) { +} + +inline int64_t BigInt::Int64Value(bool* lossless) const { + int64_t result; + napi_status status = napi_get_value_bigint_int64( + _env, _value, &result, lossless); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline uint64_t BigInt::Uint64Value(bool* lossless) const { + uint64_t result; + napi_status status = napi_get_value_bigint_uint64( + _env, _value, &result, lossless); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline size_t BigInt::WordCount() const { + size_t word_count; + napi_status status = napi_get_value_bigint_words( + _env, _value, nullptr, &word_count, nullptr); + NAPI_THROW_IF_FAILED(_env, status, 0); + return word_count; +} + +inline void BigInt::ToWords(int* sign_bit, size_t* word_count, uint64_t* words) { + napi_status status = napi_get_value_bigint_words( + _env, _value, sign_bit, word_count, words); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} +#endif // NAPI_VERSION > 5 + +#if (NAPI_VERSION > 4) +//////////////////////////////////////////////////////////////////////////////// +// Date Class +//////////////////////////////////////////////////////////////////////////////// + +inline Date Date::New(napi_env env, double val) { + napi_value value; + napi_status status = napi_create_date(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, Date()); + return Date(env, value); +} + +inline Date::Date() : Value() { +} + +inline Date::Date(napi_env env, napi_value value) : Value(env, value) { +} + +inline Date::operator double() const { + return ValueOf(); +} + +inline double Date::ValueOf() const { + double result; + napi_status status = napi_get_date_value( + _env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Name class +//////////////////////////////////////////////////////////////////////////////// + +inline Name::Name() : Value() { +} + +inline Name::Name(napi_env env, napi_value value) : Value(env, value) { +} + +//////////////////////////////////////////////////////////////////////////////// +// String class +//////////////////////////////////////////////////////////////////////////////// + +inline String String::New(napi_env env, const std::string& val) { + return String::New(env, val.c_str(), val.size()); +} + +inline String String::New(napi_env env, const std::u16string& val) { + return String::New(env, val.c_str(), val.size()); +} + +inline String String::New(napi_env env, const char* val) { + napi_value value; + napi_status status = napi_create_string_utf8(env, val, std::strlen(val), &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char16_t* val) { + napi_value value; + napi_status status = napi_create_string_utf16(env, val, std::u16string(val).size(), &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char* val, size_t length) { + napi_value value; + napi_status status = napi_create_string_utf8(env, val, length, &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char16_t* val, size_t length) { + napi_value value; + napi_status status = napi_create_string_utf16(env, val, length, &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String::String() : Name() { +} + +inline String::String(napi_env env, napi_value value) : Name(env, value) { +} + +inline String::operator std::string() const { + return Utf8Value(); +} + +inline String::operator std::u16string() const { + return Utf16Value(); +} + +inline std::string String::Utf8Value() const { + size_t length; + napi_status status = napi_get_value_string_utf8(_env, _value, nullptr, 0, &length); + NAPI_THROW_IF_FAILED(_env, status, ""); + + std::string value; + value.reserve(length + 1); + value.resize(length); + status = napi_get_value_string_utf8(_env, _value, &value[0], value.capacity(), nullptr); + NAPI_THROW_IF_FAILED(_env, status, ""); + return value; +} + +inline std::u16string String::Utf16Value() const { + size_t length; + napi_status status = napi_get_value_string_utf16(_env, _value, nullptr, 0, &length); + NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); + + std::u16string value; + value.reserve(length + 1); + value.resize(length); + status = napi_get_value_string_utf16(_env, _value, &value[0], value.capacity(), nullptr); + NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); + return value; +} + +//////////////////////////////////////////////////////////////////////////////// +// Symbol class +//////////////////////////////////////////////////////////////////////////////// + +inline Symbol Symbol::New(napi_env env, const char* description) { + napi_value descriptionValue = description != nullptr ? + String::New(env, description) : static_cast(nullptr); + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, const std::string& description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, String description) { + napi_value descriptionValue = description; + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, napi_value description) { + napi_value value; + napi_status status = napi_create_symbol(env, description, &value); + NAPI_THROW_IF_FAILED(env, status, Symbol()); + return Symbol(env, value); +} + +inline Symbol Symbol::WellKnown(napi_env env, const std::string& name) { + return Napi::Env(env).Global().Get("Symbol").As().Get(name).As(); +} + +inline Symbol::Symbol() : Name() { +} + +inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) { +} + +//////////////////////////////////////////////////////////////////////////////// +// Automagic value creation +//////////////////////////////////////////////////////////////////////////////// + +namespace details { +template +struct vf_number { + static Number From(napi_env env, T value) { + return Number::New(env, static_cast(value)); + } +}; + +template<> +struct vf_number { + static Boolean From(napi_env env, bool value) { + return Boolean::New(env, value); + } +}; + +struct vf_utf8_charp { + static String From(napi_env env, const char* value) { + return String::New(env, value); + } +}; + +struct vf_utf16_charp { + static String From(napi_env env, const char16_t* value) { + return String::New(env, value); + } +}; +struct vf_utf8_string { + static String From(napi_env env, const std::string& value) { + return String::New(env, value); + } +}; + +struct vf_utf16_string { + static String From(napi_env env, const std::u16string& value) { + return String::New(env, value); + } +}; + +template +struct vf_fallback { + static Value From(napi_env env, const T& value) { + return Value(env, value); + } +}; + +template struct disjunction : std::false_type {}; +template struct disjunction : B {}; +template +struct disjunction + : std::conditional>::type {}; + +template +struct can_make_string + : disjunction::type, + typename std::is_convertible::type, + typename std::is_convertible::type, + typename std::is_convertible::type> {}; +} + +template +Value Value::From(napi_env env, const T& value) { + using Helper = typename std::conditional< + std::is_integral::value || std::is_floating_point::value, + details::vf_number, + typename std::conditional< + details::can_make_string::value, + String, + details::vf_fallback + >::type + >::type; + return Helper::From(env, value); +} + +template +String String::From(napi_env env, const T& value) { + struct Dummy {}; + using Helper = typename std::conditional< + std::is_convertible::value, + details::vf_utf8_charp, + typename std::conditional< + std::is_convertible::value, + details::vf_utf16_charp, + typename std::conditional< + std::is_convertible::value, + details::vf_utf8_string, + typename std::conditional< + std::is_convertible::value, + details::vf_utf16_string, + Dummy + >::type + >::type + >::type + >::type; + return Helper::From(env, value); +} + +//////////////////////////////////////////////////////////////////////////////// +// Object class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Object::PropertyLValue::operator Value() const { + return Object(_env, _object).Get(_key); +} + +template template +inline Object::PropertyLValue& Object::PropertyLValue::operator =(ValueType value) { + Object(_env, _object).Set(_key, value); + return *this; +} + +template +inline Object::PropertyLValue::PropertyLValue(Object object, Key key) + : _env(object.Env()), _object(object), _key(key) {} + +inline Object Object::New(napi_env env) { + napi_value value; + napi_status status = napi_create_object(env, &value); + NAPI_THROW_IF_FAILED(env, status, Object()); + return Object(env, value); +} + +inline Object::Object() : Value() { +} + +inline Object::Object(napi_env env, napi_value value) : Value(env, value) { +} + +inline Object::PropertyLValue Object::operator [](const char* utf8name) { + return PropertyLValue(*this, utf8name); +} + +inline Object::PropertyLValue Object::operator [](const std::string& utf8name) { + return PropertyLValue(*this, utf8name); +} + +inline Object::PropertyLValue Object::operator [](uint32_t index) { + return PropertyLValue(*this, index); +} + +inline Value Object::operator [](const char* utf8name) const { + return Get(utf8name); +} + +inline Value Object::operator [](const std::string& utf8name) const { + return Get(utf8name); +} + +inline Value Object::operator [](uint32_t index) const { + return Get(index); +} + +inline bool Object::Has(napi_value key) const { + bool result; + napi_status status = napi_has_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::Has(Value key) const { + bool result; + napi_status status = napi_has_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::Has(const char* utf8name) const { + bool result; + napi_status status = napi_has_named_property(_env, _value, utf8name, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::Has(const std::string& utf8name) const { + return Has(utf8name.c_str()); +} + +inline bool Object::HasOwnProperty(napi_value key) const { + bool result; + napi_status status = napi_has_own_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::HasOwnProperty(Value key) const { + bool result; + napi_status status = napi_has_own_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::HasOwnProperty(const char* utf8name) const { + napi_value key; + napi_status status = napi_create_string_utf8(_env, utf8name, std::strlen(utf8name), &key); + NAPI_THROW_IF_FAILED(_env, status, false); + return HasOwnProperty(key); +} + +inline bool Object::HasOwnProperty(const std::string& utf8name) const { + return HasOwnProperty(utf8name.c_str()); +} + +inline Value Object::Get(napi_value key) const { + napi_value result; + napi_status status = napi_get_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +inline Value Object::Get(Value key) const { + napi_value result; + napi_status status = napi_get_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +inline Value Object::Get(const char* utf8name) const { + napi_value result; + napi_status status = napi_get_named_property(_env, _value, utf8name, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +inline Value Object::Get(const std::string& utf8name) const { + return Get(utf8name.c_str()); +} + +template +inline bool Object::Set(napi_value key, const ValueType& value) { + napi_status status = + napi_set_property(_env, _value, key, Value::From(_env, value)); + NAPI_THROW_IF_FAILED(_env, status, false); + return true; +} + +template +inline bool Object::Set(Value key, const ValueType& value) { + napi_status status = + napi_set_property(_env, _value, key, Value::From(_env, value)); + NAPI_THROW_IF_FAILED(_env, status, false); + return true; +} + +template +inline bool Object::Set(const char* utf8name, const ValueType& value) { + napi_status status = + napi_set_named_property(_env, _value, utf8name, Value::From(_env, value)); + NAPI_THROW_IF_FAILED(_env, status, false); + return true; +} + +template +inline bool Object::Set(const std::string& utf8name, const ValueType& value) { + return Set(utf8name.c_str(), value); +} + +inline bool Object::Delete(napi_value key) { + bool result; + napi_status status = napi_delete_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::Delete(Value key) { + bool result; + napi_status status = napi_delete_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::Delete(const char* utf8name) { + return Delete(String::New(_env, utf8name)); +} + +inline bool Object::Delete(const std::string& utf8name) { + return Delete(String::New(_env, utf8name)); +} + +inline bool Object::Has(uint32_t index) const { + bool result; + napi_status status = napi_has_element(_env, _value, index, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline Value Object::Get(uint32_t index) const { + napi_value value; + napi_status status = napi_get_element(_env, _value, index, &value); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, value); +} + +template +inline bool Object::Set(uint32_t index, const ValueType& value) { + napi_status status = + napi_set_element(_env, _value, index, Value::From(_env, value)); + NAPI_THROW_IF_FAILED(_env, status, false); + return true; +} + +inline bool Object::Delete(uint32_t index) { + bool result; + napi_status status = napi_delete_element(_env, _value, index, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline Array Object::GetPropertyNames() const { + napi_value result; + napi_status status = napi_get_property_names(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, Array()); + return Array(_env, result); +} + +inline bool Object::DefineProperty(const PropertyDescriptor& property) { + napi_status status = napi_define_properties(_env, _value, 1, + reinterpret_cast(&property)); + NAPI_THROW_IF_FAILED(_env, status, false); + return true; +} + +inline bool Object::DefineProperties( + const std::initializer_list& properties) { + napi_status status = napi_define_properties(_env, _value, properties.size(), + reinterpret_cast(properties.begin())); + NAPI_THROW_IF_FAILED(_env, status, false); + return true; +} + +inline bool Object::DefineProperties( + const std::vector& properties) { + napi_status status = napi_define_properties(_env, _value, properties.size(), + reinterpret_cast(properties.data())); + NAPI_THROW_IF_FAILED(_env, status, false); + return true; +} + +inline bool Object::InstanceOf(const Function& constructor) const { + bool result; + napi_status status = napi_instanceof(_env, _value, constructor, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +template +inline void Object::AddFinalizer(Finalizer finalizeCallback, T* data) { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = + details::AttachData(_env, + *this, + data, + details::FinalizeData::Wrapper, + finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +template +inline void Object::AddFinalizer(Finalizer finalizeCallback, + T* data, + Hint* finalizeHint) { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = + details::AttachData(_env, + *this, + data, + details::FinalizeData::WrapperWithHint, + finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +#if NAPI_VERSION >= 8 +inline bool Object::Freeze() { + napi_status status = napi_object_freeze(_env, _value); + NAPI_THROW_IF_FAILED(_env, status, false); + return true; +} + +inline bool Object::Seal() { + napi_status status = napi_object_seal(_env, _value); + NAPI_THROW_IF_FAILED(_env, status, false); + return true; +} +#endif // NAPI_VERSION >= 8 + +//////////////////////////////////////////////////////////////////////////////// +// External class +//////////////////////////////////////////////////////////////////////////////// + +template +inline External External::New(napi_env env, T* data) { + napi_value value; + napi_status status = napi_create_external(env, data, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, External()); + return External(env, value); +} + +template +template +inline External External::New(napi_env env, + T* data, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = napi_create_external( + env, + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, External()); + } + return External(env, value); +} + +template +template +inline External External::New(napi_env env, + T* data, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = napi_create_external( + env, + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, External()); + } + return External(env, value); +} + +template +inline External::External() : Value() { +} + +template +inline External::External(napi_env env, napi_value value) : Value(env, value) { +} + +template +inline T* External::Data() const { + void* data; + napi_status status = napi_get_value_external(_env, _value, &data); + NAPI_THROW_IF_FAILED(_env, status, nullptr); + return reinterpret_cast(data); +} + +//////////////////////////////////////////////////////////////////////////////// +// Array class +//////////////////////////////////////////////////////////////////////////////// + +inline Array Array::New(napi_env env) { + napi_value value; + napi_status status = napi_create_array(env, &value); + NAPI_THROW_IF_FAILED(env, status, Array()); + return Array(env, value); +} + +inline Array Array::New(napi_env env, size_t length) { + napi_value value; + napi_status status = napi_create_array_with_length(env, length, &value); + NAPI_THROW_IF_FAILED(env, status, Array()); + return Array(env, value); +} + +inline Array::Array() : Object() { +} + +inline Array::Array(napi_env env, napi_value value) : Object(env, value) { +} + +inline uint32_t Array::Length() const { + uint32_t result; + napi_status status = napi_get_array_length(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// ArrayBuffer class +//////////////////////////////////////////////////////////////////////////////// + +inline ArrayBuffer ArrayBuffer::New(napi_env env, size_t byteLength) { + napi_value value; + void* data; + napi_status status = napi_create_arraybuffer(env, byteLength, &data, &value); + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + + return ArrayBuffer(env, value); +} + +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength) { + napi_value value; + napi_status status = napi_create_external_arraybuffer( + env, externalData, byteLength, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + + return ArrayBuffer(env, value); +} + +template +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = napi_create_external_arraybuffer( + env, + externalData, + byteLength, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + } + + return ArrayBuffer(env, value); +} + +template +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = napi_create_external_arraybuffer( + env, + externalData, + byteLength, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + } + + return ArrayBuffer(env, value); +} + +inline ArrayBuffer::ArrayBuffer() : Object() { +} + +inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value) + : Object(env, value) { +} + +inline void* ArrayBuffer::Data() { + void* data; + napi_status status = napi_get_arraybuffer_info(_env, _value, &data, nullptr); + NAPI_THROW_IF_FAILED(_env, status, nullptr); + return data; +} + +inline size_t ArrayBuffer::ByteLength() { + size_t length; + napi_status status = napi_get_arraybuffer_info(_env, _value, nullptr, &length); + NAPI_THROW_IF_FAILED(_env, status, 0); + return length; +} + +#if NAPI_VERSION >= 7 +inline bool ArrayBuffer::IsDetached() const { + bool detached; + napi_status status = napi_is_detached_arraybuffer(_env, _value, &detached); + NAPI_THROW_IF_FAILED(_env, status, false); + return detached; +} + +inline void ArrayBuffer::Detach() { + napi_status status = napi_detach_arraybuffer(_env, _value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} +#endif // NAPI_VERSION >= 7 + +//////////////////////////////////////////////////////////////////////////////// +// DataView class +//////////////////////////////////////////////////////////////////////////////// +inline DataView DataView::New(napi_env env, + Napi::ArrayBuffer arrayBuffer) { + return New(env, arrayBuffer, 0, arrayBuffer.ByteLength()); +} + +inline DataView DataView::New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset) { + if (byteOffset > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New(env, + "Start offset is outside the bounds of the buffer"), + DataView()); + } + return New(env, arrayBuffer, byteOffset, + arrayBuffer.ByteLength() - byteOffset); +} + +inline DataView DataView::New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength) { + if (byteOffset + byteLength > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New(env, "Invalid DataView length"), + DataView()); + } + napi_value value; + napi_status status = napi_create_dataview( + env, byteLength, arrayBuffer, byteOffset, &value); + NAPI_THROW_IF_FAILED(env, status, DataView()); + return DataView(env, value); +} + +inline DataView::DataView() : Object() { +} + +inline DataView::DataView(napi_env env, napi_value value) : Object(env, value) { + napi_status status = napi_get_dataview_info( + _env, + _value /* dataView */, + &_length /* byteLength */, + &_data /* data */, + nullptr /* arrayBuffer */, + nullptr /* byteOffset */); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline Napi::ArrayBuffer DataView::ArrayBuffer() const { + napi_value arrayBuffer; + napi_status status = napi_get_dataview_info( + _env, + _value /* dataView */, + nullptr /* byteLength */, + nullptr /* data */, + &arrayBuffer /* arrayBuffer */, + nullptr /* byteOffset */); + NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer()); + return Napi::ArrayBuffer(_env, arrayBuffer); +} + +inline size_t DataView::ByteOffset() const { + size_t byteOffset; + napi_status status = napi_get_dataview_info( + _env, + _value /* dataView */, + nullptr /* byteLength */, + nullptr /* data */, + nullptr /* arrayBuffer */, + &byteOffset /* byteOffset */); + NAPI_THROW_IF_FAILED(_env, status, 0); + return byteOffset; +} + +inline size_t DataView::ByteLength() const { + return _length; +} + +inline void* DataView::Data() const { + return _data; +} + +inline float DataView::GetFloat32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline double DataView::GetFloat64(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int8_t DataView::GetInt8(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int16_t DataView::GetInt16(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int32_t DataView::GetInt32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint8_t DataView::GetUint8(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint16_t DataView::GetUint16(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint32_t DataView::GetUint32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline void DataView::SetFloat32(size_t byteOffset, float value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetFloat64(size_t byteOffset, double value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt8(size_t byteOffset, int8_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt16(size_t byteOffset, int16_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt32(size_t byteOffset, int32_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint8(size_t byteOffset, uint8_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint16(size_t byteOffset, uint16_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint32(size_t byteOffset, uint32_t value) const { + WriteData(byteOffset, value); +} + +template +inline T DataView::ReadData(size_t byteOffset) const { + if (byteOffset + sizeof(T) > _length || + byteOffset + sizeof(T) < byteOffset) { // overflow + NAPI_THROW(RangeError::New(_env, + "Offset is outside the bounds of the DataView"), 0); + } + + return *reinterpret_cast(static_cast(_data) + byteOffset); +} + +template +inline void DataView::WriteData(size_t byteOffset, T value) const { + if (byteOffset + sizeof(T) > _length || + byteOffset + sizeof(T) < byteOffset) { // overflow + NAPI_THROW_VOID(RangeError::New(_env, + "Offset is outside the bounds of the DataView")); + } + + *reinterpret_cast(static_cast(_data) + byteOffset) = value; +} + +//////////////////////////////////////////////////////////////////////////////// +// TypedArray class +//////////////////////////////////////////////////////////////////////////////// + +inline TypedArray::TypedArray() + : Object(), _type(TypedArray::unknown_array_type), _length(0) { +} + +inline TypedArray::TypedArray(napi_env env, napi_value value) + : Object(env, value), _type(TypedArray::unknown_array_type), _length(0) { +} + +inline TypedArray::TypedArray(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length) + : Object(env, value), _type(type), _length(length) { +} + +inline napi_typedarray_type TypedArray::TypedArrayType() const { + if (_type == TypedArray::unknown_array_type) { + napi_status status = napi_get_typedarray_info(_env, _value, + &const_cast(this)->_type, &const_cast(this)->_length, + nullptr, nullptr, nullptr); + NAPI_THROW_IF_FAILED(_env, status, napi_int8_array); + } + + return _type; +} + +inline uint8_t TypedArray::ElementSize() const { + switch (TypedArrayType()) { + case napi_int8_array: + case napi_uint8_array: + case napi_uint8_clamped_array: + return 1; + case napi_int16_array: + case napi_uint16_array: + return 2; + case napi_int32_array: + case napi_uint32_array: + case napi_float32_array: + return 4; + case napi_float64_array: +#if (NAPI_VERSION > 5) + case napi_bigint64_array: + case napi_biguint64_array: +#endif // (NAPI_VERSION > 5) + return 8; + default: + return 0; + } +} + +inline size_t TypedArray::ElementLength() const { + if (_type == TypedArray::unknown_array_type) { + napi_status status = napi_get_typedarray_info(_env, _value, + &const_cast(this)->_type, &const_cast(this)->_length, + nullptr, nullptr, nullptr); + NAPI_THROW_IF_FAILED(_env, status, 0); + } + + return _length; +} + +inline size_t TypedArray::ByteOffset() const { + size_t byteOffset; + napi_status status = napi_get_typedarray_info( + _env, _value, nullptr, nullptr, nullptr, nullptr, &byteOffset); + NAPI_THROW_IF_FAILED(_env, status, 0); + return byteOffset; +} + +inline size_t TypedArray::ByteLength() const { + return ElementSize() * ElementLength(); +} + +inline Napi::ArrayBuffer TypedArray::ArrayBuffer() const { + napi_value arrayBuffer; + napi_status status = napi_get_typedarray_info( + _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr); + NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer()); + return Napi::ArrayBuffer(_env, arrayBuffer); +} + +//////////////////////////////////////////////////////////////////////////////// +// TypedArrayOf class +//////////////////////////////////////////////////////////////////////////////// + +template +inline TypedArrayOf TypedArrayOf::New(napi_env env, + size_t elementLength, + napi_typedarray_type type) { + Napi::ArrayBuffer arrayBuffer = Napi::ArrayBuffer::New(env, elementLength * sizeof (T)); + return New(env, elementLength, arrayBuffer, 0, type); +} + +template +inline TypedArrayOf TypedArrayOf::New(napi_env env, + size_t elementLength, + Napi::ArrayBuffer arrayBuffer, + size_t bufferOffset, + napi_typedarray_type type) { + napi_value value; + napi_status status = napi_create_typedarray( + env, type, elementLength, arrayBuffer, bufferOffset, &value); + NAPI_THROW_IF_FAILED(env, status, TypedArrayOf()); + + return TypedArrayOf( + env, value, type, elementLength, + reinterpret_cast(reinterpret_cast(arrayBuffer.Data()) + bufferOffset)); +} + +template +inline TypedArrayOf::TypedArrayOf() : TypedArray(), _data(nullptr) { +} + +template +inline TypedArrayOf::TypedArrayOf(napi_env env, napi_value value) + : TypedArray(env, value), _data(nullptr) { + napi_status status = napi_ok; + if (value != nullptr) { + status = napi_get_typedarray_info( + _env, _value, &_type, &_length, reinterpret_cast(&_data), nullptr, nullptr); + } else { + _type = TypedArrayTypeForPrimitiveType(); + _length = 0; + } + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +template +inline TypedArrayOf::TypedArrayOf(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length, + T* data) + : TypedArray(env, value, type, length), _data(data) { + if (!(type == TypedArrayTypeForPrimitiveType() || + (type == napi_uint8_clamped_array && std::is_same::value))) { + NAPI_THROW_VOID(TypeError::New(env, "Array type must match the template parameter. " + "(Uint8 arrays may optionally have the \"clamped\" array type.)")); + } +} + +template +inline T& TypedArrayOf::operator [](size_t index) { + return _data[index]; +} + +template +inline const T& TypedArrayOf::operator [](size_t index) const { + return _data[index]; +} + +template +inline T* TypedArrayOf::Data() { + return _data; +} + +template +inline const T* TypedArrayOf::Data() const { + return _data; +} + +//////////////////////////////////////////////////////////////////////////////// +// Function class +//////////////////////////////////////////////////////////////////////////////// + +template +static inline napi_status +CreateFunction(napi_env env, + const char* utf8name, + napi_callback cb, + CbData* data, + napi_value* result) { + napi_status status = + napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, cb, data, result); + if (status == napi_ok) { + status = Napi::details::AttachData(env, *result, data); + } + + return status; +} + +template +inline Function Function::New(napi_env env, const char* utf8name, void* data) { + napi_value result = nullptr; + napi_status status = napi_create_function(env, + utf8name, + NAPI_AUTO_LENGTH, + details::TemplatedVoidCallback, + data, + &result); + NAPI_THROW_IF_FAILED(env, status, Function()); + return Function(env, result); +} + +template +inline Function Function::New(napi_env env, const char* utf8name, void* data) { + napi_value result = nullptr; + napi_status status = napi_create_function(env, + utf8name, + NAPI_AUTO_LENGTH, + details::TemplatedCallback, + data, + &result); + NAPI_THROW_IF_FAILED(env, status, Function()); + return Function(env, result); +} + +template +inline Function Function::New(napi_env env, + const std::string& utf8name, + void* data) { + return Function::New(env, utf8name.c_str(), data); +} + +template +inline Function Function::New(napi_env env, + const std::string& utf8name, + void* data) { + return Function::New(env, utf8name.c_str(), data); +} + +template +inline Function Function::New(napi_env env, + Callable cb, + const char* utf8name, + void* data) { + using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); + using CbData = details::CallbackData; + auto callbackData = new CbData({ cb, data }); + + napi_value value; + napi_status status = CreateFunction(env, + utf8name, + CbData::Wrapper, + callbackData, + &value); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, Function()); + } + + return Function(env, value); +} + +template +inline Function Function::New(napi_env env, + Callable cb, + const std::string& utf8name, + void* data) { + return New(env, cb, utf8name.c_str(), data); +} + +inline Function::Function() : Object() { +} + +inline Function::Function(napi_env env, napi_value value) : Object(env, value) { +} + +inline Value Function::operator ()(const std::initializer_list& args) const { + return Call(Env().Undefined(), args); +} + +inline Value Function::Call(const std::initializer_list& args) const { + return Call(Env().Undefined(), args); +} + +inline Value Function::Call(const std::vector& args) const { + return Call(Env().Undefined(), args); +} + +inline Value Function::Call(size_t argc, const napi_value* args) const { + return Call(Env().Undefined(), argc, args); +} + +inline Value Function::Call(napi_value recv, const std::initializer_list& args) const { + return Call(recv, args.size(), args.begin()); +} + +inline Value Function::Call(napi_value recv, const std::vector& args) const { + return Call(recv, args.size(), args.data()); +} + +inline Value Function::Call(napi_value recv, size_t argc, const napi_value* args) const { + napi_value result; + napi_status status = napi_call_function( + _env, recv, _value, argc, args, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +inline Value Function::MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context) const { + return MakeCallback(recv, args.size(), args.begin(), context); +} + +inline Value Function::MakeCallback( + napi_value recv, + const std::vector& args, + napi_async_context context) const { + return MakeCallback(recv, args.size(), args.data(), context); +} + +inline Value Function::MakeCallback( + napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context) const { + napi_value result; + napi_status status = napi_make_callback( + _env, context, recv, _value, argc, args, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +inline Object Function::New(const std::initializer_list& args) const { + return New(args.size(), args.begin()); +} + +inline Object Function::New(const std::vector& args) const { + return New(args.size(), args.data()); +} + +inline Object Function::New(size_t argc, const napi_value* args) const { + napi_value result; + napi_status status = napi_new_instance( + _env, _value, argc, args, &result); + NAPI_THROW_IF_FAILED(_env, status, Object()); + return Object(_env, result); +} + +//////////////////////////////////////////////////////////////////////////////// +// Promise class +//////////////////////////////////////////////////////////////////////////////// + +inline Promise::Deferred Promise::Deferred::New(napi_env env) { + return Promise::Deferred(env); +} + +inline Promise::Deferred::Deferred(napi_env env) : _env(env) { + napi_status status = napi_create_promise(_env, &_deferred, &_promise); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline Promise Promise::Deferred::Promise() const { + return Napi::Promise(_env, _promise); +} + +inline Napi::Env Promise::Deferred::Env() const { + return Napi::Env(_env); +} + +inline void Promise::Deferred::Resolve(napi_value value) const { + napi_status status = napi_resolve_deferred(_env, _deferred, value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void Promise::Deferred::Reject(napi_value value) const { + napi_status status = napi_reject_deferred(_env, _deferred, value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) { +} + +//////////////////////////////////////////////////////////////////////////////// +// Buffer class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Buffer Buffer::New(napi_env env, size_t length) { + napi_value value; + void* data; + napi_status status = napi_create_buffer(env, length * sizeof (T), &data, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value, length, static_cast(data)); +} + +template +inline Buffer Buffer::New(napi_env env, T* data, size_t length) { + napi_value value; + napi_status status = napi_create_external_buffer( + env, length * sizeof (T), data, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value, length, data); +} + +template +template +inline Buffer Buffer::New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = napi_create_external_buffer( + env, + length * sizeof (T), + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value, length, data); +} + +template +template +inline Buffer Buffer::New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = napi_create_external_buffer( + env, + length * sizeof (T), + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value, length, data); +} + +template +inline Buffer Buffer::Copy(napi_env env, const T* data, size_t length) { + napi_value value; + napi_status status = napi_create_buffer_copy( + env, length * sizeof (T), data, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value); +} + +template +inline Buffer::Buffer() : Uint8Array(), _length(0), _data(nullptr) { +} + +template +inline Buffer::Buffer(napi_env env, napi_value value) + : Uint8Array(env, value), _length(0), _data(nullptr) { +} + +template +inline Buffer::Buffer(napi_env env, napi_value value, size_t length, T* data) + : Uint8Array(env, value), _length(length), _data(data) { +} + +template +inline size_t Buffer::Length() const { + EnsureInfo(); + return _length; +} + +template +inline T* Buffer::Data() const { + EnsureInfo(); + return _data; +} + +template +inline void Buffer::EnsureInfo() const { + // The Buffer instance may have been constructed from a napi_value whose + // length/data are not yet known. Fetch and cache these values just once, + // since they can never change during the lifetime of the Buffer. + if (_data == nullptr) { + size_t byteLength; + void* voidData; + napi_status status = napi_get_buffer_info(_env, _value, &voidData, &byteLength); + NAPI_THROW_IF_FAILED_VOID(_env, status); + _length = byteLength / sizeof (T); + _data = static_cast(voidData); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Error class +//////////////////////////////////////////////////////////////////////////////// + +inline Error Error::New(napi_env env) { + napi_status status; + napi_value error = nullptr; + bool is_exception_pending; + const napi_extended_error_info* info; + + // We must retrieve the last error info before doing anything else, because + // doing anything else will replace the last error info. + status = napi_get_last_error_info(env, &info); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_last_error_info"); + + status = napi_is_exception_pending(env, &is_exception_pending); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_is_exception_pending"); + + // A pending exception takes precedence over any internal error status. + if (is_exception_pending) { + status = napi_get_and_clear_last_exception(env, &error); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_and_clear_last_exception"); + } + else { + const char* error_message = info->error_message != nullptr ? + info->error_message : "Error in native callback"; + + napi_value message; + status = napi_create_string_utf8( + env, + error_message, + std::strlen(error_message), + &message); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_string_utf8"); + + switch (info->error_code) { + case napi_object_expected: + case napi_string_expected: + case napi_boolean_expected: + case napi_number_expected: + status = napi_create_type_error(env, nullptr, message, &error); + break; + default: + status = napi_create_error(env, nullptr, message, &error); + break; + } + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_error"); + } + + return Error(env, error); +} + +inline Error Error::New(napi_env env, const char* message) { + return Error::New(env, message, std::strlen(message), napi_create_error); +} + +inline Error Error::New(napi_env env, const std::string& message) { + return Error::New(env, message.c_str(), message.size(), napi_create_error); +} + +inline NAPI_NO_RETURN void Error::Fatal(const char* location, const char* message) { + napi_fatal_error(location, NAPI_AUTO_LENGTH, message, NAPI_AUTO_LENGTH); +} + +inline Error::Error() : ObjectReference() { +} + +inline Error::Error(napi_env env, napi_value value) : ObjectReference(env, nullptr) { + if (value != nullptr) { + napi_status status = napi_create_reference(env, value, 1, &_ref); + + // Avoid infinite recursion in the failure case. + // Don't try to construct & throw another Error instance. + NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_reference"); + } +} + +inline Error::Error(Error&& other) : ObjectReference(std::move(other)) { +} + +inline Error& Error::operator =(Error&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline Error::Error(const Error& other) : ObjectReference(other) { +} + +inline Error& Error::operator =(const Error& other) { + Reset(); + + _env = other.Env(); + HandleScope scope(_env); + + napi_value value = other.Value(); + if (value != nullptr) { + napi_status status = napi_create_reference(_env, value, 1, &_ref); + NAPI_THROW_IF_FAILED(_env, status, *this); + } + + return *this; +} + +inline const std::string& Error::Message() const NAPI_NOEXCEPT { + if (_message.size() == 0 && _env != nullptr) { +#ifdef NAPI_CPP_EXCEPTIONS + try { + _message = Get("message").As(); + } + catch (...) { + // Catch all errors here, to include e.g. a std::bad_alloc from + // the std::string::operator=, because this method may not throw. + } +#else // NAPI_CPP_EXCEPTIONS + _message = Get("message").As(); +#endif // NAPI_CPP_EXCEPTIONS + } + return _message; +} + +inline void Error::ThrowAsJavaScriptException() const { + HandleScope scope(_env); + if (!IsEmpty()) { + + // We intentionally don't use `NAPI_THROW_*` macros here to ensure + // that there is no possible recursion as `ThrowAsJavaScriptException` + // is part of `NAPI_THROW_*` macro definition for noexcept. + + napi_status status = napi_throw(_env, Value()); + +#ifdef NAPI_CPP_EXCEPTIONS + if (status != napi_ok) { + throw Error::New(_env); + } +#else // NAPI_CPP_EXCEPTIONS + NAPI_FATAL_IF_FAILED(status, "Error::ThrowAsJavaScriptException", "napi_throw"); +#endif // NAPI_CPP_EXCEPTIONS + } +} + +#ifdef NAPI_CPP_EXCEPTIONS + +inline const char* Error::what() const NAPI_NOEXCEPT { + return Message().c_str(); +} + +#endif // NAPI_CPP_EXCEPTIONS + +template +inline TError Error::New(napi_env env, + const char* message, + size_t length, + create_error_fn create_error) { + napi_value str; + napi_status status = napi_create_string_utf8(env, message, length, &str); + NAPI_THROW_IF_FAILED(env, status, TError()); + + napi_value error; + status = create_error(env, nullptr, str, &error); + NAPI_THROW_IF_FAILED(env, status, TError()); + + return TError(env, error); +} + +inline TypeError TypeError::New(napi_env env, const char* message) { + return Error::New(env, message, std::strlen(message), napi_create_type_error); +} + +inline TypeError TypeError::New(napi_env env, const std::string& message) { + return Error::New(env, message.c_str(), message.size(), napi_create_type_error); +} + +inline TypeError::TypeError() : Error() { +} + +inline TypeError::TypeError(napi_env env, napi_value value) : Error(env, value) { +} + +inline RangeError RangeError::New(napi_env env, const char* message) { + return Error::New(env, message, std::strlen(message), napi_create_range_error); +} + +inline RangeError RangeError::New(napi_env env, const std::string& message) { + return Error::New(env, message.c_str(), message.size(), napi_create_range_error); +} + +inline RangeError::RangeError() : Error() { +} + +inline RangeError::RangeError(napi_env env, napi_value value) : Error(env, value) { +} + +//////////////////////////////////////////////////////////////////////////////// +// Reference class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Reference Reference::New(const T& value, uint32_t initialRefcount) { + napi_env env = value.Env(); + napi_value val = value; + + if (val == nullptr) { + return Reference(env, nullptr); + } + + napi_ref ref; + napi_status status = napi_create_reference(env, value, initialRefcount, &ref); + NAPI_THROW_IF_FAILED(env, status, Reference()); + + return Reference(env, ref); +} + + +template +inline Reference::Reference() : _env(nullptr), _ref(nullptr), _suppressDestruct(false) { +} + +template +inline Reference::Reference(napi_env env, napi_ref ref) + : _env(env), _ref(ref), _suppressDestruct(false) { +} + +template +inline Reference::~Reference() { + if (_ref != nullptr) { + if (!_suppressDestruct) { + napi_delete_reference(_env, _ref); + } + + _ref = nullptr; + } +} + +template +inline Reference::Reference(Reference&& other) + : _env(other._env), _ref(other._ref), _suppressDestruct(other._suppressDestruct) { + other._env = nullptr; + other._ref = nullptr; + other._suppressDestruct = false; +} + +template +inline Reference& Reference::operator =(Reference&& other) { + Reset(); + _env = other._env; + _ref = other._ref; + _suppressDestruct = other._suppressDestruct; + other._env = nullptr; + other._ref = nullptr; + other._suppressDestruct = false; + return *this; +} + +template +inline Reference::Reference(const Reference& other) + : _env(other._env), _ref(nullptr), _suppressDestruct(false) { + HandleScope scope(_env); + + napi_value value = other.Value(); + if (value != nullptr) { + // Copying is a limited scenario (currently only used for Error object) and always creates a + // strong reference to the given value even if the incoming reference is weak. + napi_status status = napi_create_reference(_env, value, 1, &_ref); + NAPI_FATAL_IF_FAILED(status, "Reference::Reference", "napi_create_reference"); + } +} + +template +inline Reference::operator napi_ref() const { + return _ref; +} + +template +inline bool Reference::operator ==(const Reference &other) const { + HandleScope scope(_env); + return this->Value().StrictEquals(other.Value()); +} + +template +inline bool Reference::operator !=(const Reference &other) const { + return !this->operator ==(other); +} + +template +inline Napi::Env Reference::Env() const { + return Napi::Env(_env); +} + +template +inline bool Reference::IsEmpty() const { + return _ref == nullptr; +} + +template +inline T Reference::Value() const { + if (_ref == nullptr) { + return T(_env, nullptr); + } + + napi_value value; + napi_status status = napi_get_reference_value(_env, _ref, &value); + NAPI_THROW_IF_FAILED(_env, status, T()); + return T(_env, value); +} + +template +inline uint32_t Reference::Ref() { + uint32_t result; + napi_status status = napi_reference_ref(_env, _ref, &result); + NAPI_THROW_IF_FAILED(_env, status, 1); + return result; +} + +template +inline uint32_t Reference::Unref() { + uint32_t result; + napi_status status = napi_reference_unref(_env, _ref, &result); + NAPI_THROW_IF_FAILED(_env, status, 1); + return result; +} + +template +inline void Reference::Reset() { + if (_ref != nullptr) { + napi_status status = napi_delete_reference(_env, _ref); + NAPI_THROW_IF_FAILED_VOID(_env, status); + _ref = nullptr; + } +} + +template +inline void Reference::Reset(const T& value, uint32_t refcount) { + Reset(); + _env = value.Env(); + + napi_value val = value; + if (val != nullptr) { + napi_status status = napi_create_reference(_env, value, refcount, &_ref); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +template +inline void Reference::SuppressDestruct() { + _suppressDestruct = true; +} + +template +inline Reference Weak(T value) { + return Reference::New(value, 0); +} + +inline ObjectReference Weak(Object value) { + return Reference::New(value, 0); +} + +inline FunctionReference Weak(Function value) { + return Reference::New(value, 0); +} + +template +inline Reference Persistent(T value) { + return Reference::New(value, 1); +} + +inline ObjectReference Persistent(Object value) { + return Reference::New(value, 1); +} + +inline FunctionReference Persistent(Function value) { + return Reference::New(value, 1); +} + +//////////////////////////////////////////////////////////////////////////////// +// ObjectReference class +//////////////////////////////////////////////////////////////////////////////// + +inline ObjectReference::ObjectReference(): Reference() { +} + +inline ObjectReference::ObjectReference(napi_env env, napi_ref ref): Reference(env, ref) { +} + +inline ObjectReference::ObjectReference(Reference&& other) + : Reference(std::move(other)) { +} + +inline ObjectReference& ObjectReference::operator =(Reference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline ObjectReference::ObjectReference(ObjectReference&& other) + : Reference(std::move(other)) { +} + +inline ObjectReference& ObjectReference::operator =(ObjectReference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline ObjectReference::ObjectReference(const ObjectReference& other) + : Reference(other) { +} + +inline Napi::Value ObjectReference::Get(const char* utf8name) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value().Get(utf8name)); +} + +inline Napi::Value ObjectReference::Get(const std::string& utf8name) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value().Get(utf8name)); +} + +inline bool ObjectReference::Set(const char* utf8name, napi_value value) { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline bool ObjectReference::Set(const char* utf8name, Napi::Value value) { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline bool ObjectReference::Set(const char* utf8name, const char* utf8value) { + HandleScope scope(_env); + return Value().Set(utf8name, utf8value); +} + +inline bool ObjectReference::Set(const char* utf8name, bool boolValue) { + HandleScope scope(_env); + return Value().Set(utf8name, boolValue); +} + +inline bool ObjectReference::Set(const char* utf8name, double numberValue) { + HandleScope scope(_env); + return Value().Set(utf8name, numberValue); +} + +inline bool ObjectReference::Set(const std::string& utf8name, + napi_value value) { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline bool ObjectReference::Set(const std::string& utf8name, + Napi::Value value) { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline bool ObjectReference::Set(const std::string& utf8name, + std::string& utf8value) { + HandleScope scope(_env); + return Value().Set(utf8name, utf8value); +} + +inline bool ObjectReference::Set(const std::string& utf8name, bool boolValue) { + HandleScope scope(_env); + return Value().Set(utf8name, boolValue); +} + +inline bool ObjectReference::Set(const std::string& utf8name, + double numberValue) { + HandleScope scope(_env); + return Value().Set(utf8name, numberValue); +} + +inline Napi::Value ObjectReference::Get(uint32_t index) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value().Get(index)); +} + +inline bool ObjectReference::Set(uint32_t index, napi_value value) { + HandleScope scope(_env); + return Value().Set(index, value); +} + +inline bool ObjectReference::Set(uint32_t index, Napi::Value value) { + HandleScope scope(_env); + return Value().Set(index, value); +} + +inline bool ObjectReference::Set(uint32_t index, const char* utf8value) { + HandleScope scope(_env); + return Value().Set(index, utf8value); +} + +inline bool ObjectReference::Set(uint32_t index, const std::string& utf8value) { + HandleScope scope(_env); + return Value().Set(index, utf8value); +} + +inline bool ObjectReference::Set(uint32_t index, bool boolValue) { + HandleScope scope(_env); + return Value().Set(index, boolValue); +} + +inline bool ObjectReference::Set(uint32_t index, double numberValue) { + HandleScope scope(_env); + return Value().Set(index, numberValue); +} + +//////////////////////////////////////////////////////////////////////////////// +// FunctionReference class +//////////////////////////////////////////////////////////////////////////////// + +inline FunctionReference::FunctionReference(): Reference() { +} + +inline FunctionReference::FunctionReference(napi_env env, napi_ref ref) + : Reference(env, ref) { +} + +inline FunctionReference::FunctionReference(Reference&& other) + : Reference(std::move(other)) { +} + +inline FunctionReference& FunctionReference::operator =(Reference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline FunctionReference::FunctionReference(FunctionReference&& other) + : Reference(std::move(other)) { +} + +inline FunctionReference& FunctionReference::operator =(FunctionReference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline Napi::Value FunctionReference::operator ()( + const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value()(args)); +} + +inline Napi::Value FunctionReference::Call(const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().Call(args); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Napi::Value FunctionReference::Call(const std::vector& args) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().Call(args); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Napi::Value FunctionReference::Call( + napi_value recv, const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().Call(recv, args); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Napi::Value FunctionReference::Call( + napi_value recv, const std::vector& args) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().Call(recv, args); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Napi::Value FunctionReference::Call( + napi_value recv, size_t argc, const napi_value* args) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().Call(recv, argc, args); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Napi::Value FunctionReference::MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().MakeCallback(recv, args, context); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Napi::Value FunctionReference::MakeCallback( + napi_value recv, + const std::vector& args, + napi_async_context context) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().MakeCallback(recv, args, context); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Napi::Value FunctionReference::MakeCallback( + napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().MakeCallback(recv, argc, args, context); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Object FunctionReference::New(const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value().New(args)).As(); +} + +inline Object FunctionReference::New(const std::vector& args) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value().New(args)).As(); +} + +//////////////////////////////////////////////////////////////////////////////// +// CallbackInfo class +//////////////////////////////////////////////////////////////////////////////// + +inline CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info) + : _env(env), _info(info), _this(nullptr), _dynamicArgs(nullptr), _data(nullptr) { + _argc = _staticArgCount; + _argv = _staticArgs; + napi_status status = napi_get_cb_info(env, info, &_argc, _argv, &_this, &_data); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + if (_argc > _staticArgCount) { + // Use either a fixed-size array (on the stack) or a dynamically-allocated + // array (on the heap) depending on the number of args. + _dynamicArgs = new napi_value[_argc]; + _argv = _dynamicArgs; + + status = napi_get_cb_info(env, info, &_argc, _argv, nullptr, nullptr); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +inline CallbackInfo::~CallbackInfo() { + if (_dynamicArgs != nullptr) { + delete[] _dynamicArgs; + } +} + +inline Value CallbackInfo::NewTarget() const { + napi_value newTarget; + napi_status status = napi_get_new_target(_env, _info, &newTarget); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, newTarget); +} + +inline bool CallbackInfo::IsConstructCall() const { + return !NewTarget().IsEmpty(); +} + +inline Napi::Env CallbackInfo::Env() const { + return Napi::Env(_env); +} + +inline size_t CallbackInfo::Length() const { + return _argc; +} + +inline const Value CallbackInfo::operator [](size_t index) const { + return index < _argc ? Value(_env, _argv[index]) : Env().Undefined(); +} + +inline Value CallbackInfo::This() const { + if (_this == nullptr) { + return Env().Undefined(); + } + return Object(_env, _this); +} + +inline void* CallbackInfo::Data() const { + return _data; +} + +inline void CallbackInfo::SetData(void* data) { + _data = data; +} + +//////////////////////////////////////////////////////////////////////////////// +// PropertyDescriptor class +//////////////////////////////////////////////////////////////////////////////// + +template +PropertyDescriptor +PropertyDescriptor::Accessor(const char* utf8name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + + desc.utf8name = utf8name; + desc.getter = details::TemplatedCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template +PropertyDescriptor +PropertyDescriptor::Accessor(const std::string& utf8name, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), attributes, data); +} + +template +PropertyDescriptor +PropertyDescriptor::Accessor(Name name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + + desc.name = name; + desc.getter = details::TemplatedCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template < +typename PropertyDescriptor::GetterCallback Getter, +typename PropertyDescriptor::SetterCallback Setter> +PropertyDescriptor +PropertyDescriptor::Accessor(const char* utf8name, + napi_property_attributes attributes, + void* data) { + + napi_property_descriptor desc = napi_property_descriptor(); + + desc.utf8name = utf8name; + desc.getter = details::TemplatedCallback; + desc.setter = details::TemplatedVoidCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template < +typename PropertyDescriptor::GetterCallback Getter, +typename PropertyDescriptor::SetterCallback Setter> +PropertyDescriptor +PropertyDescriptor::Accessor(const std::string& utf8name, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), attributes, data); +} + +template < +typename PropertyDescriptor::GetterCallback Getter, +typename PropertyDescriptor::SetterCallback Setter> +PropertyDescriptor +PropertyDescriptor::Accessor(Name name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + + desc.name = name; + desc.getter = details::TemplatedCallback; + desc.setter = details::TemplatedVoidCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template +inline PropertyDescriptor +PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { + using CbData = details::CallbackData; + auto callbackData = new CbData({ getter, data }); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({ + utf8name, + nullptr, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { + return Accessor(env, object, utf8name.c_str(), getter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + napi_property_attributes attributes, + void* data) { + using CbData = details::CallbackData; + auto callbackData = new CbData({ getter, data }); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({ + nullptr, + name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + using CbData = details::AccessorCallbackData; + auto callbackData = new CbData({ getter, setter, data }); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({ + utf8name, + nullptr, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + return Accessor(env, object, utf8name.c_str(), getter, setter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + using CbData = details::AccessorCallbackData; + auto callbackData = new CbData({ getter, setter, data }); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({ + nullptr, + name, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env, + Napi::Object /*object*/, + const char* utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return PropertyDescriptor({ + utf8name, + nullptr, + nullptr, + nullptr, + nullptr, + Napi::Function::New(env, cb, utf8name, data), + attributes, + nullptr + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return Function(env, object, utf8name.c_str(), cb, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env, + Napi::Object /*object*/, + Name name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return PropertyDescriptor({ + nullptr, + name, + nullptr, + nullptr, + nullptr, + Napi::Function::New(env, cb, nullptr, data), + attributes, + nullptr + }); +} + +inline PropertyDescriptor PropertyDescriptor::Value(const char* utf8name, + napi_value value, + napi_property_attributes attributes) { + return PropertyDescriptor({ + utf8name, nullptr, nullptr, nullptr, nullptr, value, attributes, nullptr + }); +} + +inline PropertyDescriptor PropertyDescriptor::Value(const std::string& utf8name, + napi_value value, + napi_property_attributes attributes) { + return Value(utf8name.c_str(), value, attributes); +} + +inline PropertyDescriptor PropertyDescriptor::Value(napi_value name, + napi_value value, + napi_property_attributes attributes) { + return PropertyDescriptor({ + nullptr, name, nullptr, nullptr, nullptr, value, attributes, nullptr + }); +} + +inline PropertyDescriptor PropertyDescriptor::Value(Name name, + Napi::Value value, + napi_property_attributes attributes) { + napi_value nameValue = name; + napi_value valueValue = value; + return PropertyDescriptor::Value(nameValue, valueValue, attributes); +} + +inline PropertyDescriptor::PropertyDescriptor(napi_property_descriptor desc) + : _desc(desc) { +} + +inline PropertyDescriptor::operator napi_property_descriptor&() { + return _desc; +} + +inline PropertyDescriptor::operator const napi_property_descriptor&() const { + return _desc; +} + +//////////////////////////////////////////////////////////////////////////////// +// InstanceWrap class +//////////////////////////////////////////////////////////////////////////////// + +template +inline void InstanceWrap::AttachPropData(napi_env env, + napi_value value, + const napi_property_descriptor* prop) { + napi_status status; + if (!(prop->attributes & napi_static)) { + if (prop->method == T::InstanceVoidMethodCallbackWrapper) { + status = Napi::details::AttachData(env, + value, + static_cast(prop->data)); + NAPI_THROW_IF_FAILED_VOID(env, status); + } else if (prop->method == T::InstanceMethodCallbackWrapper) { + status = Napi::details::AttachData(env, + value, + static_cast(prop->data)); + NAPI_THROW_IF_FAILED_VOID(env, status); + } else if (prop->getter == T::InstanceGetterCallbackWrapper || + prop->setter == T::InstanceSetterCallbackWrapper) { + status = Napi::details::AttachData(env, + value, + static_cast(prop->data)); + NAPI_THROW_IF_FAILED_VOID(env, status); + } + } +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceVoidMethodCallbackData* callbackData = + new InstanceVoidMethodCallbackData({ method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::InstanceVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, + InstanceMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceMethodCallbackData* callbackData = new InstanceMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::InstanceMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceVoidMethodCallbackData* callbackData = + new InstanceVoidMethodCallbackData({ method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::InstanceVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, + InstanceMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceMethodCallbackData* callbackData = new InstanceMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::InstanceMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceVoidMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedInstanceVoidCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedInstanceCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceVoidMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedInstanceVoidCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedInstanceCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + const char* utf8name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes, + void* data) { + InstanceAccessorCallbackData* callbackData = + new InstanceAccessorCallbackData({ getter, setter, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + Symbol name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes, + void* data) { + InstanceAccessorCallbackData* callbackData = + new InstanceAccessorCallbackData({ getter, setter, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceGetterCallback getter, + typename InstanceWrap::InstanceSetterCallback setter> +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + const char* utf8name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = details::TemplatedInstanceCallback; + desc.setter = This::WrapSetter(This::SetterTag()); + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceGetterCallback getter, + typename InstanceWrap::InstanceSetterCallback setter> +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + Symbol name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = details::TemplatedInstanceCallback; + desc.setter = This::WrapSetter(This::SetterTag()); + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.value = value; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceValue( + Symbol name, + Napi::Value value, + napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.value = value; + desc.attributes = attributes; + return desc; +} + +template +inline napi_value InstanceWrap::InstanceVoidMethodCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceVoidMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->callback; + (instance->*cb)(callbackInfo); + return nullptr; + }); +} + +template +inline napi_value InstanceWrap::InstanceMethodCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->callback; + return (instance->*cb)(callbackInfo); + }); +} + +template +inline napi_value InstanceWrap::InstanceGetterCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->getterCallback; + return (instance->*cb)(callbackInfo); + }); +} + +template +inline napi_value InstanceWrap::InstanceSetterCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->setterCallback; + (instance->*cb)(callbackInfo, callbackInfo[0]); + return nullptr; + }); +} + +template +template ::InstanceSetterCallback method> +inline napi_value InstanceWrap::WrappedMethod( + napi_env env, napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback([&] { + const CallbackInfo cbInfo(env, info); + T* instance = T::Unwrap(cbInfo.This().As()); + (instance->*method)(cbInfo, cbInfo[0]); + return nullptr; + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// ObjectWrap class +//////////////////////////////////////////////////////////////////////////////// + +template +inline ObjectWrap::ObjectWrap(const Napi::CallbackInfo& callbackInfo) { + napi_env env = callbackInfo.Env(); + napi_value wrapper = callbackInfo.This(); + napi_status status; + napi_ref ref; + T* instance = static_cast(this); + status = napi_wrap(env, wrapper, instance, FinalizeCallback, nullptr, &ref); + NAPI_THROW_IF_FAILED_VOID(env, status); + + Reference* instanceRef = instance; + *instanceRef = Reference(env, ref); +} + +template +inline ObjectWrap::~ObjectWrap() { + // If the JS object still exists at this point, remove the finalizer added + // through `napi_wrap()`. + if (!IsEmpty()) { + Object object = Value(); + // It is not valid to call `napi_remove_wrap()` with an empty `object`. + // This happens e.g. during garbage collection. + if (!object.IsEmpty() && _construction_failed) { + napi_remove_wrap(Env(), object, nullptr); + } + } +} + +template +inline T* ObjectWrap::Unwrap(Object wrapper) { + T* unwrapped; + napi_status status = napi_unwrap(wrapper.Env(), wrapper, reinterpret_cast(&unwrapped)); + NAPI_THROW_IF_FAILED(wrapper.Env(), status, nullptr); + return unwrapped; +} + +template +inline Function +ObjectWrap::DefineClass(Napi::Env env, + const char* utf8name, + const size_t props_count, + const napi_property_descriptor* descriptors, + void* data) { + napi_status status; + std::vector props(props_count); + + // We copy the descriptors to a local array because before defining the class + // we must replace static method property descriptors with value property + // descriptors such that the value is a function-valued `napi_value` created + // with `CreateFunction()`. + // + // This replacement could be made for instance methods as well, but V8 aborts + // if we do that, because it expects methods defined on the prototype template + // to have `FunctionTemplate`s. + for (size_t index = 0; index < props_count; index++) { + props[index] = descriptors[index]; + napi_property_descriptor* prop = &props[index]; + if (prop->method == T::StaticMethodCallbackWrapper) { + status = CreateFunction(env, + utf8name, + prop->method, + static_cast(prop->data), + &(prop->value)); + NAPI_THROW_IF_FAILED(env, status, Function()); + prop->method = nullptr; + prop->data = nullptr; + } else if (prop->method == T::StaticVoidMethodCallbackWrapper) { + status = CreateFunction(env, + utf8name, + prop->method, + static_cast(prop->data), + &(prop->value)); + NAPI_THROW_IF_FAILED(env, status, Function()); + prop->method = nullptr; + prop->data = nullptr; + } + } + + napi_value value; + status = napi_define_class(env, + utf8name, + NAPI_AUTO_LENGTH, + T::ConstructorCallbackWrapper, + data, + props_count, + props.data(), + &value); + NAPI_THROW_IF_FAILED(env, status, Function()); + + // After defining the class we iterate once more over the property descriptors + // and attach the data associated with accessors and instance methods to the + // newly created JavaScript class. + for (size_t idx = 0; idx < props_count; idx++) { + const napi_property_descriptor* prop = &props[idx]; + + if (prop->getter == T::StaticGetterCallbackWrapper || + prop->setter == T::StaticSetterCallbackWrapper) { + status = Napi::details::AttachData(env, + value, + static_cast(prop->data)); + NAPI_THROW_IF_FAILED(env, status, Function()); + } else { + // InstanceWrap::AttachPropData is responsible for attaching the data + // of instance methods and accessors. + T::AttachPropData(env, value, prop); + } + } + + return Function(env, value); +} + +template +inline Function ObjectWrap::DefineClass( + Napi::Env env, + const char* utf8name, + const std::initializer_list>& properties, + void* data) { + return DefineClass(env, + utf8name, + properties.size(), + reinterpret_cast(properties.begin()), + data); +} + +template +inline Function ObjectWrap::DefineClass( + Napi::Env env, + const char* utf8name, + const std::vector>& properties, + void* data) { + return DefineClass(env, + utf8name, + properties.size(), + reinterpret_cast(properties.data()), + data); +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, + StaticVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticVoidMethodCallbackData* callbackData = new StaticVoidMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::StaticVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, + StaticMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticMethodCallbackData* callbackData = new StaticMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::StaticMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, + StaticVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticVoidMethodCallbackData* callbackData = new StaticVoidMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::StaticVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, + StaticMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticMethodCallbackData* callbackData = new StaticMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::StaticMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticVoidMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedVoidCallback; + desc.data = data; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticVoidMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedVoidCallback; + desc.data = data; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedCallback; + desc.data = data; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedCallback; + desc.data = data; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + const char* utf8name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes, + void* data) { + StaticAccessorCallbackData* callbackData = + new StaticAccessorCallbackData({ getter, setter, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + Symbol name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes, + void* data) { + StaticAccessorCallbackData* callbackData = + new StaticAccessorCallbackData({ getter, setter, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticGetterCallback getter, + typename ObjectWrap::StaticSetterCallback setter> +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + const char* utf8name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = details::TemplatedCallback; + desc.setter = This::WrapStaticSetter(This::StaticSetterTag()); + desc.data = data; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticGetterCallback getter, + typename ObjectWrap::StaticSetterCallback setter> +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + Symbol name, + napi_property_attributes attributes, + void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = details::TemplatedCallback; + desc.setter = This::WrapStaticSetter(This::StaticSetterTag()); + desc.data = data; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticValue(const char* utf8name, + Napi::Value value, napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.value = value; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticValue(Symbol name, + Napi::Value value, napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.value = value; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline void ObjectWrap::Finalize(Napi::Env /*env*/) {} + +template +inline napi_value ObjectWrap::ConstructorCallbackWrapper( + napi_env env, + napi_callback_info info) { + napi_value new_target; + napi_status status = napi_get_new_target(env, info, &new_target); + if (status != napi_ok) return nullptr; + + bool isConstructCall = (new_target != nullptr); + if (!isConstructCall) { + napi_throw_type_error(env, nullptr, "Class constructors cannot be invoked without 'new'"); + return nullptr; + } + + napi_value wrapper = details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + T* instance = new T(callbackInfo); +#ifdef NAPI_CPP_EXCEPTIONS + instance->_construction_failed = false; +#else + if (callbackInfo.Env().IsExceptionPending()) { + // We need to clear the exception so that removing the wrap might work. + Error e = callbackInfo.Env().GetAndClearPendingException(); + delete instance; + e.ThrowAsJavaScriptException(); + } else { + instance->_construction_failed = false; + } +# endif // NAPI_CPP_EXCEPTIONS + return callbackInfo.This(); + }); + + return wrapper; +} + +template +inline napi_value ObjectWrap::StaticVoidMethodCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticVoidMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->callback(callbackInfo); + return nullptr; + }); +} + +template +inline napi_value ObjectWrap::StaticMethodCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->callback(callbackInfo); + }); +} + +template +inline napi_value ObjectWrap::StaticGetterCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->getterCallback(callbackInfo); + }); +} + +template +inline napi_value ObjectWrap::StaticSetterCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->setterCallback(callbackInfo, callbackInfo[0]); + return nullptr; + }); +} + +template +inline void ObjectWrap::FinalizeCallback(napi_env env, void* data, void* /*hint*/) { + HandleScope scope(env); + T* instance = static_cast(data); + instance->Finalize(Napi::Env(env)); + delete instance; +} + +template +template ::StaticSetterCallback method> +inline napi_value ObjectWrap::WrappedMethod( + napi_env env, napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback([&] { + const CallbackInfo cbInfo(env, info); + method(cbInfo, cbInfo[0]); + return nullptr; + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// HandleScope class +//////////////////////////////////////////////////////////////////////////////// + +inline HandleScope::HandleScope(napi_env env, napi_handle_scope scope) + : _env(env), _scope(scope) { +} + +inline HandleScope::HandleScope(Napi::Env env) : _env(env) { + napi_status status = napi_open_handle_scope(_env, &_scope); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline HandleScope::~HandleScope() { + napi_status status = napi_close_handle_scope(_env, _scope); + NAPI_FATAL_IF_FAILED(status, + "HandleScope::~HandleScope", + "napi_close_handle_scope"); +} + +inline HandleScope::operator napi_handle_scope() const { + return _scope; +} + +inline Napi::Env HandleScope::Env() const { + return Napi::Env(_env); +} + +//////////////////////////////////////////////////////////////////////////////// +// EscapableHandleScope class +//////////////////////////////////////////////////////////////////////////////// + +inline EscapableHandleScope::EscapableHandleScope( + napi_env env, napi_escapable_handle_scope scope) : _env(env), _scope(scope) { +} + +inline EscapableHandleScope::EscapableHandleScope(Napi::Env env) : _env(env) { + napi_status status = napi_open_escapable_handle_scope(_env, &_scope); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline EscapableHandleScope::~EscapableHandleScope() { + napi_status status = napi_close_escapable_handle_scope(_env, _scope); + NAPI_FATAL_IF_FAILED(status, + "EscapableHandleScope::~EscapableHandleScope", + "napi_close_escapable_handle_scope"); +} + +inline EscapableHandleScope::operator napi_escapable_handle_scope() const { + return _scope; +} + +inline Napi::Env EscapableHandleScope::Env() const { + return Napi::Env(_env); +} + +inline Value EscapableHandleScope::Escape(napi_value escapee) { + napi_value result; + napi_status status = napi_escape_handle(_env, _scope, escapee, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + + +#if (NAPI_VERSION > 2) +//////////////////////////////////////////////////////////////////////////////// +// CallbackScope class +//////////////////////////////////////////////////////////////////////////////// + +inline CallbackScope::CallbackScope( + napi_env env, napi_callback_scope scope) : _env(env), _scope(scope) { +} + +inline CallbackScope::CallbackScope(napi_env env, napi_async_context context) + : _env(env) { + napi_status status = napi_open_callback_scope( + _env, Object::New(env), context, &_scope); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline CallbackScope::~CallbackScope() { + napi_status status = napi_close_callback_scope(_env, _scope); + NAPI_FATAL_IF_FAILED(status, + "CallbackScope::~CallbackScope", + "napi_close_callback_scope"); +} + +inline CallbackScope::operator napi_callback_scope() const { + return _scope; +} + +inline Napi::Env CallbackScope::Env() const { + return Napi::Env(_env); +} +#endif + +//////////////////////////////////////////////////////////////////////////////// +// AsyncContext class +//////////////////////////////////////////////////////////////////////////////// + +inline AsyncContext::AsyncContext(napi_env env, const char* resource_name) + : AsyncContext(env, resource_name, Object::New(env)) { +} + +inline AsyncContext::AsyncContext(napi_env env, + const char* resource_name, + const Object& resource) + : _env(env), _context(nullptr) { + napi_value resource_id; + napi_status status = napi_create_string_utf8( + _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + status = napi_async_init(_env, resource, resource_id, &_context); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline AsyncContext::~AsyncContext() { + if (_context != nullptr) { + napi_async_destroy(_env, _context); + _context = nullptr; + } +} + +inline AsyncContext::AsyncContext(AsyncContext&& other) { + _env = other._env; + other._env = nullptr; + _context = other._context; + other._context = nullptr; +} + +inline AsyncContext& AsyncContext::operator =(AsyncContext&& other) { + _env = other._env; + other._env = nullptr; + _context = other._context; + other._context = nullptr; + return *this; +} + +inline AsyncContext::operator napi_async_context() const { + return _context; +} + +inline Napi::Env AsyncContext::Env() const { + return Napi::Env(_env); +} + +//////////////////////////////////////////////////////////////////////////////// +// AsyncWorker class +//////////////////////////////////////////////////////////////////////////////// + +inline AsyncWorker::AsyncWorker(const Function& callback) + : AsyncWorker(callback, "generic") { +} + +inline AsyncWorker::AsyncWorker(const Function& callback, + const char* resource_name) + : AsyncWorker(callback, resource_name, Object::New(callback.Env())) { +} + +inline AsyncWorker::AsyncWorker(const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncWorker(Object::New(callback.Env()), + callback, + resource_name, + resource) { +} + +inline AsyncWorker::AsyncWorker(const Object& receiver, + const Function& callback) + : AsyncWorker(receiver, callback, "generic") { +} + +inline AsyncWorker::AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name) + : AsyncWorker(receiver, + callback, + resource_name, + Object::New(callback.Env())) { +} + +inline AsyncWorker::AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource) + : _env(callback.Env()), + _receiver(Napi::Persistent(receiver)), + _callback(Napi::Persistent(callback)), + _suppress_destruct(false) { + napi_value resource_id; + napi_status status = napi_create_string_latin1( + _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + status = napi_create_async_work(_env, resource, resource_id, OnAsyncWorkExecute, + OnAsyncWorkComplete, this, &_work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline AsyncWorker::AsyncWorker(Napi::Env env) + : AsyncWorker(env, "generic") { +} + +inline AsyncWorker::AsyncWorker(Napi::Env env, + const char* resource_name) + : AsyncWorker(env, resource_name, Object::New(env)) { +} + +inline AsyncWorker::AsyncWorker(Napi::Env env, + const char* resource_name, + const Object& resource) + : _env(env), + _receiver(), + _callback(), + _suppress_destruct(false) { + napi_value resource_id; + napi_status status = napi_create_string_latin1( + _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + status = napi_create_async_work(_env, resource, resource_id, OnAsyncWorkExecute, + OnAsyncWorkComplete, this, &_work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline AsyncWorker::~AsyncWorker() { + if (_work != nullptr) { + napi_delete_async_work(_env, _work); + _work = nullptr; + } +} + +inline void AsyncWorker::Destroy() { + delete this; +} + +inline AsyncWorker::AsyncWorker(AsyncWorker&& other) { + _env = other._env; + other._env = nullptr; + _work = other._work; + other._work = nullptr; + _receiver = std::move(other._receiver); + _callback = std::move(other._callback); + _error = std::move(other._error); + _suppress_destruct = other._suppress_destruct; +} + +inline AsyncWorker& AsyncWorker::operator =(AsyncWorker&& other) { + _env = other._env; + other._env = nullptr; + _work = other._work; + other._work = nullptr; + _receiver = std::move(other._receiver); + _callback = std::move(other._callback); + _error = std::move(other._error); + _suppress_destruct = other._suppress_destruct; + return *this; +} + +inline AsyncWorker::operator napi_async_work() const { + return _work; +} + +inline Napi::Env AsyncWorker::Env() const { + return Napi::Env(_env); +} + +inline void AsyncWorker::Queue() { + napi_status status = napi_queue_async_work(_env, _work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void AsyncWorker::Cancel() { + napi_status status = napi_cancel_async_work(_env, _work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline ObjectReference& AsyncWorker::Receiver() { + return _receiver; +} + +inline FunctionReference& AsyncWorker::Callback() { + return _callback; +} + +inline void AsyncWorker::SuppressDestruct() { + _suppress_destruct = true; +} + +inline void AsyncWorker::OnOK() { + if (!_callback.IsEmpty()) { + _callback.Call(_receiver.Value(), GetResult(_callback.Env())); + } +} + +inline void AsyncWorker::OnError(const Error& e) { + if (!_callback.IsEmpty()) { + _callback.Call(_receiver.Value(), std::initializer_list{ e.Value() }); + } +} + +inline void AsyncWorker::SetError(const std::string& error) { + _error = error; +} + +inline std::vector AsyncWorker::GetResult(Napi::Env /*env*/) { + return {}; +} +// The OnAsyncWorkExecute method receives an napi_env argument. However, do NOT +// use it within this method, as it does not run on the JavaScript thread and +// must not run any method that would cause JavaScript to run. In practice, +// this means that almost any use of napi_env will be incorrect. +inline void AsyncWorker::OnAsyncWorkExecute(napi_env env, void* asyncworker) { + AsyncWorker* self = static_cast(asyncworker); + self->OnExecute(env); +} +// The OnExecute method receives an napi_env argument. However, do NOT +// use it within this method, as it does not run on the JavaScript thread and +// must not run any method that would cause JavaScript to run. In practice, +// this means that almost any use of napi_env will be incorrect. +inline void AsyncWorker::OnExecute(Napi::Env /*DO_NOT_USE*/) { +#ifdef NAPI_CPP_EXCEPTIONS + try { + Execute(); + } catch (const std::exception& e) { + SetError(e.what()); + } +#else // NAPI_CPP_EXCEPTIONS + Execute(); +#endif // NAPI_CPP_EXCEPTIONS +} + +inline void AsyncWorker::OnAsyncWorkComplete(napi_env env, + napi_status status, + void* asyncworker) { + AsyncWorker* self = static_cast(asyncworker); + self->OnWorkComplete(env, status); +} +inline void AsyncWorker::OnWorkComplete(Napi::Env /*env*/, napi_status status) { + if (status != napi_cancelled) { + HandleScope scope(_env); + details::WrapCallback([&] { + if (_error.size() == 0) { + OnOK(); + } + else { + OnError(Error::New(_env, _error)); + } + return nullptr; + }); + } + if (!_suppress_destruct) { + Destroy(); + } +} + +#if (NAPI_VERSION > 3 && !defined(__wasm32__)) +//////////////////////////////////////////////////////////////////////////////// +// TypedThreadSafeFunction class +//////////////////////////////////////////////////////////////////////////////// + +// Starting with NAPI 5, the JavaScript function `func` parameter of +// `napi_create_threadsafe_function` is optional. +#if NAPI_VERSION > 4 +// static, with Callback [missing] Resource [missing] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + nullptr, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [missing] Resource [passed] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + nullptr, + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [missing] Resource [missing] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + napi_status status = napi_create_threadsafe_function( + env, + nullptr, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [missing] Resource [passed] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + napi_status status = napi_create_threadsafe_function( + env, + nullptr, + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} +#endif + +// static, with Callback [passed] Resource [missing] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + callback, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [passed] Resource [passed] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + callback, + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [passed] Resource [missing] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + napi_status status = napi_create_threadsafe_function( + env, + callback, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with: Callback [passed] Resource [passed] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + CallbackType callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + napi_status status = napi_create_threadsafe_function( + env, + details::DefaultCallbackWrapper< + CallbackType, + TypedThreadSafeFunction>(env, + callback), + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +template +inline TypedThreadSafeFunction:: + TypedThreadSafeFunction() + : _tsfn() {} + +template +inline TypedThreadSafeFunction:: + TypedThreadSafeFunction(napi_threadsafe_function tsfn) + : _tsfn(tsfn) {} + +template +inline TypedThreadSafeFunction:: +operator napi_threadsafe_function() const { + return _tsfn; +} + +template +inline napi_status +TypedThreadSafeFunction::BlockingCall( + DataType* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking); +} + +template +inline napi_status +TypedThreadSafeFunction::NonBlockingCall( + DataType* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking); +} + +template +inline void TypedThreadSafeFunction::Ref( + napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_ref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +template +inline void TypedThreadSafeFunction::Unref( + napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_unref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +template +inline napi_status +TypedThreadSafeFunction::Acquire() const { + return napi_acquire_threadsafe_function(_tsfn); +} + +template +inline napi_status +TypedThreadSafeFunction::Release() { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_release); +} + +template +inline napi_status +TypedThreadSafeFunction::Abort() { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort); +} + +template +inline ContextType* +TypedThreadSafeFunction::GetContext() const { + void* context; + napi_status status = napi_get_threadsafe_function_context(_tsfn, &context); + NAPI_FATAL_IF_FAILED(status, + "TypedThreadSafeFunction::GetContext", + "napi_get_threadsafe_function_context"); + return static_cast(context); +} + +// static +template +void TypedThreadSafeFunction::CallJsInternal( + napi_env env, napi_value jsCallback, void* context, void* data) { + details::CallJsWrapper( + env, jsCallback, context, data); +} + +#if NAPI_VERSION == 4 +// static +template +Napi::Function +TypedThreadSafeFunction::EmptyFunctionFactory( + Napi::Env env) { + return Napi::Function::New(env, [](const CallbackInfo& cb) {}); +} + +// static +template +Napi::Function +TypedThreadSafeFunction::FunctionOrEmpty( + Napi::Env env, Napi::Function& callback) { + if (callback.IsEmpty()) { + return EmptyFunctionFactory(env); + } + return callback; +} + +#else +// static +template +std::nullptr_t +TypedThreadSafeFunction::EmptyFunctionFactory( + Napi::Env /*env*/) { + return nullptr; +} + +// static +template +Napi::Function +TypedThreadSafeFunction::FunctionOrEmpty( + Napi::Env /*env*/, Napi::Function& callback) { + return callback; +} + +#endif + +//////////////////////////////////////////////////////////////////////////////// +// ThreadSafeFunction class +//////////////////////////////////////////////////////////////////////////////// + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount) { + return New(env, callback, Object(), resourceName, maxQueueSize, + initialThreadCount); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + return New(env, callback, Object(), resourceName, maxQueueSize, + initialThreadCount, context); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback) { + return New(env, callback, Object(), resourceName, maxQueueSize, + initialThreadCount, finalizeCallback); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, callback, Object(), resourceName, maxQueueSize, + initialThreadCount, finalizeCallback, data); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback) { + return New(env, callback, Object(), resourceName, maxQueueSize, + initialThreadCount, context, finalizeCallback); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, callback, Object(), resourceName, maxQueueSize, + initialThreadCount, context, finalizeCallback, data); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount) { + return New(env, callback, resource, resourceName, maxQueueSize, + initialThreadCount, static_cast(nullptr) /* context */); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + return New(env, callback, resource, resourceName, maxQueueSize, + initialThreadCount, context, + [](Env, ContextType*) {} /* empty finalizer */); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback) { + return New(env, callback, resource, resourceName, maxQueueSize, + initialThreadCount, static_cast(nullptr) /* context */, + finalizeCallback, static_cast(nullptr) /* data */, + details::ThreadSafeFinalize::Wrapper); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, callback, resource, resourceName, maxQueueSize, + initialThreadCount, static_cast(nullptr) /* context */, + finalizeCallback, data, + details::ThreadSafeFinalize< + void, Finalizer, FinalizerDataType>::FinalizeWrapperWithData); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback) { + return New(env, callback, resource, resourceName, maxQueueSize, + initialThreadCount, context, finalizeCallback, + static_cast(nullptr) /* data */, + details::ThreadSafeFinalize< + ContextType, Finalizer>::FinalizeWrapperWithContext); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, callback, resource, resourceName, maxQueueSize, + initialThreadCount, context, finalizeCallback, data, + details::ThreadSafeFinalize::FinalizeFinalizeWrapperWithDataAndContext); +} + +inline ThreadSafeFunction::ThreadSafeFunction() + : _tsfn() { +} + +inline ThreadSafeFunction::ThreadSafeFunction( + napi_threadsafe_function tsfn) + : _tsfn(tsfn) { +} + +inline ThreadSafeFunction::operator napi_threadsafe_function() const { + return _tsfn; +} + +inline napi_status ThreadSafeFunction::BlockingCall() const { + return CallInternal(nullptr, napi_tsfn_blocking); +} + +template <> +inline napi_status ThreadSafeFunction::BlockingCall( + void* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking); +} + +template +inline napi_status ThreadSafeFunction::BlockingCall( + Callback callback) const { + return CallInternal(new CallbackWrapper(callback), napi_tsfn_blocking); +} + +template +inline napi_status ThreadSafeFunction::BlockingCall( + DataType* data, Callback callback) const { + auto wrapper = [data, callback](Env env, Function jsCallback) { + callback(env, jsCallback, data); + }; + return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_blocking); +} + +inline napi_status ThreadSafeFunction::NonBlockingCall() const { + return CallInternal(nullptr, napi_tsfn_nonblocking); +} + +template <> +inline napi_status ThreadSafeFunction::NonBlockingCall( + void* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking); +} + +template +inline napi_status ThreadSafeFunction::NonBlockingCall( + Callback callback) const { + return CallInternal(new CallbackWrapper(callback), napi_tsfn_nonblocking); +} + +template +inline napi_status ThreadSafeFunction::NonBlockingCall( + DataType* data, Callback callback) const { + auto wrapper = [data, callback](Env env, Function jsCallback) { + callback(env, jsCallback, data); + }; + return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_nonblocking); +} + +inline void ThreadSafeFunction::Ref(napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_ref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +inline void ThreadSafeFunction::Unref(napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_unref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +inline napi_status ThreadSafeFunction::Acquire() const { + return napi_acquire_threadsafe_function(_tsfn); +} + +inline napi_status ThreadSafeFunction::Release() { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_release); +} + +inline napi_status ThreadSafeFunction::Abort() { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort); +} + +inline ThreadSafeFunction::ConvertibleContext +ThreadSafeFunction::GetContext() const { + void* context; + napi_status status = napi_get_threadsafe_function_context(_tsfn, &context); + NAPI_FATAL_IF_FAILED(status, "ThreadSafeFunction::GetContext", "napi_get_threadsafe_function_context"); + return ConvertibleContext({ context }); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data, + napi_finalize wrapper) { + static_assert(details::can_make_string::value + || std::is_convertible::value, + "Resource name should be convertible to the string type"); + + ThreadSafeFunction tsfn; + auto* finalizeData = new details::ThreadSafeFinalize({ data, finalizeCallback }); + napi_status status = napi_create_threadsafe_function(env, callback, resource, + Value::From(env, resourceName), maxQueueSize, initialThreadCount, + finalizeData, wrapper, context, CallJS, &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, ThreadSafeFunction()); + } + + return tsfn; +} + +inline napi_status ThreadSafeFunction::CallInternal( + CallbackWrapper* callbackWrapper, + napi_threadsafe_function_call_mode mode) const { + napi_status status = napi_call_threadsafe_function( + _tsfn, callbackWrapper, mode); + if (status != napi_ok && callbackWrapper != nullptr) { + delete callbackWrapper; + } + + return status; +} + +// static +inline void ThreadSafeFunction::CallJS(napi_env env, + napi_value jsCallback, + void* /* context */, + void* data) { + if (env == nullptr && jsCallback == nullptr) { + return; + } + + if (data != nullptr) { + auto* callbackWrapper = static_cast(data); + (*callbackWrapper)(env, Function(env, jsCallback)); + delete callbackWrapper; + } else if (jsCallback != nullptr) { + Function(env, jsCallback).Call({}); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Async Progress Worker Base class +//////////////////////////////////////////////////////////////////////////////// +template +inline AsyncProgressWorkerBase::AsyncProgressWorkerBase(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource, + size_t queue_size) + : AsyncWorker(receiver, callback, resource_name, resource) { + // Fill all possible arguments to work around ambiguous ThreadSafeFunction::New signatures. + _tsfn = ThreadSafeFunction::New(callback.Env(), + callback, + resource, + resource_name, + queue_size, + /** initialThreadCount */ 1, + /** context */ this, + OnThreadSafeFunctionFinalize, + /** finalizeData */ this); +} + +#if NAPI_VERSION > 4 +template +inline AsyncProgressWorkerBase::AsyncProgressWorkerBase(Napi::Env env, + const char* resource_name, + const Object& resource, + size_t queue_size) + : AsyncWorker(env, resource_name, resource) { + // TODO: Once the changes to make the callback optional for threadsafe + // functions are available on all versions we can remove the dummy Function here. + Function callback; + // Fill all possible arguments to work around ambiguous ThreadSafeFunction::New signatures. + _tsfn = ThreadSafeFunction::New(env, + callback, + resource, + resource_name, + queue_size, + /** initialThreadCount */ 1, + /** context */ this, + OnThreadSafeFunctionFinalize, + /** finalizeData */ this); +} +#endif + +template +inline AsyncProgressWorkerBase::~AsyncProgressWorkerBase() { + // Abort pending tsfn call. + // Don't send progress events after we've already completed. + // It's ok to call ThreadSafeFunction::Abort and ThreadSafeFunction::Release duplicated. + _tsfn.Abort(); +} + +template +inline void AsyncProgressWorkerBase::OnAsyncWorkProgress(Napi::Env /* env */, + Napi::Function /* jsCallback */, + void* data) { + ThreadSafeData* tsd = static_cast(data); + tsd->asyncprogressworker()->OnWorkProgress(tsd->data()); + delete tsd; +} + +template +inline napi_status AsyncProgressWorkerBase::NonBlockingCall(DataType* data) { + auto tsd = new AsyncProgressWorkerBase::ThreadSafeData(this, data); + return _tsfn.NonBlockingCall(tsd, OnAsyncWorkProgress); +} + +template +inline void AsyncProgressWorkerBase::OnWorkComplete(Napi::Env /* env */, napi_status status) { + _work_completed = true; + _complete_status = status; + _tsfn.Release(); +} + +template +inline void AsyncProgressWorkerBase::OnThreadSafeFunctionFinalize(Napi::Env env, void* /* data */, AsyncProgressWorkerBase* context) { + if (context->_work_completed) { + context->AsyncWorker::OnWorkComplete(env, context->_complete_status); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Async Progress Worker class +//////////////////////////////////////////////////////////////////////////////// +template +inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback) + : AsyncProgressWorker(callback, "generic") { +} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback, + const char* resource_name) + : AsyncProgressWorker(callback, resource_name, Object::New(callback.Env())) { +} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncProgressWorker(Object::New(callback.Env()), + callback, + resource_name, + resource) { +} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, + const Function& callback) + : AsyncProgressWorker(receiver, callback, "generic") { +} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name) + : AsyncProgressWorker(receiver, + callback, + resource_name, + Object::New(callback.Env())) { +} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncProgressWorkerBase(receiver, callback, resource_name, resource), + _asyncdata(nullptr), + _asyncsize(0) { +} + +#if NAPI_VERSION > 4 +template +inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env) + : AsyncProgressWorker(env, "generic") { +} + +template +inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env, + const char* resource_name) + : AsyncProgressWorker(env, resource_name, Object::New(env)) { +} + +template +inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env, + const char* resource_name, + const Object& resource) + : AsyncProgressWorkerBase(env, resource_name, resource), + _asyncdata(nullptr), + _asyncsize(0) { +} +#endif + +template +inline AsyncProgressWorker::~AsyncProgressWorker() { + { + std::lock_guard lock(this->_mutex); + _asyncdata = nullptr; + _asyncsize = 0; + } +} + +template +inline void AsyncProgressWorker::Execute() { + ExecutionProgress progress(this); + Execute(progress); +} + +template +inline void AsyncProgressWorker::OnWorkProgress(void*) { + T* data; + size_t size; + { + std::lock_guard lock(this->_mutex); + data = this->_asyncdata; + size = this->_asyncsize; + this->_asyncdata = nullptr; + this->_asyncsize = 0; + } + + /** + * The callback of ThreadSafeFunction is not been invoked immediately on the + * callback of uv_async_t (uv io poll), rather the callback of TSFN is + * invoked on the right next uv idle callback. There are chances that during + * the deferring the signal of uv_async_t is been sent again, i.e. potential + * not coalesced two calls of the TSFN callback. + */ + if (data == nullptr) { + return; + } + + this->OnProgress(data, size); + delete[] data; +} + +template +inline void AsyncProgressWorker::SendProgress_(const T* data, size_t count) { + T* new_data = new T[count]; + std::copy(data, data + count, new_data); + + T* old_data; + { + std::lock_guard lock(this->_mutex); + old_data = _asyncdata; + _asyncdata = new_data; + _asyncsize = count; + } + this->NonBlockingCall(nullptr); + + delete[] old_data; +} + +template +inline void AsyncProgressWorker::Signal() const { + this->NonBlockingCall(static_cast(nullptr)); +} + +template +inline void AsyncProgressWorker::ExecutionProgress::Signal() const { + _worker->Signal(); +} + +template +inline void AsyncProgressWorker::ExecutionProgress::Send(const T* data, size_t count) const { + _worker->SendProgress_(data, count); +} + +//////////////////////////////////////////////////////////////////////////////// +// Async Progress Queue Worker class +//////////////////////////////////////////////////////////////////////////////// +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Function& callback) + : AsyncProgressQueueWorker(callback, "generic") { +} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Function& callback, + const char* resource_name) + : AsyncProgressQueueWorker(callback, resource_name, Object::New(callback.Env())) { +} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncProgressQueueWorker(Object::New(callback.Env()), + callback, + resource_name, + resource) { +} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Object& receiver, + const Function& callback) + : AsyncProgressQueueWorker(receiver, callback, "generic") { +} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Object& receiver, + const Function& callback, + const char* resource_name) + : AsyncProgressQueueWorker(receiver, + callback, + resource_name, + Object::New(callback.Env())) { +} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncProgressWorkerBase>(receiver, callback, resource_name, resource, /** unlimited queue size */0) { +} + +#if NAPI_VERSION > 4 +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(Napi::Env env) + : AsyncProgressQueueWorker(env, "generic") { +} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(Napi::Env env, + const char* resource_name) + : AsyncProgressQueueWorker(env, resource_name, Object::New(env)) { +} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(Napi::Env env, + const char* resource_name, + const Object& resource) + : AsyncProgressWorkerBase>(env, resource_name, resource, /** unlimited queue size */0) { +} +#endif + +template +inline void AsyncProgressQueueWorker::Execute() { + ExecutionProgress progress(this); + Execute(progress); +} + +template +inline void AsyncProgressQueueWorker::OnWorkProgress(std::pair* datapair) { + if (datapair == nullptr) { + return; + } + + T *data = datapair->first; + size_t size = datapair->second; + + this->OnProgress(data, size); + delete datapair; + delete[] data; +} + +template +inline void AsyncProgressQueueWorker::SendProgress_(const T* data, size_t count) { + T* new_data = new T[count]; + std::copy(data, data + count, new_data); + + auto pair = new std::pair(new_data, count); + this->NonBlockingCall(pair); +} + +template +inline void AsyncProgressQueueWorker::Signal() const { + this->NonBlockingCall(nullptr); +} + +template +inline void AsyncProgressQueueWorker::OnWorkComplete(Napi::Env env, napi_status status) { + // Draining queued items in TSFN. + AsyncProgressWorkerBase>::OnWorkComplete(env, status); +} + +template +inline void AsyncProgressQueueWorker::ExecutionProgress::Signal() const { + _worker->Signal(); +} + +template +inline void AsyncProgressQueueWorker::ExecutionProgress::Send(const T* data, size_t count) const { + _worker->SendProgress_(data, count); +} +#endif // NAPI_VERSION > 3 && !defined(__wasm32__) + +//////////////////////////////////////////////////////////////////////////////// +// Memory Management class +//////////////////////////////////////////////////////////////////////////////// + +inline int64_t MemoryManagement::AdjustExternalMemory(Env env, int64_t change_in_bytes) { + int64_t result; + napi_status status = napi_adjust_external_memory(env, change_in_bytes, &result); + NAPI_THROW_IF_FAILED(env, status, 0); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// Version Management class +//////////////////////////////////////////////////////////////////////////////// + +inline uint32_t VersionManagement::GetNapiVersion(Env env) { + uint32_t result; + napi_status status = napi_get_version(env, &result); + NAPI_THROW_IF_FAILED(env, status, 0); + return result; +} + +inline const napi_node_version* VersionManagement::GetNodeVersion(Env env) { + const napi_node_version* result; + napi_status status = napi_get_node_version(env, &result); + NAPI_THROW_IF_FAILED(env, status, 0); + return result; +} + +#if NAPI_VERSION > 5 +//////////////////////////////////////////////////////////////////////////////// +// Addon class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Object Addon::Init(Env env, Object exports) { + T* addon = new T(env, exports); + env.SetInstanceData(addon); + return addon->entry_point_; +} + +template +inline T* Addon::Unwrap(Object wrapper) { + return wrapper.Env().GetInstanceData(); +} + +template +inline void +Addon::DefineAddon(Object exports, + const std::initializer_list& props) { + DefineProperties(exports, props); + entry_point_ = exports; +} + +template +inline Napi::Object +Addon::DefineProperties(Object object, + const std::initializer_list& props) { + const napi_property_descriptor* properties = + reinterpret_cast(props.begin()); + size_t size = props.size(); + napi_status status = napi_define_properties(object.Env(), + object, + size, + properties); + NAPI_THROW_IF_FAILED(object.Env(), status, object); + for (size_t idx = 0; idx < size; idx++) + T::AttachPropData(object.Env(), object, &properties[idx]); + return object; +} +#endif // NAPI_VERSION > 5 + +} // namespace Napi + +#endif // SRC_NAPI_INL_H_ diff --git a/node_modules/node-addon-api/napi.h b/node_modules/node-addon-api/napi.h new file mode 100644 index 0000000..7dc9b17 --- /dev/null +++ b/node_modules/node-addon-api/napi.h @@ -0,0 +1,2727 @@ +#ifndef SRC_NAPI_H_ +#define SRC_NAPI_H_ + +#include +#include +#include +#include +#include +#include +#include + +// VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known good version) +#if !defined(_MSC_VER) || _MSC_FULL_VER >= 190024210 +#define NAPI_HAS_CONSTEXPR 1 +#endif + +// VS2013 does not support char16_t literal strings, so we'll work around it using wchar_t strings +// and casting them. This is safe as long as the character sizes are the same. +#if defined(_MSC_VER) && _MSC_VER <= 1800 +static_assert(sizeof(char16_t) == sizeof(wchar_t), "Size mismatch between char16_t and wchar_t"); +#define NAPI_WIDE_TEXT(x) reinterpret_cast(L ## x) +#else +#define NAPI_WIDE_TEXT(x) u ## x +#endif + +// If C++ exceptions are not explicitly enabled or disabled, enable them +// if exceptions were enabled in the compiler settings. +#if !defined(NAPI_CPP_EXCEPTIONS) && !defined(NAPI_DISABLE_CPP_EXCEPTIONS) + #if defined(_CPPUNWIND) || defined (__EXCEPTIONS) + #define NAPI_CPP_EXCEPTIONS + #else + #error Exception support not detected. \ + Define either NAPI_CPP_EXCEPTIONS or NAPI_DISABLE_CPP_EXCEPTIONS. + #endif +#endif + +#ifdef _NOEXCEPT + #define NAPI_NOEXCEPT _NOEXCEPT +#else + #define NAPI_NOEXCEPT noexcept +#endif + +#ifdef NAPI_CPP_EXCEPTIONS + +// When C++ exceptions are enabled, Errors are thrown directly. There is no need +// to return anything after the throw statements. The variadic parameter is an +// optional return value that is ignored. +// We need _VOID versions of the macros to avoid warnings resulting from +// leaving the NAPI_THROW_* `...` argument empty. + +#define NAPI_THROW(e, ...) throw e +#define NAPI_THROW_VOID(e) throw e + +#define NAPI_THROW_IF_FAILED(env, status, ...) \ + if ((status) != napi_ok) throw Napi::Error::New(env); + +#define NAPI_THROW_IF_FAILED_VOID(env, status) \ + if ((status) != napi_ok) throw Napi::Error::New(env); + +#else // NAPI_CPP_EXCEPTIONS + +// When C++ exceptions are disabled, Errors are thrown as JavaScript exceptions, +// which are pending until the callback returns to JS. The variadic parameter +// is an optional return value; usually it is an empty result. +// We need _VOID versions of the macros to avoid warnings resulting from +// leaving the NAPI_THROW_* `...` argument empty. + +#define NAPI_THROW(e, ...) \ + do { \ + (e).ThrowAsJavaScriptException(); \ + return __VA_ARGS__; \ + } while (0) + +#define NAPI_THROW_VOID(e) \ + do { \ + (e).ThrowAsJavaScriptException(); \ + return; \ + } while (0) + +#define NAPI_THROW_IF_FAILED(env, status, ...) \ + if ((status) != napi_ok) { \ + Napi::Error::New(env).ThrowAsJavaScriptException(); \ + return __VA_ARGS__; \ + } + +#define NAPI_THROW_IF_FAILED_VOID(env, status) \ + if ((status) != napi_ok) { \ + Napi::Error::New(env).ThrowAsJavaScriptException(); \ + return; \ + } + +#endif // NAPI_CPP_EXCEPTIONS + +# define NAPI_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete; +# define NAPI_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete; + +#define NAPI_DISALLOW_ASSIGN_COPY(CLASS) \ + NAPI_DISALLOW_ASSIGN(CLASS) \ + NAPI_DISALLOW_COPY(CLASS) + +#define NAPI_FATAL_IF_FAILED(status, location, message) \ + do { \ + if ((status) != napi_ok) { \ + Napi::Error::Fatal((location), (message)); \ + } \ + } while (0) + +//////////////////////////////////////////////////////////////////////////////// +/// Node-API C++ Wrapper Classes +/// +/// These classes wrap the "Node-API" ABI-stable C APIs for Node.js, providing a +/// C++ object model and C++ exception-handling semantics with low overhead. +/// The wrappers are all header-only so that they do not affect the ABI. +//////////////////////////////////////////////////////////////////////////////// +namespace Napi { + + // Forward declarations + class Env; + class Value; + class Boolean; + class Number; +#if NAPI_VERSION > 5 + class BigInt; +#endif // NAPI_VERSION > 5 +#if (NAPI_VERSION > 4) + class Date; +#endif + class String; + class Object; + class Array; + class ArrayBuffer; + class Function; + class Error; + class PropertyDescriptor; + class CallbackInfo; + class TypedArray; + template class TypedArrayOf; + + using Int8Array = + TypedArrayOf; ///< Typed-array of signed 8-bit integers + using Uint8Array = + TypedArrayOf; ///< Typed-array of unsigned 8-bit integers + using Int16Array = + TypedArrayOf; ///< Typed-array of signed 16-bit integers + using Uint16Array = + TypedArrayOf; ///< Typed-array of unsigned 16-bit integers + using Int32Array = + TypedArrayOf; ///< Typed-array of signed 32-bit integers + using Uint32Array = + TypedArrayOf; ///< Typed-array of unsigned 32-bit integers + using Float32Array = + TypedArrayOf; ///< Typed-array of 32-bit floating-point values + using Float64Array = + TypedArrayOf; ///< Typed-array of 64-bit floating-point values +#if NAPI_VERSION > 5 + using BigInt64Array = + TypedArrayOf; ///< Typed array of signed 64-bit integers + using BigUint64Array = + TypedArrayOf; ///< Typed array of unsigned 64-bit integers +#endif // NAPI_VERSION > 5 + + /// Defines the signature of a Node-API C++ module's registration callback + /// (init) function. + using ModuleRegisterCallback = Object (*)(Env env, Object exports); + + class MemoryManagement; + + /// Environment for Node-API values and operations. + /// + /// All Node-API values and operations must be associated with an environment. + /// An environment instance is always provided to callback functions; that + /// environment must then be used for any creation of Node-API values or other + /// Node-API operations within the callback. (Many methods infer the + /// environment from the `this` instance that the method is called on.) + /// + /// In the future, multiple environments per process may be supported, + /// although current implementations only support one environment per process. + /// + /// In the V8 JavaScript engine, a Node-API environment approximately + /// corresponds to an Isolate. + class Env { +#if NAPI_VERSION > 5 + private: + template static void DefaultFini(Env, T* data); + template + static void DefaultFiniWithHint(Env, DataType* data, HintType* hint); +#endif // NAPI_VERSION > 5 + public: + Env(napi_env env); + + operator napi_env() const; + + Object Global() const; + Value Undefined() const; + Value Null() const; + + bool IsExceptionPending() const; + Error GetAndClearPendingException(); + + Value RunScript(const char* utf8script); + Value RunScript(const std::string& utf8script); + Value RunScript(String script); + +#if NAPI_VERSION > 5 + template T* GetInstanceData(); + + template using Finalizer = void (*)(Env, T*); + template fini = Env::DefaultFini> + void SetInstanceData(T* data); + + template + using FinalizerWithHint = void (*)(Env, DataType*, HintType*); + template fini = + Env::DefaultFiniWithHint> + void SetInstanceData(DataType* data, HintType* hint); +#endif // NAPI_VERSION > 5 + + private: + napi_env _env; + }; + + /// A JavaScript value of unknown type. + /// + /// For type-specific operations, convert to one of the Value subclasses using a `To*` or `As()` + /// method. The `To*` methods do type coercion; the `As()` method does not. + /// + /// Napi::Value value = ... + /// if (!value.IsString()) throw Napi::TypeError::New(env, "Invalid arg..."); + /// Napi::String str = value.As(); // Cast to a string value + /// + /// Napi::Value anotherValue = ... + /// bool isTruthy = anotherValue.ToBoolean(); // Coerce to a boolean value + class Value { + public: + Value(); ///< Creates a new _empty_ Value instance. + Value(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + /// Creates a JS value from a C++ primitive. + /// + /// `value` may be any of: + /// - bool + /// - Any integer type + /// - Any floating point type + /// - const char* (encoded using UTF-8, null-terminated) + /// - const char16_t* (encoded using UTF-16-LE, null-terminated) + /// - std::string (encoded using UTF-8) + /// - std::u16string + /// - napi::Value + /// - napi_value + template + static Value From(napi_env env, const T& value); + + /// Converts to a Node-API value primitive. + /// + /// If the instance is _empty_, this returns `nullptr`. + operator napi_value() const; + + /// Tests if this value strictly equals another value. + bool operator ==(const Value& other) const; + + /// Tests if this value does not strictly equal another value. + bool operator !=(const Value& other) const; + + /// Tests if this value strictly equals another value. + bool StrictEquals(const Value& other) const; + + /// Gets the environment the value is associated with. + Napi::Env Env() const; + + /// Checks if the value is empty (uninitialized). + /// + /// An empty value is invalid, and most attempts to perform an operation on an empty value + /// will result in an exception. Note an empty value is distinct from JavaScript `null` or + /// `undefined`, which are valid values. + /// + /// When C++ exceptions are disabled at compile time, a method with a `Value` return type may + /// return an empty value to indicate a pending exception. So when not using C++ exceptions, + /// callers should check whether the value is empty before attempting to use it. + bool IsEmpty() const; + + napi_valuetype Type() const; ///< Gets the type of the value. + + bool IsUndefined() const; ///< Tests if a value is an undefined JavaScript value. + bool IsNull() const; ///< Tests if a value is a null JavaScript value. + bool IsBoolean() const; ///< Tests if a value is a JavaScript boolean. + bool IsNumber() const; ///< Tests if a value is a JavaScript number. +#if NAPI_VERSION > 5 + bool IsBigInt() const; ///< Tests if a value is a JavaScript bigint. +#endif // NAPI_VERSION > 5 +#if (NAPI_VERSION > 4) + bool IsDate() const; ///< Tests if a value is a JavaScript date. +#endif + bool IsString() const; ///< Tests if a value is a JavaScript string. + bool IsSymbol() const; ///< Tests if a value is a JavaScript symbol. + bool IsArray() const; ///< Tests if a value is a JavaScript array. + bool IsArrayBuffer() const; ///< Tests if a value is a JavaScript array buffer. + bool IsTypedArray() const; ///< Tests if a value is a JavaScript typed array. + bool IsObject() const; ///< Tests if a value is a JavaScript object. + bool IsFunction() const; ///< Tests if a value is a JavaScript function. + bool IsPromise() const; ///< Tests if a value is a JavaScript promise. + bool IsDataView() const; ///< Tests if a value is a JavaScript data view. + bool IsBuffer() const; ///< Tests if a value is a Node buffer. + bool IsExternal() const; ///< Tests if a value is a pointer to external data. + + /// Casts to another type of `Napi::Value`, when the actual type is known or assumed. + /// + /// This conversion does NOT coerce the type. Calling any methods inappropriate for the actual + /// value type will throw `Napi::Error`. + template T As() const; + + Boolean ToBoolean() const; ///< Coerces a value to a JavaScript boolean. + Number ToNumber() const; ///< Coerces a value to a JavaScript number. + String ToString() const; ///< Coerces a value to a JavaScript string. + Object ToObject() const; ///< Coerces a value to a JavaScript object. + + protected: + /// !cond INTERNAL + napi_env _env; + napi_value _value; + /// !endcond + }; + + /// A JavaScript boolean value. + class Boolean : public Value { + public: + static Boolean New(napi_env env, ///< Node-API environment + bool value ///< Boolean value + ); + + Boolean(); ///< Creates a new _empty_ Boolean instance. + Boolean(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + operator bool() const; ///< Converts a Boolean value to a boolean primitive. + bool Value() const; ///< Converts a Boolean value to a boolean primitive. + }; + + /// A JavaScript number value. + class Number : public Value { + public: + static Number New(napi_env env, ///< Node-API environment + double value ///< Number value + ); + + Number(); ///< Creates a new _empty_ Number instance. + Number(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + operator int32_t() + const; ///< Converts a Number value to a 32-bit signed integer value. + operator uint32_t() + const; ///< Converts a Number value to a 32-bit unsigned integer value. + operator int64_t() + const; ///< Converts a Number value to a 64-bit signed integer value. + operator float() + const; ///< Converts a Number value to a 32-bit floating-point value. + operator double() + const; ///< Converts a Number value to a 64-bit floating-point value. + + int32_t Int32Value() + const; ///< Converts a Number value to a 32-bit signed integer value. + uint32_t Uint32Value() + const; ///< Converts a Number value to a 32-bit unsigned integer value. + int64_t Int64Value() + const; ///< Converts a Number value to a 64-bit signed integer value. + float FloatValue() + const; ///< Converts a Number value to a 32-bit floating-point value. + double DoubleValue() + const; ///< Converts a Number value to a 64-bit floating-point value. + }; + +#if NAPI_VERSION > 5 + /// A JavaScript bigint value. + class BigInt : public Value { + public: + static BigInt New(napi_env env, ///< Node-API environment + int64_t value ///< Number value + ); + static BigInt New(napi_env env, ///< Node-API environment + uint64_t value ///< Number value + ); + + /// Creates a new BigInt object using a specified sign bit and a + /// specified list of digits/words. + /// The resulting number is calculated as: + /// (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...) + static BigInt New(napi_env env, ///< Node-API environment + int sign_bit, ///< Sign bit. 1 if negative. + size_t word_count, ///< Number of words in array + const uint64_t* words ///< Array of words + ); + + BigInt(); ///< Creates a new _empty_ BigInt instance. + BigInt(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + int64_t Int64Value(bool* lossless) + const; ///< Converts a BigInt value to a 64-bit signed integer value. + uint64_t Uint64Value(bool* lossless) + const; ///< Converts a BigInt value to a 64-bit unsigned integer value. + + size_t WordCount() const; ///< The number of 64-bit words needed to store + ///< the result of ToWords(). + + /// Writes the contents of this BigInt to a specified memory location. + /// `sign_bit` must be provided and will be set to 1 if this BigInt is + /// negative. + /// `*word_count` has to be initialized to the length of the `words` array. + /// Upon return, it will be set to the actual number of words that would + /// be needed to store this BigInt (i.e. the return value of `WordCount()`). + void ToWords(int* sign_bit, size_t* word_count, uint64_t* words); + }; +#endif // NAPI_VERSION > 5 + +#if (NAPI_VERSION > 4) + /// A JavaScript date value. + class Date : public Value { + public: + /// Creates a new Date value from a double primitive. + static Date New(napi_env env, ///< Node-API environment + double value ///< Number value + ); + + Date(); ///< Creates a new _empty_ Date instance. + Date(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. + operator double() const; ///< Converts a Date value to double primitive + + double ValueOf() const; ///< Converts a Date value to a double primitive. + }; + #endif + + /// A JavaScript string or symbol value (that can be used as a property name). + class Name : public Value { + public: + Name(); ///< Creates a new _empty_ Name instance. + Name(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + }; + + /// A JavaScript string value. + class String : public Name { + public: + /// Creates a new String value from a UTF-8 encoded C++ string. + static String New(napi_env env, ///< Node-API environment + const std::string& value ///< UTF-8 encoded C++ string + ); + + /// Creates a new String value from a UTF-16 encoded C++ string. + static String New(napi_env env, ///< Node-API environment + const std::u16string& value ///< UTF-16 encoded C++ string + ); + + /// Creates a new String value from a UTF-8 encoded C string. + static String New( + napi_env env, ///< Node-API environment + const char* value ///< UTF-8 encoded null-terminated C string + ); + + /// Creates a new String value from a UTF-16 encoded C string. + static String New( + napi_env env, ///< Node-API environment + const char16_t* value ///< UTF-16 encoded null-terminated C string + ); + + /// Creates a new String value from a UTF-8 encoded C string with specified + /// length. + static String New(napi_env env, ///< Node-API environment + const char* value, ///< UTF-8 encoded C string (not + ///< necessarily null-terminated) + size_t length ///< length of the string in bytes + ); + + /// Creates a new String value from a UTF-16 encoded C string with specified + /// length. + static String New( + napi_env env, ///< Node-API environment + const char16_t* value, ///< UTF-16 encoded C string (not necessarily + ///< null-terminated) + size_t length ///< Length of the string in 2-byte code units + ); + + /// Creates a new String based on the original object's type. + /// + /// `value` may be any of: + /// - const char* (encoded using UTF-8, null-terminated) + /// - const char16_t* (encoded using UTF-16-LE, null-terminated) + /// - std::string (encoded using UTF-8) + /// - std::u16string + template + static String From(napi_env env, const T& value); + + String(); ///< Creates a new _empty_ String instance. + String(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + operator std::string() + const; ///< Converts a String value to a UTF-8 encoded C++ string. + operator std::u16string() + const; ///< Converts a String value to a UTF-16 encoded C++ string. + std::string Utf8Value() + const; ///< Converts a String value to a UTF-8 encoded C++ string. + std::u16string Utf16Value() + const; ///< Converts a String value to a UTF-16 encoded C++ string. + }; + + /// A JavaScript symbol value. + class Symbol : public Name { + public: + /// Creates a new Symbol value with an optional description. + static Symbol New( + napi_env env, ///< Node-API environment + const char* description = + nullptr ///< Optional UTF-8 encoded null-terminated C string + /// describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< Node-API environment + const std::string& + description ///< UTF-8 encoded C++ string describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New(napi_env env, ///< Node-API environment + String description ///< String value describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< Node-API environment + napi_value description ///< String value describing the symbol + ); + + /// Get a public Symbol (e.g. Symbol.iterator). + static Symbol WellKnown(napi_env, const std::string& name); + + Symbol(); ///< Creates a new _empty_ Symbol instance. + Symbol(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + }; + + /// A JavaScript object value. + class Object : public Value { + public: + /// Enables property and element assignments using indexing syntax. + /// + /// Example: + /// + /// Napi::Value propertyValue = object1['A']; + /// object2['A'] = propertyValue; + /// Napi::Value elementValue = array[0]; + /// array[1] = elementValue; + template + class PropertyLValue { + public: + /// Converts an L-value to a value. + operator Value() const; + + /// Assigns a value to the property. The type of value can be + /// anything supported by `Object::Set`. + template + PropertyLValue& operator =(ValueType value); + + private: + PropertyLValue() = delete; + PropertyLValue(Object object, Key key); + napi_env _env; + napi_value _object; + Key _key; + + friend class Napi::Object; + }; + + /// Creates a new Object value. + static Object New(napi_env env ///< Node-API environment + ); + + Object(); ///< Creates a new _empty_ Object instance. + Object(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + /// Gets or sets a named property. + PropertyLValue operator []( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ); + + /// Gets or sets a named property. + PropertyLValue operator []( + const std::string& utf8name ///< UTF-8 encoded property name + ); + + /// Gets or sets an indexed property or array element. + PropertyLValue operator []( + uint32_t index /// Property / element index + ); + + /// Gets a named property. + Value operator []( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Gets a named property. + Value operator []( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Gets an indexed property or array element. + Value operator []( + uint32_t index ///< Property / element index + ) const; + + /// Checks whether a property is present. + bool Has( + napi_value key ///< Property key primitive + ) const; + + /// Checks whether a property is present. + bool Has( + Value key ///< Property key + ) const; + + /// Checks whether a named property is present. + bool Has( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Checks whether a named property is present. + bool Has( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Checks whether a own property is present. + bool HasOwnProperty( + napi_value key ///< Property key primitive + ) const; + + /// Checks whether a own property is present. + bool HasOwnProperty( + Value key ///< Property key + ) const; + + /// Checks whether a own property is present. + bool HasOwnProperty( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Checks whether a own property is present. + bool HasOwnProperty( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Gets a property. + Value Get( + napi_value key ///< Property key primitive + ) const; + + /// Gets a property. + Value Get( + Value key ///< Property key + ) const; + + /// Gets a named property. + Value Get( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Gets a named property. + Value Get( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Sets a property. + template + bool Set(napi_value key, ///< Property key primitive + const ValueType& value ///< Property value primitive + ); + + /// Sets a property. + template + bool Set(Value key, ///< Property key + const ValueType& value ///< Property value + ); + + /// Sets a named property. + template + bool Set( + const char* utf8name, ///< UTF-8 encoded null-terminated property name + const ValueType& value); + + /// Sets a named property. + template + bool Set(const std::string& utf8name, ///< UTF-8 encoded property name + const ValueType& value ///< Property value primitive + ); + + /// Delete property. + bool Delete( + napi_value key ///< Property key primitive + ); + + /// Delete property. + bool Delete( + Value key ///< Property key + ); + + /// Delete property. + bool Delete( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ); + + /// Delete property. + bool Delete( + const std::string& utf8name ///< UTF-8 encoded property name + ); + + /// Checks whether an indexed property is present. + bool Has( + uint32_t index ///< Property / element index + ) const; + + /// Gets an indexed property or array element. + Value Get( + uint32_t index ///< Property / element index + ) const; + + /// Sets an indexed property or array element. + template + bool Set(uint32_t index, ///< Property / element index + const ValueType& value ///< Property value primitive + ); + + /// Deletes an indexed property or array element. + bool Delete( + uint32_t index ///< Property / element index + ); + + Array GetPropertyNames() const; ///< Get all property names + + /// Defines a property on the object. + bool DefineProperty( + const PropertyDescriptor& + property ///< Descriptor for the property to be defined + ); + + /// Defines properties on the object. + bool DefineProperties( + const std::initializer_list& properties + ///< List of descriptors for the properties to be defined + ); + + /// Defines properties on the object. + bool DefineProperties( + const std::vector& properties + ///< Vector of descriptors for the properties to be defined + ); + + /// Checks if an object is an instance created by a constructor function. + /// + /// This is equivalent to the JavaScript `instanceof` operator. + bool InstanceOf( + const Function& constructor ///< Constructor function + ) const; + + template + inline void AddFinalizer(Finalizer finalizeCallback, T* data); + + template + inline void AddFinalizer(Finalizer finalizeCallback, + T* data, + Hint* finalizeHint); +#if NAPI_VERSION >= 8 + bool Freeze(); + bool Seal(); +#endif // NAPI_VERSION >= 8 + }; + + template + class External : public Value { + public: + static External New(napi_env env, T* data); + + // Finalizer must implement `void operator()(Env env, T* data)`. + template + static External New(napi_env env, + T* data, + Finalizer finalizeCallback); + // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + template + static External New(napi_env env, + T* data, + Finalizer finalizeCallback, + Hint* finalizeHint); + + External(); + External(napi_env env, napi_value value); + + T* Data() const; + }; + + class Array : public Object { + public: + static Array New(napi_env env); + static Array New(napi_env env, size_t length); + + Array(); + Array(napi_env env, napi_value value); + + uint32_t Length() const; + }; + + /// A JavaScript array buffer value. + class ArrayBuffer : public Object { + public: + /// Creates a new ArrayBuffer instance over a new automatically-allocated buffer. + static ArrayBuffer New( + napi_env env, ///< Node-API environment + size_t byteLength ///< Length of the buffer to be allocated, in bytes + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength ///< Length of the external buffer to be used by the + ///< array, in bytes + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + template + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength, ///< Length of the external buffer to be used by the + ///< array, + /// in bytes + Finalizer finalizeCallback ///< Function to be called when the array + ///< buffer is destroyed; + /// must implement `void operator()(Env env, + /// void* externalData)` + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + template + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength, ///< Length of the external buffer to be used by the + ///< array, + /// in bytes + Finalizer finalizeCallback, ///< Function to be called when the array + ///< buffer is destroyed; + /// must implement `void operator()(Env + /// env, void* externalData, Hint* hint)` + Hint* finalizeHint ///< Hint (second parameter) to be passed to the + ///< finalize callback + ); + + ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance. + ArrayBuffer(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + void* Data(); ///< Gets a pointer to the data buffer. + size_t ByteLength(); ///< Gets the length of the array buffer in bytes. + +#if NAPI_VERSION >= 7 + bool IsDetached() const; + void Detach(); +#endif // NAPI_VERSION >= 7 + }; + + /// A JavaScript typed-array value with unknown array type. + /// + /// For type-specific operations, cast to a `TypedArrayOf` instance using the `As()` + /// method: + /// + /// Napi::TypedArray array = ... + /// if (t.TypedArrayType() == napi_int32_array) { + /// Napi::Int32Array int32Array = t.As(); + /// } + class TypedArray : public Object { + public: + TypedArray(); ///< Creates a new _empty_ TypedArray instance. + TypedArray(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + napi_typedarray_type TypedArrayType() const; ///< Gets the type of this typed-array. + Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. + + uint8_t ElementSize() const; ///< Gets the size in bytes of one element in the array. + size_t ElementLength() const; ///< Gets the number of elements in the array. + size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts. + size_t ByteLength() const; ///< Gets the length of the array in bytes. + + protected: + /// !cond INTERNAL + napi_typedarray_type _type; + size_t _length; + + TypedArray(napi_env env, napi_value value, napi_typedarray_type type, size_t length); + + static const napi_typedarray_type unknown_array_type = static_cast(-1); + + template + static +#if defined(NAPI_HAS_CONSTEXPR) + constexpr +#endif + napi_typedarray_type TypedArrayTypeForPrimitiveType() { + return std::is_same::value ? napi_int8_array + : std::is_same::value ? napi_uint8_array + : std::is_same::value ? napi_int16_array + : std::is_same::value ? napi_uint16_array + : std::is_same::value ? napi_int32_array + : std::is_same::value ? napi_uint32_array + : std::is_same::value ? napi_float32_array + : std::is_same::value ? napi_float64_array +#if NAPI_VERSION > 5 + : std::is_same::value ? napi_bigint64_array + : std::is_same::value ? napi_biguint64_array +#endif // NAPI_VERSION > 5 + : unknown_array_type; + } + /// !endcond + }; + + /// A JavaScript typed-array value with known array type. + /// + /// Note while it is possible to create and access Uint8 "clamped" arrays using this class, + /// the _clamping_ behavior is only applied in JavaScript. + template + class TypedArrayOf : public TypedArray { + public: + /// Creates a new TypedArray instance over a new automatically-allocated array buffer. + /// + /// The array type parameter can normally be omitted (because it is inferred from the template + /// parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< Node-API environment + size_t elementLength, ///< Length of the created array, as a number of + ///< elements +#if defined(NAPI_HAS_CONSTEXPR) + napi_typedarray_type type = + TypedArray::TypedArrayTypeForPrimitiveType() +#else + napi_typedarray_type type +#endif + ///< Type of array, if different from the default array type for the + ///< template parameter T. + ); + + /// Creates a new TypedArray instance over a provided array buffer. + /// + /// The array type parameter can normally be omitted (because it is inferred from the template + /// parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< Node-API environment + size_t elementLength, ///< Length of the created array, as a number of + ///< elements + Napi::ArrayBuffer arrayBuffer, ///< Backing array buffer instance to use + size_t bufferOffset, ///< Offset into the array buffer where the + ///< typed-array starts +#if defined(NAPI_HAS_CONSTEXPR) + napi_typedarray_type type = + TypedArray::TypedArrayTypeForPrimitiveType() +#else + napi_typedarray_type type +#endif + ///< Type of array, if different from the default array type for the + ///< template parameter T. + ); + + TypedArrayOf(); ///< Creates a new _empty_ TypedArrayOf instance. + TypedArrayOf(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + T& operator [](size_t index); ///< Gets or sets an element in the array. + const T& operator [](size_t index) const; ///< Gets an element in the array. + + /// Gets a pointer to the array's backing buffer. + /// + /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, because the + /// typed-array may have a non-zero `ByteOffset()` into the `ArrayBuffer`. + T* Data(); + + /// Gets a pointer to the array's backing buffer. + /// + /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, because the + /// typed-array may have a non-zero `ByteOffset()` into the `ArrayBuffer`. + const T* Data() const; + + private: + T* _data; + + TypedArrayOf(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length, + T* data); + }; + + /// The DataView provides a low-level interface for reading/writing multiple + /// number types in an ArrayBuffer irrespective of the platform's endianness. + class DataView : public Object { + public: + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer); + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset); + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength); + + DataView(); ///< Creates a new _empty_ DataView instance. + DataView(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. + size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts. + size_t ByteLength() const; ///< Gets the length of the array in bytes. + + void* Data() const; + + float GetFloat32(size_t byteOffset) const; + double GetFloat64(size_t byteOffset) const; + int8_t GetInt8(size_t byteOffset) const; + int16_t GetInt16(size_t byteOffset) const; + int32_t GetInt32(size_t byteOffset) const; + uint8_t GetUint8(size_t byteOffset) const; + uint16_t GetUint16(size_t byteOffset) const; + uint32_t GetUint32(size_t byteOffset) const; + + void SetFloat32(size_t byteOffset, float value) const; + void SetFloat64(size_t byteOffset, double value) const; + void SetInt8(size_t byteOffset, int8_t value) const; + void SetInt16(size_t byteOffset, int16_t value) const; + void SetInt32(size_t byteOffset, int32_t value) const; + void SetUint8(size_t byteOffset, uint8_t value) const; + void SetUint16(size_t byteOffset, uint16_t value) const; + void SetUint32(size_t byteOffset, uint32_t value) const; + + private: + template + T ReadData(size_t byteOffset) const; + + template + void WriteData(size_t byteOffset, T value) const; + + void* _data; + size_t _length; + }; + + class Function : public Object { + public: + using VoidCallback = void (*)(const CallbackInfo& info); + using Callback = Value (*)(const CallbackInfo& info); + + template + static Function New(napi_env env, + const char* utf8name = nullptr, + void* data = nullptr); + + template + static Function New(napi_env env, + const char* utf8name = nullptr, + void* data = nullptr); + + template + static Function New(napi_env env, + const std::string& utf8name, + void* data = nullptr); + + template + static Function New(napi_env env, + const std::string& utf8name, + void* data = nullptr); + + /// Callable must implement operator() accepting a const CallbackInfo& + /// and return either void or Value. + template + static Function New(napi_env env, + Callable cb, + const char* utf8name = nullptr, + void* data = nullptr); + /// Callable must implement operator() accepting a const CallbackInfo& + /// and return either void or Value. + template + static Function New(napi_env env, + Callable cb, + const std::string& utf8name, + void* data = nullptr); + + Function(); + Function(napi_env env, napi_value value); + + Value operator()(const std::initializer_list& args) const; + + Value Call(const std::initializer_list& args) const; + Value Call(const std::vector& args) const; + Value Call(size_t argc, const napi_value* args) const; + Value Call(napi_value recv, + const std::initializer_list& args) const; + Value Call(napi_value recv, const std::vector& args) const; + Value Call(napi_value recv, size_t argc, const napi_value* args) const; + + Value MakeCallback(napi_value recv, + const std::initializer_list& args, + napi_async_context context = nullptr) const; + Value MakeCallback(napi_value recv, + const std::vector& args, + napi_async_context context = nullptr) const; + Value MakeCallback(napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context = nullptr) const; + + Object New(const std::initializer_list& args) const; + Object New(const std::vector& args) const; + Object New(size_t argc, const napi_value* args) const; + }; + + class Promise : public Object { + public: + class Deferred { + public: + static Deferred New(napi_env env); + Deferred(napi_env env); + + Napi::Promise Promise() const; + Napi::Env Env() const; + + void Resolve(napi_value value) const; + void Reject(napi_value value) const; + + private: + napi_env _env; + napi_deferred _deferred; + napi_value _promise; + }; + + Promise(napi_env env, napi_value value); + }; + + template + class Buffer : public Uint8Array { + public: + static Buffer New(napi_env env, size_t length); + static Buffer New(napi_env env, T* data, size_t length); + + // Finalizer must implement `void operator()(Env env, T* data)`. + template + static Buffer New(napi_env env, T* data, + size_t length, + Finalizer finalizeCallback); + // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + template + static Buffer New(napi_env env, T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint); + + static Buffer Copy(napi_env env, const T* data, size_t length); + + Buffer(); + Buffer(napi_env env, napi_value value); + size_t Length() const; + T* Data() const; + + private: + mutable size_t _length; + mutable T* _data; + + Buffer(napi_env env, napi_value value, size_t length, T* data); + void EnsureInfo() const; + }; + + /// Holds a counted reference to a value; initially a weak reference unless otherwise specified, + /// may be changed to/from a strong reference by adjusting the refcount. + /// + /// The referenced value is not immediately destroyed when the reference count is zero; it is + /// merely then eligible for garbage-collection if there are no other references to the value. + template + class Reference { + public: + static Reference New(const T& value, uint32_t initialRefcount = 0); + + Reference(); + Reference(napi_env env, napi_ref ref); + ~Reference(); + + // A reference can be moved but cannot be copied. + Reference(Reference&& other); + Reference& operator =(Reference&& other); + NAPI_DISALLOW_ASSIGN(Reference) + + operator napi_ref() const; + bool operator ==(const Reference &other) const; + bool operator !=(const Reference &other) const; + + Napi::Env Env() const; + bool IsEmpty() const; + + // Note when getting the value of a Reference it is usually correct to do so + // within a HandleScope so that the value handle gets cleaned up efficiently. + T Value() const; + + uint32_t Ref(); + uint32_t Unref(); + void Reset(); + void Reset(const T& value, uint32_t refcount = 0); + + // Call this on a reference that is declared as static data, to prevent its + // destructor from running at program shutdown time, which would attempt to + // reset the reference when the environment is no longer valid. Avoid using + // this if at all possible. If you do need to use static data, MAKE SURE to + // warn your users that your addon is NOT threadsafe. + void SuppressDestruct(); + + protected: + Reference(const Reference&); + + /// !cond INTERNAL + napi_env _env; + napi_ref _ref; + /// !endcond + + private: + bool _suppressDestruct; + }; + + class ObjectReference: public Reference { + public: + ObjectReference(); + ObjectReference(napi_env env, napi_ref ref); + + // A reference can be moved but cannot be copied. + ObjectReference(Reference&& other); + ObjectReference& operator =(Reference&& other); + ObjectReference(ObjectReference&& other); + ObjectReference& operator =(ObjectReference&& other); + NAPI_DISALLOW_ASSIGN(ObjectReference) + + Napi::Value Get(const char* utf8name) const; + Napi::Value Get(const std::string& utf8name) const; + bool Set(const char* utf8name, napi_value value); + bool Set(const char* utf8name, Napi::Value value); + bool Set(const char* utf8name, const char* utf8value); + bool Set(const char* utf8name, bool boolValue); + bool Set(const char* utf8name, double numberValue); + bool Set(const std::string& utf8name, napi_value value); + bool Set(const std::string& utf8name, Napi::Value value); + bool Set(const std::string& utf8name, std::string& utf8value); + bool Set(const std::string& utf8name, bool boolValue); + bool Set(const std::string& utf8name, double numberValue); + + Napi::Value Get(uint32_t index) const; + bool Set(uint32_t index, const napi_value value); + bool Set(uint32_t index, const Napi::Value value); + bool Set(uint32_t index, const char* utf8value); + bool Set(uint32_t index, const std::string& utf8value); + bool Set(uint32_t index, bool boolValue); + bool Set(uint32_t index, double numberValue); + + protected: + ObjectReference(const ObjectReference&); + }; + + class FunctionReference: public Reference { + public: + FunctionReference(); + FunctionReference(napi_env env, napi_ref ref); + + // A reference can be moved but cannot be copied. + FunctionReference(Reference&& other); + FunctionReference& operator =(Reference&& other); + FunctionReference(FunctionReference&& other); + FunctionReference& operator =(FunctionReference&& other); + NAPI_DISALLOW_ASSIGN_COPY(FunctionReference) + + Napi::Value operator ()(const std::initializer_list& args) const; + + Napi::Value Call(const std::initializer_list& args) const; + Napi::Value Call(const std::vector& args) const; + Napi::Value Call(napi_value recv, const std::initializer_list& args) const; + Napi::Value Call(napi_value recv, const std::vector& args) const; + Napi::Value Call(napi_value recv, size_t argc, const napi_value* args) const; + + Napi::Value MakeCallback(napi_value recv, + const std::initializer_list& args, + napi_async_context context = nullptr) const; + Napi::Value MakeCallback(napi_value recv, + const std::vector& args, + napi_async_context context = nullptr) const; + Napi::Value MakeCallback(napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context = nullptr) const; + + Object New(const std::initializer_list& args) const; + Object New(const std::vector& args) const; + }; + + // Shortcuts to creating a new reference with inferred type and refcount = 0. + template Reference Weak(T value); + ObjectReference Weak(Object value); + FunctionReference Weak(Function value); + + // Shortcuts to creating a new reference with inferred type and refcount = 1. + template Reference Persistent(T value); + ObjectReference Persistent(Object value); + FunctionReference Persistent(Function value); + + /// A persistent reference to a JavaScript error object. Use of this class + /// depends somewhat on whether C++ exceptions are enabled at compile time. + /// + /// ### Handling Errors With C++ Exceptions + /// + /// If C++ exceptions are enabled, then the `Error` class extends + /// `std::exception` and enables integrated error-handling for C++ exceptions + /// and JavaScript exceptions. + /// + /// If a Node-API call fails without executing any JavaScript code (for + /// example due to an invalid argument), then the Node-API wrapper + /// automatically converts and throws the error as a C++ exception of type + /// `Napi::Error`. Or if a JavaScript function called by C++ code via Node-API + /// throws a JavaScript exception, then the Node-API wrapper automatically + /// converts and throws it as a C++ exception of type `Napi::Error`. + /// + /// If a C++ exception of type `Napi::Error` escapes from a Node-API C++ + /// callback, then the Node-API wrapper automatically converts and throws it + /// as a JavaScript exception. Therefore, catching a C++ exception of type + /// `Napi::Error` prevents a JavaScript exception from being thrown. + /// + /// #### Example 1A - Throwing a C++ exception: + /// + /// Napi::Env env = ... + /// throw Napi::Error::New(env, "Example exception"); + /// + /// Following C++ statements will not be executed. The exception will bubble + /// up as a C++ exception of type `Napi::Error`, until it is either caught + /// while still in C++, or else automatically propataged as a JavaScript + /// exception when the callback returns to JavaScript. + /// + /// #### Example 2A - Propagating a Node-API C++ exception: + /// + /// Napi::Function jsFunctionThatThrows = someObj.As(); + /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); + /// + /// Following C++ statements will not be executed. The exception will bubble + /// up as a C++ exception of type `Napi::Error`, until it is either caught + /// while still in C++, or else automatically propagated as a JavaScript + /// exception when the callback returns to JavaScript. + /// + /// #### Example 3A - Handling a Node-API C++ exception: + /// + /// Napi::Function jsFunctionThatThrows = someObj.As(); + /// Napi::Value result; + /// try { + /// result = jsFunctionThatThrows({ arg1, arg2 }); + /// } catch (const Napi::Error& e) { + /// cerr << "Caught JavaScript exception: " + e.what(); + /// } + /// + /// Since the exception was caught here, it will not be propagated as a + /// JavaScript exception. + /// + /// ### Handling Errors Without C++ Exceptions + /// + /// If C++ exceptions are disabled (by defining `NAPI_DISABLE_CPP_EXCEPTIONS`) + /// then this class does not extend `std::exception`, and APIs in the `Napi` + /// namespace do not throw C++ exceptions when they fail. Instead, they raise + /// _pending_ JavaScript exceptions and return _empty_ `Value`s. Calling code + /// should check `Value::IsEmpty()` before attempting to use a returned value, + /// and may use methods on the `Env` class to check for, get, and clear a + /// pending JavaScript exception. If the pending exception is not cleared, it + /// will be thrown when the native callback returns to JavaScript. + /// + /// #### Example 1B - Throwing a JS exception + /// + /// Napi::Env env = ... + /// Napi::Error::New(env, "Example + /// exception").ThrowAsJavaScriptException(); return; + /// + /// After throwing a JS exception, the code should generally return + /// immediately from the native callback, after performing any necessary + /// cleanup. + /// + /// #### Example 2B - Propagating a Node-API JS exception: + /// + /// Napi::Function jsFunctionThatThrows = someObj.As(); + /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); + /// if (result.IsEmpty()) return; + /// + /// An empty value result from a Node-API call indicates an error occurred, + /// and a JavaScript exception is pending. To let the exception propagate, the + /// code should generally return immediately from the native callback, after + /// performing any necessary cleanup. + /// + /// #### Example 3B - Handling a Node-API JS exception: + /// + /// Napi::Function jsFunctionThatThrows = someObj.As(); + /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); + /// if (result.IsEmpty()) { + /// Napi::Error e = env.GetAndClearPendingException(); + /// cerr << "Caught JavaScript exception: " + e.Message(); + /// } + /// + /// Since the exception was cleared here, it will not be propagated as a + /// JavaScript exception after the native callback returns. + class Error : public ObjectReference +#ifdef NAPI_CPP_EXCEPTIONS + , public std::exception +#endif // NAPI_CPP_EXCEPTIONS + { + public: + static Error New(napi_env env); + static Error New(napi_env env, const char* message); + static Error New(napi_env env, const std::string& message); + + static NAPI_NO_RETURN void Fatal(const char* location, const char* message); + + Error(); + Error(napi_env env, napi_value value); + + // An error can be moved or copied. + Error(Error&& other); + Error& operator =(Error&& other); + Error(const Error&); + Error& operator =(const Error&); + + const std::string& Message() const NAPI_NOEXCEPT; + void ThrowAsJavaScriptException() const; + +#ifdef NAPI_CPP_EXCEPTIONS + const char* what() const NAPI_NOEXCEPT override; +#endif // NAPI_CPP_EXCEPTIONS + + protected: + /// !cond INTERNAL + using create_error_fn = napi_status (*)(napi_env envb, + napi_value code, + napi_value msg, + napi_value* result); + + template + static TError New(napi_env env, + const char* message, + size_t length, + create_error_fn create_error); + /// !endcond + + private: + mutable std::string _message; + }; + + class TypeError : public Error { + public: + static TypeError New(napi_env env, const char* message); + static TypeError New(napi_env env, const std::string& message); + + TypeError(); + TypeError(napi_env env, napi_value value); + }; + + class RangeError : public Error { + public: + static RangeError New(napi_env env, const char* message); + static RangeError New(napi_env env, const std::string& message); + + RangeError(); + RangeError(napi_env env, napi_value value); + }; + + class CallbackInfo { + public: + CallbackInfo(napi_env env, napi_callback_info info); + ~CallbackInfo(); + + // Disallow copying to prevent multiple free of _dynamicArgs + NAPI_DISALLOW_ASSIGN_COPY(CallbackInfo) + + Napi::Env Env() const; + Value NewTarget() const; + bool IsConstructCall() const; + size_t Length() const; + const Value operator [](size_t index) const; + Value This() const; + void* Data() const; + void SetData(void* data); + + private: + const size_t _staticArgCount = 6; + napi_env _env; + napi_callback_info _info; + napi_value _this; + size_t _argc; + napi_value* _argv; + napi_value _staticArgs[6]; + napi_value* _dynamicArgs; + void* _data; + }; + + class PropertyDescriptor { + public: + using GetterCallback = Napi::Value (*)(const Napi::CallbackInfo& info); + using SetterCallback = void (*)(const Napi::CallbackInfo& info); + +#ifndef NODE_ADDON_API_DISABLE_DEPRECATED + template + static PropertyDescriptor Accessor(const char* utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(const std::string& utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(napi_value name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Name name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(napi_value name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(const char* utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(const std::string& utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(napi_value name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(Name name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED + + template + static PropertyDescriptor Accessor(const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor(const std::string& utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor(Name name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor(const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor(const std::string& utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor(Name name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(Napi::Env env, + Napi::Object object, + const char* utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(Napi::Env env, + Napi::Object object, + Name name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor Value(const char* utf8name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value(const std::string& utf8name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value(napi_value name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value(Name name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + + PropertyDescriptor(napi_property_descriptor desc); + + operator napi_property_descriptor&(); + operator const napi_property_descriptor&() const; + + private: + napi_property_descriptor _desc; + }; + + /// Property descriptor for use with `ObjectWrap::DefineClass()`. + /// + /// This is different from the standalone `PropertyDescriptor` because it is specific to each + /// `ObjectWrap` subclass. This prevents using descriptors from a different class when + /// defining a new class (preventing the callbacks from having incorrect `this` pointers). + template + class ClassPropertyDescriptor { + public: + ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {} + + operator napi_property_descriptor&() { return _desc; } + operator const napi_property_descriptor&() const { return _desc; } + + private: + napi_property_descriptor _desc; + }; + + template + struct MethodCallbackData { + TCallback callback; + void* data; + }; + + template + struct AccessorCallbackData { + TGetterCallback getterCallback; + TSetterCallback setterCallback; + void* data; + }; + + template + class InstanceWrap { + public: + using InstanceVoidMethodCallback = void (T::*)(const CallbackInfo& info); + using InstanceMethodCallback = Napi::Value (T::*)(const CallbackInfo& info); + using InstanceGetterCallback = Napi::Value (T::*)(const CallbackInfo& info); + using InstanceSetterCallback = void (T::*)(const CallbackInfo& info, + const Napi::Value& value); + + using PropertyDescriptor = ClassPropertyDescriptor; + + static PropertyDescriptor InstanceMethod(const char* utf8name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod(const char* utf8name, + InstanceMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod(Symbol name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod(Symbol name, + InstanceMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod(const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod(const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod(Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod(Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceAccessor(const char* utf8name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceAccessor(Symbol name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceAccessor(const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceAccessor(Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceValue(const char* utf8name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor InstanceValue(Symbol name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + + protected: + static void AttachPropData(napi_env env, napi_value value, const napi_property_descriptor* prop); + + private: + using This = InstanceWrap; + + using InstanceVoidMethodCallbackData = + MethodCallbackData; + using InstanceMethodCallbackData = + MethodCallbackData; + using InstanceAccessorCallbackData = + AccessorCallbackData; + + static napi_value InstanceVoidMethodCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value InstanceMethodCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value InstanceGetterCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value InstanceSetterCallbackWrapper(napi_env env, napi_callback_info info); + + template + static napi_value WrappedMethod(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT; + + template struct SetterTag {}; + + template + static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { + return &This::WrappedMethod; + } + static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { + return nullptr; + } + }; + + /// Base class to be extended by C++ classes exposed to JavaScript; each C++ class instance gets + /// "wrapped" by a JavaScript object that is managed by this class. + /// + /// At initialization time, the `DefineClass()` method must be used to + /// hook up the accessor and method callbacks. It takes a list of + /// property descriptors, which can be constructed via the various + /// static methods on the base class. + /// + /// #### Example: + /// + /// class Example: public Napi::ObjectWrap { + /// public: + /// static void Initialize(Napi::Env& env, Napi::Object& target) { + /// Napi::Function constructor = DefineClass(env, "Example", { + /// InstanceAccessor<&Example::GetSomething, &Example::SetSomething>("value"), + /// InstanceMethod<&Example::DoSomething>("doSomething"), + /// }); + /// target.Set("Example", constructor); + /// } + /// + /// Example(const Napi::CallbackInfo& info); // Constructor + /// Napi::Value GetSomething(const Napi::CallbackInfo& info); + /// void SetSomething(const Napi::CallbackInfo& info, const Napi::Value& value); + /// Napi::Value DoSomething(const Napi::CallbackInfo& info); + /// } + template + class ObjectWrap : public InstanceWrap, public Reference { + public: + ObjectWrap(const CallbackInfo& callbackInfo); + virtual ~ObjectWrap(); + + static T* Unwrap(Object wrapper); + + // Methods exposed to JavaScript must conform to one of these callback signatures. + using StaticVoidMethodCallback = void (*)(const CallbackInfo& info); + using StaticMethodCallback = Napi::Value (*)(const CallbackInfo& info); + using StaticGetterCallback = Napi::Value (*)(const CallbackInfo& info); + using StaticSetterCallback = void (*)(const CallbackInfo& info, + const Napi::Value& value); + + using PropertyDescriptor = ClassPropertyDescriptor; + + static Function DefineClass(Napi::Env env, + const char* utf8name, + const std::initializer_list& properties, + void* data = nullptr); + static Function DefineClass(Napi::Env env, + const char* utf8name, + const std::vector& properties, + void* data = nullptr); + static PropertyDescriptor StaticMethod(const char* utf8name, + StaticVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod(const char* utf8name, + StaticMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod(Symbol name, + StaticVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod(Symbol name, + StaticMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod(const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod(Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod(const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod(Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticAccessor(const char* utf8name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticAccessor(Symbol name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticAccessor(const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticAccessor(Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticValue(const char* utf8name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor StaticValue(Symbol name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + virtual void Finalize(Napi::Env env); + + private: + using This = ObjectWrap; + + static napi_value ConstructorCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value StaticVoidMethodCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value StaticMethodCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value StaticGetterCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value StaticSetterCallbackWrapper(napi_env env, napi_callback_info info); + static void FinalizeCallback(napi_env env, void* data, void* hint); + static Function DefineClass(Napi::Env env, + const char* utf8name, + const size_t props_count, + const napi_property_descriptor* props, + void* data = nullptr); + + using StaticVoidMethodCallbackData = + MethodCallbackData; + using StaticMethodCallbackData = + MethodCallbackData; + + using StaticAccessorCallbackData = + AccessorCallbackData; + + template + static napi_value WrappedMethod(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT; + + template struct StaticSetterTag {}; + + template + static napi_callback WrapStaticSetter(StaticSetterTag) + NAPI_NOEXCEPT { + return &This::WrappedMethod; + } + static napi_callback WrapStaticSetter(StaticSetterTag) + NAPI_NOEXCEPT { + return nullptr; + } + + bool _construction_failed = true; + }; + + class HandleScope { + public: + HandleScope(napi_env env, napi_handle_scope scope); + explicit HandleScope(Napi::Env env); + ~HandleScope(); + + // Disallow copying to prevent double close of napi_handle_scope + NAPI_DISALLOW_ASSIGN_COPY(HandleScope) + + operator napi_handle_scope() const; + + Napi::Env Env() const; + + private: + napi_env _env; + napi_handle_scope _scope; + }; + + class EscapableHandleScope { + public: + EscapableHandleScope(napi_env env, napi_escapable_handle_scope scope); + explicit EscapableHandleScope(Napi::Env env); + ~EscapableHandleScope(); + + // Disallow copying to prevent double close of napi_escapable_handle_scope + NAPI_DISALLOW_ASSIGN_COPY(EscapableHandleScope) + + operator napi_escapable_handle_scope() const; + + Napi::Env Env() const; + Value Escape(napi_value escapee); + + private: + napi_env _env; + napi_escapable_handle_scope _scope; + }; + +#if (NAPI_VERSION > 2) + class CallbackScope { + public: + CallbackScope(napi_env env, napi_callback_scope scope); + CallbackScope(napi_env env, napi_async_context context); + virtual ~CallbackScope(); + + // Disallow copying to prevent double close of napi_callback_scope + NAPI_DISALLOW_ASSIGN_COPY(CallbackScope) + + operator napi_callback_scope() const; + + Napi::Env Env() const; + + private: + napi_env _env; + napi_callback_scope _scope; + }; +#endif + + class AsyncContext { + public: + explicit AsyncContext(napi_env env, const char* resource_name); + explicit AsyncContext(napi_env env, const char* resource_name, const Object& resource); + virtual ~AsyncContext(); + + AsyncContext(AsyncContext&& other); + AsyncContext& operator =(AsyncContext&& other); + NAPI_DISALLOW_ASSIGN_COPY(AsyncContext) + + operator napi_async_context() const; + + Napi::Env Env() const; + + private: + napi_env _env; + napi_async_context _context; + }; + + class AsyncWorker { + public: + virtual ~AsyncWorker(); + + // An async worker can be moved but cannot be copied. + AsyncWorker(AsyncWorker&& other); + AsyncWorker& operator =(AsyncWorker&& other); + NAPI_DISALLOW_ASSIGN_COPY(AsyncWorker) + + operator napi_async_work() const; + + Napi::Env Env() const; + + void Queue(); + void Cancel(); + void SuppressDestruct(); + + ObjectReference& Receiver(); + FunctionReference& Callback(); + + virtual void OnExecute(Napi::Env env); + virtual void OnWorkComplete(Napi::Env env, + napi_status status); + + protected: + explicit AsyncWorker(const Function& callback); + explicit AsyncWorker(const Function& callback, + const char* resource_name); + explicit AsyncWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncWorker(const Object& receiver, + const Function& callback); + explicit AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + + explicit AsyncWorker(Napi::Env env); + explicit AsyncWorker(Napi::Env env, + const char* resource_name); + explicit AsyncWorker(Napi::Env env, + const char* resource_name, + const Object& resource); + + virtual void Execute() = 0; + virtual void OnOK(); + virtual void OnError(const Error& e); + virtual void Destroy(); + virtual std::vector GetResult(Napi::Env env); + + void SetError(const std::string& error); + + private: + static inline void OnAsyncWorkExecute(napi_env env, void* asyncworker); + static inline void OnAsyncWorkComplete(napi_env env, + napi_status status, + void* asyncworker); + + napi_env _env; + napi_async_work _work; + ObjectReference _receiver; + FunctionReference _callback; + std::string _error; + bool _suppress_destruct; + }; + + #if (NAPI_VERSION > 3 && !defined(__wasm32__)) + class ThreadSafeFunction { + public: + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data); + + ThreadSafeFunction(); + ThreadSafeFunction(napi_threadsafe_function tsFunctionValue); + + operator napi_threadsafe_function() const; + + // This API may be called from any thread. + napi_status BlockingCall() const; + + // This API may be called from any thread. + template + napi_status BlockingCall(Callback callback) const; + + // This API may be called from any thread. + template + napi_status BlockingCall(DataType* data, Callback callback) const; + + // This API may be called from any thread. + napi_status NonBlockingCall() const; + + // This API may be called from any thread. + template + napi_status NonBlockingCall(Callback callback) const; + + // This API may be called from any thread. + template + napi_status NonBlockingCall(DataType* data, Callback callback) const; + + // This API may only be called from the main thread. + void Ref(napi_env env) const; + + // This API may only be called from the main thread. + void Unref(napi_env env) const; + + // This API may be called from any thread. + napi_status Acquire() const; + + // This API may be called from any thread. + napi_status Release(); + + // This API may be called from any thread. + napi_status Abort(); + + struct ConvertibleContext + { + template + operator T*() { return static_cast(context); } + void* context; + }; + + // This API may be called from any thread. + ConvertibleContext GetContext() const; + + private: + using CallbackWrapper = std::function; + + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data, + napi_finalize wrapper); + + napi_status CallInternal(CallbackWrapper* callbackWrapper, + napi_threadsafe_function_call_mode mode) const; + + static void CallJS(napi_env env, + napi_value jsCallback, + void* context, + void* data); + + napi_threadsafe_function _tsfn; + }; + + // A TypedThreadSafeFunction by default has no context (nullptr) and can + // accept any type (void) to its CallJs. + template + class TypedThreadSafeFunction { + public: + // This API may only be called from the main thread. + // Helper function that returns nullptr if running Node-API 5+, otherwise a + // non-empty, no-op Function. This provides the ability to specify at + // compile-time a callback parameter to `New` that safely does no action + // when targeting _any_ Node-API version. +#if NAPI_VERSION > 4 + static std::nullptr_t EmptyFunctionFactory(Napi::Env env); +#else + static Napi::Function EmptyFunctionFactory(Napi::Env env); +#endif + static Napi::Function FunctionOrEmpty(Napi::Env env, + Napi::Function& callback); + +#if NAPI_VERSION > 4 + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [missing] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [passed] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [missing] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [passed] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); +#endif + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [missing] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [passed] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [missing] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [passed] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + CallbackType callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + TypedThreadSafeFunction(); + TypedThreadSafeFunction( + napi_threadsafe_function tsFunctionValue); + + operator napi_threadsafe_function() const; + + // This API may be called from any thread. + napi_status BlockingCall(DataType* data = nullptr) const; + + // This API may be called from any thread. + napi_status NonBlockingCall(DataType* data = nullptr) const; + + // This API may only be called from the main thread. + void Ref(napi_env env) const; + + // This API may only be called from the main thread. + void Unref(napi_env env) const; + + // This API may be called from any thread. + napi_status Acquire() const; + + // This API may be called from any thread. + napi_status Release(); + + // This API may be called from any thread. + napi_status Abort(); + + // This API may be called from any thread. + ContextType* GetContext() const; + + private: + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data, + napi_finalize wrapper); + + static void CallJsInternal(napi_env env, + napi_value jsCallback, + void* context, + void* data); + + protected: + napi_threadsafe_function _tsfn; + }; + template + class AsyncProgressWorkerBase : public AsyncWorker { + public: + virtual void OnWorkProgress(DataType* data) = 0; + class ThreadSafeData { + public: + ThreadSafeData(AsyncProgressWorkerBase* asyncprogressworker, DataType* data) + : _asyncprogressworker(asyncprogressworker), _data(data) {} + + AsyncProgressWorkerBase* asyncprogressworker() { return _asyncprogressworker; }; + DataType* data() { return _data; }; + + private: + AsyncProgressWorkerBase* _asyncprogressworker; + DataType* _data; + }; + void OnWorkComplete(Napi::Env env, napi_status status) override; + protected: + explicit AsyncProgressWorkerBase(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource, + size_t queue_size = 1); + virtual ~AsyncProgressWorkerBase(); + +// Optional callback of Napi::ThreadSafeFunction only available after NAPI_VERSION 4. +// Refs: https://github.com/nodejs/node/pull/27791 +#if NAPI_VERSION > 4 + explicit AsyncProgressWorkerBase(Napi::Env env, + const char* resource_name, + const Object& resource, + size_t queue_size = 1); +#endif + + static inline void OnAsyncWorkProgress(Napi::Env env, + Napi::Function jsCallback, + void* data); + + napi_status NonBlockingCall(DataType* data); + + private: + ThreadSafeFunction _tsfn; + bool _work_completed = false; + napi_status _complete_status; + static inline void OnThreadSafeFunctionFinalize(Napi::Env env, void* data, AsyncProgressWorkerBase* context); + }; + + template + class AsyncProgressWorker : public AsyncProgressWorkerBase { + public: + virtual ~AsyncProgressWorker(); + + class ExecutionProgress { + friend class AsyncProgressWorker; + public: + void Signal() const; + void Send(const T* data, size_t count) const; + private: + explicit ExecutionProgress(AsyncProgressWorker* worker) : _worker(worker) {} + AsyncProgressWorker* const _worker; + }; + + void OnWorkProgress(void*) override; + + protected: + explicit AsyncProgressWorker(const Function& callback); + explicit AsyncProgressWorker(const Function& callback, + const char* resource_name); + explicit AsyncProgressWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + +// Optional callback of Napi::ThreadSafeFunction only available after NAPI_VERSION 4. +// Refs: https://github.com/nodejs/node/pull/27791 +#if NAPI_VERSION > 4 + explicit AsyncProgressWorker(Napi::Env env); + explicit AsyncProgressWorker(Napi::Env env, + const char* resource_name); + explicit AsyncProgressWorker(Napi::Env env, + const char* resource_name, + const Object& resource); +#endif + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void OnProgress(const T* data, size_t count) = 0; + + private: + void Execute() override; + void Signal() const; + void SendProgress_(const T* data, size_t count); + + std::mutex _mutex; + T* _asyncdata; + size_t _asyncsize; + }; + + template + class AsyncProgressQueueWorker : public AsyncProgressWorkerBase> { + public: + virtual ~AsyncProgressQueueWorker() {}; + + class ExecutionProgress { + friend class AsyncProgressQueueWorker; + public: + void Signal() const; + void Send(const T* data, size_t count) const; + private: + explicit ExecutionProgress(AsyncProgressQueueWorker* worker) : _worker(worker) {} + AsyncProgressQueueWorker* const _worker; + }; + + void OnWorkComplete(Napi::Env env, napi_status status) override; + void OnWorkProgress(std::pair*) override; + + protected: + explicit AsyncProgressQueueWorker(const Function& callback); + explicit AsyncProgressQueueWorker(const Function& callback, + const char* resource_name); + explicit AsyncProgressQueueWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + +// Optional callback of Napi::ThreadSafeFunction only available after NAPI_VERSION 4. +// Refs: https://github.com/nodejs/node/pull/27791 +#if NAPI_VERSION > 4 + explicit AsyncProgressQueueWorker(Napi::Env env); + explicit AsyncProgressQueueWorker(Napi::Env env, + const char* resource_name); + explicit AsyncProgressQueueWorker(Napi::Env env, + const char* resource_name, + const Object& resource); +#endif + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void OnProgress(const T* data, size_t count) = 0; + + private: + void Execute() override; + void Signal() const; + void SendProgress_(const T* data, size_t count); + }; + #endif // NAPI_VERSION > 3 && !defined(__wasm32__) + + // Memory management. + class MemoryManagement { + public: + static int64_t AdjustExternalMemory(Env env, int64_t change_in_bytes); + }; + + // Version management + class VersionManagement { + public: + static uint32_t GetNapiVersion(Env env); + static const napi_node_version* GetNodeVersion(Env env); + }; + +#if NAPI_VERSION > 5 + template + class Addon : public InstanceWrap { + public: + static inline Object Init(Env env, Object exports); + static T* Unwrap(Object wrapper); + + protected: + using AddonProp = ClassPropertyDescriptor; + void DefineAddon(Object exports, + const std::initializer_list& props); + Napi::Object DefineProperties(Object object, + const std::initializer_list& props); + + private: + Object entry_point_; + }; +#endif // NAPI_VERSION > 5 + +} // namespace Napi + +// Inline implementations of all the above class methods are included here. +#include "napi-inl.h" + +#endif // SRC_NAPI_H_ diff --git a/node_modules/node-addon-api/node_api.gyp b/node_modules/node-addon-api/node_api.gyp new file mode 100644 index 0000000..4ff0ae7 --- /dev/null +++ b/node_modules/node-addon-api/node_api.gyp @@ -0,0 +1,9 @@ +{ + 'targets': [ + { + 'target_name': 'nothing', + 'type': 'static_library', + 'sources': [ 'nothing.c' ] + } + ] +} diff --git a/node_modules/node-addon-api/noexcept.gypi b/node_modules/node-addon-api/noexcept.gypi new file mode 100644 index 0000000..179f21f --- /dev/null +++ b/node_modules/node-addon-api/noexcept.gypi @@ -0,0 +1,16 @@ +{ + 'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ], + 'cflags': [ '-fno-exceptions' ], + 'cflags_cc': [ '-fno-exceptions' ], + 'msvs_settings': { + 'VCCLCompilerTool': { + 'ExceptionHandling': 0, + 'EnablePREfast': 'true', + }, + }, + 'xcode_settings': { + 'CLANG_CXX_LIBRARY': 'libc++', + 'MACOSX_DEPLOYMENT_TARGET': '10.7', + 'GCC_ENABLE_CPP_EXCEPTIONS': 'NO', + }, +} diff --git a/node_modules/node-addon-api/nothing.c b/node_modules/node-addon-api/nothing.c new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/node-addon-api/package-support.json b/node_modules/node-addon-api/package-support.json new file mode 100644 index 0000000..10d3607 --- /dev/null +++ b/node_modules/node-addon-api/package-support.json @@ -0,0 +1,21 @@ +{ + "versions": [ + { + "version": "*", + "target": { + "node": "active" + }, + "response": { + "type": "time-permitting", + "paid": false, + "contact": { + "name": "node-addon-api team", + "url": "https://github.com/nodejs/node-addon-api/issues" + } + }, + "backing": [ { "project": "https://github.com/nodejs" }, + { "foundation": "https://openjsf.org/" } + ] + } + ] +} diff --git a/node_modules/node-addon-api/package.json b/node_modules/node-addon-api/package.json new file mode 100644 index 0000000..6c8da4f --- /dev/null +++ b/node_modules/node-addon-api/package.json @@ -0,0 +1,368 @@ +{ + "bugs": { + "url": "https://github.com/nodejs/node-addon-api/issues" + }, + "contributors": [ + { + "name": "Abhishek Kumar Singh", + "url": "https://github.com/abhi11210646" + }, + { + "name": "Alba Mendez", + "url": "https://github.com/jmendeth" + }, + { + "name": "András Timár, Dr", + "url": "https://github.com/timarandras" + }, + { + "name": "Andrew Petersen", + "url": "https://github.com/kirbysayshi" + }, + { + "name": "Anisha Rohra", + "url": "https://github.com/anisha-rohra" + }, + { + "name": "Anna Henningsen", + "url": "https://github.com/addaleax" + }, + { + "name": "Arnaud Botella", + "url": "https://github.com/BotellaA" + }, + { + "name": "Arunesh Chandra", + "url": "https://github.com/aruneshchandra" + }, + { + "name": "Azlan Mukhtar", + "url": "https://github.com/azlan" + }, + { + "name": "Ben Berman", + "url": "https://github.com/rivertam" + }, + { + "name": "Benjamin Byholm", + "url": "https://github.com/kkoopa" + }, + { + "name": "Bill Gallafent", + "url": "https://github.com/gallafent" + }, + { + "name": "blagoev", + "url": "https://github.com/blagoev" + }, + { + "name": "Bruce A. MacNaughton", + "url": "https://github.com/bmacnaughton" + }, + { + "name": "Cory Mickelson", + "url": "https://github.com/corymickelson" + }, + { + "name": "Daniel Bevenius", + "url": "https://github.com/danbev" + }, + { + "name": "Darshan Sen", + "url": "https://github.com/RaisinTen" + }, + { + "name": "David Halls", + "url": "https://github.com/davedoesdev" + }, + { + "name": "Dmitry Ashkadov", + "url": "https://github.com/dmitryash" + }, + { + "name": "Dongjin Na", + "url": "https://github.com/nadongguri" + }, + { + "name": "Ferdinand Holzer", + "url": "https://github.com/fholzer" + }, + { + "name": "Eric Bickle", + "url": "https://github.com/ebickle" + }, + { + "name": "Gabriel Schulhof", + "url": "https://github.com/gabrielschulhof" + }, + { + "name": "Guenter Sandner", + "url": "https://github.com/gms1" + }, + { + "name": "Gus Caplan", + "url": "https://github.com/devsnek" + }, + { + "name": "Helio Frota", + "url": "https://github.com/helio-frota" + }, + { + "name": "Hitesh Kanwathirtha", + "url": "https://github.com/digitalinfinity" + }, + { + "name": "ikokostya", + "url": "https://github.com/ikokostya" + }, + { + "name": "Jack Xia", + "url": "https://github.com/JckXia" + }, + { + "name": "Jake Barnes", + "url": "https://github.com/DuBistKomisch" + }, + { + "name": "Jake Yoon", + "url": "https://github.com/yjaeseok" + }, + { + "name": "Jason Ginchereau", + "url": "https://github.com/jasongin" + }, + { + "name": "Jeroen Janssen", + "url": "https://github.com/japj" + }, + { + "name": "Jim Schlight", + "url": "https://github.com/jschlight" + }, + { + "name": "Jinho Bang", + "url": "https://github.com/romandev" + }, + { + "name": "José Expósito", + "url": "https://github.com/JoseExposito" + }, + { + "name": "joshgarde", + "url": "https://github.com/joshgarde" + }, + { + "name": "Kasumi Hanazuki", + "url": "https://github.com/hanazuki" + }, + { + "name": "Kelvin", + "url": "https://github.com/kelvinhammond" + }, + { + "name": "Kevin Eady", + "url": "https://github.com/KevinEady" + }, + { + "name": "Kévin VOYER", + "url": "https://github.com/kecsou" + }, + { + "name": "kidneysolo", + "url": "https://github.com/kidneysolo" + }, + { + "name": "Koki Nishihara", + "url": "https://github.com/Nishikoh" + }, + { + "name": "Konstantin Tarkus", + "url": "https://github.com/koistya" + }, + { + "name": "Kyle Farnung", + "url": "https://github.com/kfarnung" + }, + { + "name": "legendecas", + "url": "https://github.com/legendecas" + }, + { + "name": "LongYinan", + "url": "https://github.com/Brooooooklyn" + }, + { + "name": "Lovell Fuller", + "url": "https://github.com/lovell" + }, + { + "name": "Luciano Martorella", + "url": "https://github.com/lmartorella" + }, + { + "name": "mastergberry", + "url": "https://github.com/mastergberry" + }, + { + "name": "Mathias Küsel", + "url": "https://github.com/mathiask88" + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina" + }, + { + "name": "Michael Dawson", + "url": "https://github.com/mhdawson" + }, + { + "name": "Michael Price", + "url": "https://github.com/mikepricedev" + }, + { + "name": "Michele Campus", + "url": "https://github.com/kYroL01" + }, + { + "name": "Mikhail Cheshkov", + "url": "https://github.com/mcheshkov" + }, + { + "name": "nempoBu4", + "url": "https://github.com/nempoBu4" + }, + { + "name": "Nicola Del Gobbo", + "url": "https://github.com/NickNaso" + }, + { + "name": "Nick Soggin", + "url": "https://github.com/iSkore" + }, + { + "name": "Nikolai Vavilov", + "url": "https://github.com/seishun" + }, + { + "name": "Nurbol Alpysbayev", + "url": "https://github.com/anurbol" + }, + { + "name": "pacop", + "url": "https://github.com/pacop" + }, + { + "name": "Philipp Renoth", + "url": "https://github.com/DaAitch" + }, + { + "name": "Rolf Timmermans", + "url": "https://github.com/rolftimmermans" + }, + { + "name": "Ross Weir", + "url": "https://github.com/ross-weir" + }, + { + "name": "Ryuichi Okumura", + "url": "https://github.com/okuryu" + }, + { + "name": "Sampson Gao", + "url": "https://github.com/sampsongao" + }, + { + "name": "Sam Roberts", + "url": "https://github.com/sam-github" + }, + { + "name": "Taylor Woll", + "url": "https://github.com/boingoing" + }, + { + "name": "Thomas Gentilhomme", + "url": "https://github.com/fraxken" + }, + { + "name": "Tim Rach", + "url": "https://github.com/timrach" + }, + { + "name": "Tobias Nießen", + "url": "https://github.com/tniessen" + }, + { + "name": "Tux3", + "url": "https://github.com/tux3" + }, + { + "name": "Vlad Velmisov", + "url": "https://github.com/Velmisov" + }, + { + "name": "Yohei Kishimoto", + "url": "https://github.com/morokosi" + }, + { + "name": "Yulong Wang", + "url": "https://github.com/fs-eire" + }, + { + "name": "Ziqiu Zhao", + "url": "https://github.com/ZzqiZQute" + } + ], + "description": "Node.js API (Node-API)", + "devDependencies": { + "benchmark": "^2.1.4", + "bindings": "^1.5.0", + "clang-format": "^1.4.0", + "fs-extra": "^9.0.1", + "pre-commit": "^1.2.2", + "safe-buffer": "^5.1.1" + }, + "directories": {}, + "gypfile": false, + "homepage": "https://github.com/nodejs/node-addon-api", + "keywords": [ + "n-api", + "napi", + "addon", + "native", + "bindings", + "c", + "c++", + "nan", + "node-addon-api" + ], + "license": "MIT", + "main": "index.js", + "name": "node-addon-api", + "optionalDependencies": {}, + "readme": "README.md", + "repository": { + "type": "git", + "url": "git://github.com/nodejs/node-addon-api.git" + }, + "files": [ + "*.{c,h,gyp,gypi}", + "package-support.json", + "tools/" + ], + "scripts": { + "prebenchmark": "node-gyp rebuild -C benchmark", + "benchmark": "node benchmark", + "pretest": "node-gyp rebuild -C test", + "test": "node test", + "predev": "node-gyp rebuild -C test --debug", + "dev": "node test", + "predev:incremental": "node-gyp configure build -C test --debug", + "dev:incremental": "node test", + "doc": "doxygen doc/Doxyfile", + "lint": "node tools/clang-format", + "lint:fix": "node tools/clang-format --fix" + }, + "pre-commit": "lint", + "version": "3.2.1", + "support": true +} diff --git a/node_modules/node-addon-api/tools/README.md b/node_modules/node-addon-api/tools/README.md new file mode 100644 index 0000000..6b80e94 --- /dev/null +++ b/node_modules/node-addon-api/tools/README.md @@ -0,0 +1,73 @@ +# Tools + +## clang-format + +The clang-format checking tools is designed to check changed lines of code compared to given git-refs. + +## Migration Script + +The migration tool is designed to reduce repetitive work in the migration process. However, the script is not aiming to convert every thing for you. There are usually some small fixes and major reconstruction required. + +### How To Use + +To run the conversion script, first make sure you have the latest `node-addon-api` in your `node_modules` directory. +``` +npm install node-addon-api +``` + +Then run the script passing your project directory +``` +node ./node_modules/node-addon-api/tools/conversion.js ./ +``` + +After finish, recompile and debug things that are missed by the script. + + +### Quick Fixes +Here is the list of things that can be fixed easily. + 1. Change your methods' return value to void if it doesn't return value to JavaScript. + 2. Use `.` to access attribute or to invoke member function in Napi::Object instead of `->`. + 3. `Napi::New(env, value);` to `Napi::[Type]::New(env, value); + + +### Major Reconstructions +The implementation of `Napi::ObjectWrap` is significantly different from NAN's. `Napi::ObjectWrap` takes a pointer to the wrapped object and creates a reference to the wrapped object inside ObjectWrap constructor. `Napi::ObjectWrap` also associates wrapped object's instance methods to Javascript module instead of static methods like NAN. + +So if you use Nan::ObjectWrap in your module, you will need to execute the following steps. + + 1. Convert your [ClassName]::New function to a constructor function that takes a `Napi::CallbackInfo`. Declare it as +``` +[ClassName](const Napi::CallbackInfo& info); +``` +and define it as +``` +[ClassName]::[ClassName](const Napi::CallbackInfo& info) : Napi::ObjectWrap<[ClassName]>(info){ + ... +} +``` +This way, the `Napi::ObjectWrap` constructor will be invoked after the object has been instantiated and `Napi::ObjectWrap` can use the `this` pointer to create a reference to the wrapped object. + + 2. Move your original constructor code into the new constructor. Delete your original constructor. + 3. In your class initialization function, associate native methods in the following way. +``` +Napi::FunctionReference constructor; + +void [ClassName]::Init(Napi::Env env, Napi::Object exports, Napi::Object module) { + Napi::HandleScope scope(env); + Napi::Function ctor = DefineClass(env, "Canvas", { + InstanceMethod<&[ClassName]::Func1>("Func1"), + InstanceMethod<&[ClassName]::Func2>("Func2"), + InstanceAccessor<&[ClassName]::ValueGetter>("Value"), + StaticMethod<&[ClassName]::StaticMethod>("MethodName"), + InstanceValue("Value", Napi::[Type]::New(env, value)), + }); + + constructor = Napi::Persistent(ctor); + constructor .SuppressDestruct(); + exports.Set("[ClassName]", ctor); +} +``` + 4. In function where you need to Unwrap the ObjectWrap in NAN like `[ClassName]* native = Nan::ObjectWrap::Unwrap<[ClassName]>(info.This());`, use `this` pointer directly as the unwrapped object as each ObjectWrap instance is associated with a unique object instance. + + +If you still find issues after following this guide, please leave us an issue describing your problem and we will try to resolve it. diff --git a/node_modules/node-addon-api/tools/check-napi.js b/node_modules/node-addon-api/tools/check-napi.js new file mode 100644 index 0000000..48fdfc0 --- /dev/null +++ b/node_modules/node-addon-api/tools/check-napi.js @@ -0,0 +1,100 @@ +'use strict'; +// Descend into a directory structure and, for each file matching *.node, output +// based on the imports found in the file whether it's an N-API module or not. + +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); + +// Read the output of the command, break it into lines, and use the reducer to +// decide whether the file is an N-API module or not. +function checkFile(file, command, argv, reducer) { + const child = child_process.spawn(command, argv, { + stdio: ['inherit', 'pipe', 'inherit'] + }); + let leftover = ''; + let isNapi = undefined; + child.stdout.on('data', (chunk) => { + if (isNapi === undefined) { + chunk = (leftover + chunk.toString()).split(/[\r\n]+/); + leftover = chunk.pop(); + isNapi = chunk.reduce(reducer, isNapi); + if (isNapi !== undefined) { + child.kill(); + } + } + }); + child.on('close', (code, signal) => { + if ((code === null && signal !== null) || (code !== 0)) { + console.log( + command + ' exited with code: ' + code + ' and signal: ' + signal); + } else { + // Green if it's a N-API module, red otherwise. + console.log( + '\x1b[' + (isNapi ? '42' : '41') + 'm' + + (isNapi ? ' N-API' : 'Not N-API') + + '\x1b[0m: ' + file); + } + }); +} + +// Use nm -a to list symbols. +function checkFileUNIX(file) { + checkFile(file, 'nm', ['-a', file], (soFar, line) => { + if (soFar === undefined) { + line = line.match(/([0-9a-f]*)? ([a-zA-Z]) (.*$)/); + if (line[2] === 'U') { + if (/^napi/.test(line[3])) { + soFar = true; + } + } + } + return soFar; + }); +} + +// Use dumpbin /imports to list symbols. +function checkFileWin32(file) { + checkFile(file, 'dumpbin', ['/imports', file], (soFar, line) => { + if (soFar === undefined) { + line = line.match(/([0-9a-f]*)? +([a-zA-Z0-9]) (.*$)/); + if (line && /^napi/.test(line[line.length - 1])) { + soFar = true; + } + } + return soFar; + }); +} + +// Descend into a directory structure and pass each file ending in '.node' to +// one of the above checks, depending on the OS. +function recurse(top) { + fs.readdir(top, (error, items) => { + if (error) { + throw ("error reading directory " + top + ": " + error); + } + items.forEach((item) => { + item = path.join(top, item); + fs.stat(item, ((item) => (error, stats) => { + if (error) { + throw ("error about " + item + ": " + error); + } + if (stats.isDirectory()) { + recurse(item); + } else if (/[.]node$/.test(item) && + // Explicitly ignore files called 'nothing.node' because they are + // artefacts of node-addon-api having identified a version of + // Node.js that ships with a correct implementation of N-API. + path.basename(item) !== 'nothing.node') { + process.platform === 'win32' ? + checkFileWin32(item) : + checkFileUNIX(item); + } + })(item)); + }); + }); +} + +// Start with the directory given on the command line or the current directory +// if nothing was given. +recurse(process.argv.length > 3 ? process.argv[2] : '.'); diff --git a/node_modules/node-addon-api/tools/clang-format.js b/node_modules/node-addon-api/tools/clang-format.js new file mode 100644 index 0000000..e970983 --- /dev/null +++ b/node_modules/node-addon-api/tools/clang-format.js @@ -0,0 +1,67 @@ +#!/usr/bin/env node + +const spawn = require('child_process').spawnSync; +const path = require('path'); + +const filesToCheck = ['*.h', '*.cc']; +const CLANG_FORMAT_START = process.env.CLANG_FORMAT_START || 'main'; + +function main(args) { + let fix = false; + while (args.length > 0) { + switch (args[0]) { + case '-f': + case '--fix': + fix = true; + default: + } + args.shift(); + } + + let clangFormatPath = path.dirname(require.resolve('clang-format')); + const options = ['--binary=node_modules/.bin/clang-format', '--style=file']; + if (fix) { + options.push(CLANG_FORMAT_START); + } else { + options.push('--diff', CLANG_FORMAT_START); + } + + const gitClangFormatPath = path.join(clangFormatPath, + 'bin/git-clang-format'); + const result = spawn('python', [ + gitClangFormatPath, + ...options, + '--', + ...filesToCheck + ], { encoding: 'utf-8' }); + + if (result.stderr) { + console.error('Error running git-clang-format:', result.stderr); + return 2; + } + + const clangFormatOutput = result.stdout.trim(); + // Bail fast if in fix mode. + if (fix) { + console.log(clangFormatOutput); + return 0; + } + // Detect if there is any complains from clang-format + if (clangFormatOutput !== '' && + clangFormatOutput !== ('no modified files to format') && + clangFormatOutput !== ('clang-format did not modify any files')) { + console.error(clangFormatOutput); + const fixCmd = 'npm run lint:fix'; + console.error(` + ERROR: please run "${fixCmd}" to format changes in your commit + Note that when running the command locally, please keep your local + main branch and working branch up to date with nodejs/node-addon-api + to exclude un-related complains. + Or you can run "env CLANG_FORMAT_START=upstream/main ${fixCmd}".`); + return 1; + } +} + +if (require.main === module) { + process.exitCode = main(process.argv.slice(2)); +} diff --git a/node_modules/node-addon-api/tools/conversion.js b/node_modules/node-addon-api/tools/conversion.js new file mode 100644 index 0000000..5aef2c3 --- /dev/null +++ b/node_modules/node-addon-api/tools/conversion.js @@ -0,0 +1,309 @@ +#! /usr/bin/env node + +'use strict' + +const fs = require('fs'); +const path = require('path'); + +const args = process.argv.slice(2); +const dir = args[0]; +if (!dir) { + console.log('Usage: node ' + path.basename(__filename) + ' '); + process.exit(1); +} + +const NodeApiVersion = require('../package.json').version; + +const disable = args[1]; +if (disable != "--disable" && dir != "--disable") { + var ConfigFileOperations = { + 'package.json': [ + [ /([ ]*)"dependencies": {/g, '$1"dependencies": {\n$1 "node-addon-api": "' + NodeApiVersion + '",'], + [ /[ ]*"nan": *"[^"]+"(,|)[\n\r]/g, '' ] + ], + 'binding.gyp': [ + [ /([ ]*)'include_dirs': \[/g, '$1\'include_dirs\': [\n$1 \'\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {' ], + [ /Local\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);\s+(\w+)\.Reset\((\1)\);\s+\1->SetClassName\((Nan::String::New|Nan::New<(v8::)*String>)\("(.+?)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$6", {'], + [ /Local\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {' ], + [ /Nan::New\(([\w\d:]+)\)->GetFunction\(\)/g, 'Napi::Function::New(env, $1)' ], + [ /Nan::New\(([\w\d:]+)\)->GetFunction()/g, 'Napi::Function::New(env, $1);' ], + [ /Nan::New\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)' ], + [ /Nan::New\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)' ], + + // FunctionTemplate to FunctionReference + [ /Nan::Persistent<(v8::)*FunctionTemplate>/g, 'Napi::FunctionReference' ], + [ /Nan::Persistent<(v8::)*Function>/g, 'Napi::FunctionReference' ], + [ /v8::Local/g, 'Napi::FunctionReference' ], + [ /Local/g, 'Napi::FunctionReference' ], + [ /v8::FunctionTemplate/g, 'Napi::FunctionReference' ], + [ /FunctionTemplate/g, 'Napi::FunctionReference' ], + + + [ /([ ]*)Nan::SetPrototypeMethod\(\w+, "(\w+)", (\w+)\);/g, '$1InstanceMethod("$2", &$3),' ], + [ /([ ]*)(?:\w+\.Reset\(\w+\);\s+)?\(target\)\.Set\("(\w+)",\s*Nan::GetFunction\((\w+)\)\);/gm, + '});\n\n' + + '$1constructor = Napi::Persistent($3);\n' + + '$1constructor.SuppressDestruct();\n' + + '$1target.Set("$2", $3);' ], + + + // TODO: Other attribute combinations + [ /static_cast\(ReadOnly\s*\|\s*DontDelete\)/gm, + 'static_cast(napi_enumerable | napi_configurable)' ], + + [ /([\w\d:<>]+?)::Cast\((.+?)\)/g, '$2.As<$1>()' ], + + [ /\*Nan::Utf8String\(([^)]+)\)/g, '$1->As().Utf8Value().c_str()' ], + [ /Nan::Utf8String +(\w+)\(([^)]+)\)/g, 'std::string $1 = $2.As()' ], + [ /Nan::Utf8String/g, 'std::string' ], + + [ /v8::String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)' ], + [ /String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)' ], + [ /\.length\(\)/g, '.Length()' ], + + [ /Nan::MakeCallback\(([^,]+),[\s\\]+([^,]+),/gm, '$2.MakeCallback($1,' ], + + [ /class\s+(\w+)\s*:\s*public\s+Nan::ObjectWrap/g, 'class $1 : public Napi::ObjectWrap<$1>' ], + [ /(\w+)\(([^\)]*)\)\s*:\s*Nan::ObjectWrap\(\)\s*(,)?/gm, '$1($2) : Napi::ObjectWrap<$1>()$3' ], + + // HandleOKCallback to OnOK + [ /HandleOKCallback/g, 'OnOK' ], + // HandleErrorCallback to OnError + [ /HandleErrorCallback/g, 'OnError' ], + + // ex. .As() to .As() + [ /\.As\(\)/g, '.As()' ], + [ /\.As<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>\(\)/g, '.As()' ], + + // ex. Nan::New(info[0]) to Napi::Number::New(info[0]) + [ /Nan::New<(v8::)*Integer>\((.+?)\)/g, 'Napi::Number::New(env, $2)' ], + [ /Nan::New\(([0-9\.]+)\)/g, 'Napi::Number::New(env, $1)' ], + [ /Nan::New<(v8::)*String>\("(.+?)"\)/g, 'Napi::String::New(env, "$2")' ], + [ /Nan::New\("(.+?)"\)/g, 'Napi::String::New(env, "$1")' ], + [ /Nan::New<(v8::)*(.+?)>\(\)/g, 'Napi::$2::New(env)' ], + [ /Nan::New<(.+?)>\(\)/g, 'Napi::$1::New(env)' ], + [ /Nan::New<(v8::)*(.+?)>\(/g, 'Napi::$2::New(env, ' ], + [ /Nan::New<(.+?)>\(/g, 'Napi::$1::New(env, ' ], + [ /Nan::NewBuffer\(/g, 'Napi::Buffer::New(env, ' ], + // TODO: Properly handle this + [ /Nan::New\(/g, 'Napi::New(env, ' ], + + [ /\.IsInt32\(\)/g, '.IsNumber()' ], + [ /->IsInt32\(\)/g, '.IsNumber()' ], + + + [ /(.+?)->BooleanValue\(\)/g, '$1.As().Value()' ], + [ /(.+?)->Int32Value\(\)/g, '$1.As().Int32Value()' ], + [ /(.+?)->Uint32Value\(\)/g, '$1.As().Uint32Value()' ], + [ /(.+?)->IntegerValue\(\)/g, '$1.As().Int64Value()' ], + [ /(.+?)->NumberValue\(\)/g, '$1.As().DoubleValue()' ], + + // ex. Nan::To(info[0]) to info[0].Value() + [ /Nan::To\((.+?)\)/g, '$2.To()' ], + [ /Nan::To<(Boolean|String|Number|Object|Array|Symbol|Function)>\((.+?)\)/g, '$2.To()' ], + // ex. Nan::To(info[0]) to info[0].As().Value() + [ /Nan::To\((.+?)\)/g, '$1.As().Value()' ], + // ex. Nan::To(info[0]) to info[0].As().Int32Value() + [ /Nan::To\((.+?)\)/g, '$1.As().Int32Value()' ], + // ex. Nan::To(info[0]) to info[0].As().Int32Value() + [ /Nan::To\((.+?)\)/g, '$1.As().Int32Value()' ], + // ex. Nan::To(info[0]) to info[0].As().Uint32Value() + [ /Nan::To\((.+?)\)/g, '$1.As().Uint32Value()' ], + // ex. Nan::To(info[0]) to info[0].As().Int64Value() + [ /Nan::To\((.+?)\)/g, '$1.As().Int64Value()' ], + // ex. Nan::To(info[0]) to info[0].As().FloatValue() + [ /Nan::To\((.+?)\)/g, '$1.As().FloatValue()' ], + // ex. Nan::To(info[0]) to info[0].As().DoubleValue() + [ /Nan::To\((.+?)\)/g, '$1.As().DoubleValue()' ], + + [ /Nan::New\((\w+)\)->HasInstance\((\w+)\)/g, '$2.InstanceOf($1.Value())' ], + + [ /Nan::Has\(([^,]+),\s*/gm, '($1).Has(' ], + [ /\.Has\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Has($1)' ], + [ /\.Has\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Has($1)' ], + + [ /Nan::Get\(([^,]+),\s*/gm, '($1).Get(' ], + [ /\.Get\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Get($1)' ], + [ /\.Get\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Get($1)' ], + + [ /Nan::Set\(([^,]+),\s*/gm, '($1).Set(' ], + [ /\.Set\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\s*,/gm, '.Set($1,' ], + [ /\.Set\([\s|\\]*Nan::New\(([^)]+)\)\s*,/gm, '.Set($1,' ], + + + // ex. node::Buffer::HasInstance(info[0]) to info[0].IsBuffer() + [ /node::Buffer::HasInstance\((.+?)\)/g, '$1.IsBuffer()' ], + // ex. node::Buffer::Length(info[0]) to info[0].Length() + [ /node::Buffer::Length\((.+?)\)/g, '$1.As>().Length()' ], + // ex. node::Buffer::Data(info[0]) to info[0].Data() + [ /node::Buffer::Data\((.+?)\)/g, '$1.As>().Data()' ], + [ /Nan::CopyBuffer\(/g, 'Napi::Buffer::Copy(env, ' ], + + // Nan::AsyncQueueWorker(worker) + [ /Nan::AsyncQueueWorker\((.+)\);/g, '$1.Queue();' ], + [ /Nan::(Undefined|Null|True|False)\(\)/g, 'env.$1()' ], + + // Nan::ThrowError(error) to Napi::Error::New(env, error).ThrowAsJavaScriptException() + [ /([ ]*)return Nan::Throw(\w*?)Error\((.+?)\);/g, '$1Napi::$2Error::New(env, $3).ThrowAsJavaScriptException();\n$1return env.Null();' ], + [ /Nan::Throw(\w*?)Error\((.+?)\);\n(\s*)return;/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n$3return env.Null();' ], + [ /Nan::Throw(\w*?)Error\((.+?)\);/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n' ], + // Nan::RangeError(error) to Napi::RangeError::New(env, error) + [ /Nan::(\w*?)Error\((.+)\)/g, 'Napi::$1Error::New(env, $2)' ], + + [ /Nan::Set\((.+?),\n* *(.+?),\n* *(.+?),\n* *(.+?)\)/g, '$1.Set($2, $3, $4)' ], + + [ /Nan::(Escapable)?HandleScope\s+(\w+)\s*;/g, 'Napi::$1HandleScope $2(env);' ], + [ /Nan::(Escapable)?HandleScope/g, 'Napi::$1HandleScope' ], + [ /Nan::ForceSet\(([^,]+), ?/g, '$1->DefineProperty(' ], + [ /\.ForceSet\(Napi::String::New\(env, "(\w+)"\),\s*?/g, '.DefineProperty("$1", ' ], + // [ /Nan::GetPropertyNames\(([^,]+)\)/, '$1->GetPropertyNames()' ], + [ /Nan::Equals\(([^,]+),/g, '$1.StrictEquals(' ], + + + [ /(.+)->Set\(/g, '$1.Set\(' ], + + + [ /Nan::Callback/g, 'Napi::FunctionReference' ], + + + [ /Nan::Persistent/g, 'Napi::ObjectReference' ], + [ /Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target/g, 'Napi::Env& env, Napi::Object& target' ], + + [ /(\w+)\*\s+(\w+)\s*=\s*Nan::ObjectWrap::Unwrap<\w+>\(info\.This\(\)\);/g, '$1* $2 = this;' ], + [ /Nan::ObjectWrap::Unwrap<(\w+)>\((.*)\);/g, '$2.Unwrap<$1>();' ], + + [ /Nan::NAN_METHOD_RETURN_TYPE/g, 'void' ], + [ /NAN_INLINE/g, 'inline' ], + + [ /Nan::NAN_METHOD_ARGS_TYPE/g, 'const Napi::CallbackInfo&' ], + [ /NAN_METHOD\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], + [ /static\s*NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)' ], + [ /NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)' ], + [ /static\s*NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)' ], + [ /NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)' ], + [ /void Init\((v8::)*Local<(v8::)*Object> exports\)/g, 'Napi::Object Init(Napi::Env env, Napi::Object exports)' ], + [ /NAN_MODULE_INIT\(([\w\d:]+?)\);/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports);' ], + [ /NAN_MODULE_INIT\(([\w\d:]+?)\)/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports)' ], + + + [ /::(Init(?:ialize)?)\(target\)/g, '::$1(env, target, module)' ], + [ /constructor_template/g, 'constructor' ], + + [ /Nan::FunctionCallbackInfo<(v8::)?Value>[ ]*& [ ]*info\)[ ]*{\n*([ ]*)/gm, 'Napi::CallbackInfo& info) {\n$2Napi::Env env = info.Env();\n$2' ], + [ /Nan::FunctionCallbackInfo<(v8::)*Value>\s*&\s*info\);/g, 'Napi::CallbackInfo& info);' ], + [ /Nan::FunctionCallbackInfo<(v8::)*Value>\s*&/g, 'Napi::CallbackInfo&' ], + + [ /Buffer::HasInstance\(([^)]+)\)/g, '$1.IsBuffer()' ], + + [ /info\[(\d+)\]->/g, 'info[$1].' ], + [ /info\[([\w\d]+)\]->/g, 'info[$1].' ], + [ /info\.This\(\)->/g, 'info.This().' ], + [ /->Is(Object|String|Int32|Number)\(\)/g, '.Is$1()' ], + [ /info.GetReturnValue\(\).SetUndefined\(\)/g, 'return env.Undefined()' ], + [ /info\.GetReturnValue\(\)\.Set\(((\n|.)+?)\);/g, 'return $1;' ], + + + // ex. Local to Napi::Value + [ /v8::Local/g, 'Napi::$1' ], + [ /Local<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>/g, 'Napi::$1' ], + + // Declare an env in helper functions that take a Napi::Value + [ /(\w+)\(Napi::Value (\w+)(,\s*[^\()]+)?\)\s*{\n*([ ]*)/gm, '$1(Napi::Value $2$3) {\n$4Napi::Env env = $2.Env();\n$4' ], + + // delete #include and/or + [ /#include +(<|")(?:node|nan).h("|>)/g, "#include $1napi.h$2\n#include $1uv.h$2" ], + // NODE_MODULE to NODE_API_MODULE + [ /NODE_MODULE/g, 'NODE_API_MODULE' ], + [ /Nan::/g, 'Napi::' ], + [ /nan.h/g, 'napi.h' ], + + // delete .FromJust() + [ /\.FromJust\(\)/g, '' ], + // delete .ToLocalCheck() + [ /\.ToLocalChecked\(\)/g, '' ], + [ /^.*->SetInternalFieldCount\(.*$/gm, '' ], + + // replace using node; and/or using v8; to using Napi; + [ /using (node|v8);/g, 'using Napi;' ], + [ /using namespace (node|Nan|v8);/g, 'using namespace Napi;' ], + // delete using v8::Local; + [ /using v8::Local;\n/g, '' ], + // replace using v8::XXX; with using Napi::XXX + [ /using v8::([A-Za-z]+);/g, 'using Napi::$1;' ], + +]; + +var paths = listFiles(dir); +paths.forEach(function(dirEntry) { + var filename = dirEntry.split('\\').pop().split('/').pop(); + + // Check whether the file is a source file or a config file + // then execute function accordingly + var sourcePattern = /.+\.h|.+\.cc|.+\.cpp/; + if (sourcePattern.test(filename)) { + convertFile(dirEntry, SourceFileOperations); + } else if (ConfigFileOperations[filename] != null) { + convertFile(dirEntry, ConfigFileOperations[filename]); + } +}); + +function listFiles(dir, filelist) { + var files = fs.readdirSync(dir); + filelist = filelist || []; + files.forEach(function(file) { + if (file === 'node_modules') { + return + } + + if (fs.statSync(path.join(dir, file)).isDirectory()) { + filelist = listFiles(path.join(dir, file), filelist); + } else { + filelist.push(path.join(dir, file)); + } + }); + return filelist; +} + +function convert(content, operations) { + for (let i = 0; i < operations.length; i ++) { + let operation = operations[i]; + content = content.replace(operation[0], operation[1]); + } + return content; +} + +function convertFile(fileName, operations) { + fs.readFile(fileName, "utf-8", function (err, file) { + if (err) throw err; + + file = convert(file, operations); + + fs.writeFile(fileName, file, function(err){ + if (err) throw err; + }); + }); +} diff --git a/node_modules/node-fetch/LICENSE.md b/node_modules/node-fetch/LICENSE.md new file mode 100644 index 0000000..660ffec --- /dev/null +++ b/node_modules/node-fetch/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 David Frank + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/node-fetch/README.md b/node_modules/node-fetch/README.md new file mode 100644 index 0000000..2dde742 --- /dev/null +++ b/node_modules/node-fetch/README.md @@ -0,0 +1,590 @@ +node-fetch +========== + +[![npm version][npm-image]][npm-url] +[![build status][travis-image]][travis-url] +[![coverage status][codecov-image]][codecov-url] +[![install size][install-size-image]][install-size-url] +[![Discord][discord-image]][discord-url] + +A light-weight module that brings `window.fetch` to Node.js + +(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) + +[![Backers][opencollective-image]][opencollective-url] + + + +- [Motivation](#motivation) +- [Features](#features) +- [Difference from client-side fetch](#difference-from-client-side-fetch) +- [Installation](#installation) +- [Loading and configuring the module](#loading-and-configuring-the-module) +- [Common Usage](#common-usage) + - [Plain text or HTML](#plain-text-or-html) + - [JSON](#json) + - [Simple Post](#simple-post) + - [Post with JSON](#post-with-json) + - [Post with form parameters](#post-with-form-parameters) + - [Handling exceptions](#handling-exceptions) + - [Handling client and server errors](#handling-client-and-server-errors) +- [Advanced Usage](#advanced-usage) + - [Streams](#streams) + - [Buffer](#buffer) + - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) + - [Extract Set-Cookie Header](#extract-set-cookie-header) + - [Post data using a file stream](#post-data-using-a-file-stream) + - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart) + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) +- [API](#api) + - [fetch(url[, options])](#fetchurl-options) + - [Options](#options) + - [Class: Request](#class-request) + - [Class: Response](#class-response) + - [Class: Headers](#class-headers) + - [Interface: Body](#interface-body) + - [Class: FetchError](#class-fetcherror) +- [License](#license) +- [Acknowledgement](#acknowledgement) + + + +## Motivation + +Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. + +See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). + +## Features + +- Stay consistent with `window.fetch` API. +- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. +- Use native promise but allow substituting it with [insert your favorite promise library]. +- Use native Node streams for body on both request and response. +- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. +- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. + +## Difference from client-side fetch + +- See [Known Differences](LIMITS.md) for details. +- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. +- Pull requests are welcomed too! + +## Installation + +Current stable release (`2.x`) + +```sh +$ npm install node-fetch +``` + +## Loading and configuring the module +We suggest you load the module via `require` until the stabilization of ES modules in node: +```js +const fetch = require('node-fetch'); +``` + +If you are using a Promise library other than native, set it through `fetch.Promise`: +```js +const Bluebird = require('bluebird'); + +fetch.Promise = Bluebird; +``` + +## Common Usage + +NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. + +#### Plain text or HTML +```js +fetch('https://github.com/') + .then(res => res.text()) + .then(body => console.log(body)); +``` + +#### JSON + +```js + +fetch('https://api.github.com/users/github') + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Simple Post +```js +fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) + .then(res => res.json()) // expecting a json response + .then(json => console.log(json)); +``` + +#### Post with JSON + +```js +const body = { a: 1 }; + +fetch('https://httpbin.org/post', { + method: 'post', + body: JSON.stringify(body), + headers: { 'Content-Type': 'application/json' }, + }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form parameters +`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. + +NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: + +```js +const { URLSearchParams } = require('url'); + +const params = new URLSearchParams(); +params.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: params }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Handling exceptions +NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. + +Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. + +```js +fetch('https://domain.invalid/') + .catch(err => console.error(err)); +``` + +#### Handling client and server errors +It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: + +```js +function checkStatus(res) { + if (res.ok) { // res.status >= 200 && res.status < 300 + return res; + } else { + throw MyCustomError(res.statusText); + } +} + +fetch('https://httpbin.org/status/400') + .then(checkStatus) + .then(res => console.log('will not get here...')) +``` + +## Advanced Usage + +#### Streams +The "Node.js way" is to use streams when possible: + +```js +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => { + const dest = fs.createWriteStream('./octocat.png'); + res.body.pipe(dest); + }); +``` + +#### Buffer +If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) + +```js +const fileType = require('file-type'); + +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => res.buffer()) + .then(buffer => fileType(buffer)) + .then(type => { /* ... */ }); +``` + +#### Accessing Headers and other Meta data +```js +fetch('https://github.com/') + .then(res => { + console.log(res.ok); + console.log(res.status); + console.log(res.statusText); + console.log(res.headers.raw()); + console.log(res.headers.get('content-type')); + }); +``` + +#### Extract Set-Cookie Header + +Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. + +```js +fetch(url).then(res => { + // returns an array of values, instead of a string of comma-separated values + console.log(res.headers.raw()['set-cookie']); +}); +``` + +#### Post data using a file stream + +```js +const { createReadStream } = require('fs'); + +const stream = createReadStream('input.txt'); + +fetch('https://httpbin.org/post', { method: 'POST', body: stream }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form-data (detect multipart) + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: form }) + .then(res => res.json()) + .then(json => console.log(json)); + +// OR, using custom headers +// NOTE: getHeaders() is non-standard API + +const form = new FormData(); +form.append('a', 1); + +const options = { + method: 'POST', + body: form, + headers: form.getHeaders() +} + +fetch('https://httpbin.org/post', options) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Request cancellation with AbortSignal + +> NOTE: You may cancel streamed requests only on Node >= v8.0.0 + +You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). + +An example of timing out a request after 150ms could be achieved as the following: + +```js +import AbortController from 'abort-controller'; + +const controller = new AbortController(); +const timeout = setTimeout( + () => { controller.abort(); }, + 150, +); + +fetch(url, { signal: controller.signal }) + .then(res => res.json()) + .then( + data => { + useData(data) + }, + err => { + if (err.name === 'AbortError') { + // request was aborted + } + }, + ) + .finally(() => { + clearTimeout(timeout); + }); +``` + +See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples. + + +## API + +### fetch(url[, options]) + +- `url` A string representing the URL for fetching +- `options` [Options](#fetch-options) for the HTTP(S) request +- Returns: Promise<[Response](#class-response)> + +Perform an HTTP(S) fetch. + +`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. + + +### Options + +The default values are shown after each option key. + +```js +{ + // These properties are part of the Fetch Standard + method: 'GET', + headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) + body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream + redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect + signal: null, // pass an instance of AbortSignal to optionally abort requests + + // The following properties are node-fetch extensions + follow: 20, // maximum redirect count. 0 to not follow redirect + timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. + compress: true, // support gzip/deflate content encoding. false to disable + size: 0, // maximum response body size in bytes. 0 to disable + agent: null // http(s).Agent instance or function that returns an instance (see below) +} +``` + +##### Default Headers + +If no values are set, the following request headers will be sent automatically: + +Header | Value +------------------- | -------------------------------------------------------- +`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ +`Accept` | `*/*` +`Connection` | `close` _(when no `options.agent` is present)_ +`Content-Length` | _(automatically calculated, if possible)_ +`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ +`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` + +Note: when `body` is a `Stream`, `Content-Length` is not set automatically. + +##### Custom Agent + +The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: + +- Support self-signed certificate +- Use only IPv4 or IPv6 +- Custom DNS Lookup + +See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. + +In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. + +```js +const httpAgent = new http.Agent({ + keepAlive: true +}); +const httpsAgent = new https.Agent({ + keepAlive: true +}); + +const options = { + agent: function (_parsedURL) { + if (_parsedURL.protocol == 'http:') { + return httpAgent; + } else { + return httpsAgent; + } + } +} +``` + + +### Class: Request + +An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. + +Due to the nature of Node.js, the following properties are not implemented at this moment: + +- `type` +- `destination` +- `referrer` +- `referrerPolicy` +- `mode` +- `credentials` +- `cache` +- `integrity` +- `keepalive` + +The following node-fetch extension properties are provided: + +- `follow` +- `compress` +- `counter` +- `agent` + +See [options](#fetch-options) for exact meaning of these extensions. + +#### new Request(input[, options]) + +*(spec-compliant)* + +- `input` A string representing a URL, or another `Request` (which will be cloned) +- `options` [Options][#fetch-options] for the HTTP(S) request + +Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). + +In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. + + +### Class: Response + +An HTTP(S) response. This class implements the [Body](#iface-body) interface. + +The following properties are not implemented in node-fetch at this moment: + +- `Response.error()` +- `Response.redirect()` +- `type` +- `trailer` + +#### new Response([body[, options]]) + +*(spec-compliant)* + +- `body` A `String` or [`Readable` stream][node-readable] +- `options` A [`ResponseInit`][response-init] options dictionary + +Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). + +Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. + +#### response.ok + +*(spec-compliant)* + +Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. + +#### response.redirected + +*(spec-compliant)* + +Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. + + +### Class: Headers + +This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. + +#### new Headers([init]) + +*(spec-compliant)* + +- `init` Optional argument to pre-fill the `Headers` object + +Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. + +```js +// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class + +const meta = { + 'Content-Type': 'text/xml', + 'Breaking-Bad': '<3' +}; +const headers = new Headers(meta); + +// The above is equivalent to +const meta = [ + [ 'Content-Type', 'text/xml' ], + [ 'Breaking-Bad', '<3' ] +]; +const headers = new Headers(meta); + +// You can in fact use any iterable objects, like a Map or even another Headers +const meta = new Map(); +meta.set('Content-Type', 'text/xml'); +meta.set('Breaking-Bad', '<3'); +const headers = new Headers(meta); +const copyOfHeaders = new Headers(headers); +``` + + +### Interface: Body + +`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. + +The following methods are not yet implemented in node-fetch at this moment: + +- `formData()` + +#### body.body + +*(deviation from spec)* + +* Node.js [`Readable` stream][node-readable] + +Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. + +#### body.bodyUsed + +*(spec-compliant)* + +* `Boolean` + +A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. + +#### body.arrayBuffer() +#### body.blob() +#### body.json() +#### body.text() + +*(spec-compliant)* + +* Returns: Promise + +Consume the body and return a promise that will resolve to one of these formats. + +#### body.buffer() + +*(node-fetch extension)* + +* Returns: Promise<Buffer> + +Consume the body and return a promise that will resolve to a Buffer. + +#### body.textConverted() + +*(node-fetch extension)* + +* Returns: Promise<String> + +Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. + +(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) + + +### Class: FetchError + +*(node-fetch extension)* + +An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. + + +### Class: AbortError + +*(node-fetch extension)* + +An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. + +## Acknowledgement + +Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. + +`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). + +## License + +MIT + +[npm-image]: https://flat.badgen.net/npm/v/node-fetch +[npm-url]: https://www.npmjs.com/package/node-fetch +[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch +[travis-url]: https://travis-ci.org/bitinn/node-fetch +[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master +[codecov-url]: https://codecov.io/gh/bitinn/node-fetch +[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch +[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch +[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square +[discord-url]: https://discord.gg/Zxbndcm +[opencollective-image]: https://opencollective.com/node-fetch/backers.svg +[opencollective-url]: https://opencollective.com/node-fetch +[whatwg-fetch]: https://fetch.spec.whatwg.org/ +[response-init]: https://fetch.spec.whatwg.org/#responseinit +[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams +[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers +[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md +[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md +[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md diff --git a/node_modules/node-fetch/browser.js b/node_modules/node-fetch/browser.js new file mode 100644 index 0000000..83c54c5 --- /dev/null +++ b/node_modules/node-fetch/browser.js @@ -0,0 +1,25 @@ +"use strict"; + +// ref: https://github.com/tc39/proposal-global +var getGlobal = function () { + // the only reliable means to get the global object is + // `Function('return this')()` + // However, this causes CSP violations in Chrome apps. + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof global !== 'undefined') { return global; } + throw new Error('unable to locate global object'); +} + +var global = getGlobal(); + +module.exports = exports = global.fetch; + +// Needed for TypeScript and Webpack. +if (global.fetch) { + exports.default = global.fetch.bind(global); +} + +exports.Headers = global.Headers; +exports.Request = global.Request; +exports.Response = global.Response; \ No newline at end of file diff --git a/node_modules/node-fetch/lib/index.es.js b/node_modules/node-fetch/lib/index.es.js new file mode 100644 index 0000000..79f70d3 --- /dev/null +++ b/node_modules/node-fetch/lib/index.es.js @@ -0,0 +1,1662 @@ +process.emitWarning("The .es.js file is deprecated. Use .mjs instead."); + +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; +const resolve_url = Url.resolve; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError }; diff --git a/node_modules/node-fetch/lib/index.js b/node_modules/node-fetch/lib/index.js new file mode 100644 index 0000000..45d3985 --- /dev/null +++ b/node_modules/node-fetch/lib/index.js @@ -0,0 +1,1671 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(require('stream')); +var http = _interopDefault(require('http')); +var Url = _interopDefault(require('url')); +var whatwgUrl = _interopDefault(require('whatwg-url')); +var https = _interopDefault(require('https')); +var zlib = _interopDefault(require('zlib')); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; +const resolve_url = Url.resolve; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; diff --git a/node_modules/node-fetch/lib/index.mjs b/node_modules/node-fetch/lib/index.mjs new file mode 100644 index 0000000..31260e5 --- /dev/null +++ b/node_modules/node-fetch/lib/index.mjs @@ -0,0 +1,1660 @@ +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; +const resolve_url = Url.resolve; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError }; diff --git a/node_modules/node-fetch/node_modules/tr46/.npmignore b/node_modules/node-fetch/node_modules/tr46/.npmignore new file mode 100644 index 0000000..96e9161 --- /dev/null +++ b/node_modules/node-fetch/node_modules/tr46/.npmignore @@ -0,0 +1,4 @@ +scripts/ +test/ + +!lib/mapping_table.json diff --git a/node_modules/node-fetch/node_modules/tr46/index.js b/node_modules/node-fetch/node_modules/tr46/index.js new file mode 100644 index 0000000..9ce12ca --- /dev/null +++ b/node_modules/node-fetch/node_modules/tr46/index.js @@ -0,0 +1,193 @@ +"use strict"; + +var punycode = require("punycode"); +var mappingTable = require("./lib/mappingTable.json"); + +var PROCESSING_OPTIONS = { + TRANSITIONAL: 0, + NONTRANSITIONAL: 1 +}; + +function normalize(str) { // fix bug in v8 + return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); +} + +function findStatus(val) { + var start = 0; + var end = mappingTable.length - 1; + + while (start <= end) { + var mid = Math.floor((start + end) / 2); + + var target = mappingTable[mid]; + if (target[0][0] <= val && target[0][1] >= val) { + return target; + } else if (target[0][0] > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return null; +} + +var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + +function countSymbols(string) { + return string + // replace every surrogate pair with a BMP symbol + .replace(regexAstralSymbols, '_') + // then get the length + .length; +} + +function mapChars(domain_name, useSTD3, processing_option) { + var hasError = false; + var processed = ""; + + var len = countSymbols(domain_name); + for (var i = 0; i < len; ++i) { + var codePoint = domain_name.codePointAt(i); + var status = findStatus(codePoint); + + switch (status[1]) { + case "disallowed": + hasError = true; + processed += String.fromCodePoint(codePoint); + break; + case "ignored": + break; + case "mapped": + processed += String.fromCodePoint.apply(String, status[2]); + break; + case "deviation": + if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { + processed += String.fromCodePoint.apply(String, status[2]); + } else { + processed += String.fromCodePoint(codePoint); + } + break; + case "valid": + processed += String.fromCodePoint(codePoint); + break; + case "disallowed_STD3_mapped": + if (useSTD3) { + hasError = true; + processed += String.fromCodePoint(codePoint); + } else { + processed += String.fromCodePoint.apply(String, status[2]); + } + break; + case "disallowed_STD3_valid": + if (useSTD3) { + hasError = true; + } + + processed += String.fromCodePoint(codePoint); + break; + } + } + + return { + string: processed, + error: hasError + }; +} + +var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; + +function validateLabel(label, processing_option) { + if (label.substr(0, 4) === "xn--") { + label = punycode.toUnicode(label); + processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; + } + + var error = false; + + if (normalize(label) !== label || + (label[3] === "-" && label[4] === "-") || + label[0] === "-" || label[label.length - 1] === "-" || + label.indexOf(".") !== -1 || + label.search(combiningMarksRegex) === 0) { + error = true; + } + + var len = countSymbols(label); + for (var i = 0; i < len; ++i) { + var status = findStatus(label.codePointAt(i)); + if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || + (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && + status[1] !== "valid" && status[1] !== "deviation")) { + error = true; + break; + } + } + + return { + label: label, + error: error + }; +} + +function processing(domain_name, useSTD3, processing_option) { + var result = mapChars(domain_name, useSTD3, processing_option); + result.string = normalize(result.string); + + var labels = result.string.split("."); + for (var i = 0; i < labels.length; ++i) { + try { + var validation = validateLabel(labels[i]); + labels[i] = validation.label; + result.error = result.error || validation.error; + } catch(e) { + result.error = true; + } + } + + return { + string: labels.join("."), + error: result.error + }; +} + +module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { + var result = processing(domain_name, useSTD3, processing_option); + var labels = result.string.split("."); + labels = labels.map(function(l) { + try { + return punycode.toASCII(l); + } catch(e) { + result.error = true; + return l; + } + }); + + if (verifyDnsLength) { + var total = labels.slice(0, labels.length - 1).join(".").length; + if (total.length > 253 || total.length === 0) { + result.error = true; + } + + for (var i=0; i < labels.length; ++i) { + if (labels.length > 63 || labels.length === 0) { + result.error = true; + break; + } + } + } + + if (result.error) return null; + return labels.join("."); +}; + +module.exports.toUnicode = function(domain_name, useSTD3) { + var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); + + return { + domain: result.string, + error: result.error + }; +}; + +module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; diff --git a/node_modules/node-fetch/node_modules/tr46/lib/.gitkeep b/node_modules/node-fetch/node_modules/tr46/lib/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/node-fetch/node_modules/tr46/lib/mappingTable.json b/node_modules/node-fetch/node_modules/tr46/lib/mappingTable.json new file mode 100644 index 0000000..89cf19a --- /dev/null +++ b/node_modules/node-fetch/node_modules/tr46/lib/mappingTable.json @@ -0,0 +1 @@ +[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",[108,183]],[[321,321],"mapped",[322]],[[322,322],"valid"],[[323,323],"mapped",[324]],[[324,324],"valid"],[[325,325],"mapped",[326]],[[326,326],"valid"],[[327,327],"mapped",[328]],[[328,328],"valid"],[[329,329],"mapped",[700,110]],[[330,330],"mapped",[331]],[[331,331],"valid"],[[332,332],"mapped",[333]],[[333,333],"valid"],[[334,334],"mapped",[335]],[[335,335],"valid"],[[336,336],"mapped",[337]],[[337,337],"valid"],[[338,338],"mapped",[339]],[[339,339],"valid"],[[340,340],"mapped",[341]],[[341,341],"valid"],[[342,342],"mapped",[343]],[[343,343],"valid"],[[344,344],"mapped",[345]],[[345,345],"valid"],[[346,346],"mapped",[347]],[[347,347],"valid"],[[348,348],"mapped",[349]],[[349,349],"valid"],[[350,350],"mapped",[351]],[[351,351],"valid"],[[352,352],"mapped",[353]],[[353,353],"valid"],[[354,354],"mapped",[355]],[[355,355],"valid"],[[356,356],"mapped",[357]],[[357,357],"valid"],[[358,358],"mapped",[359]],[[359,359],"valid"],[[360,360],"mapped",[361]],[[361,361],"valid"],[[362,362],"mapped",[363]],[[363,363],"valid"],[[364,364],"mapped",[365]],[[365,365],"valid"],[[366,366],"mapped",[367]],[[367,367],"valid"],[[368,368],"mapped",[369]],[[369,369],"valid"],[[370,370],"mapped",[371]],[[371,371],"valid"],[[372,372],"mapped",[373]],[[373,373],"valid"],[[374,374],"mapped",[375]],[[375,375],"valid"],[[376,376],"mapped",[255]],[[377,377],"mapped",[378]],[[378,378],"valid"],[[379,379],"mapped",[380]],[[380,380],"valid"],[[381,381],"mapped",[382]],[[382,382],"valid"],[[383,383],"mapped",[115]],[[384,384],"valid"],[[385,385],"mapped",[595]],[[386,386],"mapped",[387]],[[387,387],"valid"],[[388,388],"mapped",[389]],[[389,389],"valid"],[[390,390],"mapped",[596]],[[391,391],"mapped",[392]],[[392,392],"valid"],[[393,393],"mapped",[598]],[[394,394],"mapped",[599]],[[395,395],"mapped",[396]],[[396,397],"valid"],[[398,398],"mapped",[477]],[[399,399],"mapped",[601]],[[400,400],"mapped",[603]],[[401,401],"mapped",[402]],[[402,402],"valid"],[[403,403],"mapped",[608]],[[404,404],"mapped",[611]],[[405,405],"valid"],[[406,406],"mapped",[617]],[[407,407],"mapped",[616]],[[408,408],"mapped",[409]],[[409,411],"valid"],[[412,412],"mapped",[623]],[[413,413],"mapped",[626]],[[414,414],"valid"],[[415,415],"mapped",[629]],[[416,416],"mapped",[417]],[[417,417],"valid"],[[418,418],"mapped",[419]],[[419,419],"valid"],[[420,420],"mapped",[421]],[[421,421],"valid"],[[422,422],"mapped",[640]],[[423,423],"mapped",[424]],[[424,424],"valid"],[[425,425],"mapped",[643]],[[426,427],"valid"],[[428,428],"mapped",[429]],[[429,429],"valid"],[[430,430],"mapped",[648]],[[431,431],"mapped",[432]],[[432,432],"valid"],[[433,433],"mapped",[650]],[[434,434],"mapped",[651]],[[435,435],"mapped",[436]],[[436,436],"valid"],[[437,437],"mapped",[438]],[[438,438],"valid"],[[439,439],"mapped",[658]],[[440,440],"mapped",[441]],[[441,443],"valid"],[[444,444],"mapped",[445]],[[445,451],"valid"],[[452,454],"mapped",[100,382]],[[455,457],"mapped",[108,106]],[[458,460],"mapped",[110,106]],[[461,461],"mapped",[462]],[[462,462],"valid"],[[463,463],"mapped",[464]],[[464,464],"valid"],[[465,465],"mapped",[466]],[[466,466],"valid"],[[467,467],"mapped",[468]],[[468,468],"valid"],[[469,469],"mapped",[470]],[[470,470],"valid"],[[471,471],"mapped",[472]],[[472,472],"valid"],[[473,473],"mapped",[474]],[[474,474],"valid"],[[475,475],"mapped",[476]],[[476,477],"valid"],[[478,478],"mapped",[479]],[[479,479],"valid"],[[480,480],"mapped",[481]],[[481,481],"valid"],[[482,482],"mapped",[483]],[[483,483],"valid"],[[484,484],"mapped",[485]],[[485,485],"valid"],[[486,486],"mapped",[487]],[[487,487],"valid"],[[488,488],"mapped",[489]],[[489,489],"valid"],[[490,490],"mapped",[491]],[[491,491],"valid"],[[492,492],"mapped",[493]],[[493,493],"valid"],[[494,494],"mapped",[495]],[[495,496],"valid"],[[497,499],"mapped",[100,122]],[[500,500],"mapped",[501]],[[501,501],"valid"],[[502,502],"mapped",[405]],[[503,503],"mapped",[447]],[[504,504],"mapped",[505]],[[505,505],"valid"],[[506,506],"mapped",[507]],[[507,507],"valid"],[[508,508],"mapped",[509]],[[509,509],"valid"],[[510,510],"mapped",[511]],[[511,511],"valid"],[[512,512],"mapped",[513]],[[513,513],"valid"],[[514,514],"mapped",[515]],[[515,515],"valid"],[[516,516],"mapped",[517]],[[517,517],"valid"],[[518,518],"mapped",[519]],[[519,519],"valid"],[[520,520],"mapped",[521]],[[521,521],"valid"],[[522,522],"mapped",[523]],[[523,523],"valid"],[[524,524],"mapped",[525]],[[525,525],"valid"],[[526,526],"mapped",[527]],[[527,527],"valid"],[[528,528],"mapped",[529]],[[529,529],"valid"],[[530,530],"mapped",[531]],[[531,531],"valid"],[[532,532],"mapped",[533]],[[533,533],"valid"],[[534,534],"mapped",[535]],[[535,535],"valid"],[[536,536],"mapped",[537]],[[537,537],"valid"],[[538,538],"mapped",[539]],[[539,539],"valid"],[[540,540],"mapped",[541]],[[541,541],"valid"],[[542,542],"mapped",[543]],[[543,543],"valid"],[[544,544],"mapped",[414]],[[545,545],"valid"],[[546,546],"mapped",[547]],[[547,547],"valid"],[[548,548],"mapped",[549]],[[549,549],"valid"],[[550,550],"mapped",[551]],[[551,551],"valid"],[[552,552],"mapped",[553]],[[553,553],"valid"],[[554,554],"mapped",[555]],[[555,555],"valid"],[[556,556],"mapped",[557]],[[557,557],"valid"],[[558,558],"mapped",[559]],[[559,559],"valid"],[[560,560],"mapped",[561]],[[561,561],"valid"],[[562,562],"mapped",[563]],[[563,563],"valid"],[[564,566],"valid"],[[567,569],"valid"],[[570,570],"mapped",[11365]],[[571,571],"mapped",[572]],[[572,572],"valid"],[[573,573],"mapped",[410]],[[574,574],"mapped",[11366]],[[575,576],"valid"],[[577,577],"mapped",[578]],[[578,578],"valid"],[[579,579],"mapped",[384]],[[580,580],"mapped",[649]],[[581,581],"mapped",[652]],[[582,582],"mapped",[583]],[[583,583],"valid"],[[584,584],"mapped",[585]],[[585,585],"valid"],[[586,586],"mapped",[587]],[[587,587],"valid"],[[588,588],"mapped",[589]],[[589,589],"valid"],[[590,590],"mapped",[591]],[[591,591],"valid"],[[592,680],"valid"],[[681,685],"valid"],[[686,687],"valid"],[[688,688],"mapped",[104]],[[689,689],"mapped",[614]],[[690,690],"mapped",[106]],[[691,691],"mapped",[114]],[[692,692],"mapped",[633]],[[693,693],"mapped",[635]],[[694,694],"mapped",[641]],[[695,695],"mapped",[119]],[[696,696],"mapped",[121]],[[697,705],"valid"],[[706,709],"valid",[],"NV8"],[[710,721],"valid"],[[722,727],"valid",[],"NV8"],[[728,728],"disallowed_STD3_mapped",[32,774]],[[729,729],"disallowed_STD3_mapped",[32,775]],[[730,730],"disallowed_STD3_mapped",[32,778]],[[731,731],"disallowed_STD3_mapped",[32,808]],[[732,732],"disallowed_STD3_mapped",[32,771]],[[733,733],"disallowed_STD3_mapped",[32,779]],[[734,734],"valid",[],"NV8"],[[735,735],"valid",[],"NV8"],[[736,736],"mapped",[611]],[[737,737],"mapped",[108]],[[738,738],"mapped",[115]],[[739,739],"mapped",[120]],[[740,740],"mapped",[661]],[[741,745],"valid",[],"NV8"],[[746,747],"valid",[],"NV8"],[[748,748],"valid"],[[749,749],"valid",[],"NV8"],[[750,750],"valid"],[[751,767],"valid",[],"NV8"],[[768,831],"valid"],[[832,832],"mapped",[768]],[[833,833],"mapped",[769]],[[834,834],"valid"],[[835,835],"mapped",[787]],[[836,836],"mapped",[776,769]],[[837,837],"mapped",[953]],[[838,846],"valid"],[[847,847],"ignored"],[[848,855],"valid"],[[856,860],"valid"],[[861,863],"valid"],[[864,865],"valid"],[[866,866],"valid"],[[867,879],"valid"],[[880,880],"mapped",[881]],[[881,881],"valid"],[[882,882],"mapped",[883]],[[883,883],"valid"],[[884,884],"mapped",[697]],[[885,885],"valid"],[[886,886],"mapped",[887]],[[887,887],"valid"],[[888,889],"disallowed"],[[890,890],"disallowed_STD3_mapped",[32,953]],[[891,893],"valid"],[[894,894],"disallowed_STD3_mapped",[59]],[[895,895],"mapped",[1011]],[[896,899],"disallowed"],[[900,900],"disallowed_STD3_mapped",[32,769]],[[901,901],"disallowed_STD3_mapped",[32,776,769]],[[902,902],"mapped",[940]],[[903,903],"mapped",[183]],[[904,904],"mapped",[941]],[[905,905],"mapped",[942]],[[906,906],"mapped",[943]],[[907,907],"disallowed"],[[908,908],"mapped",[972]],[[909,909],"disallowed"],[[910,910],"mapped",[973]],[[911,911],"mapped",[974]],[[912,912],"valid"],[[913,913],"mapped",[945]],[[914,914],"mapped",[946]],[[915,915],"mapped",[947]],[[916,916],"mapped",[948]],[[917,917],"mapped",[949]],[[918,918],"mapped",[950]],[[919,919],"mapped",[951]],[[920,920],"mapped",[952]],[[921,921],"mapped",[953]],[[922,922],"mapped",[954]],[[923,923],"mapped",[955]],[[924,924],"mapped",[956]],[[925,925],"mapped",[957]],[[926,926],"mapped",[958]],[[927,927],"mapped",[959]],[[928,928],"mapped",[960]],[[929,929],"mapped",[961]],[[930,930],"disallowed"],[[931,931],"mapped",[963]],[[932,932],"mapped",[964]],[[933,933],"mapped",[965]],[[934,934],"mapped",[966]],[[935,935],"mapped",[967]],[[936,936],"mapped",[968]],[[937,937],"mapped",[969]],[[938,938],"mapped",[970]],[[939,939],"mapped",[971]],[[940,961],"valid"],[[962,962],"deviation",[963]],[[963,974],"valid"],[[975,975],"mapped",[983]],[[976,976],"mapped",[946]],[[977,977],"mapped",[952]],[[978,978],"mapped",[965]],[[979,979],"mapped",[973]],[[980,980],"mapped",[971]],[[981,981],"mapped",[966]],[[982,982],"mapped",[960]],[[983,983],"valid"],[[984,984],"mapped",[985]],[[985,985],"valid"],[[986,986],"mapped",[987]],[[987,987],"valid"],[[988,988],"mapped",[989]],[[989,989],"valid"],[[990,990],"mapped",[991]],[[991,991],"valid"],[[992,992],"mapped",[993]],[[993,993],"valid"],[[994,994],"mapped",[995]],[[995,995],"valid"],[[996,996],"mapped",[997]],[[997,997],"valid"],[[998,998],"mapped",[999]],[[999,999],"valid"],[[1000,1000],"mapped",[1001]],[[1001,1001],"valid"],[[1002,1002],"mapped",[1003]],[[1003,1003],"valid"],[[1004,1004],"mapped",[1005]],[[1005,1005],"valid"],[[1006,1006],"mapped",[1007]],[[1007,1007],"valid"],[[1008,1008],"mapped",[954]],[[1009,1009],"mapped",[961]],[[1010,1010],"mapped",[963]],[[1011,1011],"valid"],[[1012,1012],"mapped",[952]],[[1013,1013],"mapped",[949]],[[1014,1014],"valid",[],"NV8"],[[1015,1015],"mapped",[1016]],[[1016,1016],"valid"],[[1017,1017],"mapped",[963]],[[1018,1018],"mapped",[1019]],[[1019,1019],"valid"],[[1020,1020],"valid"],[[1021,1021],"mapped",[891]],[[1022,1022],"mapped",[892]],[[1023,1023],"mapped",[893]],[[1024,1024],"mapped",[1104]],[[1025,1025],"mapped",[1105]],[[1026,1026],"mapped",[1106]],[[1027,1027],"mapped",[1107]],[[1028,1028],"mapped",[1108]],[[1029,1029],"mapped",[1109]],[[1030,1030],"mapped",[1110]],[[1031,1031],"mapped",[1111]],[[1032,1032],"mapped",[1112]],[[1033,1033],"mapped",[1113]],[[1034,1034],"mapped",[1114]],[[1035,1035],"mapped",[1115]],[[1036,1036],"mapped",[1116]],[[1037,1037],"mapped",[1117]],[[1038,1038],"mapped",[1118]],[[1039,1039],"mapped",[1119]],[[1040,1040],"mapped",[1072]],[[1041,1041],"mapped",[1073]],[[1042,1042],"mapped",[1074]],[[1043,1043],"mapped",[1075]],[[1044,1044],"mapped",[1076]],[[1045,1045],"mapped",[1077]],[[1046,1046],"mapped",[1078]],[[1047,1047],"mapped",[1079]],[[1048,1048],"mapped",[1080]],[[1049,1049],"mapped",[1081]],[[1050,1050],"mapped",[1082]],[[1051,1051],"mapped",[1083]],[[1052,1052],"mapped",[1084]],[[1053,1053],"mapped",[1085]],[[1054,1054],"mapped",[1086]],[[1055,1055],"mapped",[1087]],[[1056,1056],"mapped",[1088]],[[1057,1057],"mapped",[1089]],[[1058,1058],"mapped",[1090]],[[1059,1059],"mapped",[1091]],[[1060,1060],"mapped",[1092]],[[1061,1061],"mapped",[1093]],[[1062,1062],"mapped",[1094]],[[1063,1063],"mapped",[1095]],[[1064,1064],"mapped",[1096]],[[1065,1065],"mapped",[1097]],[[1066,1066],"mapped",[1098]],[[1067,1067],"mapped",[1099]],[[1068,1068],"mapped",[1100]],[[1069,1069],"mapped",[1101]],[[1070,1070],"mapped",[1102]],[[1071,1071],"mapped",[1103]],[[1072,1103],"valid"],[[1104,1104],"valid"],[[1105,1116],"valid"],[[1117,1117],"valid"],[[1118,1119],"valid"],[[1120,1120],"mapped",[1121]],[[1121,1121],"valid"],[[1122,1122],"mapped",[1123]],[[1123,1123],"valid"],[[1124,1124],"mapped",[1125]],[[1125,1125],"valid"],[[1126,1126],"mapped",[1127]],[[1127,1127],"valid"],[[1128,1128],"mapped",[1129]],[[1129,1129],"valid"],[[1130,1130],"mapped",[1131]],[[1131,1131],"valid"],[[1132,1132],"mapped",[1133]],[[1133,1133],"valid"],[[1134,1134],"mapped",[1135]],[[1135,1135],"valid"],[[1136,1136],"mapped",[1137]],[[1137,1137],"valid"],[[1138,1138],"mapped",[1139]],[[1139,1139],"valid"],[[1140,1140],"mapped",[1141]],[[1141,1141],"valid"],[[1142,1142],"mapped",[1143]],[[1143,1143],"valid"],[[1144,1144],"mapped",[1145]],[[1145,1145],"valid"],[[1146,1146],"mapped",[1147]],[[1147,1147],"valid"],[[1148,1148],"mapped",[1149]],[[1149,1149],"valid"],[[1150,1150],"mapped",[1151]],[[1151,1151],"valid"],[[1152,1152],"mapped",[1153]],[[1153,1153],"valid"],[[1154,1154],"valid",[],"NV8"],[[1155,1158],"valid"],[[1159,1159],"valid"],[[1160,1161],"valid",[],"NV8"],[[1162,1162],"mapped",[1163]],[[1163,1163],"valid"],[[1164,1164],"mapped",[1165]],[[1165,1165],"valid"],[[1166,1166],"mapped",[1167]],[[1167,1167],"valid"],[[1168,1168],"mapped",[1169]],[[1169,1169],"valid"],[[1170,1170],"mapped",[1171]],[[1171,1171],"valid"],[[1172,1172],"mapped",[1173]],[[1173,1173],"valid"],[[1174,1174],"mapped",[1175]],[[1175,1175],"valid"],[[1176,1176],"mapped",[1177]],[[1177,1177],"valid"],[[1178,1178],"mapped",[1179]],[[1179,1179],"valid"],[[1180,1180],"mapped",[1181]],[[1181,1181],"valid"],[[1182,1182],"mapped",[1183]],[[1183,1183],"valid"],[[1184,1184],"mapped",[1185]],[[1185,1185],"valid"],[[1186,1186],"mapped",[1187]],[[1187,1187],"valid"],[[1188,1188],"mapped",[1189]],[[1189,1189],"valid"],[[1190,1190],"mapped",[1191]],[[1191,1191],"valid"],[[1192,1192],"mapped",[1193]],[[1193,1193],"valid"],[[1194,1194],"mapped",[1195]],[[1195,1195],"valid"],[[1196,1196],"mapped",[1197]],[[1197,1197],"valid"],[[1198,1198],"mapped",[1199]],[[1199,1199],"valid"],[[1200,1200],"mapped",[1201]],[[1201,1201],"valid"],[[1202,1202],"mapped",[1203]],[[1203,1203],"valid"],[[1204,1204],"mapped",[1205]],[[1205,1205],"valid"],[[1206,1206],"mapped",[1207]],[[1207,1207],"valid"],[[1208,1208],"mapped",[1209]],[[1209,1209],"valid"],[[1210,1210],"mapped",[1211]],[[1211,1211],"valid"],[[1212,1212],"mapped",[1213]],[[1213,1213],"valid"],[[1214,1214],"mapped",[1215]],[[1215,1215],"valid"],[[1216,1216],"disallowed"],[[1217,1217],"mapped",[1218]],[[1218,1218],"valid"],[[1219,1219],"mapped",[1220]],[[1220,1220],"valid"],[[1221,1221],"mapped",[1222]],[[1222,1222],"valid"],[[1223,1223],"mapped",[1224]],[[1224,1224],"valid"],[[1225,1225],"mapped",[1226]],[[1226,1226],"valid"],[[1227,1227],"mapped",[1228]],[[1228,1228],"valid"],[[1229,1229],"mapped",[1230]],[[1230,1230],"valid"],[[1231,1231],"valid"],[[1232,1232],"mapped",[1233]],[[1233,1233],"valid"],[[1234,1234],"mapped",[1235]],[[1235,1235],"valid"],[[1236,1236],"mapped",[1237]],[[1237,1237],"valid"],[[1238,1238],"mapped",[1239]],[[1239,1239],"valid"],[[1240,1240],"mapped",[1241]],[[1241,1241],"valid"],[[1242,1242],"mapped",[1243]],[[1243,1243],"valid"],[[1244,1244],"mapped",[1245]],[[1245,1245],"valid"],[[1246,1246],"mapped",[1247]],[[1247,1247],"valid"],[[1248,1248],"mapped",[1249]],[[1249,1249],"valid"],[[1250,1250],"mapped",[1251]],[[1251,1251],"valid"],[[1252,1252],"mapped",[1253]],[[1253,1253],"valid"],[[1254,1254],"mapped",[1255]],[[1255,1255],"valid"],[[1256,1256],"mapped",[1257]],[[1257,1257],"valid"],[[1258,1258],"mapped",[1259]],[[1259,1259],"valid"],[[1260,1260],"mapped",[1261]],[[1261,1261],"valid"],[[1262,1262],"mapped",[1263]],[[1263,1263],"valid"],[[1264,1264],"mapped",[1265]],[[1265,1265],"valid"],[[1266,1266],"mapped",[1267]],[[1267,1267],"valid"],[[1268,1268],"mapped",[1269]],[[1269,1269],"valid"],[[1270,1270],"mapped",[1271]],[[1271,1271],"valid"],[[1272,1272],"mapped",[1273]],[[1273,1273],"valid"],[[1274,1274],"mapped",[1275]],[[1275,1275],"valid"],[[1276,1276],"mapped",[1277]],[[1277,1277],"valid"],[[1278,1278],"mapped",[1279]],[[1279,1279],"valid"],[[1280,1280],"mapped",[1281]],[[1281,1281],"valid"],[[1282,1282],"mapped",[1283]],[[1283,1283],"valid"],[[1284,1284],"mapped",[1285]],[[1285,1285],"valid"],[[1286,1286],"mapped",[1287]],[[1287,1287],"valid"],[[1288,1288],"mapped",[1289]],[[1289,1289],"valid"],[[1290,1290],"mapped",[1291]],[[1291,1291],"valid"],[[1292,1292],"mapped",[1293]],[[1293,1293],"valid"],[[1294,1294],"mapped",[1295]],[[1295,1295],"valid"],[[1296,1296],"mapped",[1297]],[[1297,1297],"valid"],[[1298,1298],"mapped",[1299]],[[1299,1299],"valid"],[[1300,1300],"mapped",[1301]],[[1301,1301],"valid"],[[1302,1302],"mapped",[1303]],[[1303,1303],"valid"],[[1304,1304],"mapped",[1305]],[[1305,1305],"valid"],[[1306,1306],"mapped",[1307]],[[1307,1307],"valid"],[[1308,1308],"mapped",[1309]],[[1309,1309],"valid"],[[1310,1310],"mapped",[1311]],[[1311,1311],"valid"],[[1312,1312],"mapped",[1313]],[[1313,1313],"valid"],[[1314,1314],"mapped",[1315]],[[1315,1315],"valid"],[[1316,1316],"mapped",[1317]],[[1317,1317],"valid"],[[1318,1318],"mapped",[1319]],[[1319,1319],"valid"],[[1320,1320],"mapped",[1321]],[[1321,1321],"valid"],[[1322,1322],"mapped",[1323]],[[1323,1323],"valid"],[[1324,1324],"mapped",[1325]],[[1325,1325],"valid"],[[1326,1326],"mapped",[1327]],[[1327,1327],"valid"],[[1328,1328],"disallowed"],[[1329,1329],"mapped",[1377]],[[1330,1330],"mapped",[1378]],[[1331,1331],"mapped",[1379]],[[1332,1332],"mapped",[1380]],[[1333,1333],"mapped",[1381]],[[1334,1334],"mapped",[1382]],[[1335,1335],"mapped",[1383]],[[1336,1336],"mapped",[1384]],[[1337,1337],"mapped",[1385]],[[1338,1338],"mapped",[1386]],[[1339,1339],"mapped",[1387]],[[1340,1340],"mapped",[1388]],[[1341,1341],"mapped",[1389]],[[1342,1342],"mapped",[1390]],[[1343,1343],"mapped",[1391]],[[1344,1344],"mapped",[1392]],[[1345,1345],"mapped",[1393]],[[1346,1346],"mapped",[1394]],[[1347,1347],"mapped",[1395]],[[1348,1348],"mapped",[1396]],[[1349,1349],"mapped",[1397]],[[1350,1350],"mapped",[1398]],[[1351,1351],"mapped",[1399]],[[1352,1352],"mapped",[1400]],[[1353,1353],"mapped",[1401]],[[1354,1354],"mapped",[1402]],[[1355,1355],"mapped",[1403]],[[1356,1356],"mapped",[1404]],[[1357,1357],"mapped",[1405]],[[1358,1358],"mapped",[1406]],[[1359,1359],"mapped",[1407]],[[1360,1360],"mapped",[1408]],[[1361,1361],"mapped",[1409]],[[1362,1362],"mapped",[1410]],[[1363,1363],"mapped",[1411]],[[1364,1364],"mapped",[1412]],[[1365,1365],"mapped",[1413]],[[1366,1366],"mapped",[1414]],[[1367,1368],"disallowed"],[[1369,1369],"valid"],[[1370,1375],"valid",[],"NV8"],[[1376,1376],"disallowed"],[[1377,1414],"valid"],[[1415,1415],"mapped",[1381,1410]],[[1416,1416],"disallowed"],[[1417,1417],"valid",[],"NV8"],[[1418,1418],"valid",[],"NV8"],[[1419,1420],"disallowed"],[[1421,1422],"valid",[],"NV8"],[[1423,1423],"valid",[],"NV8"],[[1424,1424],"disallowed"],[[1425,1441],"valid"],[[1442,1442],"valid"],[[1443,1455],"valid"],[[1456,1465],"valid"],[[1466,1466],"valid"],[[1467,1469],"valid"],[[1470,1470],"valid",[],"NV8"],[[1471,1471],"valid"],[[1472,1472],"valid",[],"NV8"],[[1473,1474],"valid"],[[1475,1475],"valid",[],"NV8"],[[1476,1476],"valid"],[[1477,1477],"valid"],[[1478,1478],"valid",[],"NV8"],[[1479,1479],"valid"],[[1480,1487],"disallowed"],[[1488,1514],"valid"],[[1515,1519],"disallowed"],[[1520,1524],"valid"],[[1525,1535],"disallowed"],[[1536,1539],"disallowed"],[[1540,1540],"disallowed"],[[1541,1541],"disallowed"],[[1542,1546],"valid",[],"NV8"],[[1547,1547],"valid",[],"NV8"],[[1548,1548],"valid",[],"NV8"],[[1549,1551],"valid",[],"NV8"],[[1552,1557],"valid"],[[1558,1562],"valid"],[[1563,1563],"valid",[],"NV8"],[[1564,1564],"disallowed"],[[1565,1565],"disallowed"],[[1566,1566],"valid",[],"NV8"],[[1567,1567],"valid",[],"NV8"],[[1568,1568],"valid"],[[1569,1594],"valid"],[[1595,1599],"valid"],[[1600,1600],"valid",[],"NV8"],[[1601,1618],"valid"],[[1619,1621],"valid"],[[1622,1624],"valid"],[[1625,1630],"valid"],[[1631,1631],"valid"],[[1632,1641],"valid"],[[1642,1645],"valid",[],"NV8"],[[1646,1647],"valid"],[[1648,1652],"valid"],[[1653,1653],"mapped",[1575,1652]],[[1654,1654],"mapped",[1608,1652]],[[1655,1655],"mapped",[1735,1652]],[[1656,1656],"mapped",[1610,1652]],[[1657,1719],"valid"],[[1720,1721],"valid"],[[1722,1726],"valid"],[[1727,1727],"valid"],[[1728,1742],"valid"],[[1743,1743],"valid"],[[1744,1747],"valid"],[[1748,1748],"valid",[],"NV8"],[[1749,1756],"valid"],[[1757,1757],"disallowed"],[[1758,1758],"valid",[],"NV8"],[[1759,1768],"valid"],[[1769,1769],"valid",[],"NV8"],[[1770,1773],"valid"],[[1774,1775],"valid"],[[1776,1785],"valid"],[[1786,1790],"valid"],[[1791,1791],"valid"],[[1792,1805],"valid",[],"NV8"],[[1806,1806],"disallowed"],[[1807,1807],"disallowed"],[[1808,1836],"valid"],[[1837,1839],"valid"],[[1840,1866],"valid"],[[1867,1868],"disallowed"],[[1869,1871],"valid"],[[1872,1901],"valid"],[[1902,1919],"valid"],[[1920,1968],"valid"],[[1969,1969],"valid"],[[1970,1983],"disallowed"],[[1984,2037],"valid"],[[2038,2042],"valid",[],"NV8"],[[2043,2047],"disallowed"],[[2048,2093],"valid"],[[2094,2095],"disallowed"],[[2096,2110],"valid",[],"NV8"],[[2111,2111],"disallowed"],[[2112,2139],"valid"],[[2140,2141],"disallowed"],[[2142,2142],"valid",[],"NV8"],[[2143,2207],"disallowed"],[[2208,2208],"valid"],[[2209,2209],"valid"],[[2210,2220],"valid"],[[2221,2226],"valid"],[[2227,2228],"valid"],[[2229,2274],"disallowed"],[[2275,2275],"valid"],[[2276,2302],"valid"],[[2303,2303],"valid"],[[2304,2304],"valid"],[[2305,2307],"valid"],[[2308,2308],"valid"],[[2309,2361],"valid"],[[2362,2363],"valid"],[[2364,2381],"valid"],[[2382,2382],"valid"],[[2383,2383],"valid"],[[2384,2388],"valid"],[[2389,2389],"valid"],[[2390,2391],"valid"],[[2392,2392],"mapped",[2325,2364]],[[2393,2393],"mapped",[2326,2364]],[[2394,2394],"mapped",[2327,2364]],[[2395,2395],"mapped",[2332,2364]],[[2396,2396],"mapped",[2337,2364]],[[2397,2397],"mapped",[2338,2364]],[[2398,2398],"mapped",[2347,2364]],[[2399,2399],"mapped",[2351,2364]],[[2400,2403],"valid"],[[2404,2405],"valid",[],"NV8"],[[2406,2415],"valid"],[[2416,2416],"valid",[],"NV8"],[[2417,2418],"valid"],[[2419,2423],"valid"],[[2424,2424],"valid"],[[2425,2426],"valid"],[[2427,2428],"valid"],[[2429,2429],"valid"],[[2430,2431],"valid"],[[2432,2432],"valid"],[[2433,2435],"valid"],[[2436,2436],"disallowed"],[[2437,2444],"valid"],[[2445,2446],"disallowed"],[[2447,2448],"valid"],[[2449,2450],"disallowed"],[[2451,2472],"valid"],[[2473,2473],"disallowed"],[[2474,2480],"valid"],[[2481,2481],"disallowed"],[[2482,2482],"valid"],[[2483,2485],"disallowed"],[[2486,2489],"valid"],[[2490,2491],"disallowed"],[[2492,2492],"valid"],[[2493,2493],"valid"],[[2494,2500],"valid"],[[2501,2502],"disallowed"],[[2503,2504],"valid"],[[2505,2506],"disallowed"],[[2507,2509],"valid"],[[2510,2510],"valid"],[[2511,2518],"disallowed"],[[2519,2519],"valid"],[[2520,2523],"disallowed"],[[2524,2524],"mapped",[2465,2492]],[[2525,2525],"mapped",[2466,2492]],[[2526,2526],"disallowed"],[[2527,2527],"mapped",[2479,2492]],[[2528,2531],"valid"],[[2532,2533],"disallowed"],[[2534,2545],"valid"],[[2546,2554],"valid",[],"NV8"],[[2555,2555],"valid",[],"NV8"],[[2556,2560],"disallowed"],[[2561,2561],"valid"],[[2562,2562],"valid"],[[2563,2563],"valid"],[[2564,2564],"disallowed"],[[2565,2570],"valid"],[[2571,2574],"disallowed"],[[2575,2576],"valid"],[[2577,2578],"disallowed"],[[2579,2600],"valid"],[[2601,2601],"disallowed"],[[2602,2608],"valid"],[[2609,2609],"disallowed"],[[2610,2610],"valid"],[[2611,2611],"mapped",[2610,2620]],[[2612,2612],"disallowed"],[[2613,2613],"valid"],[[2614,2614],"mapped",[2616,2620]],[[2615,2615],"disallowed"],[[2616,2617],"valid"],[[2618,2619],"disallowed"],[[2620,2620],"valid"],[[2621,2621],"disallowed"],[[2622,2626],"valid"],[[2627,2630],"disallowed"],[[2631,2632],"valid"],[[2633,2634],"disallowed"],[[2635,2637],"valid"],[[2638,2640],"disallowed"],[[2641,2641],"valid"],[[2642,2648],"disallowed"],[[2649,2649],"mapped",[2582,2620]],[[2650,2650],"mapped",[2583,2620]],[[2651,2651],"mapped",[2588,2620]],[[2652,2652],"valid"],[[2653,2653],"disallowed"],[[2654,2654],"mapped",[2603,2620]],[[2655,2661],"disallowed"],[[2662,2676],"valid"],[[2677,2677],"valid"],[[2678,2688],"disallowed"],[[2689,2691],"valid"],[[2692,2692],"disallowed"],[[2693,2699],"valid"],[[2700,2700],"valid"],[[2701,2701],"valid"],[[2702,2702],"disallowed"],[[2703,2705],"valid"],[[2706,2706],"disallowed"],[[2707,2728],"valid"],[[2729,2729],"disallowed"],[[2730,2736],"valid"],[[2737,2737],"disallowed"],[[2738,2739],"valid"],[[2740,2740],"disallowed"],[[2741,2745],"valid"],[[2746,2747],"disallowed"],[[2748,2757],"valid"],[[2758,2758],"disallowed"],[[2759,2761],"valid"],[[2762,2762],"disallowed"],[[2763,2765],"valid"],[[2766,2767],"disallowed"],[[2768,2768],"valid"],[[2769,2783],"disallowed"],[[2784,2784],"valid"],[[2785,2787],"valid"],[[2788,2789],"disallowed"],[[2790,2799],"valid"],[[2800,2800],"valid",[],"NV8"],[[2801,2801],"valid",[],"NV8"],[[2802,2808],"disallowed"],[[2809,2809],"valid"],[[2810,2816],"disallowed"],[[2817,2819],"valid"],[[2820,2820],"disallowed"],[[2821,2828],"valid"],[[2829,2830],"disallowed"],[[2831,2832],"valid"],[[2833,2834],"disallowed"],[[2835,2856],"valid"],[[2857,2857],"disallowed"],[[2858,2864],"valid"],[[2865,2865],"disallowed"],[[2866,2867],"valid"],[[2868,2868],"disallowed"],[[2869,2869],"valid"],[[2870,2873],"valid"],[[2874,2875],"disallowed"],[[2876,2883],"valid"],[[2884,2884],"valid"],[[2885,2886],"disallowed"],[[2887,2888],"valid"],[[2889,2890],"disallowed"],[[2891,2893],"valid"],[[2894,2901],"disallowed"],[[2902,2903],"valid"],[[2904,2907],"disallowed"],[[2908,2908],"mapped",[2849,2876]],[[2909,2909],"mapped",[2850,2876]],[[2910,2910],"disallowed"],[[2911,2913],"valid"],[[2914,2915],"valid"],[[2916,2917],"disallowed"],[[2918,2927],"valid"],[[2928,2928],"valid",[],"NV8"],[[2929,2929],"valid"],[[2930,2935],"valid",[],"NV8"],[[2936,2945],"disallowed"],[[2946,2947],"valid"],[[2948,2948],"disallowed"],[[2949,2954],"valid"],[[2955,2957],"disallowed"],[[2958,2960],"valid"],[[2961,2961],"disallowed"],[[2962,2965],"valid"],[[2966,2968],"disallowed"],[[2969,2970],"valid"],[[2971,2971],"disallowed"],[[2972,2972],"valid"],[[2973,2973],"disallowed"],[[2974,2975],"valid"],[[2976,2978],"disallowed"],[[2979,2980],"valid"],[[2981,2983],"disallowed"],[[2984,2986],"valid"],[[2987,2989],"disallowed"],[[2990,2997],"valid"],[[2998,2998],"valid"],[[2999,3001],"valid"],[[3002,3005],"disallowed"],[[3006,3010],"valid"],[[3011,3013],"disallowed"],[[3014,3016],"valid"],[[3017,3017],"disallowed"],[[3018,3021],"valid"],[[3022,3023],"disallowed"],[[3024,3024],"valid"],[[3025,3030],"disallowed"],[[3031,3031],"valid"],[[3032,3045],"disallowed"],[[3046,3046],"valid"],[[3047,3055],"valid"],[[3056,3058],"valid",[],"NV8"],[[3059,3066],"valid",[],"NV8"],[[3067,3071],"disallowed"],[[3072,3072],"valid"],[[3073,3075],"valid"],[[3076,3076],"disallowed"],[[3077,3084],"valid"],[[3085,3085],"disallowed"],[[3086,3088],"valid"],[[3089,3089],"disallowed"],[[3090,3112],"valid"],[[3113,3113],"disallowed"],[[3114,3123],"valid"],[[3124,3124],"valid"],[[3125,3129],"valid"],[[3130,3132],"disallowed"],[[3133,3133],"valid"],[[3134,3140],"valid"],[[3141,3141],"disallowed"],[[3142,3144],"valid"],[[3145,3145],"disallowed"],[[3146,3149],"valid"],[[3150,3156],"disallowed"],[[3157,3158],"valid"],[[3159,3159],"disallowed"],[[3160,3161],"valid"],[[3162,3162],"valid"],[[3163,3167],"disallowed"],[[3168,3169],"valid"],[[3170,3171],"valid"],[[3172,3173],"disallowed"],[[3174,3183],"valid"],[[3184,3191],"disallowed"],[[3192,3199],"valid",[],"NV8"],[[3200,3200],"disallowed"],[[3201,3201],"valid"],[[3202,3203],"valid"],[[3204,3204],"disallowed"],[[3205,3212],"valid"],[[3213,3213],"disallowed"],[[3214,3216],"valid"],[[3217,3217],"disallowed"],[[3218,3240],"valid"],[[3241,3241],"disallowed"],[[3242,3251],"valid"],[[3252,3252],"disallowed"],[[3253,3257],"valid"],[[3258,3259],"disallowed"],[[3260,3261],"valid"],[[3262,3268],"valid"],[[3269,3269],"disallowed"],[[3270,3272],"valid"],[[3273,3273],"disallowed"],[[3274,3277],"valid"],[[3278,3284],"disallowed"],[[3285,3286],"valid"],[[3287,3293],"disallowed"],[[3294,3294],"valid"],[[3295,3295],"disallowed"],[[3296,3297],"valid"],[[3298,3299],"valid"],[[3300,3301],"disallowed"],[[3302,3311],"valid"],[[3312,3312],"disallowed"],[[3313,3314],"valid"],[[3315,3328],"disallowed"],[[3329,3329],"valid"],[[3330,3331],"valid"],[[3332,3332],"disallowed"],[[3333,3340],"valid"],[[3341,3341],"disallowed"],[[3342,3344],"valid"],[[3345,3345],"disallowed"],[[3346,3368],"valid"],[[3369,3369],"valid"],[[3370,3385],"valid"],[[3386,3386],"valid"],[[3387,3388],"disallowed"],[[3389,3389],"valid"],[[3390,3395],"valid"],[[3396,3396],"valid"],[[3397,3397],"disallowed"],[[3398,3400],"valid"],[[3401,3401],"disallowed"],[[3402,3405],"valid"],[[3406,3406],"valid"],[[3407,3414],"disallowed"],[[3415,3415],"valid"],[[3416,3422],"disallowed"],[[3423,3423],"valid"],[[3424,3425],"valid"],[[3426,3427],"valid"],[[3428,3429],"disallowed"],[[3430,3439],"valid"],[[3440,3445],"valid",[],"NV8"],[[3446,3448],"disallowed"],[[3449,3449],"valid",[],"NV8"],[[3450,3455],"valid"],[[3456,3457],"disallowed"],[[3458,3459],"valid"],[[3460,3460],"disallowed"],[[3461,3478],"valid"],[[3479,3481],"disallowed"],[[3482,3505],"valid"],[[3506,3506],"disallowed"],[[3507,3515],"valid"],[[3516,3516],"disallowed"],[[3517,3517],"valid"],[[3518,3519],"disallowed"],[[3520,3526],"valid"],[[3527,3529],"disallowed"],[[3530,3530],"valid"],[[3531,3534],"disallowed"],[[3535,3540],"valid"],[[3541,3541],"disallowed"],[[3542,3542],"valid"],[[3543,3543],"disallowed"],[[3544,3551],"valid"],[[3552,3557],"disallowed"],[[3558,3567],"valid"],[[3568,3569],"disallowed"],[[3570,3571],"valid"],[[3572,3572],"valid",[],"NV8"],[[3573,3584],"disallowed"],[[3585,3634],"valid"],[[3635,3635],"mapped",[3661,3634]],[[3636,3642],"valid"],[[3643,3646],"disallowed"],[[3647,3647],"valid",[],"NV8"],[[3648,3662],"valid"],[[3663,3663],"valid",[],"NV8"],[[3664,3673],"valid"],[[3674,3675],"valid",[],"NV8"],[[3676,3712],"disallowed"],[[3713,3714],"valid"],[[3715,3715],"disallowed"],[[3716,3716],"valid"],[[3717,3718],"disallowed"],[[3719,3720],"valid"],[[3721,3721],"disallowed"],[[3722,3722],"valid"],[[3723,3724],"disallowed"],[[3725,3725],"valid"],[[3726,3731],"disallowed"],[[3732,3735],"valid"],[[3736,3736],"disallowed"],[[3737,3743],"valid"],[[3744,3744],"disallowed"],[[3745,3747],"valid"],[[3748,3748],"disallowed"],[[3749,3749],"valid"],[[3750,3750],"disallowed"],[[3751,3751],"valid"],[[3752,3753],"disallowed"],[[3754,3755],"valid"],[[3756,3756],"disallowed"],[[3757,3762],"valid"],[[3763,3763],"mapped",[3789,3762]],[[3764,3769],"valid"],[[3770,3770],"disallowed"],[[3771,3773],"valid"],[[3774,3775],"disallowed"],[[3776,3780],"valid"],[[3781,3781],"disallowed"],[[3782,3782],"valid"],[[3783,3783],"disallowed"],[[3784,3789],"valid"],[[3790,3791],"disallowed"],[[3792,3801],"valid"],[[3802,3803],"disallowed"],[[3804,3804],"mapped",[3755,3737]],[[3805,3805],"mapped",[3755,3745]],[[3806,3807],"valid"],[[3808,3839],"disallowed"],[[3840,3840],"valid"],[[3841,3850],"valid",[],"NV8"],[[3851,3851],"valid"],[[3852,3852],"mapped",[3851]],[[3853,3863],"valid",[],"NV8"],[[3864,3865],"valid"],[[3866,3871],"valid",[],"NV8"],[[3872,3881],"valid"],[[3882,3892],"valid",[],"NV8"],[[3893,3893],"valid"],[[3894,3894],"valid",[],"NV8"],[[3895,3895],"valid"],[[3896,3896],"valid",[],"NV8"],[[3897,3897],"valid"],[[3898,3901],"valid",[],"NV8"],[[3902,3906],"valid"],[[3907,3907],"mapped",[3906,4023]],[[3908,3911],"valid"],[[3912,3912],"disallowed"],[[3913,3916],"valid"],[[3917,3917],"mapped",[3916,4023]],[[3918,3921],"valid"],[[3922,3922],"mapped",[3921,4023]],[[3923,3926],"valid"],[[3927,3927],"mapped",[3926,4023]],[[3928,3931],"valid"],[[3932,3932],"mapped",[3931,4023]],[[3933,3944],"valid"],[[3945,3945],"mapped",[3904,4021]],[[3946,3946],"valid"],[[3947,3948],"valid"],[[3949,3952],"disallowed"],[[3953,3954],"valid"],[[3955,3955],"mapped",[3953,3954]],[[3956,3956],"valid"],[[3957,3957],"mapped",[3953,3956]],[[3958,3958],"mapped",[4018,3968]],[[3959,3959],"mapped",[4018,3953,3968]],[[3960,3960],"mapped",[4019,3968]],[[3961,3961],"mapped",[4019,3953,3968]],[[3962,3968],"valid"],[[3969,3969],"mapped",[3953,3968]],[[3970,3972],"valid"],[[3973,3973],"valid",[],"NV8"],[[3974,3979],"valid"],[[3980,3983],"valid"],[[3984,3986],"valid"],[[3987,3987],"mapped",[3986,4023]],[[3988,3989],"valid"],[[3990,3990],"valid"],[[3991,3991],"valid"],[[3992,3992],"disallowed"],[[3993,3996],"valid"],[[3997,3997],"mapped",[3996,4023]],[[3998,4001],"valid"],[[4002,4002],"mapped",[4001,4023]],[[4003,4006],"valid"],[[4007,4007],"mapped",[4006,4023]],[[4008,4011],"valid"],[[4012,4012],"mapped",[4011,4023]],[[4013,4013],"valid"],[[4014,4016],"valid"],[[4017,4023],"valid"],[[4024,4024],"valid"],[[4025,4025],"mapped",[3984,4021]],[[4026,4028],"valid"],[[4029,4029],"disallowed"],[[4030,4037],"valid",[],"NV8"],[[4038,4038],"valid"],[[4039,4044],"valid",[],"NV8"],[[4045,4045],"disallowed"],[[4046,4046],"valid",[],"NV8"],[[4047,4047],"valid",[],"NV8"],[[4048,4049],"valid",[],"NV8"],[[4050,4052],"valid",[],"NV8"],[[4053,4056],"valid",[],"NV8"],[[4057,4058],"valid",[],"NV8"],[[4059,4095],"disallowed"],[[4096,4129],"valid"],[[4130,4130],"valid"],[[4131,4135],"valid"],[[4136,4136],"valid"],[[4137,4138],"valid"],[[4139,4139],"valid"],[[4140,4146],"valid"],[[4147,4149],"valid"],[[4150,4153],"valid"],[[4154,4159],"valid"],[[4160,4169],"valid"],[[4170,4175],"valid",[],"NV8"],[[4176,4185],"valid"],[[4186,4249],"valid"],[[4250,4253],"valid"],[[4254,4255],"valid",[],"NV8"],[[4256,4293],"disallowed"],[[4294,4294],"disallowed"],[[4295,4295],"mapped",[11559]],[[4296,4300],"disallowed"],[[4301,4301],"mapped",[11565]],[[4302,4303],"disallowed"],[[4304,4342],"valid"],[[4343,4344],"valid"],[[4345,4346],"valid"],[[4347,4347],"valid",[],"NV8"],[[4348,4348],"mapped",[4316]],[[4349,4351],"valid"],[[4352,4441],"valid",[],"NV8"],[[4442,4446],"valid",[],"NV8"],[[4447,4448],"disallowed"],[[4449,4514],"valid",[],"NV8"],[[4515,4519],"valid",[],"NV8"],[[4520,4601],"valid",[],"NV8"],[[4602,4607],"valid",[],"NV8"],[[4608,4614],"valid"],[[4615,4615],"valid"],[[4616,4678],"valid"],[[4679,4679],"valid"],[[4680,4680],"valid"],[[4681,4681],"disallowed"],[[4682,4685],"valid"],[[4686,4687],"disallowed"],[[4688,4694],"valid"],[[4695,4695],"disallowed"],[[4696,4696],"valid"],[[4697,4697],"disallowed"],[[4698,4701],"valid"],[[4702,4703],"disallowed"],[[4704,4742],"valid"],[[4743,4743],"valid"],[[4744,4744],"valid"],[[4745,4745],"disallowed"],[[4746,4749],"valid"],[[4750,4751],"disallowed"],[[4752,4782],"valid"],[[4783,4783],"valid"],[[4784,4784],"valid"],[[4785,4785],"disallowed"],[[4786,4789],"valid"],[[4790,4791],"disallowed"],[[4792,4798],"valid"],[[4799,4799],"disallowed"],[[4800,4800],"valid"],[[4801,4801],"disallowed"],[[4802,4805],"valid"],[[4806,4807],"disallowed"],[[4808,4814],"valid"],[[4815,4815],"valid"],[[4816,4822],"valid"],[[4823,4823],"disallowed"],[[4824,4846],"valid"],[[4847,4847],"valid"],[[4848,4878],"valid"],[[4879,4879],"valid"],[[4880,4880],"valid"],[[4881,4881],"disallowed"],[[4882,4885],"valid"],[[4886,4887],"disallowed"],[[4888,4894],"valid"],[[4895,4895],"valid"],[[4896,4934],"valid"],[[4935,4935],"valid"],[[4936,4954],"valid"],[[4955,4956],"disallowed"],[[4957,4958],"valid"],[[4959,4959],"valid"],[[4960,4960],"valid",[],"NV8"],[[4961,4988],"valid",[],"NV8"],[[4989,4991],"disallowed"],[[4992,5007],"valid"],[[5008,5017],"valid",[],"NV8"],[[5018,5023],"disallowed"],[[5024,5108],"valid"],[[5109,5109],"valid"],[[5110,5111],"disallowed"],[[5112,5112],"mapped",[5104]],[[5113,5113],"mapped",[5105]],[[5114,5114],"mapped",[5106]],[[5115,5115],"mapped",[5107]],[[5116,5116],"mapped",[5108]],[[5117,5117],"mapped",[5109]],[[5118,5119],"disallowed"],[[5120,5120],"valid",[],"NV8"],[[5121,5740],"valid"],[[5741,5742],"valid",[],"NV8"],[[5743,5750],"valid"],[[5751,5759],"valid"],[[5760,5760],"disallowed"],[[5761,5786],"valid"],[[5787,5788],"valid",[],"NV8"],[[5789,5791],"disallowed"],[[5792,5866],"valid"],[[5867,5872],"valid",[],"NV8"],[[5873,5880],"valid"],[[5881,5887],"disallowed"],[[5888,5900],"valid"],[[5901,5901],"disallowed"],[[5902,5908],"valid"],[[5909,5919],"disallowed"],[[5920,5940],"valid"],[[5941,5942],"valid",[],"NV8"],[[5943,5951],"disallowed"],[[5952,5971],"valid"],[[5972,5983],"disallowed"],[[5984,5996],"valid"],[[5997,5997],"disallowed"],[[5998,6000],"valid"],[[6001,6001],"disallowed"],[[6002,6003],"valid"],[[6004,6015],"disallowed"],[[6016,6067],"valid"],[[6068,6069],"disallowed"],[[6070,6099],"valid"],[[6100,6102],"valid",[],"NV8"],[[6103,6103],"valid"],[[6104,6107],"valid",[],"NV8"],[[6108,6108],"valid"],[[6109,6109],"valid"],[[6110,6111],"disallowed"],[[6112,6121],"valid"],[[6122,6127],"disallowed"],[[6128,6137],"valid",[],"NV8"],[[6138,6143],"disallowed"],[[6144,6149],"valid",[],"NV8"],[[6150,6150],"disallowed"],[[6151,6154],"valid",[],"NV8"],[[6155,6157],"ignored"],[[6158,6158],"disallowed"],[[6159,6159],"disallowed"],[[6160,6169],"valid"],[[6170,6175],"disallowed"],[[6176,6263],"valid"],[[6264,6271],"disallowed"],[[6272,6313],"valid"],[[6314,6314],"valid"],[[6315,6319],"disallowed"],[[6320,6389],"valid"],[[6390,6399],"disallowed"],[[6400,6428],"valid"],[[6429,6430],"valid"],[[6431,6431],"disallowed"],[[6432,6443],"valid"],[[6444,6447],"disallowed"],[[6448,6459],"valid"],[[6460,6463],"disallowed"],[[6464,6464],"valid",[],"NV8"],[[6465,6467],"disallowed"],[[6468,6469],"valid",[],"NV8"],[[6470,6509],"valid"],[[6510,6511],"disallowed"],[[6512,6516],"valid"],[[6517,6527],"disallowed"],[[6528,6569],"valid"],[[6570,6571],"valid"],[[6572,6575],"disallowed"],[[6576,6601],"valid"],[[6602,6607],"disallowed"],[[6608,6617],"valid"],[[6618,6618],"valid",[],"XV8"],[[6619,6621],"disallowed"],[[6622,6623],"valid",[],"NV8"],[[6624,6655],"valid",[],"NV8"],[[6656,6683],"valid"],[[6684,6685],"disallowed"],[[6686,6687],"valid",[],"NV8"],[[6688,6750],"valid"],[[6751,6751],"disallowed"],[[6752,6780],"valid"],[[6781,6782],"disallowed"],[[6783,6793],"valid"],[[6794,6799],"disallowed"],[[6800,6809],"valid"],[[6810,6815],"disallowed"],[[6816,6822],"valid",[],"NV8"],[[6823,6823],"valid"],[[6824,6829],"valid",[],"NV8"],[[6830,6831],"disallowed"],[[6832,6845],"valid"],[[6846,6846],"valid",[],"NV8"],[[6847,6911],"disallowed"],[[6912,6987],"valid"],[[6988,6991],"disallowed"],[[6992,7001],"valid"],[[7002,7018],"valid",[],"NV8"],[[7019,7027],"valid"],[[7028,7036],"valid",[],"NV8"],[[7037,7039],"disallowed"],[[7040,7082],"valid"],[[7083,7085],"valid"],[[7086,7097],"valid"],[[7098,7103],"valid"],[[7104,7155],"valid"],[[7156,7163],"disallowed"],[[7164,7167],"valid",[],"NV8"],[[7168,7223],"valid"],[[7224,7226],"disallowed"],[[7227,7231],"valid",[],"NV8"],[[7232,7241],"valid"],[[7242,7244],"disallowed"],[[7245,7293],"valid"],[[7294,7295],"valid",[],"NV8"],[[7296,7359],"disallowed"],[[7360,7367],"valid",[],"NV8"],[[7368,7375],"disallowed"],[[7376,7378],"valid"],[[7379,7379],"valid",[],"NV8"],[[7380,7410],"valid"],[[7411,7414],"valid"],[[7415,7415],"disallowed"],[[7416,7417],"valid"],[[7418,7423],"disallowed"],[[7424,7467],"valid"],[[7468,7468],"mapped",[97]],[[7469,7469],"mapped",[230]],[[7470,7470],"mapped",[98]],[[7471,7471],"valid"],[[7472,7472],"mapped",[100]],[[7473,7473],"mapped",[101]],[[7474,7474],"mapped",[477]],[[7475,7475],"mapped",[103]],[[7476,7476],"mapped",[104]],[[7477,7477],"mapped",[105]],[[7478,7478],"mapped",[106]],[[7479,7479],"mapped",[107]],[[7480,7480],"mapped",[108]],[[7481,7481],"mapped",[109]],[[7482,7482],"mapped",[110]],[[7483,7483],"valid"],[[7484,7484],"mapped",[111]],[[7485,7485],"mapped",[547]],[[7486,7486],"mapped",[112]],[[7487,7487],"mapped",[114]],[[7488,7488],"mapped",[116]],[[7489,7489],"mapped",[117]],[[7490,7490],"mapped",[119]],[[7491,7491],"mapped",[97]],[[7492,7492],"mapped",[592]],[[7493,7493],"mapped",[593]],[[7494,7494],"mapped",[7426]],[[7495,7495],"mapped",[98]],[[7496,7496],"mapped",[100]],[[7497,7497],"mapped",[101]],[[7498,7498],"mapped",[601]],[[7499,7499],"mapped",[603]],[[7500,7500],"mapped",[604]],[[7501,7501],"mapped",[103]],[[7502,7502],"valid"],[[7503,7503],"mapped",[107]],[[7504,7504],"mapped",[109]],[[7505,7505],"mapped",[331]],[[7506,7506],"mapped",[111]],[[7507,7507],"mapped",[596]],[[7508,7508],"mapped",[7446]],[[7509,7509],"mapped",[7447]],[[7510,7510],"mapped",[112]],[[7511,7511],"mapped",[116]],[[7512,7512],"mapped",[117]],[[7513,7513],"mapped",[7453]],[[7514,7514],"mapped",[623]],[[7515,7515],"mapped",[118]],[[7516,7516],"mapped",[7461]],[[7517,7517],"mapped",[946]],[[7518,7518],"mapped",[947]],[[7519,7519],"mapped",[948]],[[7520,7520],"mapped",[966]],[[7521,7521],"mapped",[967]],[[7522,7522],"mapped",[105]],[[7523,7523],"mapped",[114]],[[7524,7524],"mapped",[117]],[[7525,7525],"mapped",[118]],[[7526,7526],"mapped",[946]],[[7527,7527],"mapped",[947]],[[7528,7528],"mapped",[961]],[[7529,7529],"mapped",[966]],[[7530,7530],"mapped",[967]],[[7531,7531],"valid"],[[7532,7543],"valid"],[[7544,7544],"mapped",[1085]],[[7545,7578],"valid"],[[7579,7579],"mapped",[594]],[[7580,7580],"mapped",[99]],[[7581,7581],"mapped",[597]],[[7582,7582],"mapped",[240]],[[7583,7583],"mapped",[604]],[[7584,7584],"mapped",[102]],[[7585,7585],"mapped",[607]],[[7586,7586],"mapped",[609]],[[7587,7587],"mapped",[613]],[[7588,7588],"mapped",[616]],[[7589,7589],"mapped",[617]],[[7590,7590],"mapped",[618]],[[7591,7591],"mapped",[7547]],[[7592,7592],"mapped",[669]],[[7593,7593],"mapped",[621]],[[7594,7594],"mapped",[7557]],[[7595,7595],"mapped",[671]],[[7596,7596],"mapped",[625]],[[7597,7597],"mapped",[624]],[[7598,7598],"mapped",[626]],[[7599,7599],"mapped",[627]],[[7600,7600],"mapped",[628]],[[7601,7601],"mapped",[629]],[[7602,7602],"mapped",[632]],[[7603,7603],"mapped",[642]],[[7604,7604],"mapped",[643]],[[7605,7605],"mapped",[427]],[[7606,7606],"mapped",[649]],[[7607,7607],"mapped",[650]],[[7608,7608],"mapped",[7452]],[[7609,7609],"mapped",[651]],[[7610,7610],"mapped",[652]],[[7611,7611],"mapped",[122]],[[7612,7612],"mapped",[656]],[[7613,7613],"mapped",[657]],[[7614,7614],"mapped",[658]],[[7615,7615],"mapped",[952]],[[7616,7619],"valid"],[[7620,7626],"valid"],[[7627,7654],"valid"],[[7655,7669],"valid"],[[7670,7675],"disallowed"],[[7676,7676],"valid"],[[7677,7677],"valid"],[[7678,7679],"valid"],[[7680,7680],"mapped",[7681]],[[7681,7681],"valid"],[[7682,7682],"mapped",[7683]],[[7683,7683],"valid"],[[7684,7684],"mapped",[7685]],[[7685,7685],"valid"],[[7686,7686],"mapped",[7687]],[[7687,7687],"valid"],[[7688,7688],"mapped",[7689]],[[7689,7689],"valid"],[[7690,7690],"mapped",[7691]],[[7691,7691],"valid"],[[7692,7692],"mapped",[7693]],[[7693,7693],"valid"],[[7694,7694],"mapped",[7695]],[[7695,7695],"valid"],[[7696,7696],"mapped",[7697]],[[7697,7697],"valid"],[[7698,7698],"mapped",[7699]],[[7699,7699],"valid"],[[7700,7700],"mapped",[7701]],[[7701,7701],"valid"],[[7702,7702],"mapped",[7703]],[[7703,7703],"valid"],[[7704,7704],"mapped",[7705]],[[7705,7705],"valid"],[[7706,7706],"mapped",[7707]],[[7707,7707],"valid"],[[7708,7708],"mapped",[7709]],[[7709,7709],"valid"],[[7710,7710],"mapped",[7711]],[[7711,7711],"valid"],[[7712,7712],"mapped",[7713]],[[7713,7713],"valid"],[[7714,7714],"mapped",[7715]],[[7715,7715],"valid"],[[7716,7716],"mapped",[7717]],[[7717,7717],"valid"],[[7718,7718],"mapped",[7719]],[[7719,7719],"valid"],[[7720,7720],"mapped",[7721]],[[7721,7721],"valid"],[[7722,7722],"mapped",[7723]],[[7723,7723],"valid"],[[7724,7724],"mapped",[7725]],[[7725,7725],"valid"],[[7726,7726],"mapped",[7727]],[[7727,7727],"valid"],[[7728,7728],"mapped",[7729]],[[7729,7729],"valid"],[[7730,7730],"mapped",[7731]],[[7731,7731],"valid"],[[7732,7732],"mapped",[7733]],[[7733,7733],"valid"],[[7734,7734],"mapped",[7735]],[[7735,7735],"valid"],[[7736,7736],"mapped",[7737]],[[7737,7737],"valid"],[[7738,7738],"mapped",[7739]],[[7739,7739],"valid"],[[7740,7740],"mapped",[7741]],[[7741,7741],"valid"],[[7742,7742],"mapped",[7743]],[[7743,7743],"valid"],[[7744,7744],"mapped",[7745]],[[7745,7745],"valid"],[[7746,7746],"mapped",[7747]],[[7747,7747],"valid"],[[7748,7748],"mapped",[7749]],[[7749,7749],"valid"],[[7750,7750],"mapped",[7751]],[[7751,7751],"valid"],[[7752,7752],"mapped",[7753]],[[7753,7753],"valid"],[[7754,7754],"mapped",[7755]],[[7755,7755],"valid"],[[7756,7756],"mapped",[7757]],[[7757,7757],"valid"],[[7758,7758],"mapped",[7759]],[[7759,7759],"valid"],[[7760,7760],"mapped",[7761]],[[7761,7761],"valid"],[[7762,7762],"mapped",[7763]],[[7763,7763],"valid"],[[7764,7764],"mapped",[7765]],[[7765,7765],"valid"],[[7766,7766],"mapped",[7767]],[[7767,7767],"valid"],[[7768,7768],"mapped",[7769]],[[7769,7769],"valid"],[[7770,7770],"mapped",[7771]],[[7771,7771],"valid"],[[7772,7772],"mapped",[7773]],[[7773,7773],"valid"],[[7774,7774],"mapped",[7775]],[[7775,7775],"valid"],[[7776,7776],"mapped",[7777]],[[7777,7777],"valid"],[[7778,7778],"mapped",[7779]],[[7779,7779],"valid"],[[7780,7780],"mapped",[7781]],[[7781,7781],"valid"],[[7782,7782],"mapped",[7783]],[[7783,7783],"valid"],[[7784,7784],"mapped",[7785]],[[7785,7785],"valid"],[[7786,7786],"mapped",[7787]],[[7787,7787],"valid"],[[7788,7788],"mapped",[7789]],[[7789,7789],"valid"],[[7790,7790],"mapped",[7791]],[[7791,7791],"valid"],[[7792,7792],"mapped",[7793]],[[7793,7793],"valid"],[[7794,7794],"mapped",[7795]],[[7795,7795],"valid"],[[7796,7796],"mapped",[7797]],[[7797,7797],"valid"],[[7798,7798],"mapped",[7799]],[[7799,7799],"valid"],[[7800,7800],"mapped",[7801]],[[7801,7801],"valid"],[[7802,7802],"mapped",[7803]],[[7803,7803],"valid"],[[7804,7804],"mapped",[7805]],[[7805,7805],"valid"],[[7806,7806],"mapped",[7807]],[[7807,7807],"valid"],[[7808,7808],"mapped",[7809]],[[7809,7809],"valid"],[[7810,7810],"mapped",[7811]],[[7811,7811],"valid"],[[7812,7812],"mapped",[7813]],[[7813,7813],"valid"],[[7814,7814],"mapped",[7815]],[[7815,7815],"valid"],[[7816,7816],"mapped",[7817]],[[7817,7817],"valid"],[[7818,7818],"mapped",[7819]],[[7819,7819],"valid"],[[7820,7820],"mapped",[7821]],[[7821,7821],"valid"],[[7822,7822],"mapped",[7823]],[[7823,7823],"valid"],[[7824,7824],"mapped",[7825]],[[7825,7825],"valid"],[[7826,7826],"mapped",[7827]],[[7827,7827],"valid"],[[7828,7828],"mapped",[7829]],[[7829,7833],"valid"],[[7834,7834],"mapped",[97,702]],[[7835,7835],"mapped",[7777]],[[7836,7837],"valid"],[[7838,7838],"mapped",[115,115]],[[7839,7839],"valid"],[[7840,7840],"mapped",[7841]],[[7841,7841],"valid"],[[7842,7842],"mapped",[7843]],[[7843,7843],"valid"],[[7844,7844],"mapped",[7845]],[[7845,7845],"valid"],[[7846,7846],"mapped",[7847]],[[7847,7847],"valid"],[[7848,7848],"mapped",[7849]],[[7849,7849],"valid"],[[7850,7850],"mapped",[7851]],[[7851,7851],"valid"],[[7852,7852],"mapped",[7853]],[[7853,7853],"valid"],[[7854,7854],"mapped",[7855]],[[7855,7855],"valid"],[[7856,7856],"mapped",[7857]],[[7857,7857],"valid"],[[7858,7858],"mapped",[7859]],[[7859,7859],"valid"],[[7860,7860],"mapped",[7861]],[[7861,7861],"valid"],[[7862,7862],"mapped",[7863]],[[7863,7863],"valid"],[[7864,7864],"mapped",[7865]],[[7865,7865],"valid"],[[7866,7866],"mapped",[7867]],[[7867,7867],"valid"],[[7868,7868],"mapped",[7869]],[[7869,7869],"valid"],[[7870,7870],"mapped",[7871]],[[7871,7871],"valid"],[[7872,7872],"mapped",[7873]],[[7873,7873],"valid"],[[7874,7874],"mapped",[7875]],[[7875,7875],"valid"],[[7876,7876],"mapped",[7877]],[[7877,7877],"valid"],[[7878,7878],"mapped",[7879]],[[7879,7879],"valid"],[[7880,7880],"mapped",[7881]],[[7881,7881],"valid"],[[7882,7882],"mapped",[7883]],[[7883,7883],"valid"],[[7884,7884],"mapped",[7885]],[[7885,7885],"valid"],[[7886,7886],"mapped",[7887]],[[7887,7887],"valid"],[[7888,7888],"mapped",[7889]],[[7889,7889],"valid"],[[7890,7890],"mapped",[7891]],[[7891,7891],"valid"],[[7892,7892],"mapped",[7893]],[[7893,7893],"valid"],[[7894,7894],"mapped",[7895]],[[7895,7895],"valid"],[[7896,7896],"mapped",[7897]],[[7897,7897],"valid"],[[7898,7898],"mapped",[7899]],[[7899,7899],"valid"],[[7900,7900],"mapped",[7901]],[[7901,7901],"valid"],[[7902,7902],"mapped",[7903]],[[7903,7903],"valid"],[[7904,7904],"mapped",[7905]],[[7905,7905],"valid"],[[7906,7906],"mapped",[7907]],[[7907,7907],"valid"],[[7908,7908],"mapped",[7909]],[[7909,7909],"valid"],[[7910,7910],"mapped",[7911]],[[7911,7911],"valid"],[[7912,7912],"mapped",[7913]],[[7913,7913],"valid"],[[7914,7914],"mapped",[7915]],[[7915,7915],"valid"],[[7916,7916],"mapped",[7917]],[[7917,7917],"valid"],[[7918,7918],"mapped",[7919]],[[7919,7919],"valid"],[[7920,7920],"mapped",[7921]],[[7921,7921],"valid"],[[7922,7922],"mapped",[7923]],[[7923,7923],"valid"],[[7924,7924],"mapped",[7925]],[[7925,7925],"valid"],[[7926,7926],"mapped",[7927]],[[7927,7927],"valid"],[[7928,7928],"mapped",[7929]],[[7929,7929],"valid"],[[7930,7930],"mapped",[7931]],[[7931,7931],"valid"],[[7932,7932],"mapped",[7933]],[[7933,7933],"valid"],[[7934,7934],"mapped",[7935]],[[7935,7935],"valid"],[[7936,7943],"valid"],[[7944,7944],"mapped",[7936]],[[7945,7945],"mapped",[7937]],[[7946,7946],"mapped",[7938]],[[7947,7947],"mapped",[7939]],[[7948,7948],"mapped",[7940]],[[7949,7949],"mapped",[7941]],[[7950,7950],"mapped",[7942]],[[7951,7951],"mapped",[7943]],[[7952,7957],"valid"],[[7958,7959],"disallowed"],[[7960,7960],"mapped",[7952]],[[7961,7961],"mapped",[7953]],[[7962,7962],"mapped",[7954]],[[7963,7963],"mapped",[7955]],[[7964,7964],"mapped",[7956]],[[7965,7965],"mapped",[7957]],[[7966,7967],"disallowed"],[[7968,7975],"valid"],[[7976,7976],"mapped",[7968]],[[7977,7977],"mapped",[7969]],[[7978,7978],"mapped",[7970]],[[7979,7979],"mapped",[7971]],[[7980,7980],"mapped",[7972]],[[7981,7981],"mapped",[7973]],[[7982,7982],"mapped",[7974]],[[7983,7983],"mapped",[7975]],[[7984,7991],"valid"],[[7992,7992],"mapped",[7984]],[[7993,7993],"mapped",[7985]],[[7994,7994],"mapped",[7986]],[[7995,7995],"mapped",[7987]],[[7996,7996],"mapped",[7988]],[[7997,7997],"mapped",[7989]],[[7998,7998],"mapped",[7990]],[[7999,7999],"mapped",[7991]],[[8000,8005],"valid"],[[8006,8007],"disallowed"],[[8008,8008],"mapped",[8000]],[[8009,8009],"mapped",[8001]],[[8010,8010],"mapped",[8002]],[[8011,8011],"mapped",[8003]],[[8012,8012],"mapped",[8004]],[[8013,8013],"mapped",[8005]],[[8014,8015],"disallowed"],[[8016,8023],"valid"],[[8024,8024],"disallowed"],[[8025,8025],"mapped",[8017]],[[8026,8026],"disallowed"],[[8027,8027],"mapped",[8019]],[[8028,8028],"disallowed"],[[8029,8029],"mapped",[8021]],[[8030,8030],"disallowed"],[[8031,8031],"mapped",[8023]],[[8032,8039],"valid"],[[8040,8040],"mapped",[8032]],[[8041,8041],"mapped",[8033]],[[8042,8042],"mapped",[8034]],[[8043,8043],"mapped",[8035]],[[8044,8044],"mapped",[8036]],[[8045,8045],"mapped",[8037]],[[8046,8046],"mapped",[8038]],[[8047,8047],"mapped",[8039]],[[8048,8048],"valid"],[[8049,8049],"mapped",[940]],[[8050,8050],"valid"],[[8051,8051],"mapped",[941]],[[8052,8052],"valid"],[[8053,8053],"mapped",[942]],[[8054,8054],"valid"],[[8055,8055],"mapped",[943]],[[8056,8056],"valid"],[[8057,8057],"mapped",[972]],[[8058,8058],"valid"],[[8059,8059],"mapped",[973]],[[8060,8060],"valid"],[[8061,8061],"mapped",[974]],[[8062,8063],"disallowed"],[[8064,8064],"mapped",[7936,953]],[[8065,8065],"mapped",[7937,953]],[[8066,8066],"mapped",[7938,953]],[[8067,8067],"mapped",[7939,953]],[[8068,8068],"mapped",[7940,953]],[[8069,8069],"mapped",[7941,953]],[[8070,8070],"mapped",[7942,953]],[[8071,8071],"mapped",[7943,953]],[[8072,8072],"mapped",[7936,953]],[[8073,8073],"mapped",[7937,953]],[[8074,8074],"mapped",[7938,953]],[[8075,8075],"mapped",[7939,953]],[[8076,8076],"mapped",[7940,953]],[[8077,8077],"mapped",[7941,953]],[[8078,8078],"mapped",[7942,953]],[[8079,8079],"mapped",[7943,953]],[[8080,8080],"mapped",[7968,953]],[[8081,8081],"mapped",[7969,953]],[[8082,8082],"mapped",[7970,953]],[[8083,8083],"mapped",[7971,953]],[[8084,8084],"mapped",[7972,953]],[[8085,8085],"mapped",[7973,953]],[[8086,8086],"mapped",[7974,953]],[[8087,8087],"mapped",[7975,953]],[[8088,8088],"mapped",[7968,953]],[[8089,8089],"mapped",[7969,953]],[[8090,8090],"mapped",[7970,953]],[[8091,8091],"mapped",[7971,953]],[[8092,8092],"mapped",[7972,953]],[[8093,8093],"mapped",[7973,953]],[[8094,8094],"mapped",[7974,953]],[[8095,8095],"mapped",[7975,953]],[[8096,8096],"mapped",[8032,953]],[[8097,8097],"mapped",[8033,953]],[[8098,8098],"mapped",[8034,953]],[[8099,8099],"mapped",[8035,953]],[[8100,8100],"mapped",[8036,953]],[[8101,8101],"mapped",[8037,953]],[[8102,8102],"mapped",[8038,953]],[[8103,8103],"mapped",[8039,953]],[[8104,8104],"mapped",[8032,953]],[[8105,8105],"mapped",[8033,953]],[[8106,8106],"mapped",[8034,953]],[[8107,8107],"mapped",[8035,953]],[[8108,8108],"mapped",[8036,953]],[[8109,8109],"mapped",[8037,953]],[[8110,8110],"mapped",[8038,953]],[[8111,8111],"mapped",[8039,953]],[[8112,8113],"valid"],[[8114,8114],"mapped",[8048,953]],[[8115,8115],"mapped",[945,953]],[[8116,8116],"mapped",[940,953]],[[8117,8117],"disallowed"],[[8118,8118],"valid"],[[8119,8119],"mapped",[8118,953]],[[8120,8120],"mapped",[8112]],[[8121,8121],"mapped",[8113]],[[8122,8122],"mapped",[8048]],[[8123,8123],"mapped",[940]],[[8124,8124],"mapped",[945,953]],[[8125,8125],"disallowed_STD3_mapped",[32,787]],[[8126,8126],"mapped",[953]],[[8127,8127],"disallowed_STD3_mapped",[32,787]],[[8128,8128],"disallowed_STD3_mapped",[32,834]],[[8129,8129],"disallowed_STD3_mapped",[32,776,834]],[[8130,8130],"mapped",[8052,953]],[[8131,8131],"mapped",[951,953]],[[8132,8132],"mapped",[942,953]],[[8133,8133],"disallowed"],[[8134,8134],"valid"],[[8135,8135],"mapped",[8134,953]],[[8136,8136],"mapped",[8050]],[[8137,8137],"mapped",[941]],[[8138,8138],"mapped",[8052]],[[8139,8139],"mapped",[942]],[[8140,8140],"mapped",[951,953]],[[8141,8141],"disallowed_STD3_mapped",[32,787,768]],[[8142,8142],"disallowed_STD3_mapped",[32,787,769]],[[8143,8143],"disallowed_STD3_mapped",[32,787,834]],[[8144,8146],"valid"],[[8147,8147],"mapped",[912]],[[8148,8149],"disallowed"],[[8150,8151],"valid"],[[8152,8152],"mapped",[8144]],[[8153,8153],"mapped",[8145]],[[8154,8154],"mapped",[8054]],[[8155,8155],"mapped",[943]],[[8156,8156],"disallowed"],[[8157,8157],"disallowed_STD3_mapped",[32,788,768]],[[8158,8158],"disallowed_STD3_mapped",[32,788,769]],[[8159,8159],"disallowed_STD3_mapped",[32,788,834]],[[8160,8162],"valid"],[[8163,8163],"mapped",[944]],[[8164,8167],"valid"],[[8168,8168],"mapped",[8160]],[[8169,8169],"mapped",[8161]],[[8170,8170],"mapped",[8058]],[[8171,8171],"mapped",[973]],[[8172,8172],"mapped",[8165]],[[8173,8173],"disallowed_STD3_mapped",[32,776,768]],[[8174,8174],"disallowed_STD3_mapped",[32,776,769]],[[8175,8175],"disallowed_STD3_mapped",[96]],[[8176,8177],"disallowed"],[[8178,8178],"mapped",[8060,953]],[[8179,8179],"mapped",[969,953]],[[8180,8180],"mapped",[974,953]],[[8181,8181],"disallowed"],[[8182,8182],"valid"],[[8183,8183],"mapped",[8182,953]],[[8184,8184],"mapped",[8056]],[[8185,8185],"mapped",[972]],[[8186,8186],"mapped",[8060]],[[8187,8187],"mapped",[974]],[[8188,8188],"mapped",[969,953]],[[8189,8189],"disallowed_STD3_mapped",[32,769]],[[8190,8190],"disallowed_STD3_mapped",[32,788]],[[8191,8191],"disallowed"],[[8192,8202],"disallowed_STD3_mapped",[32]],[[8203,8203],"ignored"],[[8204,8205],"deviation",[]],[[8206,8207],"disallowed"],[[8208,8208],"valid",[],"NV8"],[[8209,8209],"mapped",[8208]],[[8210,8214],"valid",[],"NV8"],[[8215,8215],"disallowed_STD3_mapped",[32,819]],[[8216,8227],"valid",[],"NV8"],[[8228,8230],"disallowed"],[[8231,8231],"valid",[],"NV8"],[[8232,8238],"disallowed"],[[8239,8239],"disallowed_STD3_mapped",[32]],[[8240,8242],"valid",[],"NV8"],[[8243,8243],"mapped",[8242,8242]],[[8244,8244],"mapped",[8242,8242,8242]],[[8245,8245],"valid",[],"NV8"],[[8246,8246],"mapped",[8245,8245]],[[8247,8247],"mapped",[8245,8245,8245]],[[8248,8251],"valid",[],"NV8"],[[8252,8252],"disallowed_STD3_mapped",[33,33]],[[8253,8253],"valid",[],"NV8"],[[8254,8254],"disallowed_STD3_mapped",[32,773]],[[8255,8262],"valid",[],"NV8"],[[8263,8263],"disallowed_STD3_mapped",[63,63]],[[8264,8264],"disallowed_STD3_mapped",[63,33]],[[8265,8265],"disallowed_STD3_mapped",[33,63]],[[8266,8269],"valid",[],"NV8"],[[8270,8274],"valid",[],"NV8"],[[8275,8276],"valid",[],"NV8"],[[8277,8278],"valid",[],"NV8"],[[8279,8279],"mapped",[8242,8242,8242,8242]],[[8280,8286],"valid",[],"NV8"],[[8287,8287],"disallowed_STD3_mapped",[32]],[[8288,8288],"ignored"],[[8289,8291],"disallowed"],[[8292,8292],"ignored"],[[8293,8293],"disallowed"],[[8294,8297],"disallowed"],[[8298,8303],"disallowed"],[[8304,8304],"mapped",[48]],[[8305,8305],"mapped",[105]],[[8306,8307],"disallowed"],[[8308,8308],"mapped",[52]],[[8309,8309],"mapped",[53]],[[8310,8310],"mapped",[54]],[[8311,8311],"mapped",[55]],[[8312,8312],"mapped",[56]],[[8313,8313],"mapped",[57]],[[8314,8314],"disallowed_STD3_mapped",[43]],[[8315,8315],"mapped",[8722]],[[8316,8316],"disallowed_STD3_mapped",[61]],[[8317,8317],"disallowed_STD3_mapped",[40]],[[8318,8318],"disallowed_STD3_mapped",[41]],[[8319,8319],"mapped",[110]],[[8320,8320],"mapped",[48]],[[8321,8321],"mapped",[49]],[[8322,8322],"mapped",[50]],[[8323,8323],"mapped",[51]],[[8324,8324],"mapped",[52]],[[8325,8325],"mapped",[53]],[[8326,8326],"mapped",[54]],[[8327,8327],"mapped",[55]],[[8328,8328],"mapped",[56]],[[8329,8329],"mapped",[57]],[[8330,8330],"disallowed_STD3_mapped",[43]],[[8331,8331],"mapped",[8722]],[[8332,8332],"disallowed_STD3_mapped",[61]],[[8333,8333],"disallowed_STD3_mapped",[40]],[[8334,8334],"disallowed_STD3_mapped",[41]],[[8335,8335],"disallowed"],[[8336,8336],"mapped",[97]],[[8337,8337],"mapped",[101]],[[8338,8338],"mapped",[111]],[[8339,8339],"mapped",[120]],[[8340,8340],"mapped",[601]],[[8341,8341],"mapped",[104]],[[8342,8342],"mapped",[107]],[[8343,8343],"mapped",[108]],[[8344,8344],"mapped",[109]],[[8345,8345],"mapped",[110]],[[8346,8346],"mapped",[112]],[[8347,8347],"mapped",[115]],[[8348,8348],"mapped",[116]],[[8349,8351],"disallowed"],[[8352,8359],"valid",[],"NV8"],[[8360,8360],"mapped",[114,115]],[[8361,8362],"valid",[],"NV8"],[[8363,8363],"valid",[],"NV8"],[[8364,8364],"valid",[],"NV8"],[[8365,8367],"valid",[],"NV8"],[[8368,8369],"valid",[],"NV8"],[[8370,8373],"valid",[],"NV8"],[[8374,8376],"valid",[],"NV8"],[[8377,8377],"valid",[],"NV8"],[[8378,8378],"valid",[],"NV8"],[[8379,8381],"valid",[],"NV8"],[[8382,8382],"valid",[],"NV8"],[[8383,8399],"disallowed"],[[8400,8417],"valid",[],"NV8"],[[8418,8419],"valid",[],"NV8"],[[8420,8426],"valid",[],"NV8"],[[8427,8427],"valid",[],"NV8"],[[8428,8431],"valid",[],"NV8"],[[8432,8432],"valid",[],"NV8"],[[8433,8447],"disallowed"],[[8448,8448],"disallowed_STD3_mapped",[97,47,99]],[[8449,8449],"disallowed_STD3_mapped",[97,47,115]],[[8450,8450],"mapped",[99]],[[8451,8451],"mapped",[176,99]],[[8452,8452],"valid",[],"NV8"],[[8453,8453],"disallowed_STD3_mapped",[99,47,111]],[[8454,8454],"disallowed_STD3_mapped",[99,47,117]],[[8455,8455],"mapped",[603]],[[8456,8456],"valid",[],"NV8"],[[8457,8457],"mapped",[176,102]],[[8458,8458],"mapped",[103]],[[8459,8462],"mapped",[104]],[[8463,8463],"mapped",[295]],[[8464,8465],"mapped",[105]],[[8466,8467],"mapped",[108]],[[8468,8468],"valid",[],"NV8"],[[8469,8469],"mapped",[110]],[[8470,8470],"mapped",[110,111]],[[8471,8472],"valid",[],"NV8"],[[8473,8473],"mapped",[112]],[[8474,8474],"mapped",[113]],[[8475,8477],"mapped",[114]],[[8478,8479],"valid",[],"NV8"],[[8480,8480],"mapped",[115,109]],[[8481,8481],"mapped",[116,101,108]],[[8482,8482],"mapped",[116,109]],[[8483,8483],"valid",[],"NV8"],[[8484,8484],"mapped",[122]],[[8485,8485],"valid",[],"NV8"],[[8486,8486],"mapped",[969]],[[8487,8487],"valid",[],"NV8"],[[8488,8488],"mapped",[122]],[[8489,8489],"valid",[],"NV8"],[[8490,8490],"mapped",[107]],[[8491,8491],"mapped",[229]],[[8492,8492],"mapped",[98]],[[8493,8493],"mapped",[99]],[[8494,8494],"valid",[],"NV8"],[[8495,8496],"mapped",[101]],[[8497,8497],"mapped",[102]],[[8498,8498],"disallowed"],[[8499,8499],"mapped",[109]],[[8500,8500],"mapped",[111]],[[8501,8501],"mapped",[1488]],[[8502,8502],"mapped",[1489]],[[8503,8503],"mapped",[1490]],[[8504,8504],"mapped",[1491]],[[8505,8505],"mapped",[105]],[[8506,8506],"valid",[],"NV8"],[[8507,8507],"mapped",[102,97,120]],[[8508,8508],"mapped",[960]],[[8509,8510],"mapped",[947]],[[8511,8511],"mapped",[960]],[[8512,8512],"mapped",[8721]],[[8513,8516],"valid",[],"NV8"],[[8517,8518],"mapped",[100]],[[8519,8519],"mapped",[101]],[[8520,8520],"mapped",[105]],[[8521,8521],"mapped",[106]],[[8522,8523],"valid",[],"NV8"],[[8524,8524],"valid",[],"NV8"],[[8525,8525],"valid",[],"NV8"],[[8526,8526],"valid"],[[8527,8527],"valid",[],"NV8"],[[8528,8528],"mapped",[49,8260,55]],[[8529,8529],"mapped",[49,8260,57]],[[8530,8530],"mapped",[49,8260,49,48]],[[8531,8531],"mapped",[49,8260,51]],[[8532,8532],"mapped",[50,8260,51]],[[8533,8533],"mapped",[49,8260,53]],[[8534,8534],"mapped",[50,8260,53]],[[8535,8535],"mapped",[51,8260,53]],[[8536,8536],"mapped",[52,8260,53]],[[8537,8537],"mapped",[49,8260,54]],[[8538,8538],"mapped",[53,8260,54]],[[8539,8539],"mapped",[49,8260,56]],[[8540,8540],"mapped",[51,8260,56]],[[8541,8541],"mapped",[53,8260,56]],[[8542,8542],"mapped",[55,8260,56]],[[8543,8543],"mapped",[49,8260]],[[8544,8544],"mapped",[105]],[[8545,8545],"mapped",[105,105]],[[8546,8546],"mapped",[105,105,105]],[[8547,8547],"mapped",[105,118]],[[8548,8548],"mapped",[118]],[[8549,8549],"mapped",[118,105]],[[8550,8550],"mapped",[118,105,105]],[[8551,8551],"mapped",[118,105,105,105]],[[8552,8552],"mapped",[105,120]],[[8553,8553],"mapped",[120]],[[8554,8554],"mapped",[120,105]],[[8555,8555],"mapped",[120,105,105]],[[8556,8556],"mapped",[108]],[[8557,8557],"mapped",[99]],[[8558,8558],"mapped",[100]],[[8559,8559],"mapped",[109]],[[8560,8560],"mapped",[105]],[[8561,8561],"mapped",[105,105]],[[8562,8562],"mapped",[105,105,105]],[[8563,8563],"mapped",[105,118]],[[8564,8564],"mapped",[118]],[[8565,8565],"mapped",[118,105]],[[8566,8566],"mapped",[118,105,105]],[[8567,8567],"mapped",[118,105,105,105]],[[8568,8568],"mapped",[105,120]],[[8569,8569],"mapped",[120]],[[8570,8570],"mapped",[120,105]],[[8571,8571],"mapped",[120,105,105]],[[8572,8572],"mapped",[108]],[[8573,8573],"mapped",[99]],[[8574,8574],"mapped",[100]],[[8575,8575],"mapped",[109]],[[8576,8578],"valid",[],"NV8"],[[8579,8579],"disallowed"],[[8580,8580],"valid"],[[8581,8584],"valid",[],"NV8"],[[8585,8585],"mapped",[48,8260,51]],[[8586,8587],"valid",[],"NV8"],[[8588,8591],"disallowed"],[[8592,8682],"valid",[],"NV8"],[[8683,8691],"valid",[],"NV8"],[[8692,8703],"valid",[],"NV8"],[[8704,8747],"valid",[],"NV8"],[[8748,8748],"mapped",[8747,8747]],[[8749,8749],"mapped",[8747,8747,8747]],[[8750,8750],"valid",[],"NV8"],[[8751,8751],"mapped",[8750,8750]],[[8752,8752],"mapped",[8750,8750,8750]],[[8753,8799],"valid",[],"NV8"],[[8800,8800],"disallowed_STD3_valid"],[[8801,8813],"valid",[],"NV8"],[[8814,8815],"disallowed_STD3_valid"],[[8816,8945],"valid",[],"NV8"],[[8946,8959],"valid",[],"NV8"],[[8960,8960],"valid",[],"NV8"],[[8961,8961],"valid",[],"NV8"],[[8962,9000],"valid",[],"NV8"],[[9001,9001],"mapped",[12296]],[[9002,9002],"mapped",[12297]],[[9003,9082],"valid",[],"NV8"],[[9083,9083],"valid",[],"NV8"],[[9084,9084],"valid",[],"NV8"],[[9085,9114],"valid",[],"NV8"],[[9115,9166],"valid",[],"NV8"],[[9167,9168],"valid",[],"NV8"],[[9169,9179],"valid",[],"NV8"],[[9180,9191],"valid",[],"NV8"],[[9192,9192],"valid",[],"NV8"],[[9193,9203],"valid",[],"NV8"],[[9204,9210],"valid",[],"NV8"],[[9211,9215],"disallowed"],[[9216,9252],"valid",[],"NV8"],[[9253,9254],"valid",[],"NV8"],[[9255,9279],"disallowed"],[[9280,9290],"valid",[],"NV8"],[[9291,9311],"disallowed"],[[9312,9312],"mapped",[49]],[[9313,9313],"mapped",[50]],[[9314,9314],"mapped",[51]],[[9315,9315],"mapped",[52]],[[9316,9316],"mapped",[53]],[[9317,9317],"mapped",[54]],[[9318,9318],"mapped",[55]],[[9319,9319],"mapped",[56]],[[9320,9320],"mapped",[57]],[[9321,9321],"mapped",[49,48]],[[9322,9322],"mapped",[49,49]],[[9323,9323],"mapped",[49,50]],[[9324,9324],"mapped",[49,51]],[[9325,9325],"mapped",[49,52]],[[9326,9326],"mapped",[49,53]],[[9327,9327],"mapped",[49,54]],[[9328,9328],"mapped",[49,55]],[[9329,9329],"mapped",[49,56]],[[9330,9330],"mapped",[49,57]],[[9331,9331],"mapped",[50,48]],[[9332,9332],"disallowed_STD3_mapped",[40,49,41]],[[9333,9333],"disallowed_STD3_mapped",[40,50,41]],[[9334,9334],"disallowed_STD3_mapped",[40,51,41]],[[9335,9335],"disallowed_STD3_mapped",[40,52,41]],[[9336,9336],"disallowed_STD3_mapped",[40,53,41]],[[9337,9337],"disallowed_STD3_mapped",[40,54,41]],[[9338,9338],"disallowed_STD3_mapped",[40,55,41]],[[9339,9339],"disallowed_STD3_mapped",[40,56,41]],[[9340,9340],"disallowed_STD3_mapped",[40,57,41]],[[9341,9341],"disallowed_STD3_mapped",[40,49,48,41]],[[9342,9342],"disallowed_STD3_mapped",[40,49,49,41]],[[9343,9343],"disallowed_STD3_mapped",[40,49,50,41]],[[9344,9344],"disallowed_STD3_mapped",[40,49,51,41]],[[9345,9345],"disallowed_STD3_mapped",[40,49,52,41]],[[9346,9346],"disallowed_STD3_mapped",[40,49,53,41]],[[9347,9347],"disallowed_STD3_mapped",[40,49,54,41]],[[9348,9348],"disallowed_STD3_mapped",[40,49,55,41]],[[9349,9349],"disallowed_STD3_mapped",[40,49,56,41]],[[9350,9350],"disallowed_STD3_mapped",[40,49,57,41]],[[9351,9351],"disallowed_STD3_mapped",[40,50,48,41]],[[9352,9371],"disallowed"],[[9372,9372],"disallowed_STD3_mapped",[40,97,41]],[[9373,9373],"disallowed_STD3_mapped",[40,98,41]],[[9374,9374],"disallowed_STD3_mapped",[40,99,41]],[[9375,9375],"disallowed_STD3_mapped",[40,100,41]],[[9376,9376],"disallowed_STD3_mapped",[40,101,41]],[[9377,9377],"disallowed_STD3_mapped",[40,102,41]],[[9378,9378],"disallowed_STD3_mapped",[40,103,41]],[[9379,9379],"disallowed_STD3_mapped",[40,104,41]],[[9380,9380],"disallowed_STD3_mapped",[40,105,41]],[[9381,9381],"disallowed_STD3_mapped",[40,106,41]],[[9382,9382],"disallowed_STD3_mapped",[40,107,41]],[[9383,9383],"disallowed_STD3_mapped",[40,108,41]],[[9384,9384],"disallowed_STD3_mapped",[40,109,41]],[[9385,9385],"disallowed_STD3_mapped",[40,110,41]],[[9386,9386],"disallowed_STD3_mapped",[40,111,41]],[[9387,9387],"disallowed_STD3_mapped",[40,112,41]],[[9388,9388],"disallowed_STD3_mapped",[40,113,41]],[[9389,9389],"disallowed_STD3_mapped",[40,114,41]],[[9390,9390],"disallowed_STD3_mapped",[40,115,41]],[[9391,9391],"disallowed_STD3_mapped",[40,116,41]],[[9392,9392],"disallowed_STD3_mapped",[40,117,41]],[[9393,9393],"disallowed_STD3_mapped",[40,118,41]],[[9394,9394],"disallowed_STD3_mapped",[40,119,41]],[[9395,9395],"disallowed_STD3_mapped",[40,120,41]],[[9396,9396],"disallowed_STD3_mapped",[40,121,41]],[[9397,9397],"disallowed_STD3_mapped",[40,122,41]],[[9398,9398],"mapped",[97]],[[9399,9399],"mapped",[98]],[[9400,9400],"mapped",[99]],[[9401,9401],"mapped",[100]],[[9402,9402],"mapped",[101]],[[9403,9403],"mapped",[102]],[[9404,9404],"mapped",[103]],[[9405,9405],"mapped",[104]],[[9406,9406],"mapped",[105]],[[9407,9407],"mapped",[106]],[[9408,9408],"mapped",[107]],[[9409,9409],"mapped",[108]],[[9410,9410],"mapped",[109]],[[9411,9411],"mapped",[110]],[[9412,9412],"mapped",[111]],[[9413,9413],"mapped",[112]],[[9414,9414],"mapped",[113]],[[9415,9415],"mapped",[114]],[[9416,9416],"mapped",[115]],[[9417,9417],"mapped",[116]],[[9418,9418],"mapped",[117]],[[9419,9419],"mapped",[118]],[[9420,9420],"mapped",[119]],[[9421,9421],"mapped",[120]],[[9422,9422],"mapped",[121]],[[9423,9423],"mapped",[122]],[[9424,9424],"mapped",[97]],[[9425,9425],"mapped",[98]],[[9426,9426],"mapped",[99]],[[9427,9427],"mapped",[100]],[[9428,9428],"mapped",[101]],[[9429,9429],"mapped",[102]],[[9430,9430],"mapped",[103]],[[9431,9431],"mapped",[104]],[[9432,9432],"mapped",[105]],[[9433,9433],"mapped",[106]],[[9434,9434],"mapped",[107]],[[9435,9435],"mapped",[108]],[[9436,9436],"mapped",[109]],[[9437,9437],"mapped",[110]],[[9438,9438],"mapped",[111]],[[9439,9439],"mapped",[112]],[[9440,9440],"mapped",[113]],[[9441,9441],"mapped",[114]],[[9442,9442],"mapped",[115]],[[9443,9443],"mapped",[116]],[[9444,9444],"mapped",[117]],[[9445,9445],"mapped",[118]],[[9446,9446],"mapped",[119]],[[9447,9447],"mapped",[120]],[[9448,9448],"mapped",[121]],[[9449,9449],"mapped",[122]],[[9450,9450],"mapped",[48]],[[9451,9470],"valid",[],"NV8"],[[9471,9471],"valid",[],"NV8"],[[9472,9621],"valid",[],"NV8"],[[9622,9631],"valid",[],"NV8"],[[9632,9711],"valid",[],"NV8"],[[9712,9719],"valid",[],"NV8"],[[9720,9727],"valid",[],"NV8"],[[9728,9747],"valid",[],"NV8"],[[9748,9749],"valid",[],"NV8"],[[9750,9751],"valid",[],"NV8"],[[9752,9752],"valid",[],"NV8"],[[9753,9753],"valid",[],"NV8"],[[9754,9839],"valid",[],"NV8"],[[9840,9841],"valid",[],"NV8"],[[9842,9853],"valid",[],"NV8"],[[9854,9855],"valid",[],"NV8"],[[9856,9865],"valid",[],"NV8"],[[9866,9873],"valid",[],"NV8"],[[9874,9884],"valid",[],"NV8"],[[9885,9885],"valid",[],"NV8"],[[9886,9887],"valid",[],"NV8"],[[9888,9889],"valid",[],"NV8"],[[9890,9905],"valid",[],"NV8"],[[9906,9906],"valid",[],"NV8"],[[9907,9916],"valid",[],"NV8"],[[9917,9919],"valid",[],"NV8"],[[9920,9923],"valid",[],"NV8"],[[9924,9933],"valid",[],"NV8"],[[9934,9934],"valid",[],"NV8"],[[9935,9953],"valid",[],"NV8"],[[9954,9954],"valid",[],"NV8"],[[9955,9955],"valid",[],"NV8"],[[9956,9959],"valid",[],"NV8"],[[9960,9983],"valid",[],"NV8"],[[9984,9984],"valid",[],"NV8"],[[9985,9988],"valid",[],"NV8"],[[9989,9989],"valid",[],"NV8"],[[9990,9993],"valid",[],"NV8"],[[9994,9995],"valid",[],"NV8"],[[9996,10023],"valid",[],"NV8"],[[10024,10024],"valid",[],"NV8"],[[10025,10059],"valid",[],"NV8"],[[10060,10060],"valid",[],"NV8"],[[10061,10061],"valid",[],"NV8"],[[10062,10062],"valid",[],"NV8"],[[10063,10066],"valid",[],"NV8"],[[10067,10069],"valid",[],"NV8"],[[10070,10070],"valid",[],"NV8"],[[10071,10071],"valid",[],"NV8"],[[10072,10078],"valid",[],"NV8"],[[10079,10080],"valid",[],"NV8"],[[10081,10087],"valid",[],"NV8"],[[10088,10101],"valid",[],"NV8"],[[10102,10132],"valid",[],"NV8"],[[10133,10135],"valid",[],"NV8"],[[10136,10159],"valid",[],"NV8"],[[10160,10160],"valid",[],"NV8"],[[10161,10174],"valid",[],"NV8"],[[10175,10175],"valid",[],"NV8"],[[10176,10182],"valid",[],"NV8"],[[10183,10186],"valid",[],"NV8"],[[10187,10187],"valid",[],"NV8"],[[10188,10188],"valid",[],"NV8"],[[10189,10189],"valid",[],"NV8"],[[10190,10191],"valid",[],"NV8"],[[10192,10219],"valid",[],"NV8"],[[10220,10223],"valid",[],"NV8"],[[10224,10239],"valid",[],"NV8"],[[10240,10495],"valid",[],"NV8"],[[10496,10763],"valid",[],"NV8"],[[10764,10764],"mapped",[8747,8747,8747,8747]],[[10765,10867],"valid",[],"NV8"],[[10868,10868],"disallowed_STD3_mapped",[58,58,61]],[[10869,10869],"disallowed_STD3_mapped",[61,61]],[[10870,10870],"disallowed_STD3_mapped",[61,61,61]],[[10871,10971],"valid",[],"NV8"],[[10972,10972],"mapped",[10973,824]],[[10973,11007],"valid",[],"NV8"],[[11008,11021],"valid",[],"NV8"],[[11022,11027],"valid",[],"NV8"],[[11028,11034],"valid",[],"NV8"],[[11035,11039],"valid",[],"NV8"],[[11040,11043],"valid",[],"NV8"],[[11044,11084],"valid",[],"NV8"],[[11085,11087],"valid",[],"NV8"],[[11088,11092],"valid",[],"NV8"],[[11093,11097],"valid",[],"NV8"],[[11098,11123],"valid",[],"NV8"],[[11124,11125],"disallowed"],[[11126,11157],"valid",[],"NV8"],[[11158,11159],"disallowed"],[[11160,11193],"valid",[],"NV8"],[[11194,11196],"disallowed"],[[11197,11208],"valid",[],"NV8"],[[11209,11209],"disallowed"],[[11210,11217],"valid",[],"NV8"],[[11218,11243],"disallowed"],[[11244,11247],"valid",[],"NV8"],[[11248,11263],"disallowed"],[[11264,11264],"mapped",[11312]],[[11265,11265],"mapped",[11313]],[[11266,11266],"mapped",[11314]],[[11267,11267],"mapped",[11315]],[[11268,11268],"mapped",[11316]],[[11269,11269],"mapped",[11317]],[[11270,11270],"mapped",[11318]],[[11271,11271],"mapped",[11319]],[[11272,11272],"mapped",[11320]],[[11273,11273],"mapped",[11321]],[[11274,11274],"mapped",[11322]],[[11275,11275],"mapped",[11323]],[[11276,11276],"mapped",[11324]],[[11277,11277],"mapped",[11325]],[[11278,11278],"mapped",[11326]],[[11279,11279],"mapped",[11327]],[[11280,11280],"mapped",[11328]],[[11281,11281],"mapped",[11329]],[[11282,11282],"mapped",[11330]],[[11283,11283],"mapped",[11331]],[[11284,11284],"mapped",[11332]],[[11285,11285],"mapped",[11333]],[[11286,11286],"mapped",[11334]],[[11287,11287],"mapped",[11335]],[[11288,11288],"mapped",[11336]],[[11289,11289],"mapped",[11337]],[[11290,11290],"mapped",[11338]],[[11291,11291],"mapped",[11339]],[[11292,11292],"mapped",[11340]],[[11293,11293],"mapped",[11341]],[[11294,11294],"mapped",[11342]],[[11295,11295],"mapped",[11343]],[[11296,11296],"mapped",[11344]],[[11297,11297],"mapped",[11345]],[[11298,11298],"mapped",[11346]],[[11299,11299],"mapped",[11347]],[[11300,11300],"mapped",[11348]],[[11301,11301],"mapped",[11349]],[[11302,11302],"mapped",[11350]],[[11303,11303],"mapped",[11351]],[[11304,11304],"mapped",[11352]],[[11305,11305],"mapped",[11353]],[[11306,11306],"mapped",[11354]],[[11307,11307],"mapped",[11355]],[[11308,11308],"mapped",[11356]],[[11309,11309],"mapped",[11357]],[[11310,11310],"mapped",[11358]],[[11311,11311],"disallowed"],[[11312,11358],"valid"],[[11359,11359],"disallowed"],[[11360,11360],"mapped",[11361]],[[11361,11361],"valid"],[[11362,11362],"mapped",[619]],[[11363,11363],"mapped",[7549]],[[11364,11364],"mapped",[637]],[[11365,11366],"valid"],[[11367,11367],"mapped",[11368]],[[11368,11368],"valid"],[[11369,11369],"mapped",[11370]],[[11370,11370],"valid"],[[11371,11371],"mapped",[11372]],[[11372,11372],"valid"],[[11373,11373],"mapped",[593]],[[11374,11374],"mapped",[625]],[[11375,11375],"mapped",[592]],[[11376,11376],"mapped",[594]],[[11377,11377],"valid"],[[11378,11378],"mapped",[11379]],[[11379,11379],"valid"],[[11380,11380],"valid"],[[11381,11381],"mapped",[11382]],[[11382,11383],"valid"],[[11384,11387],"valid"],[[11388,11388],"mapped",[106]],[[11389,11389],"mapped",[118]],[[11390,11390],"mapped",[575]],[[11391,11391],"mapped",[576]],[[11392,11392],"mapped",[11393]],[[11393,11393],"valid"],[[11394,11394],"mapped",[11395]],[[11395,11395],"valid"],[[11396,11396],"mapped",[11397]],[[11397,11397],"valid"],[[11398,11398],"mapped",[11399]],[[11399,11399],"valid"],[[11400,11400],"mapped",[11401]],[[11401,11401],"valid"],[[11402,11402],"mapped",[11403]],[[11403,11403],"valid"],[[11404,11404],"mapped",[11405]],[[11405,11405],"valid"],[[11406,11406],"mapped",[11407]],[[11407,11407],"valid"],[[11408,11408],"mapped",[11409]],[[11409,11409],"valid"],[[11410,11410],"mapped",[11411]],[[11411,11411],"valid"],[[11412,11412],"mapped",[11413]],[[11413,11413],"valid"],[[11414,11414],"mapped",[11415]],[[11415,11415],"valid"],[[11416,11416],"mapped",[11417]],[[11417,11417],"valid"],[[11418,11418],"mapped",[11419]],[[11419,11419],"valid"],[[11420,11420],"mapped",[11421]],[[11421,11421],"valid"],[[11422,11422],"mapped",[11423]],[[11423,11423],"valid"],[[11424,11424],"mapped",[11425]],[[11425,11425],"valid"],[[11426,11426],"mapped",[11427]],[[11427,11427],"valid"],[[11428,11428],"mapped",[11429]],[[11429,11429],"valid"],[[11430,11430],"mapped",[11431]],[[11431,11431],"valid"],[[11432,11432],"mapped",[11433]],[[11433,11433],"valid"],[[11434,11434],"mapped",[11435]],[[11435,11435],"valid"],[[11436,11436],"mapped",[11437]],[[11437,11437],"valid"],[[11438,11438],"mapped",[11439]],[[11439,11439],"valid"],[[11440,11440],"mapped",[11441]],[[11441,11441],"valid"],[[11442,11442],"mapped",[11443]],[[11443,11443],"valid"],[[11444,11444],"mapped",[11445]],[[11445,11445],"valid"],[[11446,11446],"mapped",[11447]],[[11447,11447],"valid"],[[11448,11448],"mapped",[11449]],[[11449,11449],"valid"],[[11450,11450],"mapped",[11451]],[[11451,11451],"valid"],[[11452,11452],"mapped",[11453]],[[11453,11453],"valid"],[[11454,11454],"mapped",[11455]],[[11455,11455],"valid"],[[11456,11456],"mapped",[11457]],[[11457,11457],"valid"],[[11458,11458],"mapped",[11459]],[[11459,11459],"valid"],[[11460,11460],"mapped",[11461]],[[11461,11461],"valid"],[[11462,11462],"mapped",[11463]],[[11463,11463],"valid"],[[11464,11464],"mapped",[11465]],[[11465,11465],"valid"],[[11466,11466],"mapped",[11467]],[[11467,11467],"valid"],[[11468,11468],"mapped",[11469]],[[11469,11469],"valid"],[[11470,11470],"mapped",[11471]],[[11471,11471],"valid"],[[11472,11472],"mapped",[11473]],[[11473,11473],"valid"],[[11474,11474],"mapped",[11475]],[[11475,11475],"valid"],[[11476,11476],"mapped",[11477]],[[11477,11477],"valid"],[[11478,11478],"mapped",[11479]],[[11479,11479],"valid"],[[11480,11480],"mapped",[11481]],[[11481,11481],"valid"],[[11482,11482],"mapped",[11483]],[[11483,11483],"valid"],[[11484,11484],"mapped",[11485]],[[11485,11485],"valid"],[[11486,11486],"mapped",[11487]],[[11487,11487],"valid"],[[11488,11488],"mapped",[11489]],[[11489,11489],"valid"],[[11490,11490],"mapped",[11491]],[[11491,11492],"valid"],[[11493,11498],"valid",[],"NV8"],[[11499,11499],"mapped",[11500]],[[11500,11500],"valid"],[[11501,11501],"mapped",[11502]],[[11502,11505],"valid"],[[11506,11506],"mapped",[11507]],[[11507,11507],"valid"],[[11508,11512],"disallowed"],[[11513,11519],"valid",[],"NV8"],[[11520,11557],"valid"],[[11558,11558],"disallowed"],[[11559,11559],"valid"],[[11560,11564],"disallowed"],[[11565,11565],"valid"],[[11566,11567],"disallowed"],[[11568,11621],"valid"],[[11622,11623],"valid"],[[11624,11630],"disallowed"],[[11631,11631],"mapped",[11617]],[[11632,11632],"valid",[],"NV8"],[[11633,11646],"disallowed"],[[11647,11647],"valid"],[[11648,11670],"valid"],[[11671,11679],"disallowed"],[[11680,11686],"valid"],[[11687,11687],"disallowed"],[[11688,11694],"valid"],[[11695,11695],"disallowed"],[[11696,11702],"valid"],[[11703,11703],"disallowed"],[[11704,11710],"valid"],[[11711,11711],"disallowed"],[[11712,11718],"valid"],[[11719,11719],"disallowed"],[[11720,11726],"valid"],[[11727,11727],"disallowed"],[[11728,11734],"valid"],[[11735,11735],"disallowed"],[[11736,11742],"valid"],[[11743,11743],"disallowed"],[[11744,11775],"valid"],[[11776,11799],"valid",[],"NV8"],[[11800,11803],"valid",[],"NV8"],[[11804,11805],"valid",[],"NV8"],[[11806,11822],"valid",[],"NV8"],[[11823,11823],"valid"],[[11824,11824],"valid",[],"NV8"],[[11825,11825],"valid",[],"NV8"],[[11826,11835],"valid",[],"NV8"],[[11836,11842],"valid",[],"NV8"],[[11843,11903],"disallowed"],[[11904,11929],"valid",[],"NV8"],[[11930,11930],"disallowed"],[[11931,11934],"valid",[],"NV8"],[[11935,11935],"mapped",[27597]],[[11936,12018],"valid",[],"NV8"],[[12019,12019],"mapped",[40863]],[[12020,12031],"disallowed"],[[12032,12032],"mapped",[19968]],[[12033,12033],"mapped",[20008]],[[12034,12034],"mapped",[20022]],[[12035,12035],"mapped",[20031]],[[12036,12036],"mapped",[20057]],[[12037,12037],"mapped",[20101]],[[12038,12038],"mapped",[20108]],[[12039,12039],"mapped",[20128]],[[12040,12040],"mapped",[20154]],[[12041,12041],"mapped",[20799]],[[12042,12042],"mapped",[20837]],[[12043,12043],"mapped",[20843]],[[12044,12044],"mapped",[20866]],[[12045,12045],"mapped",[20886]],[[12046,12046],"mapped",[20907]],[[12047,12047],"mapped",[20960]],[[12048,12048],"mapped",[20981]],[[12049,12049],"mapped",[20992]],[[12050,12050],"mapped",[21147]],[[12051,12051],"mapped",[21241]],[[12052,12052],"mapped",[21269]],[[12053,12053],"mapped",[21274]],[[12054,12054],"mapped",[21304]],[[12055,12055],"mapped",[21313]],[[12056,12056],"mapped",[21340]],[[12057,12057],"mapped",[21353]],[[12058,12058],"mapped",[21378]],[[12059,12059],"mapped",[21430]],[[12060,12060],"mapped",[21448]],[[12061,12061],"mapped",[21475]],[[12062,12062],"mapped",[22231]],[[12063,12063],"mapped",[22303]],[[12064,12064],"mapped",[22763]],[[12065,12065],"mapped",[22786]],[[12066,12066],"mapped",[22794]],[[12067,12067],"mapped",[22805]],[[12068,12068],"mapped",[22823]],[[12069,12069],"mapped",[22899]],[[12070,12070],"mapped",[23376]],[[12071,12071],"mapped",[23424]],[[12072,12072],"mapped",[23544]],[[12073,12073],"mapped",[23567]],[[12074,12074],"mapped",[23586]],[[12075,12075],"mapped",[23608]],[[12076,12076],"mapped",[23662]],[[12077,12077],"mapped",[23665]],[[12078,12078],"mapped",[24027]],[[12079,12079],"mapped",[24037]],[[12080,12080],"mapped",[24049]],[[12081,12081],"mapped",[24062]],[[12082,12082],"mapped",[24178]],[[12083,12083],"mapped",[24186]],[[12084,12084],"mapped",[24191]],[[12085,12085],"mapped",[24308]],[[12086,12086],"mapped",[24318]],[[12087,12087],"mapped",[24331]],[[12088,12088],"mapped",[24339]],[[12089,12089],"mapped",[24400]],[[12090,12090],"mapped",[24417]],[[12091,12091],"mapped",[24435]],[[12092,12092],"mapped",[24515]],[[12093,12093],"mapped",[25096]],[[12094,12094],"mapped",[25142]],[[12095,12095],"mapped",[25163]],[[12096,12096],"mapped",[25903]],[[12097,12097],"mapped",[25908]],[[12098,12098],"mapped",[25991]],[[12099,12099],"mapped",[26007]],[[12100,12100],"mapped",[26020]],[[12101,12101],"mapped",[26041]],[[12102,12102],"mapped",[26080]],[[12103,12103],"mapped",[26085]],[[12104,12104],"mapped",[26352]],[[12105,12105],"mapped",[26376]],[[12106,12106],"mapped",[26408]],[[12107,12107],"mapped",[27424]],[[12108,12108],"mapped",[27490]],[[12109,12109],"mapped",[27513]],[[12110,12110],"mapped",[27571]],[[12111,12111],"mapped",[27595]],[[12112,12112],"mapped",[27604]],[[12113,12113],"mapped",[27611]],[[12114,12114],"mapped",[27663]],[[12115,12115],"mapped",[27668]],[[12116,12116],"mapped",[27700]],[[12117,12117],"mapped",[28779]],[[12118,12118],"mapped",[29226]],[[12119,12119],"mapped",[29238]],[[12120,12120],"mapped",[29243]],[[12121,12121],"mapped",[29247]],[[12122,12122],"mapped",[29255]],[[12123,12123],"mapped",[29273]],[[12124,12124],"mapped",[29275]],[[12125,12125],"mapped",[29356]],[[12126,12126],"mapped",[29572]],[[12127,12127],"mapped",[29577]],[[12128,12128],"mapped",[29916]],[[12129,12129],"mapped",[29926]],[[12130,12130],"mapped",[29976]],[[12131,12131],"mapped",[29983]],[[12132,12132],"mapped",[29992]],[[12133,12133],"mapped",[30000]],[[12134,12134],"mapped",[30091]],[[12135,12135],"mapped",[30098]],[[12136,12136],"mapped",[30326]],[[12137,12137],"mapped",[30333]],[[12138,12138],"mapped",[30382]],[[12139,12139],"mapped",[30399]],[[12140,12140],"mapped",[30446]],[[12141,12141],"mapped",[30683]],[[12142,12142],"mapped",[30690]],[[12143,12143],"mapped",[30707]],[[12144,12144],"mapped",[31034]],[[12145,12145],"mapped",[31160]],[[12146,12146],"mapped",[31166]],[[12147,12147],"mapped",[31348]],[[12148,12148],"mapped",[31435]],[[12149,12149],"mapped",[31481]],[[12150,12150],"mapped",[31859]],[[12151,12151],"mapped",[31992]],[[12152,12152],"mapped",[32566]],[[12153,12153],"mapped",[32593]],[[12154,12154],"mapped",[32650]],[[12155,12155],"mapped",[32701]],[[12156,12156],"mapped",[32769]],[[12157,12157],"mapped",[32780]],[[12158,12158],"mapped",[32786]],[[12159,12159],"mapped",[32819]],[[12160,12160],"mapped",[32895]],[[12161,12161],"mapped",[32905]],[[12162,12162],"mapped",[33251]],[[12163,12163],"mapped",[33258]],[[12164,12164],"mapped",[33267]],[[12165,12165],"mapped",[33276]],[[12166,12166],"mapped",[33292]],[[12167,12167],"mapped",[33307]],[[12168,12168],"mapped",[33311]],[[12169,12169],"mapped",[33390]],[[12170,12170],"mapped",[33394]],[[12171,12171],"mapped",[33400]],[[12172,12172],"mapped",[34381]],[[12173,12173],"mapped",[34411]],[[12174,12174],"mapped",[34880]],[[12175,12175],"mapped",[34892]],[[12176,12176],"mapped",[34915]],[[12177,12177],"mapped",[35198]],[[12178,12178],"mapped",[35211]],[[12179,12179],"mapped",[35282]],[[12180,12180],"mapped",[35328]],[[12181,12181],"mapped",[35895]],[[12182,12182],"mapped",[35910]],[[12183,12183],"mapped",[35925]],[[12184,12184],"mapped",[35960]],[[12185,12185],"mapped",[35997]],[[12186,12186],"mapped",[36196]],[[12187,12187],"mapped",[36208]],[[12188,12188],"mapped",[36275]],[[12189,12189],"mapped",[36523]],[[12190,12190],"mapped",[36554]],[[12191,12191],"mapped",[36763]],[[12192,12192],"mapped",[36784]],[[12193,12193],"mapped",[36789]],[[12194,12194],"mapped",[37009]],[[12195,12195],"mapped",[37193]],[[12196,12196],"mapped",[37318]],[[12197,12197],"mapped",[37324]],[[12198,12198],"mapped",[37329]],[[12199,12199],"mapped",[38263]],[[12200,12200],"mapped",[38272]],[[12201,12201],"mapped",[38428]],[[12202,12202],"mapped",[38582]],[[12203,12203],"mapped",[38585]],[[12204,12204],"mapped",[38632]],[[12205,12205],"mapped",[38737]],[[12206,12206],"mapped",[38750]],[[12207,12207],"mapped",[38754]],[[12208,12208],"mapped",[38761]],[[12209,12209],"mapped",[38859]],[[12210,12210],"mapped",[38893]],[[12211,12211],"mapped",[38899]],[[12212,12212],"mapped",[38913]],[[12213,12213],"mapped",[39080]],[[12214,12214],"mapped",[39131]],[[12215,12215],"mapped",[39135]],[[12216,12216],"mapped",[39318]],[[12217,12217],"mapped",[39321]],[[12218,12218],"mapped",[39340]],[[12219,12219],"mapped",[39592]],[[12220,12220],"mapped",[39640]],[[12221,12221],"mapped",[39647]],[[12222,12222],"mapped",[39717]],[[12223,12223],"mapped",[39727]],[[12224,12224],"mapped",[39730]],[[12225,12225],"mapped",[39740]],[[12226,12226],"mapped",[39770]],[[12227,12227],"mapped",[40165]],[[12228,12228],"mapped",[40565]],[[12229,12229],"mapped",[40575]],[[12230,12230],"mapped",[40613]],[[12231,12231],"mapped",[40635]],[[12232,12232],"mapped",[40643]],[[12233,12233],"mapped",[40653]],[[12234,12234],"mapped",[40657]],[[12235,12235],"mapped",[40697]],[[12236,12236],"mapped",[40701]],[[12237,12237],"mapped",[40718]],[[12238,12238],"mapped",[40723]],[[12239,12239],"mapped",[40736]],[[12240,12240],"mapped",[40763]],[[12241,12241],"mapped",[40778]],[[12242,12242],"mapped",[40786]],[[12243,12243],"mapped",[40845]],[[12244,12244],"mapped",[40860]],[[12245,12245],"mapped",[40864]],[[12246,12271],"disallowed"],[[12272,12283],"disallowed"],[[12284,12287],"disallowed"],[[12288,12288],"disallowed_STD3_mapped",[32]],[[12289,12289],"valid",[],"NV8"],[[12290,12290],"mapped",[46]],[[12291,12292],"valid",[],"NV8"],[[12293,12295],"valid"],[[12296,12329],"valid",[],"NV8"],[[12330,12333],"valid"],[[12334,12341],"valid",[],"NV8"],[[12342,12342],"mapped",[12306]],[[12343,12343],"valid",[],"NV8"],[[12344,12344],"mapped",[21313]],[[12345,12345],"mapped",[21316]],[[12346,12346],"mapped",[21317]],[[12347,12347],"valid",[],"NV8"],[[12348,12348],"valid"],[[12349,12349],"valid",[],"NV8"],[[12350,12350],"valid",[],"NV8"],[[12351,12351],"valid",[],"NV8"],[[12352,12352],"disallowed"],[[12353,12436],"valid"],[[12437,12438],"valid"],[[12439,12440],"disallowed"],[[12441,12442],"valid"],[[12443,12443],"disallowed_STD3_mapped",[32,12441]],[[12444,12444],"disallowed_STD3_mapped",[32,12442]],[[12445,12446],"valid"],[[12447,12447],"mapped",[12424,12426]],[[12448,12448],"valid",[],"NV8"],[[12449,12542],"valid"],[[12543,12543],"mapped",[12467,12488]],[[12544,12548],"disallowed"],[[12549,12588],"valid"],[[12589,12589],"valid"],[[12590,12592],"disallowed"],[[12593,12593],"mapped",[4352]],[[12594,12594],"mapped",[4353]],[[12595,12595],"mapped",[4522]],[[12596,12596],"mapped",[4354]],[[12597,12597],"mapped",[4524]],[[12598,12598],"mapped",[4525]],[[12599,12599],"mapped",[4355]],[[12600,12600],"mapped",[4356]],[[12601,12601],"mapped",[4357]],[[12602,12602],"mapped",[4528]],[[12603,12603],"mapped",[4529]],[[12604,12604],"mapped",[4530]],[[12605,12605],"mapped",[4531]],[[12606,12606],"mapped",[4532]],[[12607,12607],"mapped",[4533]],[[12608,12608],"mapped",[4378]],[[12609,12609],"mapped",[4358]],[[12610,12610],"mapped",[4359]],[[12611,12611],"mapped",[4360]],[[12612,12612],"mapped",[4385]],[[12613,12613],"mapped",[4361]],[[12614,12614],"mapped",[4362]],[[12615,12615],"mapped",[4363]],[[12616,12616],"mapped",[4364]],[[12617,12617],"mapped",[4365]],[[12618,12618],"mapped",[4366]],[[12619,12619],"mapped",[4367]],[[12620,12620],"mapped",[4368]],[[12621,12621],"mapped",[4369]],[[12622,12622],"mapped",[4370]],[[12623,12623],"mapped",[4449]],[[12624,12624],"mapped",[4450]],[[12625,12625],"mapped",[4451]],[[12626,12626],"mapped",[4452]],[[12627,12627],"mapped",[4453]],[[12628,12628],"mapped",[4454]],[[12629,12629],"mapped",[4455]],[[12630,12630],"mapped",[4456]],[[12631,12631],"mapped",[4457]],[[12632,12632],"mapped",[4458]],[[12633,12633],"mapped",[4459]],[[12634,12634],"mapped",[4460]],[[12635,12635],"mapped",[4461]],[[12636,12636],"mapped",[4462]],[[12637,12637],"mapped",[4463]],[[12638,12638],"mapped",[4464]],[[12639,12639],"mapped",[4465]],[[12640,12640],"mapped",[4466]],[[12641,12641],"mapped",[4467]],[[12642,12642],"mapped",[4468]],[[12643,12643],"mapped",[4469]],[[12644,12644],"disallowed"],[[12645,12645],"mapped",[4372]],[[12646,12646],"mapped",[4373]],[[12647,12647],"mapped",[4551]],[[12648,12648],"mapped",[4552]],[[12649,12649],"mapped",[4556]],[[12650,12650],"mapped",[4558]],[[12651,12651],"mapped",[4563]],[[12652,12652],"mapped",[4567]],[[12653,12653],"mapped",[4569]],[[12654,12654],"mapped",[4380]],[[12655,12655],"mapped",[4573]],[[12656,12656],"mapped",[4575]],[[12657,12657],"mapped",[4381]],[[12658,12658],"mapped",[4382]],[[12659,12659],"mapped",[4384]],[[12660,12660],"mapped",[4386]],[[12661,12661],"mapped",[4387]],[[12662,12662],"mapped",[4391]],[[12663,12663],"mapped",[4393]],[[12664,12664],"mapped",[4395]],[[12665,12665],"mapped",[4396]],[[12666,12666],"mapped",[4397]],[[12667,12667],"mapped",[4398]],[[12668,12668],"mapped",[4399]],[[12669,12669],"mapped",[4402]],[[12670,12670],"mapped",[4406]],[[12671,12671],"mapped",[4416]],[[12672,12672],"mapped",[4423]],[[12673,12673],"mapped",[4428]],[[12674,12674],"mapped",[4593]],[[12675,12675],"mapped",[4594]],[[12676,12676],"mapped",[4439]],[[12677,12677],"mapped",[4440]],[[12678,12678],"mapped",[4441]],[[12679,12679],"mapped",[4484]],[[12680,12680],"mapped",[4485]],[[12681,12681],"mapped",[4488]],[[12682,12682],"mapped",[4497]],[[12683,12683],"mapped",[4498]],[[12684,12684],"mapped",[4500]],[[12685,12685],"mapped",[4510]],[[12686,12686],"mapped",[4513]],[[12687,12687],"disallowed"],[[12688,12689],"valid",[],"NV8"],[[12690,12690],"mapped",[19968]],[[12691,12691],"mapped",[20108]],[[12692,12692],"mapped",[19977]],[[12693,12693],"mapped",[22235]],[[12694,12694],"mapped",[19978]],[[12695,12695],"mapped",[20013]],[[12696,12696],"mapped",[19979]],[[12697,12697],"mapped",[30002]],[[12698,12698],"mapped",[20057]],[[12699,12699],"mapped",[19993]],[[12700,12700],"mapped",[19969]],[[12701,12701],"mapped",[22825]],[[12702,12702],"mapped",[22320]],[[12703,12703],"mapped",[20154]],[[12704,12727],"valid"],[[12728,12730],"valid"],[[12731,12735],"disallowed"],[[12736,12751],"valid",[],"NV8"],[[12752,12771],"valid",[],"NV8"],[[12772,12783],"disallowed"],[[12784,12799],"valid"],[[12800,12800],"disallowed_STD3_mapped",[40,4352,41]],[[12801,12801],"disallowed_STD3_mapped",[40,4354,41]],[[12802,12802],"disallowed_STD3_mapped",[40,4355,41]],[[12803,12803],"disallowed_STD3_mapped",[40,4357,41]],[[12804,12804],"disallowed_STD3_mapped",[40,4358,41]],[[12805,12805],"disallowed_STD3_mapped",[40,4359,41]],[[12806,12806],"disallowed_STD3_mapped",[40,4361,41]],[[12807,12807],"disallowed_STD3_mapped",[40,4363,41]],[[12808,12808],"disallowed_STD3_mapped",[40,4364,41]],[[12809,12809],"disallowed_STD3_mapped",[40,4366,41]],[[12810,12810],"disallowed_STD3_mapped",[40,4367,41]],[[12811,12811],"disallowed_STD3_mapped",[40,4368,41]],[[12812,12812],"disallowed_STD3_mapped",[40,4369,41]],[[12813,12813],"disallowed_STD3_mapped",[40,4370,41]],[[12814,12814],"disallowed_STD3_mapped",[40,44032,41]],[[12815,12815],"disallowed_STD3_mapped",[40,45208,41]],[[12816,12816],"disallowed_STD3_mapped",[40,45796,41]],[[12817,12817],"disallowed_STD3_mapped",[40,46972,41]],[[12818,12818],"disallowed_STD3_mapped",[40,47560,41]],[[12819,12819],"disallowed_STD3_mapped",[40,48148,41]],[[12820,12820],"disallowed_STD3_mapped",[40,49324,41]],[[12821,12821],"disallowed_STD3_mapped",[40,50500,41]],[[12822,12822],"disallowed_STD3_mapped",[40,51088,41]],[[12823,12823],"disallowed_STD3_mapped",[40,52264,41]],[[12824,12824],"disallowed_STD3_mapped",[40,52852,41]],[[12825,12825],"disallowed_STD3_mapped",[40,53440,41]],[[12826,12826],"disallowed_STD3_mapped",[40,54028,41]],[[12827,12827],"disallowed_STD3_mapped",[40,54616,41]],[[12828,12828],"disallowed_STD3_mapped",[40,51452,41]],[[12829,12829],"disallowed_STD3_mapped",[40,50724,51204,41]],[[12830,12830],"disallowed_STD3_mapped",[40,50724,54980,41]],[[12831,12831],"disallowed"],[[12832,12832],"disallowed_STD3_mapped",[40,19968,41]],[[12833,12833],"disallowed_STD3_mapped",[40,20108,41]],[[12834,12834],"disallowed_STD3_mapped",[40,19977,41]],[[12835,12835],"disallowed_STD3_mapped",[40,22235,41]],[[12836,12836],"disallowed_STD3_mapped",[40,20116,41]],[[12837,12837],"disallowed_STD3_mapped",[40,20845,41]],[[12838,12838],"disallowed_STD3_mapped",[40,19971,41]],[[12839,12839],"disallowed_STD3_mapped",[40,20843,41]],[[12840,12840],"disallowed_STD3_mapped",[40,20061,41]],[[12841,12841],"disallowed_STD3_mapped",[40,21313,41]],[[12842,12842],"disallowed_STD3_mapped",[40,26376,41]],[[12843,12843],"disallowed_STD3_mapped",[40,28779,41]],[[12844,12844],"disallowed_STD3_mapped",[40,27700,41]],[[12845,12845],"disallowed_STD3_mapped",[40,26408,41]],[[12846,12846],"disallowed_STD3_mapped",[40,37329,41]],[[12847,12847],"disallowed_STD3_mapped",[40,22303,41]],[[12848,12848],"disallowed_STD3_mapped",[40,26085,41]],[[12849,12849],"disallowed_STD3_mapped",[40,26666,41]],[[12850,12850],"disallowed_STD3_mapped",[40,26377,41]],[[12851,12851],"disallowed_STD3_mapped",[40,31038,41]],[[12852,12852],"disallowed_STD3_mapped",[40,21517,41]],[[12853,12853],"disallowed_STD3_mapped",[40,29305,41]],[[12854,12854],"disallowed_STD3_mapped",[40,36001,41]],[[12855,12855],"disallowed_STD3_mapped",[40,31069,41]],[[12856,12856],"disallowed_STD3_mapped",[40,21172,41]],[[12857,12857],"disallowed_STD3_mapped",[40,20195,41]],[[12858,12858],"disallowed_STD3_mapped",[40,21628,41]],[[12859,12859],"disallowed_STD3_mapped",[40,23398,41]],[[12860,12860],"disallowed_STD3_mapped",[40,30435,41]],[[12861,12861],"disallowed_STD3_mapped",[40,20225,41]],[[12862,12862],"disallowed_STD3_mapped",[40,36039,41]],[[12863,12863],"disallowed_STD3_mapped",[40,21332,41]],[[12864,12864],"disallowed_STD3_mapped",[40,31085,41]],[[12865,12865],"disallowed_STD3_mapped",[40,20241,41]],[[12866,12866],"disallowed_STD3_mapped",[40,33258,41]],[[12867,12867],"disallowed_STD3_mapped",[40,33267,41]],[[12868,12868],"mapped",[21839]],[[12869,12869],"mapped",[24188]],[[12870,12870],"mapped",[25991]],[[12871,12871],"mapped",[31631]],[[12872,12879],"valid",[],"NV8"],[[12880,12880],"mapped",[112,116,101]],[[12881,12881],"mapped",[50,49]],[[12882,12882],"mapped",[50,50]],[[12883,12883],"mapped",[50,51]],[[12884,12884],"mapped",[50,52]],[[12885,12885],"mapped",[50,53]],[[12886,12886],"mapped",[50,54]],[[12887,12887],"mapped",[50,55]],[[12888,12888],"mapped",[50,56]],[[12889,12889],"mapped",[50,57]],[[12890,12890],"mapped",[51,48]],[[12891,12891],"mapped",[51,49]],[[12892,12892],"mapped",[51,50]],[[12893,12893],"mapped",[51,51]],[[12894,12894],"mapped",[51,52]],[[12895,12895],"mapped",[51,53]],[[12896,12896],"mapped",[4352]],[[12897,12897],"mapped",[4354]],[[12898,12898],"mapped",[4355]],[[12899,12899],"mapped",[4357]],[[12900,12900],"mapped",[4358]],[[12901,12901],"mapped",[4359]],[[12902,12902],"mapped",[4361]],[[12903,12903],"mapped",[4363]],[[12904,12904],"mapped",[4364]],[[12905,12905],"mapped",[4366]],[[12906,12906],"mapped",[4367]],[[12907,12907],"mapped",[4368]],[[12908,12908],"mapped",[4369]],[[12909,12909],"mapped",[4370]],[[12910,12910],"mapped",[44032]],[[12911,12911],"mapped",[45208]],[[12912,12912],"mapped",[45796]],[[12913,12913],"mapped",[46972]],[[12914,12914],"mapped",[47560]],[[12915,12915],"mapped",[48148]],[[12916,12916],"mapped",[49324]],[[12917,12917],"mapped",[50500]],[[12918,12918],"mapped",[51088]],[[12919,12919],"mapped",[52264]],[[12920,12920],"mapped",[52852]],[[12921,12921],"mapped",[53440]],[[12922,12922],"mapped",[54028]],[[12923,12923],"mapped",[54616]],[[12924,12924],"mapped",[52280,44256]],[[12925,12925],"mapped",[51452,51032]],[[12926,12926],"mapped",[50864]],[[12927,12927],"valid",[],"NV8"],[[12928,12928],"mapped",[19968]],[[12929,12929],"mapped",[20108]],[[12930,12930],"mapped",[19977]],[[12931,12931],"mapped",[22235]],[[12932,12932],"mapped",[20116]],[[12933,12933],"mapped",[20845]],[[12934,12934],"mapped",[19971]],[[12935,12935],"mapped",[20843]],[[12936,12936],"mapped",[20061]],[[12937,12937],"mapped",[21313]],[[12938,12938],"mapped",[26376]],[[12939,12939],"mapped",[28779]],[[12940,12940],"mapped",[27700]],[[12941,12941],"mapped",[26408]],[[12942,12942],"mapped",[37329]],[[12943,12943],"mapped",[22303]],[[12944,12944],"mapped",[26085]],[[12945,12945],"mapped",[26666]],[[12946,12946],"mapped",[26377]],[[12947,12947],"mapped",[31038]],[[12948,12948],"mapped",[21517]],[[12949,12949],"mapped",[29305]],[[12950,12950],"mapped",[36001]],[[12951,12951],"mapped",[31069]],[[12952,12952],"mapped",[21172]],[[12953,12953],"mapped",[31192]],[[12954,12954],"mapped",[30007]],[[12955,12955],"mapped",[22899]],[[12956,12956],"mapped",[36969]],[[12957,12957],"mapped",[20778]],[[12958,12958],"mapped",[21360]],[[12959,12959],"mapped",[27880]],[[12960,12960],"mapped",[38917]],[[12961,12961],"mapped",[20241]],[[12962,12962],"mapped",[20889]],[[12963,12963],"mapped",[27491]],[[12964,12964],"mapped",[19978]],[[12965,12965],"mapped",[20013]],[[12966,12966],"mapped",[19979]],[[12967,12967],"mapped",[24038]],[[12968,12968],"mapped",[21491]],[[12969,12969],"mapped",[21307]],[[12970,12970],"mapped",[23447]],[[12971,12971],"mapped",[23398]],[[12972,12972],"mapped",[30435]],[[12973,12973],"mapped",[20225]],[[12974,12974],"mapped",[36039]],[[12975,12975],"mapped",[21332]],[[12976,12976],"mapped",[22812]],[[12977,12977],"mapped",[51,54]],[[12978,12978],"mapped",[51,55]],[[12979,12979],"mapped",[51,56]],[[12980,12980],"mapped",[51,57]],[[12981,12981],"mapped",[52,48]],[[12982,12982],"mapped",[52,49]],[[12983,12983],"mapped",[52,50]],[[12984,12984],"mapped",[52,51]],[[12985,12985],"mapped",[52,52]],[[12986,12986],"mapped",[52,53]],[[12987,12987],"mapped",[52,54]],[[12988,12988],"mapped",[52,55]],[[12989,12989],"mapped",[52,56]],[[12990,12990],"mapped",[52,57]],[[12991,12991],"mapped",[53,48]],[[12992,12992],"mapped",[49,26376]],[[12993,12993],"mapped",[50,26376]],[[12994,12994],"mapped",[51,26376]],[[12995,12995],"mapped",[52,26376]],[[12996,12996],"mapped",[53,26376]],[[12997,12997],"mapped",[54,26376]],[[12998,12998],"mapped",[55,26376]],[[12999,12999],"mapped",[56,26376]],[[13000,13000],"mapped",[57,26376]],[[13001,13001],"mapped",[49,48,26376]],[[13002,13002],"mapped",[49,49,26376]],[[13003,13003],"mapped",[49,50,26376]],[[13004,13004],"mapped",[104,103]],[[13005,13005],"mapped",[101,114,103]],[[13006,13006],"mapped",[101,118]],[[13007,13007],"mapped",[108,116,100]],[[13008,13008],"mapped",[12450]],[[13009,13009],"mapped",[12452]],[[13010,13010],"mapped",[12454]],[[13011,13011],"mapped",[12456]],[[13012,13012],"mapped",[12458]],[[13013,13013],"mapped",[12459]],[[13014,13014],"mapped",[12461]],[[13015,13015],"mapped",[12463]],[[13016,13016],"mapped",[12465]],[[13017,13017],"mapped",[12467]],[[13018,13018],"mapped",[12469]],[[13019,13019],"mapped",[12471]],[[13020,13020],"mapped",[12473]],[[13021,13021],"mapped",[12475]],[[13022,13022],"mapped",[12477]],[[13023,13023],"mapped",[12479]],[[13024,13024],"mapped",[12481]],[[13025,13025],"mapped",[12484]],[[13026,13026],"mapped",[12486]],[[13027,13027],"mapped",[12488]],[[13028,13028],"mapped",[12490]],[[13029,13029],"mapped",[12491]],[[13030,13030],"mapped",[12492]],[[13031,13031],"mapped",[12493]],[[13032,13032],"mapped",[12494]],[[13033,13033],"mapped",[12495]],[[13034,13034],"mapped",[12498]],[[13035,13035],"mapped",[12501]],[[13036,13036],"mapped",[12504]],[[13037,13037],"mapped",[12507]],[[13038,13038],"mapped",[12510]],[[13039,13039],"mapped",[12511]],[[13040,13040],"mapped",[12512]],[[13041,13041],"mapped",[12513]],[[13042,13042],"mapped",[12514]],[[13043,13043],"mapped",[12516]],[[13044,13044],"mapped",[12518]],[[13045,13045],"mapped",[12520]],[[13046,13046],"mapped",[12521]],[[13047,13047],"mapped",[12522]],[[13048,13048],"mapped",[12523]],[[13049,13049],"mapped",[12524]],[[13050,13050],"mapped",[12525]],[[13051,13051],"mapped",[12527]],[[13052,13052],"mapped",[12528]],[[13053,13053],"mapped",[12529]],[[13054,13054],"mapped",[12530]],[[13055,13055],"disallowed"],[[13056,13056],"mapped",[12450,12497,12540,12488]],[[13057,13057],"mapped",[12450,12523,12501,12449]],[[13058,13058],"mapped",[12450,12531,12506,12450]],[[13059,13059],"mapped",[12450,12540,12523]],[[13060,13060],"mapped",[12452,12491,12531,12464]],[[13061,13061],"mapped",[12452,12531,12481]],[[13062,13062],"mapped",[12454,12457,12531]],[[13063,13063],"mapped",[12456,12473,12463,12540,12489]],[[13064,13064],"mapped",[12456,12540,12459,12540]],[[13065,13065],"mapped",[12458,12531,12473]],[[13066,13066],"mapped",[12458,12540,12512]],[[13067,13067],"mapped",[12459,12452,12522]],[[13068,13068],"mapped",[12459,12521,12483,12488]],[[13069,13069],"mapped",[12459,12525,12522,12540]],[[13070,13070],"mapped",[12460,12525,12531]],[[13071,13071],"mapped",[12460,12531,12510]],[[13072,13072],"mapped",[12462,12460]],[[13073,13073],"mapped",[12462,12491,12540]],[[13074,13074],"mapped",[12461,12517,12522,12540]],[[13075,13075],"mapped",[12462,12523,12480,12540]],[[13076,13076],"mapped",[12461,12525]],[[13077,13077],"mapped",[12461,12525,12464,12521,12512]],[[13078,13078],"mapped",[12461,12525,12513,12540,12488,12523]],[[13079,13079],"mapped",[12461,12525,12527,12483,12488]],[[13080,13080],"mapped",[12464,12521,12512]],[[13081,13081],"mapped",[12464,12521,12512,12488,12531]],[[13082,13082],"mapped",[12463,12523,12476,12452,12525]],[[13083,13083],"mapped",[12463,12525,12540,12493]],[[13084,13084],"mapped",[12465,12540,12473]],[[13085,13085],"mapped",[12467,12523,12490]],[[13086,13086],"mapped",[12467,12540,12509]],[[13087,13087],"mapped",[12469,12452,12463,12523]],[[13088,13088],"mapped",[12469,12531,12481,12540,12512]],[[13089,13089],"mapped",[12471,12522,12531,12464]],[[13090,13090],"mapped",[12475,12531,12481]],[[13091,13091],"mapped",[12475,12531,12488]],[[13092,13092],"mapped",[12480,12540,12473]],[[13093,13093],"mapped",[12487,12471]],[[13094,13094],"mapped",[12489,12523]],[[13095,13095],"mapped",[12488,12531]],[[13096,13096],"mapped",[12490,12494]],[[13097,13097],"mapped",[12494,12483,12488]],[[13098,13098],"mapped",[12495,12452,12484]],[[13099,13099],"mapped",[12497,12540,12475,12531,12488]],[[13100,13100],"mapped",[12497,12540,12484]],[[13101,13101],"mapped",[12496,12540,12524,12523]],[[13102,13102],"mapped",[12500,12450,12473,12488,12523]],[[13103,13103],"mapped",[12500,12463,12523]],[[13104,13104],"mapped",[12500,12467]],[[13105,13105],"mapped",[12499,12523]],[[13106,13106],"mapped",[12501,12449,12521,12483,12489]],[[13107,13107],"mapped",[12501,12451,12540,12488]],[[13108,13108],"mapped",[12502,12483,12471,12455,12523]],[[13109,13109],"mapped",[12501,12521,12531]],[[13110,13110],"mapped",[12504,12463,12479,12540,12523]],[[13111,13111],"mapped",[12506,12477]],[[13112,13112],"mapped",[12506,12491,12498]],[[13113,13113],"mapped",[12504,12523,12484]],[[13114,13114],"mapped",[12506,12531,12473]],[[13115,13115],"mapped",[12506,12540,12472]],[[13116,13116],"mapped",[12505,12540,12479]],[[13117,13117],"mapped",[12509,12452,12531,12488]],[[13118,13118],"mapped",[12508,12523,12488]],[[13119,13119],"mapped",[12507,12531]],[[13120,13120],"mapped",[12509,12531,12489]],[[13121,13121],"mapped",[12507,12540,12523]],[[13122,13122],"mapped",[12507,12540,12531]],[[13123,13123],"mapped",[12510,12452,12463,12525]],[[13124,13124],"mapped",[12510,12452,12523]],[[13125,13125],"mapped",[12510,12483,12495]],[[13126,13126],"mapped",[12510,12523,12463]],[[13127,13127],"mapped",[12510,12531,12471,12519,12531]],[[13128,13128],"mapped",[12511,12463,12525,12531]],[[13129,13129],"mapped",[12511,12522]],[[13130,13130],"mapped",[12511,12522,12496,12540,12523]],[[13131,13131],"mapped",[12513,12460]],[[13132,13132],"mapped",[12513,12460,12488,12531]],[[13133,13133],"mapped",[12513,12540,12488,12523]],[[13134,13134],"mapped",[12516,12540,12489]],[[13135,13135],"mapped",[12516,12540,12523]],[[13136,13136],"mapped",[12518,12450,12531]],[[13137,13137],"mapped",[12522,12483,12488,12523]],[[13138,13138],"mapped",[12522,12521]],[[13139,13139],"mapped",[12523,12500,12540]],[[13140,13140],"mapped",[12523,12540,12502,12523]],[[13141,13141],"mapped",[12524,12512]],[[13142,13142],"mapped",[12524,12531,12488,12466,12531]],[[13143,13143],"mapped",[12527,12483,12488]],[[13144,13144],"mapped",[48,28857]],[[13145,13145],"mapped",[49,28857]],[[13146,13146],"mapped",[50,28857]],[[13147,13147],"mapped",[51,28857]],[[13148,13148],"mapped",[52,28857]],[[13149,13149],"mapped",[53,28857]],[[13150,13150],"mapped",[54,28857]],[[13151,13151],"mapped",[55,28857]],[[13152,13152],"mapped",[56,28857]],[[13153,13153],"mapped",[57,28857]],[[13154,13154],"mapped",[49,48,28857]],[[13155,13155],"mapped",[49,49,28857]],[[13156,13156],"mapped",[49,50,28857]],[[13157,13157],"mapped",[49,51,28857]],[[13158,13158],"mapped",[49,52,28857]],[[13159,13159],"mapped",[49,53,28857]],[[13160,13160],"mapped",[49,54,28857]],[[13161,13161],"mapped",[49,55,28857]],[[13162,13162],"mapped",[49,56,28857]],[[13163,13163],"mapped",[49,57,28857]],[[13164,13164],"mapped",[50,48,28857]],[[13165,13165],"mapped",[50,49,28857]],[[13166,13166],"mapped",[50,50,28857]],[[13167,13167],"mapped",[50,51,28857]],[[13168,13168],"mapped",[50,52,28857]],[[13169,13169],"mapped",[104,112,97]],[[13170,13170],"mapped",[100,97]],[[13171,13171],"mapped",[97,117]],[[13172,13172],"mapped",[98,97,114]],[[13173,13173],"mapped",[111,118]],[[13174,13174],"mapped",[112,99]],[[13175,13175],"mapped",[100,109]],[[13176,13176],"mapped",[100,109,50]],[[13177,13177],"mapped",[100,109,51]],[[13178,13178],"mapped",[105,117]],[[13179,13179],"mapped",[24179,25104]],[[13180,13180],"mapped",[26157,21644]],[[13181,13181],"mapped",[22823,27491]],[[13182,13182],"mapped",[26126,27835]],[[13183,13183],"mapped",[26666,24335,20250,31038]],[[13184,13184],"mapped",[112,97]],[[13185,13185],"mapped",[110,97]],[[13186,13186],"mapped",[956,97]],[[13187,13187],"mapped",[109,97]],[[13188,13188],"mapped",[107,97]],[[13189,13189],"mapped",[107,98]],[[13190,13190],"mapped",[109,98]],[[13191,13191],"mapped",[103,98]],[[13192,13192],"mapped",[99,97,108]],[[13193,13193],"mapped",[107,99,97,108]],[[13194,13194],"mapped",[112,102]],[[13195,13195],"mapped",[110,102]],[[13196,13196],"mapped",[956,102]],[[13197,13197],"mapped",[956,103]],[[13198,13198],"mapped",[109,103]],[[13199,13199],"mapped",[107,103]],[[13200,13200],"mapped",[104,122]],[[13201,13201],"mapped",[107,104,122]],[[13202,13202],"mapped",[109,104,122]],[[13203,13203],"mapped",[103,104,122]],[[13204,13204],"mapped",[116,104,122]],[[13205,13205],"mapped",[956,108]],[[13206,13206],"mapped",[109,108]],[[13207,13207],"mapped",[100,108]],[[13208,13208],"mapped",[107,108]],[[13209,13209],"mapped",[102,109]],[[13210,13210],"mapped",[110,109]],[[13211,13211],"mapped",[956,109]],[[13212,13212],"mapped",[109,109]],[[13213,13213],"mapped",[99,109]],[[13214,13214],"mapped",[107,109]],[[13215,13215],"mapped",[109,109,50]],[[13216,13216],"mapped",[99,109,50]],[[13217,13217],"mapped",[109,50]],[[13218,13218],"mapped",[107,109,50]],[[13219,13219],"mapped",[109,109,51]],[[13220,13220],"mapped",[99,109,51]],[[13221,13221],"mapped",[109,51]],[[13222,13222],"mapped",[107,109,51]],[[13223,13223],"mapped",[109,8725,115]],[[13224,13224],"mapped",[109,8725,115,50]],[[13225,13225],"mapped",[112,97]],[[13226,13226],"mapped",[107,112,97]],[[13227,13227],"mapped",[109,112,97]],[[13228,13228],"mapped",[103,112,97]],[[13229,13229],"mapped",[114,97,100]],[[13230,13230],"mapped",[114,97,100,8725,115]],[[13231,13231],"mapped",[114,97,100,8725,115,50]],[[13232,13232],"mapped",[112,115]],[[13233,13233],"mapped",[110,115]],[[13234,13234],"mapped",[956,115]],[[13235,13235],"mapped",[109,115]],[[13236,13236],"mapped",[112,118]],[[13237,13237],"mapped",[110,118]],[[13238,13238],"mapped",[956,118]],[[13239,13239],"mapped",[109,118]],[[13240,13240],"mapped",[107,118]],[[13241,13241],"mapped",[109,118]],[[13242,13242],"mapped",[112,119]],[[13243,13243],"mapped",[110,119]],[[13244,13244],"mapped",[956,119]],[[13245,13245],"mapped",[109,119]],[[13246,13246],"mapped",[107,119]],[[13247,13247],"mapped",[109,119]],[[13248,13248],"mapped",[107,969]],[[13249,13249],"mapped",[109,969]],[[13250,13250],"disallowed"],[[13251,13251],"mapped",[98,113]],[[13252,13252],"mapped",[99,99]],[[13253,13253],"mapped",[99,100]],[[13254,13254],"mapped",[99,8725,107,103]],[[13255,13255],"disallowed"],[[13256,13256],"mapped",[100,98]],[[13257,13257],"mapped",[103,121]],[[13258,13258],"mapped",[104,97]],[[13259,13259],"mapped",[104,112]],[[13260,13260],"mapped",[105,110]],[[13261,13261],"mapped",[107,107]],[[13262,13262],"mapped",[107,109]],[[13263,13263],"mapped",[107,116]],[[13264,13264],"mapped",[108,109]],[[13265,13265],"mapped",[108,110]],[[13266,13266],"mapped",[108,111,103]],[[13267,13267],"mapped",[108,120]],[[13268,13268],"mapped",[109,98]],[[13269,13269],"mapped",[109,105,108]],[[13270,13270],"mapped",[109,111,108]],[[13271,13271],"mapped",[112,104]],[[13272,13272],"disallowed"],[[13273,13273],"mapped",[112,112,109]],[[13274,13274],"mapped",[112,114]],[[13275,13275],"mapped",[115,114]],[[13276,13276],"mapped",[115,118]],[[13277,13277],"mapped",[119,98]],[[13278,13278],"mapped",[118,8725,109]],[[13279,13279],"mapped",[97,8725,109]],[[13280,13280],"mapped",[49,26085]],[[13281,13281],"mapped",[50,26085]],[[13282,13282],"mapped",[51,26085]],[[13283,13283],"mapped",[52,26085]],[[13284,13284],"mapped",[53,26085]],[[13285,13285],"mapped",[54,26085]],[[13286,13286],"mapped",[55,26085]],[[13287,13287],"mapped",[56,26085]],[[13288,13288],"mapped",[57,26085]],[[13289,13289],"mapped",[49,48,26085]],[[13290,13290],"mapped",[49,49,26085]],[[13291,13291],"mapped",[49,50,26085]],[[13292,13292],"mapped",[49,51,26085]],[[13293,13293],"mapped",[49,52,26085]],[[13294,13294],"mapped",[49,53,26085]],[[13295,13295],"mapped",[49,54,26085]],[[13296,13296],"mapped",[49,55,26085]],[[13297,13297],"mapped",[49,56,26085]],[[13298,13298],"mapped",[49,57,26085]],[[13299,13299],"mapped",[50,48,26085]],[[13300,13300],"mapped",[50,49,26085]],[[13301,13301],"mapped",[50,50,26085]],[[13302,13302],"mapped",[50,51,26085]],[[13303,13303],"mapped",[50,52,26085]],[[13304,13304],"mapped",[50,53,26085]],[[13305,13305],"mapped",[50,54,26085]],[[13306,13306],"mapped",[50,55,26085]],[[13307,13307],"mapped",[50,56,26085]],[[13308,13308],"mapped",[50,57,26085]],[[13309,13309],"mapped",[51,48,26085]],[[13310,13310],"mapped",[51,49,26085]],[[13311,13311],"mapped",[103,97,108]],[[13312,19893],"valid"],[[19894,19903],"disallowed"],[[19904,19967],"valid",[],"NV8"],[[19968,40869],"valid"],[[40870,40891],"valid"],[[40892,40899],"valid"],[[40900,40907],"valid"],[[40908,40908],"valid"],[[40909,40917],"valid"],[[40918,40959],"disallowed"],[[40960,42124],"valid"],[[42125,42127],"disallowed"],[[42128,42145],"valid",[],"NV8"],[[42146,42147],"valid",[],"NV8"],[[42148,42163],"valid",[],"NV8"],[[42164,42164],"valid",[],"NV8"],[[42165,42176],"valid",[],"NV8"],[[42177,42177],"valid",[],"NV8"],[[42178,42180],"valid",[],"NV8"],[[42181,42181],"valid",[],"NV8"],[[42182,42182],"valid",[],"NV8"],[[42183,42191],"disallowed"],[[42192,42237],"valid"],[[42238,42239],"valid",[],"NV8"],[[42240,42508],"valid"],[[42509,42511],"valid",[],"NV8"],[[42512,42539],"valid"],[[42540,42559],"disallowed"],[[42560,42560],"mapped",[42561]],[[42561,42561],"valid"],[[42562,42562],"mapped",[42563]],[[42563,42563],"valid"],[[42564,42564],"mapped",[42565]],[[42565,42565],"valid"],[[42566,42566],"mapped",[42567]],[[42567,42567],"valid"],[[42568,42568],"mapped",[42569]],[[42569,42569],"valid"],[[42570,42570],"mapped",[42571]],[[42571,42571],"valid"],[[42572,42572],"mapped",[42573]],[[42573,42573],"valid"],[[42574,42574],"mapped",[42575]],[[42575,42575],"valid"],[[42576,42576],"mapped",[42577]],[[42577,42577],"valid"],[[42578,42578],"mapped",[42579]],[[42579,42579],"valid"],[[42580,42580],"mapped",[42581]],[[42581,42581],"valid"],[[42582,42582],"mapped",[42583]],[[42583,42583],"valid"],[[42584,42584],"mapped",[42585]],[[42585,42585],"valid"],[[42586,42586],"mapped",[42587]],[[42587,42587],"valid"],[[42588,42588],"mapped",[42589]],[[42589,42589],"valid"],[[42590,42590],"mapped",[42591]],[[42591,42591],"valid"],[[42592,42592],"mapped",[42593]],[[42593,42593],"valid"],[[42594,42594],"mapped",[42595]],[[42595,42595],"valid"],[[42596,42596],"mapped",[42597]],[[42597,42597],"valid"],[[42598,42598],"mapped",[42599]],[[42599,42599],"valid"],[[42600,42600],"mapped",[42601]],[[42601,42601],"valid"],[[42602,42602],"mapped",[42603]],[[42603,42603],"valid"],[[42604,42604],"mapped",[42605]],[[42605,42607],"valid"],[[42608,42611],"valid",[],"NV8"],[[42612,42619],"valid"],[[42620,42621],"valid"],[[42622,42622],"valid",[],"NV8"],[[42623,42623],"valid"],[[42624,42624],"mapped",[42625]],[[42625,42625],"valid"],[[42626,42626],"mapped",[42627]],[[42627,42627],"valid"],[[42628,42628],"mapped",[42629]],[[42629,42629],"valid"],[[42630,42630],"mapped",[42631]],[[42631,42631],"valid"],[[42632,42632],"mapped",[42633]],[[42633,42633],"valid"],[[42634,42634],"mapped",[42635]],[[42635,42635],"valid"],[[42636,42636],"mapped",[42637]],[[42637,42637],"valid"],[[42638,42638],"mapped",[42639]],[[42639,42639],"valid"],[[42640,42640],"mapped",[42641]],[[42641,42641],"valid"],[[42642,42642],"mapped",[42643]],[[42643,42643],"valid"],[[42644,42644],"mapped",[42645]],[[42645,42645],"valid"],[[42646,42646],"mapped",[42647]],[[42647,42647],"valid"],[[42648,42648],"mapped",[42649]],[[42649,42649],"valid"],[[42650,42650],"mapped",[42651]],[[42651,42651],"valid"],[[42652,42652],"mapped",[1098]],[[42653,42653],"mapped",[1100]],[[42654,42654],"valid"],[[42655,42655],"valid"],[[42656,42725],"valid"],[[42726,42735],"valid",[],"NV8"],[[42736,42737],"valid"],[[42738,42743],"valid",[],"NV8"],[[42744,42751],"disallowed"],[[42752,42774],"valid",[],"NV8"],[[42775,42778],"valid"],[[42779,42783],"valid"],[[42784,42785],"valid",[],"NV8"],[[42786,42786],"mapped",[42787]],[[42787,42787],"valid"],[[42788,42788],"mapped",[42789]],[[42789,42789],"valid"],[[42790,42790],"mapped",[42791]],[[42791,42791],"valid"],[[42792,42792],"mapped",[42793]],[[42793,42793],"valid"],[[42794,42794],"mapped",[42795]],[[42795,42795],"valid"],[[42796,42796],"mapped",[42797]],[[42797,42797],"valid"],[[42798,42798],"mapped",[42799]],[[42799,42801],"valid"],[[42802,42802],"mapped",[42803]],[[42803,42803],"valid"],[[42804,42804],"mapped",[42805]],[[42805,42805],"valid"],[[42806,42806],"mapped",[42807]],[[42807,42807],"valid"],[[42808,42808],"mapped",[42809]],[[42809,42809],"valid"],[[42810,42810],"mapped",[42811]],[[42811,42811],"valid"],[[42812,42812],"mapped",[42813]],[[42813,42813],"valid"],[[42814,42814],"mapped",[42815]],[[42815,42815],"valid"],[[42816,42816],"mapped",[42817]],[[42817,42817],"valid"],[[42818,42818],"mapped",[42819]],[[42819,42819],"valid"],[[42820,42820],"mapped",[42821]],[[42821,42821],"valid"],[[42822,42822],"mapped",[42823]],[[42823,42823],"valid"],[[42824,42824],"mapped",[42825]],[[42825,42825],"valid"],[[42826,42826],"mapped",[42827]],[[42827,42827],"valid"],[[42828,42828],"mapped",[42829]],[[42829,42829],"valid"],[[42830,42830],"mapped",[42831]],[[42831,42831],"valid"],[[42832,42832],"mapped",[42833]],[[42833,42833],"valid"],[[42834,42834],"mapped",[42835]],[[42835,42835],"valid"],[[42836,42836],"mapped",[42837]],[[42837,42837],"valid"],[[42838,42838],"mapped",[42839]],[[42839,42839],"valid"],[[42840,42840],"mapped",[42841]],[[42841,42841],"valid"],[[42842,42842],"mapped",[42843]],[[42843,42843],"valid"],[[42844,42844],"mapped",[42845]],[[42845,42845],"valid"],[[42846,42846],"mapped",[42847]],[[42847,42847],"valid"],[[42848,42848],"mapped",[42849]],[[42849,42849],"valid"],[[42850,42850],"mapped",[42851]],[[42851,42851],"valid"],[[42852,42852],"mapped",[42853]],[[42853,42853],"valid"],[[42854,42854],"mapped",[42855]],[[42855,42855],"valid"],[[42856,42856],"mapped",[42857]],[[42857,42857],"valid"],[[42858,42858],"mapped",[42859]],[[42859,42859],"valid"],[[42860,42860],"mapped",[42861]],[[42861,42861],"valid"],[[42862,42862],"mapped",[42863]],[[42863,42863],"valid"],[[42864,42864],"mapped",[42863]],[[42865,42872],"valid"],[[42873,42873],"mapped",[42874]],[[42874,42874],"valid"],[[42875,42875],"mapped",[42876]],[[42876,42876],"valid"],[[42877,42877],"mapped",[7545]],[[42878,42878],"mapped",[42879]],[[42879,42879],"valid"],[[42880,42880],"mapped",[42881]],[[42881,42881],"valid"],[[42882,42882],"mapped",[42883]],[[42883,42883],"valid"],[[42884,42884],"mapped",[42885]],[[42885,42885],"valid"],[[42886,42886],"mapped",[42887]],[[42887,42888],"valid"],[[42889,42890],"valid",[],"NV8"],[[42891,42891],"mapped",[42892]],[[42892,42892],"valid"],[[42893,42893],"mapped",[613]],[[42894,42894],"valid"],[[42895,42895],"valid"],[[42896,42896],"mapped",[42897]],[[42897,42897],"valid"],[[42898,42898],"mapped",[42899]],[[42899,42899],"valid"],[[42900,42901],"valid"],[[42902,42902],"mapped",[42903]],[[42903,42903],"valid"],[[42904,42904],"mapped",[42905]],[[42905,42905],"valid"],[[42906,42906],"mapped",[42907]],[[42907,42907],"valid"],[[42908,42908],"mapped",[42909]],[[42909,42909],"valid"],[[42910,42910],"mapped",[42911]],[[42911,42911],"valid"],[[42912,42912],"mapped",[42913]],[[42913,42913],"valid"],[[42914,42914],"mapped",[42915]],[[42915,42915],"valid"],[[42916,42916],"mapped",[42917]],[[42917,42917],"valid"],[[42918,42918],"mapped",[42919]],[[42919,42919],"valid"],[[42920,42920],"mapped",[42921]],[[42921,42921],"valid"],[[42922,42922],"mapped",[614]],[[42923,42923],"mapped",[604]],[[42924,42924],"mapped",[609]],[[42925,42925],"mapped",[620]],[[42926,42927],"disallowed"],[[42928,42928],"mapped",[670]],[[42929,42929],"mapped",[647]],[[42930,42930],"mapped",[669]],[[42931,42931],"mapped",[43859]],[[42932,42932],"mapped",[42933]],[[42933,42933],"valid"],[[42934,42934],"mapped",[42935]],[[42935,42935],"valid"],[[42936,42998],"disallowed"],[[42999,42999],"valid"],[[43000,43000],"mapped",[295]],[[43001,43001],"mapped",[339]],[[43002,43002],"valid"],[[43003,43007],"valid"],[[43008,43047],"valid"],[[43048,43051],"valid",[],"NV8"],[[43052,43055],"disallowed"],[[43056,43065],"valid",[],"NV8"],[[43066,43071],"disallowed"],[[43072,43123],"valid"],[[43124,43127],"valid",[],"NV8"],[[43128,43135],"disallowed"],[[43136,43204],"valid"],[[43205,43213],"disallowed"],[[43214,43215],"valid",[],"NV8"],[[43216,43225],"valid"],[[43226,43231],"disallowed"],[[43232,43255],"valid"],[[43256,43258],"valid",[],"NV8"],[[43259,43259],"valid"],[[43260,43260],"valid",[],"NV8"],[[43261,43261],"valid"],[[43262,43263],"disallowed"],[[43264,43309],"valid"],[[43310,43311],"valid",[],"NV8"],[[43312,43347],"valid"],[[43348,43358],"disallowed"],[[43359,43359],"valid",[],"NV8"],[[43360,43388],"valid",[],"NV8"],[[43389,43391],"disallowed"],[[43392,43456],"valid"],[[43457,43469],"valid",[],"NV8"],[[43470,43470],"disallowed"],[[43471,43481],"valid"],[[43482,43485],"disallowed"],[[43486,43487],"valid",[],"NV8"],[[43488,43518],"valid"],[[43519,43519],"disallowed"],[[43520,43574],"valid"],[[43575,43583],"disallowed"],[[43584,43597],"valid"],[[43598,43599],"disallowed"],[[43600,43609],"valid"],[[43610,43611],"disallowed"],[[43612,43615],"valid",[],"NV8"],[[43616,43638],"valid"],[[43639,43641],"valid",[],"NV8"],[[43642,43643],"valid"],[[43644,43647],"valid"],[[43648,43714],"valid"],[[43715,43738],"disallowed"],[[43739,43741],"valid"],[[43742,43743],"valid",[],"NV8"],[[43744,43759],"valid"],[[43760,43761],"valid",[],"NV8"],[[43762,43766],"valid"],[[43767,43776],"disallowed"],[[43777,43782],"valid"],[[43783,43784],"disallowed"],[[43785,43790],"valid"],[[43791,43792],"disallowed"],[[43793,43798],"valid"],[[43799,43807],"disallowed"],[[43808,43814],"valid"],[[43815,43815],"disallowed"],[[43816,43822],"valid"],[[43823,43823],"disallowed"],[[43824,43866],"valid"],[[43867,43867],"valid",[],"NV8"],[[43868,43868],"mapped",[42791]],[[43869,43869],"mapped",[43831]],[[43870,43870],"mapped",[619]],[[43871,43871],"mapped",[43858]],[[43872,43875],"valid"],[[43876,43877],"valid"],[[43878,43887],"disallowed"],[[43888,43888],"mapped",[5024]],[[43889,43889],"mapped",[5025]],[[43890,43890],"mapped",[5026]],[[43891,43891],"mapped",[5027]],[[43892,43892],"mapped",[5028]],[[43893,43893],"mapped",[5029]],[[43894,43894],"mapped",[5030]],[[43895,43895],"mapped",[5031]],[[43896,43896],"mapped",[5032]],[[43897,43897],"mapped",[5033]],[[43898,43898],"mapped",[5034]],[[43899,43899],"mapped",[5035]],[[43900,43900],"mapped",[5036]],[[43901,43901],"mapped",[5037]],[[43902,43902],"mapped",[5038]],[[43903,43903],"mapped",[5039]],[[43904,43904],"mapped",[5040]],[[43905,43905],"mapped",[5041]],[[43906,43906],"mapped",[5042]],[[43907,43907],"mapped",[5043]],[[43908,43908],"mapped",[5044]],[[43909,43909],"mapped",[5045]],[[43910,43910],"mapped",[5046]],[[43911,43911],"mapped",[5047]],[[43912,43912],"mapped",[5048]],[[43913,43913],"mapped",[5049]],[[43914,43914],"mapped",[5050]],[[43915,43915],"mapped",[5051]],[[43916,43916],"mapped",[5052]],[[43917,43917],"mapped",[5053]],[[43918,43918],"mapped",[5054]],[[43919,43919],"mapped",[5055]],[[43920,43920],"mapped",[5056]],[[43921,43921],"mapped",[5057]],[[43922,43922],"mapped",[5058]],[[43923,43923],"mapped",[5059]],[[43924,43924],"mapped",[5060]],[[43925,43925],"mapped",[5061]],[[43926,43926],"mapped",[5062]],[[43927,43927],"mapped",[5063]],[[43928,43928],"mapped",[5064]],[[43929,43929],"mapped",[5065]],[[43930,43930],"mapped",[5066]],[[43931,43931],"mapped",[5067]],[[43932,43932],"mapped",[5068]],[[43933,43933],"mapped",[5069]],[[43934,43934],"mapped",[5070]],[[43935,43935],"mapped",[5071]],[[43936,43936],"mapped",[5072]],[[43937,43937],"mapped",[5073]],[[43938,43938],"mapped",[5074]],[[43939,43939],"mapped",[5075]],[[43940,43940],"mapped",[5076]],[[43941,43941],"mapped",[5077]],[[43942,43942],"mapped",[5078]],[[43943,43943],"mapped",[5079]],[[43944,43944],"mapped",[5080]],[[43945,43945],"mapped",[5081]],[[43946,43946],"mapped",[5082]],[[43947,43947],"mapped",[5083]],[[43948,43948],"mapped",[5084]],[[43949,43949],"mapped",[5085]],[[43950,43950],"mapped",[5086]],[[43951,43951],"mapped",[5087]],[[43952,43952],"mapped",[5088]],[[43953,43953],"mapped",[5089]],[[43954,43954],"mapped",[5090]],[[43955,43955],"mapped",[5091]],[[43956,43956],"mapped",[5092]],[[43957,43957],"mapped",[5093]],[[43958,43958],"mapped",[5094]],[[43959,43959],"mapped",[5095]],[[43960,43960],"mapped",[5096]],[[43961,43961],"mapped",[5097]],[[43962,43962],"mapped",[5098]],[[43963,43963],"mapped",[5099]],[[43964,43964],"mapped",[5100]],[[43965,43965],"mapped",[5101]],[[43966,43966],"mapped",[5102]],[[43967,43967],"mapped",[5103]],[[43968,44010],"valid"],[[44011,44011],"valid",[],"NV8"],[[44012,44013],"valid"],[[44014,44015],"disallowed"],[[44016,44025],"valid"],[[44026,44031],"disallowed"],[[44032,55203],"valid"],[[55204,55215],"disallowed"],[[55216,55238],"valid",[],"NV8"],[[55239,55242],"disallowed"],[[55243,55291],"valid",[],"NV8"],[[55292,55295],"disallowed"],[[55296,57343],"disallowed"],[[57344,63743],"disallowed"],[[63744,63744],"mapped",[35912]],[[63745,63745],"mapped",[26356]],[[63746,63746],"mapped",[36554]],[[63747,63747],"mapped",[36040]],[[63748,63748],"mapped",[28369]],[[63749,63749],"mapped",[20018]],[[63750,63750],"mapped",[21477]],[[63751,63752],"mapped",[40860]],[[63753,63753],"mapped",[22865]],[[63754,63754],"mapped",[37329]],[[63755,63755],"mapped",[21895]],[[63756,63756],"mapped",[22856]],[[63757,63757],"mapped",[25078]],[[63758,63758],"mapped",[30313]],[[63759,63759],"mapped",[32645]],[[63760,63760],"mapped",[34367]],[[63761,63761],"mapped",[34746]],[[63762,63762],"mapped",[35064]],[[63763,63763],"mapped",[37007]],[[63764,63764],"mapped",[27138]],[[63765,63765],"mapped",[27931]],[[63766,63766],"mapped",[28889]],[[63767,63767],"mapped",[29662]],[[63768,63768],"mapped",[33853]],[[63769,63769],"mapped",[37226]],[[63770,63770],"mapped",[39409]],[[63771,63771],"mapped",[20098]],[[63772,63772],"mapped",[21365]],[[63773,63773],"mapped",[27396]],[[63774,63774],"mapped",[29211]],[[63775,63775],"mapped",[34349]],[[63776,63776],"mapped",[40478]],[[63777,63777],"mapped",[23888]],[[63778,63778],"mapped",[28651]],[[63779,63779],"mapped",[34253]],[[63780,63780],"mapped",[35172]],[[63781,63781],"mapped",[25289]],[[63782,63782],"mapped",[33240]],[[63783,63783],"mapped",[34847]],[[63784,63784],"mapped",[24266]],[[63785,63785],"mapped",[26391]],[[63786,63786],"mapped",[28010]],[[63787,63787],"mapped",[29436]],[[63788,63788],"mapped",[37070]],[[63789,63789],"mapped",[20358]],[[63790,63790],"mapped",[20919]],[[63791,63791],"mapped",[21214]],[[63792,63792],"mapped",[25796]],[[63793,63793],"mapped",[27347]],[[63794,63794],"mapped",[29200]],[[63795,63795],"mapped",[30439]],[[63796,63796],"mapped",[32769]],[[63797,63797],"mapped",[34310]],[[63798,63798],"mapped",[34396]],[[63799,63799],"mapped",[36335]],[[63800,63800],"mapped",[38706]],[[63801,63801],"mapped",[39791]],[[63802,63802],"mapped",[40442]],[[63803,63803],"mapped",[30860]],[[63804,63804],"mapped",[31103]],[[63805,63805],"mapped",[32160]],[[63806,63806],"mapped",[33737]],[[63807,63807],"mapped",[37636]],[[63808,63808],"mapped",[40575]],[[63809,63809],"mapped",[35542]],[[63810,63810],"mapped",[22751]],[[63811,63811],"mapped",[24324]],[[63812,63812],"mapped",[31840]],[[63813,63813],"mapped",[32894]],[[63814,63814],"mapped",[29282]],[[63815,63815],"mapped",[30922]],[[63816,63816],"mapped",[36034]],[[63817,63817],"mapped",[38647]],[[63818,63818],"mapped",[22744]],[[63819,63819],"mapped",[23650]],[[63820,63820],"mapped",[27155]],[[63821,63821],"mapped",[28122]],[[63822,63822],"mapped",[28431]],[[63823,63823],"mapped",[32047]],[[63824,63824],"mapped",[32311]],[[63825,63825],"mapped",[38475]],[[63826,63826],"mapped",[21202]],[[63827,63827],"mapped",[32907]],[[63828,63828],"mapped",[20956]],[[63829,63829],"mapped",[20940]],[[63830,63830],"mapped",[31260]],[[63831,63831],"mapped",[32190]],[[63832,63832],"mapped",[33777]],[[63833,63833],"mapped",[38517]],[[63834,63834],"mapped",[35712]],[[63835,63835],"mapped",[25295]],[[63836,63836],"mapped",[27138]],[[63837,63837],"mapped",[35582]],[[63838,63838],"mapped",[20025]],[[63839,63839],"mapped",[23527]],[[63840,63840],"mapped",[24594]],[[63841,63841],"mapped",[29575]],[[63842,63842],"mapped",[30064]],[[63843,63843],"mapped",[21271]],[[63844,63844],"mapped",[30971]],[[63845,63845],"mapped",[20415]],[[63846,63846],"mapped",[24489]],[[63847,63847],"mapped",[19981]],[[63848,63848],"mapped",[27852]],[[63849,63849],"mapped",[25976]],[[63850,63850],"mapped",[32034]],[[63851,63851],"mapped",[21443]],[[63852,63852],"mapped",[22622]],[[63853,63853],"mapped",[30465]],[[63854,63854],"mapped",[33865]],[[63855,63855],"mapped",[35498]],[[63856,63856],"mapped",[27578]],[[63857,63857],"mapped",[36784]],[[63858,63858],"mapped",[27784]],[[63859,63859],"mapped",[25342]],[[63860,63860],"mapped",[33509]],[[63861,63861],"mapped",[25504]],[[63862,63862],"mapped",[30053]],[[63863,63863],"mapped",[20142]],[[63864,63864],"mapped",[20841]],[[63865,63865],"mapped",[20937]],[[63866,63866],"mapped",[26753]],[[63867,63867],"mapped",[31975]],[[63868,63868],"mapped",[33391]],[[63869,63869],"mapped",[35538]],[[63870,63870],"mapped",[37327]],[[63871,63871],"mapped",[21237]],[[63872,63872],"mapped",[21570]],[[63873,63873],"mapped",[22899]],[[63874,63874],"mapped",[24300]],[[63875,63875],"mapped",[26053]],[[63876,63876],"mapped",[28670]],[[63877,63877],"mapped",[31018]],[[63878,63878],"mapped",[38317]],[[63879,63879],"mapped",[39530]],[[63880,63880],"mapped",[40599]],[[63881,63881],"mapped",[40654]],[[63882,63882],"mapped",[21147]],[[63883,63883],"mapped",[26310]],[[63884,63884],"mapped",[27511]],[[63885,63885],"mapped",[36706]],[[63886,63886],"mapped",[24180]],[[63887,63887],"mapped",[24976]],[[63888,63888],"mapped",[25088]],[[63889,63889],"mapped",[25754]],[[63890,63890],"mapped",[28451]],[[63891,63891],"mapped",[29001]],[[63892,63892],"mapped",[29833]],[[63893,63893],"mapped",[31178]],[[63894,63894],"mapped",[32244]],[[63895,63895],"mapped",[32879]],[[63896,63896],"mapped",[36646]],[[63897,63897],"mapped",[34030]],[[63898,63898],"mapped",[36899]],[[63899,63899],"mapped",[37706]],[[63900,63900],"mapped",[21015]],[[63901,63901],"mapped",[21155]],[[63902,63902],"mapped",[21693]],[[63903,63903],"mapped",[28872]],[[63904,63904],"mapped",[35010]],[[63905,63905],"mapped",[35498]],[[63906,63906],"mapped",[24265]],[[63907,63907],"mapped",[24565]],[[63908,63908],"mapped",[25467]],[[63909,63909],"mapped",[27566]],[[63910,63910],"mapped",[31806]],[[63911,63911],"mapped",[29557]],[[63912,63912],"mapped",[20196]],[[63913,63913],"mapped",[22265]],[[63914,63914],"mapped",[23527]],[[63915,63915],"mapped",[23994]],[[63916,63916],"mapped",[24604]],[[63917,63917],"mapped",[29618]],[[63918,63918],"mapped",[29801]],[[63919,63919],"mapped",[32666]],[[63920,63920],"mapped",[32838]],[[63921,63921],"mapped",[37428]],[[63922,63922],"mapped",[38646]],[[63923,63923],"mapped",[38728]],[[63924,63924],"mapped",[38936]],[[63925,63925],"mapped",[20363]],[[63926,63926],"mapped",[31150]],[[63927,63927],"mapped",[37300]],[[63928,63928],"mapped",[38584]],[[63929,63929],"mapped",[24801]],[[63930,63930],"mapped",[20102]],[[63931,63931],"mapped",[20698]],[[63932,63932],"mapped",[23534]],[[63933,63933],"mapped",[23615]],[[63934,63934],"mapped",[26009]],[[63935,63935],"mapped",[27138]],[[63936,63936],"mapped",[29134]],[[63937,63937],"mapped",[30274]],[[63938,63938],"mapped",[34044]],[[63939,63939],"mapped",[36988]],[[63940,63940],"mapped",[40845]],[[63941,63941],"mapped",[26248]],[[63942,63942],"mapped",[38446]],[[63943,63943],"mapped",[21129]],[[63944,63944],"mapped",[26491]],[[63945,63945],"mapped",[26611]],[[63946,63946],"mapped",[27969]],[[63947,63947],"mapped",[28316]],[[63948,63948],"mapped",[29705]],[[63949,63949],"mapped",[30041]],[[63950,63950],"mapped",[30827]],[[63951,63951],"mapped",[32016]],[[63952,63952],"mapped",[39006]],[[63953,63953],"mapped",[20845]],[[63954,63954],"mapped",[25134]],[[63955,63955],"mapped",[38520]],[[63956,63956],"mapped",[20523]],[[63957,63957],"mapped",[23833]],[[63958,63958],"mapped",[28138]],[[63959,63959],"mapped",[36650]],[[63960,63960],"mapped",[24459]],[[63961,63961],"mapped",[24900]],[[63962,63962],"mapped",[26647]],[[63963,63963],"mapped",[29575]],[[63964,63964],"mapped",[38534]],[[63965,63965],"mapped",[21033]],[[63966,63966],"mapped",[21519]],[[63967,63967],"mapped",[23653]],[[63968,63968],"mapped",[26131]],[[63969,63969],"mapped",[26446]],[[63970,63970],"mapped",[26792]],[[63971,63971],"mapped",[27877]],[[63972,63972],"mapped",[29702]],[[63973,63973],"mapped",[30178]],[[63974,63974],"mapped",[32633]],[[63975,63975],"mapped",[35023]],[[63976,63976],"mapped",[35041]],[[63977,63977],"mapped",[37324]],[[63978,63978],"mapped",[38626]],[[63979,63979],"mapped",[21311]],[[63980,63980],"mapped",[28346]],[[63981,63981],"mapped",[21533]],[[63982,63982],"mapped",[29136]],[[63983,63983],"mapped",[29848]],[[63984,63984],"mapped",[34298]],[[63985,63985],"mapped",[38563]],[[63986,63986],"mapped",[40023]],[[63987,63987],"mapped",[40607]],[[63988,63988],"mapped",[26519]],[[63989,63989],"mapped",[28107]],[[63990,63990],"mapped",[33256]],[[63991,63991],"mapped",[31435]],[[63992,63992],"mapped",[31520]],[[63993,63993],"mapped",[31890]],[[63994,63994],"mapped",[29376]],[[63995,63995],"mapped",[28825]],[[63996,63996],"mapped",[35672]],[[63997,63997],"mapped",[20160]],[[63998,63998],"mapped",[33590]],[[63999,63999],"mapped",[21050]],[[64000,64000],"mapped",[20999]],[[64001,64001],"mapped",[24230]],[[64002,64002],"mapped",[25299]],[[64003,64003],"mapped",[31958]],[[64004,64004],"mapped",[23429]],[[64005,64005],"mapped",[27934]],[[64006,64006],"mapped",[26292]],[[64007,64007],"mapped",[36667]],[[64008,64008],"mapped",[34892]],[[64009,64009],"mapped",[38477]],[[64010,64010],"mapped",[35211]],[[64011,64011],"mapped",[24275]],[[64012,64012],"mapped",[20800]],[[64013,64013],"mapped",[21952]],[[64014,64015],"valid"],[[64016,64016],"mapped",[22618]],[[64017,64017],"valid"],[[64018,64018],"mapped",[26228]],[[64019,64020],"valid"],[[64021,64021],"mapped",[20958]],[[64022,64022],"mapped",[29482]],[[64023,64023],"mapped",[30410]],[[64024,64024],"mapped",[31036]],[[64025,64025],"mapped",[31070]],[[64026,64026],"mapped",[31077]],[[64027,64027],"mapped",[31119]],[[64028,64028],"mapped",[38742]],[[64029,64029],"mapped",[31934]],[[64030,64030],"mapped",[32701]],[[64031,64031],"valid"],[[64032,64032],"mapped",[34322]],[[64033,64033],"valid"],[[64034,64034],"mapped",[35576]],[[64035,64036],"valid"],[[64037,64037],"mapped",[36920]],[[64038,64038],"mapped",[37117]],[[64039,64041],"valid"],[[64042,64042],"mapped",[39151]],[[64043,64043],"mapped",[39164]],[[64044,64044],"mapped",[39208]],[[64045,64045],"mapped",[40372]],[[64046,64046],"mapped",[37086]],[[64047,64047],"mapped",[38583]],[[64048,64048],"mapped",[20398]],[[64049,64049],"mapped",[20711]],[[64050,64050],"mapped",[20813]],[[64051,64051],"mapped",[21193]],[[64052,64052],"mapped",[21220]],[[64053,64053],"mapped",[21329]],[[64054,64054],"mapped",[21917]],[[64055,64055],"mapped",[22022]],[[64056,64056],"mapped",[22120]],[[64057,64057],"mapped",[22592]],[[64058,64058],"mapped",[22696]],[[64059,64059],"mapped",[23652]],[[64060,64060],"mapped",[23662]],[[64061,64061],"mapped",[24724]],[[64062,64062],"mapped",[24936]],[[64063,64063],"mapped",[24974]],[[64064,64064],"mapped",[25074]],[[64065,64065],"mapped",[25935]],[[64066,64066],"mapped",[26082]],[[64067,64067],"mapped",[26257]],[[64068,64068],"mapped",[26757]],[[64069,64069],"mapped",[28023]],[[64070,64070],"mapped",[28186]],[[64071,64071],"mapped",[28450]],[[64072,64072],"mapped",[29038]],[[64073,64073],"mapped",[29227]],[[64074,64074],"mapped",[29730]],[[64075,64075],"mapped",[30865]],[[64076,64076],"mapped",[31038]],[[64077,64077],"mapped",[31049]],[[64078,64078],"mapped",[31048]],[[64079,64079],"mapped",[31056]],[[64080,64080],"mapped",[31062]],[[64081,64081],"mapped",[31069]],[[64082,64082],"mapped",[31117]],[[64083,64083],"mapped",[31118]],[[64084,64084],"mapped",[31296]],[[64085,64085],"mapped",[31361]],[[64086,64086],"mapped",[31680]],[[64087,64087],"mapped",[32244]],[[64088,64088],"mapped",[32265]],[[64089,64089],"mapped",[32321]],[[64090,64090],"mapped",[32626]],[[64091,64091],"mapped",[32773]],[[64092,64092],"mapped",[33261]],[[64093,64094],"mapped",[33401]],[[64095,64095],"mapped",[33879]],[[64096,64096],"mapped",[35088]],[[64097,64097],"mapped",[35222]],[[64098,64098],"mapped",[35585]],[[64099,64099],"mapped",[35641]],[[64100,64100],"mapped",[36051]],[[64101,64101],"mapped",[36104]],[[64102,64102],"mapped",[36790]],[[64103,64103],"mapped",[36920]],[[64104,64104],"mapped",[38627]],[[64105,64105],"mapped",[38911]],[[64106,64106],"mapped",[38971]],[[64107,64107],"mapped",[24693]],[[64108,64108],"mapped",[148206]],[[64109,64109],"mapped",[33304]],[[64110,64111],"disallowed"],[[64112,64112],"mapped",[20006]],[[64113,64113],"mapped",[20917]],[[64114,64114],"mapped",[20840]],[[64115,64115],"mapped",[20352]],[[64116,64116],"mapped",[20805]],[[64117,64117],"mapped",[20864]],[[64118,64118],"mapped",[21191]],[[64119,64119],"mapped",[21242]],[[64120,64120],"mapped",[21917]],[[64121,64121],"mapped",[21845]],[[64122,64122],"mapped",[21913]],[[64123,64123],"mapped",[21986]],[[64124,64124],"mapped",[22618]],[[64125,64125],"mapped",[22707]],[[64126,64126],"mapped",[22852]],[[64127,64127],"mapped",[22868]],[[64128,64128],"mapped",[23138]],[[64129,64129],"mapped",[23336]],[[64130,64130],"mapped",[24274]],[[64131,64131],"mapped",[24281]],[[64132,64132],"mapped",[24425]],[[64133,64133],"mapped",[24493]],[[64134,64134],"mapped",[24792]],[[64135,64135],"mapped",[24910]],[[64136,64136],"mapped",[24840]],[[64137,64137],"mapped",[24974]],[[64138,64138],"mapped",[24928]],[[64139,64139],"mapped",[25074]],[[64140,64140],"mapped",[25140]],[[64141,64141],"mapped",[25540]],[[64142,64142],"mapped",[25628]],[[64143,64143],"mapped",[25682]],[[64144,64144],"mapped",[25942]],[[64145,64145],"mapped",[26228]],[[64146,64146],"mapped",[26391]],[[64147,64147],"mapped",[26395]],[[64148,64148],"mapped",[26454]],[[64149,64149],"mapped",[27513]],[[64150,64150],"mapped",[27578]],[[64151,64151],"mapped",[27969]],[[64152,64152],"mapped",[28379]],[[64153,64153],"mapped",[28363]],[[64154,64154],"mapped",[28450]],[[64155,64155],"mapped",[28702]],[[64156,64156],"mapped",[29038]],[[64157,64157],"mapped",[30631]],[[64158,64158],"mapped",[29237]],[[64159,64159],"mapped",[29359]],[[64160,64160],"mapped",[29482]],[[64161,64161],"mapped",[29809]],[[64162,64162],"mapped",[29958]],[[64163,64163],"mapped",[30011]],[[64164,64164],"mapped",[30237]],[[64165,64165],"mapped",[30239]],[[64166,64166],"mapped",[30410]],[[64167,64167],"mapped",[30427]],[[64168,64168],"mapped",[30452]],[[64169,64169],"mapped",[30538]],[[64170,64170],"mapped",[30528]],[[64171,64171],"mapped",[30924]],[[64172,64172],"mapped",[31409]],[[64173,64173],"mapped",[31680]],[[64174,64174],"mapped",[31867]],[[64175,64175],"mapped",[32091]],[[64176,64176],"mapped",[32244]],[[64177,64177],"mapped",[32574]],[[64178,64178],"mapped",[32773]],[[64179,64179],"mapped",[33618]],[[64180,64180],"mapped",[33775]],[[64181,64181],"mapped",[34681]],[[64182,64182],"mapped",[35137]],[[64183,64183],"mapped",[35206]],[[64184,64184],"mapped",[35222]],[[64185,64185],"mapped",[35519]],[[64186,64186],"mapped",[35576]],[[64187,64187],"mapped",[35531]],[[64188,64188],"mapped",[35585]],[[64189,64189],"mapped",[35582]],[[64190,64190],"mapped",[35565]],[[64191,64191],"mapped",[35641]],[[64192,64192],"mapped",[35722]],[[64193,64193],"mapped",[36104]],[[64194,64194],"mapped",[36664]],[[64195,64195],"mapped",[36978]],[[64196,64196],"mapped",[37273]],[[64197,64197],"mapped",[37494]],[[64198,64198],"mapped",[38524]],[[64199,64199],"mapped",[38627]],[[64200,64200],"mapped",[38742]],[[64201,64201],"mapped",[38875]],[[64202,64202],"mapped",[38911]],[[64203,64203],"mapped",[38923]],[[64204,64204],"mapped",[38971]],[[64205,64205],"mapped",[39698]],[[64206,64206],"mapped",[40860]],[[64207,64207],"mapped",[141386]],[[64208,64208],"mapped",[141380]],[[64209,64209],"mapped",[144341]],[[64210,64210],"mapped",[15261]],[[64211,64211],"mapped",[16408]],[[64212,64212],"mapped",[16441]],[[64213,64213],"mapped",[152137]],[[64214,64214],"mapped",[154832]],[[64215,64215],"mapped",[163539]],[[64216,64216],"mapped",[40771]],[[64217,64217],"mapped",[40846]],[[64218,64255],"disallowed"],[[64256,64256],"mapped",[102,102]],[[64257,64257],"mapped",[102,105]],[[64258,64258],"mapped",[102,108]],[[64259,64259],"mapped",[102,102,105]],[[64260,64260],"mapped",[102,102,108]],[[64261,64262],"mapped",[115,116]],[[64263,64274],"disallowed"],[[64275,64275],"mapped",[1396,1398]],[[64276,64276],"mapped",[1396,1381]],[[64277,64277],"mapped",[1396,1387]],[[64278,64278],"mapped",[1406,1398]],[[64279,64279],"mapped",[1396,1389]],[[64280,64284],"disallowed"],[[64285,64285],"mapped",[1497,1460]],[[64286,64286],"valid"],[[64287,64287],"mapped",[1522,1463]],[[64288,64288],"mapped",[1506]],[[64289,64289],"mapped",[1488]],[[64290,64290],"mapped",[1491]],[[64291,64291],"mapped",[1492]],[[64292,64292],"mapped",[1499]],[[64293,64293],"mapped",[1500]],[[64294,64294],"mapped",[1501]],[[64295,64295],"mapped",[1512]],[[64296,64296],"mapped",[1514]],[[64297,64297],"disallowed_STD3_mapped",[43]],[[64298,64298],"mapped",[1513,1473]],[[64299,64299],"mapped",[1513,1474]],[[64300,64300],"mapped",[1513,1468,1473]],[[64301,64301],"mapped",[1513,1468,1474]],[[64302,64302],"mapped",[1488,1463]],[[64303,64303],"mapped",[1488,1464]],[[64304,64304],"mapped",[1488,1468]],[[64305,64305],"mapped",[1489,1468]],[[64306,64306],"mapped",[1490,1468]],[[64307,64307],"mapped",[1491,1468]],[[64308,64308],"mapped",[1492,1468]],[[64309,64309],"mapped",[1493,1468]],[[64310,64310],"mapped",[1494,1468]],[[64311,64311],"disallowed"],[[64312,64312],"mapped",[1496,1468]],[[64313,64313],"mapped",[1497,1468]],[[64314,64314],"mapped",[1498,1468]],[[64315,64315],"mapped",[1499,1468]],[[64316,64316],"mapped",[1500,1468]],[[64317,64317],"disallowed"],[[64318,64318],"mapped",[1502,1468]],[[64319,64319],"disallowed"],[[64320,64320],"mapped",[1504,1468]],[[64321,64321],"mapped",[1505,1468]],[[64322,64322],"disallowed"],[[64323,64323],"mapped",[1507,1468]],[[64324,64324],"mapped",[1508,1468]],[[64325,64325],"disallowed"],[[64326,64326],"mapped",[1510,1468]],[[64327,64327],"mapped",[1511,1468]],[[64328,64328],"mapped",[1512,1468]],[[64329,64329],"mapped",[1513,1468]],[[64330,64330],"mapped",[1514,1468]],[[64331,64331],"mapped",[1493,1465]],[[64332,64332],"mapped",[1489,1471]],[[64333,64333],"mapped",[1499,1471]],[[64334,64334],"mapped",[1508,1471]],[[64335,64335],"mapped",[1488,1500]],[[64336,64337],"mapped",[1649]],[[64338,64341],"mapped",[1659]],[[64342,64345],"mapped",[1662]],[[64346,64349],"mapped",[1664]],[[64350,64353],"mapped",[1658]],[[64354,64357],"mapped",[1663]],[[64358,64361],"mapped",[1657]],[[64362,64365],"mapped",[1700]],[[64366,64369],"mapped",[1702]],[[64370,64373],"mapped",[1668]],[[64374,64377],"mapped",[1667]],[[64378,64381],"mapped",[1670]],[[64382,64385],"mapped",[1671]],[[64386,64387],"mapped",[1677]],[[64388,64389],"mapped",[1676]],[[64390,64391],"mapped",[1678]],[[64392,64393],"mapped",[1672]],[[64394,64395],"mapped",[1688]],[[64396,64397],"mapped",[1681]],[[64398,64401],"mapped",[1705]],[[64402,64405],"mapped",[1711]],[[64406,64409],"mapped",[1715]],[[64410,64413],"mapped",[1713]],[[64414,64415],"mapped",[1722]],[[64416,64419],"mapped",[1723]],[[64420,64421],"mapped",[1728]],[[64422,64425],"mapped",[1729]],[[64426,64429],"mapped",[1726]],[[64430,64431],"mapped",[1746]],[[64432,64433],"mapped",[1747]],[[64434,64449],"valid",[],"NV8"],[[64450,64466],"disallowed"],[[64467,64470],"mapped",[1709]],[[64471,64472],"mapped",[1735]],[[64473,64474],"mapped",[1734]],[[64475,64476],"mapped",[1736]],[[64477,64477],"mapped",[1735,1652]],[[64478,64479],"mapped",[1739]],[[64480,64481],"mapped",[1733]],[[64482,64483],"mapped",[1737]],[[64484,64487],"mapped",[1744]],[[64488,64489],"mapped",[1609]],[[64490,64491],"mapped",[1574,1575]],[[64492,64493],"mapped",[1574,1749]],[[64494,64495],"mapped",[1574,1608]],[[64496,64497],"mapped",[1574,1735]],[[64498,64499],"mapped",[1574,1734]],[[64500,64501],"mapped",[1574,1736]],[[64502,64504],"mapped",[1574,1744]],[[64505,64507],"mapped",[1574,1609]],[[64508,64511],"mapped",[1740]],[[64512,64512],"mapped",[1574,1580]],[[64513,64513],"mapped",[1574,1581]],[[64514,64514],"mapped",[1574,1605]],[[64515,64515],"mapped",[1574,1609]],[[64516,64516],"mapped",[1574,1610]],[[64517,64517],"mapped",[1576,1580]],[[64518,64518],"mapped",[1576,1581]],[[64519,64519],"mapped",[1576,1582]],[[64520,64520],"mapped",[1576,1605]],[[64521,64521],"mapped",[1576,1609]],[[64522,64522],"mapped",[1576,1610]],[[64523,64523],"mapped",[1578,1580]],[[64524,64524],"mapped",[1578,1581]],[[64525,64525],"mapped",[1578,1582]],[[64526,64526],"mapped",[1578,1605]],[[64527,64527],"mapped",[1578,1609]],[[64528,64528],"mapped",[1578,1610]],[[64529,64529],"mapped",[1579,1580]],[[64530,64530],"mapped",[1579,1605]],[[64531,64531],"mapped",[1579,1609]],[[64532,64532],"mapped",[1579,1610]],[[64533,64533],"mapped",[1580,1581]],[[64534,64534],"mapped",[1580,1605]],[[64535,64535],"mapped",[1581,1580]],[[64536,64536],"mapped",[1581,1605]],[[64537,64537],"mapped",[1582,1580]],[[64538,64538],"mapped",[1582,1581]],[[64539,64539],"mapped",[1582,1605]],[[64540,64540],"mapped",[1587,1580]],[[64541,64541],"mapped",[1587,1581]],[[64542,64542],"mapped",[1587,1582]],[[64543,64543],"mapped",[1587,1605]],[[64544,64544],"mapped",[1589,1581]],[[64545,64545],"mapped",[1589,1605]],[[64546,64546],"mapped",[1590,1580]],[[64547,64547],"mapped",[1590,1581]],[[64548,64548],"mapped",[1590,1582]],[[64549,64549],"mapped",[1590,1605]],[[64550,64550],"mapped",[1591,1581]],[[64551,64551],"mapped",[1591,1605]],[[64552,64552],"mapped",[1592,1605]],[[64553,64553],"mapped",[1593,1580]],[[64554,64554],"mapped",[1593,1605]],[[64555,64555],"mapped",[1594,1580]],[[64556,64556],"mapped",[1594,1605]],[[64557,64557],"mapped",[1601,1580]],[[64558,64558],"mapped",[1601,1581]],[[64559,64559],"mapped",[1601,1582]],[[64560,64560],"mapped",[1601,1605]],[[64561,64561],"mapped",[1601,1609]],[[64562,64562],"mapped",[1601,1610]],[[64563,64563],"mapped",[1602,1581]],[[64564,64564],"mapped",[1602,1605]],[[64565,64565],"mapped",[1602,1609]],[[64566,64566],"mapped",[1602,1610]],[[64567,64567],"mapped",[1603,1575]],[[64568,64568],"mapped",[1603,1580]],[[64569,64569],"mapped",[1603,1581]],[[64570,64570],"mapped",[1603,1582]],[[64571,64571],"mapped",[1603,1604]],[[64572,64572],"mapped",[1603,1605]],[[64573,64573],"mapped",[1603,1609]],[[64574,64574],"mapped",[1603,1610]],[[64575,64575],"mapped",[1604,1580]],[[64576,64576],"mapped",[1604,1581]],[[64577,64577],"mapped",[1604,1582]],[[64578,64578],"mapped",[1604,1605]],[[64579,64579],"mapped",[1604,1609]],[[64580,64580],"mapped",[1604,1610]],[[64581,64581],"mapped",[1605,1580]],[[64582,64582],"mapped",[1605,1581]],[[64583,64583],"mapped",[1605,1582]],[[64584,64584],"mapped",[1605,1605]],[[64585,64585],"mapped",[1605,1609]],[[64586,64586],"mapped",[1605,1610]],[[64587,64587],"mapped",[1606,1580]],[[64588,64588],"mapped",[1606,1581]],[[64589,64589],"mapped",[1606,1582]],[[64590,64590],"mapped",[1606,1605]],[[64591,64591],"mapped",[1606,1609]],[[64592,64592],"mapped",[1606,1610]],[[64593,64593],"mapped",[1607,1580]],[[64594,64594],"mapped",[1607,1605]],[[64595,64595],"mapped",[1607,1609]],[[64596,64596],"mapped",[1607,1610]],[[64597,64597],"mapped",[1610,1580]],[[64598,64598],"mapped",[1610,1581]],[[64599,64599],"mapped",[1610,1582]],[[64600,64600],"mapped",[1610,1605]],[[64601,64601],"mapped",[1610,1609]],[[64602,64602],"mapped",[1610,1610]],[[64603,64603],"mapped",[1584,1648]],[[64604,64604],"mapped",[1585,1648]],[[64605,64605],"mapped",[1609,1648]],[[64606,64606],"disallowed_STD3_mapped",[32,1612,1617]],[[64607,64607],"disallowed_STD3_mapped",[32,1613,1617]],[[64608,64608],"disallowed_STD3_mapped",[32,1614,1617]],[[64609,64609],"disallowed_STD3_mapped",[32,1615,1617]],[[64610,64610],"disallowed_STD3_mapped",[32,1616,1617]],[[64611,64611],"disallowed_STD3_mapped",[32,1617,1648]],[[64612,64612],"mapped",[1574,1585]],[[64613,64613],"mapped",[1574,1586]],[[64614,64614],"mapped",[1574,1605]],[[64615,64615],"mapped",[1574,1606]],[[64616,64616],"mapped",[1574,1609]],[[64617,64617],"mapped",[1574,1610]],[[64618,64618],"mapped",[1576,1585]],[[64619,64619],"mapped",[1576,1586]],[[64620,64620],"mapped",[1576,1605]],[[64621,64621],"mapped",[1576,1606]],[[64622,64622],"mapped",[1576,1609]],[[64623,64623],"mapped",[1576,1610]],[[64624,64624],"mapped",[1578,1585]],[[64625,64625],"mapped",[1578,1586]],[[64626,64626],"mapped",[1578,1605]],[[64627,64627],"mapped",[1578,1606]],[[64628,64628],"mapped",[1578,1609]],[[64629,64629],"mapped",[1578,1610]],[[64630,64630],"mapped",[1579,1585]],[[64631,64631],"mapped",[1579,1586]],[[64632,64632],"mapped",[1579,1605]],[[64633,64633],"mapped",[1579,1606]],[[64634,64634],"mapped",[1579,1609]],[[64635,64635],"mapped",[1579,1610]],[[64636,64636],"mapped",[1601,1609]],[[64637,64637],"mapped",[1601,1610]],[[64638,64638],"mapped",[1602,1609]],[[64639,64639],"mapped",[1602,1610]],[[64640,64640],"mapped",[1603,1575]],[[64641,64641],"mapped",[1603,1604]],[[64642,64642],"mapped",[1603,1605]],[[64643,64643],"mapped",[1603,1609]],[[64644,64644],"mapped",[1603,1610]],[[64645,64645],"mapped",[1604,1605]],[[64646,64646],"mapped",[1604,1609]],[[64647,64647],"mapped",[1604,1610]],[[64648,64648],"mapped",[1605,1575]],[[64649,64649],"mapped",[1605,1605]],[[64650,64650],"mapped",[1606,1585]],[[64651,64651],"mapped",[1606,1586]],[[64652,64652],"mapped",[1606,1605]],[[64653,64653],"mapped",[1606,1606]],[[64654,64654],"mapped",[1606,1609]],[[64655,64655],"mapped",[1606,1610]],[[64656,64656],"mapped",[1609,1648]],[[64657,64657],"mapped",[1610,1585]],[[64658,64658],"mapped",[1610,1586]],[[64659,64659],"mapped",[1610,1605]],[[64660,64660],"mapped",[1610,1606]],[[64661,64661],"mapped",[1610,1609]],[[64662,64662],"mapped",[1610,1610]],[[64663,64663],"mapped",[1574,1580]],[[64664,64664],"mapped",[1574,1581]],[[64665,64665],"mapped",[1574,1582]],[[64666,64666],"mapped",[1574,1605]],[[64667,64667],"mapped",[1574,1607]],[[64668,64668],"mapped",[1576,1580]],[[64669,64669],"mapped",[1576,1581]],[[64670,64670],"mapped",[1576,1582]],[[64671,64671],"mapped",[1576,1605]],[[64672,64672],"mapped",[1576,1607]],[[64673,64673],"mapped",[1578,1580]],[[64674,64674],"mapped",[1578,1581]],[[64675,64675],"mapped",[1578,1582]],[[64676,64676],"mapped",[1578,1605]],[[64677,64677],"mapped",[1578,1607]],[[64678,64678],"mapped",[1579,1605]],[[64679,64679],"mapped",[1580,1581]],[[64680,64680],"mapped",[1580,1605]],[[64681,64681],"mapped",[1581,1580]],[[64682,64682],"mapped",[1581,1605]],[[64683,64683],"mapped",[1582,1580]],[[64684,64684],"mapped",[1582,1605]],[[64685,64685],"mapped",[1587,1580]],[[64686,64686],"mapped",[1587,1581]],[[64687,64687],"mapped",[1587,1582]],[[64688,64688],"mapped",[1587,1605]],[[64689,64689],"mapped",[1589,1581]],[[64690,64690],"mapped",[1589,1582]],[[64691,64691],"mapped",[1589,1605]],[[64692,64692],"mapped",[1590,1580]],[[64693,64693],"mapped",[1590,1581]],[[64694,64694],"mapped",[1590,1582]],[[64695,64695],"mapped",[1590,1605]],[[64696,64696],"mapped",[1591,1581]],[[64697,64697],"mapped",[1592,1605]],[[64698,64698],"mapped",[1593,1580]],[[64699,64699],"mapped",[1593,1605]],[[64700,64700],"mapped",[1594,1580]],[[64701,64701],"mapped",[1594,1605]],[[64702,64702],"mapped",[1601,1580]],[[64703,64703],"mapped",[1601,1581]],[[64704,64704],"mapped",[1601,1582]],[[64705,64705],"mapped",[1601,1605]],[[64706,64706],"mapped",[1602,1581]],[[64707,64707],"mapped",[1602,1605]],[[64708,64708],"mapped",[1603,1580]],[[64709,64709],"mapped",[1603,1581]],[[64710,64710],"mapped",[1603,1582]],[[64711,64711],"mapped",[1603,1604]],[[64712,64712],"mapped",[1603,1605]],[[64713,64713],"mapped",[1604,1580]],[[64714,64714],"mapped",[1604,1581]],[[64715,64715],"mapped",[1604,1582]],[[64716,64716],"mapped",[1604,1605]],[[64717,64717],"mapped",[1604,1607]],[[64718,64718],"mapped",[1605,1580]],[[64719,64719],"mapped",[1605,1581]],[[64720,64720],"mapped",[1605,1582]],[[64721,64721],"mapped",[1605,1605]],[[64722,64722],"mapped",[1606,1580]],[[64723,64723],"mapped",[1606,1581]],[[64724,64724],"mapped",[1606,1582]],[[64725,64725],"mapped",[1606,1605]],[[64726,64726],"mapped",[1606,1607]],[[64727,64727],"mapped",[1607,1580]],[[64728,64728],"mapped",[1607,1605]],[[64729,64729],"mapped",[1607,1648]],[[64730,64730],"mapped",[1610,1580]],[[64731,64731],"mapped",[1610,1581]],[[64732,64732],"mapped",[1610,1582]],[[64733,64733],"mapped",[1610,1605]],[[64734,64734],"mapped",[1610,1607]],[[64735,64735],"mapped",[1574,1605]],[[64736,64736],"mapped",[1574,1607]],[[64737,64737],"mapped",[1576,1605]],[[64738,64738],"mapped",[1576,1607]],[[64739,64739],"mapped",[1578,1605]],[[64740,64740],"mapped",[1578,1607]],[[64741,64741],"mapped",[1579,1605]],[[64742,64742],"mapped",[1579,1607]],[[64743,64743],"mapped",[1587,1605]],[[64744,64744],"mapped",[1587,1607]],[[64745,64745],"mapped",[1588,1605]],[[64746,64746],"mapped",[1588,1607]],[[64747,64747],"mapped",[1603,1604]],[[64748,64748],"mapped",[1603,1605]],[[64749,64749],"mapped",[1604,1605]],[[64750,64750],"mapped",[1606,1605]],[[64751,64751],"mapped",[1606,1607]],[[64752,64752],"mapped",[1610,1605]],[[64753,64753],"mapped",[1610,1607]],[[64754,64754],"mapped",[1600,1614,1617]],[[64755,64755],"mapped",[1600,1615,1617]],[[64756,64756],"mapped",[1600,1616,1617]],[[64757,64757],"mapped",[1591,1609]],[[64758,64758],"mapped",[1591,1610]],[[64759,64759],"mapped",[1593,1609]],[[64760,64760],"mapped",[1593,1610]],[[64761,64761],"mapped",[1594,1609]],[[64762,64762],"mapped",[1594,1610]],[[64763,64763],"mapped",[1587,1609]],[[64764,64764],"mapped",[1587,1610]],[[64765,64765],"mapped",[1588,1609]],[[64766,64766],"mapped",[1588,1610]],[[64767,64767],"mapped",[1581,1609]],[[64768,64768],"mapped",[1581,1610]],[[64769,64769],"mapped",[1580,1609]],[[64770,64770],"mapped",[1580,1610]],[[64771,64771],"mapped",[1582,1609]],[[64772,64772],"mapped",[1582,1610]],[[64773,64773],"mapped",[1589,1609]],[[64774,64774],"mapped",[1589,1610]],[[64775,64775],"mapped",[1590,1609]],[[64776,64776],"mapped",[1590,1610]],[[64777,64777],"mapped",[1588,1580]],[[64778,64778],"mapped",[1588,1581]],[[64779,64779],"mapped",[1588,1582]],[[64780,64780],"mapped",[1588,1605]],[[64781,64781],"mapped",[1588,1585]],[[64782,64782],"mapped",[1587,1585]],[[64783,64783],"mapped",[1589,1585]],[[64784,64784],"mapped",[1590,1585]],[[64785,64785],"mapped",[1591,1609]],[[64786,64786],"mapped",[1591,1610]],[[64787,64787],"mapped",[1593,1609]],[[64788,64788],"mapped",[1593,1610]],[[64789,64789],"mapped",[1594,1609]],[[64790,64790],"mapped",[1594,1610]],[[64791,64791],"mapped",[1587,1609]],[[64792,64792],"mapped",[1587,1610]],[[64793,64793],"mapped",[1588,1609]],[[64794,64794],"mapped",[1588,1610]],[[64795,64795],"mapped",[1581,1609]],[[64796,64796],"mapped",[1581,1610]],[[64797,64797],"mapped",[1580,1609]],[[64798,64798],"mapped",[1580,1610]],[[64799,64799],"mapped",[1582,1609]],[[64800,64800],"mapped",[1582,1610]],[[64801,64801],"mapped",[1589,1609]],[[64802,64802],"mapped",[1589,1610]],[[64803,64803],"mapped",[1590,1609]],[[64804,64804],"mapped",[1590,1610]],[[64805,64805],"mapped",[1588,1580]],[[64806,64806],"mapped",[1588,1581]],[[64807,64807],"mapped",[1588,1582]],[[64808,64808],"mapped",[1588,1605]],[[64809,64809],"mapped",[1588,1585]],[[64810,64810],"mapped",[1587,1585]],[[64811,64811],"mapped",[1589,1585]],[[64812,64812],"mapped",[1590,1585]],[[64813,64813],"mapped",[1588,1580]],[[64814,64814],"mapped",[1588,1581]],[[64815,64815],"mapped",[1588,1582]],[[64816,64816],"mapped",[1588,1605]],[[64817,64817],"mapped",[1587,1607]],[[64818,64818],"mapped",[1588,1607]],[[64819,64819],"mapped",[1591,1605]],[[64820,64820],"mapped",[1587,1580]],[[64821,64821],"mapped",[1587,1581]],[[64822,64822],"mapped",[1587,1582]],[[64823,64823],"mapped",[1588,1580]],[[64824,64824],"mapped",[1588,1581]],[[64825,64825],"mapped",[1588,1582]],[[64826,64826],"mapped",[1591,1605]],[[64827,64827],"mapped",[1592,1605]],[[64828,64829],"mapped",[1575,1611]],[[64830,64831],"valid",[],"NV8"],[[64832,64847],"disallowed"],[[64848,64848],"mapped",[1578,1580,1605]],[[64849,64850],"mapped",[1578,1581,1580]],[[64851,64851],"mapped",[1578,1581,1605]],[[64852,64852],"mapped",[1578,1582,1605]],[[64853,64853],"mapped",[1578,1605,1580]],[[64854,64854],"mapped",[1578,1605,1581]],[[64855,64855],"mapped",[1578,1605,1582]],[[64856,64857],"mapped",[1580,1605,1581]],[[64858,64858],"mapped",[1581,1605,1610]],[[64859,64859],"mapped",[1581,1605,1609]],[[64860,64860],"mapped",[1587,1581,1580]],[[64861,64861],"mapped",[1587,1580,1581]],[[64862,64862],"mapped",[1587,1580,1609]],[[64863,64864],"mapped",[1587,1605,1581]],[[64865,64865],"mapped",[1587,1605,1580]],[[64866,64867],"mapped",[1587,1605,1605]],[[64868,64869],"mapped",[1589,1581,1581]],[[64870,64870],"mapped",[1589,1605,1605]],[[64871,64872],"mapped",[1588,1581,1605]],[[64873,64873],"mapped",[1588,1580,1610]],[[64874,64875],"mapped",[1588,1605,1582]],[[64876,64877],"mapped",[1588,1605,1605]],[[64878,64878],"mapped",[1590,1581,1609]],[[64879,64880],"mapped",[1590,1582,1605]],[[64881,64882],"mapped",[1591,1605,1581]],[[64883,64883],"mapped",[1591,1605,1605]],[[64884,64884],"mapped",[1591,1605,1610]],[[64885,64885],"mapped",[1593,1580,1605]],[[64886,64887],"mapped",[1593,1605,1605]],[[64888,64888],"mapped",[1593,1605,1609]],[[64889,64889],"mapped",[1594,1605,1605]],[[64890,64890],"mapped",[1594,1605,1610]],[[64891,64891],"mapped",[1594,1605,1609]],[[64892,64893],"mapped",[1601,1582,1605]],[[64894,64894],"mapped",[1602,1605,1581]],[[64895,64895],"mapped",[1602,1605,1605]],[[64896,64896],"mapped",[1604,1581,1605]],[[64897,64897],"mapped",[1604,1581,1610]],[[64898,64898],"mapped",[1604,1581,1609]],[[64899,64900],"mapped",[1604,1580,1580]],[[64901,64902],"mapped",[1604,1582,1605]],[[64903,64904],"mapped",[1604,1605,1581]],[[64905,64905],"mapped",[1605,1581,1580]],[[64906,64906],"mapped",[1605,1581,1605]],[[64907,64907],"mapped",[1605,1581,1610]],[[64908,64908],"mapped",[1605,1580,1581]],[[64909,64909],"mapped",[1605,1580,1605]],[[64910,64910],"mapped",[1605,1582,1580]],[[64911,64911],"mapped",[1605,1582,1605]],[[64912,64913],"disallowed"],[[64914,64914],"mapped",[1605,1580,1582]],[[64915,64915],"mapped",[1607,1605,1580]],[[64916,64916],"mapped",[1607,1605,1605]],[[64917,64917],"mapped",[1606,1581,1605]],[[64918,64918],"mapped",[1606,1581,1609]],[[64919,64920],"mapped",[1606,1580,1605]],[[64921,64921],"mapped",[1606,1580,1609]],[[64922,64922],"mapped",[1606,1605,1610]],[[64923,64923],"mapped",[1606,1605,1609]],[[64924,64925],"mapped",[1610,1605,1605]],[[64926,64926],"mapped",[1576,1582,1610]],[[64927,64927],"mapped",[1578,1580,1610]],[[64928,64928],"mapped",[1578,1580,1609]],[[64929,64929],"mapped",[1578,1582,1610]],[[64930,64930],"mapped",[1578,1582,1609]],[[64931,64931],"mapped",[1578,1605,1610]],[[64932,64932],"mapped",[1578,1605,1609]],[[64933,64933],"mapped",[1580,1605,1610]],[[64934,64934],"mapped",[1580,1581,1609]],[[64935,64935],"mapped",[1580,1605,1609]],[[64936,64936],"mapped",[1587,1582,1609]],[[64937,64937],"mapped",[1589,1581,1610]],[[64938,64938],"mapped",[1588,1581,1610]],[[64939,64939],"mapped",[1590,1581,1610]],[[64940,64940],"mapped",[1604,1580,1610]],[[64941,64941],"mapped",[1604,1605,1610]],[[64942,64942],"mapped",[1610,1581,1610]],[[64943,64943],"mapped",[1610,1580,1610]],[[64944,64944],"mapped",[1610,1605,1610]],[[64945,64945],"mapped",[1605,1605,1610]],[[64946,64946],"mapped",[1602,1605,1610]],[[64947,64947],"mapped",[1606,1581,1610]],[[64948,64948],"mapped",[1602,1605,1581]],[[64949,64949],"mapped",[1604,1581,1605]],[[64950,64950],"mapped",[1593,1605,1610]],[[64951,64951],"mapped",[1603,1605,1610]],[[64952,64952],"mapped",[1606,1580,1581]],[[64953,64953],"mapped",[1605,1582,1610]],[[64954,64954],"mapped",[1604,1580,1605]],[[64955,64955],"mapped",[1603,1605,1605]],[[64956,64956],"mapped",[1604,1580,1605]],[[64957,64957],"mapped",[1606,1580,1581]],[[64958,64958],"mapped",[1580,1581,1610]],[[64959,64959],"mapped",[1581,1580,1610]],[[64960,64960],"mapped",[1605,1580,1610]],[[64961,64961],"mapped",[1601,1605,1610]],[[64962,64962],"mapped",[1576,1581,1610]],[[64963,64963],"mapped",[1603,1605,1605]],[[64964,64964],"mapped",[1593,1580,1605]],[[64965,64965],"mapped",[1589,1605,1605]],[[64966,64966],"mapped",[1587,1582,1610]],[[64967,64967],"mapped",[1606,1580,1610]],[[64968,64975],"disallowed"],[[64976,65007],"disallowed"],[[65008,65008],"mapped",[1589,1604,1746]],[[65009,65009],"mapped",[1602,1604,1746]],[[65010,65010],"mapped",[1575,1604,1604,1607]],[[65011,65011],"mapped",[1575,1603,1576,1585]],[[65012,65012],"mapped",[1605,1581,1605,1583]],[[65013,65013],"mapped",[1589,1604,1593,1605]],[[65014,65014],"mapped",[1585,1587,1608,1604]],[[65015,65015],"mapped",[1593,1604,1610,1607]],[[65016,65016],"mapped",[1608,1587,1604,1605]],[[65017,65017],"mapped",[1589,1604,1609]],[[65018,65018],"disallowed_STD3_mapped",[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605]],[[65019,65019],"disallowed_STD3_mapped",[1580,1604,32,1580,1604,1575,1604,1607]],[[65020,65020],"mapped",[1585,1740,1575,1604]],[[65021,65021],"valid",[],"NV8"],[[65022,65023],"disallowed"],[[65024,65039],"ignored"],[[65040,65040],"disallowed_STD3_mapped",[44]],[[65041,65041],"mapped",[12289]],[[65042,65042],"disallowed"],[[65043,65043],"disallowed_STD3_mapped",[58]],[[65044,65044],"disallowed_STD3_mapped",[59]],[[65045,65045],"disallowed_STD3_mapped",[33]],[[65046,65046],"disallowed_STD3_mapped",[63]],[[65047,65047],"mapped",[12310]],[[65048,65048],"mapped",[12311]],[[65049,65049],"disallowed"],[[65050,65055],"disallowed"],[[65056,65059],"valid"],[[65060,65062],"valid"],[[65063,65069],"valid"],[[65070,65071],"valid"],[[65072,65072],"disallowed"],[[65073,65073],"mapped",[8212]],[[65074,65074],"mapped",[8211]],[[65075,65076],"disallowed_STD3_mapped",[95]],[[65077,65077],"disallowed_STD3_mapped",[40]],[[65078,65078],"disallowed_STD3_mapped",[41]],[[65079,65079],"disallowed_STD3_mapped",[123]],[[65080,65080],"disallowed_STD3_mapped",[125]],[[65081,65081],"mapped",[12308]],[[65082,65082],"mapped",[12309]],[[65083,65083],"mapped",[12304]],[[65084,65084],"mapped",[12305]],[[65085,65085],"mapped",[12298]],[[65086,65086],"mapped",[12299]],[[65087,65087],"mapped",[12296]],[[65088,65088],"mapped",[12297]],[[65089,65089],"mapped",[12300]],[[65090,65090],"mapped",[12301]],[[65091,65091],"mapped",[12302]],[[65092,65092],"mapped",[12303]],[[65093,65094],"valid",[],"NV8"],[[65095,65095],"disallowed_STD3_mapped",[91]],[[65096,65096],"disallowed_STD3_mapped",[93]],[[65097,65100],"disallowed_STD3_mapped",[32,773]],[[65101,65103],"disallowed_STD3_mapped",[95]],[[65104,65104],"disallowed_STD3_mapped",[44]],[[65105,65105],"mapped",[12289]],[[65106,65106],"disallowed"],[[65107,65107],"disallowed"],[[65108,65108],"disallowed_STD3_mapped",[59]],[[65109,65109],"disallowed_STD3_mapped",[58]],[[65110,65110],"disallowed_STD3_mapped",[63]],[[65111,65111],"disallowed_STD3_mapped",[33]],[[65112,65112],"mapped",[8212]],[[65113,65113],"disallowed_STD3_mapped",[40]],[[65114,65114],"disallowed_STD3_mapped",[41]],[[65115,65115],"disallowed_STD3_mapped",[123]],[[65116,65116],"disallowed_STD3_mapped",[125]],[[65117,65117],"mapped",[12308]],[[65118,65118],"mapped",[12309]],[[65119,65119],"disallowed_STD3_mapped",[35]],[[65120,65120],"disallowed_STD3_mapped",[38]],[[65121,65121],"disallowed_STD3_mapped",[42]],[[65122,65122],"disallowed_STD3_mapped",[43]],[[65123,65123],"mapped",[45]],[[65124,65124],"disallowed_STD3_mapped",[60]],[[65125,65125],"disallowed_STD3_mapped",[62]],[[65126,65126],"disallowed_STD3_mapped",[61]],[[65127,65127],"disallowed"],[[65128,65128],"disallowed_STD3_mapped",[92]],[[65129,65129],"disallowed_STD3_mapped",[36]],[[65130,65130],"disallowed_STD3_mapped",[37]],[[65131,65131],"disallowed_STD3_mapped",[64]],[[65132,65135],"disallowed"],[[65136,65136],"disallowed_STD3_mapped",[32,1611]],[[65137,65137],"mapped",[1600,1611]],[[65138,65138],"disallowed_STD3_mapped",[32,1612]],[[65139,65139],"valid"],[[65140,65140],"disallowed_STD3_mapped",[32,1613]],[[65141,65141],"disallowed"],[[65142,65142],"disallowed_STD3_mapped",[32,1614]],[[65143,65143],"mapped",[1600,1614]],[[65144,65144],"disallowed_STD3_mapped",[32,1615]],[[65145,65145],"mapped",[1600,1615]],[[65146,65146],"disallowed_STD3_mapped",[32,1616]],[[65147,65147],"mapped",[1600,1616]],[[65148,65148],"disallowed_STD3_mapped",[32,1617]],[[65149,65149],"mapped",[1600,1617]],[[65150,65150],"disallowed_STD3_mapped",[32,1618]],[[65151,65151],"mapped",[1600,1618]],[[65152,65152],"mapped",[1569]],[[65153,65154],"mapped",[1570]],[[65155,65156],"mapped",[1571]],[[65157,65158],"mapped",[1572]],[[65159,65160],"mapped",[1573]],[[65161,65164],"mapped",[1574]],[[65165,65166],"mapped",[1575]],[[65167,65170],"mapped",[1576]],[[65171,65172],"mapped",[1577]],[[65173,65176],"mapped",[1578]],[[65177,65180],"mapped",[1579]],[[65181,65184],"mapped",[1580]],[[65185,65188],"mapped",[1581]],[[65189,65192],"mapped",[1582]],[[65193,65194],"mapped",[1583]],[[65195,65196],"mapped",[1584]],[[65197,65198],"mapped",[1585]],[[65199,65200],"mapped",[1586]],[[65201,65204],"mapped",[1587]],[[65205,65208],"mapped",[1588]],[[65209,65212],"mapped",[1589]],[[65213,65216],"mapped",[1590]],[[65217,65220],"mapped",[1591]],[[65221,65224],"mapped",[1592]],[[65225,65228],"mapped",[1593]],[[65229,65232],"mapped",[1594]],[[65233,65236],"mapped",[1601]],[[65237,65240],"mapped",[1602]],[[65241,65244],"mapped",[1603]],[[65245,65248],"mapped",[1604]],[[65249,65252],"mapped",[1605]],[[65253,65256],"mapped",[1606]],[[65257,65260],"mapped",[1607]],[[65261,65262],"mapped",[1608]],[[65263,65264],"mapped",[1609]],[[65265,65268],"mapped",[1610]],[[65269,65270],"mapped",[1604,1570]],[[65271,65272],"mapped",[1604,1571]],[[65273,65274],"mapped",[1604,1573]],[[65275,65276],"mapped",[1604,1575]],[[65277,65278],"disallowed"],[[65279,65279],"ignored"],[[65280,65280],"disallowed"],[[65281,65281],"disallowed_STD3_mapped",[33]],[[65282,65282],"disallowed_STD3_mapped",[34]],[[65283,65283],"disallowed_STD3_mapped",[35]],[[65284,65284],"disallowed_STD3_mapped",[36]],[[65285,65285],"disallowed_STD3_mapped",[37]],[[65286,65286],"disallowed_STD3_mapped",[38]],[[65287,65287],"disallowed_STD3_mapped",[39]],[[65288,65288],"disallowed_STD3_mapped",[40]],[[65289,65289],"disallowed_STD3_mapped",[41]],[[65290,65290],"disallowed_STD3_mapped",[42]],[[65291,65291],"disallowed_STD3_mapped",[43]],[[65292,65292],"disallowed_STD3_mapped",[44]],[[65293,65293],"mapped",[45]],[[65294,65294],"mapped",[46]],[[65295,65295],"disallowed_STD3_mapped",[47]],[[65296,65296],"mapped",[48]],[[65297,65297],"mapped",[49]],[[65298,65298],"mapped",[50]],[[65299,65299],"mapped",[51]],[[65300,65300],"mapped",[52]],[[65301,65301],"mapped",[53]],[[65302,65302],"mapped",[54]],[[65303,65303],"mapped",[55]],[[65304,65304],"mapped",[56]],[[65305,65305],"mapped",[57]],[[65306,65306],"disallowed_STD3_mapped",[58]],[[65307,65307],"disallowed_STD3_mapped",[59]],[[65308,65308],"disallowed_STD3_mapped",[60]],[[65309,65309],"disallowed_STD3_mapped",[61]],[[65310,65310],"disallowed_STD3_mapped",[62]],[[65311,65311],"disallowed_STD3_mapped",[63]],[[65312,65312],"disallowed_STD3_mapped",[64]],[[65313,65313],"mapped",[97]],[[65314,65314],"mapped",[98]],[[65315,65315],"mapped",[99]],[[65316,65316],"mapped",[100]],[[65317,65317],"mapped",[101]],[[65318,65318],"mapped",[102]],[[65319,65319],"mapped",[103]],[[65320,65320],"mapped",[104]],[[65321,65321],"mapped",[105]],[[65322,65322],"mapped",[106]],[[65323,65323],"mapped",[107]],[[65324,65324],"mapped",[108]],[[65325,65325],"mapped",[109]],[[65326,65326],"mapped",[110]],[[65327,65327],"mapped",[111]],[[65328,65328],"mapped",[112]],[[65329,65329],"mapped",[113]],[[65330,65330],"mapped",[114]],[[65331,65331],"mapped",[115]],[[65332,65332],"mapped",[116]],[[65333,65333],"mapped",[117]],[[65334,65334],"mapped",[118]],[[65335,65335],"mapped",[119]],[[65336,65336],"mapped",[120]],[[65337,65337],"mapped",[121]],[[65338,65338],"mapped",[122]],[[65339,65339],"disallowed_STD3_mapped",[91]],[[65340,65340],"disallowed_STD3_mapped",[92]],[[65341,65341],"disallowed_STD3_mapped",[93]],[[65342,65342],"disallowed_STD3_mapped",[94]],[[65343,65343],"disallowed_STD3_mapped",[95]],[[65344,65344],"disallowed_STD3_mapped",[96]],[[65345,65345],"mapped",[97]],[[65346,65346],"mapped",[98]],[[65347,65347],"mapped",[99]],[[65348,65348],"mapped",[100]],[[65349,65349],"mapped",[101]],[[65350,65350],"mapped",[102]],[[65351,65351],"mapped",[103]],[[65352,65352],"mapped",[104]],[[65353,65353],"mapped",[105]],[[65354,65354],"mapped",[106]],[[65355,65355],"mapped",[107]],[[65356,65356],"mapped",[108]],[[65357,65357],"mapped",[109]],[[65358,65358],"mapped",[110]],[[65359,65359],"mapped",[111]],[[65360,65360],"mapped",[112]],[[65361,65361],"mapped",[113]],[[65362,65362],"mapped",[114]],[[65363,65363],"mapped",[115]],[[65364,65364],"mapped",[116]],[[65365,65365],"mapped",[117]],[[65366,65366],"mapped",[118]],[[65367,65367],"mapped",[119]],[[65368,65368],"mapped",[120]],[[65369,65369],"mapped",[121]],[[65370,65370],"mapped",[122]],[[65371,65371],"disallowed_STD3_mapped",[123]],[[65372,65372],"disallowed_STD3_mapped",[124]],[[65373,65373],"disallowed_STD3_mapped",[125]],[[65374,65374],"disallowed_STD3_mapped",[126]],[[65375,65375],"mapped",[10629]],[[65376,65376],"mapped",[10630]],[[65377,65377],"mapped",[46]],[[65378,65378],"mapped",[12300]],[[65379,65379],"mapped",[12301]],[[65380,65380],"mapped",[12289]],[[65381,65381],"mapped",[12539]],[[65382,65382],"mapped",[12530]],[[65383,65383],"mapped",[12449]],[[65384,65384],"mapped",[12451]],[[65385,65385],"mapped",[12453]],[[65386,65386],"mapped",[12455]],[[65387,65387],"mapped",[12457]],[[65388,65388],"mapped",[12515]],[[65389,65389],"mapped",[12517]],[[65390,65390],"mapped",[12519]],[[65391,65391],"mapped",[12483]],[[65392,65392],"mapped",[12540]],[[65393,65393],"mapped",[12450]],[[65394,65394],"mapped",[12452]],[[65395,65395],"mapped",[12454]],[[65396,65396],"mapped",[12456]],[[65397,65397],"mapped",[12458]],[[65398,65398],"mapped",[12459]],[[65399,65399],"mapped",[12461]],[[65400,65400],"mapped",[12463]],[[65401,65401],"mapped",[12465]],[[65402,65402],"mapped",[12467]],[[65403,65403],"mapped",[12469]],[[65404,65404],"mapped",[12471]],[[65405,65405],"mapped",[12473]],[[65406,65406],"mapped",[12475]],[[65407,65407],"mapped",[12477]],[[65408,65408],"mapped",[12479]],[[65409,65409],"mapped",[12481]],[[65410,65410],"mapped",[12484]],[[65411,65411],"mapped",[12486]],[[65412,65412],"mapped",[12488]],[[65413,65413],"mapped",[12490]],[[65414,65414],"mapped",[12491]],[[65415,65415],"mapped",[12492]],[[65416,65416],"mapped",[12493]],[[65417,65417],"mapped",[12494]],[[65418,65418],"mapped",[12495]],[[65419,65419],"mapped",[12498]],[[65420,65420],"mapped",[12501]],[[65421,65421],"mapped",[12504]],[[65422,65422],"mapped",[12507]],[[65423,65423],"mapped",[12510]],[[65424,65424],"mapped",[12511]],[[65425,65425],"mapped",[12512]],[[65426,65426],"mapped",[12513]],[[65427,65427],"mapped",[12514]],[[65428,65428],"mapped",[12516]],[[65429,65429],"mapped",[12518]],[[65430,65430],"mapped",[12520]],[[65431,65431],"mapped",[12521]],[[65432,65432],"mapped",[12522]],[[65433,65433],"mapped",[12523]],[[65434,65434],"mapped",[12524]],[[65435,65435],"mapped",[12525]],[[65436,65436],"mapped",[12527]],[[65437,65437],"mapped",[12531]],[[65438,65438],"mapped",[12441]],[[65439,65439],"mapped",[12442]],[[65440,65440],"disallowed"],[[65441,65441],"mapped",[4352]],[[65442,65442],"mapped",[4353]],[[65443,65443],"mapped",[4522]],[[65444,65444],"mapped",[4354]],[[65445,65445],"mapped",[4524]],[[65446,65446],"mapped",[4525]],[[65447,65447],"mapped",[4355]],[[65448,65448],"mapped",[4356]],[[65449,65449],"mapped",[4357]],[[65450,65450],"mapped",[4528]],[[65451,65451],"mapped",[4529]],[[65452,65452],"mapped",[4530]],[[65453,65453],"mapped",[4531]],[[65454,65454],"mapped",[4532]],[[65455,65455],"mapped",[4533]],[[65456,65456],"mapped",[4378]],[[65457,65457],"mapped",[4358]],[[65458,65458],"mapped",[4359]],[[65459,65459],"mapped",[4360]],[[65460,65460],"mapped",[4385]],[[65461,65461],"mapped",[4361]],[[65462,65462],"mapped",[4362]],[[65463,65463],"mapped",[4363]],[[65464,65464],"mapped",[4364]],[[65465,65465],"mapped",[4365]],[[65466,65466],"mapped",[4366]],[[65467,65467],"mapped",[4367]],[[65468,65468],"mapped",[4368]],[[65469,65469],"mapped",[4369]],[[65470,65470],"mapped",[4370]],[[65471,65473],"disallowed"],[[65474,65474],"mapped",[4449]],[[65475,65475],"mapped",[4450]],[[65476,65476],"mapped",[4451]],[[65477,65477],"mapped",[4452]],[[65478,65478],"mapped",[4453]],[[65479,65479],"mapped",[4454]],[[65480,65481],"disallowed"],[[65482,65482],"mapped",[4455]],[[65483,65483],"mapped",[4456]],[[65484,65484],"mapped",[4457]],[[65485,65485],"mapped",[4458]],[[65486,65486],"mapped",[4459]],[[65487,65487],"mapped",[4460]],[[65488,65489],"disallowed"],[[65490,65490],"mapped",[4461]],[[65491,65491],"mapped",[4462]],[[65492,65492],"mapped",[4463]],[[65493,65493],"mapped",[4464]],[[65494,65494],"mapped",[4465]],[[65495,65495],"mapped",[4466]],[[65496,65497],"disallowed"],[[65498,65498],"mapped",[4467]],[[65499,65499],"mapped",[4468]],[[65500,65500],"mapped",[4469]],[[65501,65503],"disallowed"],[[65504,65504],"mapped",[162]],[[65505,65505],"mapped",[163]],[[65506,65506],"mapped",[172]],[[65507,65507],"disallowed_STD3_mapped",[32,772]],[[65508,65508],"mapped",[166]],[[65509,65509],"mapped",[165]],[[65510,65510],"mapped",[8361]],[[65511,65511],"disallowed"],[[65512,65512],"mapped",[9474]],[[65513,65513],"mapped",[8592]],[[65514,65514],"mapped",[8593]],[[65515,65515],"mapped",[8594]],[[65516,65516],"mapped",[8595]],[[65517,65517],"mapped",[9632]],[[65518,65518],"mapped",[9675]],[[65519,65528],"disallowed"],[[65529,65531],"disallowed"],[[65532,65532],"disallowed"],[[65533,65533],"disallowed"],[[65534,65535],"disallowed"],[[65536,65547],"valid"],[[65548,65548],"disallowed"],[[65549,65574],"valid"],[[65575,65575],"disallowed"],[[65576,65594],"valid"],[[65595,65595],"disallowed"],[[65596,65597],"valid"],[[65598,65598],"disallowed"],[[65599,65613],"valid"],[[65614,65615],"disallowed"],[[65616,65629],"valid"],[[65630,65663],"disallowed"],[[65664,65786],"valid"],[[65787,65791],"disallowed"],[[65792,65794],"valid",[],"NV8"],[[65795,65798],"disallowed"],[[65799,65843],"valid",[],"NV8"],[[65844,65846],"disallowed"],[[65847,65855],"valid",[],"NV8"],[[65856,65930],"valid",[],"NV8"],[[65931,65932],"valid",[],"NV8"],[[65933,65935],"disallowed"],[[65936,65947],"valid",[],"NV8"],[[65948,65951],"disallowed"],[[65952,65952],"valid",[],"NV8"],[[65953,65999],"disallowed"],[[66000,66044],"valid",[],"NV8"],[[66045,66045],"valid"],[[66046,66175],"disallowed"],[[66176,66204],"valid"],[[66205,66207],"disallowed"],[[66208,66256],"valid"],[[66257,66271],"disallowed"],[[66272,66272],"valid"],[[66273,66299],"valid",[],"NV8"],[[66300,66303],"disallowed"],[[66304,66334],"valid"],[[66335,66335],"valid"],[[66336,66339],"valid",[],"NV8"],[[66340,66351],"disallowed"],[[66352,66368],"valid"],[[66369,66369],"valid",[],"NV8"],[[66370,66377],"valid"],[[66378,66378],"valid",[],"NV8"],[[66379,66383],"disallowed"],[[66384,66426],"valid"],[[66427,66431],"disallowed"],[[66432,66461],"valid"],[[66462,66462],"disallowed"],[[66463,66463],"valid",[],"NV8"],[[66464,66499],"valid"],[[66500,66503],"disallowed"],[[66504,66511],"valid"],[[66512,66517],"valid",[],"NV8"],[[66518,66559],"disallowed"],[[66560,66560],"mapped",[66600]],[[66561,66561],"mapped",[66601]],[[66562,66562],"mapped",[66602]],[[66563,66563],"mapped",[66603]],[[66564,66564],"mapped",[66604]],[[66565,66565],"mapped",[66605]],[[66566,66566],"mapped",[66606]],[[66567,66567],"mapped",[66607]],[[66568,66568],"mapped",[66608]],[[66569,66569],"mapped",[66609]],[[66570,66570],"mapped",[66610]],[[66571,66571],"mapped",[66611]],[[66572,66572],"mapped",[66612]],[[66573,66573],"mapped",[66613]],[[66574,66574],"mapped",[66614]],[[66575,66575],"mapped",[66615]],[[66576,66576],"mapped",[66616]],[[66577,66577],"mapped",[66617]],[[66578,66578],"mapped",[66618]],[[66579,66579],"mapped",[66619]],[[66580,66580],"mapped",[66620]],[[66581,66581],"mapped",[66621]],[[66582,66582],"mapped",[66622]],[[66583,66583],"mapped",[66623]],[[66584,66584],"mapped",[66624]],[[66585,66585],"mapped",[66625]],[[66586,66586],"mapped",[66626]],[[66587,66587],"mapped",[66627]],[[66588,66588],"mapped",[66628]],[[66589,66589],"mapped",[66629]],[[66590,66590],"mapped",[66630]],[[66591,66591],"mapped",[66631]],[[66592,66592],"mapped",[66632]],[[66593,66593],"mapped",[66633]],[[66594,66594],"mapped",[66634]],[[66595,66595],"mapped",[66635]],[[66596,66596],"mapped",[66636]],[[66597,66597],"mapped",[66637]],[[66598,66598],"mapped",[66638]],[[66599,66599],"mapped",[66639]],[[66600,66637],"valid"],[[66638,66717],"valid"],[[66718,66719],"disallowed"],[[66720,66729],"valid"],[[66730,66815],"disallowed"],[[66816,66855],"valid"],[[66856,66863],"disallowed"],[[66864,66915],"valid"],[[66916,66926],"disallowed"],[[66927,66927],"valid",[],"NV8"],[[66928,67071],"disallowed"],[[67072,67382],"valid"],[[67383,67391],"disallowed"],[[67392,67413],"valid"],[[67414,67423],"disallowed"],[[67424,67431],"valid"],[[67432,67583],"disallowed"],[[67584,67589],"valid"],[[67590,67591],"disallowed"],[[67592,67592],"valid"],[[67593,67593],"disallowed"],[[67594,67637],"valid"],[[67638,67638],"disallowed"],[[67639,67640],"valid"],[[67641,67643],"disallowed"],[[67644,67644],"valid"],[[67645,67646],"disallowed"],[[67647,67647],"valid"],[[67648,67669],"valid"],[[67670,67670],"disallowed"],[[67671,67679],"valid",[],"NV8"],[[67680,67702],"valid"],[[67703,67711],"valid",[],"NV8"],[[67712,67742],"valid"],[[67743,67750],"disallowed"],[[67751,67759],"valid",[],"NV8"],[[67760,67807],"disallowed"],[[67808,67826],"valid"],[[67827,67827],"disallowed"],[[67828,67829],"valid"],[[67830,67834],"disallowed"],[[67835,67839],"valid",[],"NV8"],[[67840,67861],"valid"],[[67862,67865],"valid",[],"NV8"],[[67866,67867],"valid",[],"NV8"],[[67868,67870],"disallowed"],[[67871,67871],"valid",[],"NV8"],[[67872,67897],"valid"],[[67898,67902],"disallowed"],[[67903,67903],"valid",[],"NV8"],[[67904,67967],"disallowed"],[[67968,68023],"valid"],[[68024,68027],"disallowed"],[[68028,68029],"valid",[],"NV8"],[[68030,68031],"valid"],[[68032,68047],"valid",[],"NV8"],[[68048,68049],"disallowed"],[[68050,68095],"valid",[],"NV8"],[[68096,68099],"valid"],[[68100,68100],"disallowed"],[[68101,68102],"valid"],[[68103,68107],"disallowed"],[[68108,68115],"valid"],[[68116,68116],"disallowed"],[[68117,68119],"valid"],[[68120,68120],"disallowed"],[[68121,68147],"valid"],[[68148,68151],"disallowed"],[[68152,68154],"valid"],[[68155,68158],"disallowed"],[[68159,68159],"valid"],[[68160,68167],"valid",[],"NV8"],[[68168,68175],"disallowed"],[[68176,68184],"valid",[],"NV8"],[[68185,68191],"disallowed"],[[68192,68220],"valid"],[[68221,68223],"valid",[],"NV8"],[[68224,68252],"valid"],[[68253,68255],"valid",[],"NV8"],[[68256,68287],"disallowed"],[[68288,68295],"valid"],[[68296,68296],"valid",[],"NV8"],[[68297,68326],"valid"],[[68327,68330],"disallowed"],[[68331,68342],"valid",[],"NV8"],[[68343,68351],"disallowed"],[[68352,68405],"valid"],[[68406,68408],"disallowed"],[[68409,68415],"valid",[],"NV8"],[[68416,68437],"valid"],[[68438,68439],"disallowed"],[[68440,68447],"valid",[],"NV8"],[[68448,68466],"valid"],[[68467,68471],"disallowed"],[[68472,68479],"valid",[],"NV8"],[[68480,68497],"valid"],[[68498,68504],"disallowed"],[[68505,68508],"valid",[],"NV8"],[[68509,68520],"disallowed"],[[68521,68527],"valid",[],"NV8"],[[68528,68607],"disallowed"],[[68608,68680],"valid"],[[68681,68735],"disallowed"],[[68736,68736],"mapped",[68800]],[[68737,68737],"mapped",[68801]],[[68738,68738],"mapped",[68802]],[[68739,68739],"mapped",[68803]],[[68740,68740],"mapped",[68804]],[[68741,68741],"mapped",[68805]],[[68742,68742],"mapped",[68806]],[[68743,68743],"mapped",[68807]],[[68744,68744],"mapped",[68808]],[[68745,68745],"mapped",[68809]],[[68746,68746],"mapped",[68810]],[[68747,68747],"mapped",[68811]],[[68748,68748],"mapped",[68812]],[[68749,68749],"mapped",[68813]],[[68750,68750],"mapped",[68814]],[[68751,68751],"mapped",[68815]],[[68752,68752],"mapped",[68816]],[[68753,68753],"mapped",[68817]],[[68754,68754],"mapped",[68818]],[[68755,68755],"mapped",[68819]],[[68756,68756],"mapped",[68820]],[[68757,68757],"mapped",[68821]],[[68758,68758],"mapped",[68822]],[[68759,68759],"mapped",[68823]],[[68760,68760],"mapped",[68824]],[[68761,68761],"mapped",[68825]],[[68762,68762],"mapped",[68826]],[[68763,68763],"mapped",[68827]],[[68764,68764],"mapped",[68828]],[[68765,68765],"mapped",[68829]],[[68766,68766],"mapped",[68830]],[[68767,68767],"mapped",[68831]],[[68768,68768],"mapped",[68832]],[[68769,68769],"mapped",[68833]],[[68770,68770],"mapped",[68834]],[[68771,68771],"mapped",[68835]],[[68772,68772],"mapped",[68836]],[[68773,68773],"mapped",[68837]],[[68774,68774],"mapped",[68838]],[[68775,68775],"mapped",[68839]],[[68776,68776],"mapped",[68840]],[[68777,68777],"mapped",[68841]],[[68778,68778],"mapped",[68842]],[[68779,68779],"mapped",[68843]],[[68780,68780],"mapped",[68844]],[[68781,68781],"mapped",[68845]],[[68782,68782],"mapped",[68846]],[[68783,68783],"mapped",[68847]],[[68784,68784],"mapped",[68848]],[[68785,68785],"mapped",[68849]],[[68786,68786],"mapped",[68850]],[[68787,68799],"disallowed"],[[68800,68850],"valid"],[[68851,68857],"disallowed"],[[68858,68863],"valid",[],"NV8"],[[68864,69215],"disallowed"],[[69216,69246],"valid",[],"NV8"],[[69247,69631],"disallowed"],[[69632,69702],"valid"],[[69703,69709],"valid",[],"NV8"],[[69710,69713],"disallowed"],[[69714,69733],"valid",[],"NV8"],[[69734,69743],"valid"],[[69744,69758],"disallowed"],[[69759,69759],"valid"],[[69760,69818],"valid"],[[69819,69820],"valid",[],"NV8"],[[69821,69821],"disallowed"],[[69822,69825],"valid",[],"NV8"],[[69826,69839],"disallowed"],[[69840,69864],"valid"],[[69865,69871],"disallowed"],[[69872,69881],"valid"],[[69882,69887],"disallowed"],[[69888,69940],"valid"],[[69941,69941],"disallowed"],[[69942,69951],"valid"],[[69952,69955],"valid",[],"NV8"],[[69956,69967],"disallowed"],[[69968,70003],"valid"],[[70004,70005],"valid",[],"NV8"],[[70006,70006],"valid"],[[70007,70015],"disallowed"],[[70016,70084],"valid"],[[70085,70088],"valid",[],"NV8"],[[70089,70089],"valid",[],"NV8"],[[70090,70092],"valid"],[[70093,70093],"valid",[],"NV8"],[[70094,70095],"disallowed"],[[70096,70105],"valid"],[[70106,70106],"valid"],[[70107,70107],"valid",[],"NV8"],[[70108,70108],"valid"],[[70109,70111],"valid",[],"NV8"],[[70112,70112],"disallowed"],[[70113,70132],"valid",[],"NV8"],[[70133,70143],"disallowed"],[[70144,70161],"valid"],[[70162,70162],"disallowed"],[[70163,70199],"valid"],[[70200,70205],"valid",[],"NV8"],[[70206,70271],"disallowed"],[[70272,70278],"valid"],[[70279,70279],"disallowed"],[[70280,70280],"valid"],[[70281,70281],"disallowed"],[[70282,70285],"valid"],[[70286,70286],"disallowed"],[[70287,70301],"valid"],[[70302,70302],"disallowed"],[[70303,70312],"valid"],[[70313,70313],"valid",[],"NV8"],[[70314,70319],"disallowed"],[[70320,70378],"valid"],[[70379,70383],"disallowed"],[[70384,70393],"valid"],[[70394,70399],"disallowed"],[[70400,70400],"valid"],[[70401,70403],"valid"],[[70404,70404],"disallowed"],[[70405,70412],"valid"],[[70413,70414],"disallowed"],[[70415,70416],"valid"],[[70417,70418],"disallowed"],[[70419,70440],"valid"],[[70441,70441],"disallowed"],[[70442,70448],"valid"],[[70449,70449],"disallowed"],[[70450,70451],"valid"],[[70452,70452],"disallowed"],[[70453,70457],"valid"],[[70458,70459],"disallowed"],[[70460,70468],"valid"],[[70469,70470],"disallowed"],[[70471,70472],"valid"],[[70473,70474],"disallowed"],[[70475,70477],"valid"],[[70478,70479],"disallowed"],[[70480,70480],"valid"],[[70481,70486],"disallowed"],[[70487,70487],"valid"],[[70488,70492],"disallowed"],[[70493,70499],"valid"],[[70500,70501],"disallowed"],[[70502,70508],"valid"],[[70509,70511],"disallowed"],[[70512,70516],"valid"],[[70517,70783],"disallowed"],[[70784,70853],"valid"],[[70854,70854],"valid",[],"NV8"],[[70855,70855],"valid"],[[70856,70863],"disallowed"],[[70864,70873],"valid"],[[70874,71039],"disallowed"],[[71040,71093],"valid"],[[71094,71095],"disallowed"],[[71096,71104],"valid"],[[71105,71113],"valid",[],"NV8"],[[71114,71127],"valid",[],"NV8"],[[71128,71133],"valid"],[[71134,71167],"disallowed"],[[71168,71232],"valid"],[[71233,71235],"valid",[],"NV8"],[[71236,71236],"valid"],[[71237,71247],"disallowed"],[[71248,71257],"valid"],[[71258,71295],"disallowed"],[[71296,71351],"valid"],[[71352,71359],"disallowed"],[[71360,71369],"valid"],[[71370,71423],"disallowed"],[[71424,71449],"valid"],[[71450,71452],"disallowed"],[[71453,71467],"valid"],[[71468,71471],"disallowed"],[[71472,71481],"valid"],[[71482,71487],"valid",[],"NV8"],[[71488,71839],"disallowed"],[[71840,71840],"mapped",[71872]],[[71841,71841],"mapped",[71873]],[[71842,71842],"mapped",[71874]],[[71843,71843],"mapped",[71875]],[[71844,71844],"mapped",[71876]],[[71845,71845],"mapped",[71877]],[[71846,71846],"mapped",[71878]],[[71847,71847],"mapped",[71879]],[[71848,71848],"mapped",[71880]],[[71849,71849],"mapped",[71881]],[[71850,71850],"mapped",[71882]],[[71851,71851],"mapped",[71883]],[[71852,71852],"mapped",[71884]],[[71853,71853],"mapped",[71885]],[[71854,71854],"mapped",[71886]],[[71855,71855],"mapped",[71887]],[[71856,71856],"mapped",[71888]],[[71857,71857],"mapped",[71889]],[[71858,71858],"mapped",[71890]],[[71859,71859],"mapped",[71891]],[[71860,71860],"mapped",[71892]],[[71861,71861],"mapped",[71893]],[[71862,71862],"mapped",[71894]],[[71863,71863],"mapped",[71895]],[[71864,71864],"mapped",[71896]],[[71865,71865],"mapped",[71897]],[[71866,71866],"mapped",[71898]],[[71867,71867],"mapped",[71899]],[[71868,71868],"mapped",[71900]],[[71869,71869],"mapped",[71901]],[[71870,71870],"mapped",[71902]],[[71871,71871],"mapped",[71903]],[[71872,71913],"valid"],[[71914,71922],"valid",[],"NV8"],[[71923,71934],"disallowed"],[[71935,71935],"valid"],[[71936,72383],"disallowed"],[[72384,72440],"valid"],[[72441,73727],"disallowed"],[[73728,74606],"valid"],[[74607,74648],"valid"],[[74649,74649],"valid"],[[74650,74751],"disallowed"],[[74752,74850],"valid",[],"NV8"],[[74851,74862],"valid",[],"NV8"],[[74863,74863],"disallowed"],[[74864,74867],"valid",[],"NV8"],[[74868,74868],"valid",[],"NV8"],[[74869,74879],"disallowed"],[[74880,75075],"valid"],[[75076,77823],"disallowed"],[[77824,78894],"valid"],[[78895,82943],"disallowed"],[[82944,83526],"valid"],[[83527,92159],"disallowed"],[[92160,92728],"valid"],[[92729,92735],"disallowed"],[[92736,92766],"valid"],[[92767,92767],"disallowed"],[[92768,92777],"valid"],[[92778,92781],"disallowed"],[[92782,92783],"valid",[],"NV8"],[[92784,92879],"disallowed"],[[92880,92909],"valid"],[[92910,92911],"disallowed"],[[92912,92916],"valid"],[[92917,92917],"valid",[],"NV8"],[[92918,92927],"disallowed"],[[92928,92982],"valid"],[[92983,92991],"valid",[],"NV8"],[[92992,92995],"valid"],[[92996,92997],"valid",[],"NV8"],[[92998,93007],"disallowed"],[[93008,93017],"valid"],[[93018,93018],"disallowed"],[[93019,93025],"valid",[],"NV8"],[[93026,93026],"disallowed"],[[93027,93047],"valid"],[[93048,93052],"disallowed"],[[93053,93071],"valid"],[[93072,93951],"disallowed"],[[93952,94020],"valid"],[[94021,94031],"disallowed"],[[94032,94078],"valid"],[[94079,94094],"disallowed"],[[94095,94111],"valid"],[[94112,110591],"disallowed"],[[110592,110593],"valid"],[[110594,113663],"disallowed"],[[113664,113770],"valid"],[[113771,113775],"disallowed"],[[113776,113788],"valid"],[[113789,113791],"disallowed"],[[113792,113800],"valid"],[[113801,113807],"disallowed"],[[113808,113817],"valid"],[[113818,113819],"disallowed"],[[113820,113820],"valid",[],"NV8"],[[113821,113822],"valid"],[[113823,113823],"valid",[],"NV8"],[[113824,113827],"ignored"],[[113828,118783],"disallowed"],[[118784,119029],"valid",[],"NV8"],[[119030,119039],"disallowed"],[[119040,119078],"valid",[],"NV8"],[[119079,119080],"disallowed"],[[119081,119081],"valid",[],"NV8"],[[119082,119133],"valid",[],"NV8"],[[119134,119134],"mapped",[119127,119141]],[[119135,119135],"mapped",[119128,119141]],[[119136,119136],"mapped",[119128,119141,119150]],[[119137,119137],"mapped",[119128,119141,119151]],[[119138,119138],"mapped",[119128,119141,119152]],[[119139,119139],"mapped",[119128,119141,119153]],[[119140,119140],"mapped",[119128,119141,119154]],[[119141,119154],"valid",[],"NV8"],[[119155,119162],"disallowed"],[[119163,119226],"valid",[],"NV8"],[[119227,119227],"mapped",[119225,119141]],[[119228,119228],"mapped",[119226,119141]],[[119229,119229],"mapped",[119225,119141,119150]],[[119230,119230],"mapped",[119226,119141,119150]],[[119231,119231],"mapped",[119225,119141,119151]],[[119232,119232],"mapped",[119226,119141,119151]],[[119233,119261],"valid",[],"NV8"],[[119262,119272],"valid",[],"NV8"],[[119273,119295],"disallowed"],[[119296,119365],"valid",[],"NV8"],[[119366,119551],"disallowed"],[[119552,119638],"valid",[],"NV8"],[[119639,119647],"disallowed"],[[119648,119665],"valid",[],"NV8"],[[119666,119807],"disallowed"],[[119808,119808],"mapped",[97]],[[119809,119809],"mapped",[98]],[[119810,119810],"mapped",[99]],[[119811,119811],"mapped",[100]],[[119812,119812],"mapped",[101]],[[119813,119813],"mapped",[102]],[[119814,119814],"mapped",[103]],[[119815,119815],"mapped",[104]],[[119816,119816],"mapped",[105]],[[119817,119817],"mapped",[106]],[[119818,119818],"mapped",[107]],[[119819,119819],"mapped",[108]],[[119820,119820],"mapped",[109]],[[119821,119821],"mapped",[110]],[[119822,119822],"mapped",[111]],[[119823,119823],"mapped",[112]],[[119824,119824],"mapped",[113]],[[119825,119825],"mapped",[114]],[[119826,119826],"mapped",[115]],[[119827,119827],"mapped",[116]],[[119828,119828],"mapped",[117]],[[119829,119829],"mapped",[118]],[[119830,119830],"mapped",[119]],[[119831,119831],"mapped",[120]],[[119832,119832],"mapped",[121]],[[119833,119833],"mapped",[122]],[[119834,119834],"mapped",[97]],[[119835,119835],"mapped",[98]],[[119836,119836],"mapped",[99]],[[119837,119837],"mapped",[100]],[[119838,119838],"mapped",[101]],[[119839,119839],"mapped",[102]],[[119840,119840],"mapped",[103]],[[119841,119841],"mapped",[104]],[[119842,119842],"mapped",[105]],[[119843,119843],"mapped",[106]],[[119844,119844],"mapped",[107]],[[119845,119845],"mapped",[108]],[[119846,119846],"mapped",[109]],[[119847,119847],"mapped",[110]],[[119848,119848],"mapped",[111]],[[119849,119849],"mapped",[112]],[[119850,119850],"mapped",[113]],[[119851,119851],"mapped",[114]],[[119852,119852],"mapped",[115]],[[119853,119853],"mapped",[116]],[[119854,119854],"mapped",[117]],[[119855,119855],"mapped",[118]],[[119856,119856],"mapped",[119]],[[119857,119857],"mapped",[120]],[[119858,119858],"mapped",[121]],[[119859,119859],"mapped",[122]],[[119860,119860],"mapped",[97]],[[119861,119861],"mapped",[98]],[[119862,119862],"mapped",[99]],[[119863,119863],"mapped",[100]],[[119864,119864],"mapped",[101]],[[119865,119865],"mapped",[102]],[[119866,119866],"mapped",[103]],[[119867,119867],"mapped",[104]],[[119868,119868],"mapped",[105]],[[119869,119869],"mapped",[106]],[[119870,119870],"mapped",[107]],[[119871,119871],"mapped",[108]],[[119872,119872],"mapped",[109]],[[119873,119873],"mapped",[110]],[[119874,119874],"mapped",[111]],[[119875,119875],"mapped",[112]],[[119876,119876],"mapped",[113]],[[119877,119877],"mapped",[114]],[[119878,119878],"mapped",[115]],[[119879,119879],"mapped",[116]],[[119880,119880],"mapped",[117]],[[119881,119881],"mapped",[118]],[[119882,119882],"mapped",[119]],[[119883,119883],"mapped",[120]],[[119884,119884],"mapped",[121]],[[119885,119885],"mapped",[122]],[[119886,119886],"mapped",[97]],[[119887,119887],"mapped",[98]],[[119888,119888],"mapped",[99]],[[119889,119889],"mapped",[100]],[[119890,119890],"mapped",[101]],[[119891,119891],"mapped",[102]],[[119892,119892],"mapped",[103]],[[119893,119893],"disallowed"],[[119894,119894],"mapped",[105]],[[119895,119895],"mapped",[106]],[[119896,119896],"mapped",[107]],[[119897,119897],"mapped",[108]],[[119898,119898],"mapped",[109]],[[119899,119899],"mapped",[110]],[[119900,119900],"mapped",[111]],[[119901,119901],"mapped",[112]],[[119902,119902],"mapped",[113]],[[119903,119903],"mapped",[114]],[[119904,119904],"mapped",[115]],[[119905,119905],"mapped",[116]],[[119906,119906],"mapped",[117]],[[119907,119907],"mapped",[118]],[[119908,119908],"mapped",[119]],[[119909,119909],"mapped",[120]],[[119910,119910],"mapped",[121]],[[119911,119911],"mapped",[122]],[[119912,119912],"mapped",[97]],[[119913,119913],"mapped",[98]],[[119914,119914],"mapped",[99]],[[119915,119915],"mapped",[100]],[[119916,119916],"mapped",[101]],[[119917,119917],"mapped",[102]],[[119918,119918],"mapped",[103]],[[119919,119919],"mapped",[104]],[[119920,119920],"mapped",[105]],[[119921,119921],"mapped",[106]],[[119922,119922],"mapped",[107]],[[119923,119923],"mapped",[108]],[[119924,119924],"mapped",[109]],[[119925,119925],"mapped",[110]],[[119926,119926],"mapped",[111]],[[119927,119927],"mapped",[112]],[[119928,119928],"mapped",[113]],[[119929,119929],"mapped",[114]],[[119930,119930],"mapped",[115]],[[119931,119931],"mapped",[116]],[[119932,119932],"mapped",[117]],[[119933,119933],"mapped",[118]],[[119934,119934],"mapped",[119]],[[119935,119935],"mapped",[120]],[[119936,119936],"mapped",[121]],[[119937,119937],"mapped",[122]],[[119938,119938],"mapped",[97]],[[119939,119939],"mapped",[98]],[[119940,119940],"mapped",[99]],[[119941,119941],"mapped",[100]],[[119942,119942],"mapped",[101]],[[119943,119943],"mapped",[102]],[[119944,119944],"mapped",[103]],[[119945,119945],"mapped",[104]],[[119946,119946],"mapped",[105]],[[119947,119947],"mapped",[106]],[[119948,119948],"mapped",[107]],[[119949,119949],"mapped",[108]],[[119950,119950],"mapped",[109]],[[119951,119951],"mapped",[110]],[[119952,119952],"mapped",[111]],[[119953,119953],"mapped",[112]],[[119954,119954],"mapped",[113]],[[119955,119955],"mapped",[114]],[[119956,119956],"mapped",[115]],[[119957,119957],"mapped",[116]],[[119958,119958],"mapped",[117]],[[119959,119959],"mapped",[118]],[[119960,119960],"mapped",[119]],[[119961,119961],"mapped",[120]],[[119962,119962],"mapped",[121]],[[119963,119963],"mapped",[122]],[[119964,119964],"mapped",[97]],[[119965,119965],"disallowed"],[[119966,119966],"mapped",[99]],[[119967,119967],"mapped",[100]],[[119968,119969],"disallowed"],[[119970,119970],"mapped",[103]],[[119971,119972],"disallowed"],[[119973,119973],"mapped",[106]],[[119974,119974],"mapped",[107]],[[119975,119976],"disallowed"],[[119977,119977],"mapped",[110]],[[119978,119978],"mapped",[111]],[[119979,119979],"mapped",[112]],[[119980,119980],"mapped",[113]],[[119981,119981],"disallowed"],[[119982,119982],"mapped",[115]],[[119983,119983],"mapped",[116]],[[119984,119984],"mapped",[117]],[[119985,119985],"mapped",[118]],[[119986,119986],"mapped",[119]],[[119987,119987],"mapped",[120]],[[119988,119988],"mapped",[121]],[[119989,119989],"mapped",[122]],[[119990,119990],"mapped",[97]],[[119991,119991],"mapped",[98]],[[119992,119992],"mapped",[99]],[[119993,119993],"mapped",[100]],[[119994,119994],"disallowed"],[[119995,119995],"mapped",[102]],[[119996,119996],"disallowed"],[[119997,119997],"mapped",[104]],[[119998,119998],"mapped",[105]],[[119999,119999],"mapped",[106]],[[120000,120000],"mapped",[107]],[[120001,120001],"mapped",[108]],[[120002,120002],"mapped",[109]],[[120003,120003],"mapped",[110]],[[120004,120004],"disallowed"],[[120005,120005],"mapped",[112]],[[120006,120006],"mapped",[113]],[[120007,120007],"mapped",[114]],[[120008,120008],"mapped",[115]],[[120009,120009],"mapped",[116]],[[120010,120010],"mapped",[117]],[[120011,120011],"mapped",[118]],[[120012,120012],"mapped",[119]],[[120013,120013],"mapped",[120]],[[120014,120014],"mapped",[121]],[[120015,120015],"mapped",[122]],[[120016,120016],"mapped",[97]],[[120017,120017],"mapped",[98]],[[120018,120018],"mapped",[99]],[[120019,120019],"mapped",[100]],[[120020,120020],"mapped",[101]],[[120021,120021],"mapped",[102]],[[120022,120022],"mapped",[103]],[[120023,120023],"mapped",[104]],[[120024,120024],"mapped",[105]],[[120025,120025],"mapped",[106]],[[120026,120026],"mapped",[107]],[[120027,120027],"mapped",[108]],[[120028,120028],"mapped",[109]],[[120029,120029],"mapped",[110]],[[120030,120030],"mapped",[111]],[[120031,120031],"mapped",[112]],[[120032,120032],"mapped",[113]],[[120033,120033],"mapped",[114]],[[120034,120034],"mapped",[115]],[[120035,120035],"mapped",[116]],[[120036,120036],"mapped",[117]],[[120037,120037],"mapped",[118]],[[120038,120038],"mapped",[119]],[[120039,120039],"mapped",[120]],[[120040,120040],"mapped",[121]],[[120041,120041],"mapped",[122]],[[120042,120042],"mapped",[97]],[[120043,120043],"mapped",[98]],[[120044,120044],"mapped",[99]],[[120045,120045],"mapped",[100]],[[120046,120046],"mapped",[101]],[[120047,120047],"mapped",[102]],[[120048,120048],"mapped",[103]],[[120049,120049],"mapped",[104]],[[120050,120050],"mapped",[105]],[[120051,120051],"mapped",[106]],[[120052,120052],"mapped",[107]],[[120053,120053],"mapped",[108]],[[120054,120054],"mapped",[109]],[[120055,120055],"mapped",[110]],[[120056,120056],"mapped",[111]],[[120057,120057],"mapped",[112]],[[120058,120058],"mapped",[113]],[[120059,120059],"mapped",[114]],[[120060,120060],"mapped",[115]],[[120061,120061],"mapped",[116]],[[120062,120062],"mapped",[117]],[[120063,120063],"mapped",[118]],[[120064,120064],"mapped",[119]],[[120065,120065],"mapped",[120]],[[120066,120066],"mapped",[121]],[[120067,120067],"mapped",[122]],[[120068,120068],"mapped",[97]],[[120069,120069],"mapped",[98]],[[120070,120070],"disallowed"],[[120071,120071],"mapped",[100]],[[120072,120072],"mapped",[101]],[[120073,120073],"mapped",[102]],[[120074,120074],"mapped",[103]],[[120075,120076],"disallowed"],[[120077,120077],"mapped",[106]],[[120078,120078],"mapped",[107]],[[120079,120079],"mapped",[108]],[[120080,120080],"mapped",[109]],[[120081,120081],"mapped",[110]],[[120082,120082],"mapped",[111]],[[120083,120083],"mapped",[112]],[[120084,120084],"mapped",[113]],[[120085,120085],"disallowed"],[[120086,120086],"mapped",[115]],[[120087,120087],"mapped",[116]],[[120088,120088],"mapped",[117]],[[120089,120089],"mapped",[118]],[[120090,120090],"mapped",[119]],[[120091,120091],"mapped",[120]],[[120092,120092],"mapped",[121]],[[120093,120093],"disallowed"],[[120094,120094],"mapped",[97]],[[120095,120095],"mapped",[98]],[[120096,120096],"mapped",[99]],[[120097,120097],"mapped",[100]],[[120098,120098],"mapped",[101]],[[120099,120099],"mapped",[102]],[[120100,120100],"mapped",[103]],[[120101,120101],"mapped",[104]],[[120102,120102],"mapped",[105]],[[120103,120103],"mapped",[106]],[[120104,120104],"mapped",[107]],[[120105,120105],"mapped",[108]],[[120106,120106],"mapped",[109]],[[120107,120107],"mapped",[110]],[[120108,120108],"mapped",[111]],[[120109,120109],"mapped",[112]],[[120110,120110],"mapped",[113]],[[120111,120111],"mapped",[114]],[[120112,120112],"mapped",[115]],[[120113,120113],"mapped",[116]],[[120114,120114],"mapped",[117]],[[120115,120115],"mapped",[118]],[[120116,120116],"mapped",[119]],[[120117,120117],"mapped",[120]],[[120118,120118],"mapped",[121]],[[120119,120119],"mapped",[122]],[[120120,120120],"mapped",[97]],[[120121,120121],"mapped",[98]],[[120122,120122],"disallowed"],[[120123,120123],"mapped",[100]],[[120124,120124],"mapped",[101]],[[120125,120125],"mapped",[102]],[[120126,120126],"mapped",[103]],[[120127,120127],"disallowed"],[[120128,120128],"mapped",[105]],[[120129,120129],"mapped",[106]],[[120130,120130],"mapped",[107]],[[120131,120131],"mapped",[108]],[[120132,120132],"mapped",[109]],[[120133,120133],"disallowed"],[[120134,120134],"mapped",[111]],[[120135,120137],"disallowed"],[[120138,120138],"mapped",[115]],[[120139,120139],"mapped",[116]],[[120140,120140],"mapped",[117]],[[120141,120141],"mapped",[118]],[[120142,120142],"mapped",[119]],[[120143,120143],"mapped",[120]],[[120144,120144],"mapped",[121]],[[120145,120145],"disallowed"],[[120146,120146],"mapped",[97]],[[120147,120147],"mapped",[98]],[[120148,120148],"mapped",[99]],[[120149,120149],"mapped",[100]],[[120150,120150],"mapped",[101]],[[120151,120151],"mapped",[102]],[[120152,120152],"mapped",[103]],[[120153,120153],"mapped",[104]],[[120154,120154],"mapped",[105]],[[120155,120155],"mapped",[106]],[[120156,120156],"mapped",[107]],[[120157,120157],"mapped",[108]],[[120158,120158],"mapped",[109]],[[120159,120159],"mapped",[110]],[[120160,120160],"mapped",[111]],[[120161,120161],"mapped",[112]],[[120162,120162],"mapped",[113]],[[120163,120163],"mapped",[114]],[[120164,120164],"mapped",[115]],[[120165,120165],"mapped",[116]],[[120166,120166],"mapped",[117]],[[120167,120167],"mapped",[118]],[[120168,120168],"mapped",[119]],[[120169,120169],"mapped",[120]],[[120170,120170],"mapped",[121]],[[120171,120171],"mapped",[122]],[[120172,120172],"mapped",[97]],[[120173,120173],"mapped",[98]],[[120174,120174],"mapped",[99]],[[120175,120175],"mapped",[100]],[[120176,120176],"mapped",[101]],[[120177,120177],"mapped",[102]],[[120178,120178],"mapped",[103]],[[120179,120179],"mapped",[104]],[[120180,120180],"mapped",[105]],[[120181,120181],"mapped",[106]],[[120182,120182],"mapped",[107]],[[120183,120183],"mapped",[108]],[[120184,120184],"mapped",[109]],[[120185,120185],"mapped",[110]],[[120186,120186],"mapped",[111]],[[120187,120187],"mapped",[112]],[[120188,120188],"mapped",[113]],[[120189,120189],"mapped",[114]],[[120190,120190],"mapped",[115]],[[120191,120191],"mapped",[116]],[[120192,120192],"mapped",[117]],[[120193,120193],"mapped",[118]],[[120194,120194],"mapped",[119]],[[120195,120195],"mapped",[120]],[[120196,120196],"mapped",[121]],[[120197,120197],"mapped",[122]],[[120198,120198],"mapped",[97]],[[120199,120199],"mapped",[98]],[[120200,120200],"mapped",[99]],[[120201,120201],"mapped",[100]],[[120202,120202],"mapped",[101]],[[120203,120203],"mapped",[102]],[[120204,120204],"mapped",[103]],[[120205,120205],"mapped",[104]],[[120206,120206],"mapped",[105]],[[120207,120207],"mapped",[106]],[[120208,120208],"mapped",[107]],[[120209,120209],"mapped",[108]],[[120210,120210],"mapped",[109]],[[120211,120211],"mapped",[110]],[[120212,120212],"mapped",[111]],[[120213,120213],"mapped",[112]],[[120214,120214],"mapped",[113]],[[120215,120215],"mapped",[114]],[[120216,120216],"mapped",[115]],[[120217,120217],"mapped",[116]],[[120218,120218],"mapped",[117]],[[120219,120219],"mapped",[118]],[[120220,120220],"mapped",[119]],[[120221,120221],"mapped",[120]],[[120222,120222],"mapped",[121]],[[120223,120223],"mapped",[122]],[[120224,120224],"mapped",[97]],[[120225,120225],"mapped",[98]],[[120226,120226],"mapped",[99]],[[120227,120227],"mapped",[100]],[[120228,120228],"mapped",[101]],[[120229,120229],"mapped",[102]],[[120230,120230],"mapped",[103]],[[120231,120231],"mapped",[104]],[[120232,120232],"mapped",[105]],[[120233,120233],"mapped",[106]],[[120234,120234],"mapped",[107]],[[120235,120235],"mapped",[108]],[[120236,120236],"mapped",[109]],[[120237,120237],"mapped",[110]],[[120238,120238],"mapped",[111]],[[120239,120239],"mapped",[112]],[[120240,120240],"mapped",[113]],[[120241,120241],"mapped",[114]],[[120242,120242],"mapped",[115]],[[120243,120243],"mapped",[116]],[[120244,120244],"mapped",[117]],[[120245,120245],"mapped",[118]],[[120246,120246],"mapped",[119]],[[120247,120247],"mapped",[120]],[[120248,120248],"mapped",[121]],[[120249,120249],"mapped",[122]],[[120250,120250],"mapped",[97]],[[120251,120251],"mapped",[98]],[[120252,120252],"mapped",[99]],[[120253,120253],"mapped",[100]],[[120254,120254],"mapped",[101]],[[120255,120255],"mapped",[102]],[[120256,120256],"mapped",[103]],[[120257,120257],"mapped",[104]],[[120258,120258],"mapped",[105]],[[120259,120259],"mapped",[106]],[[120260,120260],"mapped",[107]],[[120261,120261],"mapped",[108]],[[120262,120262],"mapped",[109]],[[120263,120263],"mapped",[110]],[[120264,120264],"mapped",[111]],[[120265,120265],"mapped",[112]],[[120266,120266],"mapped",[113]],[[120267,120267],"mapped",[114]],[[120268,120268],"mapped",[115]],[[120269,120269],"mapped",[116]],[[120270,120270],"mapped",[117]],[[120271,120271],"mapped",[118]],[[120272,120272],"mapped",[119]],[[120273,120273],"mapped",[120]],[[120274,120274],"mapped",[121]],[[120275,120275],"mapped",[122]],[[120276,120276],"mapped",[97]],[[120277,120277],"mapped",[98]],[[120278,120278],"mapped",[99]],[[120279,120279],"mapped",[100]],[[120280,120280],"mapped",[101]],[[120281,120281],"mapped",[102]],[[120282,120282],"mapped",[103]],[[120283,120283],"mapped",[104]],[[120284,120284],"mapped",[105]],[[120285,120285],"mapped",[106]],[[120286,120286],"mapped",[107]],[[120287,120287],"mapped",[108]],[[120288,120288],"mapped",[109]],[[120289,120289],"mapped",[110]],[[120290,120290],"mapped",[111]],[[120291,120291],"mapped",[112]],[[120292,120292],"mapped",[113]],[[120293,120293],"mapped",[114]],[[120294,120294],"mapped",[115]],[[120295,120295],"mapped",[116]],[[120296,120296],"mapped",[117]],[[120297,120297],"mapped",[118]],[[120298,120298],"mapped",[119]],[[120299,120299],"mapped",[120]],[[120300,120300],"mapped",[121]],[[120301,120301],"mapped",[122]],[[120302,120302],"mapped",[97]],[[120303,120303],"mapped",[98]],[[120304,120304],"mapped",[99]],[[120305,120305],"mapped",[100]],[[120306,120306],"mapped",[101]],[[120307,120307],"mapped",[102]],[[120308,120308],"mapped",[103]],[[120309,120309],"mapped",[104]],[[120310,120310],"mapped",[105]],[[120311,120311],"mapped",[106]],[[120312,120312],"mapped",[107]],[[120313,120313],"mapped",[108]],[[120314,120314],"mapped",[109]],[[120315,120315],"mapped",[110]],[[120316,120316],"mapped",[111]],[[120317,120317],"mapped",[112]],[[120318,120318],"mapped",[113]],[[120319,120319],"mapped",[114]],[[120320,120320],"mapped",[115]],[[120321,120321],"mapped",[116]],[[120322,120322],"mapped",[117]],[[120323,120323],"mapped",[118]],[[120324,120324],"mapped",[119]],[[120325,120325],"mapped",[120]],[[120326,120326],"mapped",[121]],[[120327,120327],"mapped",[122]],[[120328,120328],"mapped",[97]],[[120329,120329],"mapped",[98]],[[120330,120330],"mapped",[99]],[[120331,120331],"mapped",[100]],[[120332,120332],"mapped",[101]],[[120333,120333],"mapped",[102]],[[120334,120334],"mapped",[103]],[[120335,120335],"mapped",[104]],[[120336,120336],"mapped",[105]],[[120337,120337],"mapped",[106]],[[120338,120338],"mapped",[107]],[[120339,120339],"mapped",[108]],[[120340,120340],"mapped",[109]],[[120341,120341],"mapped",[110]],[[120342,120342],"mapped",[111]],[[120343,120343],"mapped",[112]],[[120344,120344],"mapped",[113]],[[120345,120345],"mapped",[114]],[[120346,120346],"mapped",[115]],[[120347,120347],"mapped",[116]],[[120348,120348],"mapped",[117]],[[120349,120349],"mapped",[118]],[[120350,120350],"mapped",[119]],[[120351,120351],"mapped",[120]],[[120352,120352],"mapped",[121]],[[120353,120353],"mapped",[122]],[[120354,120354],"mapped",[97]],[[120355,120355],"mapped",[98]],[[120356,120356],"mapped",[99]],[[120357,120357],"mapped",[100]],[[120358,120358],"mapped",[101]],[[120359,120359],"mapped",[102]],[[120360,120360],"mapped",[103]],[[120361,120361],"mapped",[104]],[[120362,120362],"mapped",[105]],[[120363,120363],"mapped",[106]],[[120364,120364],"mapped",[107]],[[120365,120365],"mapped",[108]],[[120366,120366],"mapped",[109]],[[120367,120367],"mapped",[110]],[[120368,120368],"mapped",[111]],[[120369,120369],"mapped",[112]],[[120370,120370],"mapped",[113]],[[120371,120371],"mapped",[114]],[[120372,120372],"mapped",[115]],[[120373,120373],"mapped",[116]],[[120374,120374],"mapped",[117]],[[120375,120375],"mapped",[118]],[[120376,120376],"mapped",[119]],[[120377,120377],"mapped",[120]],[[120378,120378],"mapped",[121]],[[120379,120379],"mapped",[122]],[[120380,120380],"mapped",[97]],[[120381,120381],"mapped",[98]],[[120382,120382],"mapped",[99]],[[120383,120383],"mapped",[100]],[[120384,120384],"mapped",[101]],[[120385,120385],"mapped",[102]],[[120386,120386],"mapped",[103]],[[120387,120387],"mapped",[104]],[[120388,120388],"mapped",[105]],[[120389,120389],"mapped",[106]],[[120390,120390],"mapped",[107]],[[120391,120391],"mapped",[108]],[[120392,120392],"mapped",[109]],[[120393,120393],"mapped",[110]],[[120394,120394],"mapped",[111]],[[120395,120395],"mapped",[112]],[[120396,120396],"mapped",[113]],[[120397,120397],"mapped",[114]],[[120398,120398],"mapped",[115]],[[120399,120399],"mapped",[116]],[[120400,120400],"mapped",[117]],[[120401,120401],"mapped",[118]],[[120402,120402],"mapped",[119]],[[120403,120403],"mapped",[120]],[[120404,120404],"mapped",[121]],[[120405,120405],"mapped",[122]],[[120406,120406],"mapped",[97]],[[120407,120407],"mapped",[98]],[[120408,120408],"mapped",[99]],[[120409,120409],"mapped",[100]],[[120410,120410],"mapped",[101]],[[120411,120411],"mapped",[102]],[[120412,120412],"mapped",[103]],[[120413,120413],"mapped",[104]],[[120414,120414],"mapped",[105]],[[120415,120415],"mapped",[106]],[[120416,120416],"mapped",[107]],[[120417,120417],"mapped",[108]],[[120418,120418],"mapped",[109]],[[120419,120419],"mapped",[110]],[[120420,120420],"mapped",[111]],[[120421,120421],"mapped",[112]],[[120422,120422],"mapped",[113]],[[120423,120423],"mapped",[114]],[[120424,120424],"mapped",[115]],[[120425,120425],"mapped",[116]],[[120426,120426],"mapped",[117]],[[120427,120427],"mapped",[118]],[[120428,120428],"mapped",[119]],[[120429,120429],"mapped",[120]],[[120430,120430],"mapped",[121]],[[120431,120431],"mapped",[122]],[[120432,120432],"mapped",[97]],[[120433,120433],"mapped",[98]],[[120434,120434],"mapped",[99]],[[120435,120435],"mapped",[100]],[[120436,120436],"mapped",[101]],[[120437,120437],"mapped",[102]],[[120438,120438],"mapped",[103]],[[120439,120439],"mapped",[104]],[[120440,120440],"mapped",[105]],[[120441,120441],"mapped",[106]],[[120442,120442],"mapped",[107]],[[120443,120443],"mapped",[108]],[[120444,120444],"mapped",[109]],[[120445,120445],"mapped",[110]],[[120446,120446],"mapped",[111]],[[120447,120447],"mapped",[112]],[[120448,120448],"mapped",[113]],[[120449,120449],"mapped",[114]],[[120450,120450],"mapped",[115]],[[120451,120451],"mapped",[116]],[[120452,120452],"mapped",[117]],[[120453,120453],"mapped",[118]],[[120454,120454],"mapped",[119]],[[120455,120455],"mapped",[120]],[[120456,120456],"mapped",[121]],[[120457,120457],"mapped",[122]],[[120458,120458],"mapped",[97]],[[120459,120459],"mapped",[98]],[[120460,120460],"mapped",[99]],[[120461,120461],"mapped",[100]],[[120462,120462],"mapped",[101]],[[120463,120463],"mapped",[102]],[[120464,120464],"mapped",[103]],[[120465,120465],"mapped",[104]],[[120466,120466],"mapped",[105]],[[120467,120467],"mapped",[106]],[[120468,120468],"mapped",[107]],[[120469,120469],"mapped",[108]],[[120470,120470],"mapped",[109]],[[120471,120471],"mapped",[110]],[[120472,120472],"mapped",[111]],[[120473,120473],"mapped",[112]],[[120474,120474],"mapped",[113]],[[120475,120475],"mapped",[114]],[[120476,120476],"mapped",[115]],[[120477,120477],"mapped",[116]],[[120478,120478],"mapped",[117]],[[120479,120479],"mapped",[118]],[[120480,120480],"mapped",[119]],[[120481,120481],"mapped",[120]],[[120482,120482],"mapped",[121]],[[120483,120483],"mapped",[122]],[[120484,120484],"mapped",[305]],[[120485,120485],"mapped",[567]],[[120486,120487],"disallowed"],[[120488,120488],"mapped",[945]],[[120489,120489],"mapped",[946]],[[120490,120490],"mapped",[947]],[[120491,120491],"mapped",[948]],[[120492,120492],"mapped",[949]],[[120493,120493],"mapped",[950]],[[120494,120494],"mapped",[951]],[[120495,120495],"mapped",[952]],[[120496,120496],"mapped",[953]],[[120497,120497],"mapped",[954]],[[120498,120498],"mapped",[955]],[[120499,120499],"mapped",[956]],[[120500,120500],"mapped",[957]],[[120501,120501],"mapped",[958]],[[120502,120502],"mapped",[959]],[[120503,120503],"mapped",[960]],[[120504,120504],"mapped",[961]],[[120505,120505],"mapped",[952]],[[120506,120506],"mapped",[963]],[[120507,120507],"mapped",[964]],[[120508,120508],"mapped",[965]],[[120509,120509],"mapped",[966]],[[120510,120510],"mapped",[967]],[[120511,120511],"mapped",[968]],[[120512,120512],"mapped",[969]],[[120513,120513],"mapped",[8711]],[[120514,120514],"mapped",[945]],[[120515,120515],"mapped",[946]],[[120516,120516],"mapped",[947]],[[120517,120517],"mapped",[948]],[[120518,120518],"mapped",[949]],[[120519,120519],"mapped",[950]],[[120520,120520],"mapped",[951]],[[120521,120521],"mapped",[952]],[[120522,120522],"mapped",[953]],[[120523,120523],"mapped",[954]],[[120524,120524],"mapped",[955]],[[120525,120525],"mapped",[956]],[[120526,120526],"mapped",[957]],[[120527,120527],"mapped",[958]],[[120528,120528],"mapped",[959]],[[120529,120529],"mapped",[960]],[[120530,120530],"mapped",[961]],[[120531,120532],"mapped",[963]],[[120533,120533],"mapped",[964]],[[120534,120534],"mapped",[965]],[[120535,120535],"mapped",[966]],[[120536,120536],"mapped",[967]],[[120537,120537],"mapped",[968]],[[120538,120538],"mapped",[969]],[[120539,120539],"mapped",[8706]],[[120540,120540],"mapped",[949]],[[120541,120541],"mapped",[952]],[[120542,120542],"mapped",[954]],[[120543,120543],"mapped",[966]],[[120544,120544],"mapped",[961]],[[120545,120545],"mapped",[960]],[[120546,120546],"mapped",[945]],[[120547,120547],"mapped",[946]],[[120548,120548],"mapped",[947]],[[120549,120549],"mapped",[948]],[[120550,120550],"mapped",[949]],[[120551,120551],"mapped",[950]],[[120552,120552],"mapped",[951]],[[120553,120553],"mapped",[952]],[[120554,120554],"mapped",[953]],[[120555,120555],"mapped",[954]],[[120556,120556],"mapped",[955]],[[120557,120557],"mapped",[956]],[[120558,120558],"mapped",[957]],[[120559,120559],"mapped",[958]],[[120560,120560],"mapped",[959]],[[120561,120561],"mapped",[960]],[[120562,120562],"mapped",[961]],[[120563,120563],"mapped",[952]],[[120564,120564],"mapped",[963]],[[120565,120565],"mapped",[964]],[[120566,120566],"mapped",[965]],[[120567,120567],"mapped",[966]],[[120568,120568],"mapped",[967]],[[120569,120569],"mapped",[968]],[[120570,120570],"mapped",[969]],[[120571,120571],"mapped",[8711]],[[120572,120572],"mapped",[945]],[[120573,120573],"mapped",[946]],[[120574,120574],"mapped",[947]],[[120575,120575],"mapped",[948]],[[120576,120576],"mapped",[949]],[[120577,120577],"mapped",[950]],[[120578,120578],"mapped",[951]],[[120579,120579],"mapped",[952]],[[120580,120580],"mapped",[953]],[[120581,120581],"mapped",[954]],[[120582,120582],"mapped",[955]],[[120583,120583],"mapped",[956]],[[120584,120584],"mapped",[957]],[[120585,120585],"mapped",[958]],[[120586,120586],"mapped",[959]],[[120587,120587],"mapped",[960]],[[120588,120588],"mapped",[961]],[[120589,120590],"mapped",[963]],[[120591,120591],"mapped",[964]],[[120592,120592],"mapped",[965]],[[120593,120593],"mapped",[966]],[[120594,120594],"mapped",[967]],[[120595,120595],"mapped",[968]],[[120596,120596],"mapped",[969]],[[120597,120597],"mapped",[8706]],[[120598,120598],"mapped",[949]],[[120599,120599],"mapped",[952]],[[120600,120600],"mapped",[954]],[[120601,120601],"mapped",[966]],[[120602,120602],"mapped",[961]],[[120603,120603],"mapped",[960]],[[120604,120604],"mapped",[945]],[[120605,120605],"mapped",[946]],[[120606,120606],"mapped",[947]],[[120607,120607],"mapped",[948]],[[120608,120608],"mapped",[949]],[[120609,120609],"mapped",[950]],[[120610,120610],"mapped",[951]],[[120611,120611],"mapped",[952]],[[120612,120612],"mapped",[953]],[[120613,120613],"mapped",[954]],[[120614,120614],"mapped",[955]],[[120615,120615],"mapped",[956]],[[120616,120616],"mapped",[957]],[[120617,120617],"mapped",[958]],[[120618,120618],"mapped",[959]],[[120619,120619],"mapped",[960]],[[120620,120620],"mapped",[961]],[[120621,120621],"mapped",[952]],[[120622,120622],"mapped",[963]],[[120623,120623],"mapped",[964]],[[120624,120624],"mapped",[965]],[[120625,120625],"mapped",[966]],[[120626,120626],"mapped",[967]],[[120627,120627],"mapped",[968]],[[120628,120628],"mapped",[969]],[[120629,120629],"mapped",[8711]],[[120630,120630],"mapped",[945]],[[120631,120631],"mapped",[946]],[[120632,120632],"mapped",[947]],[[120633,120633],"mapped",[948]],[[120634,120634],"mapped",[949]],[[120635,120635],"mapped",[950]],[[120636,120636],"mapped",[951]],[[120637,120637],"mapped",[952]],[[120638,120638],"mapped",[953]],[[120639,120639],"mapped",[954]],[[120640,120640],"mapped",[955]],[[120641,120641],"mapped",[956]],[[120642,120642],"mapped",[957]],[[120643,120643],"mapped",[958]],[[120644,120644],"mapped",[959]],[[120645,120645],"mapped",[960]],[[120646,120646],"mapped",[961]],[[120647,120648],"mapped",[963]],[[120649,120649],"mapped",[964]],[[120650,120650],"mapped",[965]],[[120651,120651],"mapped",[966]],[[120652,120652],"mapped",[967]],[[120653,120653],"mapped",[968]],[[120654,120654],"mapped",[969]],[[120655,120655],"mapped",[8706]],[[120656,120656],"mapped",[949]],[[120657,120657],"mapped",[952]],[[120658,120658],"mapped",[954]],[[120659,120659],"mapped",[966]],[[120660,120660],"mapped",[961]],[[120661,120661],"mapped",[960]],[[120662,120662],"mapped",[945]],[[120663,120663],"mapped",[946]],[[120664,120664],"mapped",[947]],[[120665,120665],"mapped",[948]],[[120666,120666],"mapped",[949]],[[120667,120667],"mapped",[950]],[[120668,120668],"mapped",[951]],[[120669,120669],"mapped",[952]],[[120670,120670],"mapped",[953]],[[120671,120671],"mapped",[954]],[[120672,120672],"mapped",[955]],[[120673,120673],"mapped",[956]],[[120674,120674],"mapped",[957]],[[120675,120675],"mapped",[958]],[[120676,120676],"mapped",[959]],[[120677,120677],"mapped",[960]],[[120678,120678],"mapped",[961]],[[120679,120679],"mapped",[952]],[[120680,120680],"mapped",[963]],[[120681,120681],"mapped",[964]],[[120682,120682],"mapped",[965]],[[120683,120683],"mapped",[966]],[[120684,120684],"mapped",[967]],[[120685,120685],"mapped",[968]],[[120686,120686],"mapped",[969]],[[120687,120687],"mapped",[8711]],[[120688,120688],"mapped",[945]],[[120689,120689],"mapped",[946]],[[120690,120690],"mapped",[947]],[[120691,120691],"mapped",[948]],[[120692,120692],"mapped",[949]],[[120693,120693],"mapped",[950]],[[120694,120694],"mapped",[951]],[[120695,120695],"mapped",[952]],[[120696,120696],"mapped",[953]],[[120697,120697],"mapped",[954]],[[120698,120698],"mapped",[955]],[[120699,120699],"mapped",[956]],[[120700,120700],"mapped",[957]],[[120701,120701],"mapped",[958]],[[120702,120702],"mapped",[959]],[[120703,120703],"mapped",[960]],[[120704,120704],"mapped",[961]],[[120705,120706],"mapped",[963]],[[120707,120707],"mapped",[964]],[[120708,120708],"mapped",[965]],[[120709,120709],"mapped",[966]],[[120710,120710],"mapped",[967]],[[120711,120711],"mapped",[968]],[[120712,120712],"mapped",[969]],[[120713,120713],"mapped",[8706]],[[120714,120714],"mapped",[949]],[[120715,120715],"mapped",[952]],[[120716,120716],"mapped",[954]],[[120717,120717],"mapped",[966]],[[120718,120718],"mapped",[961]],[[120719,120719],"mapped",[960]],[[120720,120720],"mapped",[945]],[[120721,120721],"mapped",[946]],[[120722,120722],"mapped",[947]],[[120723,120723],"mapped",[948]],[[120724,120724],"mapped",[949]],[[120725,120725],"mapped",[950]],[[120726,120726],"mapped",[951]],[[120727,120727],"mapped",[952]],[[120728,120728],"mapped",[953]],[[120729,120729],"mapped",[954]],[[120730,120730],"mapped",[955]],[[120731,120731],"mapped",[956]],[[120732,120732],"mapped",[957]],[[120733,120733],"mapped",[958]],[[120734,120734],"mapped",[959]],[[120735,120735],"mapped",[960]],[[120736,120736],"mapped",[961]],[[120737,120737],"mapped",[952]],[[120738,120738],"mapped",[963]],[[120739,120739],"mapped",[964]],[[120740,120740],"mapped",[965]],[[120741,120741],"mapped",[966]],[[120742,120742],"mapped",[967]],[[120743,120743],"mapped",[968]],[[120744,120744],"mapped",[969]],[[120745,120745],"mapped",[8711]],[[120746,120746],"mapped",[945]],[[120747,120747],"mapped",[946]],[[120748,120748],"mapped",[947]],[[120749,120749],"mapped",[948]],[[120750,120750],"mapped",[949]],[[120751,120751],"mapped",[950]],[[120752,120752],"mapped",[951]],[[120753,120753],"mapped",[952]],[[120754,120754],"mapped",[953]],[[120755,120755],"mapped",[954]],[[120756,120756],"mapped",[955]],[[120757,120757],"mapped",[956]],[[120758,120758],"mapped",[957]],[[120759,120759],"mapped",[958]],[[120760,120760],"mapped",[959]],[[120761,120761],"mapped",[960]],[[120762,120762],"mapped",[961]],[[120763,120764],"mapped",[963]],[[120765,120765],"mapped",[964]],[[120766,120766],"mapped",[965]],[[120767,120767],"mapped",[966]],[[120768,120768],"mapped",[967]],[[120769,120769],"mapped",[968]],[[120770,120770],"mapped",[969]],[[120771,120771],"mapped",[8706]],[[120772,120772],"mapped",[949]],[[120773,120773],"mapped",[952]],[[120774,120774],"mapped",[954]],[[120775,120775],"mapped",[966]],[[120776,120776],"mapped",[961]],[[120777,120777],"mapped",[960]],[[120778,120779],"mapped",[989]],[[120780,120781],"disallowed"],[[120782,120782],"mapped",[48]],[[120783,120783],"mapped",[49]],[[120784,120784],"mapped",[50]],[[120785,120785],"mapped",[51]],[[120786,120786],"mapped",[52]],[[120787,120787],"mapped",[53]],[[120788,120788],"mapped",[54]],[[120789,120789],"mapped",[55]],[[120790,120790],"mapped",[56]],[[120791,120791],"mapped",[57]],[[120792,120792],"mapped",[48]],[[120793,120793],"mapped",[49]],[[120794,120794],"mapped",[50]],[[120795,120795],"mapped",[51]],[[120796,120796],"mapped",[52]],[[120797,120797],"mapped",[53]],[[120798,120798],"mapped",[54]],[[120799,120799],"mapped",[55]],[[120800,120800],"mapped",[56]],[[120801,120801],"mapped",[57]],[[120802,120802],"mapped",[48]],[[120803,120803],"mapped",[49]],[[120804,120804],"mapped",[50]],[[120805,120805],"mapped",[51]],[[120806,120806],"mapped",[52]],[[120807,120807],"mapped",[53]],[[120808,120808],"mapped",[54]],[[120809,120809],"mapped",[55]],[[120810,120810],"mapped",[56]],[[120811,120811],"mapped",[57]],[[120812,120812],"mapped",[48]],[[120813,120813],"mapped",[49]],[[120814,120814],"mapped",[50]],[[120815,120815],"mapped",[51]],[[120816,120816],"mapped",[52]],[[120817,120817],"mapped",[53]],[[120818,120818],"mapped",[54]],[[120819,120819],"mapped",[55]],[[120820,120820],"mapped",[56]],[[120821,120821],"mapped",[57]],[[120822,120822],"mapped",[48]],[[120823,120823],"mapped",[49]],[[120824,120824],"mapped",[50]],[[120825,120825],"mapped",[51]],[[120826,120826],"mapped",[52]],[[120827,120827],"mapped",[53]],[[120828,120828],"mapped",[54]],[[120829,120829],"mapped",[55]],[[120830,120830],"mapped",[56]],[[120831,120831],"mapped",[57]],[[120832,121343],"valid",[],"NV8"],[[121344,121398],"valid"],[[121399,121402],"valid",[],"NV8"],[[121403,121452],"valid"],[[121453,121460],"valid",[],"NV8"],[[121461,121461],"valid"],[[121462,121475],"valid",[],"NV8"],[[121476,121476],"valid"],[[121477,121483],"valid",[],"NV8"],[[121484,121498],"disallowed"],[[121499,121503],"valid"],[[121504,121504],"disallowed"],[[121505,121519],"valid"],[[121520,124927],"disallowed"],[[124928,125124],"valid"],[[125125,125126],"disallowed"],[[125127,125135],"valid",[],"NV8"],[[125136,125142],"valid"],[[125143,126463],"disallowed"],[[126464,126464],"mapped",[1575]],[[126465,126465],"mapped",[1576]],[[126466,126466],"mapped",[1580]],[[126467,126467],"mapped",[1583]],[[126468,126468],"disallowed"],[[126469,126469],"mapped",[1608]],[[126470,126470],"mapped",[1586]],[[126471,126471],"mapped",[1581]],[[126472,126472],"mapped",[1591]],[[126473,126473],"mapped",[1610]],[[126474,126474],"mapped",[1603]],[[126475,126475],"mapped",[1604]],[[126476,126476],"mapped",[1605]],[[126477,126477],"mapped",[1606]],[[126478,126478],"mapped",[1587]],[[126479,126479],"mapped",[1593]],[[126480,126480],"mapped",[1601]],[[126481,126481],"mapped",[1589]],[[126482,126482],"mapped",[1602]],[[126483,126483],"mapped",[1585]],[[126484,126484],"mapped",[1588]],[[126485,126485],"mapped",[1578]],[[126486,126486],"mapped",[1579]],[[126487,126487],"mapped",[1582]],[[126488,126488],"mapped",[1584]],[[126489,126489],"mapped",[1590]],[[126490,126490],"mapped",[1592]],[[126491,126491],"mapped",[1594]],[[126492,126492],"mapped",[1646]],[[126493,126493],"mapped",[1722]],[[126494,126494],"mapped",[1697]],[[126495,126495],"mapped",[1647]],[[126496,126496],"disallowed"],[[126497,126497],"mapped",[1576]],[[126498,126498],"mapped",[1580]],[[126499,126499],"disallowed"],[[126500,126500],"mapped",[1607]],[[126501,126502],"disallowed"],[[126503,126503],"mapped",[1581]],[[126504,126504],"disallowed"],[[126505,126505],"mapped",[1610]],[[126506,126506],"mapped",[1603]],[[126507,126507],"mapped",[1604]],[[126508,126508],"mapped",[1605]],[[126509,126509],"mapped",[1606]],[[126510,126510],"mapped",[1587]],[[126511,126511],"mapped",[1593]],[[126512,126512],"mapped",[1601]],[[126513,126513],"mapped",[1589]],[[126514,126514],"mapped",[1602]],[[126515,126515],"disallowed"],[[126516,126516],"mapped",[1588]],[[126517,126517],"mapped",[1578]],[[126518,126518],"mapped",[1579]],[[126519,126519],"mapped",[1582]],[[126520,126520],"disallowed"],[[126521,126521],"mapped",[1590]],[[126522,126522],"disallowed"],[[126523,126523],"mapped",[1594]],[[126524,126529],"disallowed"],[[126530,126530],"mapped",[1580]],[[126531,126534],"disallowed"],[[126535,126535],"mapped",[1581]],[[126536,126536],"disallowed"],[[126537,126537],"mapped",[1610]],[[126538,126538],"disallowed"],[[126539,126539],"mapped",[1604]],[[126540,126540],"disallowed"],[[126541,126541],"mapped",[1606]],[[126542,126542],"mapped",[1587]],[[126543,126543],"mapped",[1593]],[[126544,126544],"disallowed"],[[126545,126545],"mapped",[1589]],[[126546,126546],"mapped",[1602]],[[126547,126547],"disallowed"],[[126548,126548],"mapped",[1588]],[[126549,126550],"disallowed"],[[126551,126551],"mapped",[1582]],[[126552,126552],"disallowed"],[[126553,126553],"mapped",[1590]],[[126554,126554],"disallowed"],[[126555,126555],"mapped",[1594]],[[126556,126556],"disallowed"],[[126557,126557],"mapped",[1722]],[[126558,126558],"disallowed"],[[126559,126559],"mapped",[1647]],[[126560,126560],"disallowed"],[[126561,126561],"mapped",[1576]],[[126562,126562],"mapped",[1580]],[[126563,126563],"disallowed"],[[126564,126564],"mapped",[1607]],[[126565,126566],"disallowed"],[[126567,126567],"mapped",[1581]],[[126568,126568],"mapped",[1591]],[[126569,126569],"mapped",[1610]],[[126570,126570],"mapped",[1603]],[[126571,126571],"disallowed"],[[126572,126572],"mapped",[1605]],[[126573,126573],"mapped",[1606]],[[126574,126574],"mapped",[1587]],[[126575,126575],"mapped",[1593]],[[126576,126576],"mapped",[1601]],[[126577,126577],"mapped",[1589]],[[126578,126578],"mapped",[1602]],[[126579,126579],"disallowed"],[[126580,126580],"mapped",[1588]],[[126581,126581],"mapped",[1578]],[[126582,126582],"mapped",[1579]],[[126583,126583],"mapped",[1582]],[[126584,126584],"disallowed"],[[126585,126585],"mapped",[1590]],[[126586,126586],"mapped",[1592]],[[126587,126587],"mapped",[1594]],[[126588,126588],"mapped",[1646]],[[126589,126589],"disallowed"],[[126590,126590],"mapped",[1697]],[[126591,126591],"disallowed"],[[126592,126592],"mapped",[1575]],[[126593,126593],"mapped",[1576]],[[126594,126594],"mapped",[1580]],[[126595,126595],"mapped",[1583]],[[126596,126596],"mapped",[1607]],[[126597,126597],"mapped",[1608]],[[126598,126598],"mapped",[1586]],[[126599,126599],"mapped",[1581]],[[126600,126600],"mapped",[1591]],[[126601,126601],"mapped",[1610]],[[126602,126602],"disallowed"],[[126603,126603],"mapped",[1604]],[[126604,126604],"mapped",[1605]],[[126605,126605],"mapped",[1606]],[[126606,126606],"mapped",[1587]],[[126607,126607],"mapped",[1593]],[[126608,126608],"mapped",[1601]],[[126609,126609],"mapped",[1589]],[[126610,126610],"mapped",[1602]],[[126611,126611],"mapped",[1585]],[[126612,126612],"mapped",[1588]],[[126613,126613],"mapped",[1578]],[[126614,126614],"mapped",[1579]],[[126615,126615],"mapped",[1582]],[[126616,126616],"mapped",[1584]],[[126617,126617],"mapped",[1590]],[[126618,126618],"mapped",[1592]],[[126619,126619],"mapped",[1594]],[[126620,126624],"disallowed"],[[126625,126625],"mapped",[1576]],[[126626,126626],"mapped",[1580]],[[126627,126627],"mapped",[1583]],[[126628,126628],"disallowed"],[[126629,126629],"mapped",[1608]],[[126630,126630],"mapped",[1586]],[[126631,126631],"mapped",[1581]],[[126632,126632],"mapped",[1591]],[[126633,126633],"mapped",[1610]],[[126634,126634],"disallowed"],[[126635,126635],"mapped",[1604]],[[126636,126636],"mapped",[1605]],[[126637,126637],"mapped",[1606]],[[126638,126638],"mapped",[1587]],[[126639,126639],"mapped",[1593]],[[126640,126640],"mapped",[1601]],[[126641,126641],"mapped",[1589]],[[126642,126642],"mapped",[1602]],[[126643,126643],"mapped",[1585]],[[126644,126644],"mapped",[1588]],[[126645,126645],"mapped",[1578]],[[126646,126646],"mapped",[1579]],[[126647,126647],"mapped",[1582]],[[126648,126648],"mapped",[1584]],[[126649,126649],"mapped",[1590]],[[126650,126650],"mapped",[1592]],[[126651,126651],"mapped",[1594]],[[126652,126703],"disallowed"],[[126704,126705],"valid",[],"NV8"],[[126706,126975],"disallowed"],[[126976,127019],"valid",[],"NV8"],[[127020,127023],"disallowed"],[[127024,127123],"valid",[],"NV8"],[[127124,127135],"disallowed"],[[127136,127150],"valid",[],"NV8"],[[127151,127152],"disallowed"],[[127153,127166],"valid",[],"NV8"],[[127167,127167],"valid",[],"NV8"],[[127168,127168],"disallowed"],[[127169,127183],"valid",[],"NV8"],[[127184,127184],"disallowed"],[[127185,127199],"valid",[],"NV8"],[[127200,127221],"valid",[],"NV8"],[[127222,127231],"disallowed"],[[127232,127232],"disallowed"],[[127233,127233],"disallowed_STD3_mapped",[48,44]],[[127234,127234],"disallowed_STD3_mapped",[49,44]],[[127235,127235],"disallowed_STD3_mapped",[50,44]],[[127236,127236],"disallowed_STD3_mapped",[51,44]],[[127237,127237],"disallowed_STD3_mapped",[52,44]],[[127238,127238],"disallowed_STD3_mapped",[53,44]],[[127239,127239],"disallowed_STD3_mapped",[54,44]],[[127240,127240],"disallowed_STD3_mapped",[55,44]],[[127241,127241],"disallowed_STD3_mapped",[56,44]],[[127242,127242],"disallowed_STD3_mapped",[57,44]],[[127243,127244],"valid",[],"NV8"],[[127245,127247],"disallowed"],[[127248,127248],"disallowed_STD3_mapped",[40,97,41]],[[127249,127249],"disallowed_STD3_mapped",[40,98,41]],[[127250,127250],"disallowed_STD3_mapped",[40,99,41]],[[127251,127251],"disallowed_STD3_mapped",[40,100,41]],[[127252,127252],"disallowed_STD3_mapped",[40,101,41]],[[127253,127253],"disallowed_STD3_mapped",[40,102,41]],[[127254,127254],"disallowed_STD3_mapped",[40,103,41]],[[127255,127255],"disallowed_STD3_mapped",[40,104,41]],[[127256,127256],"disallowed_STD3_mapped",[40,105,41]],[[127257,127257],"disallowed_STD3_mapped",[40,106,41]],[[127258,127258],"disallowed_STD3_mapped",[40,107,41]],[[127259,127259],"disallowed_STD3_mapped",[40,108,41]],[[127260,127260],"disallowed_STD3_mapped",[40,109,41]],[[127261,127261],"disallowed_STD3_mapped",[40,110,41]],[[127262,127262],"disallowed_STD3_mapped",[40,111,41]],[[127263,127263],"disallowed_STD3_mapped",[40,112,41]],[[127264,127264],"disallowed_STD3_mapped",[40,113,41]],[[127265,127265],"disallowed_STD3_mapped",[40,114,41]],[[127266,127266],"disallowed_STD3_mapped",[40,115,41]],[[127267,127267],"disallowed_STD3_mapped",[40,116,41]],[[127268,127268],"disallowed_STD3_mapped",[40,117,41]],[[127269,127269],"disallowed_STD3_mapped",[40,118,41]],[[127270,127270],"disallowed_STD3_mapped",[40,119,41]],[[127271,127271],"disallowed_STD3_mapped",[40,120,41]],[[127272,127272],"disallowed_STD3_mapped",[40,121,41]],[[127273,127273],"disallowed_STD3_mapped",[40,122,41]],[[127274,127274],"mapped",[12308,115,12309]],[[127275,127275],"mapped",[99]],[[127276,127276],"mapped",[114]],[[127277,127277],"mapped",[99,100]],[[127278,127278],"mapped",[119,122]],[[127279,127279],"disallowed"],[[127280,127280],"mapped",[97]],[[127281,127281],"mapped",[98]],[[127282,127282],"mapped",[99]],[[127283,127283],"mapped",[100]],[[127284,127284],"mapped",[101]],[[127285,127285],"mapped",[102]],[[127286,127286],"mapped",[103]],[[127287,127287],"mapped",[104]],[[127288,127288],"mapped",[105]],[[127289,127289],"mapped",[106]],[[127290,127290],"mapped",[107]],[[127291,127291],"mapped",[108]],[[127292,127292],"mapped",[109]],[[127293,127293],"mapped",[110]],[[127294,127294],"mapped",[111]],[[127295,127295],"mapped",[112]],[[127296,127296],"mapped",[113]],[[127297,127297],"mapped",[114]],[[127298,127298],"mapped",[115]],[[127299,127299],"mapped",[116]],[[127300,127300],"mapped",[117]],[[127301,127301],"mapped",[118]],[[127302,127302],"mapped",[119]],[[127303,127303],"mapped",[120]],[[127304,127304],"mapped",[121]],[[127305,127305],"mapped",[122]],[[127306,127306],"mapped",[104,118]],[[127307,127307],"mapped",[109,118]],[[127308,127308],"mapped",[115,100]],[[127309,127309],"mapped",[115,115]],[[127310,127310],"mapped",[112,112,118]],[[127311,127311],"mapped",[119,99]],[[127312,127318],"valid",[],"NV8"],[[127319,127319],"valid",[],"NV8"],[[127320,127326],"valid",[],"NV8"],[[127327,127327],"valid",[],"NV8"],[[127328,127337],"valid",[],"NV8"],[[127338,127338],"mapped",[109,99]],[[127339,127339],"mapped",[109,100]],[[127340,127343],"disallowed"],[[127344,127352],"valid",[],"NV8"],[[127353,127353],"valid",[],"NV8"],[[127354,127354],"valid",[],"NV8"],[[127355,127356],"valid",[],"NV8"],[[127357,127358],"valid",[],"NV8"],[[127359,127359],"valid",[],"NV8"],[[127360,127369],"valid",[],"NV8"],[[127370,127373],"valid",[],"NV8"],[[127374,127375],"valid",[],"NV8"],[[127376,127376],"mapped",[100,106]],[[127377,127386],"valid",[],"NV8"],[[127387,127461],"disallowed"],[[127462,127487],"valid",[],"NV8"],[[127488,127488],"mapped",[12411,12363]],[[127489,127489],"mapped",[12467,12467]],[[127490,127490],"mapped",[12469]],[[127491,127503],"disallowed"],[[127504,127504],"mapped",[25163]],[[127505,127505],"mapped",[23383]],[[127506,127506],"mapped",[21452]],[[127507,127507],"mapped",[12487]],[[127508,127508],"mapped",[20108]],[[127509,127509],"mapped",[22810]],[[127510,127510],"mapped",[35299]],[[127511,127511],"mapped",[22825]],[[127512,127512],"mapped",[20132]],[[127513,127513],"mapped",[26144]],[[127514,127514],"mapped",[28961]],[[127515,127515],"mapped",[26009]],[[127516,127516],"mapped",[21069]],[[127517,127517],"mapped",[24460]],[[127518,127518],"mapped",[20877]],[[127519,127519],"mapped",[26032]],[[127520,127520],"mapped",[21021]],[[127521,127521],"mapped",[32066]],[[127522,127522],"mapped",[29983]],[[127523,127523],"mapped",[36009]],[[127524,127524],"mapped",[22768]],[[127525,127525],"mapped",[21561]],[[127526,127526],"mapped",[28436]],[[127527,127527],"mapped",[25237]],[[127528,127528],"mapped",[25429]],[[127529,127529],"mapped",[19968]],[[127530,127530],"mapped",[19977]],[[127531,127531],"mapped",[36938]],[[127532,127532],"mapped",[24038]],[[127533,127533],"mapped",[20013]],[[127534,127534],"mapped",[21491]],[[127535,127535],"mapped",[25351]],[[127536,127536],"mapped",[36208]],[[127537,127537],"mapped",[25171]],[[127538,127538],"mapped",[31105]],[[127539,127539],"mapped",[31354]],[[127540,127540],"mapped",[21512]],[[127541,127541],"mapped",[28288]],[[127542,127542],"mapped",[26377]],[[127543,127543],"mapped",[26376]],[[127544,127544],"mapped",[30003]],[[127545,127545],"mapped",[21106]],[[127546,127546],"mapped",[21942]],[[127547,127551],"disallowed"],[[127552,127552],"mapped",[12308,26412,12309]],[[127553,127553],"mapped",[12308,19977,12309]],[[127554,127554],"mapped",[12308,20108,12309]],[[127555,127555],"mapped",[12308,23433,12309]],[[127556,127556],"mapped",[12308,28857,12309]],[[127557,127557],"mapped",[12308,25171,12309]],[[127558,127558],"mapped",[12308,30423,12309]],[[127559,127559],"mapped",[12308,21213,12309]],[[127560,127560],"mapped",[12308,25943,12309]],[[127561,127567],"disallowed"],[[127568,127568],"mapped",[24471]],[[127569,127569],"mapped",[21487]],[[127570,127743],"disallowed"],[[127744,127776],"valid",[],"NV8"],[[127777,127788],"valid",[],"NV8"],[[127789,127791],"valid",[],"NV8"],[[127792,127797],"valid",[],"NV8"],[[127798,127798],"valid",[],"NV8"],[[127799,127868],"valid",[],"NV8"],[[127869,127869],"valid",[],"NV8"],[[127870,127871],"valid",[],"NV8"],[[127872,127891],"valid",[],"NV8"],[[127892,127903],"valid",[],"NV8"],[[127904,127940],"valid",[],"NV8"],[[127941,127941],"valid",[],"NV8"],[[127942,127946],"valid",[],"NV8"],[[127947,127950],"valid",[],"NV8"],[[127951,127955],"valid",[],"NV8"],[[127956,127967],"valid",[],"NV8"],[[127968,127984],"valid",[],"NV8"],[[127985,127991],"valid",[],"NV8"],[[127992,127999],"valid",[],"NV8"],[[128000,128062],"valid",[],"NV8"],[[128063,128063],"valid",[],"NV8"],[[128064,128064],"valid",[],"NV8"],[[128065,128065],"valid",[],"NV8"],[[128066,128247],"valid",[],"NV8"],[[128248,128248],"valid",[],"NV8"],[[128249,128252],"valid",[],"NV8"],[[128253,128254],"valid",[],"NV8"],[[128255,128255],"valid",[],"NV8"],[[128256,128317],"valid",[],"NV8"],[[128318,128319],"valid",[],"NV8"],[[128320,128323],"valid",[],"NV8"],[[128324,128330],"valid",[],"NV8"],[[128331,128335],"valid",[],"NV8"],[[128336,128359],"valid",[],"NV8"],[[128360,128377],"valid",[],"NV8"],[[128378,128378],"disallowed"],[[128379,128419],"valid",[],"NV8"],[[128420,128420],"disallowed"],[[128421,128506],"valid",[],"NV8"],[[128507,128511],"valid",[],"NV8"],[[128512,128512],"valid",[],"NV8"],[[128513,128528],"valid",[],"NV8"],[[128529,128529],"valid",[],"NV8"],[[128530,128532],"valid",[],"NV8"],[[128533,128533],"valid",[],"NV8"],[[128534,128534],"valid",[],"NV8"],[[128535,128535],"valid",[],"NV8"],[[128536,128536],"valid",[],"NV8"],[[128537,128537],"valid",[],"NV8"],[[128538,128538],"valid",[],"NV8"],[[128539,128539],"valid",[],"NV8"],[[128540,128542],"valid",[],"NV8"],[[128543,128543],"valid",[],"NV8"],[[128544,128549],"valid",[],"NV8"],[[128550,128551],"valid",[],"NV8"],[[128552,128555],"valid",[],"NV8"],[[128556,128556],"valid",[],"NV8"],[[128557,128557],"valid",[],"NV8"],[[128558,128559],"valid",[],"NV8"],[[128560,128563],"valid",[],"NV8"],[[128564,128564],"valid",[],"NV8"],[[128565,128576],"valid",[],"NV8"],[[128577,128578],"valid",[],"NV8"],[[128579,128580],"valid",[],"NV8"],[[128581,128591],"valid",[],"NV8"],[[128592,128639],"valid",[],"NV8"],[[128640,128709],"valid",[],"NV8"],[[128710,128719],"valid",[],"NV8"],[[128720,128720],"valid",[],"NV8"],[[128721,128735],"disallowed"],[[128736,128748],"valid",[],"NV8"],[[128749,128751],"disallowed"],[[128752,128755],"valid",[],"NV8"],[[128756,128767],"disallowed"],[[128768,128883],"valid",[],"NV8"],[[128884,128895],"disallowed"],[[128896,128980],"valid",[],"NV8"],[[128981,129023],"disallowed"],[[129024,129035],"valid",[],"NV8"],[[129036,129039],"disallowed"],[[129040,129095],"valid",[],"NV8"],[[129096,129103],"disallowed"],[[129104,129113],"valid",[],"NV8"],[[129114,129119],"disallowed"],[[129120,129159],"valid",[],"NV8"],[[129160,129167],"disallowed"],[[129168,129197],"valid",[],"NV8"],[[129198,129295],"disallowed"],[[129296,129304],"valid",[],"NV8"],[[129305,129407],"disallowed"],[[129408,129412],"valid",[],"NV8"],[[129413,129471],"disallowed"],[[129472,129472],"valid",[],"NV8"],[[129473,131069],"disallowed"],[[131070,131071],"disallowed"],[[131072,173782],"valid"],[[173783,173823],"disallowed"],[[173824,177972],"valid"],[[177973,177983],"disallowed"],[[177984,178205],"valid"],[[178206,178207],"disallowed"],[[178208,183969],"valid"],[[183970,194559],"disallowed"],[[194560,194560],"mapped",[20029]],[[194561,194561],"mapped",[20024]],[[194562,194562],"mapped",[20033]],[[194563,194563],"mapped",[131362]],[[194564,194564],"mapped",[20320]],[[194565,194565],"mapped",[20398]],[[194566,194566],"mapped",[20411]],[[194567,194567],"mapped",[20482]],[[194568,194568],"mapped",[20602]],[[194569,194569],"mapped",[20633]],[[194570,194570],"mapped",[20711]],[[194571,194571],"mapped",[20687]],[[194572,194572],"mapped",[13470]],[[194573,194573],"mapped",[132666]],[[194574,194574],"mapped",[20813]],[[194575,194575],"mapped",[20820]],[[194576,194576],"mapped",[20836]],[[194577,194577],"mapped",[20855]],[[194578,194578],"mapped",[132380]],[[194579,194579],"mapped",[13497]],[[194580,194580],"mapped",[20839]],[[194581,194581],"mapped",[20877]],[[194582,194582],"mapped",[132427]],[[194583,194583],"mapped",[20887]],[[194584,194584],"mapped",[20900]],[[194585,194585],"mapped",[20172]],[[194586,194586],"mapped",[20908]],[[194587,194587],"mapped",[20917]],[[194588,194588],"mapped",[168415]],[[194589,194589],"mapped",[20981]],[[194590,194590],"mapped",[20995]],[[194591,194591],"mapped",[13535]],[[194592,194592],"mapped",[21051]],[[194593,194593],"mapped",[21062]],[[194594,194594],"mapped",[21106]],[[194595,194595],"mapped",[21111]],[[194596,194596],"mapped",[13589]],[[194597,194597],"mapped",[21191]],[[194598,194598],"mapped",[21193]],[[194599,194599],"mapped",[21220]],[[194600,194600],"mapped",[21242]],[[194601,194601],"mapped",[21253]],[[194602,194602],"mapped",[21254]],[[194603,194603],"mapped",[21271]],[[194604,194604],"mapped",[21321]],[[194605,194605],"mapped",[21329]],[[194606,194606],"mapped",[21338]],[[194607,194607],"mapped",[21363]],[[194608,194608],"mapped",[21373]],[[194609,194611],"mapped",[21375]],[[194612,194612],"mapped",[133676]],[[194613,194613],"mapped",[28784]],[[194614,194614],"mapped",[21450]],[[194615,194615],"mapped",[21471]],[[194616,194616],"mapped",[133987]],[[194617,194617],"mapped",[21483]],[[194618,194618],"mapped",[21489]],[[194619,194619],"mapped",[21510]],[[194620,194620],"mapped",[21662]],[[194621,194621],"mapped",[21560]],[[194622,194622],"mapped",[21576]],[[194623,194623],"mapped",[21608]],[[194624,194624],"mapped",[21666]],[[194625,194625],"mapped",[21750]],[[194626,194626],"mapped",[21776]],[[194627,194627],"mapped",[21843]],[[194628,194628],"mapped",[21859]],[[194629,194630],"mapped",[21892]],[[194631,194631],"mapped",[21913]],[[194632,194632],"mapped",[21931]],[[194633,194633],"mapped",[21939]],[[194634,194634],"mapped",[21954]],[[194635,194635],"mapped",[22294]],[[194636,194636],"mapped",[22022]],[[194637,194637],"mapped",[22295]],[[194638,194638],"mapped",[22097]],[[194639,194639],"mapped",[22132]],[[194640,194640],"mapped",[20999]],[[194641,194641],"mapped",[22766]],[[194642,194642],"mapped",[22478]],[[194643,194643],"mapped",[22516]],[[194644,194644],"mapped",[22541]],[[194645,194645],"mapped",[22411]],[[194646,194646],"mapped",[22578]],[[194647,194647],"mapped",[22577]],[[194648,194648],"mapped",[22700]],[[194649,194649],"mapped",[136420]],[[194650,194650],"mapped",[22770]],[[194651,194651],"mapped",[22775]],[[194652,194652],"mapped",[22790]],[[194653,194653],"mapped",[22810]],[[194654,194654],"mapped",[22818]],[[194655,194655],"mapped",[22882]],[[194656,194656],"mapped",[136872]],[[194657,194657],"mapped",[136938]],[[194658,194658],"mapped",[23020]],[[194659,194659],"mapped",[23067]],[[194660,194660],"mapped",[23079]],[[194661,194661],"mapped",[23000]],[[194662,194662],"mapped",[23142]],[[194663,194663],"mapped",[14062]],[[194664,194664],"disallowed"],[[194665,194665],"mapped",[23304]],[[194666,194667],"mapped",[23358]],[[194668,194668],"mapped",[137672]],[[194669,194669],"mapped",[23491]],[[194670,194670],"mapped",[23512]],[[194671,194671],"mapped",[23527]],[[194672,194672],"mapped",[23539]],[[194673,194673],"mapped",[138008]],[[194674,194674],"mapped",[23551]],[[194675,194675],"mapped",[23558]],[[194676,194676],"disallowed"],[[194677,194677],"mapped",[23586]],[[194678,194678],"mapped",[14209]],[[194679,194679],"mapped",[23648]],[[194680,194680],"mapped",[23662]],[[194681,194681],"mapped",[23744]],[[194682,194682],"mapped",[23693]],[[194683,194683],"mapped",[138724]],[[194684,194684],"mapped",[23875]],[[194685,194685],"mapped",[138726]],[[194686,194686],"mapped",[23918]],[[194687,194687],"mapped",[23915]],[[194688,194688],"mapped",[23932]],[[194689,194689],"mapped",[24033]],[[194690,194690],"mapped",[24034]],[[194691,194691],"mapped",[14383]],[[194692,194692],"mapped",[24061]],[[194693,194693],"mapped",[24104]],[[194694,194694],"mapped",[24125]],[[194695,194695],"mapped",[24169]],[[194696,194696],"mapped",[14434]],[[194697,194697],"mapped",[139651]],[[194698,194698],"mapped",[14460]],[[194699,194699],"mapped",[24240]],[[194700,194700],"mapped",[24243]],[[194701,194701],"mapped",[24246]],[[194702,194702],"mapped",[24266]],[[194703,194703],"mapped",[172946]],[[194704,194704],"mapped",[24318]],[[194705,194706],"mapped",[140081]],[[194707,194707],"mapped",[33281]],[[194708,194709],"mapped",[24354]],[[194710,194710],"mapped",[14535]],[[194711,194711],"mapped",[144056]],[[194712,194712],"mapped",[156122]],[[194713,194713],"mapped",[24418]],[[194714,194714],"mapped",[24427]],[[194715,194715],"mapped",[14563]],[[194716,194716],"mapped",[24474]],[[194717,194717],"mapped",[24525]],[[194718,194718],"mapped",[24535]],[[194719,194719],"mapped",[24569]],[[194720,194720],"mapped",[24705]],[[194721,194721],"mapped",[14650]],[[194722,194722],"mapped",[14620]],[[194723,194723],"mapped",[24724]],[[194724,194724],"mapped",[141012]],[[194725,194725],"mapped",[24775]],[[194726,194726],"mapped",[24904]],[[194727,194727],"mapped",[24908]],[[194728,194728],"mapped",[24910]],[[194729,194729],"mapped",[24908]],[[194730,194730],"mapped",[24954]],[[194731,194731],"mapped",[24974]],[[194732,194732],"mapped",[25010]],[[194733,194733],"mapped",[24996]],[[194734,194734],"mapped",[25007]],[[194735,194735],"mapped",[25054]],[[194736,194736],"mapped",[25074]],[[194737,194737],"mapped",[25078]],[[194738,194738],"mapped",[25104]],[[194739,194739],"mapped",[25115]],[[194740,194740],"mapped",[25181]],[[194741,194741],"mapped",[25265]],[[194742,194742],"mapped",[25300]],[[194743,194743],"mapped",[25424]],[[194744,194744],"mapped",[142092]],[[194745,194745],"mapped",[25405]],[[194746,194746],"mapped",[25340]],[[194747,194747],"mapped",[25448]],[[194748,194748],"mapped",[25475]],[[194749,194749],"mapped",[25572]],[[194750,194750],"mapped",[142321]],[[194751,194751],"mapped",[25634]],[[194752,194752],"mapped",[25541]],[[194753,194753],"mapped",[25513]],[[194754,194754],"mapped",[14894]],[[194755,194755],"mapped",[25705]],[[194756,194756],"mapped",[25726]],[[194757,194757],"mapped",[25757]],[[194758,194758],"mapped",[25719]],[[194759,194759],"mapped",[14956]],[[194760,194760],"mapped",[25935]],[[194761,194761],"mapped",[25964]],[[194762,194762],"mapped",[143370]],[[194763,194763],"mapped",[26083]],[[194764,194764],"mapped",[26360]],[[194765,194765],"mapped",[26185]],[[194766,194766],"mapped",[15129]],[[194767,194767],"mapped",[26257]],[[194768,194768],"mapped",[15112]],[[194769,194769],"mapped",[15076]],[[194770,194770],"mapped",[20882]],[[194771,194771],"mapped",[20885]],[[194772,194772],"mapped",[26368]],[[194773,194773],"mapped",[26268]],[[194774,194774],"mapped",[32941]],[[194775,194775],"mapped",[17369]],[[194776,194776],"mapped",[26391]],[[194777,194777],"mapped",[26395]],[[194778,194778],"mapped",[26401]],[[194779,194779],"mapped",[26462]],[[194780,194780],"mapped",[26451]],[[194781,194781],"mapped",[144323]],[[194782,194782],"mapped",[15177]],[[194783,194783],"mapped",[26618]],[[194784,194784],"mapped",[26501]],[[194785,194785],"mapped",[26706]],[[194786,194786],"mapped",[26757]],[[194787,194787],"mapped",[144493]],[[194788,194788],"mapped",[26766]],[[194789,194789],"mapped",[26655]],[[194790,194790],"mapped",[26900]],[[194791,194791],"mapped",[15261]],[[194792,194792],"mapped",[26946]],[[194793,194793],"mapped",[27043]],[[194794,194794],"mapped",[27114]],[[194795,194795],"mapped",[27304]],[[194796,194796],"mapped",[145059]],[[194797,194797],"mapped",[27355]],[[194798,194798],"mapped",[15384]],[[194799,194799],"mapped",[27425]],[[194800,194800],"mapped",[145575]],[[194801,194801],"mapped",[27476]],[[194802,194802],"mapped",[15438]],[[194803,194803],"mapped",[27506]],[[194804,194804],"mapped",[27551]],[[194805,194805],"mapped",[27578]],[[194806,194806],"mapped",[27579]],[[194807,194807],"mapped",[146061]],[[194808,194808],"mapped",[138507]],[[194809,194809],"mapped",[146170]],[[194810,194810],"mapped",[27726]],[[194811,194811],"mapped",[146620]],[[194812,194812],"mapped",[27839]],[[194813,194813],"mapped",[27853]],[[194814,194814],"mapped",[27751]],[[194815,194815],"mapped",[27926]],[[194816,194816],"mapped",[27966]],[[194817,194817],"mapped",[28023]],[[194818,194818],"mapped",[27969]],[[194819,194819],"mapped",[28009]],[[194820,194820],"mapped",[28024]],[[194821,194821],"mapped",[28037]],[[194822,194822],"mapped",[146718]],[[194823,194823],"mapped",[27956]],[[194824,194824],"mapped",[28207]],[[194825,194825],"mapped",[28270]],[[194826,194826],"mapped",[15667]],[[194827,194827],"mapped",[28363]],[[194828,194828],"mapped",[28359]],[[194829,194829],"mapped",[147153]],[[194830,194830],"mapped",[28153]],[[194831,194831],"mapped",[28526]],[[194832,194832],"mapped",[147294]],[[194833,194833],"mapped",[147342]],[[194834,194834],"mapped",[28614]],[[194835,194835],"mapped",[28729]],[[194836,194836],"mapped",[28702]],[[194837,194837],"mapped",[28699]],[[194838,194838],"mapped",[15766]],[[194839,194839],"mapped",[28746]],[[194840,194840],"mapped",[28797]],[[194841,194841],"mapped",[28791]],[[194842,194842],"mapped",[28845]],[[194843,194843],"mapped",[132389]],[[194844,194844],"mapped",[28997]],[[194845,194845],"mapped",[148067]],[[194846,194846],"mapped",[29084]],[[194847,194847],"disallowed"],[[194848,194848],"mapped",[29224]],[[194849,194849],"mapped",[29237]],[[194850,194850],"mapped",[29264]],[[194851,194851],"mapped",[149000]],[[194852,194852],"mapped",[29312]],[[194853,194853],"mapped",[29333]],[[194854,194854],"mapped",[149301]],[[194855,194855],"mapped",[149524]],[[194856,194856],"mapped",[29562]],[[194857,194857],"mapped",[29579]],[[194858,194858],"mapped",[16044]],[[194859,194859],"mapped",[29605]],[[194860,194861],"mapped",[16056]],[[194862,194862],"mapped",[29767]],[[194863,194863],"mapped",[29788]],[[194864,194864],"mapped",[29809]],[[194865,194865],"mapped",[29829]],[[194866,194866],"mapped",[29898]],[[194867,194867],"mapped",[16155]],[[194868,194868],"mapped",[29988]],[[194869,194869],"mapped",[150582]],[[194870,194870],"mapped",[30014]],[[194871,194871],"mapped",[150674]],[[194872,194872],"mapped",[30064]],[[194873,194873],"mapped",[139679]],[[194874,194874],"mapped",[30224]],[[194875,194875],"mapped",[151457]],[[194876,194876],"mapped",[151480]],[[194877,194877],"mapped",[151620]],[[194878,194878],"mapped",[16380]],[[194879,194879],"mapped",[16392]],[[194880,194880],"mapped",[30452]],[[194881,194881],"mapped",[151795]],[[194882,194882],"mapped",[151794]],[[194883,194883],"mapped",[151833]],[[194884,194884],"mapped",[151859]],[[194885,194885],"mapped",[30494]],[[194886,194887],"mapped",[30495]],[[194888,194888],"mapped",[30538]],[[194889,194889],"mapped",[16441]],[[194890,194890],"mapped",[30603]],[[194891,194891],"mapped",[16454]],[[194892,194892],"mapped",[16534]],[[194893,194893],"mapped",[152605]],[[194894,194894],"mapped",[30798]],[[194895,194895],"mapped",[30860]],[[194896,194896],"mapped",[30924]],[[194897,194897],"mapped",[16611]],[[194898,194898],"mapped",[153126]],[[194899,194899],"mapped",[31062]],[[194900,194900],"mapped",[153242]],[[194901,194901],"mapped",[153285]],[[194902,194902],"mapped",[31119]],[[194903,194903],"mapped",[31211]],[[194904,194904],"mapped",[16687]],[[194905,194905],"mapped",[31296]],[[194906,194906],"mapped",[31306]],[[194907,194907],"mapped",[31311]],[[194908,194908],"mapped",[153980]],[[194909,194910],"mapped",[154279]],[[194911,194911],"disallowed"],[[194912,194912],"mapped",[16898]],[[194913,194913],"mapped",[154539]],[[194914,194914],"mapped",[31686]],[[194915,194915],"mapped",[31689]],[[194916,194916],"mapped",[16935]],[[194917,194917],"mapped",[154752]],[[194918,194918],"mapped",[31954]],[[194919,194919],"mapped",[17056]],[[194920,194920],"mapped",[31976]],[[194921,194921],"mapped",[31971]],[[194922,194922],"mapped",[32000]],[[194923,194923],"mapped",[155526]],[[194924,194924],"mapped",[32099]],[[194925,194925],"mapped",[17153]],[[194926,194926],"mapped",[32199]],[[194927,194927],"mapped",[32258]],[[194928,194928],"mapped",[32325]],[[194929,194929],"mapped",[17204]],[[194930,194930],"mapped",[156200]],[[194931,194931],"mapped",[156231]],[[194932,194932],"mapped",[17241]],[[194933,194933],"mapped",[156377]],[[194934,194934],"mapped",[32634]],[[194935,194935],"mapped",[156478]],[[194936,194936],"mapped",[32661]],[[194937,194937],"mapped",[32762]],[[194938,194938],"mapped",[32773]],[[194939,194939],"mapped",[156890]],[[194940,194940],"mapped",[156963]],[[194941,194941],"mapped",[32864]],[[194942,194942],"mapped",[157096]],[[194943,194943],"mapped",[32880]],[[194944,194944],"mapped",[144223]],[[194945,194945],"mapped",[17365]],[[194946,194946],"mapped",[32946]],[[194947,194947],"mapped",[33027]],[[194948,194948],"mapped",[17419]],[[194949,194949],"mapped",[33086]],[[194950,194950],"mapped",[23221]],[[194951,194951],"mapped",[157607]],[[194952,194952],"mapped",[157621]],[[194953,194953],"mapped",[144275]],[[194954,194954],"mapped",[144284]],[[194955,194955],"mapped",[33281]],[[194956,194956],"mapped",[33284]],[[194957,194957],"mapped",[36766]],[[194958,194958],"mapped",[17515]],[[194959,194959],"mapped",[33425]],[[194960,194960],"mapped",[33419]],[[194961,194961],"mapped",[33437]],[[194962,194962],"mapped",[21171]],[[194963,194963],"mapped",[33457]],[[194964,194964],"mapped",[33459]],[[194965,194965],"mapped",[33469]],[[194966,194966],"mapped",[33510]],[[194967,194967],"mapped",[158524]],[[194968,194968],"mapped",[33509]],[[194969,194969],"mapped",[33565]],[[194970,194970],"mapped",[33635]],[[194971,194971],"mapped",[33709]],[[194972,194972],"mapped",[33571]],[[194973,194973],"mapped",[33725]],[[194974,194974],"mapped",[33767]],[[194975,194975],"mapped",[33879]],[[194976,194976],"mapped",[33619]],[[194977,194977],"mapped",[33738]],[[194978,194978],"mapped",[33740]],[[194979,194979],"mapped",[33756]],[[194980,194980],"mapped",[158774]],[[194981,194981],"mapped",[159083]],[[194982,194982],"mapped",[158933]],[[194983,194983],"mapped",[17707]],[[194984,194984],"mapped",[34033]],[[194985,194985],"mapped",[34035]],[[194986,194986],"mapped",[34070]],[[194987,194987],"mapped",[160714]],[[194988,194988],"mapped",[34148]],[[194989,194989],"mapped",[159532]],[[194990,194990],"mapped",[17757]],[[194991,194991],"mapped",[17761]],[[194992,194992],"mapped",[159665]],[[194993,194993],"mapped",[159954]],[[194994,194994],"mapped",[17771]],[[194995,194995],"mapped",[34384]],[[194996,194996],"mapped",[34396]],[[194997,194997],"mapped",[34407]],[[194998,194998],"mapped",[34409]],[[194999,194999],"mapped",[34473]],[[195000,195000],"mapped",[34440]],[[195001,195001],"mapped",[34574]],[[195002,195002],"mapped",[34530]],[[195003,195003],"mapped",[34681]],[[195004,195004],"mapped",[34600]],[[195005,195005],"mapped",[34667]],[[195006,195006],"mapped",[34694]],[[195007,195007],"disallowed"],[[195008,195008],"mapped",[34785]],[[195009,195009],"mapped",[34817]],[[195010,195010],"mapped",[17913]],[[195011,195011],"mapped",[34912]],[[195012,195012],"mapped",[34915]],[[195013,195013],"mapped",[161383]],[[195014,195014],"mapped",[35031]],[[195015,195015],"mapped",[35038]],[[195016,195016],"mapped",[17973]],[[195017,195017],"mapped",[35066]],[[195018,195018],"mapped",[13499]],[[195019,195019],"mapped",[161966]],[[195020,195020],"mapped",[162150]],[[195021,195021],"mapped",[18110]],[[195022,195022],"mapped",[18119]],[[195023,195023],"mapped",[35488]],[[195024,195024],"mapped",[35565]],[[195025,195025],"mapped",[35722]],[[195026,195026],"mapped",[35925]],[[195027,195027],"mapped",[162984]],[[195028,195028],"mapped",[36011]],[[195029,195029],"mapped",[36033]],[[195030,195030],"mapped",[36123]],[[195031,195031],"mapped",[36215]],[[195032,195032],"mapped",[163631]],[[195033,195033],"mapped",[133124]],[[195034,195034],"mapped",[36299]],[[195035,195035],"mapped",[36284]],[[195036,195036],"mapped",[36336]],[[195037,195037],"mapped",[133342]],[[195038,195038],"mapped",[36564]],[[195039,195039],"mapped",[36664]],[[195040,195040],"mapped",[165330]],[[195041,195041],"mapped",[165357]],[[195042,195042],"mapped",[37012]],[[195043,195043],"mapped",[37105]],[[195044,195044],"mapped",[37137]],[[195045,195045],"mapped",[165678]],[[195046,195046],"mapped",[37147]],[[195047,195047],"mapped",[37432]],[[195048,195048],"mapped",[37591]],[[195049,195049],"mapped",[37592]],[[195050,195050],"mapped",[37500]],[[195051,195051],"mapped",[37881]],[[195052,195052],"mapped",[37909]],[[195053,195053],"mapped",[166906]],[[195054,195054],"mapped",[38283]],[[195055,195055],"mapped",[18837]],[[195056,195056],"mapped",[38327]],[[195057,195057],"mapped",[167287]],[[195058,195058],"mapped",[18918]],[[195059,195059],"mapped",[38595]],[[195060,195060],"mapped",[23986]],[[195061,195061],"mapped",[38691]],[[195062,195062],"mapped",[168261]],[[195063,195063],"mapped",[168474]],[[195064,195064],"mapped",[19054]],[[195065,195065],"mapped",[19062]],[[195066,195066],"mapped",[38880]],[[195067,195067],"mapped",[168970]],[[195068,195068],"mapped",[19122]],[[195069,195069],"mapped",[169110]],[[195070,195071],"mapped",[38923]],[[195072,195072],"mapped",[38953]],[[195073,195073],"mapped",[169398]],[[195074,195074],"mapped",[39138]],[[195075,195075],"mapped",[19251]],[[195076,195076],"mapped",[39209]],[[195077,195077],"mapped",[39335]],[[195078,195078],"mapped",[39362]],[[195079,195079],"mapped",[39422]],[[195080,195080],"mapped",[19406]],[[195081,195081],"mapped",[170800]],[[195082,195082],"mapped",[39698]],[[195083,195083],"mapped",[40000]],[[195084,195084],"mapped",[40189]],[[195085,195085],"mapped",[19662]],[[195086,195086],"mapped",[19693]],[[195087,195087],"mapped",[40295]],[[195088,195088],"mapped",[172238]],[[195089,195089],"mapped",[19704]],[[195090,195090],"mapped",[172293]],[[195091,195091],"mapped",[172558]],[[195092,195092],"mapped",[172689]],[[195093,195093],"mapped",[40635]],[[195094,195094],"mapped",[19798]],[[195095,195095],"mapped",[40697]],[[195096,195096],"mapped",[40702]],[[195097,195097],"mapped",[40709]],[[195098,195098],"mapped",[40719]],[[195099,195099],"mapped",[40726]],[[195100,195100],"mapped",[40763]],[[195101,195101],"mapped",[173568]],[[195102,196605],"disallowed"],[[196606,196607],"disallowed"],[[196608,262141],"disallowed"],[[262142,262143],"disallowed"],[[262144,327677],"disallowed"],[[327678,327679],"disallowed"],[[327680,393213],"disallowed"],[[393214,393215],"disallowed"],[[393216,458749],"disallowed"],[[458750,458751],"disallowed"],[[458752,524285],"disallowed"],[[524286,524287],"disallowed"],[[524288,589821],"disallowed"],[[589822,589823],"disallowed"],[[589824,655357],"disallowed"],[[655358,655359],"disallowed"],[[655360,720893],"disallowed"],[[720894,720895],"disallowed"],[[720896,786429],"disallowed"],[[786430,786431],"disallowed"],[[786432,851965],"disallowed"],[[851966,851967],"disallowed"],[[851968,917501],"disallowed"],[[917502,917503],"disallowed"],[[917504,917504],"disallowed"],[[917505,917505],"disallowed"],[[917506,917535],"disallowed"],[[917536,917631],"disallowed"],[[917632,917759],"disallowed"],[[917760,917999],"ignored"],[[918000,983037],"disallowed"],[[983038,983039],"disallowed"],[[983040,1048573],"disallowed"],[[1048574,1048575],"disallowed"],[[1048576,1114109],"disallowed"],[[1114110,1114111],"disallowed"]] \ No newline at end of file diff --git a/node_modules/node-fetch/node_modules/tr46/package.json b/node_modules/node-fetch/node_modules/tr46/package.json new file mode 100644 index 0000000..b6826da --- /dev/null +++ b/node_modules/node-fetch/node_modules/tr46/package.json @@ -0,0 +1,31 @@ +{ + "name": "tr46", + "version": "0.0.3", + "description": "An implementation of the Unicode TR46 spec", + "main": "index.js", + "scripts": { + "test": "mocha", + "pretest": "node scripts/getLatestUnicodeTests.js", + "prepublish": "node scripts/generateMappingTable.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Sebmaster/tr46.js.git" + }, + "keywords": [ + "unicode", + "tr46", + "url", + "whatwg" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "bugs": { + "url": "https://github.com/Sebmaster/tr46.js/issues" + }, + "homepage": "https://github.com/Sebmaster/tr46.js#readme", + "devDependencies": { + "mocha": "^2.2.5", + "request": "^2.57.0" + } +} diff --git a/node_modules/node-fetch/node_modules/webidl-conversions/LICENSE.md b/node_modules/node-fetch/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 0000000..d4a994f --- /dev/null +++ b/node_modules/node-fetch/node_modules/webidl-conversions/LICENSE.md @@ -0,0 +1,12 @@ +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/node-fetch/node_modules/webidl-conversions/README.md b/node_modules/node-fetch/node_modules/webidl-conversions/README.md new file mode 100644 index 0000000..3657890 --- /dev/null +++ b/node_modules/node-fetch/node_modules/webidl-conversions/README.md @@ -0,0 +1,53 @@ +# WebIDL Type Conversions on JavaScript Values + +This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [WebIDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). + +The goal is that you should be able to write code like + +```js +const conversions = require("webidl-conversions"); + +function doStuff(x, y) { + x = conversions["boolean"](x); + y = conversions["unsigned long"](y); + // actual algorithm code here +} +``` + +and your function `doStuff` will behave the same as a WebIDL operation declared as + +```webidl +void doStuff(boolean x, unsigned long y); +``` + +## API + +This package's main module's default export is an object with a variety of methods, each corresponding to a different WebIDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the WebIDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the WebIDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). + +## Status + +All of the numeric types are implemented (float being implemented as double) and some others are as well - check the source for all of them. This list will grow over time in service of the [HTML as Custom Elements](https://github.com/dglazkov/html-as-custom-elements) project, but in the meantime, pull requests welcome! + +I'm not sure yet what the strategy will be for modifiers, e.g. [`[Clamp]`](http://heycam.github.io/webidl/#Clamp). Maybe something like `conversions["unsigned long"](x, { clamp: true })`? We'll see. + +We might also want to extend the API to give better error messages, e.g. "Argument 1 of HTMLMediaElement.fastSeek is not a finite floating-point value" instead of "Argument is not a finite floating-point value." This would require passing in more information to the conversion functions than we currently do. + +## Background + +What's actually going on here, conceptually, is pretty weird. Let's try to explain. + +WebIDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on WebIDL values, i.e. instances of WebIDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a WebIDL value of [WebIDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. + +Separately from its type system, WebIDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given WebIDL operation, how does that get converted into a WebIDL value? For example, a JavaScript `true` passed in the position of a WebIDL `boolean` argument becomes a WebIDL `true`. But, a JavaScript `true` passed in the position of a [WebIDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a WebIDL `1`. And so on. + +Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the WebIDL algorithms, they don't actually use WebIDL values, since those aren't "real" outside of specs. Instead, implementations apply the WebIDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. + +The upside of all this is that implementations can abstract all the conversion logic away, letting WebIDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of WebIDL, in a nutshell. + +And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given WebIDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ WebIDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ WebIDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a WebIDL `1` in an unsigned long context, which then becomes a JavaScript `1`. + +## Don't Use This + +Seriously, why would you ever use this? You really shouldn't. WebIDL is … not great, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from WebIDL. In general, your JavaScript should not be trying to become more like WebIDL; if anything, we should fix WebIDL to make it more like JavaScript. + +The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in WebIDL. diff --git a/node_modules/node-fetch/node_modules/webidl-conversions/lib/index.js b/node_modules/node-fetch/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 0000000..c5153a3 --- /dev/null +++ b/node_modules/node-fetch/node_modules/webidl-conversions/lib/index.js @@ -0,0 +1,189 @@ +"use strict"; + +var conversions = {}; +module.exports = conversions; + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function evenRound(x) { + // Round x to the nearest integer, choosing the even integer if it lies halfway between two. + if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) + return Math.floor(x); + } else { + return Math.round(x); + } +} + +function createNumberConversion(bitLength, typeOpts) { + if (!typeOpts.unsigned) { + --bitLength; + } + const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); + const upperBound = Math.pow(2, bitLength) - 1; + + const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); + const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); + + return function(V, opts) { + if (!opts) opts = {}; + + let x = +V; + + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite number"); + } + + x = sign(x) * Math.floor(Math.abs(x)); + if (x < lowerBound || x > upperBound) { + throw new TypeError("Argument is not in byte range"); + } + + return x; + } + + if (!isNaN(x) && opts.clamp) { + x = evenRound(x); + + if (x < lowerBound) x = lowerBound; + if (x > upperBound) x = upperBound; + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + + x = sign(x) * Math.floor(Math.abs(x)); + x = x % moduloVal; + + if (!typeOpts.unsigned && x >= moduloBound) { + return x - moduloVal; + } else if (typeOpts.unsigned) { + if (x < 0) { + x += moduloVal; + } else if (x === -0) { // don't return negative zero + return 0; + } + } + + return x; + } +} + +conversions["void"] = function () { + return undefined; +}; + +conversions["boolean"] = function (val) { + return !!val; +}; + +conversions["byte"] = createNumberConversion(8, { unsigned: false }); +conversions["octet"] = createNumberConversion(8, { unsigned: true }); + +conversions["short"] = createNumberConversion(16, { unsigned: false }); +conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); + +conversions["long"] = createNumberConversion(32, { unsigned: false }); +conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); + +conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); +conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); + +conversions["double"] = function (V) { + const x = +V; + + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite floating-point value"); + } + + return x; +}; + +conversions["unrestricted double"] = function (V) { + const x = +V; + + if (isNaN(x)) { + throw new TypeError("Argument is NaN"); + } + + return x; +}; + +// not quite valid, but good enough for JS +conversions["float"] = conversions["double"]; +conversions["unrestricted float"] = conversions["unrestricted double"]; + +conversions["DOMString"] = function (V, opts) { + if (!opts) opts = {}; + + if (opts.treatNullAsEmptyString && V === null) { + return ""; + } + + return String(V); +}; + +conversions["ByteString"] = function (V, opts) { + const x = String(V); + let c = undefined; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw new TypeError("Argument is not a valid bytestring"); + } + } + + return x; +}; + +conversions["USVString"] = function (V) { + const S = String(V); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + } + + return U.join(''); +}; + +conversions["Date"] = function (V, opts) { + if (!(V instanceof Date)) { + throw new TypeError("Argument is not a Date object"); + } + if (isNaN(V)) { + return undefined; + } + + return V; +}; + +conversions["RegExp"] = function (V, opts) { + if (!(V instanceof RegExp)) { + V = new RegExp(V); + } + + return V; +}; diff --git a/node_modules/node-fetch/node_modules/webidl-conversions/package.json b/node_modules/node-fetch/node_modules/webidl-conversions/package.json new file mode 100644 index 0000000..c31bc07 --- /dev/null +++ b/node_modules/node-fetch/node_modules/webidl-conversions/package.json @@ -0,0 +1,23 @@ +{ + "name": "webidl-conversions", + "version": "3.0.1", + "description": "Implements the WebIDL algorithms for converting to and from JavaScript values", + "main": "lib/index.js", + "scripts": { + "test": "mocha test/*.js" + }, + "repository": "jsdom/webidl-conversions", + "keywords": [ + "webidl", + "web", + "types" + ], + "files": [ + "lib/" + ], + "author": "Domenic Denicola (https://domenic.me/)", + "license": "BSD-2-Clause", + "devDependencies": { + "mocha": "^1.21.4" + } +} diff --git a/node_modules/node-fetch/node_modules/whatwg-url/LICENSE.txt b/node_modules/node-fetch/node_modules/whatwg-url/LICENSE.txt new file mode 100644 index 0000000..54dfac3 --- /dev/null +++ b/node_modules/node-fetch/node_modules/whatwg-url/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015–2016 Sebastian Mayr + +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/node-fetch/node_modules/whatwg-url/README.md b/node_modules/node-fetch/node_modules/whatwg-url/README.md new file mode 100644 index 0000000..4347a7f --- /dev/null +++ b/node_modules/node-fetch/node_modules/whatwg-url/README.md @@ -0,0 +1,67 @@ +# whatwg-url + +whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). + +## Current Status + +whatwg-url is currently up to date with the URL spec up to commit [a62223](https://github.com/whatwg/url/commit/a622235308342c9adc7fc2fd1659ff059f7d5e2a). + +## API + +### The `URL` Constructor + +The main API is the [`URL`](https://url.spec.whatwg.org/#url) export, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use this. + +### Low-level URL Standard API + +The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. + +- [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` +- [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` +- [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` +- [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` +- [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` +- [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/browsers.html#serialization-of-an-origin): `serializeURLOrigin(urlRecord)` +- [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` +- [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` +- [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` + +The `stateOverride` parameter is one of the following strings: + +- [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) +- [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) +- [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) +- [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) +- [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) +- [`"relative"`](https://url.spec.whatwg.org/#relative-state) +- [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) +- [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) +- [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) +- [`"authority"`](https://url.spec.whatwg.org/#authority-state) +- [`"host"`](https://url.spec.whatwg.org/#host-state) +- [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) +- [`"port"`](https://url.spec.whatwg.org/#port-state) +- [`"file"`](https://url.spec.whatwg.org/#file-state) +- [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) +- [`"file host"`](https://url.spec.whatwg.org/#file-host-state) +- [`"path start"`](https://url.spec.whatwg.org/#path-start-state) +- [`"path"`](https://url.spec.whatwg.org/#path-state) +- [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) +- [`"query"`](https://url.spec.whatwg.org/#query-state) +- [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) + +The URL record type has the following API: + +- [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) +- [`username`](https://url.spec.whatwg.org/#concept-url-username) +- [`password`](https://url.spec.whatwg.org/#concept-url-password) +- [`host`](https://url.spec.whatwg.org/#concept-url-host) +- [`port`](https://url.spec.whatwg.org/#concept-url-port) +- [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) +- [`query`](https://url.spec.whatwg.org/#concept-url-query) +- [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) +- [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) + +These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. + +The return value of "failure" in the spec is represented by the string `"failure"`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ the string `"failure"`. diff --git a/node_modules/node-fetch/node_modules/whatwg-url/lib/URL-impl.js b/node_modules/node-fetch/node_modules/whatwg-url/lib/URL-impl.js new file mode 100644 index 0000000..dc7452c --- /dev/null +++ b/node_modules/node-fetch/node_modules/whatwg-url/lib/URL-impl.js @@ -0,0 +1,200 @@ +"use strict"; +const usm = require("./url-state-machine"); + +exports.implementation = class URLImpl { + constructor(constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === "failure") { + throw new TypeError("Invalid base URL"); + } + } + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + + // TODO: query stuff + } + + get href() { + return usm.serializeURL(this._url); + } + + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + } + + get origin() { + return usm.serializeURLOrigin(this._url); + } + + get protocol() { + return this._url.scheme + ":"; + } + + set protocol(v) { + usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; + } + + if (url.port === null) { + return usm.serializeHost(url.host); + } + + return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); + } + + set host(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; + } + + return usm.serializeHost(this._url.host); + } + + set hostname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; + } + + return usm.serializeInteger(this._url.port); + } + + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } + + get pathname() { + if (this._url.cannotBeABaseURL) { + return this._url.path[0]; + } + + if (this._url.path.length === 0) { + return ""; + } + + return "/" + this._url.path.join("/"); + } + + set pathname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } + + return "?" + this._url.query; + } + + set search(v) { + // TODO: query stuff + + const url = this._url; + + if (v === "") { + url.query = null; + return; + } + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } + + return "#" + this._url.fragment; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } +}; diff --git a/node_modules/node-fetch/node_modules/whatwg-url/lib/URL.js b/node_modules/node-fetch/node_modules/whatwg-url/lib/URL.js new file mode 100644 index 0000000..78c7207 --- /dev/null +++ b/node_modules/node-fetch/node_modules/whatwg-url/lib/URL.js @@ -0,0 +1,196 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); +const Impl = require(".//URL-impl.js"); + +const impl = utils.implSymbol; + +function URL(url) { + if (!this || this[impl] || !(this instanceof URL)) { + throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); + } + if (arguments.length < 1) { + throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); + } + const args = []; + for (let i = 0; i < arguments.length && i < 2; ++i) { + args[i] = arguments[i]; + } + args[0] = conversions["USVString"](args[0]); + if (args[1] !== undefined) { + args[1] = conversions["USVString"](args[1]); + } + + module.exports.setup(this, args); +} + +URL.prototype.toJSON = function toJSON() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + const args = []; + for (let i = 0; i < arguments.length && i < 0; ++i) { + args[i] = arguments[i]; + } + return this[impl].toJSON.apply(this[impl], args); +}; +Object.defineProperty(URL.prototype, "href", { + get() { + return this[impl].href; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].href = V; + }, + enumerable: true, + configurable: true +}); + +URL.prototype.toString = function () { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return this.href; +}; + +Object.defineProperty(URL.prototype, "origin", { + get() { + return this[impl].origin; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "protocol", { + get() { + return this[impl].protocol; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].protocol = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "username", { + get() { + return this[impl].username; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].username = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "password", { + get() { + return this[impl].password; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].password = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "host", { + get() { + return this[impl].host; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].host = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hostname", { + get() { + return this[impl].hostname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hostname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "port", { + get() { + return this[impl].port; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].port = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "pathname", { + get() { + return this[impl].pathname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].pathname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "search", { + get() { + return this[impl].search; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].search = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hash", { + get() { + return this[impl].hash; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hash = V; + }, + enumerable: true, + configurable: true +}); + + +module.exports = { + is(obj) { + return !!obj && obj[impl] instanceof Impl.implementation; + }, + create(constructorArgs, privateData) { + let obj = Object.create(URL.prototype); + this.setup(obj, constructorArgs, privateData); + return obj; + }, + setup(obj, constructorArgs, privateData) { + if (!privateData) privateData = {}; + privateData.wrapper = obj; + + obj[impl] = new Impl.implementation(constructorArgs, privateData); + obj[impl][utils.wrapperSymbol] = obj; + }, + interface: URL, + expose: { + Window: { URL: URL }, + Worker: { URL: URL } + } +}; + diff --git a/node_modules/node-fetch/node_modules/whatwg-url/lib/public-api.js b/node_modules/node-fetch/node_modules/whatwg-url/lib/public-api.js new file mode 100644 index 0000000..932dcad --- /dev/null +++ b/node_modules/node-fetch/node_modules/whatwg-url/lib/public-api.js @@ -0,0 +1,11 @@ +"use strict"; + +exports.URL = require("./URL").interface; +exports.serializeURL = require("./url-state-machine").serializeURL; +exports.serializeURLOrigin = require("./url-state-machine").serializeURLOrigin; +exports.basicURLParse = require("./url-state-machine").basicURLParse; +exports.setTheUsername = require("./url-state-machine").setTheUsername; +exports.setThePassword = require("./url-state-machine").setThePassword; +exports.serializeHost = require("./url-state-machine").serializeHost; +exports.serializeInteger = require("./url-state-machine").serializeInteger; +exports.parseURL = require("./url-state-machine").parseURL; diff --git a/node_modules/node-fetch/node_modules/whatwg-url/lib/url-state-machine.js b/node_modules/node-fetch/node_modules/whatwg-url/lib/url-state-machine.js new file mode 100644 index 0000000..27d977a --- /dev/null +++ b/node_modules/node-fetch/node_modules/whatwg-url/lib/url-state-machine.js @@ -0,0 +1,1297 @@ +"use strict"; +const punycode = require("punycode"); +const tr46 = require("tr46"); + +const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return punycode.ucs2.decode(str).length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) { // do nothing + } else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; diff --git a/node_modules/node-fetch/node_modules/whatwg-url/lib/utils.js b/node_modules/node-fetch/node_modules/whatwg-url/lib/utils.js new file mode 100644 index 0000000..a562009 --- /dev/null +++ b/node_modules/node-fetch/node_modules/whatwg-url/lib/utils.js @@ -0,0 +1,20 @@ +"use strict"; + +module.exports.mixin = function mixin(target, source) { + const keys = Object.getOwnPropertyNames(source); + for (let i = 0; i < keys.length; ++i) { + Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + } +}; + +module.exports.wrapperSymbol = Symbol("wrapper"); +module.exports.implSymbol = Symbol("impl"); + +module.exports.wrapperForImpl = function (impl) { + return impl[module.exports.wrapperSymbol]; +}; + +module.exports.implForWrapper = function (wrapper) { + return wrapper[module.exports.implSymbol]; +}; + diff --git a/node_modules/node-fetch/node_modules/whatwg-url/package.json b/node_modules/node-fetch/node_modules/whatwg-url/package.json new file mode 100644 index 0000000..fce35ae --- /dev/null +++ b/node_modules/node-fetch/node_modules/whatwg-url/package.json @@ -0,0 +1,32 @@ +{ + "name": "whatwg-url", + "version": "5.0.0", + "description": "An implementation of the WHATWG URL Standard's URL API and parsing machinery", + "main": "lib/public-api.js", + "files": [ + "lib/" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "repository": "jsdom/whatwg-url", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + }, + "devDependencies": { + "eslint": "^2.6.0", + "istanbul": "~0.4.3", + "mocha": "^2.2.4", + "recast": "~0.10.29", + "request": "^2.55.0", + "webidl2js": "^3.0.2" + }, + "scripts": { + "build": "node scripts/transform.js && node scripts/convert-idl.js", + "coverage": "istanbul cover node_modules/mocha/bin/_mocha", + "lint": "eslint .", + "prepublish": "npm run build", + "pretest": "node scripts/get-latest-platform-tests.js && npm run build", + "test": "mocha" + } +} diff --git a/node_modules/node-fetch/package.json b/node_modules/node-fetch/package.json new file mode 100644 index 0000000..ec05105 --- /dev/null +++ b/node_modules/node-fetch/package.json @@ -0,0 +1,68 @@ +{ + "name": "node-fetch", + "version": "2.6.6", + "description": "A light-weight module that brings window.fetch to node.js", + "main": "lib/index.js", + "browser": "./browser.js", + "module": "lib/index.mjs", + "files": [ + "lib/index.js", + "lib/index.mjs", + "lib/index.es.js", + "browser.js" + ], + "engines": { + "node": "4.x || >=6.0.0" + }, + "scripts": { + "build": "cross-env BABEL_ENV=rollup rollup -c", + "prepare": "npm run build", + "test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js", + "report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js", + "coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitinn/node-fetch.git" + }, + "keywords": [ + "fetch", + "http", + "promise" + ], + "author": "David Frank", + "license": "MIT", + "bugs": { + "url": "https://github.com/bitinn/node-fetch/issues" + }, + "homepage": "https://github.com/bitinn/node-fetch", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "devDependencies": { + "@ungap/url-search-params": "^0.1.2", + "abort-controller": "^1.1.0", + "abortcontroller-polyfill": "^1.3.0", + "babel-core": "^6.26.3", + "babel-plugin-istanbul": "^4.1.6", + "babel-preset-env": "^1.6.1", + "babel-register": "^6.16.3", + "chai": "^3.5.0", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^1.1.1", + "chai-string": "~1.3.0", + "codecov": "3.3.0", + "cross-env": "^5.2.0", + "form-data": "^2.3.3", + "is-builtin-module": "^1.0.0", + "mocha": "^5.0.0", + "nyc": "11.9.0", + "parted": "^0.1.1", + "promise": "^8.0.3", + "resumer": "0.0.0", + "rollup": "^0.63.4", + "rollup-plugin-babel": "^3.0.7", + "string-to-arraybuffer": "^1.0.2", + "teeny-request": "3.7.0" + } +} diff --git a/node_modules/nopt/CHANGELOG.md b/node_modules/nopt/CHANGELOG.md new file mode 100644 index 0000000..82a09fb --- /dev/null +++ b/node_modules/nopt/CHANGELOG.md @@ -0,0 +1,58 @@ +### v4.0.1 (2016-12-14) + +#### WHOOPS + +* [`fb9b1ce`](https://github.com/npm/nopt/commit/fb9b1ce57b3c69b4f7819015be87719204f77ef6) + Merged so many patches at once that the code fencing + ([@adius](https://github.com/adius)) added got broken. Sorry, + ([@adius](https://github.com/adius))! + ([@othiym23](https://github.com/othiym23)) + +### v4.0.0 (2016-12-13) + +#### BREAKING CHANGES + +* [`651d447`](https://github.com/npm/nopt/commit/651d4473946096d341a480bbe56793de3fc706aa) + When parsing String-typed arguments, if the next value is `""`, don't simply + swallow it. ([@samjonester](https://github.com/samjonester)) + +#### PERFORMANCE TWEAKS + +* [`3370ce8`](https://github.com/npm/nopt/commit/3370ce87a7618ba228883861db84ddbcdff252a9) + Simplify initialization. ([@elidoran](https://github.com/elidoran)) +* [`356e58e`](https://github.com/npm/nopt/commit/356e58e3b3b431a4b1af7fd7bdee44c2c0526a09) + Store `Array.isArray(types[arg])` for reuse. + ([@elidoran](https://github.com/elidoran)) +* [`0d95e90`](https://github.com/npm/nopt/commit/0d95e90515844f266015b56d2c80b94e5d14a07e) + Interpret single-item type arrays as a single type. + ([@samjonester](https://github.com/samjonester)) +* [`07c69d3`](https://github.com/npm/nopt/commit/07c69d38b5186450941fbb505550becb78a0e925) + Simplify key-value extraction. ([@elidoran](https://github.com/elidoran)) +* [`39b6e5c`](https://github.com/npm/nopt/commit/39b6e5c65ac47f60cd43a1fbeece5cd4c834c254) + Only call `Date.parse(val)` once. ([@elidoran](https://github.com/elidoran)) +* [`934943d`](https://github.com/npm/nopt/commit/934943dffecb55123a2b15959fe2a359319a5dbd) + Use `osenv.home()` to find a user's home directory instead of assuming it's + always `$HOME`. ([@othiym23](https://github.com/othiym23)) + +#### TEST & CI IMPROVEMENTS + +* [`326ffff`](https://github.com/npm/nopt/commit/326ffff7f78a00bcd316adecf69075f8a8093619) + Fix `/tmp` test to work on Windows. + ([@elidoran](https://github.com/elidoran)) +* [`c89d31a`](https://github.com/npm/nopt/commit/c89d31a49d14f2238bc6672db08da697bbc57f1b) + Only run Windows tests on Windows, only run Unix tests on a Unix. + ([@elidoran](https://github.com/elidoran)) +* [`affd3d1`](https://github.com/npm/nopt/commit/affd3d1d0addffa93006397b2013b18447339366) + Refresh Travis to run the tests against the currently-supported batch of npm + versions. ([@helio](https://github.com/helio)-frota) +* [`55f9449`](https://github.com/npm/nopt/commit/55f94497d163ed4d16dd55fd6c4fb95cc440e66d) + `tap@8.0.1` ([@othiym23](https://github.com/othiym23)) + +#### DOC TWEAKS + +* [`5271229`](https://github.com/npm/nopt/commit/5271229ee7c810217dd51616c086f5d9ab224581) + Use JavaScript code block for syntax highlighting. + ([@adius](https://github.com/adius)) +* [`c0d156f`](https://github.com/npm/nopt/commit/c0d156f229f9994c5dfcec4a8886eceff7a07682) + The code sample in the README had `many2: [ oneThing ]`, and now it has + `many2: [ two, things ]`. ([@silkentrance](https://github.com/silkentrance)) diff --git a/node_modules/nopt/LICENSE b/node_modules/nopt/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/nopt/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/nopt/README.md b/node_modules/nopt/README.md new file mode 100644 index 0000000..a99531c --- /dev/null +++ b/node_modules/nopt/README.md @@ -0,0 +1,213 @@ +If you want to write an option parser, and have it be good, there are +two ways to do it. The Right Way, and the Wrong Way. + +The Wrong Way is to sit down and write an option parser. We've all done +that. + +The Right Way is to write some complex configurable program with so many +options that you hit the limit of your frustration just trying to +manage them all, and defer it with duct-tape solutions until you see +exactly to the core of the problem, and finally snap and write an +awesome option parser. + +If you want to write an option parser, don't write an option parser. +Write a package manager, or a source control system, or a service +restarter, or an operating system. You probably won't end up with a +good one of those, but if you don't give up, and you are relentless and +diligent enough in your procrastination, you may just end up with a very +nice option parser. + +## USAGE + +```javascript +// my-program.js +var nopt = require("nopt") + , Stream = require("stream").Stream + , path = require("path") + , knownOpts = { "foo" : [String, null] + , "bar" : [Stream, Number] + , "baz" : path + , "bloo" : [ "big", "medium", "small" ] + , "flag" : Boolean + , "pick" : Boolean + , "many1" : [String, Array] + , "many2" : [path, Array] + } + , shortHands = { "foofoo" : ["--foo", "Mr. Foo"] + , "b7" : ["--bar", "7"] + , "m" : ["--bloo", "medium"] + , "p" : ["--pick"] + , "f" : ["--flag"] + } + // everything is optional. + // knownOpts and shorthands default to {} + // arg list defaults to process.argv + // slice defaults to 2 + , parsed = nopt(knownOpts, shortHands, process.argv, 2) +console.log(parsed) +``` + +This would give you support for any of the following: + +```console +$ node my-program.js --foo "blerp" --no-flag +{ "foo" : "blerp", "flag" : false } + +$ node my-program.js ---bar 7 --foo "Mr. Hand" --flag +{ bar: 7, foo: "Mr. Hand", flag: true } + +$ node my-program.js --foo "blerp" -f -----p +{ foo: "blerp", flag: true, pick: true } + +$ node my-program.js -fp --foofoo +{ foo: "Mr. Foo", flag: true, pick: true } + +$ node my-program.js --foofoo -- -fp # -- stops the flag parsing. +{ foo: "Mr. Foo", argv: { remain: ["-fp"] } } + +$ node my-program.js --blatzk -fp # unknown opts are ok. +{ blatzk: true, flag: true, pick: true } + +$ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value +{ blatzk: 1000, flag: true, pick: true } + +$ node my-program.js --no-blatzk -fp # unless they start with "no-" +{ blatzk: false, flag: true, pick: true } + +$ node my-program.js --baz b/a/z # known paths are resolved. +{ baz: "/Users/isaacs/b/a/z" } + +# if Array is one of the types, then it can take many +# values, and will always be an array. The other types provided +# specify what types are allowed in the list. + +$ node my-program.js --many1 5 --many1 null --many1 foo +{ many1: ["5", "null", "foo"] } + +$ node my-program.js --many2 foo --many2 bar +{ many2: ["/path/to/foo", "path/to/bar"] } +``` + +Read the tests at the bottom of `lib/nopt.js` for more examples of +what this puppy can do. + +## Types + +The following types are supported, and defined on `nopt.typeDefs` + +* String: A normal string. No parsing is done. +* path: A file system path. Gets resolved against cwd if not absolute. +* url: A url. If it doesn't parse, it isn't accepted. +* Number: Must be numeric. +* Date: Must parse as a date. If it does, and `Date` is one of the options, + then it will return a Date object, not a string. +* Boolean: Must be either `true` or `false`. If an option is a boolean, + then it does not need a value, and its presence will imply `true` as + the value. To negate boolean flags, do `--no-whatever` or `--whatever + false` +* NaN: Means that the option is strictly not allowed. Any value will + fail. +* Stream: An object matching the "Stream" class in node. Valuable + for use when validating programmatically. (npm uses this to let you + supply any WriteStream on the `outfd` and `logfd` config options.) +* Array: If `Array` is specified as one of the types, then the value + will be parsed as a list of options. This means that multiple values + can be specified, and that the value will always be an array. + +If a type is an array of values not on this list, then those are +considered valid values. For instance, in the example above, the +`--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`, +and any other value will be rejected. + +When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be +interpreted as their JavaScript equivalents. + +You can also mix types and values, or multiple types, in a list. For +instance `{ blah: [Number, null] }` would allow a value to be set to +either a Number or null. When types are ordered, this implies a +preference, and the first type that can be used to properly interpret +the value will be used. + +To define a new type, add it to `nopt.typeDefs`. Each item in that +hash is an object with a `type` member and a `validate` method. The +`type` member is an object that matches what goes in the type list. The +`validate` method is a function that gets called with `validate(data, +key, val)`. Validate methods should assign `data[key]` to the valid +value of `val` if it can be handled properly, or return boolean +`false` if it cannot. + +You can also call `nopt.clean(data, types, typeDefs)` to clean up a +config object and remove its invalid properties. + +## Error Handling + +By default, nopt outputs a warning to standard error when invalid values for +known options are found. You can change this behavior by assigning a method +to `nopt.invalidHandler`. This method will be called with +the offending `nopt.invalidHandler(key, val, types)`. + +If no `nopt.invalidHandler` is assigned, then it will console.error +its whining. If it is assigned to boolean `false` then the warning is +suppressed. + +## Abbreviations + +Yes, they are supported. If you define options like this: + +```javascript +{ "foolhardyelephants" : Boolean +, "pileofmonkeys" : Boolean } +``` + +Then this will work: + +```bash +node program.js --foolhar --pil +node program.js --no-f --pileofmon +# etc. +``` + +## Shorthands + +Shorthands are a hash of shorter option names to a snippet of args that +they expand to. + +If multiple one-character shorthands are all combined, and the +combination does not unambiguously match any other option or shorthand, +then they will be broken up into their constituent parts. For example: + +```json +{ "s" : ["--loglevel", "silent"] +, "g" : "--global" +, "f" : "--force" +, "p" : "--parseable" +, "l" : "--long" +} +``` + +```bash +npm ls -sgflp +# just like doing this: +npm ls --loglevel silent --global --force --long --parseable +``` + +## The Rest of the args + +The config object returned by nopt is given a special member called +`argv`, which is an object with the following fields: + +* `remain`: The remaining args after all the parsing has occurred. +* `original`: The args as they originally appeared. +* `cooked`: The args after flags and shorthands are expanded. + +## Slicing + +Node programs are called with more or less the exact argv as it appears +in C land, after the v8 and node-specific options have been plucked off. +As such, `argv[0]` is always `node` and `argv[1]` is always the +JavaScript program being run. + +That's usually not very useful to you. So they're sliced off by +default. If you want them, then you can pass in `0` as the last +argument, or any other number that you'd like to slice off the start of +the list. diff --git a/node_modules/nopt/bin/nopt.js b/node_modules/nopt/bin/nopt.js new file mode 100644 index 0000000..3232d4c --- /dev/null +++ b/node_modules/nopt/bin/nopt.js @@ -0,0 +1,54 @@ +#!/usr/bin/env node +var nopt = require("../lib/nopt") + , path = require("path") + , types = { num: Number + , bool: Boolean + , help: Boolean + , list: Array + , "num-list": [Number, Array] + , "str-list": [String, Array] + , "bool-list": [Boolean, Array] + , str: String + , clear: Boolean + , config: Boolean + , length: Number + , file: path + } + , shorthands = { s: [ "--str", "astring" ] + , b: [ "--bool" ] + , nb: [ "--no-bool" ] + , tft: [ "--bool-list", "--no-bool-list", "--bool-list", "true" ] + , "?": ["--help"] + , h: ["--help"] + , H: ["--help"] + , n: [ "--num", "125" ] + , c: ["--config"] + , l: ["--length"] + , f: ["--file"] + } + , parsed = nopt( types + , shorthands + , process.argv + , 2 ) + +console.log("parsed", parsed) + +if (parsed.help) { + console.log("") + console.log("nopt cli tester") + console.log("") + console.log("types") + console.log(Object.keys(types).map(function M (t) { + var type = types[t] + if (Array.isArray(type)) { + return [t, type.map(function (type) { return type.name })] + } + return [t, type && type.name] + }).reduce(function (s, i) { + s[i[0]] = i[1] + return s + }, {})) + console.log("") + console.log("shorthands") + console.log(shorthands) +} diff --git a/node_modules/nopt/lib/nopt.js b/node_modules/nopt/lib/nopt.js new file mode 100644 index 0000000..ecfa5da --- /dev/null +++ b/node_modules/nopt/lib/nopt.js @@ -0,0 +1,441 @@ +// info about each config option. + +var debug = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG + ? function () { console.error.apply(console, arguments) } + : function () {} + +var url = require("url") + , path = require("path") + , Stream = require("stream").Stream + , abbrev = require("abbrev") + , os = require("os") + +module.exports = exports = nopt +exports.clean = clean + +exports.typeDefs = + { String : { type: String, validate: validateString } + , Boolean : { type: Boolean, validate: validateBoolean } + , url : { type: url, validate: validateUrl } + , Number : { type: Number, validate: validateNumber } + , path : { type: path, validate: validatePath } + , Stream : { type: Stream, validate: validateStream } + , Date : { type: Date, validate: validateDate } + } + +function nopt (types, shorthands, args, slice) { + args = args || process.argv + types = types || {} + shorthands = shorthands || {} + if (typeof slice !== "number") slice = 2 + + debug(types, shorthands, args, slice) + + args = args.slice(slice) + var data = {} + , key + , argv = { + remain: [], + cooked: args, + original: args.slice(0) + } + + parse(args, data, argv.remain, types, shorthands) + // now data is full + clean(data, types, exports.typeDefs) + data.argv = argv + Object.defineProperty(data.argv, 'toString', { value: function () { + return this.original.map(JSON.stringify).join(" ") + }, enumerable: false }) + return data +} + +function clean (data, types, typeDefs) { + typeDefs = typeDefs || exports.typeDefs + var remove = {} + , typeDefault = [false, true, null, String, Array] + + Object.keys(data).forEach(function (k) { + if (k === "argv") return + var val = data[k] + , isArray = Array.isArray(val) + , type = types[k] + if (!isArray) val = [val] + if (!type) type = typeDefault + if (type === Array) type = typeDefault.concat(Array) + if (!Array.isArray(type)) type = [type] + + debug("val=%j", val) + debug("types=", type) + val = val.map(function (val) { + // if it's an unknown value, then parse false/true/null/numbers/dates + if (typeof val === "string") { + debug("string %j", val) + val = val.trim() + if ((val === "null" && ~type.indexOf(null)) + || (val === "true" && + (~type.indexOf(true) || ~type.indexOf(Boolean))) + || (val === "false" && + (~type.indexOf(false) || ~type.indexOf(Boolean)))) { + val = JSON.parse(val) + debug("jsonable %j", val) + } else if (~type.indexOf(Number) && !isNaN(val)) { + debug("convert to number", val) + val = +val + } else if (~type.indexOf(Date) && !isNaN(Date.parse(val))) { + debug("convert to date", val) + val = new Date(val) + } + } + + if (!types.hasOwnProperty(k)) { + return val + } + + // allow `--no-blah` to set 'blah' to null if null is allowed + if (val === false && ~type.indexOf(null) && + !(~type.indexOf(false) || ~type.indexOf(Boolean))) { + val = null + } + + var d = {} + d[k] = val + debug("prevalidated val", d, val, types[k]) + if (!validate(d, k, val, types[k], typeDefs)) { + if (exports.invalidHandler) { + exports.invalidHandler(k, val, types[k], data) + } else if (exports.invalidHandler !== false) { + debug("invalid: "+k+"="+val, types[k]) + } + return remove + } + debug("validated val", d, val, types[k]) + return d[k] + }).filter(function (val) { return val !== remove }) + + // if we allow Array specifically, then an empty array is how we + // express 'no value here', not null. Allow it. + if (!val.length && type.indexOf(Array) === -1) { + debug('VAL HAS NO LENGTH, DELETE IT', val, k, type.indexOf(Array)) + delete data[k] + } + else if (isArray) { + debug(isArray, data[k], val) + data[k] = val + } else data[k] = val[0] + + debug("k=%s val=%j", k, val, data[k]) + }) +} + +function validateString (data, k, val) { + data[k] = String(val) +} + +function validatePath (data, k, val) { + if (val === true) return false + if (val === null) return true + + val = String(val) + + var isWin = process.platform === 'win32' + , homePattern = isWin ? /^~(\/|\\)/ : /^~\// + , home = os.homedir() + + if (home && val.match(homePattern)) { + data[k] = path.resolve(home, val.substr(2)) + } else { + data[k] = path.resolve(val) + } + return true +} + +function validateNumber (data, k, val) { + debug("validate Number %j %j %j", k, val, isNaN(val)) + if (isNaN(val)) return false + data[k] = +val +} + +function validateDate (data, k, val) { + var s = Date.parse(val) + debug("validate Date %j %j %j", k, val, s) + if (isNaN(s)) return false + data[k] = new Date(val) +} + +function validateBoolean (data, k, val) { + if (val instanceof Boolean) val = val.valueOf() + else if (typeof val === "string") { + if (!isNaN(val)) val = !!(+val) + else if (val === "null" || val === "false") val = false + else val = true + } else val = !!val + data[k] = val +} + +function validateUrl (data, k, val) { + val = url.parse(String(val)) + if (!val.host) return false + data[k] = val.href +} + +function validateStream (data, k, val) { + if (!(val instanceof Stream)) return false + data[k] = val +} + +function validate (data, k, val, type, typeDefs) { + // arrays are lists of types. + if (Array.isArray(type)) { + for (var i = 0, l = type.length; i < l; i ++) { + if (type[i] === Array) continue + if (validate(data, k, val, type[i], typeDefs)) return true + } + delete data[k] + return false + } + + // an array of anything? + if (type === Array) return true + + // NaN is poisonous. Means that something is not allowed. + if (type !== type) { + debug("Poison NaN", k, val, type) + delete data[k] + return false + } + + // explicit list of values + if (val === type) { + debug("Explicitly allowed %j", val) + // if (isArray) (data[k] = data[k] || []).push(val) + // else data[k] = val + data[k] = val + return true + } + + // now go through the list of typeDefs, validate against each one. + var ok = false + , types = Object.keys(typeDefs) + for (var i = 0, l = types.length; i < l; i ++) { + debug("test type %j %j %j", k, val, types[i]) + var t = typeDefs[types[i]] + if (t && + ((type && type.name && t.type && t.type.name) ? (type.name === t.type.name) : (type === t.type))) { + var d = {} + ok = false !== t.validate(d, k, val) + val = d[k] + if (ok) { + // if (isArray) (data[k] = data[k] || []).push(val) + // else data[k] = val + data[k] = val + break + } + } + } + debug("OK? %j (%j %j %j)", ok, k, val, types[i]) + + if (!ok) delete data[k] + return ok +} + +function parse (args, data, remain, types, shorthands) { + debug("parse", args, data, remain) + + var key = null + , abbrevs = abbrev(Object.keys(types)) + , shortAbbr = abbrev(Object.keys(shorthands)) + + for (var i = 0; i < args.length; i ++) { + var arg = args[i] + debug("arg", arg) + + if (arg.match(/^-{2,}$/)) { + // done with keys. + // the rest are args. + remain.push.apply(remain, args.slice(i + 1)) + args[i] = "--" + break + } + var hadEq = false + if (arg.charAt(0) === "-" && arg.length > 1) { + var at = arg.indexOf('=') + if (at > -1) { + hadEq = true + var v = arg.substr(at + 1) + arg = arg.substr(0, at) + args.splice(i, 1, arg, v) + } + + // see if it's a shorthand + // if so, splice and back up to re-parse it. + var shRes = resolveShort(arg, shorthands, shortAbbr, abbrevs) + debug("arg=%j shRes=%j", arg, shRes) + if (shRes) { + debug(arg, shRes) + args.splice.apply(args, [i, 1].concat(shRes)) + if (arg !== shRes[0]) { + i -- + continue + } + } + arg = arg.replace(/^-+/, "") + var no = null + while (arg.toLowerCase().indexOf("no-") === 0) { + no = !no + arg = arg.substr(3) + } + + if (abbrevs[arg]) arg = abbrevs[arg] + + var argType = types[arg] + var isTypeArray = Array.isArray(argType) + if (isTypeArray && argType.length === 1) { + isTypeArray = false + argType = argType[0] + } + + var isArray = argType === Array || + isTypeArray && argType.indexOf(Array) !== -1 + + // allow unknown things to be arrays if specified multiple times. + if (!types.hasOwnProperty(arg) && data.hasOwnProperty(arg)) { + if (!Array.isArray(data[arg])) + data[arg] = [data[arg]] + isArray = true + } + + var val + , la = args[i + 1] + + var isBool = typeof no === 'boolean' || + argType === Boolean || + isTypeArray && argType.indexOf(Boolean) !== -1 || + (typeof argType === 'undefined' && !hadEq) || + (la === "false" && + (argType === null || + isTypeArray && ~argType.indexOf(null))) + + if (isBool) { + // just set and move along + val = !no + // however, also support --bool true or --bool false + if (la === "true" || la === "false") { + val = JSON.parse(la) + la = null + if (no) val = !val + i ++ + } + + // also support "foo":[Boolean, "bar"] and "--foo bar" + if (isTypeArray && la) { + if (~argType.indexOf(la)) { + // an explicit type + val = la + i ++ + } else if ( la === "null" && ~argType.indexOf(null) ) { + // null allowed + val = null + i ++ + } else if ( !la.match(/^-{2,}[^-]/) && + !isNaN(la) && + ~argType.indexOf(Number) ) { + // number + val = +la + i ++ + } else if ( !la.match(/^-[^-]/) && ~argType.indexOf(String) ) { + // string + val = la + i ++ + } + } + + if (isArray) (data[arg] = data[arg] || []).push(val) + else data[arg] = val + + continue + } + + if (argType === String) { + if (la === undefined) { + la = "" + } else if (la.match(/^-{1,2}[^-]+/)) { + la = "" + i -- + } + } + + if (la && la.match(/^-{2,}$/)) { + la = undefined + i -- + } + + val = la === undefined ? true : la + if (isArray) (data[arg] = data[arg] || []).push(val) + else data[arg] = val + + i ++ + continue + } + remain.push(arg) + } +} + +function resolveShort (arg, shorthands, shortAbbr, abbrevs) { + // handle single-char shorthands glommed together, like + // npm ls -glp, but only if there is one dash, and only if + // all of the chars are single-char shorthands, and it's + // not a match to some other abbrev. + arg = arg.replace(/^-+/, '') + + // if it's an exact known option, then don't go any further + if (abbrevs[arg] === arg) + return null + + // if it's an exact known shortopt, same deal + if (shorthands[arg]) { + // make it an array, if it's a list of words + if (shorthands[arg] && !Array.isArray(shorthands[arg])) + shorthands[arg] = shorthands[arg].split(/\s+/) + + return shorthands[arg] + } + + // first check to see if this arg is a set of single-char shorthands + var singles = shorthands.___singles + if (!singles) { + singles = Object.keys(shorthands).filter(function (s) { + return s.length === 1 + }).reduce(function (l,r) { + l[r] = true + return l + }, {}) + shorthands.___singles = singles + debug('shorthand singles', singles) + } + + var chrs = arg.split("").filter(function (c) { + return singles[c] + }) + + if (chrs.join("") === arg) return chrs.map(function (c) { + return shorthands[c] + }).reduce(function (l, r) { + return l.concat(r) + }, []) + + + // if it's an arg abbrev, and not a literal shorthand, then prefer the arg + if (abbrevs[arg] && !shorthands[arg]) + return null + + // if it's an abbr for a shorthand, then use that + if (shortAbbr[arg]) + arg = shortAbbr[arg] + + // make it an array, if it's a list of words + if (shorthands[arg] && !Array.isArray(shorthands[arg])) + shorthands[arg] = shorthands[arg].split(/\s+/) + + return shorthands[arg] +} diff --git a/node_modules/nopt/package.json b/node_modules/nopt/package.json new file mode 100644 index 0000000..12ed02d --- /dev/null +++ b/node_modules/nopt/package.json @@ -0,0 +1,34 @@ +{ + "name": "nopt", + "version": "5.0.0", + "description": "Option parsing for Node, supporting types, shorthands, etc. Used by npm.", + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "main": "lib/nopt.js", + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/npm/nopt.git" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "license": "ISC", + "dependencies": { + "abbrev": "1" + }, + "devDependencies": { + "tap": "^14.10.6" + }, + "files": [ + "bin", + "lib" + ], + "engines": { + "node": ">=6" + } +} diff --git a/node_modules/npmlog/LICENSE b/node_modules/npmlog/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/npmlog/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/npmlog/README.md b/node_modules/npmlog/README.md new file mode 100644 index 0000000..268a4af --- /dev/null +++ b/node_modules/npmlog/README.md @@ -0,0 +1,216 @@ +# npmlog + +The logger util that npm uses. + +This logger is very basic. It does the logging for npm. It supports +custom levels and colored output. + +By default, logs are written to stderr. If you want to send log messages +to outputs other than streams, then you can change the `log.stream` +member, or you can just listen to the events that it emits, and do +whatever you want with them. + +# Installation + +```console +npm install npmlog --save +``` + +# Basic Usage + +```javascript +var log = require('npmlog') + +// additional stuff ---------------------------+ +// message ----------+ | +// prefix ----+ | | +// level -+ | | | +// v v v v + log.info('fyi', 'I have a kitty cat: %j', myKittyCat) +``` + +## log.level + +* {String} + +The level to display logs at. Any logs at or above this level will be +displayed. The special level `silent` will prevent anything from being +displayed ever. + +## log.record + +* {Array} + +An array of all the log messages that have been entered. + +## log.maxRecordSize + +* {Number} + +The maximum number of records to keep. If log.record gets bigger than +10% over this value, then it is sliced down to 90% of this value. + +The reason for the 10% window is so that it doesn't have to resize a +large array on every log entry. + +## log.prefixStyle + +* {Object} + +A style object that specifies how prefixes are styled. (See below) + +## log.headingStyle + +* {Object} + +A style object that specifies how the heading is styled. (See below) + +## log.heading + +* {String} Default: "" + +If set, a heading that is printed at the start of every line. + +## log.stream + +* {Stream} Default: `process.stderr` + +The stream where output is written. + +## log.enableColor() + +Force colors to be used on all messages, regardless of the output +stream. + +## log.disableColor() + +Disable colors on all messages. + +## log.enableProgress() + +Enable the display of log activity spinner and progress bar + +## log.disableProgress() + +Disable the display of a progress bar + +## log.enableUnicode() + +Force the unicode theme to be used for the progress bar. + +## log.disableUnicode() + +Disable the use of unicode in the progress bar. + +## log.setGaugeTemplate(template) + +Set a template for outputting the progress bar. See the [gauge documentation] for details. + +[gauge documentation]: https://npmjs.com/package/gauge + +## log.setGaugeThemeset(themes) + +Select a themeset to pick themes from for the progress bar. See the [gauge documentation] for details. + +## log.pause() + +Stop emitting messages to the stream, but do not drop them. + +## log.resume() + +Emit all buffered messages that were written while paused. + +## log.log(level, prefix, message, ...) + +* `level` {String} The level to emit the message at +* `prefix` {String} A string prefix. Set to "" to skip. +* `message...` Arguments to `util.format` + +Emit a log message at the specified level. + +## log\[level](prefix, message, ...) + +For example, + +* log.silly(prefix, message, ...) +* log.verbose(prefix, message, ...) +* log.info(prefix, message, ...) +* log.http(prefix, message, ...) +* log.warn(prefix, message, ...) +* log.error(prefix, message, ...) + +Like `log.log(level, prefix, message, ...)`. In this way, each level is +given a shorthand, so you can do `log.info(prefix, message)`. + +## log.addLevel(level, n, style, disp) + +* `level` {String} Level indicator +* `n` {Number} The numeric level +* `style` {Object} Object with fg, bg, inverse, etc. +* `disp` {String} Optional replacement for `level` in the output. + +Sets up a new level with a shorthand function and so forth. + +Note that if the number is `Infinity`, then setting the level to that +will cause all log messages to be suppressed. If the number is +`-Infinity`, then the only way to show it is to enable all log messages. + +## log.newItem(name, todo, weight) + +* `name` {String} Optional; progress item name. +* `todo` {Number} Optional; total amount of work to be done. Default 0. +* `weight` {Number} Optional; the weight of this item relative to others. Default 1. + +This adds a new `are-we-there-yet` item tracker to the progress tracker. The +object returned has the `log[level]` methods but is otherwise an +`are-we-there-yet` `Tracker` object. + +## log.newStream(name, todo, weight) + +This adds a new `are-we-there-yet` stream tracker to the progress tracker. The +object returned has the `log[level]` methods but is otherwise an +`are-we-there-yet` `TrackerStream` object. + +## log.newGroup(name, weight) + +This adds a new `are-we-there-yet` tracker group to the progress tracker. The +object returned has the `log[level]` methods but is otherwise an +`are-we-there-yet` `TrackerGroup` object. + +# Events + +Events are all emitted with the message object. + +* `log` Emitted for all messages +* `log.` Emitted for all messages with the `` level. +* `` Messages with prefixes also emit their prefix as an event. + +# Style Objects + +Style objects can have the following fields: + +* `fg` {String} Color for the foreground text +* `bg` {String} Color for the background +* `bold`, `inverse`, `underline` {Boolean} Set the associated property +* `bell` {Boolean} Make a noise (This is pretty annoying, probably.) + +# Message Objects + +Every log event is emitted with a message object, and the `log.record` +list contains all of them that have been created. They have the +following fields: + +* `id` {Number} +* `level` {String} +* `prefix` {String} +* `message` {String} Result of `util.format()` +* `messageRaw` {Array} Arguments to `util.format()` + +# Blocking TTYs + +We use [`set-blocking`](https://npmjs.com/package/set-blocking) to set +stderr and stdout blocking if they are tty's and have the setBlocking call. +This is a work around for an issue in early versions of Node.js 6.x, which +made stderr and stdout non-blocking on OSX. (They are always blocking +Windows and were never blocking on Linux.) `npmlog` needs them to be blocking +so that it can allow output to stdout and stderr to be interlaced. diff --git a/node_modules/npmlog/log.js b/node_modules/npmlog/log.js new file mode 100644 index 0000000..85ab8a4 --- /dev/null +++ b/node_modules/npmlog/log.js @@ -0,0 +1,403 @@ +'use strict' +var Progress = require('are-we-there-yet') +var Gauge = require('gauge') +var EE = require('events').EventEmitter +var log = exports = module.exports = new EE() +var util = require('util') + +var setBlocking = require('set-blocking') +var consoleControl = require('console-control-strings') + +setBlocking(true) +var stream = process.stderr +Object.defineProperty(log, 'stream', { + set: function (newStream) { + stream = newStream + if (this.gauge) { + this.gauge.setWriteTo(stream, stream) + } + }, + get: function () { + return stream + }, +}) + +// by default, decide based on tty-ness. +var colorEnabled +log.useColor = function () { + return colorEnabled != null ? colorEnabled : stream.isTTY +} + +log.enableColor = function () { + colorEnabled = true + this.gauge.setTheme({hasColor: colorEnabled, hasUnicode: unicodeEnabled}) +} +log.disableColor = function () { + colorEnabled = false + this.gauge.setTheme({hasColor: colorEnabled, hasUnicode: unicodeEnabled}) +} + +// default level +log.level = 'info' + +log.gauge = new Gauge(stream, { + enabled: false, // no progress bars unless asked + theme: {hasColor: log.useColor()}, + template: [ + {type: 'progressbar', length: 20}, + {type: 'activityIndicator', kerning: 1, length: 1}, + {type: 'section', default: ''}, + ':', + {type: 'logline', kerning: 1, default: ''}, + ], +}) + +log.tracker = new Progress.TrackerGroup() + +// we track this separately as we may need to temporarily disable the +// display of the status bar for our own loggy purposes. +log.progressEnabled = log.gauge.isEnabled() + +var unicodeEnabled + +log.enableUnicode = function () { + unicodeEnabled = true + this.gauge.setTheme({hasColor: this.useColor(), hasUnicode: unicodeEnabled}) +} + +log.disableUnicode = function () { + unicodeEnabled = false + this.gauge.setTheme({hasColor: this.useColor(), hasUnicode: unicodeEnabled}) +} + +log.setGaugeThemeset = function (themes) { + this.gauge.setThemeset(themes) +} + +log.setGaugeTemplate = function (template) { + this.gauge.setTemplate(template) +} + +log.enableProgress = function () { + if (this.progressEnabled) { + return + } + + this.progressEnabled = true + this.tracker.on('change', this.showProgress) + if (this._paused) { + return + } + + this.gauge.enable() +} + +log.disableProgress = function () { + if (!this.progressEnabled) { + return + } + this.progressEnabled = false + this.tracker.removeListener('change', this.showProgress) + this.gauge.disable() +} + +var trackerConstructors = ['newGroup', 'newItem', 'newStream'] + +var mixinLog = function (tracker) { + // mixin the public methods from log into the tracker + // (except: conflicts and one's we handle specially) + Object.keys(log).forEach(function (P) { + if (P[0] === '_') { + return + } + + if (trackerConstructors.filter(function (C) { + return C === P + }).length) { + return + } + + if (tracker[P]) { + return + } + + if (typeof log[P] !== 'function') { + return + } + + var func = log[P] + tracker[P] = function () { + return func.apply(log, arguments) + } + }) + // if the new tracker is a group, make sure any subtrackers get + // mixed in too + if (tracker instanceof Progress.TrackerGroup) { + trackerConstructors.forEach(function (C) { + var func = tracker[C] + tracker[C] = function () { + return mixinLog(func.apply(tracker, arguments)) + } + }) + } + return tracker +} + +// Add tracker constructors to the top level log object +trackerConstructors.forEach(function (C) { + log[C] = function () { + return mixinLog(this.tracker[C].apply(this.tracker, arguments)) + } +}) + +log.clearProgress = function (cb) { + if (!this.progressEnabled) { + return cb && process.nextTick(cb) + } + + this.gauge.hide(cb) +} + +log.showProgress = function (name, completed) { + if (!this.progressEnabled) { + return + } + + var values = {} + if (name) { + values.section = name + } + + var last = log.record[log.record.length - 1] + if (last) { + values.subsection = last.prefix + var disp = log.disp[last.level] || last.level + var logline = this._format(disp, log.style[last.level]) + if (last.prefix) { + logline += ' ' + this._format(last.prefix, this.prefixStyle) + } + + logline += ' ' + last.message.split(/\r?\n/)[0] + values.logline = logline + } + values.completed = completed || this.tracker.completed() + this.gauge.show(values) +}.bind(log) // bind for use in tracker's on-change listener + +// temporarily stop emitting, but don't drop +log.pause = function () { + this._paused = true + if (this.progressEnabled) { + this.gauge.disable() + } +} + +log.resume = function () { + if (!this._paused) { + return + } + + this._paused = false + + var b = this._buffer + this._buffer = [] + b.forEach(function (m) { + this.emitLog(m) + }, this) + if (this.progressEnabled) { + this.gauge.enable() + } +} + +log._buffer = [] + +var id = 0 +log.record = [] +log.maxRecordSize = 10000 +log.log = function (lvl, prefix, message) { + var l = this.levels[lvl] + if (l === undefined) { + return this.emit('error', new Error(util.format( + 'Undefined log level: %j', lvl))) + } + + var a = new Array(arguments.length - 2) + var stack = null + for (var i = 2; i < arguments.length; i++) { + var arg = a[i - 2] = arguments[i] + + // resolve stack traces to a plain string. + if (typeof arg === 'object' && arg instanceof Error && arg.stack) { + Object.defineProperty(arg, 'stack', { + value: stack = arg.stack + '', + enumerable: true, + writable: true, + }) + } + } + if (stack) { + a.unshift(stack + '\n') + } + message = util.format.apply(util, a) + + var m = { + id: id++, + level: lvl, + prefix: String(prefix || ''), + message: message, + messageRaw: a, + } + + this.emit('log', m) + this.emit('log.' + lvl, m) + if (m.prefix) { + this.emit(m.prefix, m) + } + + this.record.push(m) + var mrs = this.maxRecordSize + var n = this.record.length - mrs + if (n > mrs / 10) { + var newSize = Math.floor(mrs * 0.9) + this.record = this.record.slice(-1 * newSize) + } + + this.emitLog(m) +}.bind(log) + +log.emitLog = function (m) { + if (this._paused) { + this._buffer.push(m) + return + } + if (this.progressEnabled) { + this.gauge.pulse(m.prefix) + } + + var l = this.levels[m.level] + if (l === undefined) { + return + } + + if (l < this.levels[this.level]) { + return + } + + if (l > 0 && !isFinite(l)) { + return + } + + // If 'disp' is null or undefined, use the lvl as a default + // Allows: '', 0 as valid disp + var disp = log.disp[m.level] != null ? log.disp[m.level] : m.level + this.clearProgress() + m.message.split(/\r?\n/).forEach(function (line) { + if (this.heading) { + this.write(this.heading, this.headingStyle) + this.write(' ') + } + this.write(disp, log.style[m.level]) + var p = m.prefix || '' + if (p) { + this.write(' ') + } + + this.write(p, this.prefixStyle) + this.write(' ' + line + '\n') + }, this) + this.showProgress() +} + +log._format = function (msg, style) { + if (!stream) { + return + } + + var output = '' + if (this.useColor()) { + style = style || {} + var settings = [] + if (style.fg) { + settings.push(style.fg) + } + + if (style.bg) { + settings.push('bg' + style.bg[0].toUpperCase() + style.bg.slice(1)) + } + + if (style.bold) { + settings.push('bold') + } + + if (style.underline) { + settings.push('underline') + } + + if (style.inverse) { + settings.push('inverse') + } + + if (settings.length) { + output += consoleControl.color(settings) + } + + if (style.beep) { + output += consoleControl.beep() + } + } + output += msg + if (this.useColor()) { + output += consoleControl.color('reset') + } + + return output +} + +log.write = function (msg, style) { + if (!stream) { + return + } + + stream.write(this._format(msg, style)) +} + +log.addLevel = function (lvl, n, style, disp) { + // If 'disp' is null or undefined, use the lvl as a default + if (disp == null) { + disp = lvl + } + + this.levels[lvl] = n + this.style[lvl] = style + if (!this[lvl]) { + this[lvl] = function () { + var a = new Array(arguments.length + 1) + a[0] = lvl + for (var i = 0; i < arguments.length; i++) { + a[i + 1] = arguments[i] + } + + return this.log.apply(this, a) + }.bind(this) + } + this.disp[lvl] = disp +} + +log.prefixStyle = { fg: 'magenta' } +log.headingStyle = { fg: 'white', bg: 'black' } + +log.style = {} +log.levels = {} +log.disp = {} +log.addLevel('silly', -Infinity, { inverse: true }, 'sill') +log.addLevel('verbose', 1000, { fg: 'blue', bg: 'black' }, 'verb') +log.addLevel('info', 2000, { fg: 'green' }) +log.addLevel('timing', 2500, { fg: 'green', bg: 'black' }) +log.addLevel('http', 3000, { fg: 'green', bg: 'black' }) +log.addLevel('notice', 3500, { fg: 'blue', bg: 'black' }) +log.addLevel('warn', 4000, { fg: 'black', bg: 'yellow' }, 'WARN') +log.addLevel('error', 5000, { fg: 'red', bg: 'black' }, 'ERR!') +log.addLevel('silent', Infinity) + +// allow 'error' prefix +log.on('error', function () {}) diff --git a/node_modules/npmlog/package.json b/node_modules/npmlog/package.json new file mode 100644 index 0000000..960ea92 --- /dev/null +++ b/node_modules/npmlog/package.json @@ -0,0 +1,33 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "name": "npmlog", + "description": "logger for npm", + "version": "5.0.1", + "repository": { + "type": "git", + "url": "https://github.com/npm/npmlog.git" + }, + "main": "log.js", + "files": [ + "log.js" + ], + "scripts": { + "test": "tap test/*.js --branches=95", + "npmclilint": "npmcli-lint", + "lint": "npm run npmclilint -- \"*.*js\" \"test/**/*.*js\"", + "lintfix": "npm run lint -- --fix", + "posttest": "npm run lint --", + "postsnap": "npm run lintfix --" + }, + "dependencies": { + "are-we-there-yet": "^2.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^3.0.0", + "set-blocking": "^2.0.0" + }, + "devDependencies": { + "@npmcli/lint": "^1.0.1", + "tap": "^15.0.9" + }, + "license": "ISC" +} diff --git a/node_modules/object-assign/index.js b/node_modules/object-assign/index.js new file mode 100644 index 0000000..0930cf8 --- /dev/null +++ b/node_modules/object-assign/index.js @@ -0,0 +1,90 @@ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; diff --git a/node_modules/object-assign/license b/node_modules/object-assign/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/object-assign/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/object-assign/package.json b/node_modules/object-assign/package.json new file mode 100644 index 0000000..503eb1e --- /dev/null +++ b/node_modules/object-assign/package.json @@ -0,0 +1,42 @@ +{ + "name": "object-assign", + "version": "4.1.1", + "description": "ES2015 `Object.assign()` ponyfill", + "license": "MIT", + "repository": "sindresorhus/object-assign", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava", + "bench": "matcha bench.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "assign", + "extend", + "properties", + "es2015", + "ecmascript", + "harmony", + "ponyfill", + "prollyfill", + "polyfill", + "shim", + "browser" + ], + "devDependencies": { + "ava": "^0.16.0", + "lodash": "^4.16.4", + "matcha": "^0.7.0", + "xo": "^0.16.0" + } +} diff --git a/node_modules/object-assign/readme.md b/node_modules/object-assign/readme.md new file mode 100644 index 0000000..1be09d3 --- /dev/null +++ b/node_modules/object-assign/readme.md @@ -0,0 +1,61 @@ +# object-assign [![Build Status](https://travis-ci.org/sindresorhus/object-assign.svg?branch=master)](https://travis-ci.org/sindresorhus/object-assign) + +> ES2015 [`Object.assign()`](http://www.2ality.com/2014/01/object-assign.html) [ponyfill](https://ponyfill.com) + + +## Use the built-in + +Node.js 4 and up, as well as every evergreen browser (Chrome, Edge, Firefox, Opera, Safari), +support `Object.assign()` :tada:. If you target only those environments, then by all +means, use `Object.assign()` instead of this package. + + +## Install + +``` +$ npm install --save object-assign +``` + + +## Usage + +```js +const objectAssign = require('object-assign'); + +objectAssign({foo: 0}, {bar: 1}); +//=> {foo: 0, bar: 1} + +// multiple sources +objectAssign({foo: 0}, {bar: 1}, {baz: 2}); +//=> {foo: 0, bar: 1, baz: 2} + +// overwrites equal keys +objectAssign({foo: 0}, {foo: 1}, {foo: 2}); +//=> {foo: 2} + +// ignores null and undefined sources +objectAssign({foo: 0}, null, {bar: 1}, undefined); +//=> {foo: 0, bar: 1} +``` + + +## API + +### objectAssign(target, [source, ...]) + +Assigns enumerable own properties of `source` objects to the `target` object and returns the `target` object. Additional `source` objects will overwrite previous ones. + + +## Resources + +- [ES2015 spec - Object.assign](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign) + + +## Related + +- [deep-assign](https://github.com/sindresorhus/deep-assign) - Recursive `Object.assign()` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/on-finished/HISTORY.md b/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000..98ff0e9 --- /dev/null +++ b/node_modules/on-finished/HISTORY.md @@ -0,0 +1,88 @@ +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +2.2.1 / 2015-04-22 +================== + + * Fix `isFinished(req)` when data buffered + +2.2.0 / 2014-12-22 +================== + + * Add message object to callback arguments + +2.1.1 / 2014-10-22 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/node_modules/on-finished/LICENSE b/node_modules/on-finished/LICENSE new file mode 100644 index 0000000..5931fd2 --- /dev/null +++ b/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +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/on-finished/README.md b/node_modules/on-finished/README.md new file mode 100644 index 0000000..a0e1157 --- /dev/null +++ b/node_modules/on-finished/README.md @@ -0,0 +1,154 @@ +# on-finished + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to an error, the first argument will contain the error. If the response +has already finished, the listener will be invoked. + +Listening to the end of a response would be used to close things associated +with the response, like open files. + +Listener is invoked as `listener(err, res)`. + +```js +onFinished(res, function (err, res) { + // clean up open fds, etc. + // err contains the error is request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to an error, the first argument will contain the error. If the request +has already finished, the listener will be invoked. + +Listening to the end of a request would be used to know when to continue +after reading the data. + +Listener is invoked as `listener(err, req)`. + +```js +var data = '' + +req.setEncoding('utf8') +res.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest(req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/on-finished.svg +[npm-url]: https://npmjs.org/package/on-finished +[node-version-image]: https://img.shields.io/node/v/on-finished.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/on-finished/master.svg +[travis-url]: https://travis-ci.org/jshttp/on-finished +[coveralls-image]: https://img.shields.io/coveralls/jshttp/on-finished/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg +[downloads-url]: https://npmjs.org/package/on-finished diff --git a/node_modules/on-finished/index.js b/node_modules/on-finished/index.js new file mode 100644 index 0000000..9abd98f --- /dev/null +++ b/node_modules/on-finished/index.js @@ -0,0 +1,196 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, listener) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished(msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener(msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish(error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket(socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket) + callback(socket) + } +} diff --git a/node_modules/on-finished/package.json b/node_modules/on-finished/package.json new file mode 100644 index 0000000..b9df1bd --- /dev/null +++ b/node_modules/on-finished/package.json @@ -0,0 +1,31 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.3.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/on-finished", + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/once/LICENSE b/node_modules/once/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/once/README.md b/node_modules/once/README.md new file mode 100644 index 0000000..1f1ffca --- /dev/null +++ b/node_modules/once/README.md @@ -0,0 +1,79 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` + +## `once.strict(func)` + +Throw an error if the function is called twice. + +Some functions are expected to be called only once. Using `once` for them would +potentially hide logical errors. + +In the example below, the `greet` function has to call the callback only once: + +```javascript +function greet (name, cb) { + // return is missing from the if statement + // when no name is passed, the callback is called twice + if (!name) cb('Hello anonymous') + cb('Hello ' + name) +} + +function log (msg) { + console.log(msg) +} + +// this will print 'Hello anonymous' but the logical error will be missed +greet(null, once(msg)) + +// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time +greet(null, once.strict(msg)) +``` diff --git a/node_modules/once/once.js b/node_modules/once/once.js new file mode 100644 index 0000000..2354067 --- /dev/null +++ b/node_modules/once/once.js @@ -0,0 +1,42 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} diff --git a/node_modules/once/package.json b/node_modules/once/package.json new file mode 100644 index 0000000..16815b2 --- /dev/null +++ b/node_modules/once/package.json @@ -0,0 +1,33 @@ +{ + "name": "once", + "version": "1.4.0", + "description": "Run a function exactly one time", + "main": "once.js", + "directories": { + "test": "test" + }, + "dependencies": { + "wrappy": "1" + }, + "devDependencies": { + "tap": "^7.0.1" + }, + "scripts": { + "test": "tap test/*.js" + }, + "files": [ + "once.js" + ], + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once" + }, + "keywords": [ + "once", + "function", + "one", + "single" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/node_modules/parseurl/HISTORY.md b/node_modules/parseurl/HISTORY.md new file mode 100644 index 0000000..8e40954 --- /dev/null +++ b/node_modules/parseurl/HISTORY.md @@ -0,0 +1,58 @@ +1.3.3 / 2019-04-15 +================== + + * Fix Node.js 0.8 return value inconsistencies + +1.3.2 / 2017-09-09 +================== + + * perf: reduce overhead for full URLs + * perf: unroll the "fast-path" `RegExp` + +1.3.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.3.0 / 2014-08-09 +================== + + * Add `parseurl.original` for parsing `req.originalUrl` with fallback + * Return `undefined` if `req.url` is `undefined` + +1.2.0 / 2014-07-21 +================== + + * Cache URLs based on original value + * Remove no-longer-needed URL mis-parse work-around + * Simplify the "fast-path" `RegExp` + +1.1.3 / 2014-07-08 +================== + + * Fix typo + +1.1.2 / 2014-07-08 +================== + + * Seriously fix Node.js 0.8 compatibility + +1.1.1 / 2014-07-08 +================== + + * Fix Node.js 0.8 compatibility + +1.1.0 / 2014-07-08 +================== + + * Incorporate URL href-only parse fast-path + +1.0.1 / 2014-03-08 +================== + + * Add missing `require` + +1.0.0 / 2014-03-08 +================== + + * Genesis from `connect` diff --git a/node_modules/parseurl/LICENSE b/node_modules/parseurl/LICENSE new file mode 100644 index 0000000..27653d3 --- /dev/null +++ b/node_modules/parseurl/LICENSE @@ -0,0 +1,24 @@ + +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/parseurl/README.md b/node_modules/parseurl/README.md new file mode 100644 index 0000000..443e716 --- /dev/null +++ b/node_modules/parseurl/README.md @@ -0,0 +1,133 @@ +# parseurl + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse a URL with memoization. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install parseurl +``` + +## API + +```js +var parseurl = require('parseurl') +``` + +### parseurl(req) + +Parse the URL of the given request object (looks at the `req.url` property) +and return the result. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.url` does +not change will return a cached parsed object, rather than parsing again. + +### parseurl.original(req) + +Parse the original URL of the given request object and return the result. +This works by trying to parse `req.originalUrl` if it is a string, otherwise +parses `req.url`. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.originalUrl` +does not change will return a cached parsed object, rather than parsing again. + +## Benchmark + +```bash +$ npm run-script bench + +> parseurl@1.3.3 bench nodejs-parseurl +> node benchmark/index.js + + http_parser@2.8.0 + node@10.6.0 + v8@6.7.288.46-node.13 + uv@1.21.0 + zlib@1.2.11 + ares@1.14.0 + modules@64 + nghttp2@1.32.0 + napi@3 + openssl@1.1.0h + icu@61.1 + unicode@10.0 + cldr@33.0 + tz@2018c + +> node benchmark/fullurl.js + + Parsing URL "http://localhost:8888/foo/bar?user=tj&pet=fluffy" + + 4 tests completed. + + fasturl x 2,207,842 ops/sec ±3.76% (184 runs sampled) + nativeurl - legacy x 507,180 ops/sec ±0.82% (191 runs sampled) + nativeurl - whatwg x 290,044 ops/sec ±1.96% (189 runs sampled) + parseurl x 488,907 ops/sec ±2.13% (192 runs sampled) + +> node benchmark/pathquery.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" + + 4 tests completed. + + fasturl x 3,812,564 ops/sec ±3.15% (188 runs sampled) + nativeurl - legacy x 2,651,631 ops/sec ±1.68% (189 runs sampled) + nativeurl - whatwg x 161,837 ops/sec ±2.26% (189 runs sampled) + parseurl x 4,166,338 ops/sec ±2.23% (184 runs sampled) + +> node benchmark/samerequest.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" on same request object + + 4 tests completed. + + fasturl x 3,821,651 ops/sec ±2.42% (185 runs sampled) + nativeurl - legacy x 2,651,162 ops/sec ±1.90% (187 runs sampled) + nativeurl - whatwg x 175,166 ops/sec ±1.44% (188 runs sampled) + parseurl x 14,912,606 ops/sec ±3.59% (183 runs sampled) + +> node benchmark/simplepath.js + + Parsing URL "/foo/bar" + + 4 tests completed. + + fasturl x 12,421,765 ops/sec ±2.04% (191 runs sampled) + nativeurl - legacy x 7,546,036 ops/sec ±1.41% (188 runs sampled) + nativeurl - whatwg x 198,843 ops/sec ±1.83% (189 runs sampled) + parseurl x 24,244,006 ops/sec ±0.51% (194 runs sampled) + +> node benchmark/slash.js + + Parsing URL "/" + + 4 tests completed. + + fasturl x 17,159,456 ops/sec ±3.25% (188 runs sampled) + nativeurl - legacy x 11,635,097 ops/sec ±3.79% (184 runs sampled) + nativeurl - whatwg x 240,693 ops/sec ±0.83% (189 runs sampled) + parseurl x 42,279,067 ops/sec ±0.55% (190 runs sampled) +``` + +## License + + [MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/parseurl/master +[coveralls-url]: https://coveralls.io/r/pillarjs/parseurl?branch=master +[node-image]: https://badgen.net/npm/node/parseurl +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/parseurl +[npm-url]: https://npmjs.org/package/parseurl +[npm-version-image]: https://badgen.net/npm/v/parseurl +[travis-image]: https://badgen.net/travis/pillarjs/parseurl/master +[travis-url]: https://travis-ci.org/pillarjs/parseurl diff --git a/node_modules/parseurl/index.js b/node_modules/parseurl/index.js new file mode 100644 index 0000000..ece7223 --- /dev/null +++ b/node_modules/parseurl/index.js @@ -0,0 +1,158 @@ +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var url = require('url') +var parse = url.parse +var Url = url.Url + +/** + * Module exports. + * @public + */ + +module.exports = parseurl +module.exports.original = originalurl + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function parseurl (req) { + var url = req.url + + if (url === undefined) { + // URL is undefined + return undefined + } + + var parsed = req._parsedUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedUrl = parsed) +}; + +/** + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function originalurl (req) { + var url = req.originalUrl + + if (typeof url !== 'string') { + // Fallback + return parseurl(req) + } + + var parsed = req._parsedOriginalUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedOriginalUrl = parsed) +}; + +/** + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} + * @private + */ + +function fastparse (str) { + if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { + return parse(str) + } + + var pathname = str + var query = null + var search = null + + // This takes the regexp from https://github.com/joyent/node/pull/7878 + // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ + // And unrolls it into a for loop + for (var i = 1; i < str.length; i++) { + switch (str.charCodeAt(i)) { + case 0x3f: /* ? */ + if (search === null) { + pathname = str.substring(0, i) + query = str.substring(i + 1) + search = str.substring(i) + } + break + case 0x09: /* \t */ + case 0x0a: /* \n */ + case 0x0c: /* \f */ + case 0x0d: /* \r */ + case 0x20: /* */ + case 0x23: /* # */ + case 0xa0: + case 0xfeff: + return parse(str) + } + } + + var url = Url !== undefined + ? new Url() + : {} + + url.path = str + url.href = str + url.pathname = pathname + + if (search !== null) { + url.query = query + url.search = search + } + + return url +} + +/** + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} + * @private + */ + +function fresh (url, parsedUrl) { + return typeof parsedUrl === 'object' && + parsedUrl !== null && + (Url === undefined || parsedUrl instanceof Url) && + parsedUrl._raw === url +} diff --git a/node_modules/parseurl/package.json b/node_modules/parseurl/package.json new file mode 100644 index 0000000..6b443ca --- /dev/null +++ b/node_modules/parseurl/package.json @@ -0,0 +1,40 @@ +{ + "name": "parseurl", + "description": "parse a url with memoization", + "version": "1.3.3", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "pillarjs/parseurl", + "license": "MIT", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.1", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "fast-url-parser": "1.1.3", + "istanbul": "0.4.5", + "mocha": "6.1.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --check-leaks --bail --reporter spec test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec test/" + } +} diff --git a/node_modules/passport-jwt/.travis.yml b/node_modules/passport-jwt/.travis.yml new file mode 100644 index 0000000..9173c83 --- /dev/null +++ b/node_modules/passport-jwt/.travis.yml @@ -0,0 +1,12 @@ + language: node_js + node_js: + - "8" + - "7" + - "6" + - "5" + - "4" + - "3" # io.js + - "2" # io.js + - "1" # io.js + - "0.12" + - "0.10" diff --git a/node_modules/passport-jwt/LICENSE b/node_modules/passport-jwt/LICENSE new file mode 100644 index 0000000..1e767ef --- /dev/null +++ b/node_modules/passport-jwt/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2014 themikenicholson + +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/passport-jwt/README.md b/node_modules/passport-jwt/README.md new file mode 100644 index 0000000..b16d962 --- /dev/null +++ b/node_modules/passport-jwt/README.md @@ -0,0 +1,176 @@ +# passport-jwt + +[![Build Status](https://travis-ci.org/themikenicholson/passport-jwt.svg?branch=master)](https://travis-ci.org/themikenicholson/passport-jwt) +[![Code Climate](https://codeclimate.com/github/themikenicholson/passport-jwt/badges/gpa.svg)](https://codeclimate.com/github/themikenicholson/passport-jwt) + +A [Passport](http://passportjs.org/) strategy for authenticating with a +[JSON Web Token](http://jwt.io). + +This module lets you authenticate endpoints using a JSON web token. It is +intended to be used to secure RESTful endpoints without sessions. + +## Supported By + +If you want to quickly add secure token-based authentication to Node.js apps, feel free to check out Auth0's Node.js SDK and free plan at [auth0.com/overview](https://auth0.com/overview?utm_source=GHsponsor&utm_medium=GHsponsor&utm_campaign=passport-jwt&utm_content=auth) Auth0 Logo + +## Install + + npm install passport-jwt + +## Usage + +### Configure Strategy + +The JWT authentication strategy is constructed as follows: + + new JwtStrategy(options, verify) + +`options` is an object literal containing options to control how the token is +extracted from the request or verified. + +* `secretOrKey` is a string or buffer containing the secret + (symmetric) or PEM-encoded public key (asymmetric) for verifying the token's + signature. REQUIRED unless `secretOrKeyProvider` is provided. +* `secretOrKeyProvider` is a callback in the format `function secretOrKeyProvider(request, rawJwtToken, done)`, + which should call `done` with a secret or PEM-encoded public key (asymmetric) for the given key and request combination. + `done` accepts arguments in the format `function done(err, secret)`. Note it is up to the implementer to decode rawJwtToken. + REQUIRED unless `secretOrKey` is provided. +* `jwtFromRequest` (REQUIRED) Function that accepts a request as the only + parameter and returns either the JWT as a string or *null*. See + [Extracting the JWT from the request](#extracting-the-jwt-from-the-request) for + more details. +* `issuer`: If defined the token issuer (iss) will be verified against this + value. +* `audience`: If defined, the token audience (aud) will be verified against + this value. +* `algorithms`: List of strings with the names of the allowed algorithms. For instance, ["HS256", "HS384"]. +* `ignoreExpiration`: if true do not validate the expiration of the token. +* `passReqToCallback`: If true the request will be passed to the verify + callback. i.e. verify(request, jwt_payload, done_callback). +* `jsonWebTokenOptions`: passport-jwt is verifying the token using [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken). +Pass here an options object for any other option you can pass the jsonwebtoken verifier. (i.e maxAge) + +`verify` is a function with the parameters `verify(jwt_payload, done)` + +* `jwt_payload` is an object literal containing the decoded JWT payload. +* `done` is a passport error first callback accepting arguments + done(error, user, info) + +An example configuration which reads the JWT from the http +Authorization header with the scheme 'bearer': + +```js +var JwtStrategy = require('passport-jwt').Strategy, + ExtractJwt = require('passport-jwt').ExtractJwt; +var opts = {} +opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken(); +opts.secretOrKey = 'secret'; +opts.issuer = 'accounts.examplesoft.com'; +opts.audience = 'yoursite.net'; +passport.use(new JwtStrategy(opts, function(jwt_payload, done) { + User.findOne({id: jwt_payload.sub}, function(err, user) { + if (err) { + return done(err, false); + } + if (user) { + return done(null, user); + } else { + return done(null, false); + // or you could create a new account + } + }); +})); +``` + +### Extracting the JWT from the request + +There are a number of ways the JWT may be included in a request. In order to remain as flexible as +possible the JWT is parsed from the request by a user-supplied callback passed in as the +`jwtFromRequest` parameter. This callback, from now on referred to as an extractor, +accepts a request object as an argument and returns the encoded JWT string or *null*. + +#### Included extractors + +A number of extractor factory functions are provided in passport-jwt.ExtractJwt. These factory +functions return a new extractor configured with the given parameters. + +* ```fromHeader(header_name)``` creates a new extractor that looks for the JWT in the given http + header +* ```fromBodyField(field_name)``` creates a new extractor that looks for the JWT in the given body + field. You must have a body parser configured in order to use this method. +* ```fromUrlQueryParameter(param_name)``` creates a new extractor that looks for the JWT in the given + URL query parameter. +* ```fromAuthHeaderWithScheme(auth_scheme)``` creates a new extractor that looks for the JWT in the + authorization header, expecting the scheme to match auth_scheme. +* ```fromAuthHeaderAsBearerToken()``` creates a new extractor that looks for the JWT in the authorization header + with the scheme 'bearer' +* ```fromExtractors([array of extractor functions])``` creates a new extractor using an array of + extractors provided. Each extractor is attempted in order until one returns a token. + +### Writing a custom extractor function + +If the supplied extractors don't meet your needs you can easily provide your own callback. For +example, if you are using the cookie-parser middleware and want to extract the JWT in a cookie +you could use the following function as the argument to the jwtFromRequest option: + +``` +var cookieExtractor = function(req) { + var token = null; + if (req && req.cookies) + { + token = req.cookies['jwt']; + } + return token; +}; +``` + +### Authenticate requests + +Use `passport.authenticate()` specifying `'JWT'` as the strategy. + +```js +app.post('/profile', passport.authenticate('jwt', { session: false }), + function(req, res) { + res.send(req.user.profile); + } +); +``` + +### Include the JWT in requests + +The strategy will first check the request for the standard *Authorization* +header. If this header is present and the scheme matches `options.authScheme` +or 'JWT' if no auth scheme was specified then the token will be retrieved from +it. e.g. + + Authorization: JWT JSON_WEB_TOKEN_STRING..... + +If the authorization header with the expected scheme is not found, the request +body will be checked for a field matching either `options.tokenBodyField` or +`auth_token` if the option was not specified. + +Finally, the URL query parameters will be checked for a field matching either +`options.tokenQueryParameterName` or `auth_token` if the option was not +specified. + +## Migrating + +The the [Migration Guide](docs/migrating.md) for help upgrading to the latest +major version of passport-jwt + +## Tests + + npm install + npm test + +To generate test-coverage reports: + + npm install -g istanbul + npm run-script testcov + istanbul report + +## License + +The [MIT License](http://opensource.org/licenses/MIT) + +Copyright (c) 2015 Mike Nicholson diff --git a/node_modules/passport-jwt/docs/migrating.md b/node_modules/passport-jwt/docs/migrating.md new file mode 100644 index 0000000..fb46fbc --- /dev/null +++ b/node_modules/passport-jwt/docs/migrating.md @@ -0,0 +1,70 @@ +# Migration Guide + +The following instructions should help in migrating to a new major version of +passport-jwt. + +## Migrating from 3.x.x to 4.x.x + +Version 4.0.0 was released to update [jsonwebtoken's](https://github.com/auth0/node-jsonwebtoken) +major version from v7 to v8 in order to fix a security issue (see +[#147](https://github.com/themikenicholson/passport-jwt/issues/147)). + +Users of `passport-jwt` are exposed to the API of `jsonwebtoken` through the `jsonWebTokenOptions` +constructor option. Therefore, a major version rev of `jsonwebtoken` triggered a major version rev +of `passport-jwt`. + +See the +[jsonwebtoken v7-v8 Migration Notes](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v7-to-v8) +for the full details. The change in units for the `maxAge` attribute of `jsonWebTokenOptions` is +likely to impact the greatest number of `passport-jwt` users. + +## Migrating from 2.x.x to 3.x.x + +Version 3.0.0 removes the `ExtractJwt.fromAuthHeader()` extractor function that would extract +JWT's from `Authorization` headers with the auth scheme 'jwt'. The default authorization scheme +of 'jwt' as the was not RFC 6750 compliant. The extractor was replaced with +`ExtractJwt.fromAuthHeaderAsBearerToken()`. The removal of `ExtractJwt.fromAuthHeader()` was done +to clearly change the API so any code relying on the old API would clearly break, hopefully saving +people some debugging time. + +If you want to maintain the behavior of `ExtractJwt.fromAuthHeader()` when switching to v3.3.0, simply +replace it with `ExtractJwt.fromAuthHeaderWithScheme('jwt')` in your implementation. + +## Migrating from version 1.x.x to 2.x.x + +The v2 API is not backwards compatible with v1, specifically with regards to the introduction +of the concept of JWT extractor functions. If you require the legacy behavior in v1 you can use +the extractor function ```versionOneCompatibility(options)``` + +*options* is an object with any of the three custom JWT extraction options present in the v1 +constructor: +* `tokenBodyField`: Field in a request body to search for the JWT. + Default is auth_token. +* `tokenQueryParameterName`: Query parameter name containing the token. + Default is auth_token. +* `authScheme`: Expected authorization scheme if token is submitted through + the HTTP Authorization header. Defaults to JWT +If in v1 you constructed the strategy like this: + +```js +var JwtStrategy = require('passport-jwt').Strategy; +var opts = {} +opts.tokenBodyField = 'MY_CUSTOM_BODY_FIELD'; +opts.secretOrKey = 'secret'; +opts.issuer = 'accounts.examplesoft.com'; +opts.audience = 'yoursite.net'; +passport.use(new JwtStrategy(opts, verifyFunction)); +``` + +Identical behavior can be achieved under v2 with the versionOneCompatibility extractor: + +```js +var JwtStrategy = require('passport-jwt').Strategy, + ExtractJwt = require('passport-jwt').ExtractJwt; +var opts = {} +opts.jwtFromRequest = ExtractJwt.versionOneCompatibility({ tokenBodyField = 'MY_CUSTOM_BODY_FIELD' }); +opts.opts.secretOrKey = 'secret'; +opts.issuer = 'accounts.examplesoft.com'; +opts.audience = 'yoursite.net'; +passport.use(new JwtStrategy(opts, verifyFunction)); +``` diff --git a/node_modules/passport-jwt/lib/auth_header.js b/node_modules/passport-jwt/lib/auth_header.js new file mode 100644 index 0000000..95f976f --- /dev/null +++ b/node_modules/passport-jwt/lib/auth_header.js @@ -0,0 +1,19 @@ +'use strict'; + +var re = /(\S+)\s+(\S+)/; + + + +function parseAuthHeader(hdrValue) { + if (typeof hdrValue !== 'string') { + return null; + } + var matches = hdrValue.match(re); + return matches && { scheme: matches[1], value: matches[2] }; +} + + + +module.exports = { + parse: parseAuthHeader +}; diff --git a/node_modules/passport-jwt/lib/extract_jwt.js b/node_modules/passport-jwt/lib/extract_jwt.js new file mode 100644 index 0000000..7f112ab --- /dev/null +++ b/node_modules/passport-jwt/lib/extract_jwt.js @@ -0,0 +1,134 @@ +"use strict"; + +var url = require('url'), + auth_hdr = require('./auth_header'); + +// Note: express http converts all headers +// to lower case. +var AUTH_HEADER = "authorization", + LEGACY_AUTH_SCHEME = "JWT", + BEARER_AUTH_SCHEME = 'bearer'; + + +var extractors = {}; + + +extractors.fromHeader = function (header_name) { + return function (request) { + var token = null; + if (request.headers[header_name]) { + token = request.headers[header_name]; + } + return token; + }; +}; + + + +extractors.fromBodyField = function (field_name) { + return function (request) { + var token = null; + if (request.body && Object.prototype.hasOwnProperty.call(request.body, field_name)) { + token = request.body[field_name]; + } + return token; + }; +}; + + + +extractors.fromUrlQueryParameter = function (param_name) { + return function (request) { + var token = null, + parsed_url = url.parse(request.url, true); + if (parsed_url.query && Object.prototype.hasOwnProperty.call(parsed_url.query, param_name)) { + token = parsed_url.query[param_name]; + } + return token; + }; +}; + + + +extractors.fromAuthHeaderWithScheme = function (auth_scheme) { + var auth_scheme_lower = auth_scheme.toLowerCase(); + return function (request) { + + var token = null; + if (request.headers[AUTH_HEADER]) { + var auth_params = auth_hdr.parse(request.headers[AUTH_HEADER]); + if (auth_params && auth_scheme_lower === auth_params.scheme.toLowerCase()) { + token = auth_params.value; + } + } + return token; + }; +}; + + + +extractors.fromAuthHeaderAsBearerToken = function () { + return extractors.fromAuthHeaderWithScheme(BEARER_AUTH_SCHEME); +}; + + +extractors.fromExtractors = function(extractors) { + if (!Array.isArray(extractors)) { + throw new TypeError('extractors.fromExtractors expects an array') + } + + return function (request) { + var token = null; + var index = 0; + while(!token && index < extractors.length) { + token = extractors[index].call(this, request); + index ++; + } + return token; + } +}; + + +/** + * This extractor mimics the behavior of the v1.*.* extraction logic. + * + * This extractor exists only to provide an easy transition from the v1.*.* API to the v2.0.0 + * API. + * + * This extractor first checks the auth header, if it doesn't find a token there then it checks the + * specified body field and finally the url query parameters. + * + * @param options + * authScheme: Expected scheme when JWT can be found in HTTP Authorize header. Default is JWT. + * tokenBodyField: Field in request body containing token. Default is auth_token. + * tokenQueryParameterName: Query parameter name containing the token. Default is auth_token. + */ +extractors.versionOneCompatibility = function (options) { + var authScheme = options.authScheme || LEGACY_AUTH_SCHEME, + bodyField = options.tokenBodyField || 'auth_token', + queryParam = options.tokenQueryParameterName || 'auth_token'; + + return function (request) { + var authHeaderExtractor = extractors.fromAuthHeaderWithScheme(authScheme); + var token = authHeaderExtractor(request); + + if (!token) { + var bodyExtractor = extractors.fromBodyField(bodyField); + token = bodyExtractor(request); + } + + if (!token) { + var queryExtractor = extractors.fromUrlQueryParameter(queryParam); + token = queryExtractor(request); + } + + return token; + }; +} + + + +/** + * Export the Jwt extraction functions + */ +module.exports = extractors; diff --git a/node_modules/passport-jwt/lib/helpers/assign.js b/node_modules/passport-jwt/lib/helpers/assign.js new file mode 100644 index 0000000..f9cbd36 --- /dev/null +++ b/node_modules/passport-jwt/lib/helpers/assign.js @@ -0,0 +1,24 @@ +// note: This is a polyfill to Object.assign to support old nodejs versions (0.10 / 0.12) where +// Object.assign doesn't exist. +// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign +module.exports = function(target, varArgs) { + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; +}; diff --git a/node_modules/passport-jwt/lib/index.js b/node_modules/passport-jwt/lib/index.js new file mode 100644 index 0000000..9d8c422 --- /dev/null +++ b/node_modules/passport-jwt/lib/index.js @@ -0,0 +1,10 @@ +'use strict'; + +var Strategy = require('./strategy'), + ExtractJwt = require('./extract_jwt.js'); + + +module.exports = { + Strategy: Strategy, + ExtractJwt : ExtractJwt +}; diff --git a/node_modules/passport-jwt/lib/strategy.js b/node_modules/passport-jwt/lib/strategy.js new file mode 100644 index 0000000..cb072c5 --- /dev/null +++ b/node_modules/passport-jwt/lib/strategy.js @@ -0,0 +1,139 @@ +var passport = require('passport-strategy') + , auth_hdr = require('./auth_header') + , util = require('util') + , url = require('url') + , assign = require('./helpers/assign.js'); + + + +/** + * Strategy constructor + * + * @param options + * secretOrKey: String or buffer containing the secret or PEM-encoded public key. Required unless secretOrKeyProvider is provided. + * secretOrKeyProvider: callback in the format secretOrKeyProvider(request, rawJwtToken, done)`, + * which should call done with a secret or PEM-encoded public key + * (asymmetric) for the given undecoded jwt token string and request + * combination. done has the signature function done(err, secret). + * REQUIRED unless `secretOrKey` is provided. + * jwtFromRequest: (REQUIRED) Function that accepts a reqeust as the only parameter and returns the either JWT as a string or null + * issuer: If defined issuer will be verified against this value + * audience: If defined audience will be verified against this value + * algorithms: List of strings with the names of the allowed algorithms. For instance, ["HS256", "HS384"]. + * ignoreExpiration: if true do not validate the expiration of the token. + * passReqToCallback: If true the, the verify callback will be called with args (request, jwt_payload, done_callback). + * @param verify - Verify callback with args (jwt_payload, done_callback) if passReqToCallback is false, + * (request, jwt_payload, done_callback) if true. + */ +function JwtStrategy(options, verify) { + + passport.Strategy.call(this); + this.name = 'jwt'; + + this._secretOrKeyProvider = options.secretOrKeyProvider; + + if (options.secretOrKey) { + if (this._secretOrKeyProvider) { + throw new TypeError('JwtStrategy has been given both a secretOrKey and a secretOrKeyProvider'); + } + this._secretOrKeyProvider = function (request, rawJwtToken, done) { + done(null, options.secretOrKey) + }; + } + + if (!this._secretOrKeyProvider) { + throw new TypeError('JwtStrategy requires a secret or key'); + } + + this._verify = verify; + if (!this._verify) { + throw new TypeError('JwtStrategy requires a verify callback'); + } + + this._jwtFromRequest = options.jwtFromRequest; + if (!this._jwtFromRequest) { + throw new TypeError('JwtStrategy requires a function to retrieve jwt from requests (see option jwtFromRequest)'); + } + + this._passReqToCallback = options.passReqToCallback; + var jsonWebTokenOptions = options.jsonWebTokenOptions || {}; + //for backwards compatibility, still allowing you to pass + //audience / issuer / algorithms / ignoreExpiration + //on the options. + this._verifOpts = assign({}, jsonWebTokenOptions, { + audience: options.audience, + issuer: options.issuer, + algorithms: options.algorithms, + ignoreExpiration: !!options.ignoreExpiration + }); + +} +util.inherits(JwtStrategy, passport.Strategy); + + + +/** + * Allow for injection of JWT Verifier. + * + * This improves testability by allowing tests to cleanly isolate failures in the JWT Verification + * process from failures in the passport related mechanics of authentication. + * + * Note that this should only be replaced in tests. + */ +JwtStrategy.JwtVerifier = require('./verify_jwt'); + + + +/** + * Authenticate request based on JWT obtained from header or post body + */ +JwtStrategy.prototype.authenticate = function(req, options) { + var self = this; + + var token = self._jwtFromRequest(req); + + if (!token) { + return self.fail(new Error("No auth token")); + } + + this._secretOrKeyProvider(req, token, function(secretOrKeyError, secretOrKey) { + if (secretOrKeyError) { + self.fail(secretOrKeyError) + } else { + // Verify the JWT + JwtStrategy.JwtVerifier(token, secretOrKey, self._verifOpts, function(jwt_err, payload) { + if (jwt_err) { + return self.fail(jwt_err); + } else { + // Pass the parsed token to the user + var verified = function(err, user, info) { + if(err) { + return self.error(err); + } else if (!user) { + return self.fail(info); + } else { + return self.success(user, info); + } + }; + + try { + if (self._passReqToCallback) { + self._verify(req, payload, verified); + } else { + self._verify(payload, verified); + } + } catch(ex) { + self.error(ex); + } + } + }); + } + }); +}; + + + +/** + * Export the Jwt Strategy + */ + module.exports = JwtStrategy; diff --git a/node_modules/passport-jwt/lib/verify_jwt.js b/node_modules/passport-jwt/lib/verify_jwt.js new file mode 100644 index 0000000..7c4755c --- /dev/null +++ b/node_modules/passport-jwt/lib/verify_jwt.js @@ -0,0 +1,5 @@ +var jwt = require('jsonwebtoken'); + +module.exports = function(token, secretOrKey, options, callback) { + return jwt.verify(token, secretOrKey, options, callback); +}; diff --git a/node_modules/passport-jwt/package.json b/node_modules/passport-jwt/package.json new file mode 100644 index 0000000..01ba48f --- /dev/null +++ b/node_modules/passport-jwt/package.json @@ -0,0 +1,39 @@ +{ + "name": "passport-jwt", + "version": "4.0.0", + "description": "Passport authentication strategy using JSON Web Tokens", + "main": "./lib", + "scripts": { + "test": "./node_modules/.bin/mocha --reporter spec --require test/bootstrap test/*test.js", + "testcov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter spec --require test/bootstrap test/*test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/themikenicholson/passport-jwt.git" + }, + "keywords": [ + "Passport", + "Strategy", + "JSON", + "Web", + "Token", + "JWT" + ], + "author": "Mike Nicholson", + "license": "MIT", + "bugs": { + "url": "https://github.com/themikenicholson/passport-jwt/issues" + }, + "homepage": "https://github.com/themikenicholson/passport-jwt", + "devDependencies": { + "chai": "^3.0.0", + "chai-passport-strategy": "^1.0.0", + "istanbul": "^0.4.5", + "mocha": "^3.0.0", + "sinon": "^1.0.0" + }, + "dependencies": { + "jsonwebtoken": "^8.2.0", + "passport-strategy": "^1.0.0" + } +} diff --git a/node_modules/passport-jwt/test/auth_header-test.js b/node_modules/passport-jwt/test/auth_header-test.js new file mode 100644 index 0000000..fdab7f4 --- /dev/null +++ b/node_modules/passport-jwt/test/auth_header-test.js @@ -0,0 +1,28 @@ +var auth_hdr = require('../lib/auth_header') + + +describe('Parsing Auth Header field-value', function() { + + it('Should handle single space separated values', function() { + var res = auth_hdr.parse("SCHEME VALUE"); + expect(res).to.deep.equal({scheme: "SCHEME", value: "VALUE"}); + }); + + + it('Should handle CRLF separator', function() { + var res = auth_hdr.parse("SCHEME\nVALUE"); + expect(res).to.deep.equal({scheme: "SCHEME", value: "VALUE"}); + }); + + + it('Should handle malformed authentication headers with no scheme', function() { + var res = auth_hdr.parse("malformed"); + expect(res).to.not.be.ok; + }); + + + it('Should return null when the auth header is not a string', function() { + var res = auth_hdr.parse({}); + expect(res).to.be.null; + }); +}); diff --git a/node_modules/passport-jwt/test/bootstrap.js b/node_modules/passport-jwt/test/bootstrap.js new file mode 100644 index 0000000..ccbb983 --- /dev/null +++ b/node_modules/passport-jwt/test/bootstrap.js @@ -0,0 +1,3 @@ +var chai = require('chai'); +chai.use(require('chai-passport-strategy')); +global.expect = chai.expect; diff --git a/node_modules/passport-jwt/test/extrators-test.js b/node_modules/passport-jwt/test/extrators-test.js new file mode 100644 index 0000000..e38a9bf --- /dev/null +++ b/node_modules/passport-jwt/test/extrators-test.js @@ -0,0 +1,287 @@ +var extract_jwt = require('../lib/extract_jwt'), + Request = require('./mock_request'); + +describe('Token extractor', function() { + + describe('fromHeader', function() { + + var extractor = extract_jwt.fromHeader('test_header'); + + it('should return null no when token is present', function() { + var req = new Request(); + + var token = extractor(req); + + expect(token).to.be.null; + }); + + + it('should return the value from the specified header', function() { + var req = new Request(); + req.headers['test_header'] = 'abcd123' + + var token = extractor(req) + + expect(token).to.equal('abcd123'); + }); + }); + + + describe('fromBodyField', function() { + + var extractor = extract_jwt.fromBodyField('test_field'); + + it('should return null when no body is present', function() { + var req = new Request(); + + var token = extractor(req); + + expect(token).to.be.null; + }); + + + it('should return null when the specified body field is not present', function() { + var req = new Request(); + req.body = {}; + + var token = extractor(req); + + expect(token).to.be.null; + }); + + + it('should return the value from the specified body field', function() { + var req = new Request(); + req.body = {}; + req.body.test_field = 'abcd123'; + + var token = extractor(req); + + expect(token).to.equal('abcd123'); + }); + + + it('should work properly with querystring', function() { + var req = new Request(); + const querystring = require('querystring'); + req.body = querystring.parse('test_field=abcd123') + + var token = extractor(req); + + expect(token).to.equal('abcd123') + }); + }); + + + describe('fromUrlQueryParameter', function() { + + var extractor = extract_jwt.fromUrlQueryParameter('test_param'); + + + it('should return null when the specified paramter is not present', function() { + var req = new Request(); + + var token = extractor(req); + + expect(token).to.be.null; + }); + + + it('should return the value from the specified parameter', function() { + var req = new Request(); + req.url += '?test_param=abcd123'; + + var token = extractor(req); + + expect(token).to.equal('abcd123'); + }); + }); + + + describe('fromAuthHeaderWithScheme', function() { + + var extractor = extract_jwt.fromAuthHeaderWithScheme('TEST_SCHEME'); + + it('should return null when no auth header is present', function() { + var req = new Request(); + + var token = extractor(req); + + expect(token).to.be.null; + }); + + + it('should return null when the auth header is present but the auth scheme doesnt match', function() { + var req = new Request() + req.headers['authorization'] = "NOT_TEST_SCHEME abcd123"; + + var token = extractor(req); + + expect(token).to.be.null; + }); + + + it('should return the value from the authorization header with specified auth scheme', function() { + var req = new Request() + req.headers['authorization'] = "TEST_SCHEME abcd123"; + + var token = extractor(req); + + expect(token).to.equal('abcd123'); + }); + + + it('should perform a case-insensivite string comparison', function () { + var req = new Request() + req.headers['authorization'] = 'test_scheme abcd123'; + + var token = extractor(req); + + expect(token).to.equal('abcd123'); + }); + }); + + + describe('fromAuthHeader', function() { + + var extractor = extract_jwt.fromAuthHeaderAsBearerToken(); + + it('should return the value from the authorization header with default JWT auth scheme', function() { + var req = new Request() + req.headers['authorization'] = "bearer abcd123"; + + var token = extractor(req); + + expect(token).to.equal('abcd123'); + }); + + + }); + + describe('fromExtractors', function() { + + it('should raise a type error when the extractor is constructed with a non-array argument', function() { + this_should_throw = function() { + var extractor = extract_jwt.fromExtractors({}) + } + + expect(this_should_throw).to.throw(TypeError) + }); + + + var extractor = extract_jwt.fromExtractors([extract_jwt.fromAuthHeaderAsBearerToken(), extract_jwt.fromHeader('authorization')]); + + it('should return null when no extractor extracts token', function() { + var req = new Request(); + + var token = extractor(req); + + expect(token).to.be.null; + }); + + + it('should return token found by least extractor', function() { + var req = new Request() + req.headers['authorization'] = "abcd123"; + + var token = extractor(req); + + expect(token).to.equal('abcd123'); + }); + + + it('should return token found by first extractor', function() { + var req = new Request() + req.headers['authorization'] = "bearer abcd123"; + + var token = extractor(req); + + expect(token).to.equal('abcd123'); + }); + + }); + + + describe('versionOneCompatibility', function () { + + describe('default behavior', function() { + + var extractor = extract_jwt.versionOneCompatibility({}); + + it('should return the token in the default "JWT" auth header', function () { + var req = new Request(); + req.headers['authorization'] = "JWT abcd123"; + + var token = extractor(req); + + expect(token).to.equal('abcd123'); + }); + + + it('should return the token in the default "auth_token" body field', function () { + var req = new Request(); + req.body = {}; + req.body['auth_token'] = 'xyzabcd'; + + var token = extractor(req); + + expect(token).to.equal('xyzabcd'); + }); + + + it('should return then token in the default "auth_token" query parameter', function () { + var req = new Request(); + req.url += '?auth_token=abcd123'; + + var token = extractor(req); + + expect(token).to.equal('abcd123'); + }); + }); + + + describe('user supplied parameters', function() { + + it('should return the token in an auth header with a user specified auth scheme', function() { + var opts = { authScheme: 'MY_CUSTOM_AUTH_SCHEME' }; + var extractor = extract_jwt.versionOneCompatibility(opts); + var req = new Request(); + req.headers['authorization'] = 'MY_CUSTOM_AUTH_SCHEME deadbeef'; + + var token = extractor(req); + + expect(token).to.equal('deadbeef'); + }); + + + it('should return the token in a user supplied body field', function () { + var opts = { tokenBodyField: 'CUSTOM_BODY_FIELD' }; + var extractor = extract_jwt.versionOneCompatibility(opts); + var req = new Request(); + req.body = {}; + req.body['CUSTOM_BODY_FIELD'] = 'badbeef'; + + var token = extractor(req); + + expect(token).to.equal('badbeef'); + }); + + + it('should return the token in a user specified query parameter', function () { + var opts = { tokenQueryParameterName: 'CustomQueryParam' }; + var extractor = extract_jwt.versionOneCompatibility(opts); + var req = new Request(); + req.url += '?CustomQueryParam=deadbeef'; + + var token = extractor(req); + + expect(token).to.equal('deadbeef'); + }); + + }); + + + }); + +}); + diff --git a/node_modules/passport-jwt/test/mock_request.js b/node_modules/passport-jwt/test/mock_request.js new file mode 100644 index 0000000..14cf80d --- /dev/null +++ b/node_modules/passport-jwt/test/mock_request.js @@ -0,0 +1,10 @@ +/** + A mock Request for testing jwt extractor functions + */ +function Request() { + this.method = 'GET'; + this.url = '/'; + this.headers = {}; +} + +module.exports = Request; diff --git a/node_modules/passport-jwt/test/strategy-init-test.js b/node_modules/passport-jwt/test/strategy-init-test.js new file mode 100644 index 0000000..45254ac --- /dev/null +++ b/node_modules/passport-jwt/test/strategy-init-test.js @@ -0,0 +1,41 @@ +var Strategy = require('../lib/strategy'); + +describe('Strategy', function() { + var strategy = new Strategy({jwtFromRequest: function(){}, secretOrKey: 'secret'}, function() {}); + + it('should be named jwt', function() { + expect(strategy.name).to.equal('jwt'); + }); + + + it('should throw if constructed without a verify callback', function() { + expect(function() { + var s = new Strategy({jwtFromRequest: function(r) {}, secretOrKey: 'secret'}); + }).to.throw(TypeError, "JwtStrategy requires a verify callback"); + }); + + + it('should throw if constructed neither a secretOrKey or a secretOrKeyProvider arg', function() { + expect(function() { + var s = new Strategy({jwtFromRequest: function(r) {}, secretOrKey: null}, function() {}); + }).to.throw(TypeError, 'JwtStrategy requires a secret or key'); + }); + + + it('should throw if constructed with both a secretOrKey and a secretOrKeyProvider', function () { + expect(function() { + var s = new Strategy({ + secretOrKey: 'secret', + secretOrKeyProvider: function(req, token, done) {}, + jwtFromReqeust: function(r) {} + }); + }).to.throw(TypeError); + }); + + + it('should throw if constructed without a jwtFromRequest arg', function() { + expect(function() { + var s = new Strategy({secretOrKey: 'secret'}, function() {}); + }).to.throw(TypeError); + }); +}); diff --git a/node_modules/passport-jwt/test/strategy-requests-test.js b/node_modules/passport-jwt/test/strategy-requests-test.js new file mode 100644 index 0000000..c30d997 --- /dev/null +++ b/node_modules/passport-jwt/test/strategy-requests-test.js @@ -0,0 +1,124 @@ +var Strategy = require('../lib/strategy') + , chai = require('chai') + , sinon = require('sinon') + , test_data= require('./testdata') + , url = require('url') + , extract_jwt = require('../lib/extract_jwt') + + +describe('Strategy', function() { + + var mockVerifier = null; + + before(function() { + // Replace the JWT Verfier with a stub to capture the value + // extracted from the request + mockVerifier = sinon.stub(); + mockVerifier.callsArgWith(3, null, test_data.valid_jwt.payload); + Strategy.JwtVerifier = mockVerifier; + }); + + + + describe('handling request JWT present in request', function() { + var strategy; + + before(function(done) { + strategy = new Strategy({ + jwtFromRequest: function (r) { return test_data.valid_jwt.token; }, + secretOrKey: 'secret' + }, + function(jwt_payload, next) { + // Return values aren't important in this case + return next(null, {}, {}); + } + ); + + mockVerifier.reset(); + + chai.passport.use(strategy) + .success(function(u, i) { + done(); + }) + .authenticate(); + }); + + + it("verifies the right jwt", function() { + sinon.assert.calledOnce(mockVerifier); + expect(mockVerifier.args[0][0]).to.equal(test_data.valid_jwt.token); + }); + }); + + + + describe('handling request with NO JWT', function() { + + var info; + + before(function(done) { + strategy = new Strategy({jwtFromRequest: function(r) {}, secretOrKey: 'secret'}, function(jwt_payload, next) { + // Return values aren't important in this case + return next(null, {}, {}); + }); + + mockVerifier.reset(); + + chai.passport.use(strategy) + .fail(function(i) { + info = i + done(); + }) + .req(function(req) { + req.body = {} + }) + .authenticate(); + }); + + + it('should fail authentication', function() { + expect(info).to.be.an.object; + expect(info.message).to.equal("No auth token"); + }); + + + it('Should not try to verify anything', function() { + sinon.assert.notCalled(mockVerifier); + }); + + }); + + describe('handling request url set to url.Url instead of string', function() { + + var info; + + before(function(done) { + strategy = new Strategy({jwtFromRequest: function(r) {}, secretOrKey: 'secret'}, function(jwt_payload, next) { + // Return values aren't important in this case + return next(null, {}, {}); + }); + + mockVerifier.reset(); + + chai.passport.use(strategy) + .fail(function(i) { + info = i + done(); + }) + .req(function(req) { + req.body = {}; + req.url = new url.Url('/'); + }) + .authenticate(); + }); + + + it('should fail authentication', function() { + expect(info).to.be.an.object; + expect(info.message).to.equal("No auth token"); + }); + + }); + + +}); diff --git a/node_modules/passport-jwt/test/strategy-validation-test.js b/node_modules/passport-jwt/test/strategy-validation-test.js new file mode 100644 index 0000000..ea4e5f3 --- /dev/null +++ b/node_modules/passport-jwt/test/strategy-validation-test.js @@ -0,0 +1,182 @@ +var Strategy = require('../lib/strategy') + , chai = require('chai') + , test_data = require('./testdata') + , sinon = require('sinon') + , extract_jwt = require('../lib/extract_jwt'); + +describe('Strategy', function() { + + describe('calling JWT validation function', function() { + var strategy; + + before(function(done) { + verifyStub = sinon.stub(); + verifyStub.callsArgWith(1, null, {}, {}); + options = {}; + options.issuer = "TestIssuer"; + options.audience = "TestAudience"; + options.secretOrKey = 'secret'; + options.algorithms = ["HS256", "HS384"]; + options.ignoreExpiration = false; + options.jsonWebTokenOptions = { + clockTolerance: 10, + maxAge: "1h", + }; + options.jwtFromRequest = extract_jwt.fromAuthHeaderAsBearerToken(); + strategy = new Strategy(options, verifyStub); + + Strategy.JwtVerifier = sinon.stub(); + Strategy.JwtVerifier.callsArgWith(3, null, test_data.valid_jwt.payload); + + chai.passport.use(strategy) + .success(function(u, i) { + done(); + }) + .req(function(req) { + req.headers['authorization'] = "bearer " + test_data.valid_jwt.token; + }) + .authenticate(); + }); + + + it('should call with the right secret as an argument', function() { + expect(Strategy.JwtVerifier.args[0][1]).to.equal('secret'); + }); + + + it('should call with the right issuer option', function() { + expect(Strategy.JwtVerifier.args[0][2]).to.be.an.object; + expect(Strategy.JwtVerifier.args[0][2].issuer).to.equal('TestIssuer'); + }); + + + it('should call with the right audience option', function() { + expect(Strategy.JwtVerifier.args[0][2]).to.be.an.object; + expect(Strategy.JwtVerifier.args[0][2].audience).to.equal('TestAudience'); + }); + + it('should call with the right algorithms option', function() { + expect(Strategy.JwtVerifier.args[0][2]).to.be.an.object; + expect(Strategy.JwtVerifier.args[0][2].algorithms).to.eql(["HS256", "HS384"]); + }); + + it('should call with the right ignoreExpiration option', function() { + expect(Strategy.JwtVerifier.args[0][2]).to.be.an.object; + expect(Strategy.JwtVerifier.args[0][2].ignoreExpiration).to.be.false; + }); + + it('should call with the right maxAge option', function() { + expect(Strategy.JwtVerifier.args[0][2]).to.be.an.object; + expect(Strategy.JwtVerifier.args[0][2].maxAge).to.equal('1h'); + }); + + it('should call with the right clockTolerance option', function() { + expect(Strategy.JwtVerifier.args[0][2]).to.be.an.object; + expect(Strategy.JwtVerifier.args[0][2].clockTolerance).to.equal(10); + }); + + }); + + + describe('handling valid jwt', function() { + var strategy, payload; + + before(function(done) { + strategy = new Strategy({jwtFromRequest: extract_jwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'secret'}, function(jwt_payload, next) { + payload = jwt_payload; + next(null, {}, {}); + }); + + // Mock successful verification + Strategy.JwtVerifier = sinon.stub(); + Strategy.JwtVerifier.callsArgWith(3, null, test_data.valid_jwt.payload); + + chai.passport.use(strategy) + .success(function(u, i) { + done(); + }) + .req(function(req) { + req.headers['authorization'] = "bearer " + test_data.valid_jwt.token; + }) + .authenticate(); + }); + + + it('should call verify with the correct payload', function() { + expect(payload).to.deep.equal(test_data.valid_jwt.payload); + }); + + + }); + + + describe('handling failing jwt', function() { + var strategy, info; + var verify_spy = sinon.spy(); + + before(function(done) { + + strategy = new Strategy({jwtFromRequest: extract_jwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'secret'}, verify_spy); + + // Mock errored verification + Strategy.JwtVerifier = sinon.stub(); + Strategy.JwtVerifier.callsArgWith(3, new Error("jwt expired"), false); + + chai.passport.use(strategy) + .fail(function(i) { + info = i; + done(); + }) + .req(function(req) { + req.headers['authorization'] = "bearer " + test_data.valid_jwt.token; + }) + .authenticate(); + }); + + + it('should not call verify', function() { + sinon.assert.notCalled(verify_spy); + }); + + + it('should fail with error message.', function() { + expect(info).to.be.an.object; + expect(info.message).to.equal('jwt expired'); + }); + + }); + + + describe('handling an invalid authentication header', function() { + var strategy, info; + var verify_spy = sinon.spy(); + + before(function(done) { + + strategy = new Strategy({jwtFromRequest: extract_jwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'secret'}, verify_spy); + + chai.passport.use(strategy) + .fail(function(i) { + info = i; + done(); + }) + .req(function(req) { + req.headers['authorization'] = "malformed"; + }) + .authenticate(); + }); + + + it('should not call verify', function() { + sinon.assert.notCalled(verify_spy); + }); + + + it('should fail with error message.', function() { + expect(info).to.be.an.object; + expect(info).to.be.an.instanceof(Error); + }); + + }); + +}); diff --git a/node_modules/passport-jwt/test/strategy-verify-test.js b/node_modules/passport-jwt/test/strategy-verify-test.js new file mode 100644 index 0000000..f642c3b --- /dev/null +++ b/node_modules/passport-jwt/test/strategy-verify-test.js @@ -0,0 +1,245 @@ +var chai = require('chai') + , Strategy = require('../lib/strategy') + , test_data = require('./testdata') + , sinon = require('sinon') + , verify = require('../lib/verify_jwt') + , extract_jwt = require('../lib/extract_jwt'); + + +describe('Strategy', function() { + + before(function() { + Strategy.JwtVerifier = sinon.stub(); + Strategy.JwtVerifier.callsArgWith(3, null, test_data.valid_jwt.payload); + }); + + describe('Handling a request with a valid JWT and succesful verification', function() { + + var strategy, user, info; + + before(function(done) { + strategy = new Strategy({jwtFromRequest:extract_jwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'secret'}, function(jwt_paylod, next) { + return next(null, {user_id: 1234567890}, {foo:'bar'}); + }); + + chai.passport.use(strategy) + .success(function(u, i) { + user = u; + info = i; + done(); + }) + .req(function(req) { + req.headers['authorization'] = "bearer " + test_data.valid_jwt.token; + }) + .authenticate(); + }); + + + it('should provide a user', function() { + expect(user).to.be.an.object; + expect(user.user_id).to.equal(1234567890); + }); + + + it('should forward info', function() { + expect(info).to.be.an.object; + expect(info.foo).to.equal('bar'); + }); + + }); + + + + describe('handling a request with valid jwt and failed verification', function() { + + var strategy, info; + + before(function(done) { + strategy = new Strategy({jwtFromRequest: extract_jwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'secret'}, function(jwt_payload, next) { + return next(null, false, {message: 'invalid user'}); + }); + + chai.passport.use(strategy) + .fail(function(i) { + info = i; + done(); + }) + .req(function(req) { + req.headers['authorization'] = "bearer " + test_data.valid_jwt.token; + }) + .authenticate(); + }); + + + it('should fail with info', function() { + expect(info).to.be.an.object; + expect(info.message).to.equal('invalid user'); + }); + + }); + + + + describe('handling a request with a valid jwt and an error during verification', function() { + + var strategy, err; + + before(function(done) { + strategy = new Strategy({jwtFromRequest: extract_jwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'secrety'}, function(jwt_payload, next) { + return next(new Error("ERROR"), false, {message: 'invalid user'}); + }); + + chai.passport.use(strategy) + .error(function(e) { + err = e; + done(); + }) + .req(function(req) { + req.headers['authorization'] = "bearer " + test_data.valid_jwt.token; + }) + .authenticate(); + }); + + + it('should error', function() { + expect(err).to.be.an.instanceof(Error); + expect(err.message).to.equal('ERROR'); + }); + + }); + + + + describe('handling a request with a valid jwt and an exception during verification', function() { + var strategy, err; + + before(function(done) { + strategy = new Strategy({jwtFromRequest: extract_jwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'secret'}, function(jwt_payload, next) { + throw new Error("EXCEPTION"); + }); + + chai.passport.use(strategy) + .error(function(e) { + err = e; + done(); + }) + .req(function(req) { + req.headers['authorization'] = "bearer " + test_data.valid_jwt.token; + }) + .authenticate(); + }); + + + it('should error', function() { + expect(err).to.be.an.instanceof(Error); + expect(err.message).to.equal('EXCEPTION'); + }); + + }); + + + + describe('handling a request with a valid jwt and option passReqToCallback is true', function() { + + var strategy, expected_request, request_arg; + + before(function(done) { + opts = { passReqToCallback: true }; + opts.secretOrKey = 'secret'; + opts.jwtFromRequest = extract_jwt.fromAuthHeaderAsBearerToken(); + strategy = new Strategy(opts, function(request, jwt_payload, next) { + // Capture the value passed in as the request argument + request_arg = request; + return next(null, {user_id: 1234567890}, {foo:'bar'}); + }); + + chai.passport.use(strategy) + .success(function(u, i) { + done(); + }) + .req(function(req) { + req.headers['authorization'] = "bearer " + test_data.valid_jwt.token; + expected_request = req; + }) + .authenticate(); + }); + + it('will call verify with request as the first argument', function() { + expect(expected_request).to.equal(request_arg); + }); + + }); + + + describe('handling a request when constructed with a secretOrKeyProvider function that succeeds', function() { + + var strategy, fakeSecretOrKeyProvider, expectedReqeust; + + before(function(done) { + fakeSecretOrKeyProvider = sinon.spy(function(request, token, done) { + done(null, 'secret from callback'); + }); + opts = { + secretOrKeyProvider: fakeSecretOrKeyProvider, + jwtFromRequest: function(request) { + return 'an undecoded jwt string'; + } + } + strategy = new Strategy(opts, function(jwtPayload, next) { + return next(null, {user_id: 'dont care'}, {}); + }); + + chai.passport.use(strategy) + .success(function(u, i) { + done(); + }) + .req(function(req) { + expectedReqeust = req; + }) + .authenticate(); + }); + + it('should call the fake secret or key provider with the reqeust', function() { + expect(fakeSecretOrKeyProvider.calledWith(expectedReqeust, sinon.match.any, sinon.match.any)).to.be.true; + }); + + it('should call the secretOrKeyProvider with the undecoded jwt', function() { + expect(fakeSecretOrKeyProvider.calledWith(sinon.match.any, 'an undecoded jwt string', sinon.match.any)).to.be.true; + }); + + it('should call JwtVerifier with the value returned from secretOrKeyProvider', function() { + expect(Strategy.JwtVerifier.calledWith(sinon.match.any, 'secret from callback', sinon.match.any, sinon.match.any)).to.be.true; + }); + }); + + + describe('handling a request when constructed with a secretOrKeyProvider function that errors', function() { + var errorMessage; + + before(function(done) { + fakeSecretOrKeyProvider = sinon.spy(function(request, token, done) { + done('Error occurred looking for the secret'); + }); + opts = { + secretOrKeyProvider: fakeSecretOrKeyProvider, + jwtFromRequest: function(request) { + return 'an undecoded jwt string'; + } + } + strategy = new Strategy(opts, function(jwtPayload, next) { + return next(null, {user_id: 'dont care'}, {}); + }); + + chai.passport.use(strategy) + .fail(function(i) { + errorMessage = i; + done(); + }) + .authenticate(); + }); + + it('should fail with the error message from the secretOrKeyProvider', function() { + expect(errorMessage).to.equal('Error occurred looking for the secret'); + }); + }); +}); diff --git a/node_modules/passport-jwt/test/testdata.js b/node_modules/passport-jwt/test/testdata.js new file mode 100644 index 0000000..4b083b4 --- /dev/null +++ b/node_modules/passport-jwt/test/testdata.js @@ -0,0 +1,14 @@ +module.exports = { + // Note, this JWT will expire sometime in 2286. If unit tests are failing around this time try + // generating a new, valid token :) + valid_jwt : { + token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjEyMzQ1Njc4OTAsIm5hbWUiOiJKb2huIERvZSIsImlzcyI6ImV4YW1wbGVzb2Z0LmNvbSIsImV4cCI6Ijk5OTk5OTk5OTkifQ.CbpI0TNI-FYXe6p3PgM__jwlz6aCT1qpUBsTVCfWuBM", + payload : { + "sub": "1234567890", + "name": "John Doe", + "iss": "examplesoft.com", + "exp": "9999999999" + }, + secret: 'secret' + } +}; diff --git a/node_modules/passport-strategy/.jshintrc b/node_modules/passport-strategy/.jshintrc new file mode 100644 index 0000000..a07354b --- /dev/null +++ b/node_modules/passport-strategy/.jshintrc @@ -0,0 +1,20 @@ +{ + "node": true, + + "bitwise": true, + "camelcase": true, + "curly": true, + "forin": true, + "immed": true, + "latedef": true, + "newcap": true, + "noarg": true, + "noempty": true, + "nonew": true, + "quotmark": "single", + "undef": true, + "unused": true, + "trailing": true, + + "laxcomma": true +} diff --git a/node_modules/passport-strategy/.travis.yml b/node_modules/passport-strategy/.travis.yml new file mode 100644 index 0000000..45f8624 --- /dev/null +++ b/node_modules/passport-strategy/.travis.yml @@ -0,0 +1,15 @@ +language: "node_js" +node_js: + - "0.4" + - "0.6" + - "0.8" + - "0.10" + +before_install: + - "npm install istanbul -g" + - "npm install coveralls -g" + +script: "make ci-travis" + +after_success: + - "make submit-coverage-to-coveralls" diff --git a/node_modules/passport-strategy/LICENSE b/node_modules/passport-strategy/LICENSE new file mode 100644 index 0000000..ec885b5 --- /dev/null +++ b/node_modules/passport-strategy/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2011-2013 Jared Hanson + +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/passport-strategy/README.md b/node_modules/passport-strategy/README.md new file mode 100644 index 0000000..71de07f --- /dev/null +++ b/node_modules/passport-strategy/README.md @@ -0,0 +1,61 @@ +# passport-strategy + +[![Build](https://travis-ci.org/jaredhanson/passport-strategy.png)](http://travis-ci.org/jaredhanson/passport-strategy) +[![Coverage](https://coveralls.io/repos/jaredhanson/passport-strategy/badge.png)](https://coveralls.io/r/jaredhanson/passport-strategy) +[![Dependencies](https://david-dm.org/jaredhanson/passport-strategy.png)](http://david-dm.org/jaredhanson/passport-strategy) + + +An abstract class implementing [Passport](http://passportjs.org/)'s strategy +API. + +## Install + + $ npm install passport-strategy + +## Usage + +This module exports an abstract `Strategy` class that is intended to be +subclassed when implementing concrete authentication strategies. Once +implemented, such strategies can be used by applications that utilize Passport +middleware for authentication. + +#### Subclass Strategy + +Create a new `CustomStrategy` constructor which inherits from `Strategy`: + +```javascript +var util = require('util') + , Strategy = require('passport-strategy'); + +function CustomStrategy(...) { + Strategy.call(this); +} + +util.inherits(CustomStrategy, Strategy); +``` + +#### Implement Authentication + +Implement `autheticate()`, performing the necessary operations required by the +authentication scheme or protocol being implemented. + +```javascript +CustomStrategy.prototype.authenticate = function(req, options) { + // TODO: authenticate request +} +``` + +## Tests + + $ npm install + $ npm test + +## Credits + + - [Jared Hanson](http://github.com/jaredhanson) + +## License + +[The MIT License](http://opensource.org/licenses/MIT) + +Copyright (c) 2011-2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> diff --git a/node_modules/passport-strategy/lib/index.js b/node_modules/passport-strategy/lib/index.js new file mode 100644 index 0000000..a6fdfa7 --- /dev/null +++ b/node_modules/passport-strategy/lib/index.js @@ -0,0 +1,15 @@ +/** + * Module dependencies. + */ +var Strategy = require('./strategy'); + + +/** + * Expose `Strategy` directly from package. + */ +exports = module.exports = Strategy; + +/** + * Export constructors. + */ +exports.Strategy = Strategy; diff --git a/node_modules/passport-strategy/lib/strategy.js b/node_modules/passport-strategy/lib/strategy.js new file mode 100644 index 0000000..5a7eb28 --- /dev/null +++ b/node_modules/passport-strategy/lib/strategy.js @@ -0,0 +1,28 @@ +/** + * Creates an instance of `Strategy`. + * + * @constructor + * @api public + */ +function Strategy() { +} + +/** + * Authenticate request. + * + * This function must be overridden by subclasses. In abstract form, it always + * throws an exception. + * + * @param {Object} req The request to authenticate. + * @param {Object} [options] Strategy-specific options. + * @api public + */ +Strategy.prototype.authenticate = function(req, options) { + throw new Error('Strategy#authenticate must be overridden by subclass'); +}; + + +/** + * Expose `Strategy`. + */ +module.exports = Strategy; diff --git a/node_modules/passport-strategy/package.json b/node_modules/passport-strategy/package.json new file mode 100644 index 0000000..666d265 --- /dev/null +++ b/node_modules/passport-strategy/package.json @@ -0,0 +1,50 @@ +{ + "name": "passport-strategy", + "version": "1.0.0", + "description": "An abstract class implementing Passport's strategy API.", + "keywords": [ + "passport", + "strategy" + ], + "repository": { + "type": "git", + "url": "git://github.com/jaredhanson/passport-strategy.git" + }, + "bugs": { + "url": "http://github.com/jaredhanson/passport-strategy/issues" + }, + "author": { + "name": "Jared Hanson", + "email": "jaredhanson@gmail.com", + "url": "http://www.jaredhanson.net/" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://www.opensource.org/licenses/MIT" + } + ], + "main": "./lib", + "dependencies": { + }, + "devDependencies": { + "mocha": "1.x.x", + "chai": "1.x.x" + }, + "engines": { + "node": ">= 0.4.0" + }, + "scripts": { + "test": "node_modules/.bin/mocha --reporter spec --require test/bootstrap/node test/*.test.js" + }, + "testling": { + "browsers": [ + "chrome/latest" + ], + "harness" : "mocha", + "files": [ + "test/bootstrap/testling.js", + "test/*.test.js" + ] + } +} diff --git a/node_modules/passport/CHANGELOG.md b/node_modules/passport/CHANGELOG.md new file mode 100644 index 0000000..fad77f0 --- /dev/null +++ b/node_modules/passport/CHANGELOG.md @@ -0,0 +1,48 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.5.2] - 2021-12-16 +### Fixed +- Introduced a compatibility layer for strategies that depend directly on +`passport@0.4.x` or earlier (such as `passport-azure-ad`), which were +broken by the removal of private variables in `passport@0.5.1`. + +## [0.5.1] - 2021-12-15 +### Added +- Informative error message in session strategy if session support is not +available. + +### Changed + +- `authenticate()` middleware, rather than `initialize()` middleware, extends +request with `login()`, `logIn()`, `logout()`, `logOut()`, `isAuthenticated()`, +and `isUnauthenticated()` functions. + +## [0.5.0] - 2021-09-23 +### Changed + +- `initialize()` middleware extends request with `login()`, `logIn()`, +`logout()`, `logOut()`, `isAuthenticated()`, and `isUnauthenticated()` +functions. + +### Removed + +- `login()`, `logIn()`, `logout()`, `logOut()`, `isAuthenticated()`, and +`isUnauthenticated()` functions no longer added to `http.IncomingMessage.prototype`. + +### Fixed + +- `userProperty` option to `initialize()` middleware only affects the current +request, rather than all requests processed via singleton Passport instance, +eliminating a race condition in situations where `initialize()` middleware is +used multiple times in an application with `userProperty` set to different +values. + +[Unreleased]: https://github.com/jaredhanson/passport/compare/v0.5.2...HEAD +[0.5.2]: https://github.com/jaredhanson/passport/compare/v0.5.1...v0.5.2 +[0.5.1]: https://github.com/jaredhanson/passport/compare/v0.5.0...v0.5.1 diff --git a/node_modules/passport/LICENSE b/node_modules/passport/LICENSE new file mode 100644 index 0000000..2a3ab4d --- /dev/null +++ b/node_modules/passport/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2011-2021 Jared Hanson + +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/passport/README.md b/node_modules/passport/README.md new file mode 100644 index 0000000..55e887d --- /dev/null +++ b/node_modules/passport/README.md @@ -0,0 +1,174 @@ +[![passport banner](http://cdn.auth0.com/img/passport-banner-github.png)](http://passportjs.org) + +# Passport + +Passport is [Express](http://expressjs.com/)-compatible authentication +middleware for [Node.js](http://nodejs.org/). + +Passport's sole purpose is to authenticate requests, which it does through an +extensible set of plugins known as _strategies_. Passport does not mount +routes or assume any particular database schema, which maximizes flexibility and +allows application-level decisions to be made by the developer. The API is +simple: you provide Passport a request to authenticate, and Passport provides +hooks for controlling what occurs when authentication succeeds or fails. + +--- + +

+ Sponsors +
+
+ LoginRadius is built for the developer community to integrate robust Authentication and Single Sign-On in just a few lines of code.
FREE Signup +

+
+ Your app, enterprise-ready.
Start selling to enterprise customers with just a few lines of code. Add Single Sign-On (and more) in minutes instead of months.
+

+ +--- + +Status: +[![Build](https://travis-ci.org/jaredhanson/passport.svg?branch=master)](https://travis-ci.org/jaredhanson/passport) +[![Coverage](https://coveralls.io/repos/jaredhanson/passport/badge.svg?branch=master)](https://coveralls.io/r/jaredhanson/passport) +[![Dependencies](https://david-dm.org/jaredhanson/passport.svg)](https://david-dm.org/jaredhanson/passport) + + +## Install + +``` +$ npm install passport +``` + +## Usage + +#### Strategies + +Passport uses the concept of strategies to authenticate requests. Strategies +can range from verifying username and password credentials, delegated +authentication using [OAuth](http://oauth.net/) (for example, via [Facebook](http://www.facebook.com/) +or [Twitter](http://twitter.com/)), or federated authentication using [OpenID](http://openid.net/). + +Before authenticating requests, the strategy (or strategies) used by an +application must be configured. + +```javascript +passport.use(new LocalStrategy( + function(username, password, done) { + User.findOne({ username: username }, function (err, user) { + if (err) { return done(err); } + if (!user) { return done(null, false); } + if (!user.verifyPassword(password)) { return done(null, false); } + return done(null, user); + }); + } +)); +``` + +There are 480+ strategies. Find the ones you want at: [passportjs.org](http://passportjs.org) + +#### Sessions + +Passport will maintain persistent login sessions. In order for persistent +sessions to work, the authenticated user must be serialized to the session, and +deserialized when subsequent requests are made. + +Passport does not impose any restrictions on how your user records are stored. +Instead, you provide functions to Passport which implements the necessary +serialization and deserialization logic. In a typical application, this will be +as simple as serializing the user ID, and finding the user by ID when +deserializing. + +```javascript +passport.serializeUser(function(user, done) { + done(null, user.id); +}); + +passport.deserializeUser(function(id, done) { + User.findById(id, function (err, user) { + done(err, user); + }); +}); +``` + +#### Middleware + +To use Passport in an [Express](http://expressjs.com/) or +[Connect](http://senchalabs.github.com/connect/)-based application, configure it +with the required `passport.initialize()` middleware. If your application uses +persistent login sessions (recommended, but not required), `passport.session()` +middleware must also be used. + +```javascript +var app = express(); +app.use(require('serve-static')(__dirname + '/../../public')); +app.use(require('cookie-parser')()); +app.use(require('body-parser').urlencoded({ extended: true })); +app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true })); +app.use(passport.initialize()); +app.use(passport.session()); +``` + +#### Authenticate Requests + +Passport provides an `authenticate()` function, which is used as route +middleware to authenticate requests. + +```javascript +app.post('/login', + passport.authenticate('local', { failureRedirect: '/login' }), + function(req, res) { + res.redirect('/'); + }); +``` + +## Strategies + +Passport has a comprehensive set of **over 480** authentication strategies +covering social networking, enterprise integration, API services, and more. + +## Search all strategies + +There is a **Strategy Search** at [passportjs.org](http://passportjs.org) + +The following table lists commonly used strategies: + +|Strategy | Protocol |Developer | +|---------------------------------------------------------------|--------------------------|------------------------------------------------| +|[Local](https://github.com/jaredhanson/passport-local) | HTML form |[Jared Hanson](https://github.com/jaredhanson) | +|[OpenID](https://github.com/jaredhanson/passport-openid) | OpenID |[Jared Hanson](https://github.com/jaredhanson) | +|[BrowserID](https://github.com/jaredhanson/passport-browserid) | BrowserID |[Jared Hanson](https://github.com/jaredhanson) | +|[Facebook](https://github.com/jaredhanson/passport-facebook) | OAuth 2.0 |[Jared Hanson](https://github.com/jaredhanson) | +|[Google](https://github.com/jaredhanson/passport-google) | OpenID |[Jared Hanson](https://github.com/jaredhanson) | +|[Google](https://github.com/jaredhanson/passport-google-oauth) | OAuth / OAuth 2.0 |[Jared Hanson](https://github.com/jaredhanson) | +|[Twitter](https://github.com/jaredhanson/passport-twitter) | OAuth |[Jared Hanson](https://github.com/jaredhanson) | +|[Azure Active Directory](https://github.com/AzureAD/passport-azure-ad) | OAuth 2.0 / OpenID / SAML |[Azure](https://github.com/azuread) | + +## Examples + +- For a complete, working example, refer to the [example](https://github.com/passport/express-4.x-local-example) +that uses [passport-local](https://github.com/jaredhanson/passport-local). +- **Local Strategy**: Refer to the following tutorials for setting up user authentication via LocalStrategy (`passport-local`): + - Mongo + - Express v3x - [Tutorial](http://mherman.org/blog/2016/09/25/node-passport-and-postgres/#.V-govpMrJE5) / [working example](https://github.com/mjhea0/passport-local-knex) + - Express v4x - [Tutorial](http://mherman.org/blog/2015/01/31/local-authentication-with-passport-and-express-4/) / [working example](https://github.com/mjhea0/passport-local-express4) + - Postgres + - [Tutorial](http://mherman.org/blog/2015/01/31/local-authentication-with-passport-and-express-4/) / [working example](https://github.com/mjhea0/passport-local-express4) +- **Social Authentication**: Refer to the following tutorials for setting up various social authentication strategies: + - Express v3x - [Tutorial](http://mherman.org/blog/2013/11/10/social-authentication-with-passport-dot-js/) / [working example](https://github.com/mjhea0/passport-examples) + - Express v4x - [Tutorial](http://mherman.org/blog/2015/09/26/social-authentication-in-node-dot-js-with-passport) / [working example](https://github.com/mjhea0/passport-social-auth) + +## Related Modules + +- [Locomotive](https://github.com/jaredhanson/locomotive) — Powerful MVC web framework +- [OAuthorize](https://github.com/jaredhanson/oauthorize) — OAuth service provider toolkit +- [OAuth2orize](https://github.com/jaredhanson/oauth2orize) — OAuth 2.0 authorization server toolkit +- [connect-ensure-login](https://github.com/jaredhanson/connect-ensure-login) — middleware to ensure login sessions + +The [modules](https://github.com/jaredhanson/passport/wiki/Modules) page on the +[wiki](https://github.com/jaredhanson/passport/wiki) lists other useful modules +that build upon or integrate with Passport. + +## License + +[The MIT License](http://opensource.org/licenses/MIT) + +Copyright (c) 2011-2021 Jared Hanson <[https://www.jaredhanson.me/](https://www.jaredhanson.me/)> diff --git a/node_modules/passport/lib/authenticator.js b/node_modules/passport/lib/authenticator.js new file mode 100644 index 0000000..03f9878 --- /dev/null +++ b/node_modules/passport/lib/authenticator.js @@ -0,0 +1,468 @@ +/** + * Module dependencies. + */ +var SessionStrategy = require('./strategies/session') + , SessionManager = require('./sessionmanager'); + + +/** + * `Authenticator` constructor. + * + * @api public + */ +function Authenticator() { + this._key = 'passport'; + this._strategies = {}; + this._serializers = []; + this._deserializers = []; + this._infoTransformers = []; + this._framework = null; + + this.init(); +} + +/** + * Initialize authenticator. + * + * @api protected + */ +Authenticator.prototype.init = function() { + this.framework(require('./framework/connect')()); + this.use(new SessionStrategy({ key: this._key }, this.deserializeUser.bind(this))); + this._sm = new SessionManager({ key: this._key }, this.serializeUser.bind(this)); +}; + +/** + * Utilize the given `strategy` with optional `name`, overridding the strategy's + * default name. + * + * Examples: + * + * passport.use(new TwitterStrategy(...)); + * + * passport.use('api', new http.BasicStrategy(...)); + * + * @param {String|Strategy} name + * @param {Strategy} strategy + * @return {Authenticator} for chaining + * @api public + */ +Authenticator.prototype.use = function(name, strategy) { + if (!strategy) { + strategy = name; + name = strategy.name; + } + if (!name) { throw new Error('Authentication strategies must have a name'); } + + this._strategies[name] = strategy; + return this; +}; + +/** + * Un-utilize the `strategy` with given `name`. + * + * In typical applications, the necessary authentication strategies are static, + * configured once and always available. As such, there is often no need to + * invoke this function. + * + * However, in certain situations, applications may need dynamically configure + * and de-configure authentication strategies. The `use()`/`unuse()` + * combination satisfies these scenarios. + * + * Examples: + * + * passport.unuse('legacy-api'); + * + * @param {String} name + * @return {Authenticator} for chaining + * @api public + */ +Authenticator.prototype.unuse = function(name) { + delete this._strategies[name]; + return this; +}; + +/** + * Setup Passport to be used under framework. + * + * By default, Passport exposes middleware that operate using Connect-style + * middleware using a `fn(req, res, next)` signature. Other popular frameworks + * have different expectations, and this function allows Passport to be adapted + * to operate within such environments. + * + * If you are using a Connect-compatible framework, including Express, there is + * no need to invoke this function. + * + * Examples: + * + * passport.framework(require('hapi-passport')()); + * + * @param {Object} name + * @return {Authenticator} for chaining + * @api public + */ +Authenticator.prototype.framework = function(fw) { + this._framework = fw; + return this; +}; + +/** + * Passport's primary initialization middleware. + * + * This middleware must be in use by the Connect/Express application for + * Passport to operate. + * + * Options: + * - `userProperty` Property to set on `req` upon login, defaults to _user_ + * + * Examples: + * + * app.use(passport.initialize()); + * + * app.use(passport.initialize({ userProperty: 'currentUser' })); + * + * @param {Object} options + * @return {Function} middleware + * @api public + */ +Authenticator.prototype.initialize = function(options) { + options = options || {}; + return this._framework.initialize(this, options); +}; + +/** + * Middleware that will authenticate a request using the given `strategy` name, + * with optional `options` and `callback`. + * + * Examples: + * + * passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' })(req, res); + * + * passport.authenticate('local', function(err, user) { + * if (!user) { return res.redirect('/login'); } + * res.end('Authenticated!'); + * })(req, res); + * + * passport.authenticate('basic', { session: false })(req, res); + * + * app.get('/auth/twitter', passport.authenticate('twitter'), function(req, res) { + * // request will be redirected to Twitter + * }); + * app.get('/auth/twitter/callback', passport.authenticate('twitter'), function(req, res) { + * res.json(req.user); + * }); + * + * @param {String} strategy + * @param {Object} options + * @param {Function} callback + * @return {Function} middleware + * @api public + */ +Authenticator.prototype.authenticate = function(strategy, options, callback) { + return this._framework.authenticate(this, strategy, options, callback); +}; + +/** + * Middleware that will authorize a third-party account using the given + * `strategy` name, with optional `options`. + * + * If authorization is successful, the result provided by the strategy's verify + * callback will be assigned to `req.account`. The existing login session and + * `req.user` will be unaffected. + * + * This function is particularly useful when connecting third-party accounts + * to the local account of a user that is currently authenticated. + * + * Examples: + * + * passport.authorize('twitter-authz', { failureRedirect: '/account' }); + * + * @param {String} strategy + * @param {Object} options + * @return {Function} middleware + * @api public + */ +Authenticator.prototype.authorize = function(strategy, options, callback) { + options = options || {}; + options.assignProperty = 'account'; + + var fn = this._framework.authorize || this._framework.authenticate; + return fn(this, strategy, options, callback); +}; + +/** + * Middleware that will restore login state from a session. + * + * Web applications typically use sessions to maintain login state between + * requests. For example, a user will authenticate by entering credentials into + * a form which is submitted to the server. If the credentials are valid, a + * login session is established by setting a cookie containing a session + * identifier in the user's web browser. The web browser will send this cookie + * in subsequent requests to the server, allowing a session to be maintained. + * + * If sessions are being utilized, and a login session has been established, + * this middleware will populate `req.user` with the current user. + * + * Note that sessions are not strictly required for Passport to operate. + * However, as a general rule, most web applications will make use of sessions. + * An exception to this rule would be an API server, which expects each HTTP + * request to provide credentials in an Authorization header. + * + * Examples: + * + * app.use(connect.cookieParser()); + * app.use(connect.session({ secret: 'keyboard cat' })); + * app.use(passport.initialize()); + * app.use(passport.session()); + * + * Options: + * - `pauseStream` Pause the request stream before deserializing the user + * object from the session. Defaults to _false_. Should + * be set to true in cases where middleware consuming the + * request body is configured after passport and the + * deserializeUser method is asynchronous. + * + * @param {Object} options + * @return {Function} middleware + * @api public + */ +Authenticator.prototype.session = function(options) { + return this.authenticate('session', options); +}; + +// TODO: Make session manager pluggable +/* +Authenticator.prototype.sessionManager = function(mgr) { + this._sm = mgr; + return this; +} +*/ + +/** + * Registers a function used to serialize user objects into the session. + * + * Examples: + * + * passport.serializeUser(function(user, done) { + * done(null, user.id); + * }); + * + * @api public + */ +Authenticator.prototype.serializeUser = function(fn, req, done) { + if (typeof fn === 'function') { + return this._serializers.push(fn); + } + + // private implementation that traverses the chain of serializers, attempting + // to serialize a user + var user = fn; + + // For backwards compatibility + if (typeof req === 'function') { + done = req; + req = undefined; + } + + var stack = this._serializers; + (function pass(i, err, obj) { + // serializers use 'pass' as an error to skip processing + if ('pass' === err) { + err = undefined; + } + // an error or serialized object was obtained, done + if (err || obj || obj === 0) { return done(err, obj); } + + var layer = stack[i]; + if (!layer) { + return done(new Error('Failed to serialize user into session')); + } + + + function serialized(e, o) { + pass(i + 1, e, o); + } + + try { + var arity = layer.length; + if (arity == 3) { + layer(req, user, serialized); + } else { + layer(user, serialized); + } + } catch(e) { + return done(e); + } + })(0); +}; + +/** + * Registers a function used to deserialize user objects out of the session. + * + * Examples: + * + * passport.deserializeUser(function(id, done) { + * User.findById(id, function (err, user) { + * done(err, user); + * }); + * }); + * + * @api public + */ +Authenticator.prototype.deserializeUser = function(fn, req, done) { + if (typeof fn === 'function') { + return this._deserializers.push(fn); + } + + // private implementation that traverses the chain of deserializers, + // attempting to deserialize a user + var obj = fn; + + // For backwards compatibility + if (typeof req === 'function') { + done = req; + req = undefined; + } + + var stack = this._deserializers; + (function pass(i, err, user) { + // deserializers use 'pass' as an error to skip processing + if ('pass' === err) { + err = undefined; + } + // an error or deserialized user was obtained, done + if (err || user) { return done(err, user); } + // a valid user existed when establishing the session, but that user has + // since been removed + if (user === null || user === false) { return done(null, false); } + + var layer = stack[i]; + if (!layer) { + return done(new Error('Failed to deserialize user out of session')); + } + + + function deserialized(e, u) { + pass(i + 1, e, u); + } + + try { + var arity = layer.length; + if (arity == 3) { + layer(req, obj, deserialized); + } else { + layer(obj, deserialized); + } + } catch(e) { + return done(e); + } + })(0); +}; + +/** + * Registers a function used to transform auth info. + * + * In some circumstances authorization details are contained in authentication + * credentials or loaded as part of verification. + * + * For example, when using bearer tokens for API authentication, the tokens may + * encode (either directly or indirectly in a database), details such as scope + * of access or the client to which the token was issued. + * + * Such authorization details should be enforced separately from authentication. + * Because Passport deals only with the latter, this is the responsiblity of + * middleware or routes further along the chain. However, it is not optimal to + * decode the same data or execute the same database query later. To avoid + * this, Passport accepts optional `info` along with the authenticated `user` + * in a strategy's `success()` action. This info is set at `req.authInfo`, + * where said later middlware or routes can access it. + * + * Optionally, applications can register transforms to proccess this info, + * which take effect prior to `req.authInfo` being set. This is useful, for + * example, when the info contains a client ID. The transform can load the + * client from the database and include the instance in the transformed info, + * allowing the full set of client properties to be convieniently accessed. + * + * If no transforms are registered, `info` supplied by the strategy will be left + * unmodified. + * + * Examples: + * + * passport.transformAuthInfo(function(info, done) { + * Client.findById(info.clientID, function (err, client) { + * info.client = client; + * done(err, info); + * }); + * }); + * + * @api public + */ +Authenticator.prototype.transformAuthInfo = function(fn, req, done) { + if (typeof fn === 'function') { + return this._infoTransformers.push(fn); + } + + // private implementation that traverses the chain of transformers, + // attempting to transform auth info + var info = fn; + + // For backwards compatibility + if (typeof req === 'function') { + done = req; + req = undefined; + } + + var stack = this._infoTransformers; + (function pass(i, err, tinfo) { + // transformers use 'pass' as an error to skip processing + if ('pass' === err) { + err = undefined; + } + // an error or transformed info was obtained, done + if (err || tinfo) { return done(err, tinfo); } + + var layer = stack[i]; + if (!layer) { + // if no transformers are registered (or they all pass), the default + // behavior is to use the un-transformed info as-is + return done(null, info); + } + + + function transformed(e, t) { + pass(i + 1, e, t); + } + + try { + var arity = layer.length; + if (arity == 1) { + // sync + var t = layer(info); + transformed(null, t); + } else if (arity == 3) { + layer(req, info, transformed); + } else { + layer(info, transformed); + } + } catch(e) { + return done(e); + } + })(0); +}; + +/** + * Return strategy with given `name`. + * + * @param {String} name + * @return {Strategy} + * @api private + */ +Authenticator.prototype._strategy = function(name) { + return this._strategies[name]; +}; + + +/** + * Expose `Authenticator`. + */ +module.exports = Authenticator; diff --git a/node_modules/passport/lib/errors/authenticationerror.js b/node_modules/passport/lib/errors/authenticationerror.js new file mode 100644 index 0000000..2b1da14 --- /dev/null +++ b/node_modules/passport/lib/errors/authenticationerror.js @@ -0,0 +1,20 @@ +/** + * `AuthenticationError` error. + * + * @constructor + * @api private + */ +function AuthenticationError(message, status) { + Error.call(this); + Error.captureStackTrace(this, arguments.callee); + this.name = 'AuthenticationError'; + this.message = message; + this.status = status || 401; +} + +// Inherit from `Error`. +AuthenticationError.prototype.__proto__ = Error.prototype; + + +// Expose constructor. +module.exports = AuthenticationError; diff --git a/node_modules/passport/lib/framework/connect.js b/node_modules/passport/lib/framework/connect.js new file mode 100644 index 0000000..7d2db6e --- /dev/null +++ b/node_modules/passport/lib/framework/connect.js @@ -0,0 +1,22 @@ +/** + * Module dependencies. + */ +var initialize = require('../middleware/initialize') + , authenticate = require('../middleware/authenticate'); + +/** + * Framework support for Connect/Express. + * + * This module provides support for using Passport with Express. It exposes + * middleware that conform to the `fn(req, res, next)` signature. + * + * @return {Object} + * @api protected + */ +exports = module.exports = function() { + + return { + initialize: initialize, + authenticate: authenticate + }; +}; diff --git a/node_modules/passport/lib/http/request.js b/node_modules/passport/lib/http/request.js new file mode 100644 index 0000000..0198539 --- /dev/null +++ b/node_modules/passport/lib/http/request.js @@ -0,0 +1,82 @@ +var req = exports = module.exports = {}; + +/** + * Initiate a login session for `user`. + * + * Options: + * - `session` Save login state in session, defaults to _true_ + * + * Examples: + * + * req.logIn(user, { session: false }); + * + * req.logIn(user, function(err) { + * if (err) { throw err; } + * // session saved + * }); + * + * @param {User} user + * @param {Object} options + * @param {Function} done + * @api public + */ +req.login = +req.logIn = function(user, options, done) { + if (typeof options == 'function') { + done = options; + options = {}; + } + options = options || {}; + + var property = this._userProperty || 'user'; + var session = (options.session === undefined) ? true : options.session; + + this[property] = user; + if (session && this._sessionManager) { + if (typeof done != 'function') { throw new Error('req#login requires a callback function'); } + + var self = this; + this._sessionManager.logIn(this, user, function(err) { + if (err) { self[property] = null; return done(err); } + done(); + }); + } else { + done && done(); + } +}; + +/** + * Terminate an existing login session. + * + * @api public + */ +req.logout = +req.logOut = function() { + var property = this._userProperty || 'user'; + + this[property] = null; + if (this._sessionManager) { + this._sessionManager.logOut(this); + } +}; + +/** + * Test if request is authenticated. + * + * @return {Boolean} + * @api public + */ +req.isAuthenticated = function() { + var property = this._userProperty || 'user'; + return (this[property]) ? true : false; +}; + +/** + * Test if request is unauthenticated. + * + * @return {Boolean} + * @api public + */ +req.isUnauthenticated = function() { + return !this.isAuthenticated(); +}; diff --git a/node_modules/passport/lib/index.js b/node_modules/passport/lib/index.js new file mode 100644 index 0000000..ab17469 --- /dev/null +++ b/node_modules/passport/lib/index.js @@ -0,0 +1,26 @@ +/** + * Module dependencies. + */ +var Passport = require('./authenticator') + , SessionStrategy = require('./strategies/session'); + + +/** + * Export default singleton. + * + * @api public + */ +exports = module.exports = new Passport(); + +/** + * Expose constructors. + */ +exports.Passport = +exports.Authenticator = Passport; +exports.Strategy = require('passport-strategy'); + +/** + * Expose strategies. + */ +exports.strategies = {}; +exports.strategies.SessionStrategy = SessionStrategy; diff --git a/node_modules/passport/lib/middleware/authenticate.js b/node_modules/passport/lib/middleware/authenticate.js new file mode 100644 index 0000000..ce290f2 --- /dev/null +++ b/node_modules/passport/lib/middleware/authenticate.js @@ -0,0 +1,372 @@ +/** + * Module dependencies. + */ +var http = require('http') + , IncomingMessageExt = require('../http/request') + , AuthenticationError = require('../errors/authenticationerror'); + + +/** + * Authenticates requests. + * + * Applies the `name`ed strategy (or strategies) to the incoming request, in + * order to authenticate the request. If authentication is successful, the user + * will be logged in and populated at `req.user` and a session will be + * established by default. If authentication fails, an unauthorized response + * will be sent. + * + * Options: + * - `session` Save login state in session, defaults to _true_ + * - `successRedirect` After successful login, redirect to given URL + * - `successMessage` True to store success message in + * req.session.messages, or a string to use as override + * message for success. + * - `successFlash` True to flash success messages or a string to use as a flash + * message for success (overrides any from the strategy itself). + * - `failureRedirect` After failed login, redirect to given URL + * - `failureMessage` True to store failure message in + * req.session.messages, or a string to use as override + * message for failure. + * - `failureFlash` True to flash failure messages or a string to use as a flash + * message for failures (overrides any from the strategy itself). + * - `assignProperty` Assign the object provided by the verify callback to given property + * + * An optional `callback` can be supplied to allow the application to override + * the default manner in which authentication attempts are handled. The + * callback has the following signature, where `user` will be set to the + * authenticated user on a successful authentication attempt, or `false` + * otherwise. An optional `info` argument will be passed, containing additional + * details provided by the strategy's verify callback - this could be information about + * a successful authentication or a challenge message for a failed authentication. + * An optional `status` argument will be passed when authentication fails - this could + * be a HTTP response code for a remote authentication failure or similar. + * + * app.get('/protected', function(req, res, next) { + * passport.authenticate('local', function(err, user, info, status) { + * if (err) { return next(err) } + * if (!user) { return res.redirect('/signin') } + * res.redirect('/account'); + * })(req, res, next); + * }); + * + * Note that if a callback is supplied, it becomes the application's + * responsibility to log-in the user, establish a session, and otherwise perform + * the desired operations. + * + * Examples: + * + * passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }); + * + * passport.authenticate('basic', { session: false }); + * + * passport.authenticate('twitter'); + * + * @param {Strategy|String|Array} name + * @param {Object} options + * @param {Function} callback + * @return {Function} + * @api public + */ +module.exports = function authenticate(passport, name, options, callback) { + if (typeof options == 'function') { + callback = options; + options = {}; + } + options = options || {}; + + var multi = true; + + // Cast `name` to an array, allowing authentication to pass through a chain of + // strategies. The first strategy to succeed, redirect, or error will halt + // the chain. Authentication failures will proceed through each strategy in + // series, ultimately failing if all strategies fail. + // + // This is typically used on API endpoints to allow clients to authenticate + // using their preferred choice of Basic, Digest, token-based schemes, etc. + // It is not feasible to construct a chain of multiple strategies that involve + // redirection (for example both Facebook and Twitter), since the first one to + // redirect will halt the chain. + if (!Array.isArray(name)) { + name = [ name ]; + multi = false; + } + + return function authenticate(req, res, next) { + req.login = + req.logIn = req.logIn || IncomingMessageExt.logIn; + req.logout = + req.logOut = req.logOut || IncomingMessageExt.logOut; + req.isAuthenticated = req.isAuthenticated || IncomingMessageExt.isAuthenticated; + req.isUnauthenticated = req.isUnauthenticated || IncomingMessageExt.isUnauthenticated; + + req._sessionManager = passport._sm; + + // accumulator for failures from each strategy in the chain + var failures = []; + + function allFailed() { + if (callback) { + if (!multi) { + return callback(null, false, failures[0].challenge, failures[0].status); + } else { + var challenges = failures.map(function(f) { return f.challenge; }); + var statuses = failures.map(function(f) { return f.status; }); + return callback(null, false, challenges, statuses); + } + } + + // Strategies are ordered by priority. For the purpose of flashing a + // message, the first failure will be displayed. + var failure = failures[0] || {} + , challenge = failure.challenge || {} + , msg; + + if (options.failureFlash) { + var flash = options.failureFlash; + if (typeof flash == 'string') { + flash = { type: 'error', message: flash }; + } + flash.type = flash.type || 'error'; + + var type = flash.type || challenge.type || 'error'; + msg = flash.message || challenge.message || challenge; + if (typeof msg == 'string') { + req.flash(type, msg); + } + } + if (options.failureMessage) { + msg = options.failureMessage; + if (typeof msg == 'boolean') { + msg = challenge.message || challenge; + } + if (typeof msg == 'string') { + req.session.messages = req.session.messages || []; + req.session.messages.push(msg); + } + } + if (options.failureRedirect) { + return res.redirect(options.failureRedirect); + } + + // When failure handling is not delegated to the application, the default + // is to respond with 401 Unauthorized. Note that the WWW-Authenticate + // header will be set according to the strategies in use (see + // actions#fail). If multiple strategies failed, each of their challenges + // will be included in the response. + var rchallenge = [] + , rstatus, status; + + for (var j = 0, len = failures.length; j < len; j++) { + failure = failures[j]; + challenge = failure.challenge; + status = failure.status; + + rstatus = rstatus || status; + if (typeof challenge == 'string') { + rchallenge.push(challenge); + } + } + + res.statusCode = rstatus || 401; + if (res.statusCode == 401 && rchallenge.length) { + res.setHeader('WWW-Authenticate', rchallenge); + } + if (options.failWithError) { + return next(new AuthenticationError(http.STATUS_CODES[res.statusCode], rstatus)); + } + res.end(http.STATUS_CODES[res.statusCode]); + } + + (function attempt(i) { + var layer = name[i]; + // If no more strategies exist in the chain, authentication has failed. + if (!layer) { return allFailed(); } + + // Get the strategy, which will be used as prototype from which to create + // a new instance. Action functions will then be bound to the strategy + // within the context of the HTTP request/response pair. + var strategy, prototype; + if (typeof layer.authenticate == 'function') { + strategy = layer; + } else { + prototype = passport._strategy(layer); + if (!prototype) { return next(new Error('Unknown authentication strategy "' + layer + '"')); } + + strategy = Object.create(prototype); + } + + + // ----- BEGIN STRATEGY AUGMENTATION ----- + // Augment the new strategy instance with action functions. These action + // functions are bound via closure the the request/response pair. The end + // goal of the strategy is to invoke *one* of these action methods, in + // order to indicate successful or failed authentication, redirect to a + // third-party identity provider, etc. + + /** + * Authenticate `user`, with optional `info`. + * + * Strategies should call this function to successfully authenticate a + * user. `user` should be an object supplied by the application after it + * has been given an opportunity to verify credentials. `info` is an + * optional argument containing additional user information. This is + * useful for third-party authentication strategies to pass profile + * details. + * + * @param {Object} user + * @param {Object} info + * @api public + */ + strategy.success = function(user, info) { + if (callback) { + return callback(null, user, info); + } + + info = info || {}; + var msg; + + if (options.successFlash) { + var flash = options.successFlash; + if (typeof flash == 'string') { + flash = { type: 'success', message: flash }; + } + flash.type = flash.type || 'success'; + + var type = flash.type || info.type || 'success'; + msg = flash.message || info.message || info; + if (typeof msg == 'string') { + req.flash(type, msg); + } + } + if (options.successMessage) { + msg = options.successMessage; + if (typeof msg == 'boolean') { + msg = info.message || info; + } + if (typeof msg == 'string') { + req.session.messages = req.session.messages || []; + req.session.messages.push(msg); + } + } + if (options.assignProperty) { + req[options.assignProperty] = user; + return next(); + } + + req.logIn(user, options, function(err) { + if (err) { return next(err); } + + function complete() { + if (options.successReturnToOrRedirect) { + var url = options.successReturnToOrRedirect; + if (req.session && req.session.returnTo) { + url = req.session.returnTo; + delete req.session.returnTo; + } + return res.redirect(url); + } + if (options.successRedirect) { + return res.redirect(options.successRedirect); + } + next(); + } + + if (options.authInfo !== false) { + passport.transformAuthInfo(info, req, function(err, tinfo) { + if (err) { return next(err); } + req.authInfo = tinfo; + complete(); + }); + } else { + complete(); + } + }); + }; + + /** + * Fail authentication, with optional `challenge` and `status`, defaulting + * to 401. + * + * Strategies should call this function to fail an authentication attempt. + * + * @param {String} challenge + * @param {Number} status + * @api public + */ + strategy.fail = function(challenge, status) { + if (typeof challenge == 'number') { + status = challenge; + challenge = undefined; + } + + // push this failure into the accumulator and attempt authentication + // using the next strategy + failures.push({ challenge: challenge, status: status }); + attempt(i + 1); + }; + + /** + * Redirect to `url` with optional `status`, defaulting to 302. + * + * Strategies should call this function to redirect the user (via their + * user agent) to a third-party website for authentication. + * + * @param {String} url + * @param {Number} status + * @api public + */ + strategy.redirect = function(url, status) { + // NOTE: Do not use `res.redirect` from Express, because it can't decide + // what it wants. + // + // Express 2.x: res.redirect(url, status) + // Express 3.x: res.redirect(status, url) -OR- res.redirect(url, status) + // - as of 3.14.0, deprecated warnings are issued if res.redirect(url, status) + // is used + // Express 4.x: res.redirect(status, url) + // - all versions (as of 4.8.7) continue to accept res.redirect(url, status) + // but issue deprecated versions + + res.statusCode = status || 302; + res.setHeader('Location', url); + res.setHeader('Content-Length', '0'); + res.end(); + }; + + /** + * Pass without making a success or fail decision. + * + * Under most circumstances, Strategies should not need to call this + * function. It exists primarily to allow previous authentication state + * to be restored, for example from an HTTP session. + * + * @api public + */ + strategy.pass = function() { + next(); + }; + + /** + * Internal error while performing authentication. + * + * Strategies should call this function when an internal error occurs + * during the process of performing authentication; for example, if the + * user directory is not available. + * + * @param {Error} err + * @api public + */ + strategy.error = function(err) { + if (callback) { + return callback(err); + } + + next(err); + }; + + // ----- END STRATEGY AUGMENTATION ----- + + strategy.authenticate(req, options); + })(0); // attempt + }; +}; diff --git a/node_modules/passport/lib/middleware/initialize.js b/node_modules/passport/lib/middleware/initialize.js new file mode 100644 index 0000000..47ba7e8 --- /dev/null +++ b/node_modules/passport/lib/middleware/initialize.js @@ -0,0 +1,91 @@ +/** + * Module dependencies. + */ +var IncomingMessageExt = require('../http/request'); + + +/** + * Passport initialization. + * + * Intializes Passport for incoming requests, allowing authentication strategies + * to be applied. + * + * If sessions are being utilized, applications must set up Passport with + * functions to serialize a user into and out of a session. For example, a + * common pattern is to serialize just the user ID into the session (due to the + * fact that it is desirable to store the minimum amount of data in a session). + * When a subsequent request arrives for the session, the full User object can + * be loaded from the database by ID. + * + * Note that additional middleware is required to persist login state, so we + * must use the `connect.session()` middleware _before_ `passport.initialize()`. + * + * If sessions are being used, this middleware must be in use by the + * Connect/Express application for Passport to operate. If the application is + * entirely stateless (not using sessions), this middleware is not necessary, + * but its use will not have any adverse impact. + * + * Examples: + * + * app.use(connect.cookieParser()); + * app.use(connect.session({ secret: 'keyboard cat' })); + * app.use(passport.initialize()); + * app.use(passport.session()); + * + * passport.serializeUser(function(user, done) { + * done(null, user.id); + * }); + * + * passport.deserializeUser(function(id, done) { + * User.findById(id, function (err, user) { + * done(err, user); + * }); + * }); + * + * @return {Function} + * @api public + */ +module.exports = function initialize(passport, options) { + options = options || {}; + + return function initialize(req, res, next) { + if (options.userProperty) { + req._userProperty = options.userProperty; + } + + var compat = (options.compat === undefined) ? true : options.compat; + if (compat) { + // `passport@0.5.1` [removed][1] all internal use of `req._passport`. + // From the standpoint of this package, this should have been a + // non-breaking change. However, some strategies (such as `passport-azure-ad`) + // depend directly on `passport@0.4.x` or earlier. `require`-ing earlier + // versions of `passport` has the effect of monkeypatching `http.IncomingMessage` + // with `logIn`, `logOut`, `isAuthenticated` and `isUnauthenticated` + // functions that [expect][2] the `req._passport` property to exist. + // Since pre-existing functions on `req` are given [preference][3], this + // results in [issues][4]. + // + // The changes here restore the expected properties needed when earlier + // versions of `passport` are `require`-ed. This compatibility mode is + // enabled by default, and can be disabld by simply not `use`-ing `passport.initialize()` + // middleware or setting `compat: false` as an option to the middleware. + // + // An alternative approach to addressing this issue would be to not + // preferentially use pre-existing functions on `req`, but rather always + // overwrite `req.logIn`, etc. with the versions of those functions shiped + // with `authenticate()` middleware. This option should be reconsidered + // in a future major version release. + // + // [1]: https://github.com/jaredhanson/passport/pull/875 + // [2]: https://github.com/jaredhanson/passport/blob/v0.4.1/lib/http/request.js + // [3]: https://github.com/jaredhanson/passport/blob/v0.5.1/lib/middleware/authenticate.js#L96 + // [4]: https://github.com/jaredhanson/passport/issues/877 + passport._userProperty = options.userProperty || 'user'; + + req._passport = {}; + req._passport.instance = passport; + } + + next(); + }; +}; diff --git a/node_modules/passport/lib/sessionmanager.js b/node_modules/passport/lib/sessionmanager.js new file mode 100644 index 0000000..3d5c51c --- /dev/null +++ b/node_modules/passport/lib/sessionmanager.js @@ -0,0 +1,39 @@ +function SessionManager(options, serializeUser) { + if (typeof options == 'function') { + serializeUser = options; + options = undefined; + } + options = options || {}; + + this._key = options.key || 'passport'; + this._serializeUser = serializeUser; +} + +SessionManager.prototype.logIn = function(req, user, cb) { + var self = this; + this._serializeUser(user, req, function(err, obj) { + if (err) { + return cb(err); + } + // TODO: Error if session isn't available here. + if (!req.session) { + req.session = {}; + } + if (!req.session[self._key]) { + req.session[self._key] = {}; + } + req.session[self._key].user = obj; + cb(); + }); +} + +SessionManager.prototype.logOut = function(req, cb) { + if (req.session && req.session[this._key]) { + delete req.session[this._key].user; + } + + cb && cb(); +} + + +module.exports = SessionManager; diff --git a/node_modules/passport/lib/strategies/session.js b/node_modules/passport/lib/strategies/session.js new file mode 100644 index 0000000..9c6c6df --- /dev/null +++ b/node_modules/passport/lib/strategies/session.js @@ -0,0 +1,83 @@ +/** + * Module dependencies. + */ +var pause = require('pause') + , util = require('util') + , Strategy = require('passport-strategy'); + + +/** + * `SessionStrategy` constructor. + * + * @api public + */ +function SessionStrategy(options, deserializeUser) { + if (typeof options == 'function') { + deserializeUser = options; + options = undefined; + } + options = options || {}; + + Strategy.call(this); + this.name = 'session'; + this._key = options.key || 'passport'; + this._deserializeUser = deserializeUser; +} + +/** + * Inherit from `Strategy`. + */ +util.inherits(SessionStrategy, Strategy); + +/** + * Authenticate request based on the current session state. + * + * The session authentication strategy uses the session to restore any login + * state across requests. If a login session has been established, `req.user` + * will be populated with the current user. + * + * This strategy is registered automatically by Passport. + * + * @param {Object} req + * @param {Object} options + * @api protected + */ +SessionStrategy.prototype.authenticate = function(req, options) { + if (!req.session) { return this.error(new Error('Login sessions require session support. Did you forget to use `express-session` middleware?')); } + options = options || {}; + + var self = this, + su; + if (req.session[this._key]) { + su = req.session[this._key].user; + } + + if (su || su === 0) { + // NOTE: Stream pausing is desirable in the case where later middleware is + // listening for events emitted from request. For discussion on the + // matter, refer to: https://github.com/jaredhanson/passport/pull/106 + + var paused = options.pauseStream ? pause(req) : null; + this._deserializeUser(su, req, function(err, user) { + if (err) { return self.error(err); } + if (!user) { + delete req.session[self._key].user; + } else { + var property = req._userProperty || 'user'; + req[property] = user; + } + self.pass(); + if (paused) { + paused.resume(); + } + }); + } else { + self.pass(); + } +}; + + +/** + * Expose `SessionStrategy`. + */ +module.exports = SessionStrategy; diff --git a/node_modules/passport/package.json b/node_modules/passport/package.json new file mode 100644 index 0000000..cb45a4a --- /dev/null +++ b/node_modules/passport/package.json @@ -0,0 +1,55 @@ +{ + "name": "passport", + "version": "0.5.2", + "description": "Simple, unobtrusive authentication for Node.js.", + "keywords": [ + "express", + "connect", + "auth", + "authn", + "authentication" + ], + "author": { + "name": "Jared Hanson", + "email": "jaredhanson@gmail.com", + "url": "https://www.jaredhanson.me/" + }, + "homepage": "https://www.passportjs.org/", + "repository": { + "type": "git", + "url": "git://github.com/jaredhanson/passport.git" + }, + "bugs": { + "url": "https://github.com/jaredhanson/passport/issues" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jaredhanson" + }, + "license": "MIT", + "licenses": [ + { + "type": "MIT", + "url": "https://opensource.org/licenses/MIT" + } + ], + "main": "./lib", + "dependencies": { + "passport-strategy": "1.x.x", + "pause": "0.0.1" + }, + "devDependencies": { + "make-node": "0.3.x", + "mocha": "2.x.x", + "chai": "2.x.x", + "chai-connect-middleware": "0.3.x", + "chai-passport-strategy": "0.2.x", + "proxyquire": "1.4.x" + }, + "engines": { + "node": ">= 0.4.0" + }, + "scripts": { + "test": "node_modules/.bin/mocha --reporter spec --require test/bootstrap/node test/*.test.js test/**/*.test.js" + } +} diff --git a/node_modules/passport/sponsors/loginradius.png b/node_modules/passport/sponsors/loginradius.png new file mode 100644 index 0000000000000000000000000000000000000000..884f0f47dfd4a441194317faa071895c740b3aeb GIT binary patch literal 10888 zcmZ{K1ymf{vNrDS&fpMaa0~A4PH=Y_G!Wd~gS)$1aEIXTF2Mr9HT>k9``$hOUH8pe zJ>9#izWvo#yKAr2Gaas^Ac>4XfB*&thAb^5rt*Hiem_{@VBWvOMb4StPv9UGNfEH> zNuuNT0lcG>HV6z15%bRh4wjyY2L=X3VWp=3)f!u(P!X@p|x+{}sXee*MP`BnSKz;$p*3t|hMo5Or`i18^|0Gcl73AOHXW zK4(*NUKKHkf5G2J{N$D{E{?oFpu4*}lRF!egR=#Yg@=a+$jl04Wo3MiU<7&EyBK*e z+Jh+mp5%Y#5i*D+?BMFcPfq@a=zl+d=jmc){%N%+}1#%-#j`j$`?+bnmtOU*P|j zq=%8?-(-Ik@o#N>e=_G)F#|c+y8bDFy1kW)04v{Lg8tL|?~4455_Pb1bT$Kl-eCgF z|APF}_Mh=u|E3Y(`X7#e8vhfZ=xp__)aXxM0xbU`_^0hZEN z{sA;K;RU%GTbr4<{A0P^7wxZ`U&P1)_zyE5@V`d$z26GF@(!j}=AL3kE@lF(%&g3e zEUb(yEN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IU6$9tffDxf^i&21{E`Z0MV z_?aaxBeiWxRgz(#;}~O{teIv}Y|g3Inwt>QBikZ1b*qU5>nX3=q=v!E*-Z5qp9m-{ zO_XoZ@(D%6rzo0(h7EY=;UJ8GA9o$-jb41i48bRIgk?FAQ4VeG z=T0`IlqYQ`lROTToYD(5(KE3z963F~yNb(-w&ms{^!h?NNTX^0{yg<~vn>=eJ)hqG z*2jKWfhEhv1=k$2OJpS<%7USals(H#){rub(FI8$bBn&Z=iPvc38SMpZVyRP`H?iG z<{PtOjDtl#SY*=+w7wRma1?W0GuwEzt{;a^>5Uezk+g$&-MZfe{}%Vlftv^)Ys7?h zTP8%XS$H(AeFc7Ehe)p=wXwN9jsT%auXM4~z(zP*)5go=DN8JPR03xR;f`V5{hZ7h z`4jlzEdBf^O}Na2X>gH4YPhpP=al6|A(=P&U}J1aelq%bdRTO3=4GS~!OgNkdKhnv z@}vu+&R2BSbA)mNPmAohHE#3R_%pk&RUeE@(XJ440or0#jcM9x@;WUwI5^6-c U+XQ|7ydEkot{_$|Vi@rM0KWR)8~^|S literal 0 HcmV?d00001 diff --git a/node_modules/passport/sponsors/workos.png b/node_modules/passport/sponsors/workos.png new file mode 100644 index 0000000000000000000000000000000000000000..514b691edb37fdfef2fe8f165a72cf6b04b91739 GIT binary patch literal 6854 zcma)hbyQT}`|b=OF*GuO3^ho{kVB`y(2WcYQi8+~N;e2d3rGzqB^?q1(n_aDiPX?2 zA|VYIzu(XO{O6Ggj(<2< z06>%@0Ouc$$zA`qsNB`RKL72p^MU`Pn2+@@`$InVzgY0ETg)l_Uj+h`im@jE0HXX` zfq*PD&7GRDqXE(jsi`4hnCo{y`-Vgzk&WO|6Qk-qy7Ixa`pTtt-Azae`jC;1^Z&B_6Gsa6H~9atnEz(_AM0JJGK5mFf45DBkk(=q4*;M+s4B`E_yB+A z5TMMyroFsuY-KgBH-TGW-xC5lV~K?hW_%?Z;+LbrqIHT61=uIc_Y!fIbdhARBCTFz z%gMh6Cfc%zQQ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mlNTAZ~G6Jw$&&r%k)e z$@r9dZ}WIt5*!%2bdDaoi8^tMu$I*o=S)r}d=-k#-5AL47b@nV2M83W$>0Ms6f^(n>t{XxL}Qm@Eb6Q0p>yF zuYV@j)jc`2w_L;^B(C45S*aa2&} zmE^e1fU=5i=(VF+ibDIJ&{8MHZ~WKUo83NT<&nHpZ!pJ&bad_>1LuwbFU#(B&hg%Qo^o4v0FO_rLh$fyyEh(=0|T% z%%S2s>if*$@uXpXk&I~yZR72Uu~oJNnO5Mah`Cflo$gs{j6-QB~4XtX8lJ`(J+mbG`ro literal 0 HcmV?d00001 diff --git a/node_modules/path-is-absolute/index.js b/node_modules/path-is-absolute/index.js new file mode 100644 index 0000000..22aa6c3 --- /dev/null +++ b/node_modules/path-is-absolute/index.js @@ -0,0 +1,20 @@ +'use strict'; + +function posix(path) { + return path.charAt(0) === '/'; +} + +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} + +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; diff --git a/node_modules/path-is-absolute/license b/node_modules/path-is-absolute/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/path-is-absolute/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/path-is-absolute/package.json b/node_modules/path-is-absolute/package.json new file mode 100644 index 0000000..91196d5 --- /dev/null +++ b/node_modules/path-is-absolute/package.json @@ -0,0 +1,43 @@ +{ + "name": "path-is-absolute", + "version": "1.0.1", + "description": "Node.js 0.12 path.isAbsolute() ponyfill", + "license": "MIT", + "repository": "sindresorhus/path-is-absolute", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && node test.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "path", + "paths", + "file", + "dir", + "absolute", + "isabsolute", + "is-absolute", + "built-in", + "util", + "utils", + "core", + "ponyfill", + "polyfill", + "shim", + "is", + "detect", + "check" + ], + "devDependencies": { + "xo": "^0.16.0" + } +} diff --git a/node_modules/path-is-absolute/readme.md b/node_modules/path-is-absolute/readme.md new file mode 100644 index 0000000..8dbdf5f --- /dev/null +++ b/node_modules/path-is-absolute/readme.md @@ -0,0 +1,59 @@ +# path-is-absolute [![Build Status](https://travis-ci.org/sindresorhus/path-is-absolute.svg?branch=master)](https://travis-ci.org/sindresorhus/path-is-absolute) + +> Node.js 0.12 [`path.isAbsolute()`](http://nodejs.org/api/path.html#path_path_isabsolute_path) [ponyfill](https://ponyfill.com) + + +## Install + +``` +$ npm install --save path-is-absolute +``` + + +## Usage + +```js +const pathIsAbsolute = require('path-is-absolute'); + +// Running on Linux +pathIsAbsolute('/home/foo'); +//=> true +pathIsAbsolute('C:/Users/foo'); +//=> false + +// Running on Windows +pathIsAbsolute('C:/Users/foo'); +//=> true +pathIsAbsolute('/home/foo'); +//=> false + +// Running on any OS +pathIsAbsolute.posix('/home/foo'); +//=> true +pathIsAbsolute.posix('C:/Users/foo'); +//=> false +pathIsAbsolute.win32('C:/Users/foo'); +//=> true +pathIsAbsolute.win32('/home/foo'); +//=> false +``` + + +## API + +See the [`path.isAbsolute()` docs](http://nodejs.org/api/path.html#path_path_isabsolute_path). + +### pathIsAbsolute(path) + +### pathIsAbsolute.posix(path) + +POSIX specific version. + +### pathIsAbsolute.win32(path) + +Windows specific version. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/path-to-regexp/History.md b/node_modules/path-to-regexp/History.md new file mode 100644 index 0000000..7f65878 --- /dev/null +++ b/node_modules/path-to-regexp/History.md @@ -0,0 +1,36 @@ +0.1.7 / 2015-07-28 +================== + + * Fixed regression with escaped round brackets and matching groups. + +0.1.6 / 2015-06-19 +================== + + * Replace `index` feature by outputting all parameters, unnamed and named. + +0.1.5 / 2015-05-08 +================== + + * Add an index property for position in match result. + +0.1.4 / 2015-03-05 +================== + + * Add license information + +0.1.3 / 2014-07-06 +================== + + * Better array support + * Improved support for trailing slash in non-ending mode + +0.1.0 / 2014-03-06 +================== + + * add options.end + +0.0.2 / 2013-02-10 +================== + + * Update to match current express + * add .license property to component.json diff --git a/node_modules/path-to-regexp/LICENSE b/node_modules/path-to-regexp/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/node_modules/path-to-regexp/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/path-to-regexp/Readme.md b/node_modules/path-to-regexp/Readme.md new file mode 100644 index 0000000..95452a6 --- /dev/null +++ b/node_modules/path-to-regexp/Readme.md @@ -0,0 +1,35 @@ +# Path-to-RegExp + +Turn an Express-style path string such as `/user/:name` into a regular expression. + +**Note:** This is a legacy branch. You should upgrade to `1.x`. + +## Usage + +```javascript +var pathToRegexp = require('path-to-regexp'); +``` + +### pathToRegexp(path, keys, options) + + - **path** A string in the express format, an array of such strings, or a regular expression + - **keys** An array to be populated with the keys present in the url. Once the function completes, this will be an array of strings. + - **options** + - **options.sensitive** Defaults to false, set this to true to make routes case sensitive + - **options.strict** Defaults to false, set this to true to make the trailing slash matter. + - **options.end** Defaults to true, set this to false to only match the prefix of the URL. + +```javascript +var keys = []; +var exp = pathToRegexp('/foo/:bar', keys); +//keys = ['bar'] +//exp = /^\/foo\/(?:([^\/]+?))\/?$/i +``` + +## Live Demo + +You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.com/express-route-tester/). + +## License + + MIT diff --git a/node_modules/path-to-regexp/index.js b/node_modules/path-to-regexp/index.js new file mode 100644 index 0000000..500d1da --- /dev/null +++ b/node_modules/path-to-regexp/index.js @@ -0,0 +1,129 @@ +/** + * Expose `pathtoRegexp`. + */ + +module.exports = pathtoRegexp; + +/** + * Match matching groups in a regular expression. + */ +var MATCHING_GROUP_REGEXP = /\((?!\?)/g; + +/** + * Normalize the given path string, + * returning a regular expression. + * + * An empty array should be passed, + * which will contain the placeholder + * key names. For example "/user/:id" will + * then contain ["id"]. + * + * @param {String|RegExp|Array} path + * @param {Array} keys + * @param {Object} options + * @return {RegExp} + * @api private + */ + +function pathtoRegexp(path, keys, options) { + options = options || {}; + keys = keys || []; + var strict = options.strict; + var end = options.end !== false; + var flags = options.sensitive ? '' : 'i'; + var extraOffset = 0; + var keysOffset = keys.length; + var i = 0; + var name = 0; + var m; + + if (path instanceof RegExp) { + while (m = MATCHING_GROUP_REGEXP.exec(path.source)) { + keys.push({ + name: name++, + optional: false, + offset: m.index + }); + } + + return path; + } + + if (Array.isArray(path)) { + // Map array parts into regexps and return their source. We also pass + // the same keys and options instance into every generation to get + // consistent matching groups before we join the sources together. + path = path.map(function (value) { + return pathtoRegexp(value, keys, options).source; + }); + + return new RegExp('(?:' + path.join('|') + ')', flags); + } + + path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?')) + .replace(/\/\(/g, '/(?:') + .replace(/([\/\.])/g, '\\$1') + .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) { + slash = slash || ''; + format = format || ''; + capture = capture || '([^\\/' + format + ']+?)'; + optional = optional || ''; + + keys.push({ + name: key, + optional: !!optional, + offset: offset + extraOffset + }); + + var result = '' + + (optional ? '' : slash) + + '(?:' + + format + (optional ? slash : '') + capture + + (star ? '((?:[\\/' + format + '].+?)?)' : '') + + ')' + + optional; + + extraOffset += result.length - match.length; + + return result; + }) + .replace(/\*/g, function (star, index) { + var len = keys.length + + while (len-- > keysOffset && keys[len].offset > index) { + keys[len].offset += 3; // Replacement length minus asterisk length. + } + + return '(.*)'; + }); + + // This is a workaround for handling unnamed matching groups. + while (m = MATCHING_GROUP_REGEXP.exec(path)) { + var escapeCount = 0; + var index = m.index; + + while (path.charAt(--index) === '\\') { + escapeCount++; + } + + // It's possible to escape the bracket. + if (escapeCount % 2 === 1) { + continue; + } + + if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) { + keys.splice(keysOffset + i, 0, { + name: name++, // Unnamed matching groups must be consistently linear. + optional: false, + offset: m.index + }); + } + + i++; + } + + // If the path is non-ending, match until the end or a slash. + path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)')); + + return new RegExp(path, flags); +}; diff --git a/node_modules/path-to-regexp/package.json b/node_modules/path-to-regexp/package.json new file mode 100644 index 0000000..d4e51b5 --- /dev/null +++ b/node_modules/path-to-regexp/package.json @@ -0,0 +1,30 @@ +{ + "name": "path-to-regexp", + "description": "Express style path to RegExp utility", + "version": "0.1.7", + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "keywords": [ + "express", + "regexp" + ], + "component": { + "scripts": { + "path-to-regexp": "index.js" + } + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/component/path-to-regexp.git" + }, + "devDependencies": { + "mocha": "^1.17.1", + "istanbul": "^0.2.6" + } +} diff --git a/node_modules/pause/.npmignore b/node_modules/pause/.npmignore new file mode 100644 index 0000000..f1250e5 --- /dev/null +++ b/node_modules/pause/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/node_modules/pause/History.md b/node_modules/pause/History.md new file mode 100644 index 0000000..c8aa68f --- /dev/null +++ b/node_modules/pause/History.md @@ -0,0 +1,5 @@ + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/pause/Makefile b/node_modules/pause/Makefile new file mode 100644 index 0000000..4e9c8d3 --- /dev/null +++ b/node_modules/pause/Makefile @@ -0,0 +1,7 @@ + +test: + @./node_modules/.bin/mocha \ + --require should \ + --reporter spec + +.PHONY: test \ No newline at end of file diff --git a/node_modules/pause/Readme.md b/node_modules/pause/Readme.md new file mode 100644 index 0000000..1cdd68a --- /dev/null +++ b/node_modules/pause/Readme.md @@ -0,0 +1,29 @@ + +# pause + + Pause streams... + +## License + +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> + +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. \ No newline at end of file diff --git a/node_modules/pause/index.js b/node_modules/pause/index.js new file mode 100644 index 0000000..1b7b379 --- /dev/null +++ b/node_modules/pause/index.js @@ -0,0 +1,29 @@ + +module.exports = function(obj){ + var onData + , onEnd + , events = []; + + // buffer data + obj.on('data', onData = function(data, encoding){ + events.push(['data', data, encoding]); + }); + + // buffer end + obj.on('end', onEnd = function(data, encoding){ + events.push(['end', data, encoding]); + }); + + return { + end: function(){ + obj.removeListener('data', onData); + obj.removeListener('end', onEnd); + }, + resume: function(){ + this.end(); + for (var i = 0, len = events.length; i < len; ++i) { + obj.emit.apply(obj, events[i]); + } + } + }; +}; \ No newline at end of file diff --git a/node_modules/pause/package.json b/node_modules/pause/package.json new file mode 100644 index 0000000..ae472ac --- /dev/null +++ b/node_modules/pause/package.json @@ -0,0 +1,13 @@ +{ + "name": "pause", + "version": "0.0.1", + "description": "Pause streams...", + "keywords": [], + "author": "TJ Holowaychuk ", + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "main": "index" +} \ No newline at end of file diff --git a/node_modules/proxy-addr/HISTORY.md b/node_modules/proxy-addr/HISTORY.md new file mode 100644 index 0000000..8480242 --- /dev/null +++ b/node_modules/proxy-addr/HISTORY.md @@ -0,0 +1,161 @@ +2.0.7 / 2021-05-31 +================== + + * deps: forwarded@0.2.0 + - Use `req.socket` over deprecated `req.connection` + +2.0.6 / 2020-02-24 +================== + + * deps: ipaddr.js@1.9.1 + +2.0.5 / 2019-04-16 +================== + + * deps: ipaddr.js@1.9.0 + +2.0.4 / 2018-07-26 +================== + + * deps: ipaddr.js@1.8.0 + +2.0.3 / 2018-02-19 +================== + + * deps: ipaddr.js@1.6.0 + +2.0.2 / 2017-09-24 +================== + + * deps: forwarded@~0.1.2 + - perf: improve header parsing + - perf: reduce overhead when no `X-Forwarded-For` header + +2.0.1 / 2017-09-10 +================== + + * deps: forwarded@~0.1.1 + - Fix trimming leading / trailing OWS + - perf: hoist regular expression + * deps: ipaddr.js@1.5.2 + +2.0.0 / 2017-08-08 +================== + + * Drop support for Node.js below 0.10 + +1.1.5 / 2017-07-25 +================== + + * Fix array argument being altered + * deps: ipaddr.js@1.4.0 + +1.1.4 / 2017-03-24 +================== + + * deps: ipaddr.js@1.3.0 + +1.1.3 / 2017-01-14 +================== + + * deps: ipaddr.js@1.2.0 + +1.1.2 / 2016-05-29 +================== + + * deps: ipaddr.js@1.1.1 + - Fix IPv6-mapped IPv4 validation edge cases + +1.1.1 / 2016-05-03 +================== + + * Fix regression matching mixed versions against multiple subnets + +1.1.0 / 2016-05-01 +================== + + * Fix accepting various invalid netmasks + - IPv4 netmasks must be contingous + - IPv6 addresses cannot be used as a netmask + * deps: ipaddr.js@1.1.0 + +1.0.10 / 2015-12-09 +=================== + + * deps: ipaddr.js@1.0.5 + - Fix regression in `isValid` with non-string arguments + +1.0.9 / 2015-12-01 +================== + + * deps: ipaddr.js@1.0.4 + - Fix accepting some invalid IPv6 addresses + - Reject CIDRs with negative or overlong masks + * perf: enable strict mode + +1.0.8 / 2015-05-10 +================== + + * deps: ipaddr.js@1.0.1 + +1.0.7 / 2015-03-16 +================== + + * deps: ipaddr.js@0.1.9 + - Fix OOM on certain inputs to `isValid` + +1.0.6 / 2015-02-01 +================== + + * deps: ipaddr.js@0.1.8 + +1.0.5 / 2015-01-08 +================== + + * deps: ipaddr.js@0.1.6 + +1.0.4 / 2014-11-23 +================== + + * deps: ipaddr.js@0.1.5 + - Fix edge cases with `isValid` + +1.0.3 / 2014-09-21 +================== + + * Use `forwarded` npm module + +1.0.2 / 2014-09-18 +================== + + * Fix a global leak when multiple subnets are trusted + * Support Node.js 0.6 + * deps: ipaddr.js@0.1.3 + +1.0.1 / 2014-06-03 +================== + + * Fix links in npm package + +1.0.0 / 2014-05-08 +================== + + * Add `trust` argument to determine proxy trust on + * Accepts custom function + * Accepts IPv4/IPv6 address(es) + * Accepts subnets + * Accepts pre-defined names + * Add optional `trust` argument to `proxyaddr.all` to + stop at first untrusted + * Add `proxyaddr.compile` to pre-compile `trust` function + to make subsequent calls faster + +0.0.1 / 2014-05-04 +================== + + * Fix bad npm publish + +0.0.0 / 2014-05-04 +================== + + * Initial release diff --git a/node_modules/proxy-addr/LICENSE b/node_modules/proxy-addr/LICENSE new file mode 100644 index 0000000..cab251c --- /dev/null +++ b/node_modules/proxy-addr/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 Douglas Christopher Wilson + +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/proxy-addr/README.md b/node_modules/proxy-addr/README.md new file mode 100644 index 0000000..69c0b63 --- /dev/null +++ b/node_modules/proxy-addr/README.md @@ -0,0 +1,139 @@ +# proxy-addr + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Determine address of proxied request + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install proxy-addr +``` + +## API + +```js +var proxyaddr = require('proxy-addr') +``` + +### proxyaddr(req, trust) + +Return the address of the request, using the given `trust` parameter. + +The `trust` argument is a function that returns `true` if you trust +the address, `false` if you don't. The closest untrusted address is +returned. + +```js +proxyaddr(req, function (addr) { return addr === '127.0.0.1' }) +proxyaddr(req, function (addr, i) { return i < 1 }) +``` + +The `trust` arugment may also be a single IP address string or an +array of trusted addresses, as plain IP addresses, CIDR-formatted +strings, or IP/netmask strings. + +```js +proxyaddr(req, '127.0.0.1') +proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) +proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) +``` + +This module also supports IPv6. Your IPv6 addresses will be normalized +automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). + +```js +proxyaddr(req, '::1') +proxyaddr(req, ['::1/128', 'fe80::/10']) +``` + +This module will automatically work with IPv4-mapped IPv6 addresses +as well to support node.js in IPv6-only mode. This means that you do +not have to specify both `::ffff:a00:1` and `10.0.0.1`. + +As a convenience, this module also takes certain pre-defined names +in addition to IP addresses, which expand into IP addresses: + +```js +proxyaddr(req, 'loopback') +proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) +``` + + * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and + `127.0.0.1`). + * `linklocal`: IPv4 and IPv6 link-local addresses (like + `fe80::1:1:1:1` and `169.254.0.1`). + * `uniquelocal`: IPv4 private addresses and IPv6 unique-local + addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). + +When `trust` is specified as a function, it will be called for each +address to determine if it is a trusted address. The function is +given two arguments: `addr` and `i`, where `addr` is a string of +the address to check and `i` is a number that represents the distance +from the socket address. + +### proxyaddr.all(req, [trust]) + +Return all the addresses of the request, optionally stopping at the +first untrusted. This array is ordered from closest to furthest +(i.e. `arr[0] === req.connection.remoteAddress`). + +```js +proxyaddr.all(req) +``` + +The optional `trust` argument takes the same arguments as `trust` +does in `proxyaddr(req, trust)`. + +```js +proxyaddr.all(req, 'loopback') +``` + +### proxyaddr.compile(val) + +Compiles argument `val` into a `trust` function. This function takes +the same arguments as `trust` does in `proxyaddr(req, trust)` and +returns a function suitable for `proxyaddr(req, trust)`. + +```js +var trust = proxyaddr.compile('loopback') +var addr = proxyaddr(req, trust) +``` + +This function is meant to be optimized for use against every request. +It is recommend to compile a trust function up-front for the trusted +configuration and pass that to `proxyaddr(req, trust)` for each request. + +## Testing + +```sh +$ npm test +``` + +## Benchmarks + +```sh +$ npm run-script bench +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/proxy-addr/master?label=ci +[ci-url]: https://github.com/jshttp/proxy-addr/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/proxy-addr/master +[coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master +[node-image]: https://badgen.net/npm/node/proxy-addr +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/proxy-addr +[npm-url]: https://npmjs.org/package/proxy-addr +[npm-version-image]: https://badgen.net/npm/v/proxy-addr diff --git a/node_modules/proxy-addr/index.js b/node_modules/proxy-addr/index.js new file mode 100644 index 0000000..a909b05 --- /dev/null +++ b/node_modules/proxy-addr/index.js @@ -0,0 +1,327 @@ +/*! + * proxy-addr + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = proxyaddr +module.exports.all = alladdrs +module.exports.compile = compile + +/** + * Module dependencies. + * @private + */ + +var forwarded = require('forwarded') +var ipaddr = require('ipaddr.js') + +/** + * Variables. + * @private + */ + +var DIGIT_REGEXP = /^[0-9]+$/ +var isip = ipaddr.isValid +var parseip = ipaddr.parse + +/** + * Pre-defined IP ranges. + * @private + */ + +var IP_RANGES = { + linklocal: ['169.254.0.0/16', 'fe80::/10'], + loopback: ['127.0.0.1/8', '::1/128'], + uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'] +} + +/** + * Get all addresses in the request, optionally stopping + * at the first untrusted. + * + * @param {Object} request + * @param {Function|Array|String} [trust] + * @public + */ + +function alladdrs (req, trust) { + // get addresses + var addrs = forwarded(req) + + if (!trust) { + // Return all addresses + return addrs + } + + if (typeof trust !== 'function') { + trust = compile(trust) + } + + for (var i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue + + addrs.length = i + 1 + } + + return addrs +} + +/** + * Compile argument into trust function. + * + * @param {Array|String} val + * @private + */ + +function compile (val) { + if (!val) { + throw new TypeError('argument is required') + } + + var trust + + if (typeof val === 'string') { + trust = [val] + } else if (Array.isArray(val)) { + trust = val.slice() + } else { + throw new TypeError('unsupported trust argument') + } + + for (var i = 0; i < trust.length; i++) { + val = trust[i] + + if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) { + continue + } + + // Splice in pre-defined range + val = IP_RANGES[val] + trust.splice.apply(trust, [i, 1].concat(val)) + i += val.length - 1 + } + + return compileTrust(compileRangeSubnets(trust)) +} + +/** + * Compile `arr` elements into range subnets. + * + * @param {Array} arr + * @private + */ + +function compileRangeSubnets (arr) { + var rangeSubnets = new Array(arr.length) + + for (var i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]) + } + + return rangeSubnets +} + +/** + * Compile range subnet array into trust function. + * + * @param {Array} rangeSubnets + * @private + */ + +function compileTrust (rangeSubnets) { + // Return optimized function based on length + var len = rangeSubnets.length + return len === 0 + ? trustNone + : len === 1 + ? trustSingle(rangeSubnets[0]) + : trustMulti(rangeSubnets) +} + +/** + * Parse IP notation string into range subnet. + * + * @param {String} note + * @private + */ + +function parseipNotation (note) { + var pos = note.lastIndexOf('/') + var str = pos !== -1 + ? note.substring(0, pos) + : note + + if (!isip(str)) { + throw new TypeError('invalid IP address: ' + str) + } + + var ip = parseip(str) + + if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { + // Store as IPv4 + ip = ip.toIPv4Address() + } + + var max = ip.kind() === 'ipv6' + ? 128 + : 32 + + var range = pos !== -1 + ? note.substring(pos + 1, note.length) + : null + + if (range === null) { + range = max + } else if (DIGIT_REGEXP.test(range)) { + range = parseInt(range, 10) + } else if (ip.kind() === 'ipv4' && isip(range)) { + range = parseNetmask(range) + } else { + range = null + } + + if (range <= 0 || range > max) { + throw new TypeError('invalid range on address: ' + note) + } + + return [ip, range] +} + +/** + * Parse netmask string into CIDR range. + * + * @param {String} netmask + * @private + */ + +function parseNetmask (netmask) { + var ip = parseip(netmask) + var kind = ip.kind() + + return kind === 'ipv4' + ? ip.prefixLengthFromSubnetMask() + : null +} + +/** + * Determine address of proxied request. + * + * @param {Object} request + * @param {Function|Array|String} trust + * @public + */ + +function proxyaddr (req, trust) { + if (!req) { + throw new TypeError('req argument is required') + } + + if (!trust) { + throw new TypeError('trust argument is required') + } + + var addrs = alladdrs(req, trust) + var addr = addrs[addrs.length - 1] + + return addr +} + +/** + * Static trust function to trust nothing. + * + * @private + */ + +function trustNone () { + return false +} + +/** + * Compile trust function for multiple subnets. + * + * @param {Array} subnets + * @private + */ + +function trustMulti (subnets) { + return function trust (addr) { + if (!isip(addr)) return false + + var ip = parseip(addr) + var ipconv + var kind = ip.kind() + + for (var i = 0; i < subnets.length; i++) { + var subnet = subnets[i] + var subnetip = subnet[0] + var subnetkind = subnetip.kind() + var subnetrange = subnet[1] + var trusted = ip + + if (kind !== subnetkind) { + if (subnetkind === 'ipv4' && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + continue + } + + if (!ipconv) { + // Convert IP to match subnet IP kind + ipconv = subnetkind === 'ipv4' + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + trusted = ipconv + } + + if (trusted.match(subnetip, subnetrange)) { + return true + } + } + + return false + } +} + +/** + * Compile trust function for single subnet. + * + * @param {Object} subnet + * @private + */ + +function trustSingle (subnet) { + var subnetip = subnet[0] + var subnetkind = subnetip.kind() + var subnetisipv4 = subnetkind === 'ipv4' + var subnetrange = subnet[1] + + return function trust (addr) { + if (!isip(addr)) return false + + var ip = parseip(addr) + var kind = ip.kind() + + if (kind !== subnetkind) { + if (subnetisipv4 && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + return false + } + + // Convert IP to match subnet IP kind + ip = subnetisipv4 + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + return ip.match(subnetip, subnetrange) + } +} diff --git a/node_modules/proxy-addr/package.json b/node_modules/proxy-addr/package.json new file mode 100644 index 0000000..24ba8f7 --- /dev/null +++ b/node_modules/proxy-addr/package.json @@ -0,0 +1,47 @@ +{ + "name": "proxy-addr", + "description": "Determine address of proxied request", + "version": "2.0.7", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "ip", + "proxy", + "x-forwarded-for" + ], + "repository": "jshttp/proxy-addr", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "devDependencies": { + "benchmark": "2.1.4", + "beautify-benchmark": "0.2.4", + "deep-equal": "1.0.1", + "eslint": "7.26.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.23.4", + "eslint-plugin-markdown": "2.2.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.10" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/punycode/LICENSE-MIT.txt b/node_modules/punycode/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/punycode/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/punycode/README.md b/node_modules/punycode/README.md new file mode 100644 index 0000000..ee2f9d6 --- /dev/null +++ b/node_modules/punycode/README.md @@ -0,0 +1,122 @@ +# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) + +Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). + +This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: + +* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) +* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) +* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) +* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) +* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) + +This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). + +The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install punycode --save +``` + +In [Node.js](https://nodejs.org/): + +```js +const punycode = require('punycode'); +``` + +## API + +### `punycode.decode(string)` + +Converts a Punycode string of ASCII symbols to a string of Unicode symbols. + +```js +// decode domain name parts +punycode.decode('maana-pta'); // 'mañana' +punycode.decode('--dqo34k'); // '☃-⌘' +``` + +### `punycode.encode(string)` + +Converts a string of Unicode symbols to a Punycode string of ASCII symbols. + +```js +// encode domain name parts +punycode.encode('mañana'); // 'maana-pta' +punycode.encode('☃-⌘'); // '--dqo34k' +``` + +### `punycode.toUnicode(input)` + +Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. + +```js +// decode domain names +punycode.toUnicode('xn--maana-pta.com'); +// → 'mañana.com' +punycode.toUnicode('xn----dqo34k.com'); +// → '☃-⌘.com' + +// decode email addresses +punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); +// → 'джумла@джpумлатест.bрфa' +``` + +### `punycode.toASCII(input)` + +Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. + +```js +// encode domain names +punycode.toASCII('mañana.com'); +// → 'xn--maana-pta.com' +punycode.toASCII('☃-⌘.com'); +// → 'xn----dqo34k.com' + +// encode email addresses +punycode.toASCII('джумла@джpумлатест.bрфa'); +// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' +``` + +### `punycode.ucs2` + +#### `punycode.ucs2.decode(string)` + +Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. + +```js +punycode.ucs2.decode('abc'); +// → [0x61, 0x62, 0x63] +// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: +punycode.ucs2.decode('\uD834\uDF06'); +// → [0x1D306] +``` + +#### `punycode.ucs2.encode(codePoints)` + +Creates a string based on an array of numeric code point values. + +```js +punycode.ucs2.encode([0x61, 0x62, 0x63]); +// → 'abc' +punycode.ucs2.encode([0x1D306]); +// → '\uD834\uDF06' +``` + +### `punycode.version` + +A string representing the current Punycode.js version number. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +Punycode.js is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/punycode/package.json b/node_modules/punycode/package.json new file mode 100644 index 0000000..9202ccf --- /dev/null +++ b/node_modules/punycode/package.json @@ -0,0 +1,58 @@ +{ + "name": "punycode", + "version": "2.1.1", + "description": "A robust Punycode converter that fully complies to RFC 3492 and RFC 5891, and works on nearly all JavaScript platforms.", + "homepage": "https://mths.be/punycode", + "main": "punycode.js", + "jsnext:main": "punycode.es6.js", + "module": "punycode.es6.js", + "engines": { + "node": ">=6" + }, + "keywords": [ + "punycode", + "unicode", + "idn", + "idna", + "dns", + "url", + "domain" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "contributors": [ + { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/bestiejs/punycode.js.git" + }, + "bugs": "https://github.com/bestiejs/punycode.js/issues", + "files": [ + "LICENSE-MIT.txt", + "punycode.js", + "punycode.es6.js" + ], + "scripts": { + "test": "mocha tests", + "prepublish": "node scripts/prepublish.js" + }, + "devDependencies": { + "codecov": "^1.0.1", + "istanbul": "^0.4.1", + "mocha": "^2.5.3" + }, + "jspm": { + "map": { + "./punycode.js": { + "node": "@node/punycode" + } + } + } +} diff --git a/node_modules/punycode/punycode.es6.js b/node_modules/punycode/punycode.es6.js new file mode 100644 index 0000000..4610bc9 --- /dev/null +++ b/node_modules/punycode/punycode.es6.js @@ -0,0 +1,441 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + const result = []; + let length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + const parts = string.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + const labels = string.split('.'); + const encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = array => String.fromCodePoint(...array); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + let oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + let inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + let basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +export { ucs2decode, ucs2encode, decode, encode, toASCII, toUnicode }; +export default punycode; diff --git a/node_modules/punycode/punycode.js b/node_modules/punycode/punycode.js new file mode 100644 index 0000000..ea61fd0 --- /dev/null +++ b/node_modules/punycode/punycode.js @@ -0,0 +1,440 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + const result = []; + let length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + const parts = string.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + const labels = string.split('.'); + const encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = array => String.fromCodePoint(...array); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + let oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + let inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + let basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +module.exports = punycode; diff --git a/node_modules/qs/.editorconfig b/node_modules/qs/.editorconfig new file mode 100644 index 0000000..a4893dd --- /dev/null +++ b/node_modules/qs/.editorconfig @@ -0,0 +1,30 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 160 + +[test/*] +max_line_length = off + +[*.md] +max_line_length = off + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[LICENSE] +indent_size = 2 +max_line_length = off diff --git a/node_modules/qs/.eslintignore b/node_modules/qs/.eslintignore new file mode 100644 index 0000000..1521c8b --- /dev/null +++ b/node_modules/qs/.eslintignore @@ -0,0 +1 @@ +dist diff --git a/node_modules/qs/.eslintrc b/node_modules/qs/.eslintrc new file mode 100644 index 0000000..e3bde89 --- /dev/null +++ b/node_modules/qs/.eslintrc @@ -0,0 +1,21 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": 0, + "consistent-return": 1, + "func-name-matching": 0, + "id-length": [2, { "min": 1, "max": 25, "properties": "never" }], + "indent": [2, 4], + "max-lines-per-function": [2, { "max": 150 }], + "max-params": [2, 14], + "max-statements": [2, 52], + "multiline-comment-style": 0, + "no-continue": 1, + "no-magic-numbers": 0, + "no-restricted-syntax": [2, "BreakStatement", "DebuggerStatement", "ForInStatement", "LabeledStatement", "WithStatement"], + "operator-linebreak": [2, "before"], + } +} diff --git a/node_modules/qs/CHANGELOG.md b/node_modules/qs/CHANGELOG.md new file mode 100644 index 0000000..50505c4 --- /dev/null +++ b/node_modules/qs/CHANGELOG.md @@ -0,0 +1,256 @@ +## **6.7.0** +- [New] `stringify`/`parse`: add `comma` as an `arrayFormat` option (#276, #219) +- [Fix] correctly parse nested arrays (#212) +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source, also with an array source +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] `stringify`/`utils`: cache `Array.isArray` +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] temporarily allow coverage to fail + +## **6.6.0** +- [New] Add support for iso-8859-1, utf8 "sentinel" and numeric entities (#268) +- [New] move two-value combine to a `utils` function (#189) +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` (#260) +- [Fix] `stringify`: do not crash in an obscure combo of `interpretNumericEntities`, a bad custom `decoder`, & `iso-8859-1` +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Refactor] `parse`/`stringify`: clean up `charset` options checking; fix defaults +- [Refactor] add missing defaults +- [Refactor] `parse`: one less `concat` call +- [Refactor] `utils`: `compactQueue`: make it explicitly side-effecting +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`, `iconv-lite`, `safe-publish-latest`, `tape` +- [Tests] up to `node` `v10.10`, `v9.11`, `v8.12`, `v6.14`, `v4.9`; pin included builds to LTS + +## **6.5.2** +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Refactor] utils: `module.exports` one thing, instead of mutating `exports` (#230) +- [Dev Deps] update `browserify`, `eslint`, `iconv-lite`, `safer-buffer`, `tape`, `browserify` + +## **6.5.1** +- [Fix] Fix parsing & compacting very deep objects (#224) +- [Refactor] name utils functions +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` +- [Tests] up to `node` `v8.4`; use `nvm install-latest-npm` so newer npm doesn’t break older node +- [Tests] Use precise dist for Node.js 0.6 runtime (#225) +- [Tests] make 0.6 required, now that it’s passing +- [Tests] on `node` `v8.2`; fix npm on node 0.6 + +## **6.5.0** +- [New] add `utils.assign` +- [New] pass default encoder/decoder to custom encoder/decoder functions (#206) +- [New] `parse`/`stringify`: add `ignoreQueryPrefix`/`addQueryPrefix` options, respectively (#213) +- [Fix] Handle stringifying empty objects with addQueryPrefix (#217) +- [Fix] do not mutate `options` argument (#207) +- [Refactor] `parse`: cache index to reuse in else statement (#182) +- [Docs] add various badges to readme (#208) +- [Dev Deps] update `eslint`, `browserify`, `iconv-lite`, `tape` +- [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`; npm v4.6 breaks on node < v1; npm v5+ breaks on node < v4 +- [Tests] add `editorconfig-tools` + +## **6.4.0** +- [New] `qs.stringify`: add `encodeValuesOnly` option +- [Fix] follow `allowPrototypes` option during merge (#201, #201) +- [Fix] support keys starting with brackets (#202, #200) +- [Fix] chmod a-x +- [Dev Deps] update `eslint` +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds +- [eslint] reduce warnings + +## **6.3.2** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Dev Deps] update `eslint` +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.3.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties (thanks, @snyk!) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `iconv-lite`, `qs-iconv`, `tape` +- [Tests] on all node minors; improve test matrix +- [Docs] document stringify option `allowDots` (#195) +- [Docs] add empty object and array values example (#195) +- [Docs] Fix minor inconsistency/typo (#192) +- [Docs] document stringify option `sort` (#191) +- [Refactor] `stringify`: throw faster with an invalid encoder +- [Refactor] remove unnecessary escapes (#184) +- Remove contributing.md, since `qs` is no longer part of `hapi` (#183) + +## **6.3.0** +- [New] Add support for RFC 1738 (#174, #173) +- [New] `stringify`: Add `serializeDate` option to customize Date serialization (#159) +- [Fix] ensure `utils.merge` handles merging two arrays +- [Refactor] only constructors should be capitalized +- [Refactor] capitalized var names are for constructors only +- [Refactor] avoid using a sparse array +- [Robustness] `formats`: cache `String#replace` +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`; add `safe-publish-latest` +- [Tests] up to `node` `v6.8`, `v4.6`; improve test matrix +- [Tests] flesh out arrayLimit/arrayFormat tests (#107) +- [Tests] skip Object.create tests when null objects are not available +- [Tests] Turn on eslint for test files (#175) + +## **6.2.3** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.2.2** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## **6.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values +- [Refactor] Be explicit and use `Object.prototype.hasOwnProperty.call` +- [Tests] remove `parallelshell` since it does not reliably report failures +- [Tests] up to `node` `v6.3`, `v5.12` +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `qs-iconv` + +## [**6.2.0**](https://github.com/ljharb/qs/issues?milestone=36&state=closed) +- [New] pass Buffers to the encoder/decoder directly (#161) +- [New] add "encoder" and "decoder" options, for custom param encoding/decoding (#160) +- [Fix] fix compacting of nested sparse arrays (#150) + +## **6.1.2 +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.1.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## [**6.1.0**](https://github.com/ljharb/qs/issues?milestone=35&state=closed) +- [New] allowDots option for `stringify` (#151) +- [Fix] "sort" option should work at a depth of 3 or more (#151) +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## **6.0.4** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.0.3** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## [**6.0.2**](https://github.com/ljharb/qs/issues?milestone=33&state=closed) +- Revert ES6 requirement and restore support for node down to v0.8. + +## [**6.0.1**](https://github.com/ljharb/qs/issues?milestone=32&state=closed) +- [**#127**](https://github.com/ljharb/qs/pull/127) Fix engines definition in package.json + +## [**6.0.0**](https://github.com/ljharb/qs/issues?milestone=31&state=closed) +- [**#124**](https://github.com/ljharb/qs/issues/124) Use ES6 and drop support for node < v4 + +## **5.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values + +## [**5.2.0**](https://github.com/ljharb/qs/issues?milestone=30&state=closed) +- [**#64**](https://github.com/ljharb/qs/issues/64) Add option to sort object keys in the query string + +## [**5.1.0**](https://github.com/ljharb/qs/issues?milestone=29&state=closed) +- [**#117**](https://github.com/ljharb/qs/issues/117) make URI encoding stringified results optional +- [**#106**](https://github.com/ljharb/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify + +## [**5.0.0**](https://github.com/ljharb/qs/issues?milestone=28&state=closed) +- [**#114**](https://github.com/ljharb/qs/issues/114) default allowDots to false +- [**#100**](https://github.com/ljharb/qs/issues/100) include dist to npm + +## [**4.0.0**](https://github.com/ljharb/qs/issues?milestone=26&state=closed) +- [**#98**](https://github.com/ljharb/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional + +## [**3.1.0**](https://github.com/ljharb/qs/issues?milestone=24&state=closed) +- [**#89**](https://github.com/ljharb/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/ljharb/qs/issues?milestone=23&state=closed) +- [**#80**](https://github.com/ljharb/qs/issues/80) qs.parse silently drops properties +- [**#77**](https://github.com/ljharb/qs/issues/77) Perf boost +- [**#60**](https://github.com/ljharb/qs/issues/60) Add explicit option to disable array parsing +- [**#74**](https://github.com/ljharb/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/ljharb/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/ljharb/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/ljharb/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/ljharb/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/ljharb/qs/issues/85) No equal sign +- [**#84**](https://github.com/ljharb/qs/issues/84) update license attribute + +## [**2.4.1**](https://github.com/ljharb/qs/issues?milestone=20&state=closed) +- [**#73**](https://github.com/ljharb/qs/issues/73) Property 'hasOwnProperty' of object # is not a function + +## [**2.4.0**](https://github.com/ljharb/qs/issues?milestone=19&state=closed) +- [**#70**](https://github.com/ljharb/qs/issues/70) Add arrayFormat option + +## [**2.3.3**](https://github.com/ljharb/qs/issues?milestone=18&state=closed) +- [**#59**](https://github.com/ljharb/qs/issues/59) make sure array indexes are >= 0, closes #57 +- [**#58**](https://github.com/ljharb/qs/issues/58) make qs usable for browser loader + +## [**2.3.2**](https://github.com/ljharb/qs/issues?milestone=17&state=closed) +- [**#55**](https://github.com/ljharb/qs/issues/55) allow merging a string into an object + +## [**2.3.1**](https://github.com/ljharb/qs/issues?milestone=16&state=closed) +- [**#52**](https://github.com/ljharb/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError". + +## [**2.3.0**](https://github.com/ljharb/qs/issues?milestone=15&state=closed) +- [**#50**](https://github.com/ljharb/qs/issues/50) add option to omit array indices, closes #46 + +## [**2.2.5**](https://github.com/ljharb/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/ljharb/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/ljharb/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/ljharb/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/ljharb/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/ljharb/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/ljharb/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/ljharb/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/ljharb/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/ljharb/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/ljharb/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/ljharb/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/ljharb/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/ljharb/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/ljharb/qs/issues/32) account for circular references properly, closes #31 +- [**#31**](https://github.com/ljharb/qs/issues/31) qs.parse stackoverflow on circular objects + +## [**2.2.0**](https://github.com/ljharb/qs/issues?milestone=9&state=closed) +- [**#26**](https://github.com/ljharb/qs/issues/26) Don't use Buffer global if it's not present +- [**#30**](https://github.com/ljharb/qs/issues/30) Bug when merging non-object values into arrays +- [**#29**](https://github.com/ljharb/qs/issues/29) Don't call Utils.clone at the top of Utils.merge +- [**#23**](https://github.com/ljharb/qs/issues/23) Ability to not limit parameters? + +## [**2.1.0**](https://github.com/ljharb/qs/issues?milestone=8&state=closed) +- [**#22**](https://github.com/ljharb/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/ljharb/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/ljharb/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/ljharb/qs/issues/20) Configurable parametersLimit +- [**#21**](https://github.com/ljharb/qs/issues/21) make all limits optional, for #18, for #20 + +## [**1.2.2**](https://github.com/ljharb/qs/issues?milestone=6&state=closed) +- [**#19**](https://github.com/ljharb/qs/issues/19) Don't overwrite null values + +## [**1.2.1**](https://github.com/ljharb/qs/issues?milestone=5&state=closed) +- [**#16**](https://github.com/ljharb/qs/issues/16) ignore non-string delimiters +- [**#15**](https://github.com/ljharb/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/ljharb/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/ljharb/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/ljharb/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/ljharb/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/ljharb/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/ljharb/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/ljharb/qs/issues/6) Minor grammar fix in README + +## [**1.0.2**](https://github.com/ljharb/qs/issues?milestone=2&state=closed) +- [**#5**](https://github.com/ljharb/qs/issues/5) array holes incorrectly copied into object on large index diff --git a/node_modules/qs/LICENSE b/node_modules/qs/LICENSE new file mode 100644 index 0000000..d456948 --- /dev/null +++ b/node_modules/qs/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors diff --git a/node_modules/qs/README.md b/node_modules/qs/README.md new file mode 100644 index 0000000..8590cfd --- /dev/null +++ b/node_modules/qs/README.md @@ -0,0 +1,570 @@ +# qs [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +A querystring parsing and stringifying library with some added security. + +Lead Maintainer: [Jordan Harband](https://github.com/ljharb) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var qs = require('qs'); +var assert = require('assert'); + +var obj = qs.parse('a=c'); +assert.deepEqual(obj, { a: 'c' }); + +var str = qs.stringify(obj); +assert.equal(str, 'a=c'); +``` + +### Parsing Objects + +[](#preventEval) +```javascript +qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +assert.deepEqual(qs.parse('foo[bar]=baz'), { + foo: { + bar: 'baz' + } +}); +``` + +When using the `plainObjects` option the parsed value is returned as a null object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); +assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } }); +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. + +```javascript +var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }); +assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } }); +``` + +URI encoded strings work too: + +```javascript +assert.deepEqual(qs.parse('a%5Bb%5D=c'), { + a: { b: 'c' } +}); +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), { + foo: { + bar: { + baz: 'foobarbaz' + } + } +}); +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +var expected = { + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +}; +var string = 'a[b][c][d][e][f][g][h][i]=j'; +assert.deepEqual(qs.parse(string), expected); +``` + +This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`: + +```javascript +var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }); +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +var limited = qs.parse('a=b&c=d', { parameterLimit: 1 }); +assert.deepEqual(limited, { a: 'b' }); +``` + +To bypass the leading question mark, use `ignoreQueryPrefix`: + +```javascript +var prefixed = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true }); +assert.deepEqual(prefixed, { a: 'b', c: 'd' }); +``` + +An optional delimiter can also be passed: + +```javascript +var delimited = qs.parse('a=b;c=d', { delimiter: ';' }); +assert.deepEqual(delimited, { a: 'b', c: 'd' }); +``` + +Delimiters can be a regular expression too: + +```javascript +var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' }); +``` + +Option `allowDots` can be used to enable dot notation: + +```javascript +var withDots = qs.parse('a.b=c', { allowDots: true }); +assert.deepEqual(withDots, { a: { b: 'c' } }); +``` + +If you have to deal with legacy browsers or services, there's +also support for decoding percent-encoded octets as iso-8859-1: + +```javascript +var oldCharset = qs.parse('a=%A7', { charset: 'iso-8859-1' }); +assert.deepEqual(oldCharset, { a: '§' }); +``` + +Some services add an initial `utf8=✓` value to forms so that old +Internet Explorer versions are more likely to submit the form as +utf-8. Additionally, the server can check the value against wrong +encodings of the checkmark character and detect that a query string +or `application/x-www-form-urlencoded` body was *not* sent as +utf-8, eg. if the form had an `accept-charset` parameter or the +containing page had a different character set. + +**qs** supports this mechanism via the `charsetSentinel` option. +If specified, the `utf8` parameter will be omitted from the +returned object. It will be used to switch to `iso-8859-1`/`utf-8` +mode depending on how the checkmark is encoded. + +**Important**: When you specify both the `charset` option and the +`charsetSentinel` option, the `charset` will be overridden when +the request contains a `utf8` parameter from which the actual +charset can be deduced. In that sense the `charset` will behave +as the default charset rather than the authoritative charset. + +```javascript +var detectedAsUtf8 = qs.parse('utf8=%E2%9C%93&a=%C3%B8', { + charset: 'iso-8859-1', + charsetSentinel: true +}); +assert.deepEqual(detectedAsUtf8, { a: 'ø' }); + +// Browsers encode the checkmark as ✓ when submitting as iso-8859-1: +var detectedAsIso8859_1 = qs.parse('utf8=%26%2310003%3B&a=%F8', { + charset: 'utf-8', + charsetSentinel: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: 'ø' }); +``` + +If you want to decode the `&#...;` syntax to the actual character, +you can specify the `interpretNumericEntities` option as well: + +```javascript +var detectedAsIso8859_1 = qs.parse('a=%26%239786%3B', { + charset: 'iso-8859-1', + interpretNumericEntities: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: '☺' }); +``` + +It also works when the charset has been detected in `charsetSentinel` +mode. + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +var withArray = qs.parse('a[]=b&a[]=c'); +assert.deepEqual(withArray, { a: ['b', 'c'] }); +``` + +You may specify an index as well: + +```javascript +var withIndexes = qs.parse('a[1]=c&a[0]=b'); +assert.deepEqual(withIndexes, { a: ['b', 'c'] }); +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +var noSparse = qs.parse('a[1]=b&a[15]=c'); +assert.deepEqual(noSparse, { a: ['b', 'c'] }); +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +var withEmptyString = qs.parse('a[]=&a[]=b'); +assert.deepEqual(withEmptyString, { a: ['', 'b'] }); + +var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c'); +assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] }); +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key. This is needed to handle cases when someone sent, for example, `a[999999999]` and it will take significant time to iterate over this huge array. + +```javascript +var withMaxIndex = qs.parse('a[100]=b'); +assert.deepEqual(withMaxIndex, { a: { '100': 'b' } }); +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 }); +assert.deepEqual(withArrayLimit, { a: { '1': 'b' } }); +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +var noParsingArrays = qs.parse('a[]=b', { parseArrays: false }); +assert.deepEqual(noParsingArrays, { a: { '0': 'b' } }); +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +var mixedNotation = qs.parse('a[0]=b&a[b]=c'); +assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } }); +``` + +You can also create arrays of objects: + +```javascript +var arraysOfObjects = qs.parse('a[][b]=c'); +assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] }); +``` + +Some people use comma to join array, **qs** can parse it: +```javascript +var arraysOfObjects = qs.parse('a=b,c', { comma: true }) +assert.deepEqual(arraysOfObjects, { a: ['b', 'c'] }) +``` +(_this cannot convert nested objects, such as `a={b:1},{c:d}`_) + +### Stringifying + +[](#preventEval) +```javascript +qs.stringify(object, [options]); +``` + +When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect: + +```javascript +assert.equal(qs.stringify({ a: 'b' }), 'a=b'); +assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); +``` + +This encoding can be disabled by setting the `encode` option to `false`: + +```javascript +var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false }); +assert.equal(unencoded, 'a[b]=c'); +``` + +Encoding can be disabled for keys by setting the `encodeValuesOnly` option to `true`: +```javascript +var encodedValues = qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } +); +assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'); +``` + +This encoding can also be replaced by a custom encoding method set as `encoder` option: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) { + // Passed in values `a`, `b`, `c` + return // Return encoded string +}}) +``` + +_(Note: the `encoder` option does not apply if `encode` is `false`)_ + +Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str) { + // Passed in values `x`, `z` + return // Return decoded string +}}) +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, by default they are given explicit indices: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); +// 'a=b&a=c&a=d' +``` + +You may use the `arrayFormat` option to specify the format of the output array: + +```javascript +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) +// 'a[0]=b&a[1]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) +// 'a[]=b&a[]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) +// 'a=b&a=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' }) +// 'a=b,c' +``` + +When objects are stringified, by default they use bracket notation: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }); +// 'a[b][c]=d&a[b][e]=f' +``` + +You may override this to use dot notation by setting the `allowDots` option to `true`: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true }); +// 'a.b.c=d&a.b.e=f' +``` + +Empty strings and null values will omit the value, but the equals sign (=) remains in place: + +```javascript +assert.equal(qs.stringify({ a: '' }), 'a='); +``` + +Key with no values (such as an empty object or array) will return nothing: + +```javascript +assert.equal(qs.stringify({ a: [] }), ''); +assert.equal(qs.stringify({ a: {} }), ''); +assert.equal(qs.stringify({ a: [{}] }), ''); +assert.equal(qs.stringify({ a: { b: []} }), ''); +assert.equal(qs.stringify({ a: { b: {}} }), ''); +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +assert.equal(qs.stringify({ a: null, b: undefined }), 'a='); +``` + +The query string may optionally be prepended with a question mark: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }), '?a=b&c=d'); +``` + +The delimiter may be overridden with stringify as well: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); +``` + +If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option: + +```javascript +var date = new Date(7); +assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A')); +assert.equal( + qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }), + 'a=7' +); +``` + +You may use the `sort` option to affect the order of parameter keys: + +```javascript +function alphabeticalSort(a, b) { + return a.localeCompare(b); +} +assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y'); +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you +pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }); +// 'a=b&c=d&e[f]=123&e[g][0]=4' +qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }); +// 'a=b&e=f' +qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }); +// 'a[0]=b&a[2]=d' +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +var withNull = qs.stringify({ a: null, b: '' }); +assert.equal(withNull, 'a=&b='); +``` + +Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. + +```javascript +var equalsInsensitive = qs.parse('a&b='); +assert.deepEqual(equalsInsensitive, { a: '', b: '' }); +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +assert.equal(strictNull, 'a&b='); +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true }); +assert.deepEqual(parsedStrictNull, { a: null, b: '' }); +``` + +To completely skip rendering keys with `null` values, use the `skipNulls` flag: + +```javascript +var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true }); +assert.equal(nullsSkipped, 'a=b'); +``` + +If you're communicating with legacy systems, you can switch to `iso-8859-1` +using the `charset` option: + +```javascript +var iso = qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }); +assert.equal(iso, '%E6=%E6'); +``` + +Characters that don't exist in `iso-8859-1` will be converted to numeric +entities, similar to what browsers do: + +```javascript +var numeric = qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }); +assert.equal(numeric, 'a=%26%239786%3B'); +``` + +You can use the `charsetSentinel` option to announce the character by +including an `utf8=✓` parameter with the proper encoding if the checkmark, +similar to what Ruby on Rails and others do when submitting forms. + +```javascript +var sentinel = qs.stringify({ a: '☺' }, { charsetSentinel: true }); +assert.equal(sentinel, 'utf8=%E2%9C%93&a=%E2%98%BA'); + +var isoSentinel = qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }); +assert.equal(isoSentinel, 'utf8=%26%2310003%3B&a=%E6'); +``` + +### Dealing with special character sets + +By default the encoding and decoding of characters is done in `utf-8`, +and `iso-8859-1` support is also built in via the `charset` parameter. + +If you wish to encode querystrings to a different character set (i.e. +[Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the +[`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library: + +```javascript +var encoder = require('qs-iconv/encoder')('shift_jis'); +var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder }); +assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I'); +``` + +This also works for decoding of query strings: + +```javascript +var decoder = require('qs-iconv/decoder')('shift_jis'); +var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder }); +assert.deepEqual(obj, { a: 'こんにちは!' }); +``` + +### RFC 3986 and RFC 1738 space encoding + +RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible. +In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'. + +``` +assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c'); +``` + +[1]: https://npmjs.org/package/qs +[2]: http://versionbadg.es/ljharb/qs.svg +[3]: https://api.travis-ci.org/ljharb/qs.svg +[4]: https://travis-ci.org/ljharb/qs +[5]: https://david-dm.org/ljharb/qs.svg +[6]: https://david-dm.org/ljharb/qs +[7]: https://david-dm.org/ljharb/qs/dev-status.svg +[8]: https://david-dm.org/ljharb/qs?type=dev +[9]: https://ci.testling.com/ljharb/qs.png +[10]: https://ci.testling.com/ljharb/qs +[11]: https://nodei.co/npm/qs.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/qs.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/qs.svg +[downloads-url]: http://npm-stat.com/charts.html?package=qs diff --git a/node_modules/qs/dist/qs.js b/node_modules/qs/dist/qs.js new file mode 100644 index 0000000..17f4e60 --- /dev/null +++ b/node_modules/qs/dist/qs.js @@ -0,0 +1,782 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i -1) { + val = val.split(','); + } + + if (has.call(obj, key)) { + obj[key] = utils.combine(obj[key], val); + } else { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options) { + var leaf = val; + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else { + obj[cleanRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new Error('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + return { + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + depth: typeof opts.depth === 'number' ? opts.depth : defaults.depth, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options); + obj = utils.merge(obj, newObj, options); + } + + return utils.compact(obj); +}; + +},{"./utils":5}],4:[function(require,module,exports){ +'use strict'; + +var utils = require('./utils'); +var formats = require('./formats'); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { // eslint-disable-line func-name-matching + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { // eslint-disable-line func-name-matching + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { // eslint-disable-line func-name-matching + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaults = { + addQueryPrefix: false, + allowDots: false, + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + formatter: formats.formatters[formats['default']], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var stringify = function stringify( // eslint-disable-line func-name-matching + object, + prefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly, + charset +) { + var obj = object; + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = obj.join(','); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset) : prefix; + } + + obj = ''; + } + + if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (skipNulls && obj[key] === null) { + continue; + } + + if (isArray(obj)) { + pushToArray(values, stringify( + obj[key], + typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly, + charset + )); + } else { + pushToArray(values, stringify( + obj[key], + prefix + (allowDots ? '.' + key : '[' + key + ']'), + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly, + charset + )); + } + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && 'indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys, stringify( + obj[key], + key, + generateArrayPrefix, + options.strictNullHandling, + options.skipNulls, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.formatter, + options.encodeValuesOnly, + options.charset + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; + +},{"./formats":1,"./utils":5}],5:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var encode = function encode(str, defaultEncoder, charset) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = typeof str === 'string' ? str : String(str); + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + merge: merge +}; + +},{}]},{},[2])(2) +}); diff --git a/node_modules/qs/lib/formats.js b/node_modules/qs/lib/formats.js new file mode 100644 index 0000000..df45997 --- /dev/null +++ b/node_modules/qs/lib/formats.js @@ -0,0 +1,18 @@ +'use strict'; + +var replace = String.prototype.replace; +var percentTwenties = /%20/g; + +module.exports = { + 'default': 'RFC3986', + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return value; + } + }, + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' +}; diff --git a/node_modules/qs/lib/index.js b/node_modules/qs/lib/index.js new file mode 100644 index 0000000..0d6a97d --- /dev/null +++ b/node_modules/qs/lib/index.js @@ -0,0 +1,11 @@ +'use strict'; + +var stringify = require('./stringify'); +var parse = require('./parse'); +var formats = require('./formats'); + +module.exports = { + formats: formats, + parse: parse, + stringify: stringify +}; diff --git a/node_modules/qs/lib/parse.js b/node_modules/qs/lib/parse.js new file mode 100644 index 0000000..d81628b --- /dev/null +++ b/node_modules/qs/lib/parse.js @@ -0,0 +1,242 @@ +'use strict'; + +var utils = require('./utils'); + +var has = Object.prototype.hasOwnProperty; + +var defaults = { + allowDots: false, + allowPrototypes: false, + arrayLimit: 20, + charset: 'utf-8', + charsetSentinel: false, + comma: false, + decoder: utils.decode, + delimiter: '&', + depth: 5, + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1000, + parseArrays: true, + plainObjects: false, + strictNullHandling: false +}; + +var interpretNumericEntities = function (str) { + return str.replace(/&#(\d+);/g, function ($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); +}; + +// This is what browsers will submit when the ✓ character occurs in an +// application/x-www-form-urlencoded body and the encoding of the page containing +// the form is iso-8859-1, or when the submitted form has an accept-charset +// attribute of iso-8859-1. Presumably also with other charsets that do not contain +// the ✓ character, such as us-ascii. +var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') + +// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. +var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') + +var parseValues = function parseQueryStringValues(str, options) { + var obj = {}; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; + + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key, val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset); + val = options.decoder(part.slice(pos + 1), defaults.decoder, charset); + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(val); + } + + if (val && options.comma && val.indexOf(',') > -1) { + val = val.split(','); + } + + if (has.call(obj, key)) { + obj[key] = utils.combine(obj[key], val); + } else { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options) { + var leaf = val; + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else { + obj[cleanRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new Error('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + return { + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + depth: typeof opts.depth === 'number' ? opts.depth : defaults.depth, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options); + obj = utils.merge(obj, newObj, options); + } + + return utils.compact(obj); +}; diff --git a/node_modules/qs/lib/stringify.js b/node_modules/qs/lib/stringify.js new file mode 100644 index 0000000..7455049 --- /dev/null +++ b/node_modules/qs/lib/stringify.js @@ -0,0 +1,269 @@ +'use strict'; + +var utils = require('./utils'); +var formats = require('./formats'); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { // eslint-disable-line func-name-matching + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { // eslint-disable-line func-name-matching + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { // eslint-disable-line func-name-matching + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaults = { + addQueryPrefix: false, + allowDots: false, + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + formatter: formats.formatters[formats['default']], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var stringify = function stringify( // eslint-disable-line func-name-matching + object, + prefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly, + charset +) { + var obj = object; + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = obj.join(','); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset) : prefix; + } + + obj = ''; + } + + if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (skipNulls && obj[key] === null) { + continue; + } + + if (isArray(obj)) { + pushToArray(values, stringify( + obj[key], + typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly, + charset + )); + } else { + pushToArray(values, stringify( + obj[key], + prefix + (allowDots ? '.' + key : '[' + key + ']'), + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly, + charset + )); + } + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && 'indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys, stringify( + obj[key], + key, + generateArrayPrefix, + options.strictNullHandling, + options.skipNulls, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.formatter, + options.encodeValuesOnly, + options.charset + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; diff --git a/node_modules/qs/lib/utils.js b/node_modules/qs/lib/utils.js new file mode 100644 index 0000000..1b219cd --- /dev/null +++ b/node_modules/qs/lib/utils.js @@ -0,0 +1,230 @@ +'use strict'; + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var encode = function encode(str, defaultEncoder, charset) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = typeof str === 'string' ? str : String(str); + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + merge: merge +}; diff --git a/node_modules/qs/package.json b/node_modules/qs/package.json new file mode 100644 index 0000000..28d98a1 --- /dev/null +++ b/node_modules/qs/package.json @@ -0,0 +1,58 @@ +{ + "name": "qs", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/ljharb/qs", + "version": "6.7.0", + "repository": { + "type": "git", + "url": "https://github.com/ljharb/qs.git" + }, + "main": "lib/index.js", + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "keywords": [ + "querystring", + "qs", + "query", + "url", + "parse", + "stringify" + ], + "engines": { + "node": ">=0.6" + }, + "dependencies": {}, + "devDependencies": { + "@ljharb/eslint-config": "^13.1.1", + "browserify": "^16.2.3", + "covert": "^1.1.1", + "editorconfig-tools": "^0.1.1", + "eslint": "^5.15.3", + "evalmd": "^0.0.17", + "for-each": "^0.3.3", + "iconv-lite": "^0.4.24", + "mkdirp": "^0.5.1", + "object-inspect": "^1.6.0", + "qs-iconv": "^1.0.4", + "safe-publish-latest": "^1.1.2", + "safer-buffer": "^2.1.2", + "tape": "^4.10.1" + }, + "scripts": { + "prepublish": "safe-publish-latest && npm run dist", + "pretest": "npm run --silent readme && npm run --silent lint", + "test": "npm run --silent coverage", + "tests-only": "node test", + "readme": "evalmd README.md", + "postlint": "editorconfig-tools check * lib/* test/*", + "lint": "eslint lib/*.js test/*.js", + "coverage": "covert test", + "dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js" + }, + "license": "BSD-3-Clause" +} diff --git a/node_modules/qs/test/.eslintrc b/node_modules/qs/test/.eslintrc new file mode 100644 index 0000000..9ebbb92 --- /dev/null +++ b/node_modules/qs/test/.eslintrc @@ -0,0 +1,17 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "consistent-return": 2, + "function-paren-newline": 0, + "max-lines": 0, + "max-lines-per-function": 0, + "max-nested-callbacks": [2, 3], + "max-statements": 0, + "no-buffer-constructor": 0, + "no-extend-native": 0, + "no-magic-numbers": 0, + "object-curly-newline": 0, + "sort-keys": 0 + } +} diff --git a/node_modules/qs/test/index.js b/node_modules/qs/test/index.js new file mode 100644 index 0000000..5e6bc8f --- /dev/null +++ b/node_modules/qs/test/index.js @@ -0,0 +1,7 @@ +'use strict'; + +require('./parse'); + +require('./stringify'); + +require('./utils'); diff --git a/node_modules/qs/test/parse.js b/node_modules/qs/test/parse.js new file mode 100644 index 0000000..8967789 --- /dev/null +++ b/node_modules/qs/test/parse.js @@ -0,0 +1,676 @@ +'use strict'; + +var test = require('tape'); +var qs = require('../'); +var utils = require('../lib/utils'); +var iconv = require('iconv-lite'); +var SaferBuffer = require('safer-buffer').Buffer; + +test('parse()', function (t) { + t.test('parses a simple string', function (st) { + st.deepEqual(qs.parse('0=foo'), { 0: 'foo' }); + st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' }); + st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } }); + st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } }); + st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } }); + st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null }); + st.deepEqual(qs.parse('foo'), { foo: '' }); + st.deepEqual(qs.parse('foo='), { foo: '' }); + st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' }); + st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' }); + st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' }); + st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' }); + st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' }); + st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null }); + st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' }); + st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), { + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + st.end(); + }); + + t.test('allows enabling dot notation', function (st) { + st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' }); + st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } }); + st.end(); + }); + + t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string'); + t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string'); + t.deepEqual( + qs.parse('a[b][c][d][e][f][g][h]=i'), + { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }, + 'defaults to a depth of 5' + ); + + t.test('only parses one level when depth = 1', function (st) { + st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } }); + st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } }); + st.end(); + }); + + t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array'); + + t.test('parses an explicit array', function (st) { + st.deepEqual(qs.parse('a[]=b'), { a: ['b'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] }); + st.end(); + }); + + t.test('parses a mix of simple and explicit arrays', function (st) { + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a[1]=b&a=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a=b&a[1]=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + + st.end(); + }); + + t.test('parses a nested array', function (st) { + st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } }); + st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } }); + st.end(); + }); + + t.test('allows to specify array indices', function (st) { + st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] }); + st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 20 }), { a: ['c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 0 }), { a: { 1: 'c' } }); + st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] }); + st.end(); + }); + + t.test('limits specific array indices to arrayLimit', function (st) { + st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a', { arrayLimit: 20 }), { a: { 21: 'a' } }); + st.end(); + }); + + t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number'); + + t.test('supports encoded = signs', function (st) { + st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' }); + st.end(); + }); + + t.test('is ok with url encoded strings', function (st) { + st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } }); + st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } }); + st.end(); + }); + + t.test('allows brackets in the value', function (st) { + st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' }); + st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' }); + st.end(); + }); + + t.test('allows empty values', function (st) { + st.deepEqual(qs.parse(''), {}); + st.deepEqual(qs.parse(null), {}); + st.deepEqual(qs.parse(undefined), {}); + st.end(); + }); + + t.test('transforms arrays to objects', function (st) { + st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { 0: 'b', t: 'u' } }); + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { 0: 'b', t: 'u', hasOwnProperty: 'c' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { 0: 'b', x: 'y' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { 0: 'b', hasOwnProperty: 'c', x: 'y' } }); + st.end(); + }); + + t.test('transforms arrays to objects (dot notation)', function (st) { + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] }); + st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + st.end(); + }); + + t.test('correctly prunes undefined values when converting an array to an object', function (st) { + st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { 2: 'b', 99999999: 'c' } }); + st.end(); + }); + + t.test('supports malformed uri characters', function (st) { + st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null }); + st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' }); + st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' }); + st.end(); + }); + + t.test('doesn\'t produce empty keys', function (st) { + st.deepEqual(qs.parse('_r=1&'), { _r: '1' }); + st.end(); + }); + + t.test('cannot access Object prototype', function (st) { + qs.parse('constructor[prototype][bad]=bad'); + qs.parse('bad[constructor][prototype][bad]=bad'); + st.equal(typeof Object.prototype.bad, 'undefined'); + st.end(); + }); + + t.test('parses arrays of objects', function (st) { + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] }); + st.end(); + }); + + t.test('allows for empty strings in arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] }); + + st.deepEqual( + qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 20 + array indices: null then empty string works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 0 + array brackets: null then empty string works' + ); + + st.deepEqual( + qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 20 + array indices: empty string then null works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 0 + array brackets: empty string then null works' + ); + + st.deepEqual( + qs.parse('a[]=&a[]=b&a[]=c'), + { a: ['', 'b', 'c'] }, + 'array brackets: empty strings work' + ); + st.end(); + }); + + t.test('compacts sparse arrays', function (st) { + st.deepEqual(qs.parse('a[10]=1&a[2]=2', { arrayLimit: 20 }), { a: ['2', '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { arrayLimit: 20 }), { a: [{ b: [{ c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { arrayLimit: 20 }), { a: [[[{ c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { arrayLimit: 20 }), { a: [[[{ c: ['1'] }]]] }); + st.end(); + }); + + t.test('parses semi-parsed strings', function (st) { + st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } }); + st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } }); + st.end(); + }); + + t.test('parses buffers correctly', function (st) { + var b = SaferBuffer.from('test'); + st.deepEqual(qs.parse({ a: b }), { a: b }); + st.end(); + }); + + t.test('parses jquery-param strings', function (st) { + // readable = 'filter[0][]=int1&filter[0][]==&filter[0][]=77&filter[]=and&filter[2][]=int2&filter[2][]==&filter[2][]=8' + var encoded = 'filter%5B0%5D%5B%5D=int1&filter%5B0%5D%5B%5D=%3D&filter%5B0%5D%5B%5D=77&filter%5B%5D=and&filter%5B2%5D%5B%5D=int2&filter%5B2%5D%5B%5D=%3D&filter%5B2%5D%5B%5D=8'; + var expected = { filter: [['int1', '=', '77'], 'and', ['int2', '=', '8']] }; + st.deepEqual(qs.parse(encoded), expected); + st.end(); + }); + + t.test('continues parsing when no parent is found', function (st) { + st.deepEqual(qs.parse('[]=&a=b'), { 0: '', a: 'b' }); + st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { 0: null, a: 'b' }); + st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' }); + st.end(); + }); + + t.test('does not error when parsing a very long array', function (st) { + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str = str + '&' + str; + } + + st.doesNotThrow(function () { + qs.parse(str); + }); + + st.end(); + }); + + t.test('should not throw when a native prototype has an enumerable property', function (st) { + Object.prototype.crash = ''; + Array.prototype.crash = ''; + st.doesNotThrow(qs.parse.bind(null, 'a=b')); + st.deepEqual(qs.parse('a=b'), { a: 'b' }); + st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c')); + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + delete Object.prototype.crash; + delete Array.prototype.crash; + st.end(); + }); + + t.test('parses a string with an alternative string delimiter', function (st) { + st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('parses a string with an alternative RegExp delimiter', function (st) { + st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not use non-splittable objects as delimiters', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding parameter limit', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' }); + st.end(); + }); + + t.test('allows setting the parameter limit to Infinity', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding array limit', function (st) { + st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { 0: 'b' } }); + st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } }); + st.end(); + }); + + t.test('allows disabling array parsing', function (st) { + var indices = qs.parse('a[0]=b&a[1]=c', { parseArrays: false }); + st.deepEqual(indices, { a: { 0: 'b', 1: 'c' } }); + st.equal(Array.isArray(indices.a), false, 'parseArrays:false, indices case is not an array'); + + var emptyBrackets = qs.parse('a[]=b', { parseArrays: false }); + st.deepEqual(emptyBrackets, { a: { 0: 'b' } }); + st.equal(Array.isArray(emptyBrackets.a), false, 'parseArrays:false, empty brackets case is not an array'); + + st.end(); + }); + + t.test('allows for query string prefix', function (st) { + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' }); + st.end(); + }); + + t.test('parses an object', function (st) { + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses string with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo=bar,tee', { comma: true }), { foo: ['bar', 'tee'] }); + st.deepEqual(qs.parse('foo[bar]=coffee,tee', { comma: true }), { foo: { bar: ['coffee', 'tee'] } }); + st.deepEqual(qs.parse('foo=', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true, strictNullHandling: true }), { foo: null }); + st.end(); + }); + + t.test('parses an object in dot notation', function (st) { + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input, { allowDots: true }); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses an object and not child values', function (st) { + var input = { + 'user[name]': { 'pop[bob]': { test: 3 } }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': { test: 3 } }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = qs.parse('a=b&c=d'); + global.Buffer = tempBuffer; + st.deepEqual(result, { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + var parsed; + + st.doesNotThrow(function () { + parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + st.equal('bar' in parsed.foo, true); + st.equal('baz' in parsed.foo, true); + st.equal(parsed.foo.bar, 'baz'); + st.deepEqual(parsed.foo.baz, a); + st.end(); + }); + + t.test('does not crash when parsing deep objects', function (st) { + var parsed; + var str = 'foo'; + + for (var i = 0; i < 5000; i++) { + str += '[p]'; + } + + str += '=bar'; + + st.doesNotThrow(function () { + parsed = qs.parse(str, { depth: 5000 }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + + var depth = 0; + var ref = parsed.foo; + while ((ref = ref.p)) { + depth += 1; + } + + st.equal(depth, 5000, 'parsed is 5000 properties deep'); + + st.end(); + }); + + t.test('parses null objects correctly', { skip: !Object.create }, function (st) { + var a = Object.create(null); + a.b = 'c'; + + st.deepEqual(qs.parse(a), { b: 'c' }); + var result = qs.parse({ a: a }); + st.equal('a' in result, true, 'result has "a" property'); + st.deepEqual(result.a, a); + st.end(); + }); + + t.test('parses dates correctly', function (st) { + var now = new Date(); + st.deepEqual(qs.parse({ a: now }), { a: now }); + st.end(); + }); + + t.test('parses regular expressions correctly', function (st) { + var re = /^test$/; + st.deepEqual(qs.parse({ a: re }), { a: re }); + st.end(); + }); + + t.test('does not allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: false }), {}); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: false }), {}); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: false }), + {}, + 'bare "toString" results in {}' + ); + + st.end(); + }); + + t.test('can allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } }); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' }); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: true }), + { toString: '' }, + 'bare "toString" results in { toString: "" }' + ); + + st.end(); + }); + + t.test('params starting with a closing bracket', function (st) { + st.deepEqual(qs.parse(']=toString'), { ']': 'toString' }); + st.deepEqual(qs.parse(']]=toString'), { ']]': 'toString' }); + st.deepEqual(qs.parse(']hello]=toString'), { ']hello]': 'toString' }); + st.end(); + }); + + t.test('params starting with a starting bracket', function (st) { + st.deepEqual(qs.parse('[=toString'), { '[': 'toString' }); + st.deepEqual(qs.parse('[[=toString'), { '[[': 'toString' }); + st.deepEqual(qs.parse('[hello[=toString'), { '[hello[': 'toString' }); + st.end(); + }); + + t.test('add keys to objects', function (st) { + st.deepEqual( + qs.parse('a[b]=c&a=d'), + { a: { b: 'c', d: true } }, + 'can add keys to objects' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString'), + { a: { b: 'c' } }, + 'can not overwrite prototype' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { allowPrototypes: true }), + { a: { b: 'c', toString: true } }, + 'can overwrite prototype with allowPrototypes true' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { plainObjects: true }), + { a: { b: 'c', toString: true } }, + 'can overwrite prototype with plainObjects true' + ); + + st.end(); + }); + + t.test('can return null objects', { skip: !Object.create }, function (st) { + var expected = Object.create(null); + expected.a = Object.create(null); + expected.a.b = 'c'; + expected.a.hasOwnProperty = 'd'; + st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected); + st.deepEqual(qs.parse(null, { plainObjects: true }), Object.create(null)); + var expectedArray = Object.create(null); + expectedArray.a = Object.create(null); + expectedArray.a[0] = 'b'; + expectedArray.a.c = 'd'; + st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray); + st.end(); + }); + + t.test('can parse with custom encoding', function (st) { + st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', { + decoder: function (str) { + var reg = /%([0-9A-F]{2})/ig; + var result = []; + var parts = reg.exec(str); + while (parts) { + result.push(parseInt(parts[1], 16)); + parts = reg.exec(str); + } + return String(iconv.decode(SaferBuffer.from(result), 'shift_jis')); + } + }), { 県: '大阪府' }); + st.end(); + }); + + t.test('receives the default decoder as a second argument', function (st) { + st.plan(1); + qs.parse('a', { + decoder: function (str, defaultDecoder) { + st.equal(defaultDecoder, utils.decode); + } + }); + st.end(); + }); + + t.test('throws error with wrong decoder', function (st) { + st['throws'](function () { + qs.parse({}, { decoder: 'string' }); + }, new TypeError('Decoder has to be a function.')); + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.parse('a[b]=true', options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.parse('a=b', { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('parses an iso-8859-1 string if asked to', function (st) { + st.deepEqual(qs.parse('%A2=%BD', { charset: 'iso-8859-1' }), { '¢': '½' }); + st.end(); + }); + + var urlEncodedCheckmarkInUtf8 = '%E2%9C%93'; + var urlEncodedOSlashInUtf8 = '%C3%B8'; + var urlEncodedNumCheckmark = '%26%2310003%3B'; + var urlEncodedNumSmiley = '%26%239786%3B'; + + t.test('prefers an utf-8 charset specified by the utf8 sentinel to a default charset of iso-8859-1', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'iso-8859-1' }), { ø: 'ø' }); + st.end(); + }); + + t.test('prefers an iso-8859-1 charset specified by the utf8 sentinel to a default charset of utf-8', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('does not require the utf8 sentinel to be defined before the parameters whose decoding it affects', function (st) { + st.deepEqual(qs.parse('a=' + urlEncodedOSlashInUtf8 + '&utf8=' + urlEncodedNumCheckmark, { charsetSentinel: true, charset: 'utf-8' }), { a: 'ø' }); + st.end(); + }); + + t.test('should ignore an utf8 sentinel with an unknown value', function (st) { + st.deepEqual(qs.parse('utf8=foo&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to utf-8 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to iso-8859-1 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('interprets numeric entities in iso-8859-1 when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('handles a custom decoder returning `null`, in the `iso-8859-1` charset, when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=&bar=' + urlEncodedNumSmiley, { + charset: 'iso-8859-1', + decoder: function (str, defaultDecoder, charset) { + return str ? defaultDecoder(str, defaultDecoder, charset) : null; + }, + interpretNumericEntities: true + }), { foo: null, bar: '☺' }); + st.end(); + }); + + t.test('does not interpret numeric entities in iso-8859-1 when `interpretNumericEntities` is absent', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1' }), { foo: '☺' }); + st.end(); + }); + + t.test('does not interpret numeric entities when the charset is utf-8, even when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'utf-8', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('does not interpret %uXXXX syntax in iso-8859-1 mode', function (st) { + st.deepEqual(qs.parse('%u263A=%u263A', { charset: 'iso-8859-1' }), { '%u263A': '%u263A' }); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/qs/test/stringify.js b/node_modules/qs/test/stringify.js new file mode 100644 index 0000000..53041c2 --- /dev/null +++ b/node_modules/qs/test/stringify.js @@ -0,0 +1,679 @@ +'use strict'; + +var test = require('tape'); +var qs = require('../'); +var utils = require('../lib/utils'); +var iconv = require('iconv-lite'); +var SaferBuffer = require('safer-buffer').Buffer; + +test('stringify()', function (t) { + t.test('stringifies a querystring object', function (st) { + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: 1 }), 'a=1'); + st.equal(qs.stringify({ a: 1, b: 2 }), 'a=1&b=2'); + st.equal(qs.stringify({ a: 'A_Z' }), 'a=A_Z'); + st.equal(qs.stringify({ a: '€' }), 'a=%E2%82%AC'); + st.equal(qs.stringify({ a: '' }), 'a=%EE%80%80'); + st.equal(qs.stringify({ a: 'א' }), 'a=%D7%90'); + st.equal(qs.stringify({ a: '𐐷' }), 'a=%F0%90%90%B7'); + st.end(); + }); + + t.test('stringifies falsy values', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(null, { strictNullHandling: true }), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(0), ''); + st.end(); + }); + + t.test('adds query prefix', function (st) { + st.equal(qs.stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b'); + st.end(); + }); + + t.test('with query prefix, outputs blank string given an empty object', function (st) { + st.equal(qs.stringify({}, { addQueryPrefix: true }), ''); + st.end(); + }); + + t.test('stringifies nested falsy values', function (st) { + st.equal(qs.stringify({ a: { b: { c: null } } }), 'a%5Bb%5D%5Bc%5D='); + st.equal(qs.stringify({ a: { b: { c: null } } }, { strictNullHandling: true }), 'a%5Bb%5D%5Bc%5D'); + st.equal(qs.stringify({ a: { b: { c: false } } }), 'a%5Bb%5D%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies a nested object', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + st.end(); + }); + + t.test('stringifies a nested object with dots notation', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }, { allowDots: true }), 'a.b=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true }), 'a.b.c.d=e'); + st.end(); + }); + + t.test('stringifies an array value', function (st) { + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'indices' }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'brackets' }), + 'a%5B%5D=b&a%5B%5D=c&a%5B%5D=d', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma' }), + 'a=b%2Cc%2Cd', + 'comma => comma' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'default => indices' + ); + st.end(); + }); + + t.test('omits nulls when asked', function (st) { + st.equal(qs.stringify({ a: 'b', c: null }, { skipNulls: true }), 'a=b'); + st.end(); + }); + + t.test('omits nested nulls when asked', function (st) { + st.equal(qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('omits array indices when asked', function (st) { + st.equal(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d'); + st.end(); + }); + + t.test('stringifies a nested array value', function (st) { + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'indices' }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'brackets' }), 'a%5Bb%5D%5B%5D=c&a%5Bb%5D%5B%5D=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'comma' }), 'a%5Bb%5D=c%2Cd'); // a[b]=c,d + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + st.end(); + }); + + t.test('stringifies a nested array value with dots notation', function (st) { + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a.b[0]=c&a.b[1]=d', + 'indices: stringifies with dots + indices' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a.b[]=c&a.b[]=d', + 'brackets: stringifies with dots + brackets' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encode: false, arrayFormat: 'comma' } + ), + 'a.b=c,d', + 'comma: stringifies with dots + comma' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encode: false } + ), + 'a.b[0]=c&a.b[1]=d', + 'default: stringifies with dots + indices' + ); + st.end(); + }); + + t.test('stringifies an object inside an array', function (st) { + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'indices' }), + 'a%5B0%5D%5Bb%5D=c', // a[0][b]=c + 'indices => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets' }), + 'a%5B%5D%5Bb%5D=c', // a[][b]=c + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }), + 'a%5B0%5D%5Bb%5D=c', + 'default => indices' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'indices' }), + 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1', + 'indices => indices' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'brackets' }), + 'a%5B%5D%5Bb%5D%5Bc%5D%5B%5D=1', + 'brackets => brackets' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }), + 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an array with mixed objects and primitives', function (st) { + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false, arrayFormat: 'indices' }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false, arrayFormat: 'brackets' }), + 'a[][b]=1&a[]=2&a[]=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an object inside an array with dots notation', function (st) { + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b=c', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b=c', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false } + ), + 'a[0].b=c', + 'default => indices' + ); + + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b.c[0]=1', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b.c[]=1', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false } + ), + 'a[0].b.c[0]=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('does not omit object keys when indices = false', function (st) { + st.equal(qs.stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when indices=true', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when no arrayFormat is specified', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when no arrayFormat=indices', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses repeat notation for arrays when no arrayFormat=repeat', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c'); + st.end(); + }); + + t.test('uses brackets notation for arrays when no arrayFormat=brackets', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c'); + st.end(); + }); + + t.test('stringifies a complicated object', function (st) { + st.equal(qs.stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e'); + st.end(); + }); + + t.test('stringifies an empty value', function (st) { + st.equal(qs.stringify({ a: '' }), 'a='); + st.equal(qs.stringify({ a: null }, { strictNullHandling: true }), 'a'); + + st.equal(qs.stringify({ a: '', b: '' }), 'a=&b='); + st.equal(qs.stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b='); + + st.equal(qs.stringify({ a: { b: '' } }), 'a%5Bb%5D='); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D'); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D='); + + st.end(); + }); + + t.test('stringifies a null object', { skip: !Object.create }, function (st) { + var obj = Object.create(null); + obj.a = 'b'; + st.equal(qs.stringify(obj), 'a=b'); + st.end(); + }); + + t.test('returns an empty string for invalid input', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(''), ''); + st.end(); + }); + + t.test('stringifies an object with a null object as a child', { skip: !Object.create }, function (st) { + var obj = { a: Object.create(null) }; + + obj.a.b = 'c'; + st.equal(qs.stringify(obj), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('drops keys with a value of undefined', function (st) { + st.equal(qs.stringify({ a: undefined }), ''); + + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), 'a%5Bc%5D'); + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), 'a%5Bc%5D='); + st.equal(qs.stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D='); + st.end(); + }); + + t.test('url encodes values', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.end(); + }); + + t.test('stringifies a date', function (st) { + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + st.equal(qs.stringify({ a: now }), str); + st.end(); + }); + + t.test('stringifies the weird object from qs', function (st) { + st.equal(qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + st.end(); + }); + + t.test('skips properties that are part of the object prototype', function (st) { + Object.prototype.crash = 'test'; + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + delete Object.prototype.crash; + st.end(); + }); + + t.test('stringifies boolean values', function (st) { + st.equal(qs.stringify({ a: true }), 'a=true'); + st.equal(qs.stringify({ a: { b: true } }), 'a%5Bb%5D=true'); + st.equal(qs.stringify({ b: false }), 'b=false'); + st.equal(qs.stringify({ b: { c: false } }), 'b%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies buffer values', function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from('test') }), 'a=test'); + st.equal(qs.stringify({ a: { b: SaferBuffer.from('test') } }), 'a%5Bb%5D=test'); + st.end(); + }); + + t.test('stringifies an object using an alternative delimiter', function (st) { + st.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); + st.end(); + }); + + t.test('doesn\'t blow up when Buffer global is missing', function (st) { + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = qs.stringify({ a: 'b', c: 'd' }); + global.Buffer = tempBuffer; + st.equal(result, 'a=b&c=d'); + st.end(); + }); + + t.test('selects properties when filter=array', function (st) { + st.equal(qs.stringify({ a: 'b' }, { filter: ['a'] }), 'a=b'); + st.equal(qs.stringify({ a: 1 }, { filter: [] }), ''); + + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'indices' } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'brackets' } + ), + 'a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2] } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('supports custom representations when filter=function', function (st) { + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + calls += 1; + if (calls === 1) { + st.equal(prefix, '', 'prefix is empty'); + st.equal(value, obj); + } else if (prefix === 'c') { + return void 0; + } else if (value instanceof Date) { + st.equal(prefix, 'e[f]'); + return value.getTime(); + } + return value; + }; + + st.equal(qs.stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000'); + st.equal(calls, 5); + st.end(); + }); + + t.test('can disable uri encoding', function (st) { + st.equal(qs.stringify({ a: 'b' }, { encode: false }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c'); + st.equal(qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), 'a=b&c'); + st.end(); + }); + + t.test('can sort the keys', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal(qs.stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y'); + st.equal(qs.stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a'); + st.end(); + }); + + t.test('can sort the keys at depth 3 or more too', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: sort, encode: false } + ), + 'a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb' + ); + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: null, encode: false } + ), + 'a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b' + ); + st.end(); + }); + + t.test('can stringify with custom encoding', function (st) { + st.equal(qs.stringify({ 県: '大阪府', '': '' }, { + encoder: function (str) { + if (str.length === 0) { + return ''; + } + var buf = iconv.encode(str, 'shiftjis'); + var result = []; + for (var i = 0; i < buf.length; ++i) { + result.push(buf.readUInt8(i).toString(16)); + } + return '%' + result.join('%'); + } + }), '%8c%a7=%91%e5%8d%e3%95%7b&='); + st.end(); + }); + + t.test('receives the default encoder as a second argument', function (st) { + st.plan(2); + qs.stringify({ a: 1 }, { + encoder: function (str, defaultEncoder) { + st.equal(defaultEncoder, utils.encode); + } + }); + st.end(); + }); + + t.test('throws error with wrong encoder', function (st) { + st['throws'](function () { + qs.stringify({}, { encoder: 'string' }); + }, new TypeError('Encoder has to be a function.')); + st.end(); + }); + + t.test('can use custom encoder for a buffer object', { skip: typeof Buffer === 'undefined' }, function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from([1]) }, { + encoder: function (buffer) { + if (typeof buffer === 'string') { + return buffer; + } + return String.fromCharCode(buffer.readUInt8(0) + 97); + } + }), 'a=b'); + st.end(); + }); + + t.test('serializeDate option', function (st) { + var date = new Date(); + st.equal( + qs.stringify({ a: date }), + 'a=' + date.toISOString().replace(/:/g, '%3A'), + 'default is toISOString' + ); + + var mutatedDate = new Date(); + mutatedDate.toISOString = function () { + throw new SyntaxError(); + }; + st['throws'](function () { + mutatedDate.toISOString(); + }, SyntaxError); + st.equal( + qs.stringify({ a: mutatedDate }), + 'a=' + Date.prototype.toISOString.call(mutatedDate).replace(/:/g, '%3A'), + 'toISOString works even when method is not locally present' + ); + + var specificDate = new Date(6); + st.equal( + qs.stringify( + { a: specificDate }, + { serializeDate: function (d) { return d.getTime() * 7; } } + ), + 'a=42', + 'custom serializeDate function called' + ); + + st.end(); + }); + + t.test('RFC 1738 spaces serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC1738 }), 'a=b+c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC1738 }), 'a+b=c+d'); + st.end(); + }); + + t.test('RFC 3986 spaces serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC3986 }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC3986 }), 'a%20b=c%20d'); + st.end(); + }); + + t.test('Backward compatibility to RFC 3986', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.end(); + }); + + t.test('Edge cases and unknown formats', function (st) { + ['UFO1234', false, 1234, null, {}, []].forEach( + function (format) { + st['throws']( + function () { + qs.stringify({ a: 'b c' }, { format: format }); + }, + new TypeError('Unknown format option provided.') + ); + } + ); + st.end(); + }); + + t.test('encodeValuesOnly', function (st) { + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } + ), + 'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] } + ), + 'a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h' + ); + st.end(); + }); + + t.test('encodeValuesOnly - strictNullHandling', function (st) { + st.equal( + qs.stringify( + { a: { b: null } }, + { encodeValuesOnly: true, strictNullHandling: true } + ), + 'a[b]' + ); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.stringify({ a: 'b' }, { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('respects a charset of iso-8859-1', function (st) { + st.equal(qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }), '%E6=%E6'); + st.end(); + }); + + t.test('encodes unrepresentable chars as numeric entities in iso-8859-1 mode', function (st) { + st.equal(qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }), 'a=%26%239786%3B'); + st.end(); + }); + + t.test('respects an explicit charset of utf-8 (the default)', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charset: 'utf-8' }), 'a=%C3%A6'); + st.end(); + }); + + t.test('adds the right sentinel when instructed to and the charset is utf-8', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'utf-8' }), 'utf8=%E2%9C%93&a=%C3%A6'); + st.end(); + }); + + t.test('adds the right sentinel when instructed to and the charset is iso-8859-1', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }), 'utf8=%26%2310003%3B&a=%E6'); + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.stringify({}, options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('strictNullHandling works with custom filter', function (st) { + var filter = function (prefix, value) { + return value; + }; + + var options = { strictNullHandling: true, filter: filter }; + st.equal(qs.stringify({ key: null }, options), 'key'); + st.end(); + }); + + t.test('strictNullHandling works with null serializeDate', function (st) { + var serializeDate = function () { + return null; + }; + var options = { strictNullHandling: true, serializeDate: serializeDate }; + var date = new Date(); + st.equal(qs.stringify({ key: date }, options), 'key'); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/qs/test/utils.js b/node_modules/qs/test/utils.js new file mode 100644 index 0000000..da31ce5 --- /dev/null +++ b/node_modules/qs/test/utils.js @@ -0,0 +1,136 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var SaferBuffer = require('safer-buffer').Buffer; +var forEach = require('for-each'); +var utils = require('../lib/utils'); + +test('merge()', function (t) { + t.deepEqual(utils.merge(null, true), [null, true], 'merges true into null'); + + t.deepEqual(utils.merge(null, [42]), [null, 42], 'merges null into an array'); + + t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key'); + + var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } }); + t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array'); + + var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } }); + t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array'); + + var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' }); + t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array'); + + var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] }); + t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] }); + + var noOptionsNonObjectSource = utils.merge({ foo: 'baz' }, 'bar'); + t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true }); + + t.test( + 'avoids invoking array setters unnecessarily', + { skip: typeof Object.defineProperty !== 'function' }, + function (st) { + var setCount = 0; + var getCount = 0; + var observed = []; + Object.defineProperty(observed, 0, { + get: function () { + getCount += 1; + return { bar: 'baz' }; + }, + set: function () { setCount += 1; } + }); + utils.merge(observed, [null]); + st.equal(setCount, 0); + st.equal(getCount, 1); + observed[0] = observed[0]; // eslint-disable-line no-self-assign + st.equal(setCount, 1); + st.equal(getCount, 2); + st.end(); + } + ); + + t.end(); +}); + +test('assign()', function (t) { + var target = { a: 1, b: 2 }; + var source = { b: 3, c: 4 }; + var result = utils.assign(target, source); + + t.equal(result, target, 'returns the target'); + t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged'); + t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched'); + + t.end(); +}); + +test('combine()', function (t) { + t.test('both arrays', function (st) { + var a = [1]; + var b = [2]; + var combined = utils.combine(a, b); + + st.deepEqual(a, [1], 'a is not mutated'); + st.deepEqual(b, [2], 'b is not mutated'); + st.notEqual(a, combined, 'a !== combined'); + st.notEqual(b, combined, 'b !== combined'); + st.deepEqual(combined, [1, 2], 'combined is a + b'); + + st.end(); + }); + + t.test('one array, one non-array', function (st) { + var aN = 1; + var a = [aN]; + var bN = 2; + var b = [bN]; + + var combinedAnB = utils.combine(aN, b); + st.deepEqual(b, [bN], 'b is not mutated'); + st.notEqual(aN, combinedAnB, 'aN + b !== aN'); + st.notEqual(a, combinedAnB, 'aN + b !== a'); + st.notEqual(bN, combinedAnB, 'aN + b !== bN'); + st.notEqual(b, combinedAnB, 'aN + b !== b'); + st.deepEqual([1, 2], combinedAnB, 'first argument is array-wrapped when not an array'); + + var combinedABn = utils.combine(a, bN); + st.deepEqual(a, [aN], 'a is not mutated'); + st.notEqual(aN, combinedABn, 'a + bN !== aN'); + st.notEqual(a, combinedABn, 'a + bN !== a'); + st.notEqual(bN, combinedABn, 'a + bN !== bN'); + st.notEqual(b, combinedABn, 'a + bN !== b'); + st.deepEqual([1, 2], combinedABn, 'second argument is array-wrapped when not an array'); + + st.end(); + }); + + t.test('neither is an array', function (st) { + var combined = utils.combine(1, 2); + st.notEqual(1, combined, '1 + 2 !== 1'); + st.notEqual(2, combined, '1 + 2 !== 2'); + st.deepEqual([1, 2], combined, 'both arguments are array-wrapped when not an array'); + + st.end(); + }); + + t.end(); +}); + +test('isBuffer()', function (t) { + forEach([null, undefined, true, false, '', 'abc', 42, 0, NaN, {}, [], function () {}, /a/g], function (x) { + t.equal(utils.isBuffer(x), false, inspect(x) + ' is not a buffer'); + }); + + var fakeBuffer = { constructor: Buffer }; + t.equal(utils.isBuffer(fakeBuffer), false, 'fake buffer is not a buffer'); + + var saferBuffer = SaferBuffer.from('abc'); + t.equal(utils.isBuffer(saferBuffer), true, 'SaferBuffer instance is a buffer'); + + var buffer = Buffer.from ? Buffer.from('abc') : new Buffer('abc'); + t.equal(utils.isBuffer(buffer), true, 'real Buffer instance is a buffer'); + t.end(); +}); diff --git a/node_modules/range-parser/HISTORY.md b/node_modules/range-parser/HISTORY.md new file mode 100644 index 0000000..70a973d --- /dev/null +++ b/node_modules/range-parser/HISTORY.md @@ -0,0 +1,56 @@ +1.2.1 / 2019-05-10 +================== + + * Improve error when `str` is not a string + +1.2.0 / 2016-06-01 +================== + + * Add `combine` option to combine overlapping ranges + +1.1.0 / 2016-05-13 +================== + + * Fix incorrectly returning -1 when there is at least one valid range + * perf: remove internal function + +1.0.3 / 2015-10-29 +================== + + * perf: enable strict mode + +1.0.2 / 2014-09-08 +================== + + * Support Node.js 0.6 + +1.0.1 / 2014-09-07 +================== + + * Move repository to jshttp + +1.0.0 / 2013-12-11 +================== + + * Add repository to package.json + * Add MIT license + +0.0.4 / 2012-06-17 +================== + + * Change ret -1 for unsatisfiable and -2 when invalid + +0.0.3 / 2012-06-17 +================== + + * Fix last-byte-pos default to len - 1 + +0.0.2 / 2012-06-14 +================== + + * Add `.type` + +0.0.1 / 2012-06-11 +================== + + * Initial release diff --git a/node_modules/range-parser/LICENSE b/node_modules/range-parser/LICENSE new file mode 100644 index 0000000..3599954 --- /dev/null +++ b/node_modules/range-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015-2016 Douglas Christopher Wilson + +```js +var parseRange = require('range-parser') +``` + +### parseRange(size, header, options) + +Parse the given `header` string where `size` is the maximum size of the resource. +An array of ranges will be returned or negative numbers indicating an error parsing. + + * `-2` signals a malformed header string + * `-1` signals an unsatisfiable range + + + +```js +// parse header from request +var range = parseRange(size, req.headers.range) + +// the type of the range +if (range.type === 'bytes') { + // the ranges + range.forEach(function (r) { + // do something with r.start and r.end + }) +} +``` + +#### Options + +These properties are accepted in the options object. + +##### combine + +Specifies if overlapping & adjacent ranges should be combined, defaults to `false`. +When `true`, ranges will be combined and returned as if they were specified that +way in the header. + + + +```js +parseRange(100, 'bytes=50-55,0-10,5-10,56-60', { combine: true }) +// => [ +// { start: 0, end: 10 }, +// { start: 50, end: 60 } +// ] +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/range-parser/master +[coveralls-url]: https://coveralls.io/r/jshttp/range-parser?branch=master +[node-image]: https://badgen.net/npm/node/range-parser +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/range-parser +[npm-url]: https://npmjs.org/package/range-parser +[npm-version-image]: https://badgen.net/npm/v/range-parser +[travis-image]: https://badgen.net/travis/jshttp/range-parser/master +[travis-url]: https://travis-ci.org/jshttp/range-parser diff --git a/node_modules/range-parser/index.js b/node_modules/range-parser/index.js new file mode 100644 index 0000000..b7dc5c0 --- /dev/null +++ b/node_modules/range-parser/index.js @@ -0,0 +1,162 @@ +/*! + * range-parser + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = rangeParser + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @param {Object} [options] + * @return {Array} + * @public + */ + +function rangeParser (size, str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string') + } + + var index = str.indexOf('=') + + if (index === -1) { + return -2 + } + + // split the range string + var arr = str.slice(index + 1).split(',') + var ranges = [] + + // add ranges type + ranges.type = str.slice(0, index) + + // parse all ranges + for (var i = 0; i < arr.length; i++) { + var range = arr[i].split('-') + var start = parseInt(range[0], 10) + var end = parseInt(range[1], 10) + + // -nnn + if (isNaN(start)) { + start = size - end + end = size - 1 + // nnn- + } else if (isNaN(end)) { + end = size - 1 + } + + // limit last-byte-pos to current length + if (end > size - 1) { + end = size - 1 + } + + // invalid or unsatisifiable + if (isNaN(start) || isNaN(end) || start > end || start < 0) { + continue + } + + // add range + ranges.push({ + start: start, + end: end + }) + } + + if (ranges.length < 1) { + // unsatisifiable + return -1 + } + + return options && options.combine + ? combineRanges(ranges) + : ranges +} + +/** + * Combine overlapping & adjacent ranges. + * @private + */ + +function combineRanges (ranges) { + var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart) + + for (var j = 0, i = 1; i < ordered.length; i++) { + var range = ordered[i] + var current = ordered[j] + + if (range.start > current.end + 1) { + // next range + ordered[++j] = range + } else if (range.end > current.end) { + // extend range + current.end = range.end + current.index = Math.min(current.index, range.index) + } + } + + // trim ordered array + ordered.length = j + 1 + + // generate combined range + var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex) + + // copy ranges type + combined.type = ranges.type + + return combined +} + +/** + * Map function to add index value to ranges. + * @private + */ + +function mapWithIndex (range, index) { + return { + start: range.start, + end: range.end, + index: index + } +} + +/** + * Map function to remove index value from ranges. + * @private + */ + +function mapWithoutIndex (range) { + return { + start: range.start, + end: range.end + } +} + +/** + * Sort function to sort ranges by index. + * @private + */ + +function sortByRangeIndex (a, b) { + return a.index - b.index +} + +/** + * Sort function to sort ranges by start position. + * @private + */ + +function sortByRangeStart (a, b) { + return a.start - b.start +} diff --git a/node_modules/range-parser/package.json b/node_modules/range-parser/package.json new file mode 100644 index 0000000..abea6d8 --- /dev/null +++ b/node_modules/range-parser/package.json @@ -0,0 +1,44 @@ +{ + "name": "range-parser", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "description": "Range header field string parser", + "version": "1.2.1", + "contributors": [ + "Douglas Christopher Wilson ", + "James Wyatt Cready ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "range", + "parser", + "http" + ], + "repository": "jshttp/range-parser", + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "mocha": "6.1.4", + "nyc": "14.1.1" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + } +} diff --git a/node_modules/raw-body/HISTORY.md b/node_modules/raw-body/HISTORY.md new file mode 100644 index 0000000..88c79fc --- /dev/null +++ b/node_modules/raw-body/HISTORY.md @@ -0,0 +1,270 @@ +2.4.0 / 2019-04-17 +================== + + * deps: bytes@3.1.0 + - Add petabyte (`pb`) support + * deps: http-errors@1.7.2 + - Set constructor name when possible + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: iconv-lite@0.4.24 + - Added encoding MIK + +2.3.3 / 2018-05-08 +================== + + * deps: http-errors@1.6.3 + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.0 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.23 + - Fix loading encoding with year appended + - Fix deprecation warnings on Node.js 10+ + +2.3.2 / 2017-09-09 +================== + + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + +2.3.1 / 2017-09-07 +================== + + * deps: bytes@3.0.0 + * deps: http-errors@1.6.2 + - deps: depd@1.1.1 + * perf: skip buffer decoding on overage chunk + +2.3.0 / 2017-08-04 +================== + + * Add TypeScript definitions + * Use `http-errors` for standard emitted errors + * deps: bytes@2.5.0 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + +2.2.0 / 2017-01-02 +================== + + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + +2.1.7 / 2016-06-19 +================== + + * deps: bytes@2.4.0 + * perf: remove double-cleanup on happy path + +2.1.6 / 2016-03-07 +================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + +2.1.5 / 2015-11-30 +================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + +2.1.4 / 2015-09-27 +================== + + * Fix masking critical errors from `iconv-lite` + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + +2.1.3 / 2015-09-12 +================== + + * Fix sync callback when attaching data listener causes sync read + - Node.js 0.10 compatibility issue + +2.1.2 / 2015-07-05 +================== + + * Fix error stack traces to skip `makeError` + * deps: iconv-lite@0.4.11 + - Add encoding CESU-8 + +2.1.1 / 2015-06-14 +================== + + * Use `unpipe` module for unpiping requests + +2.1.0 / 2015-05-28 +================== + + * deps: iconv-lite@0.4.10 + - Improved UTF-16 endianness detection + - Leading BOM is now removed when decoding + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + +2.0.2 / 2015-05-21 +================== + + * deps: bytes@2.1.0 + - Slight optimizations + +2.0.1 / 2015-05-10 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + +2.0.0 / 2015-05-08 +================== + + * Return a promise without callback instead of thunk + * deps: bytes@2.0.1 + - units no longer case sensitive when parsing + +1.3.4 / 2015-04-15 +================== + + * Fix hanging callback if request aborts during read + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + +1.3.3 / 2015-02-08 +================== + + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + +1.3.2 / 2015-01-20 +================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + +1.3.1 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + +1.3.0 / 2014-07-20 +================== + + * Fully unpipe the stream on error + - Fixes `Cannot switch to old mode now` error on Node.js 0.10+ + +1.2.3 / 2014-07-20 +================== + + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + +1.2.2 / 2014-06-19 +================== + + * Send invalid encoding error to callback + +1.2.1 / 2014-06-15 +================== + + * deps: iconv-lite@0.4.3 + - Added encodings UTF-16BE and UTF-16 with BOM + +1.2.0 / 2014-06-13 +================== + + * Passing string as `options` interpreted as encoding + * Support all encodings from `iconv-lite` + +1.1.7 / 2014-06-12 +================== + + * use `string_decoder` module from npm + +1.1.6 / 2014-05-27 +================== + + * check encoding for old streams1 + * support node.js < 0.10.6 + +1.1.5 / 2014-05-14 +================== + + * bump bytes + +1.1.4 / 2014-04-19 +================== + + * allow true as an option + * bump bytes + +1.1.3 / 2014-03-02 +================== + + * fix case when length=null + +1.1.2 / 2013-12-01 +================== + + * be less strict on state.encoding check + +1.1.1 / 2013-11-27 +================== + + * add engines + +1.1.0 / 2013-11-27 +================== + + * add err.statusCode and err.type + * allow for encoding option to be true + * pause the stream instead of dumping on error + * throw if the stream's encoding is set + +1.0.1 / 2013-11-19 +================== + + * dont support streams1, throw if dev set encoding + +1.0.0 / 2013-11-17 +================== + + * rename `expected` option to `length` + +0.2.0 / 2013-11-15 +================== + + * republish + +0.1.1 / 2013-11-15 +================== + + * use bytes + +0.1.0 / 2013-11-11 +================== + + * generator support + +0.0.3 / 2013-10-10 +================== + + * update repo + +0.0.2 / 2013-09-14 +================== + + * dump stream on bad headers + * listen to events after defining received and buffers + +0.0.1 / 2013-09-14 +================== + + * Initial release diff --git a/node_modules/raw-body/LICENSE b/node_modules/raw-body/LICENSE new file mode 100644 index 0000000..d695c8f --- /dev/null +++ b/node_modules/raw-body/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2013-2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/raw-body/README.md b/node_modules/raw-body/README.md new file mode 100644 index 0000000..2ce79d2 --- /dev/null +++ b/node_modules/raw-body/README.md @@ -0,0 +1,219 @@ +# raw-body + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +Gets the entire buffer of a stream either as a `Buffer` or a string. +Validates the stream's length against an expected length and maximum limit. +Ideal for parsing request bodies. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install raw-body +``` + +### TypeScript + +This module includes a [TypeScript](https://www.typescriptlang.org/) +declaration file to enable auto complete in compatible editors and type +information for TypeScript projects. This module depends on the Node.js +types, so install `@types/node`: + +```sh +$ npm install @types/node +``` + +## API + + + +```js +var getRawBody = require('raw-body') +``` + +### getRawBody(stream, [options], [callback]) + +**Returns a promise if no callback specified and global `Promise` exists.** + +Options: + +- `length` - The length of the stream. + If the contents of the stream do not add up to this length, + an `400` error code is returned. +- `limit` - The byte limit of the body. + This is the number of bytes or any string format supported by + [bytes](https://www.npmjs.com/package/bytes), + for example `1000`, `'500kb'` or `'3mb'`. + If the body ends up being larger than this limit, + a `413` error code is returned. +- `encoding` - The encoding to use to decode the body into a string. + By default, a `Buffer` instance will be returned when no encoding is specified. + Most likely, you want `utf-8`, so setting `encoding` to `true` will decode as `utf-8`. + You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme). + +You can also pass a string in place of options to just specify the encoding. + +If an error occurs, the stream will be paused, everything unpiped, +and you are responsible for correctly disposing the stream. +For HTTP requests, no handling is required if you send a response. +For streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks. + +## Errors + +This module creates errors depending on the error condition during reading. +The error may be an error from the underlying Node.js implementation, but is +otherwise an error created by this module, which has the following attributes: + + * `limit` - the limit in bytes + * `length` and `expected` - the expected length of the stream + * `received` - the received bytes + * `encoding` - the invalid encoding + * `status` and `statusCode` - the corresponding status code for the error + * `type` - the error type + +### Types + +The errors from this module have a `type` property which allows for the progamatic +determination of the type of error returned. + +#### encoding.unsupported + +This error will occur when the `encoding` option is specified, but the value does +not map to an encoding supported by the [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme) +module. + +#### entity.too.large + +This error will occur when the `limit` option is specified, but the stream has +an entity that is larger. + +#### request.aborted + +This error will occur when the request stream is aborted by the client before +reading the body has finished. + +#### request.size.invalid + +This error will occur when the `length` option is specified, but the stream has +emitted more bytes. + +#### stream.encoding.set + +This error will occur when the given stream has an encoding set on it, making it +a decoded stream. The stream should not have an encoding set and is expected to +emit `Buffer` objects. + +## Examples + +### Simple Express example + +```js +var contentType = require('content-type') +var express = require('express') +var getRawBody = require('raw-body') + +var app = express() + +app.use(function (req, res, next) { + getRawBody(req, { + length: req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(req).parameters.charset + }, function (err, string) { + if (err) return next(err) + req.text = string + next() + }) +}) + +// now access req.text +``` + +### Simple Koa example + +```js +var contentType = require('content-type') +var getRawBody = require('raw-body') +var koa = require('koa') + +var app = koa() + +app.use(function * (next) { + this.text = yield getRawBody(this.req, { + length: this.req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(this.req).parameters.charset + }) + yield next +}) + +// now access this.text +``` + +### Using as a promise + +To use this library as a promise, simply omit the `callback` and a promise is +returned, provided that a global `Promise` is defined. + +```js +var getRawBody = require('raw-body') +var http = require('http') + +var server = http.createServer(function (req, res) { + getRawBody(req) + .then(function (buf) { + res.statusCode = 200 + res.end(buf.length + ' bytes submitted') + }) + .catch(function (err) { + res.statusCode = 500 + res.end(err.message) + }) +}) + +server.listen(3000) +``` + +### Using with TypeScript + +```ts +import * as getRawBody from 'raw-body'; +import * as http from 'http'; + +const server = http.createServer((req, res) => { + getRawBody(req) + .then((buf) => { + res.statusCode = 200; + res.end(buf.length + ' bytes submitted'); + }) + .catch((err) => { + res.statusCode = err.statusCode; + res.end(err.message); + }); +}); + +server.listen(3000); +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/raw-body.svg +[npm-url]: https://npmjs.org/package/raw-body +[node-version-image]: https://img.shields.io/node/v/raw-body.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/raw-body/master.svg +[travis-url]: https://travis-ci.org/stream-utils/raw-body +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master +[downloads-image]: https://img.shields.io/npm/dm/raw-body.svg +[downloads-url]: https://npmjs.org/package/raw-body diff --git a/node_modules/raw-body/index.d.ts b/node_modules/raw-body/index.d.ts new file mode 100644 index 0000000..dcbbebd --- /dev/null +++ b/node_modules/raw-body/index.d.ts @@ -0,0 +1,87 @@ +import { Readable } from 'stream'; + +declare namespace getRawBody { + export type Encoding = string | true; + + export interface Options { + /** + * The expected length of the stream. + */ + length?: number | string | null; + /** + * The byte limit of the body. This is the number of bytes or any string + * format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. + */ + limit?: number | string | null; + /** + * The encoding to use to decode the body into a string. By default, a + * `Buffer` instance will be returned when no encoding is specified. Most + * likely, you want `utf-8`, so setting encoding to `true` will decode as + * `utf-8`. You can use any type of encoding supported by `iconv-lite`. + */ + encoding?: Encoding | null; + } + + export interface RawBodyError extends Error { + /** + * The limit in bytes. + */ + limit?: number; + /** + * The expected length of the stream. + */ + length?: number; + expected?: number; + /** + * The received bytes. + */ + received?: number; + /** + * The encoding. + */ + encoding?: string; + /** + * The corresponding status code for the error. + */ + status: number; + statusCode: number; + /** + * The error type. + */ + type: string; + } +} + +/** + * Gets the entire buffer of a stream either as a `Buffer` or a string. + * Validates the stream's length against an expected length and maximum + * limit. Ideal for parsing request bodies. + */ +declare function getRawBody( + stream: Readable, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: Readable, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding, + callback: (err: getRawBody.RawBodyError, body: string) => void +): void; + +declare function getRawBody( + stream: Readable, + options: getRawBody.Options, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: Readable, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding +): Promise; + +declare function getRawBody( + stream: Readable, + options?: getRawBody.Options +): Promise; + +export = getRawBody; diff --git a/node_modules/raw-body/index.js b/node_modules/raw-body/index.js new file mode 100644 index 0000000..7fe8186 --- /dev/null +++ b/node_modules/raw-body/index.js @@ -0,0 +1,286 @@ +/*! + * raw-body + * Copyright(c) 2013-2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var createError = require('http-errors') +var iconv = require('iconv-lite') +var unpipe = require('unpipe') + +/** + * Module exports. + * @public + */ + +module.exports = getRawBody + +/** + * Module variables. + * @private + */ + +var ICONV_ENCODING_MESSAGE_REGEXP = /^Encoding not recognized: / + +/** + * Get the decoder for a given encoding. + * + * @param {string} encoding + * @private + */ + +function getDecoder (encoding) { + if (!encoding) return null + + try { + return iconv.getDecoder(encoding) + } catch (e) { + // error getting decoder + if (!ICONV_ENCODING_MESSAGE_REGEXP.test(e.message)) throw e + + // the encoding was not found + throw createError(415, 'specified encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } +} + +/** + * Get the raw body of a stream (typically HTTP). + * + * @param {object} stream + * @param {object|string|function} [options] + * @param {function} [callback] + * @public + */ + +function getRawBody (stream, options, callback) { + var done = callback + var opts = options || {} + + if (options === true || typeof options === 'string') { + // short cut for encoding + opts = { + encoding: options + } + } + + if (typeof options === 'function') { + done = options + opts = {} + } + + // validate callback is a function, if provided + if (done !== undefined && typeof done !== 'function') { + throw new TypeError('argument callback must be a function') + } + + // require the callback without promises + if (!done && !global.Promise) { + throw new TypeError('argument callback is required') + } + + // get encoding + var encoding = opts.encoding !== true + ? opts.encoding + : 'utf-8' + + // convert the limit to an integer + var limit = bytes.parse(opts.limit) + + // convert the expected length to an integer + var length = opts.length != null && !isNaN(opts.length) + ? parseInt(opts.length, 10) + : null + + if (done) { + // classic callback style + return readStream(stream, encoding, length, limit, done) + } + + return new Promise(function executor (resolve, reject) { + readStream(stream, encoding, length, limit, function onRead (err, buf) { + if (err) return reject(err) + resolve(buf) + }) + }) +} + +/** + * Halt a stream. + * + * @param {Object} stream + * @private + */ + +function halt (stream) { + // unpipe everything from the stream + unpipe(stream) + + // pause stream + if (typeof stream.pause === 'function') { + stream.pause() + } +} + +/** + * Read the data from the stream. + * + * @param {object} stream + * @param {string} encoding + * @param {number} length + * @param {number} limit + * @param {function} callback + * @public + */ + +function readStream (stream, encoding, length, limit, callback) { + var complete = false + var sync = true + + // check the length and limit options. + // note: we intentionally leave the stream paused, + // so users should handle the stream themselves. + if (limit !== null && length !== null && length > limit) { + return done(createError(413, 'request entity too large', { + expected: length, + length: length, + limit: limit, + type: 'entity.too.large' + })) + } + + // streams1: assert request encoding is buffer. + // streams2+: assert the stream encoding is buffer. + // stream._decoder: streams1 + // state.encoding: streams2 + // state.decoder: streams2, specifically < 0.10.6 + var state = stream._readableState + if (stream._decoder || (state && (state.encoding || state.decoder))) { + // developer error + return done(createError(500, 'stream encoding should not be set', { + type: 'stream.encoding.set' + })) + } + + var received = 0 + var decoder + + try { + decoder = getDecoder(encoding) + } catch (err) { + return done(err) + } + + var buffer = decoder + ? '' + : [] + + // attach listeners + stream.on('aborted', onAborted) + stream.on('close', cleanup) + stream.on('data', onData) + stream.on('end', onEnd) + stream.on('error', onEnd) + + // mark sync section complete + sync = false + + function done () { + var args = new Array(arguments.length) + + // copy arguments + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + // mark complete + complete = true + + if (sync) { + process.nextTick(invokeCallback) + } else { + invokeCallback() + } + + function invokeCallback () { + cleanup() + + if (args[0]) { + // halt the stream on error + halt(stream) + } + + callback.apply(null, args) + } + } + + function onAborted () { + if (complete) return + + done(createError(400, 'request aborted', { + code: 'ECONNABORTED', + expected: length, + length: length, + received: received, + type: 'request.aborted' + })) + } + + function onData (chunk) { + if (complete) return + + received += chunk.length + + if (limit !== null && received > limit) { + done(createError(413, 'request entity too large', { + limit: limit, + received: received, + type: 'entity.too.large' + })) + } else if (decoder) { + buffer += decoder.write(chunk) + } else { + buffer.push(chunk) + } + } + + function onEnd (err) { + if (complete) return + if (err) return done(err) + + if (length !== null && received !== length) { + done(createError(400, 'request size did not match content length', { + expected: length, + length: length, + received: received, + type: 'request.size.invalid' + })) + } else { + var string = decoder + ? buffer + (decoder.end() || '') + : Buffer.concat(buffer) + done(null, string) + } + } + + function cleanup () { + buffer = null + + stream.removeListener('aborted', onAborted) + stream.removeListener('data', onData) + stream.removeListener('end', onEnd) + stream.removeListener('error', onEnd) + stream.removeListener('close', cleanup) + } +} diff --git a/node_modules/raw-body/package.json b/node_modules/raw-body/package.json new file mode 100644 index 0000000..7f1e5af --- /dev/null +++ b/node_modules/raw-body/package.json @@ -0,0 +1,48 @@ +{ + "name": "raw-body", + "description": "Get and validate the raw body of a readable stream.", + "version": "2.4.0", + "author": "Jonathan Ong (http://jongleberry.com)", + "contributors": [ + "Douglas Christopher Wilson ", + "Raynos " + ], + "license": "MIT", + "repository": "stream-utils/raw-body", + "dependencies": { + "bytes": "3.1.0", + "http-errors": "1.7.2", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "devDependencies": { + "bluebird": "3.5.4", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "6.1.3", + "readable-stream": "2.3.6", + "safe-buffer": "5.1.2" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.d.ts", + "index.js" + ], + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --trace-deprecation --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --trace-deprecation --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --trace-deprecation --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/readable-stream/CONTRIBUTING.md b/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 0000000..f478d58 --- /dev/null +++ b/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/node_modules/readable-stream/GOVERNANCE.md b/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 0000000..16ffb93 --- /dev/null +++ b/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/node_modules/readable-stream/LICENSE b/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..2873b3b --- /dev/null +++ b/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node 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. +""" diff --git a/node_modules/readable-stream/README.md b/node_modules/readable-stream/README.md new file mode 100644 index 0000000..6f035ab --- /dev/null +++ b/node_modules/readable-stream/README.md @@ -0,0 +1,106 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.19.0/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/node_modules/readable-stream/errors-browser.js b/node_modules/readable-stream/errors-browser.js new file mode 100644 index 0000000..fb8e73e --- /dev/null +++ b/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,127 @@ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; diff --git a/node_modules/readable-stream/errors.js b/node_modules/readable-stream/errors.js new file mode 100644 index 0000000..8471526 --- /dev/null +++ b/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/node_modules/readable-stream/experimentalWarning.js b/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 0000000..78e8414 --- /dev/null +++ b/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..6752519 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,139 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. +'use strict'; +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); + } + + return keys; +}; +/**/ + + +module.exports = Duplex; + +var Readable = require('./_stream_readable'); + +var Writable = require('./_stream_writable'); + +require('inherits')(Duplex, Readable); + +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); // the no-half-open enforcer + +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + process.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..32e7414 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +require('inherits')(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..192d451 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1124 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +'use strict'; + +module.exports = Readable; +/**/ + +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; +/**/ + +var EE = require('events').EventEmitter; + +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ + + +var Stream = require('./internal/streams/stream'); +/**/ + + +var Buffer = require('buffer').Buffer; + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ + + +var debugUtil = require('util'); + +var debug; + +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + + +var BufferList = require('./internal/streams/buffer_list'); + +var destroyImpl = require('./internal/streams/destroy'); + +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + + +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; + +require('inherits')(Readable, Stream); + +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + + this.autoDestroy = !!options.autoDestroy; // has it been destroyed + + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); // legacy + + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; + +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; // Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. + + +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; // Unshift should *always* be something directly out of read() + + +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + + + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + + return er; +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; // backwards compatibility. + + +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + + var p = this._readableState.buffer.head; + var content = ''; + + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + + this._readableState.buffer.clear(); + + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; // Don't raise the hwm > 1GB + + +var MAX_HWM = 0x40000000; + +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + + return n; +} // This function is designed to be inlinable, so please take care when making +// changes to the function body. + + +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. + + + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough + + if (!state.ended) { + state.needReadable = true; + return 0; + } + + return state.length; +} // you can override either this method, or the async _read(n) below. + + +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + + + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + + + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. + + if (state.length === 0) state.needReadable = true; // call internal read method + + this._read(state.highWaterMark); + + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + return ret; +}; + +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + + state.ended = true; + + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} // Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. + + +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} + +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + + + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} // at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. + + +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + state.readingMore = false; +} // abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. + + +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + + case 1: + state.pipes = [state.pipes, dest]; + break; + + default: + state.pipes.push(dest); + break; + } + + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + + + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken + + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + + + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. + + + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + + dest.once('close', onclose); + + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to + + + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. + + if (state.pipesCount === 0) return this; // just one destination. most common case. + + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. + + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. + + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } + + return this; + } // try to find the right one. + + + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; // set up data events if they are asked for +// Ensure readable listeners eventually get something + + +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + + return res; +}; + +Readable.prototype.addListener = Readable.prototype.on; + +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} // pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. + + +Readable.prototype.resume = function () { + var state = this._readableState; + + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume(this, state); + } + + state.paused = false; + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + debug('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + + this._readableState.paused = true; + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + + while (state.flowing && stream.read() !== null) { + ; + } +} // wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. + + +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. + + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. + + + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. + + + this._read = function (n) { + debug('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + + return createReadableStreamAsyncIterator(this); + }; +} + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); // exposed for testing purposes only. + +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); // Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. + +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} + +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + + return from(Readable, iterable, opts); + }; +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + + return -1; +} \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..41a738c --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,201 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. +'use strict'; + +module.exports = Transform; + +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + +var Duplex = require('./_stream_duplex'); + +require('inherits')(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. + + + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; // This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. + + +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; // Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. + + +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..a2634d7 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,697 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. +'use strict'; + +module.exports = Writable; +/* */ + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} // It seems a linked list but it is not +// there will be only 2 of these for each stream + + +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ + + +var Duplex; +/**/ + +Writable.WritableState = WritableState; +/**/ + +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ + +var Stream = require('./internal/streams/stream'); +/**/ + + +var Buffer = require('buffer').Buffer; + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +var destroyImpl = require('./internal/streams/destroy'); + +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + +var errorOrDestroy = destroyImpl.errorOrDestroy; + +require('inherits')(Writable, Stream); + +function nop() {} + +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + + this.finalCalled = false; // drain event flag. + + this.needDrain = false; // at the start of calling end() + + this.ending = false; // when end() has been called, and returned + + this.ended = false; // when 'finish' is emitted + + this.finished = false; // has it been destroyed + + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + + this.length = 0; // a flag to see when we're in the middle of a write. + + this.writing = false; // when true all writes will be buffered until .uncork() call + + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) + + + this.writecb = null; // the amount that is being written when _write is called. + + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + + this.prefinished = false; // True if the error was already emitted and should not be thrown again + + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + + this.autoDestroy = !!options.autoDestroy; // count buffered requests + + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + + while (current) { + out.push(current); + current = current.next; + } + + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); // Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. + + +var realHasInstance; + +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. + + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} // Otherwise people can pipe Writable streams, which is just wrong. + + +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; + +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} // Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. + + +function validChunk(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + + return true; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; + +Writable.prototype.cork = function () { + this._writableState.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); // if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. + +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} // Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. + + +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} // if there's something in the buffer waiting, then process it + + +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable(this, state, cb); + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy(stream, err); + } + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} + +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + + if (need) { + prefinish(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. + + + state.corkedRequestsFree.next = corkReq; +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; + +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 0000000..9fb615a --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,207 @@ +'use strict'; + +var _Object$setPrototypeO; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var finished = require('./end-of-stream'); + +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); + +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} + +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} + +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} + +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} + +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + + next: function next() { + var _this = this; + + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); + } + + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + + + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); + +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } + + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; + +module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 0000000..cdea425 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,210 @@ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var _require = require('buffer'), + Buffer = _require.Buffer; + +var _require2 = require('util'), + inspect = _require2.inspect; + +var custom = inspect && inspect.custom || 'inspect'; + +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} + +module.exports = +/*#__PURE__*/ +function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + + while (p = p.next) { + ret += s + p.data; + } + + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. + + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + + return BufferList; +}(); \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/destroy.js b/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 0000000..3268a16 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,105 @@ +'use strict'; // undocumented cb() API, needed for core, not for public API + +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + + return this; +} + +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} + +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 0000000..831f286 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,104 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + callback.apply(this, args); + }; +} + +function noop() {} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + + var readableEnded = stream._readableState && stream._readableState.endEmitted; + + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + + var onerror = function onerror(err) { + callback.call(stream, err); + }; + + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} + +module.exports = eos; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/from-browser.js b/node_modules/readable-stream/lib/internal/streams/from-browser.js new file mode 100644 index 0000000..a4ce56f --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/from-browser.js @@ -0,0 +1,3 @@ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; diff --git a/node_modules/readable-stream/lib/internal/streams/from.js b/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 0000000..6c41284 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,64 @@ +'use strict'; + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; + +function from(Readable, iterable, opts) { + var iterator; + + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); // Reading boolean to protect against _read + // being called before last iteration completion. + + var reading = false; + + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + + function next() { + return _next2.apply(this, arguments); + } + + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _ref = yield iterator.next(), + value = _ref.value, + done = _ref.done; + + if (done) { + readable.push(null); + } else if (readable.push((yield value))) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + + return readable; +} + +module.exports = from; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/pipeline.js b/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 0000000..6589909 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,97 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). +'use strict'; + +var eos; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} + +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} + +function call(fn) { + fn(); +} + +function pipe(from, to) { + return from.pipe(to); +} + +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} + +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} + +module.exports = pipeline; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/state.js b/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 0000000..19887eb --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,27 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; + +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} + +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + + return Math.floor(hwm); + } // Default value + + + return state.objectMode ? 16 : 16 * 1024; +} + +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 0000000..9332a3f --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/node_modules/readable-stream/lib/internal/streams/stream.js b/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 0000000..ce2ad5b --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/node_modules/readable-stream/package.json b/node_modules/readable-stream/package.json new file mode 100644 index 0000000..0b0c4bd --- /dev/null +++ b/node_modules/readable-stream/package.json @@ -0,0 +1,68 @@ +{ + "name": "readable-stream", + "version": "3.6.0", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "engines": { + "node": ">= 6" + }, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.2.0", + "@babel/core": "^7.2.0", + "@babel/polyfill": "^7.0.0", + "@babel/preset-env": "^7.2.0", + "airtap": "0.0.9", + "assert": "^1.4.0", + "bl": "^2.0.0", + "deep-strict-equal": "^0.2.0", + "events.once": "^2.0.2", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^12.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "scripts": { + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "update-browser-errors": "babel -o errors-browser.js errors.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/node_modules/readable-stream/readable-browser.js b/node_modules/readable-stream/readable-browser.js new file mode 100644 index 0000000..adbf60d --- /dev/null +++ b/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,9 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +exports.finished = require('./lib/internal/streams/end-of-stream.js'); +exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/node_modules/readable-stream/readable.js b/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..9e0ca12 --- /dev/null +++ b/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/node_modules/regexp-clone/.travis.yml b/node_modules/regexp-clone/.travis.yml new file mode 100644 index 0000000..220a17b --- /dev/null +++ b/node_modules/regexp-clone/.travis.yml @@ -0,0 +1,14 @@ +sudo: false +language: node_js +node_js: + - 8 + - 10 + - 12 +matrix: + include: + - node_js: "13" + env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly" + allow_failures: + # Allow the nightly installs to fail + - env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly" +script: "npm test" diff --git a/node_modules/regexp-clone/History.md b/node_modules/regexp-clone/History.md new file mode 100644 index 0000000..0beedfc --- /dev/null +++ b/node_modules/regexp-clone/History.md @@ -0,0 +1,5 @@ + +0.0.1 / 2013-04-17 +================== + + * initial commit diff --git a/node_modules/regexp-clone/LICENSE b/node_modules/regexp-clone/LICENSE new file mode 100644 index 0000000..98c7c89 --- /dev/null +++ b/node_modules/regexp-clone/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 [Aaron Heckmann](aaron.heckmann+github@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/regexp-clone/Makefile b/node_modules/regexp-clone/Makefile new file mode 100644 index 0000000..6c8fb75 --- /dev/null +++ b/node_modules/regexp-clone/Makefile @@ -0,0 +1,5 @@ + +test: + @./node_modules/.bin/mocha $(T) --async-only $(TESTS) + +.PHONY: test diff --git a/node_modules/regexp-clone/README.md b/node_modules/regexp-clone/README.md new file mode 100644 index 0000000..4a16bad --- /dev/null +++ b/node_modules/regexp-clone/README.md @@ -0,0 +1,42 @@ +#regexp-clone +============== + +Clones RegExps with flag and `lastIndex` preservation. + +```js +const regexpClone = require('regexp-clone'); + +const a = /somethin/misguy; +console.log(a.global); // true +console.log(a.ignoreCase); // true +console.log(a.multiline); // true +console.log(a.dotAll); // true +console.log(a.unicode); // true +console.log(a.sticky); // true + +const b = regexpClone(a); +console.log(b.global); // true +console.log(b.ignoreCase); // true +console.log(b.multiline); // true +console.log(b.dotAll); // true +console.log(b.unicode); // true +console.log(b.sticky); // true + +const c = /hi/g; +c.test('this string hi there'); +assert.strictEqual(c.lastIndex, 3); + +const d = regexpClone(c); +assert.strictEqual(d.lastIndex, 3); +d.test('this string hi there'); +assert.strictEqual(d.lastIndex, 14); +assert.strictEqual(c.lastIndex, 3); +``` + +``` +npm install regexp-clone +``` + +## License + +[MIT](https://github.com/aheckmann/regexp-clone/blob/master/LICENSE) diff --git a/node_modules/regexp-clone/index.js b/node_modules/regexp-clone/index.js new file mode 100644 index 0000000..19512b3 --- /dev/null +++ b/node_modules/regexp-clone/index.js @@ -0,0 +1,27 @@ + +const toString = Object.prototype.toString; + +function isRegExp (o) { + return 'object' == typeof o + && '[object RegExp]' == toString.call(o); +} + +module.exports = exports = function (regexp) { + if (!isRegExp(regexp)) { + throw new TypeError('Not a RegExp'); + } + + const flags = []; + if (regexp.global) flags.push('g'); + if (regexp.multiline) flags.push('m'); + if (regexp.ignoreCase) flags.push('i'); + if (regexp.dotAll) flags.push('s'); + if (regexp.unicode) flags.push('u'); + if (regexp.sticky) flags.push('y'); + const result = new RegExp(regexp.source, flags.join('')); + if (typeof regexp.lastIndex === 'number') { + result.lastIndex = regexp.lastIndex; + } + return result; +} + diff --git a/node_modules/regexp-clone/package.json b/node_modules/regexp-clone/package.json new file mode 100644 index 0000000..dd25977 --- /dev/null +++ b/node_modules/regexp-clone/package.json @@ -0,0 +1,22 @@ +{ + "name": "regexp-clone", + "version": "1.0.0", + "description": "Clone RegExps with options", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/regexp-clone.git" + }, + "keywords": [ + "RegExp", + "clone" + ], + "author": "Aaron Heckmann ", + "license": "MIT", + "devDependencies": { + "mocha": "^6.1.4" + } +} diff --git a/node_modules/regexp-clone/test/index.js b/node_modules/regexp-clone/test/index.js new file mode 100644 index 0000000..ceaea28 --- /dev/null +++ b/node_modules/regexp-clone/test/index.js @@ -0,0 +1,171 @@ + +const assert = require('assert') +const clone = require('../'); + +describe('regexp-clone', function(){ + function hasEqualSource (a, b) { + assert.ok(a !== b); + assert.equal(a.source, b.source); + } + + function isIgnoreCase (a) { + assert.ok(a.ignoreCase); + } + + function isGlobal (a) { + assert.ok(a.global); + } + + function isMultiline (a) { + assert.ok(a.multiline); + } + + function isDotAll (a) { + assert.ok(a.dotAll); + } + + function isUnicode (a) { + assert.ok(a.unicode); + } + + function isSticky(a) { + assert.ok(a.sticky); + } + + function testFlag (a, method) { + const b = clone(a); + hasEqualSource(a, b); + method(a); + method(b); + } + + function lastIndex(a) { + a.test('this string hi there'); + assert.strictEqual(a.lastIndex, 3); + const b = clone(a); + assert.strictEqual(b.lastIndex, 3); + assert.strictEqual(a.lastIndex, 3); + b.test('this string hi there'); + assert.strictEqual(b.lastIndex, 14); + assert.strictEqual(a.lastIndex, 3); + } + + function allFlags(a) { + const b = clone(a); + hasEqualSource(a, b); + testFlag(b, isIgnoreCase); + testFlag(b, isGlobal); + testFlag(b, isMultiline); + testFlag(b, isDotAll); + testFlag(b, isUnicode); + testFlag(b, isSticky); + } + + function noFlags(a) { + const b = clone(a); + hasEqualSource(a, b); + assert.ok(!b.ignoreCase); + assert.ok(!b.global); + assert.ok(!b.multiline); + assert.ok(!b.dotAll); + assert.ok(!b.unicode); + assert.ok(!b.sticky); + } + + describe('literals', function(){ + it('ignoreCase flag', function(done){ + const a = /hello/i; + testFlag(a, isIgnoreCase); + done(); + }) + it('global flag', function(done){ + const a = /hello/g; + testFlag(a, isGlobal); + done(); + }) + it('multiline flag', function(done){ + const a = /hello/m; + testFlag(a, isMultiline); + done(); + }) + it('dotAll flag', function(done){ + const a = /hello/s; + testFlag(a, isDotAll); + done(); + }) + it('unicode flag', function(done){ + const a = /hello/u; + testFlag(a, isUnicode); + done(); + }) + it('sticky flag', function(done){ + const a = /hello/y; + testFlag(a, isSticky); + done(); + }) + it('no flags', function(done){ + const a = /hello/; + noFlags(a); + done(); + }) + it('all flags', function(done){ + const a = /hello/gimsuy; + allFlags(a); + done(); + }) + it('lastIndex', function(done) { + const a = /hi/g; + lastIndex(a); + done(); + }) + }) + + describe('instances', function(){ + it('ignoreCase flag', function(done){ + const a = new RegExp('hello', 'i'); + testFlag(a, isIgnoreCase); + done(); + }) + it('global flag', function(done){ + const a = new RegExp('hello', 'g'); + testFlag(a, isGlobal); + done(); + }) + it('multiline flag', function(done){ + const a = new RegExp('hello', 'm'); + testFlag(a, isMultiline); + done(); + }) + it('dotAll flag', function(done){ + const a = new RegExp('hello', 's'); + testFlag(a, isDotAll); + done(); + }) + it('unicode flag', function(done){ + const a = new RegExp('hello', 'u'); + testFlag(a, isUnicode); + done(); + }) + it('sticky flag', function(done){ + const a = new RegExp('hello', 'y'); + testFlag(a, isSticky); + done(); + }) + it('no flags', function(done){ + const a = new RegExp('hmm'); + noFlags(a); + done(); + }) + it('all flags', function(done){ + const a = new RegExp('hello', 'misguy'); + allFlags(a); + done(); + }) + it('lastIndex', function(done) { + const a = new RegExp('hi', 'g'); + lastIndex(a); + done(); + }) + }) +}) + diff --git a/node_modules/rimraf/CHANGELOG.md b/node_modules/rimraf/CHANGELOG.md new file mode 100644 index 0000000..f116f14 --- /dev/null +++ b/node_modules/rimraf/CHANGELOG.md @@ -0,0 +1,65 @@ +# v3.0 + +- Add `--preserve-root` option to executable (default true) +- Drop support for Node.js below version 6 + +# v2.7 + +- Make `glob` an optional dependency + +# 2.6 + +- Retry on EBUSY on non-windows platforms as well +- Make `rimraf.sync` 10000% more reliable on Windows + +# 2.5 + +- Handle Windows EPERM when lstat-ing read-only dirs +- Add glob option to pass options to glob + +# 2.4 + +- Add EPERM to delay/retry loop +- Add `disableGlob` option + +# 2.3 + +- Make maxBusyTries and emfileWait configurable +- Handle weird SunOS unlink-dir issue +- Glob the CLI arg for better Windows support + +# 2.2 + +- Handle ENOENT properly on Windows +- Allow overriding fs methods +- Treat EPERM as indicative of non-empty dir +- Remove optional graceful-fs dep +- Consistently return null error instead of undefined on success +- win32: Treat ENOTEMPTY the same as EBUSY +- Add `rimraf` binary + +# 2.1 + +- Fix SunOS error code for a non-empty directory +- Try rmdir before readdir +- Treat EISDIR like EPERM +- Remove chmod +- Remove lstat polyfill, node 0.7 is not supported + +# 2.0 + +- Fix myGid call to check process.getgid +- Simplify the EBUSY backoff logic. +- Use fs.lstat in node >= 0.7.9 +- Remove gently option +- remove fiber implementation +- Delete files that are marked read-only + +# 1.0 + +- Allow ENOENT in sync method +- Throw when no callback is provided +- Make opts.gently an absolute path +- use 'stat' if 'lstat' is not available +- Consistent error naming, and rethrow non-ENOENT stat errors +- add fiber implementation diff --git a/node_modules/rimraf/LICENSE b/node_modules/rimraf/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/rimraf/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/rimraf/README.md b/node_modules/rimraf/README.md new file mode 100644 index 0000000..423b8cf --- /dev/null +++ b/node_modules/rimraf/README.md @@ -0,0 +1,101 @@ +[![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) + +The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. + +Install with `npm install rimraf`, or just drop rimraf.js somewhere. + +## API + +`rimraf(f, [opts], callback)` + +The first parameter will be interpreted as a globbing pattern for files. If you +want to disable globbing you can do so with `opts.disableGlob` (defaults to +`false`). This might be handy, for instance, if you have filenames that contain +globbing wildcard characters. + +The callback will be called with an error if there is one. Certain +errors are handled for you: + +* Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of + `opts.maxBusyTries` times before giving up, adding 100ms of wait + between each attempt. The default `maxBusyTries` is 3. +* `ENOENT` - If the file doesn't exist, rimraf will return + successfully, since your desired outcome is already the case. +* `EMFILE` - Since `readdir` requires opening a file descriptor, it's + possible to hit `EMFILE` if too many file descriptors are in use. + In the sync case, there's nothing to be done for this. But in the + async case, rimraf will gradually back off with timeouts up to + `opts.emfileWait` ms, which defaults to 1000. + +## options + +* unlink, chmod, stat, lstat, rmdir, readdir, + unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync + + In order to use a custom file system library, you can override + specific fs functions on the options object. + + If any of these functions are present on the options object, then + the supplied function will be used instead of the default fs + method. + + Sync methods are only relevant for `rimraf.sync()`, of course. + + For example: + + ```javascript + var myCustomFS = require('some-custom-fs') + + rimraf('some-thing', myCustomFS, callback) + ``` + +* maxBusyTries + + If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered + on Windows systems, then rimraf will retry with a linear backoff + wait of 100ms longer on each try. The default maxBusyTries is 3. + + Only relevant for async usage. + +* emfileWait + + If an `EMFILE` error is encountered, then rimraf will retry + repeatedly with a linear backoff of 1ms longer on each try, until + the timeout counter hits this max. The default limit is 1000. + + If you repeatedly encounter `EMFILE` errors, then consider using + [graceful-fs](http://npm.im/graceful-fs) in your program. + + Only relevant for async usage. + +* glob + + Set to `false` to disable [glob](http://npm.im/glob) pattern + matching. + + Set to an object to pass options to the glob module. The default + glob options are `{ nosort: true, silent: true }`. + + Glob version 6 is used in this module. + + Relevant for both sync and async usage. + +* disableGlob + + Set to any non-falsey value to disable globbing entirely. + (Equivalent to setting `glob: false`.) + +## rimraf.sync + +It can remove stuff synchronously, too. But that's not so good. Use +the async API. It's better. + +## CLI + +If installed with `npm install rimraf -g` it can be used as a global +command `rimraf [ ...]` which is useful for cross platform support. + +## mkdirp + +If you need to create a directory recursively, check out +[mkdirp](https://github.com/substack/node-mkdirp). diff --git a/node_modules/rimraf/bin.js b/node_modules/rimraf/bin.js new file mode 100644 index 0000000..023814c --- /dev/null +++ b/node_modules/rimraf/bin.js @@ -0,0 +1,68 @@ +#!/usr/bin/env node + +const rimraf = require('./') + +const path = require('path') + +const isRoot = arg => /^(\/|[a-zA-Z]:\\)$/.test(path.resolve(arg)) +const filterOutRoot = arg => { + const ok = preserveRoot === false || !isRoot(arg) + if (!ok) { + console.error(`refusing to remove ${arg}`) + console.error('Set --no-preserve-root to allow this') + } + return ok +} + +let help = false +let dashdash = false +let noglob = false +let preserveRoot = true +const args = process.argv.slice(2).filter(arg => { + if (dashdash) + return !!arg + else if (arg === '--') + dashdash = true + else if (arg === '--no-glob' || arg === '-G') + noglob = true + else if (arg === '--glob' || arg === '-g') + noglob = false + else if (arg.match(/^(-+|\/)(h(elp)?|\?)$/)) + help = true + else if (arg === '--preserve-root') + preserveRoot = true + else if (arg === '--no-preserve-root') + preserveRoot = false + else + return !!arg +}).filter(arg => !preserveRoot || filterOutRoot(arg)) + +const go = n => { + if (n >= args.length) + return + const options = noglob ? { glob: false } : {} + rimraf(args[n], options, er => { + if (er) + throw er + go(n+1) + }) +} + +if (help || args.length === 0) { + // If they didn't ask for help, then this is not a "success" + const log = help ? console.log : console.error + log('Usage: rimraf [ ...]') + log('') + log(' Deletes all files and folders at "path" recursively.') + log('') + log('Options:') + log('') + log(' -h, --help Display this usage info') + log(' -G, --no-glob Do not expand glob patterns in arguments') + log(' -g, --glob Expand glob patterns in arguments (default)') + log(' --preserve-root Do not remove \'/\' (default)') + log(' --no-preserve-root Do not treat \'/\' specially') + log(' -- Stop parsing flags') + process.exit(help ? 0 : 1) +} else + go(0) diff --git a/node_modules/rimraf/package.json b/node_modules/rimraf/package.json new file mode 100644 index 0000000..1bf8d5e --- /dev/null +++ b/node_modules/rimraf/package.json @@ -0,0 +1,32 @@ +{ + "name": "rimraf", + "version": "3.0.2", + "main": "rimraf.js", + "description": "A deep deletion module for node (like `rm -rf`)", + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "repository": "git://github.com/isaacs/rimraf.git", + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --follow-tags", + "test": "tap test/*.js" + }, + "bin": "./bin.js", + "dependencies": { + "glob": "^7.1.3" + }, + "files": [ + "LICENSE", + "README.md", + "bin.js", + "rimraf.js" + ], + "devDependencies": { + "mkdirp": "^0.5.1", + "tap": "^12.1.1" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } +} diff --git a/node_modules/rimraf/rimraf.js b/node_modules/rimraf/rimraf.js new file mode 100644 index 0000000..34da417 --- /dev/null +++ b/node_modules/rimraf/rimraf.js @@ -0,0 +1,360 @@ +const assert = require("assert") +const path = require("path") +const fs = require("fs") +let glob = undefined +try { + glob = require("glob") +} catch (_err) { + // treat glob as optional. +} + +const defaultGlobOpts = { + nosort: true, + silent: true +} + +// for EMFILE handling +let timeout = 0 + +const isWindows = (process.platform === "win32") + +const defaults = options => { + const methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ] + methods.forEach(m => { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) + + options.maxBusyTries = options.maxBusyTries || 3 + options.emfileWait = options.emfileWait || 1000 + if (options.glob === false) { + options.disableGlob = true + } + if (options.disableGlob !== true && glob === undefined) { + throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') + } + options.disableGlob = options.disableGlob || false + options.glob = options.glob || defaultGlobOpts +} + +const rimraf = (p, options, cb) => { + if (typeof options === 'function') { + cb = options + options = {} + } + + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert.equal(typeof cb, 'function', 'rimraf: callback function required') + assert(options, 'rimraf: invalid options argument provided') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + + defaults(options) + + let busyTries = 0 + let errState = null + let n = 0 + + const next = (er) => { + errState = errState || er + if (--n === 0) + cb(errState) + } + + const afterGlob = (er, results) => { + if (er) + return cb(er) + + n = results.length + if (n === 0) + return cb() + + results.forEach(p => { + const CB = (er) => { + if (er) { + if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && + busyTries < options.maxBusyTries) { + busyTries ++ + // try again, with the same exact callback as this one. + return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) + } + + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < options.emfileWait) { + return setTimeout(() => rimraf_(p, options, CB), timeout ++) + } + + // already gone + if (er.code === "ENOENT") er = null + } + + timeout = 0 + next(er) + } + rimraf_(p, options, CB) + }) + } + + if (options.disableGlob || !glob.hasMagic(p)) + return afterGlob(null, [p]) + + options.lstat(p, (er, stat) => { + if (!er) + return afterGlob(null, [p]) + + glob(p, options.glob, afterGlob) + }) + +} + +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +const rimraf_ = (p, options, cb) => { + assert(p) + assert(options) + assert(typeof cb === 'function') + + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, (er, st) => { + if (er && er.code === "ENOENT") + return cb(null) + + // Windows can EPERM on stat. Life is suffering. + if (er && er.code === "EPERM" && isWindows) + fixWinEPERM(p, options, er, cb) + + if (st && st.isDirectory()) + return rmdir(p, options, er, cb) + + options.unlink(p, er => { + if (er) { + if (er.code === "ENOENT") + return cb(null) + if (er.code === "EPERM") + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + if (er.code === "EISDIR") + return rmdir(p, options, er, cb) + } + return cb(er) + }) + }) +} + +const fixWinEPERM = (p, options, er, cb) => { + assert(p) + assert(options) + assert(typeof cb === 'function') + + options.chmod(p, 0o666, er2 => { + if (er2) + cb(er2.code === "ENOENT" ? null : er) + else + options.stat(p, (er3, stats) => { + if (er3) + cb(er3.code === "ENOENT" ? null : er) + else if (stats.isDirectory()) + rmdir(p, options, er, cb) + else + options.unlink(p, cb) + }) + }) +} + +const fixWinEPERMSync = (p, options, er) => { + assert(p) + assert(options) + + try { + options.chmodSync(p, 0o666) + } catch (er2) { + if (er2.code === "ENOENT") + return + else + throw er + } + + let stats + try { + stats = options.statSync(p) + } catch (er3) { + if (er3.code === "ENOENT") + return + else + throw er + } + + if (stats.isDirectory()) + rmdirSync(p, options, er) + else + options.unlinkSync(p) +} + +const rmdir = (p, options, originalEr, cb) => { + assert(p) + assert(options) + assert(typeof cb === 'function') + + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, er => { + if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) + rmkids(p, options, cb) + else if (er && er.code === "ENOTDIR") + cb(originalEr) + else + cb(er) + }) +} + +const rmkids = (p, options, cb) => { + assert(p) + assert(options) + assert(typeof cb === 'function') + + options.readdir(p, (er, files) => { + if (er) + return cb(er) + let n = files.length + if (n === 0) + return options.rmdir(p, cb) + let errState + files.forEach(f => { + rimraf(path.join(p, f), options, er => { + if (errState) + return + if (er) + return cb(errState = er) + if (--n === 0) + options.rmdir(p, cb) + }) + }) + }) +} + +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +const rimrafSync = (p, options) => { + options = options || {} + defaults(options) + + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + + let results + + if (options.disableGlob || !glob.hasMagic(p)) { + results = [p] + } else { + try { + options.lstatSync(p) + results = [p] + } catch (er) { + results = glob.sync(p, options.glob) + } + } + + if (!results.length) + return + + for (let i = 0; i < results.length; i++) { + const p = results[i] + + let st + try { + st = options.lstatSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + + // Windows can EPERM on stat. Life is suffering. + if (er.code === "EPERM" && isWindows) + fixWinEPERMSync(p, options, er) + } + + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) + rmdirSync(p, options, null) + else + options.unlinkSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "EPERM") + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + if (er.code !== "EISDIR") + throw er + + rmdirSync(p, options, er) + } + } +} + +const rmdirSync = (p, options, originalEr) => { + assert(p) + assert(options) + + try { + options.rmdirSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "ENOTDIR") + throw originalEr + if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") + rmkidsSync(p, options) + } +} + +const rmkidsSync = (p, options) => { + assert(p) + assert(options) + options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) + + // We only end up here once we got ENOTEMPTY at least once, and + // at this point, we are guaranteed to have removed all the kids. + // So, we know that it won't be ENOENT or ENOTDIR or anything else. + // try really hard to delete stuff on windows, because it has a + // PROFOUNDLY annoying habit of not closing handles promptly when + // files are deleted, resulting in spurious ENOTEMPTY errors. + const retries = isWindows ? 100 : 1 + let i = 0 + do { + let threw = true + try { + const ret = options.rmdirSync(p, options) + threw = false + return ret + } finally { + if (++i < retries && threw) + continue + } + } while (true) +} + +module.exports = rimraf +rimraf.sync = rimrafSync diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +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'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +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 to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that 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(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +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(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +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 to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` 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()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.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); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/safe-buffer/index.d.ts b/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): 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'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..22438da --- /dev/null +++ b/node_modules/safe-buffer/index.js @@ -0,0 +1,62 @@ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..623fbc3 --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,37 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.1.2", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + } +} diff --git a/node_modules/safer-buffer/LICENSE b/node_modules/safer-buffer/LICENSE new file mode 100644 index 0000000..4fe9e6f --- /dev/null +++ b/node_modules/safer-buffer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Nikita Skovoroda + +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/safer-buffer/Porting-Buffer.md b/node_modules/safer-buffer/Porting-Buffer.md new file mode 100644 index 0000000..68d86ba --- /dev/null +++ b/node_modules/safer-buffer/Porting-Buffer.md @@ -0,0 +1,268 @@ +# Porting to the Buffer.from/Buffer.alloc API + + +## Overview + +- [Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x.](#variant-1) (*recommended*) +- [Variant 2: Use a polyfill](#variant-2) +- [Variant 3: manual detection, with safeguards](#variant-3) + +### Finding problematic bits of code using grep + +Just run `grep -nrE '[^a-zA-Z](Slow)?Buffer\s*\(' --exclude-dir node_modules`. + +It will find all the potentially unsafe places in your own code (with some considerably unlikely +exceptions). + +### Finding problematic bits of code using Node.js 8 + +If you’re using Node.js ≥ 8.0.0 (which is recommended), Node.js exposes multiple options that help with finding the relevant pieces of code: + +- `--trace-warnings` will make Node.js show a stack trace for this warning and other warnings that are printed by Node.js. +- `--trace-deprecation` does the same thing, but only for deprecation warnings. +- `--pending-deprecation` will show more types of deprecation warnings. In particular, it will show the `Buffer()` deprecation warning, even on Node.js 8. + +You can set these flags using an environment variable: + +```console +$ export NODE_OPTIONS='--trace-warnings --pending-deprecation' +$ cat example.js +'use strict'; +const foo = new Buffer('foo'); +$ node example.js +(node:7147) [DEP0005] DeprecationWarning: The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead. + at showFlaggedDeprecation (buffer.js:127:13) + at new Buffer (buffer.js:148:3) + at Object. (/path/to/example.js:2:13) + [... more stack trace lines ...] +``` + +### Finding problematic bits of code using linters + +Eslint rules [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +also find calls to deprecated `Buffer()` API. Those rules are included in some pre-sets. + +There is a drawback, though, that it doesn't always +[work correctly](https://github.com/chalker/safer-buffer#why-not-safe-buffer) when `Buffer` is +overriden e.g. with a polyfill, so recommended is a combination of this and some other method +described above. + + +## Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x. + +This is the recommended solution nowadays that would imply only minimal overhead. + +The Node.js 5.x release line has been unsupported since July 2016, and the Node.js 4.x release line reaches its End of Life in April 2018 (→ [Schedule](https://github.com/nodejs/Release#release-schedule)). This means that these versions of Node.js will *not* receive any updates, even in case of security issues, so using these release lines should be avoided, if at all possible. + +What you would do in this case is to convert all `new Buffer()` or `Buffer()` calls to use `Buffer.alloc()` or `Buffer.from()`, in the following way: + +- For `new Buffer(number)`, replace it with `Buffer.alloc(number)`. +- For `new Buffer(string)` (or `new Buffer(string, encoding)`), replace it with `Buffer.from(string)` (or `Buffer.from(string, encoding)`). +- For all other combinations of arguments (these are much rarer), also replace `new Buffer(...arguments)` with `Buffer.from(...arguments)`. + +Note that `Buffer.alloc()` is also _faster_ on the current Node.js versions than +`new Buffer(size).fill(0)`, which is what you would otherwise need to ensure zero-filling. + +Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +is recommended to avoid accidential unsafe Buffer API usage. + +There is also a [JSCodeshift codemod](https://github.com/joyeecheung/node-dep-codemod#dep005) +for automatically migrating Buffer constructors to `Buffer.alloc()` or `Buffer.from()`. +Note that it currently only works with cases where the arguments are literals or where the +constructor is invoked with two arguments. + +_If you currently support those older Node.js versions and dropping them would be a semver-major change +for you, or if you support older branches of your packages, consider using [Variant 2](#variant-2) +or [Variant 3](#variant-3) on older branches, so people using those older branches will also receive +the fix. That way, you will eradicate potential issues caused by unguarded Buffer API usage and +your users will not observe a runtime deprecation warning when running your code on Node.js 10._ + + +## Variant 2: Use a polyfill + +Utilize [safer-buffer](https://www.npmjs.com/package/safer-buffer) as a polyfill to support older +Node.js versions. + +You would take exacly the same steps as in [Variant 1](#variant-1), but with a polyfill +`const Buffer = require('safer-buffer').Buffer` in all files where you use the new `Buffer` api. + +Make sure that you do not use old `new Buffer` API — in any files where the line above is added, +using old `new Buffer()` API will _throw_. It will be easy to notice that in CI, though. + +Alternatively, you could use [buffer-from](https://www.npmjs.com/package/buffer-from) and/or +[buffer-alloc](https://www.npmjs.com/package/buffer-alloc) [ponyfills](https://ponyfill.com/) — +those are great, the only downsides being 4 deps in the tree and slightly more code changes to +migrate off them (as you would be using e.g. `Buffer.from` under a different name). If you need only +`Buffer.from` polyfilled — `buffer-from` alone which comes with no extra dependencies. + +_Alternatively, you could use [safe-buffer](https://www.npmjs.com/package/safe-buffer) — it also +provides a polyfill, but takes a different approach which has +[it's drawbacks](https://github.com/chalker/safer-buffer#why-not-safe-buffer). It will allow you +to also use the older `new Buffer()` API in your code, though — but that's arguably a benefit, as +it is problematic, can cause issues in your code, and will start emitting runtime deprecation +warnings starting with Node.js 10._ + +Note that in either case, it is important that you also remove all calls to the old Buffer +API manually — just throwing in `safe-buffer` doesn't fix the problem by itself, it just provides +a polyfill for the new API. I have seen people doing that mistake. + +Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +is recommended. + +_Don't forget to drop the polyfill usage once you drop support for Node.js < 4.5.0._ + + +## Variant 3 — manual detection, with safeguards + +This is useful if you create Buffer instances in only a few places (e.g. one), or you have your own +wrapper around them. + +### Buffer(0) + +This special case for creating empty buffers can be safely replaced with `Buffer.concat([])`, which +returns the same result all the way down to Node.js 0.8.x. + +### Buffer(notNumber) + +Before: + +```js +var buf = new Buffer(notNumber, encoding); +``` + +After: + +```js +var buf; +if (Buffer.from && Buffer.from !== Uint8Array.from) { + buf = Buffer.from(notNumber, encoding); +} else { + if (typeof notNumber === 'number') + throw new Error('The "size" argument must be of type number.'); + buf = new Buffer(notNumber, encoding); +} +``` + +`encoding` is optional. + +Note that the `typeof notNumber` before `new Buffer` is required (for cases when `notNumber` argument is not +hard-coded) and _is not caused by the deprecation of Buffer constructor_ — it's exactly _why_ the +Buffer constructor is deprecated. Ecosystem packages lacking this type-check caused numereous +security issues — situations when unsanitized user input could end up in the `Buffer(arg)` create +problems ranging from DoS to leaking sensitive information to the attacker from the process memory. + +When `notNumber` argument is hardcoded (e.g. literal `"abc"` or `[0,1,2]`), the `typeof` check can +be omitted. + +Also note that using TypeScript does not fix this problem for you — when libs written in +`TypeScript` are used from JS, or when user input ends up there — it behaves exactly as pure JS, as +all type checks are translation-time only and are not present in the actual JS code which TS +compiles to. + +### Buffer(number) + +For Node.js 0.10.x (and below) support: + +```js +var buf; +if (Buffer.alloc) { + buf = Buffer.alloc(number); +} else { + buf = new Buffer(number); + buf.fill(0); +} +``` + +Otherwise (Node.js ≥ 0.12.x): + +```js +const buf = Buffer.alloc ? Buffer.alloc(number) : new Buffer(number).fill(0); +``` + +## Regarding Buffer.allocUnsafe + +Be extra cautious when using `Buffer.allocUnsafe`: + * Don't use it if you don't have a good reason to + * e.g. you probably won't ever see a performance difference for small buffers, in fact, those + might be even faster with `Buffer.alloc()`, + * if your code is not in the hot code path — you also probably won't notice a difference, + * keep in mind that zero-filling minimizes the potential risks. + * If you use it, make sure that you never return the buffer in a partially-filled state, + * if you are writing to it sequentially — always truncate it to the actuall written length + +Errors in handling buffers allocated with `Buffer.allocUnsafe` could result in various issues, +ranged from undefined behaviour of your code to sensitive data (user input, passwords, certs) +leaking to the remote attacker. + +_Note that the same applies to `new Buffer` usage without zero-filling, depending on the Node.js +version (and lacking type checks also adds DoS to the list of potential problems)._ + + +## FAQ + + +### What is wrong with the `Buffer` constructor? + +The `Buffer` constructor could be used to create a buffer in many different ways: + +- `new Buffer(42)` creates a `Buffer` of 42 bytes. Before Node.js 8, this buffer contained + *arbitrary memory* for performance reasons, which could include anything ranging from + program source code to passwords and encryption keys. +- `new Buffer('abc')` creates a `Buffer` that contains the UTF-8-encoded version of + the string `'abc'`. A second argument could specify another encoding: For example, + `new Buffer(string, 'base64')` could be used to convert a Base64 string into the original + sequence of bytes that it represents. +- There are several other combinations of arguments. + +This meant that, in code like `var buffer = new Buffer(foo);`, *it is not possible to tell +what exactly the contents of the generated buffer are* without knowing the type of `foo`. + +Sometimes, the value of `foo` comes from an external source. For example, this function +could be exposed as a service on a web server, converting a UTF-8 string into its Base64 form: + +``` +function stringToBase64(req, res) { + // The request body should have the format of `{ string: 'foobar' }` + const rawBytes = new Buffer(req.body.string) + const encoded = rawBytes.toString('base64') + res.end({ encoded: encoded }) +} +``` + +Note that this code does *not* validate the type of `req.body.string`: + +- `req.body.string` is expected to be a string. If this is the case, all goes well. +- `req.body.string` is controlled by the client that sends the request. +- If `req.body.string` is the *number* `50`, the `rawBytes` would be 50 bytes: + - Before Node.js 8, the content would be uninitialized + - After Node.js 8, the content would be `50` bytes with the value `0` + +Because of the missing type check, an attacker could intentionally send a number +as part of the request. Using this, they can either: + +- Read uninitialized memory. This **will** leak passwords, encryption keys and other + kinds of sensitive information. (Information leak) +- Force the program to allocate a large amount of memory. For example, when specifying + `500000000` as the input value, each request will allocate 500MB of memory. + This can be used to either exhaust the memory available of a program completely + and make it crash, or slow it down significantly. (Denial of Service) + +Both of these scenarios are considered serious security issues in a real-world +web server context. + +when using `Buffer.from(req.body.string)` instead, passing a number will always +throw an exception instead, giving a controlled behaviour that can always be +handled by the program. + + +### The `Buffer()` constructor has been deprecated for a while. Is this really an issue? + +Surveys of code in the `npm` ecosystem have shown that the `Buffer()` constructor is still +widely used. This includes new code, and overall usage of such code has actually been +*increasing*. diff --git a/node_modules/safer-buffer/Readme.md b/node_modules/safer-buffer/Readme.md new file mode 100644 index 0000000..14b0822 --- /dev/null +++ b/node_modules/safer-buffer/Readme.md @@ -0,0 +1,156 @@ +# safer-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![javascript style guide][standard-image]][standard-url] [![Security Responsible Disclosure][secuirty-image]][secuirty-url] + +[travis-image]: https://travis-ci.org/ChALkeR/safer-buffer.svg?branch=master +[travis-url]: https://travis-ci.org/ChALkeR/safer-buffer +[npm-image]: https://img.shields.io/npm/v/safer-buffer.svg +[npm-url]: https://npmjs.org/package/safer-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com +[secuirty-image]: https://img.shields.io/badge/Security-Responsible%20Disclosure-green.svg +[secuirty-url]: https://github.com/nodejs/security-wg/blob/master/processes/responsible_disclosure_template.md + +Modern Buffer API polyfill without footguns, working on Node.js from 0.8 to current. + +## How to use? + +First, port all `Buffer()` and `new Buffer()` calls to `Buffer.alloc()` and `Buffer.from()` API. + +Then, to achieve compatibility with outdated Node.js versions (`<4.5.0` and 5.x `<5.9.0`), use +`const Buffer = require('safer-buffer').Buffer` in all files where you make calls to the new +Buffer API. _Use `var` instead of `const` if you need that for your Node.js version range support._ + +Also, see the +[porting Buffer](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) guide. + +## Do I need it? + +Hopefully, not — dropping support for outdated Node.js versions should be fine nowdays, and that +is the recommended path forward. You _do_ need to port to the `Buffer.alloc()` and `Buffer.from()` +though. + +See the [porting guide](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) +for a better description. + +## Why not [safe-buffer](https://npmjs.com/safe-buffer)? + +_In short: while `safe-buffer` serves as a polyfill for the new API, it allows old API usage and +itself contains footguns._ + +`safe-buffer` could be used safely to get the new API while still keeping support for older +Node.js versions (like this module), but while analyzing ecosystem usage of the old Buffer API +I found out that `safe-buffer` is itself causing problems in some cases. + +For example, consider the following snippet: + +```console +$ cat example.unsafe.js +console.log(Buffer(20)) +$ ./node-v6.13.0-linux-x64/bin/node example.unsafe.js + +$ standard example.unsafe.js +standard: Use JavaScript Standard Style (https://standardjs.com) + /home/chalker/repo/safer-buffer/example.unsafe.js:2:13: 'Buffer()' was deprecated since v6. Use 'Buffer.alloc()' or 'Buffer.from()' (use 'https://www.npmjs.com/package/safe-buffer' for '<4.5.0') instead. +``` + +This is allocates and writes to console an uninitialized chunk of memory. +[standard](https://www.npmjs.com/package/standard) linter (among others) catch that and warn people +to avoid using unsafe API. + +Let's now throw in `safe-buffer`! + +```console +$ cat example.safe-buffer.js +const Buffer = require('safe-buffer').Buffer +console.log(Buffer(20)) +$ standard example.safe-buffer.js +$ ./node-v6.13.0-linux-x64/bin/node example.safe-buffer.js + +``` + +See the problem? Adding in `safe-buffer` _magically removes the lint warning_, but the behavior +remains identiсal to what we had before, and when launched on Node.js 6.x LTS — this dumps out +chunks of uninitialized memory. +_And this code will still emit runtime warnings on Node.js 10.x and above._ + +That was done by design. I first considered changing `safe-buffer`, prohibiting old API usage or +emitting warnings on it, but that significantly diverges from `safe-buffer` design. After some +discussion, it was decided to move my approach into a separate package, and _this is that separate +package_. + +This footgun is not imaginary — I observed top-downloaded packages doing that kind of thing, +«fixing» the lint warning by blindly including `safe-buffer` without any actual changes. + +Also in some cases, even if the API _was_ migrated to use of safe Buffer API — a random pull request +can bring unsafe Buffer API usage back to the codebase by adding new calls — and that could go +unnoticed even if you have a linter prohibiting that (becase of the reason stated above), and even +pass CI. _I also observed that being done in popular packages._ + +Some examples: + * [webdriverio](https://github.com/webdriverio/webdriverio/commit/05cbd3167c12e4930f09ef7cf93b127ba4effae4#diff-124380949022817b90b622871837d56cR31) + (a module with 548 759 downloads/month), + * [websocket-stream](https://github.com/maxogden/websocket-stream/commit/c9312bd24d08271687d76da0fe3c83493871cf61) + (218 288 d/m, fix in [maxogden/websocket-stream#142](https://github.com/maxogden/websocket-stream/pull/142)), + * [node-serialport](https://github.com/node-serialport/node-serialport/commit/e8d9d2b16c664224920ce1c895199b1ce2def48c) + (113 138 d/m, fix in [node-serialport/node-serialport#1510](https://github.com/node-serialport/node-serialport/pull/1510)), + * [karma](https://github.com/karma-runner/karma/commit/3d94b8cf18c695104ca195334dc75ff054c74eec) + (3 973 193 d/m, fix in [karma-runner/karma#2947](https://github.com/karma-runner/karma/pull/2947)), + * [spdy-transport](https://github.com/spdy-http2/spdy-transport/commit/5375ac33f4a62a4f65bcfc2827447d42a5dbe8b1) + (5 970 727 d/m, fix in [spdy-http2/spdy-transport#53](https://github.com/spdy-http2/spdy-transport/pull/53)). + * And there are a lot more over the ecosystem. + +I filed a PR at +[mysticatea/eslint-plugin-node#110](https://github.com/mysticatea/eslint-plugin-node/pull/110) to +partially fix that (for cases when that lint rule is used), but it is a semver-major change for +linter rules and presets, so it would take significant time for that to reach actual setups. +_It also hasn't been released yet (2018-03-20)._ + +Also, `safer-buffer` discourages the usage of `.allocUnsafe()`, which is often done by a mistake. +It still supports it with an explicit concern barier, by placing it under +`require('safer-buffer/dangereous')`. + +## But isn't throwing bad? + +Not really. It's an error that could be noticed and fixed early, instead of causing havoc later like +unguarded `new Buffer()` calls that end up receiving user input can do. + +This package affects only the files where `var Buffer = require('safer-buffer').Buffer` was done, so +it is really simple to keep track of things and make sure that you don't mix old API usage with that. +Also, CI should hint anything that you might have missed. + +New commits, if tested, won't land new usage of unsafe Buffer API this way. +_Node.js 10.x also deals with that by printing a runtime depecation warning._ + +### Would it affect third-party modules? + +No, unless you explicitly do an awful thing like monkey-patching or overriding the built-in `Buffer`. +Don't do that. + +### But I don't want throwing… + +That is also fine! + +Also, it could be better in some cases when you don't comprehensive enough test coverage. + +In that case — just don't override `Buffer` and use +`var SaferBuffer = require('safer-buffer').Buffer` instead. + +That way, everything using `Buffer` natively would still work, but there would be two drawbacks: + +* `Buffer.from`/`Buffer.alloc` won't be polyfilled — use `SaferBuffer.from` and + `SaferBuffer.alloc` instead. +* You are still open to accidentally using the insecure deprecated API — use a linter to catch that. + +Note that using a linter to catch accidential `Buffer` constructor usage in this case is strongly +recommended. `Buffer` is not overriden in this usecase, so linters won't get confused. + +## «Without footguns»? + +Well, it is still possible to do _some_ things with `Buffer` API, e.g. accessing `.buffer` property +on older versions and duping things from there. You shouldn't do that in your code, probabably. + +The intention is to remove the most significant footguns that affect lots of packages in the +ecosystem, and to do it in the proper way. + +Also, this package doesn't protect against security issues affecting some Node.js versions, so for +usage in your own production code, it is still recommended to update to a Node.js version +[supported by upstream](https://github.com/nodejs/release#release-schedule). diff --git a/node_modules/safer-buffer/dangerous.js b/node_modules/safer-buffer/dangerous.js new file mode 100644 index 0000000..ca41fdc --- /dev/null +++ b/node_modules/safer-buffer/dangerous.js @@ -0,0 +1,58 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var buffer = require('buffer') +var Buffer = buffer.Buffer +var safer = require('./safer.js') +var Safer = safer.Buffer + +var dangerous = {} + +var key + +for (key in safer) { + if (!safer.hasOwnProperty(key)) continue + dangerous[key] = safer[key] +} + +var Dangereous = dangerous.Buffer = {} + +// Copy Safer API +for (key in Safer) { + if (!Safer.hasOwnProperty(key)) continue + Dangereous[key] = Safer[key] +} + +// Copy those missing unsafe methods, if they are present +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (Dangereous.hasOwnProperty(key)) continue + Dangereous[key] = Buffer[key] +} + +if (!Dangereous.allocUnsafe) { + Dangereous.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + return Buffer(size) + } +} + +if (!Dangereous.allocUnsafeSlow) { + Dangereous.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + return buffer.SlowBuffer(size) + } +} + +module.exports = dangerous diff --git a/node_modules/safer-buffer/package.json b/node_modules/safer-buffer/package.json new file mode 100644 index 0000000..d452b04 --- /dev/null +++ b/node_modules/safer-buffer/package.json @@ -0,0 +1,34 @@ +{ + "name": "safer-buffer", + "version": "2.1.2", + "description": "Modern Buffer API polyfill without footguns", + "main": "safer.js", + "scripts": { + "browserify-test": "browserify --external tape tests.js > browserify-tests.js && tape browserify-tests.js", + "test": "standard && tape tests.js" + }, + "author": { + "name": "Nikita Skovoroda", + "email": "chalkerx@gmail.com", + "url": "https://github.com/ChALkeR" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ChALkeR/safer-buffer.git" + }, + "bugs": { + "url": "https://github.com/ChALkeR/safer-buffer/issues" + }, + "devDependencies": { + "standard": "^11.0.1", + "tape": "^4.9.0" + }, + "files": [ + "Porting-Buffer.md", + "Readme.md", + "tests.js", + "dangerous.js", + "safer.js" + ] +} diff --git a/node_modules/safer-buffer/safer.js b/node_modules/safer-buffer/safer.js new file mode 100644 index 0000000..37c7e1a --- /dev/null +++ b/node_modules/safer-buffer/safer.js @@ -0,0 +1,77 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var buffer = require('buffer') +var Buffer = buffer.Buffer + +var safer = {} + +var key + +for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue + if (key === 'SlowBuffer' || key === 'Buffer') continue + safer[key] = buffer[key] +} + +var Safer = safer.Buffer = {} +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue + Safer[key] = Buffer[key] +} + +safer.Buffer.prototype = Buffer.prototype + +if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) + } + if (value && typeof value.length === 'undefined') { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) + } + return Buffer(value, encodingOrOffset, length) + } +} + +if (!Safer.alloc) { + Safer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + var buf = Buffer(size) + if (!fill || fill.length === 0) { + buf.fill(0) + } else if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + return buf + } +} + +if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding('buffer').kStringMaxLength + } catch (e) { + // we can't determine kStringMaxLength in environments where process.binding + // is unsupported, so let's not set it + } +} + +if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + } + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + } +} + +module.exports = safer diff --git a/node_modules/safer-buffer/tests.js b/node_modules/safer-buffer/tests.js new file mode 100644 index 0000000..7ed2777 --- /dev/null +++ b/node_modules/safer-buffer/tests.js @@ -0,0 +1,406 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var test = require('tape') + +var buffer = require('buffer') + +var index = require('./') +var safer = require('./safer') +var dangerous = require('./dangerous') + +/* Inheritance tests */ + +test('Default is Safer', function (t) { + t.equal(index, safer) + t.notEqual(safer, dangerous) + t.notEqual(index, dangerous) + t.end() +}) + +test('Is not a function', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(typeof impl, 'object') + t.equal(typeof impl.Buffer, 'object') + }); + [buffer].forEach(function (impl) { + t.equal(typeof impl, 'object') + t.equal(typeof impl.Buffer, 'function') + }) + t.end() +}) + +test('Constructor throws', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.throws(function () { impl.Buffer() }) + t.throws(function () { impl.Buffer(0) }) + t.throws(function () { impl.Buffer('a') }) + t.throws(function () { impl.Buffer('a', 'utf-8') }) + t.throws(function () { return new impl.Buffer() }) + t.throws(function () { return new impl.Buffer(0) }) + t.throws(function () { return new impl.Buffer('a') }) + t.throws(function () { return new impl.Buffer('a', 'utf-8') }) + }) + t.end() +}) + +test('Safe methods exist', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(typeof impl.Buffer.alloc, 'function', 'alloc') + t.equal(typeof impl.Buffer.from, 'function', 'from') + }) + t.end() +}) + +test('Unsafe methods exist only in Dangerous', function (t) { + [index, safer].forEach(function (impl) { + t.equal(typeof impl.Buffer.allocUnsafe, 'undefined') + t.equal(typeof impl.Buffer.allocUnsafeSlow, 'undefined') + }); + [dangerous].forEach(function (impl) { + t.equal(typeof impl.Buffer.allocUnsafe, 'function') + t.equal(typeof impl.Buffer.allocUnsafeSlow, 'function') + }) + t.end() +}) + +test('Generic methods/properties are defined and equal', function (t) { + ['poolSize', 'isBuffer', 'concat', 'byteLength'].forEach(function (method) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], buffer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Built-in buffer static methods/properties are inherited', function (t) { + Object.keys(buffer).forEach(function (method) { + if (method === 'SlowBuffer' || method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], buffer[method], method) + t.notEqual(typeof impl[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Built-in Buffer static methods/properties are inherited', function (t) { + Object.keys(buffer.Buffer).forEach(function (method) { + if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], buffer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('.prototype property of Buffer is inherited', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.prototype, buffer.Buffer.prototype, 'prototype') + t.notEqual(typeof impl.Buffer.prototype, 'undefined', 'prototype') + }) + t.end() +}) + +test('All Safer methods are present in Dangerous', function (t) { + Object.keys(safer).forEach(function (method) { + if (method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], safer[method], method) + if (method !== 'kStringMaxLength') { + t.notEqual(typeof impl[method], 'undefined', method) + } + }) + }) + Object.keys(safer.Buffer).forEach(function (method) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], safer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Safe methods from Dangerous methods are present in Safer', function (t) { + Object.keys(dangerous).forEach(function (method) { + if (method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], dangerous[method], method) + if (method !== 'kStringMaxLength') { + t.notEqual(typeof impl[method], 'undefined', method) + } + }) + }) + Object.keys(dangerous.Buffer).forEach(function (method) { + if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], dangerous.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +/* Behaviour tests */ + +test('Methods return Buffers', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 10))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 'a'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10, 'x'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(9, 'ab'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(''))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string', 'utf-8'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([0, 42, 3]))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(new Uint8Array([0, 42, 3])))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([]))) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](0))) + t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](10))) + }) + t.end() +}) + +test('Constructor is buffer.Buffer', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.alloc(0).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(0, 10).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(0, 'a').constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(10).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(10, 'x').constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(9, 'ab').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('string').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('string', 'utf-8').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').constructor, buffer.Buffer) + t.equal(impl.Buffer.from([0, 42, 3]).constructor, buffer.Buffer) + t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).constructor, buffer.Buffer) + t.equal(impl.Buffer.from([]).constructor, buffer.Buffer) + }); + [0, 10, 100].forEach(function (arg) { + t.equal(dangerous.Buffer.allocUnsafe(arg).constructor, buffer.Buffer) + t.equal(dangerous.Buffer.allocUnsafeSlow(arg).constructor, buffer.SlowBuffer(0).constructor) + }) + t.end() +}) + +test('Invalid calls throw', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.throws(function () { impl.Buffer.from(0) }) + t.throws(function () { impl.Buffer.from(10) }) + t.throws(function () { impl.Buffer.from(10, 'utf-8') }) + t.throws(function () { impl.Buffer.from('string', 'invalid encoding') }) + t.throws(function () { impl.Buffer.from(-10) }) + t.throws(function () { impl.Buffer.from(1e90) }) + t.throws(function () { impl.Buffer.from(Infinity) }) + t.throws(function () { impl.Buffer.from(-Infinity) }) + t.throws(function () { impl.Buffer.from(NaN) }) + t.throws(function () { impl.Buffer.from(null) }) + t.throws(function () { impl.Buffer.from(undefined) }) + t.throws(function () { impl.Buffer.from() }) + t.throws(function () { impl.Buffer.from({}) }) + t.throws(function () { impl.Buffer.alloc('') }) + t.throws(function () { impl.Buffer.alloc('string') }) + t.throws(function () { impl.Buffer.alloc('string', 'utf-8') }) + t.throws(function () { impl.Buffer.alloc('b25ldHdvdGhyZWU=', 'base64') }) + t.throws(function () { impl.Buffer.alloc(-10) }) + t.throws(function () { impl.Buffer.alloc(1e90) }) + t.throws(function () { impl.Buffer.alloc(2 * (1 << 30)) }) + t.throws(function () { impl.Buffer.alloc(Infinity) }) + t.throws(function () { impl.Buffer.alloc(-Infinity) }) + t.throws(function () { impl.Buffer.alloc(null) }) + t.throws(function () { impl.Buffer.alloc(undefined) }) + t.throws(function () { impl.Buffer.alloc() }) + t.throws(function () { impl.Buffer.alloc([]) }) + t.throws(function () { impl.Buffer.alloc([0, 42, 3]) }) + t.throws(function () { impl.Buffer.alloc({}) }) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.throws(function () { dangerous.Buffer[method]('') }) + t.throws(function () { dangerous.Buffer[method]('string') }) + t.throws(function () { dangerous.Buffer[method]('string', 'utf-8') }) + t.throws(function () { dangerous.Buffer[method](2 * (1 << 30)) }) + t.throws(function () { dangerous.Buffer[method](Infinity) }) + if (dangerous.Buffer[method] === buffer.Buffer.allocUnsafe) { + t.skip('Skipping, older impl of allocUnsafe coerced negative sizes to 0') + } else { + t.throws(function () { dangerous.Buffer[method](-10) }) + t.throws(function () { dangerous.Buffer[method](-1e90) }) + t.throws(function () { dangerous.Buffer[method](-Infinity) }) + } + t.throws(function () { dangerous.Buffer[method](null) }) + t.throws(function () { dangerous.Buffer[method](undefined) }) + t.throws(function () { dangerous.Buffer[method]() }) + t.throws(function () { dangerous.Buffer[method]([]) }) + t.throws(function () { dangerous.Buffer[method]([0, 42, 3]) }) + t.throws(function () { dangerous.Buffer[method]({}) }) + }) + t.end() +}) + +test('Buffers have appropriate lengths', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.alloc(0).length, 0) + t.equal(impl.Buffer.alloc(10).length, 10) + t.equal(impl.Buffer.from('').length, 0) + t.equal(impl.Buffer.from('string').length, 6) + t.equal(impl.Buffer.from('string', 'utf-8').length, 6) + t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').length, 11) + t.equal(impl.Buffer.from([0, 42, 3]).length, 3) + t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).length, 3) + t.equal(impl.Buffer.from([]).length, 0) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.equal(dangerous.Buffer[method](0).length, 0) + t.equal(dangerous.Buffer[method](10).length, 10) + }) + t.end() +}) + +test('Buffers have appropriate lengths (2)', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true; + [ safer.Buffer.alloc, + dangerous.Buffer.allocUnsafe, + dangerous.Buffer.allocUnsafeSlow + ].forEach(function (method) { + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 1e5) + var buf = method(length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + } + }) + t.ok(ok) + t.end() +}) + +test('.alloc(size) is zero-filled and has correct length', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var buf = index.Buffer.alloc(length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + var j + for (j = 0; j < length; j++) { + if (buf[j] !== 0) ok = false + } + buf.fill(1) + for (j = 0; j < length; j++) { + if (buf[j] !== 1) ok = false + } + } + t.ok(ok) + t.end() +}) + +test('.allocUnsafe / .allocUnsafeSlow are fillable and have correct lengths', function (t) { + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var buf = dangerous.Buffer[method](length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + buf.fill(0, 0, length) + var j + for (j = 0; j < length; j++) { + if (buf[j] !== 0) ok = false + } + buf.fill(1, 0, length) + for (j = 0; j < length; j++) { + if (buf[j] !== 1) ok = false + } + } + t.ok(ok, method) + }) + t.end() +}) + +test('.alloc(size, fill) is `fill`-filled', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var fill = Math.round(Math.random() * 255) + var buf = index.Buffer.alloc(length, fill) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + for (var j = 0; j < length; j++) { + if (buf[j] !== fill) ok = false + } + } + t.ok(ok) + t.end() +}) + +test('.alloc(size, fill) is `fill`-filled', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var fill = Math.round(Math.random() * 255) + var buf = index.Buffer.alloc(length, fill) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + for (var j = 0; j < length; j++) { + if (buf[j] !== fill) ok = false + } + } + t.ok(ok) + t.deepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 97)) + t.notDeepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 98)) + + var tmp = new buffer.Buffer(2) + tmp.fill('ok') + if (tmp[1] === tmp[0]) { + // Outdated Node.js + t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('ooooo')) + } else { + t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('okoko')) + } + t.notDeepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('kokok')) + + t.end() +}) + +test('safer.Buffer.from returns results same as Buffer constructor', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.deepEqual(impl.Buffer.from(''), new buffer.Buffer('')) + t.deepEqual(impl.Buffer.from('string'), new buffer.Buffer('string')) + t.deepEqual(impl.Buffer.from('string', 'utf-8'), new buffer.Buffer('string', 'utf-8')) + t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), new buffer.Buffer('b25ldHdvdGhyZWU=', 'base64')) + t.deepEqual(impl.Buffer.from([0, 42, 3]), new buffer.Buffer([0, 42, 3])) + t.deepEqual(impl.Buffer.from(new Uint8Array([0, 42, 3])), new buffer.Buffer(new Uint8Array([0, 42, 3]))) + t.deepEqual(impl.Buffer.from([]), new buffer.Buffer([])) + }) + t.end() +}) + +test('safer.Buffer.from returns consistent results', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.deepEqual(impl.Buffer.from(''), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from([]), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from(new Uint8Array([])), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from('string', 'utf-8'), impl.Buffer.from('string')) + t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from([115, 116, 114, 105, 110, 103])) + t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from(impl.Buffer.from('string'))) + t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), impl.Buffer.from('onetwothree')) + t.notDeepEqual(impl.Buffer.from('b25ldHdvdGhyZWU='), impl.Buffer.from('onetwothree')) + }) + t.end() +}) diff --git a/node_modules/saslprep/.editorconfig b/node_modules/saslprep/.editorconfig new file mode 100644 index 0000000..d1d8a41 --- /dev/null +++ b/node_modules/saslprep/.editorconfig @@ -0,0 +1,10 @@ +# http://editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/node_modules/saslprep/.gitattributes b/node_modules/saslprep/.gitattributes new file mode 100644 index 0000000..3ba4536 --- /dev/null +++ b/node_modules/saslprep/.gitattributes @@ -0,0 +1 @@ +*.mem binary diff --git a/node_modules/saslprep/.travis.yml b/node_modules/saslprep/.travis.yml new file mode 100644 index 0000000..0bca826 --- /dev/null +++ b/node_modules/saslprep/.travis.yml @@ -0,0 +1,10 @@ +sudo: false +language: node_js +node_js: + - "6" + - "8" + - "10" + - "12" + +before_install: +- npm install -g npm@6 diff --git a/node_modules/saslprep/CHANGELOG.md b/node_modules/saslprep/CHANGELOG.md new file mode 100644 index 0000000..7798078 --- /dev/null +++ b/node_modules/saslprep/CHANGELOG.md @@ -0,0 +1,19 @@ +# Change Log +All notable changes to the "saslprep" package will be documented in this file. + +## [1.0.3] - 2019-05-01 + +- Correctly get code points >U+FFFF ([#5](https://github.com/reklatsmasters/saslprep/pull/5)) +- Fix perfomance downgrades from [#5](https://github.com/reklatsmasters/saslprep/pull/5). + +## [1.0.2] - 2018-09-13 + +- Reduced initialization time ([#3](https://github.com/reklatsmasters/saslprep/issues/3)) + +## [1.0.1] - 2018-06-20 + +- Reduced stack overhead of range creation ([#2](https://github.com/reklatsmasters/saslprep/pull/2)) + +## [1.0.0] - 2017-06-21 + +- First release diff --git a/node_modules/saslprep/LICENSE b/node_modules/saslprep/LICENSE new file mode 100644 index 0000000..481c7a5 --- /dev/null +++ b/node_modules/saslprep/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2014 Dmitry Tsvettsikh + +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. \ No newline at end of file diff --git a/node_modules/saslprep/code-points.mem b/node_modules/saslprep/code-points.mem new file mode 100644 index 0000000000000000000000000000000000000000..4781b066802688bdf954d2e89bcfac967db29c09 GIT binary patch literal 419864 zcmeI*O^9Si9RTop)4e+(t{DX(dsufSM8xBQfdsOo2lf&{@FWO&5cZ;Y@FWHe%nKV~ z@sxvzw;c53DIgdRk!c;t<{;##B4%51h#=^gL^8Y6+hx^z-92x{*9;3Umv`GA&vUy%enler!HTQKkA3&c=OSJMn7j|JGjl-d;Iey^#7>ZH0(RWYm^YJNA>kJ59aOu`p6X{MHRe9bu8cD2oYvN=9*ybv z%TyjdGTZ46aN&^<{xI6U)O2~U(!G+Yl0gPYRjbu8Wx~a<(#z+pIGvPkC#O7E&NgnV zIeue)&FW_ULfI&__U^^i@bTrer0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xb|Z>^W9wXR6Vl#j!mc_rtE>35?{Z6IbwcGK;>nSRoF zHt&;$O2P80zs-^hqp)?4qhw2`7#YP=_?Tw>wDeltgbe?$_^GM=@ z?HoDm9erzgM=HMNFC|BJRZD;X0RjXF5FkK+009C72oNAZfB*pk1PBlya0-DOe>pzY z-vZ3vILv9#>4l5=+gV#xaVim;YNYBg{{HIj=YJUg^!l*j-g~>b;hnpk&0)>Sr{)*n zj_ut&1&%HR2oRWKfn%Q^H4q>`fB*pk1PBlyK!5-N0t5&UAVA>E3Jm7>U0X{dK!5-N z0t5&U__zX7c= character.codePointAt(0); +const first = x => x[0]; +const last = x => x[x.length - 1]; + +/** + * Convert provided string into an array of Unicode Code Points. + * Based on https://stackoverflow.com/a/21409165/1556249 + * and https://www.npmjs.com/package/code-point-at. + * @param {string} input + * @returns {number[]} + */ +function toCodePoints(input) { + const codepoints = []; + const size = input.length; + + for (let i = 0; i < size; i += 1) { + const before = input.charCodeAt(i); + + if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { + const next = input.charCodeAt(i + 1); + + if (next >= 0xdc00 && next <= 0xdfff) { + codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); + i += 1; + continue; + } + } + + codepoints.push(before); + } + + return codepoints; +} + +/** + * SASLprep. + * @param {string} input + * @param {Object} opts + * @param {boolean} opts.allowUnassigned + * @returns {string} + */ +function saslprep(input, opts = {}) { + if (typeof input !== 'string') { + throw new TypeError('Expected string.'); + } + + if (input.length === 0) { + return ''; + } + + // 1. Map + const mapped_input = toCodePoints(input) + // 1.1 mapping to space + .map(character => (mapping2space.get(character) ? 0x20 : character)) + // 1.2 mapping to nothing + .filter(character => !mapping2nothing.get(character)); + + // 2. Normalize + const normalized_input = String.fromCodePoint + .apply(null, mapped_input) + .normalize('NFKC'); + + const normalized_map = toCodePoints(normalized_input); + + // 3. Prohibit + const hasProhibited = normalized_map.some(character => + prohibited_characters.get(character) + ); + + if (hasProhibited) { + throw new Error( + 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' + ); + } + + // Unassigned Code Points + if (opts.allowUnassigned !== true) { + const hasUnassigned = normalized_map.some(character => + unassigned_code_points.get(character) + ); + + if (hasUnassigned) { + throw new Error( + 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' + ); + } + } + + // 4. check bidi + + const hasBidiRAL = normalized_map.some(character => + bidirectional_r_al.get(character) + ); + + const hasBidiL = normalized_map.some(character => + bidirectional_l.get(character) + ); + + // 4.1 If a string contains any RandALCat character, the string MUST NOT + // contain any LCat character. + if (hasBidiRAL && hasBidiL) { + throw new Error( + 'String must not contain RandALCat and LCat at the same time,' + + ' see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + /** + * 4.2 If a string contains any RandALCat character, a RandALCat + * character MUST be the first character of the string, and a + * RandALCat character MUST be the last character of the string. + */ + + const isFirstBidiRAL = bidirectional_r_al.get( + getCodePoint(first(normalized_input)) + ); + const isLastBidiRAL = bidirectional_r_al.get( + getCodePoint(last(normalized_input)) + ); + + if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { + throw new Error( + 'Bidirectional RandALCat character must be the first and the last' + + ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + return normalized_input; +} diff --git a/node_modules/saslprep/lib/code-points.js b/node_modules/saslprep/lib/code-points.js new file mode 100644 index 0000000..222182c --- /dev/null +++ b/node_modules/saslprep/lib/code-points.js @@ -0,0 +1,996 @@ +'use strict'; + +const { range } = require('./util'); + +/** + * A.1 Unassigned code points in Unicode 3.2 + * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 + */ +const unassigned_code_points = new Set([ + 0x0221, + ...range(0x0234, 0x024f), + ...range(0x02ae, 0x02af), + ...range(0x02ef, 0x02ff), + ...range(0x0350, 0x035f), + ...range(0x0370, 0x0373), + ...range(0x0376, 0x0379), + ...range(0x037b, 0x037d), + ...range(0x037f, 0x0383), + 0x038b, + 0x038d, + 0x03a2, + 0x03cf, + ...range(0x03f7, 0x03ff), + 0x0487, + 0x04cf, + ...range(0x04f6, 0x04f7), + ...range(0x04fa, 0x04ff), + ...range(0x0510, 0x0530), + ...range(0x0557, 0x0558), + 0x0560, + 0x0588, + ...range(0x058b, 0x0590), + 0x05a2, + 0x05ba, + ...range(0x05c5, 0x05cf), + ...range(0x05eb, 0x05ef), + ...range(0x05f5, 0x060b), + ...range(0x060d, 0x061a), + ...range(0x061c, 0x061e), + 0x0620, + ...range(0x063b, 0x063f), + ...range(0x0656, 0x065f), + ...range(0x06ee, 0x06ef), + 0x06ff, + 0x070e, + ...range(0x072d, 0x072f), + ...range(0x074b, 0x077f), + ...range(0x07b2, 0x0900), + 0x0904, + ...range(0x093a, 0x093b), + ...range(0x094e, 0x094f), + ...range(0x0955, 0x0957), + ...range(0x0971, 0x0980), + 0x0984, + ...range(0x098d, 0x098e), + ...range(0x0991, 0x0992), + 0x09a9, + 0x09b1, + ...range(0x09b3, 0x09b5), + ...range(0x09ba, 0x09bb), + 0x09bd, + ...range(0x09c5, 0x09c6), + ...range(0x09c9, 0x09ca), + ...range(0x09ce, 0x09d6), + ...range(0x09d8, 0x09db), + 0x09de, + ...range(0x09e4, 0x09e5), + ...range(0x09fb, 0x0a01), + ...range(0x0a03, 0x0a04), + ...range(0x0a0b, 0x0a0e), + ...range(0x0a11, 0x0a12), + 0x0a29, + 0x0a31, + 0x0a34, + 0x0a37, + ...range(0x0a3a, 0x0a3b), + 0x0a3d, + ...range(0x0a43, 0x0a46), + ...range(0x0a49, 0x0a4a), + ...range(0x0a4e, 0x0a58), + 0x0a5d, + ...range(0x0a5f, 0x0a65), + ...range(0x0a75, 0x0a80), + 0x0a84, + 0x0a8c, + 0x0a8e, + 0x0a92, + 0x0aa9, + 0x0ab1, + 0x0ab4, + ...range(0x0aba, 0x0abb), + 0x0ac6, + 0x0aca, + ...range(0x0ace, 0x0acf), + ...range(0x0ad1, 0x0adf), + ...range(0x0ae1, 0x0ae5), + ...range(0x0af0, 0x0b00), + 0x0b04, + ...range(0x0b0d, 0x0b0e), + ...range(0x0b11, 0x0b12), + 0x0b29, + 0x0b31, + ...range(0x0b34, 0x0b35), + ...range(0x0b3a, 0x0b3b), + ...range(0x0b44, 0x0b46), + ...range(0x0b49, 0x0b4a), + ...range(0x0b4e, 0x0b55), + ...range(0x0b58, 0x0b5b), + 0x0b5e, + ...range(0x0b62, 0x0b65), + ...range(0x0b71, 0x0b81), + 0x0b84, + ...range(0x0b8b, 0x0b8d), + 0x0b91, + ...range(0x0b96, 0x0b98), + 0x0b9b, + 0x0b9d, + ...range(0x0ba0, 0x0ba2), + ...range(0x0ba5, 0x0ba7), + ...range(0x0bab, 0x0bad), + 0x0bb6, + ...range(0x0bba, 0x0bbd), + ...range(0x0bc3, 0x0bc5), + 0x0bc9, + ...range(0x0bce, 0x0bd6), + ...range(0x0bd8, 0x0be6), + ...range(0x0bf3, 0x0c00), + 0x0c04, + 0x0c0d, + 0x0c11, + 0x0c29, + 0x0c34, + ...range(0x0c3a, 0x0c3d), + 0x0c45, + 0x0c49, + ...range(0x0c4e, 0x0c54), + ...range(0x0c57, 0x0c5f), + ...range(0x0c62, 0x0c65), + ...range(0x0c70, 0x0c81), + 0x0c84, + 0x0c8d, + 0x0c91, + 0x0ca9, + 0x0cb4, + ...range(0x0cba, 0x0cbd), + 0x0cc5, + 0x0cc9, + ...range(0x0cce, 0x0cd4), + ...range(0x0cd7, 0x0cdd), + 0x0cdf, + ...range(0x0ce2, 0x0ce5), + ...range(0x0cf0, 0x0d01), + 0x0d04, + 0x0d0d, + 0x0d11, + 0x0d29, + ...range(0x0d3a, 0x0d3d), + ...range(0x0d44, 0x0d45), + 0x0d49, + ...range(0x0d4e, 0x0d56), + ...range(0x0d58, 0x0d5f), + ...range(0x0d62, 0x0d65), + ...range(0x0d70, 0x0d81), + 0x0d84, + ...range(0x0d97, 0x0d99), + 0x0db2, + 0x0dbc, + ...range(0x0dbe, 0x0dbf), + ...range(0x0dc7, 0x0dc9), + ...range(0x0dcb, 0x0dce), + 0x0dd5, + 0x0dd7, + ...range(0x0de0, 0x0df1), + ...range(0x0df5, 0x0e00), + ...range(0x0e3b, 0x0e3e), + ...range(0x0e5c, 0x0e80), + 0x0e83, + ...range(0x0e85, 0x0e86), + 0x0e89, + ...range(0x0e8b, 0x0e8c), + ...range(0x0e8e, 0x0e93), + 0x0e98, + 0x0ea0, + 0x0ea4, + 0x0ea6, + ...range(0x0ea8, 0x0ea9), + 0x0eac, + 0x0eba, + ...range(0x0ebe, 0x0ebf), + 0x0ec5, + 0x0ec7, + ...range(0x0ece, 0x0ecf), + ...range(0x0eda, 0x0edb), + ...range(0x0ede, 0x0eff), + 0x0f48, + ...range(0x0f6b, 0x0f70), + ...range(0x0f8c, 0x0f8f), + 0x0f98, + 0x0fbd, + ...range(0x0fcd, 0x0fce), + ...range(0x0fd0, 0x0fff), + 0x1022, + 0x1028, + 0x102b, + ...range(0x1033, 0x1035), + ...range(0x103a, 0x103f), + ...range(0x105a, 0x109f), + ...range(0x10c6, 0x10cf), + ...range(0x10f9, 0x10fa), + ...range(0x10fc, 0x10ff), + ...range(0x115a, 0x115e), + ...range(0x11a3, 0x11a7), + ...range(0x11fa, 0x11ff), + 0x1207, + 0x1247, + 0x1249, + ...range(0x124e, 0x124f), + 0x1257, + 0x1259, + ...range(0x125e, 0x125f), + 0x1287, + 0x1289, + ...range(0x128e, 0x128f), + 0x12af, + 0x12b1, + ...range(0x12b6, 0x12b7), + 0x12bf, + 0x12c1, + ...range(0x12c6, 0x12c7), + 0x12cf, + 0x12d7, + 0x12ef, + 0x130f, + 0x1311, + ...range(0x1316, 0x1317), + 0x131f, + 0x1347, + ...range(0x135b, 0x1360), + ...range(0x137d, 0x139f), + ...range(0x13f5, 0x1400), + ...range(0x1677, 0x167f), + ...range(0x169d, 0x169f), + ...range(0x16f1, 0x16ff), + 0x170d, + ...range(0x1715, 0x171f), + ...range(0x1737, 0x173f), + ...range(0x1754, 0x175f), + 0x176d, + 0x1771, + ...range(0x1774, 0x177f), + ...range(0x17dd, 0x17df), + ...range(0x17ea, 0x17ff), + 0x180f, + ...range(0x181a, 0x181f), + ...range(0x1878, 0x187f), + ...range(0x18aa, 0x1dff), + ...range(0x1e9c, 0x1e9f), + ...range(0x1efa, 0x1eff), + ...range(0x1f16, 0x1f17), + ...range(0x1f1e, 0x1f1f), + ...range(0x1f46, 0x1f47), + ...range(0x1f4e, 0x1f4f), + 0x1f58, + 0x1f5a, + 0x1f5c, + 0x1f5e, + ...range(0x1f7e, 0x1f7f), + 0x1fb5, + 0x1fc5, + ...range(0x1fd4, 0x1fd5), + 0x1fdc, + ...range(0x1ff0, 0x1ff1), + 0x1ff5, + 0x1fff, + ...range(0x2053, 0x2056), + ...range(0x2058, 0x205e), + ...range(0x2064, 0x2069), + ...range(0x2072, 0x2073), + ...range(0x208f, 0x209f), + ...range(0x20b2, 0x20cf), + ...range(0x20eb, 0x20ff), + ...range(0x213b, 0x213c), + ...range(0x214c, 0x2152), + ...range(0x2184, 0x218f), + ...range(0x23cf, 0x23ff), + ...range(0x2427, 0x243f), + ...range(0x244b, 0x245f), + 0x24ff, + ...range(0x2614, 0x2615), + 0x2618, + ...range(0x267e, 0x267f), + ...range(0x268a, 0x2700), + 0x2705, + ...range(0x270a, 0x270b), + 0x2728, + 0x274c, + 0x274e, + ...range(0x2753, 0x2755), + 0x2757, + ...range(0x275f, 0x2760), + ...range(0x2795, 0x2797), + 0x27b0, + ...range(0x27bf, 0x27cf), + ...range(0x27ec, 0x27ef), + ...range(0x2b00, 0x2e7f), + 0x2e9a, + ...range(0x2ef4, 0x2eff), + ...range(0x2fd6, 0x2fef), + ...range(0x2ffc, 0x2fff), + 0x3040, + ...range(0x3097, 0x3098), + ...range(0x3100, 0x3104), + ...range(0x312d, 0x3130), + 0x318f, + ...range(0x31b8, 0x31ef), + ...range(0x321d, 0x321f), + ...range(0x3244, 0x3250), + ...range(0x327c, 0x327e), + ...range(0x32cc, 0x32cf), + 0x32ff, + ...range(0x3377, 0x337a), + ...range(0x33de, 0x33df), + 0x33ff, + ...range(0x4db6, 0x4dff), + ...range(0x9fa6, 0x9fff), + ...range(0xa48d, 0xa48f), + ...range(0xa4c7, 0xabff), + ...range(0xd7a4, 0xd7ff), + ...range(0xfa2e, 0xfa2f), + ...range(0xfa6b, 0xfaff), + ...range(0xfb07, 0xfb12), + ...range(0xfb18, 0xfb1c), + 0xfb37, + 0xfb3d, + 0xfb3f, + 0xfb42, + 0xfb45, + ...range(0xfbb2, 0xfbd2), + ...range(0xfd40, 0xfd4f), + ...range(0xfd90, 0xfd91), + ...range(0xfdc8, 0xfdcf), + ...range(0xfdfd, 0xfdff), + ...range(0xfe10, 0xfe1f), + ...range(0xfe24, 0xfe2f), + ...range(0xfe47, 0xfe48), + 0xfe53, + 0xfe67, + ...range(0xfe6c, 0xfe6f), + 0xfe75, + ...range(0xfefd, 0xfefe), + 0xff00, + ...range(0xffbf, 0xffc1), + ...range(0xffc8, 0xffc9), + ...range(0xffd0, 0xffd1), + ...range(0xffd8, 0xffd9), + ...range(0xffdd, 0xffdf), + 0xffe7, + ...range(0xffef, 0xfff8), + ...range(0x10000, 0x102ff), + 0x1031f, + ...range(0x10324, 0x1032f), + ...range(0x1034b, 0x103ff), + ...range(0x10426, 0x10427), + ...range(0x1044e, 0x1cfff), + ...range(0x1d0f6, 0x1d0ff), + ...range(0x1d127, 0x1d129), + ...range(0x1d1de, 0x1d3ff), + 0x1d455, + 0x1d49d, + ...range(0x1d4a0, 0x1d4a1), + ...range(0x1d4a3, 0x1d4a4), + ...range(0x1d4a7, 0x1d4a8), + 0x1d4ad, + 0x1d4ba, + 0x1d4bc, + 0x1d4c1, + 0x1d4c4, + 0x1d506, + ...range(0x1d50b, 0x1d50c), + 0x1d515, + 0x1d51d, + 0x1d53a, + 0x1d53f, + 0x1d545, + ...range(0x1d547, 0x1d549), + 0x1d551, + ...range(0x1d6a4, 0x1d6a7), + ...range(0x1d7ca, 0x1d7cd), + ...range(0x1d800, 0x1fffd), + ...range(0x2a6d7, 0x2f7ff), + ...range(0x2fa1e, 0x2fffd), + ...range(0x30000, 0x3fffd), + ...range(0x40000, 0x4fffd), + ...range(0x50000, 0x5fffd), + ...range(0x60000, 0x6fffd), + ...range(0x70000, 0x7fffd), + ...range(0x80000, 0x8fffd), + ...range(0x90000, 0x9fffd), + ...range(0xa0000, 0xafffd), + ...range(0xb0000, 0xbfffd), + ...range(0xc0000, 0xcfffd), + ...range(0xd0000, 0xdfffd), + 0xe0000, + ...range(0xe0002, 0xe001f), + ...range(0xe0080, 0xefffd), +]); + +/** + * B.1 Commonly mapped to nothing + * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 + */ +const commonly_mapped_to_nothing = new Set([ + 0x00ad, + 0x034f, + 0x1806, + 0x180b, + 0x180c, + 0x180d, + 0x200b, + 0x200c, + 0x200d, + 0x2060, + 0xfe00, + 0xfe01, + 0xfe02, + 0xfe03, + 0xfe04, + 0xfe05, + 0xfe06, + 0xfe07, + 0xfe08, + 0xfe09, + 0xfe0a, + 0xfe0b, + 0xfe0c, + 0xfe0d, + 0xfe0e, + 0xfe0f, + 0xfeff, +]); + +/** + * C.1.2 Non-ASCII space characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 + */ +const non_ASCII_space_characters = new Set([ + 0x00a0 /* NO-BREAK SPACE */, + 0x1680 /* OGHAM SPACE MARK */, + 0x2000 /* EN QUAD */, + 0x2001 /* EM QUAD */, + 0x2002 /* EN SPACE */, + 0x2003 /* EM SPACE */, + 0x2004 /* THREE-PER-EM SPACE */, + 0x2005 /* FOUR-PER-EM SPACE */, + 0x2006 /* SIX-PER-EM SPACE */, + 0x2007 /* FIGURE SPACE */, + 0x2008 /* PUNCTUATION SPACE */, + 0x2009 /* THIN SPACE */, + 0x200a /* HAIR SPACE */, + 0x200b /* ZERO WIDTH SPACE */, + 0x202f /* NARROW NO-BREAK SPACE */, + 0x205f /* MEDIUM MATHEMATICAL SPACE */, + 0x3000 /* IDEOGRAPHIC SPACE */, +]); + +/** + * 2.3. Prohibited Output + * @type {Set} + */ +const prohibited_characters = new Set([ + ...non_ASCII_space_characters, + + /** + * C.2.1 ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 + */ + ...range(0, 0x001f) /* [CONTROL CHARACTERS] */, + 0x007f /* DELETE */, + + /** + * C.2.2 Non-ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 + */ + ...range(0x0080, 0x009f) /* [CONTROL CHARACTERS] */, + 0x06dd /* ARABIC END OF AYAH */, + 0x070f /* SYRIAC ABBREVIATION MARK */, + 0x180e /* MONGOLIAN VOWEL SEPARATOR */, + 0x200c /* ZERO WIDTH NON-JOINER */, + 0x200d /* ZERO WIDTH JOINER */, + 0x2028 /* LINE SEPARATOR */, + 0x2029 /* PARAGRAPH SEPARATOR */, + 0x2060 /* WORD JOINER */, + 0x2061 /* FUNCTION APPLICATION */, + 0x2062 /* INVISIBLE TIMES */, + 0x2063 /* INVISIBLE SEPARATOR */, + ...range(0x206a, 0x206f) /* [CONTROL CHARACTERS] */, + 0xfeff /* ZERO WIDTH NO-BREAK SPACE */, + ...range(0xfff9, 0xfffc) /* [CONTROL CHARACTERS] */, + ...range(0x1d173, 0x1d17a) /* [MUSICAL CONTROL CHARACTERS] */, + + /** + * C.3 Private use + * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 + */ + ...range(0xe000, 0xf8ff) /* [PRIVATE USE, PLANE 0] */, + ...range(0xf0000, 0xffffd) /* [PRIVATE USE, PLANE 15] */, + ...range(0x100000, 0x10fffd) /* [PRIVATE USE, PLANE 16] */, + + /** + * C.4 Non-character code points + * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 + */ + ...range(0xfdd0, 0xfdef) /* [NONCHARACTER CODE POINTS] */, + ...range(0xfffe, 0xffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x1fffe, 0x1ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x2fffe, 0x2ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x3fffe, 0x3ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x4fffe, 0x4ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x5fffe, 0x5ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x6fffe, 0x6ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x7fffe, 0x7ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x8fffe, 0x8ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x9fffe, 0x9ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xafffe, 0xaffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xbfffe, 0xbffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xcfffe, 0xcffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xdfffe, 0xdffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xefffe, 0xeffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x10fffe, 0x10ffff) /* [NONCHARACTER CODE POINTS] */, + + /** + * C.5 Surrogate codes + * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 + */ + ...range(0xd800, 0xdfff), + + /** + * C.6 Inappropriate for plain text + * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 + */ + 0xfff9 /* INTERLINEAR ANNOTATION ANCHOR */, + 0xfffa /* INTERLINEAR ANNOTATION SEPARATOR */, + 0xfffb /* INTERLINEAR ANNOTATION TERMINATOR */, + 0xfffc /* OBJECT REPLACEMENT CHARACTER */, + 0xfffd /* REPLACEMENT CHARACTER */, + + /** + * C.7 Inappropriate for canonical representation + * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 + */ + ...range(0x2ff0, 0x2ffb) /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */, + + /** + * C.8 Change display properties or are deprecated + * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 + */ + 0x0340 /* COMBINING GRAVE TONE MARK */, + 0x0341 /* COMBINING ACUTE TONE MARK */, + 0x200e /* LEFT-TO-RIGHT MARK */, + 0x200f /* RIGHT-TO-LEFT MARK */, + 0x202a /* LEFT-TO-RIGHT EMBEDDING */, + 0x202b /* RIGHT-TO-LEFT EMBEDDING */, + 0x202c /* POP DIRECTIONAL FORMATTING */, + 0x202d /* LEFT-TO-RIGHT OVERRIDE */, + 0x202e /* RIGHT-TO-LEFT OVERRIDE */, + 0x206a /* INHIBIT SYMMETRIC SWAPPING */, + 0x206b /* ACTIVATE SYMMETRIC SWAPPING */, + 0x206c /* INHIBIT ARABIC FORM SHAPING */, + 0x206d /* ACTIVATE ARABIC FORM SHAPING */, + 0x206e /* NATIONAL DIGIT SHAPES */, + 0x206f /* NOMINAL DIGIT SHAPES */, + + /** + * C.9 Tagging characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 + */ + 0xe0001 /* LANGUAGE TAG */, + ...range(0xe0020, 0xe007f) /* [TAGGING CHARACTERS] */, +]); + +/** + * D.1 Characters with bidirectional property "R" or "AL" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 + */ +const bidirectional_r_al = new Set([ + 0x05be, + 0x05c0, + 0x05c3, + ...range(0x05d0, 0x05ea), + ...range(0x05f0, 0x05f4), + 0x061b, + 0x061f, + ...range(0x0621, 0x063a), + ...range(0x0640, 0x064a), + ...range(0x066d, 0x066f), + ...range(0x0671, 0x06d5), + 0x06dd, + ...range(0x06e5, 0x06e6), + ...range(0x06fa, 0x06fe), + ...range(0x0700, 0x070d), + 0x0710, + ...range(0x0712, 0x072c), + ...range(0x0780, 0x07a5), + 0x07b1, + 0x200f, + 0xfb1d, + ...range(0xfb1f, 0xfb28), + ...range(0xfb2a, 0xfb36), + ...range(0xfb38, 0xfb3c), + 0xfb3e, + ...range(0xfb40, 0xfb41), + ...range(0xfb43, 0xfb44), + ...range(0xfb46, 0xfbb1), + ...range(0xfbd3, 0xfd3d), + ...range(0xfd50, 0xfd8f), + ...range(0xfd92, 0xfdc7), + ...range(0xfdf0, 0xfdfc), + ...range(0xfe70, 0xfe74), + ...range(0xfe76, 0xfefc), +]); + +/** + * D.2 Characters with bidirectional property "L" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 + */ +const bidirectional_l = new Set([ + ...range(0x0041, 0x005a), + ...range(0x0061, 0x007a), + 0x00aa, + 0x00b5, + 0x00ba, + ...range(0x00c0, 0x00d6), + ...range(0x00d8, 0x00f6), + ...range(0x00f8, 0x0220), + ...range(0x0222, 0x0233), + ...range(0x0250, 0x02ad), + ...range(0x02b0, 0x02b8), + ...range(0x02bb, 0x02c1), + ...range(0x02d0, 0x02d1), + ...range(0x02e0, 0x02e4), + 0x02ee, + 0x037a, + 0x0386, + ...range(0x0388, 0x038a), + 0x038c, + ...range(0x038e, 0x03a1), + ...range(0x03a3, 0x03ce), + ...range(0x03d0, 0x03f5), + ...range(0x0400, 0x0482), + ...range(0x048a, 0x04ce), + ...range(0x04d0, 0x04f5), + ...range(0x04f8, 0x04f9), + ...range(0x0500, 0x050f), + ...range(0x0531, 0x0556), + ...range(0x0559, 0x055f), + ...range(0x0561, 0x0587), + 0x0589, + 0x0903, + ...range(0x0905, 0x0939), + ...range(0x093d, 0x0940), + ...range(0x0949, 0x094c), + 0x0950, + ...range(0x0958, 0x0961), + ...range(0x0964, 0x0970), + ...range(0x0982, 0x0983), + ...range(0x0985, 0x098c), + ...range(0x098f, 0x0990), + ...range(0x0993, 0x09a8), + ...range(0x09aa, 0x09b0), + 0x09b2, + ...range(0x09b6, 0x09b9), + ...range(0x09be, 0x09c0), + ...range(0x09c7, 0x09c8), + ...range(0x09cb, 0x09cc), + 0x09d7, + ...range(0x09dc, 0x09dd), + ...range(0x09df, 0x09e1), + ...range(0x09e6, 0x09f1), + ...range(0x09f4, 0x09fa), + ...range(0x0a05, 0x0a0a), + ...range(0x0a0f, 0x0a10), + ...range(0x0a13, 0x0a28), + ...range(0x0a2a, 0x0a30), + ...range(0x0a32, 0x0a33), + ...range(0x0a35, 0x0a36), + ...range(0x0a38, 0x0a39), + ...range(0x0a3e, 0x0a40), + ...range(0x0a59, 0x0a5c), + 0x0a5e, + ...range(0x0a66, 0x0a6f), + ...range(0x0a72, 0x0a74), + 0x0a83, + ...range(0x0a85, 0x0a8b), + 0x0a8d, + ...range(0x0a8f, 0x0a91), + ...range(0x0a93, 0x0aa8), + ...range(0x0aaa, 0x0ab0), + ...range(0x0ab2, 0x0ab3), + ...range(0x0ab5, 0x0ab9), + ...range(0x0abd, 0x0ac0), + 0x0ac9, + ...range(0x0acb, 0x0acc), + 0x0ad0, + 0x0ae0, + ...range(0x0ae6, 0x0aef), + ...range(0x0b02, 0x0b03), + ...range(0x0b05, 0x0b0c), + ...range(0x0b0f, 0x0b10), + ...range(0x0b13, 0x0b28), + ...range(0x0b2a, 0x0b30), + ...range(0x0b32, 0x0b33), + ...range(0x0b36, 0x0b39), + ...range(0x0b3d, 0x0b3e), + 0x0b40, + ...range(0x0b47, 0x0b48), + ...range(0x0b4b, 0x0b4c), + 0x0b57, + ...range(0x0b5c, 0x0b5d), + ...range(0x0b5f, 0x0b61), + ...range(0x0b66, 0x0b70), + 0x0b83, + ...range(0x0b85, 0x0b8a), + ...range(0x0b8e, 0x0b90), + ...range(0x0b92, 0x0b95), + ...range(0x0b99, 0x0b9a), + 0x0b9c, + ...range(0x0b9e, 0x0b9f), + ...range(0x0ba3, 0x0ba4), + ...range(0x0ba8, 0x0baa), + ...range(0x0bae, 0x0bb5), + ...range(0x0bb7, 0x0bb9), + ...range(0x0bbe, 0x0bbf), + ...range(0x0bc1, 0x0bc2), + ...range(0x0bc6, 0x0bc8), + ...range(0x0bca, 0x0bcc), + 0x0bd7, + ...range(0x0be7, 0x0bf2), + ...range(0x0c01, 0x0c03), + ...range(0x0c05, 0x0c0c), + ...range(0x0c0e, 0x0c10), + ...range(0x0c12, 0x0c28), + ...range(0x0c2a, 0x0c33), + ...range(0x0c35, 0x0c39), + ...range(0x0c41, 0x0c44), + ...range(0x0c60, 0x0c61), + ...range(0x0c66, 0x0c6f), + ...range(0x0c82, 0x0c83), + ...range(0x0c85, 0x0c8c), + ...range(0x0c8e, 0x0c90), + ...range(0x0c92, 0x0ca8), + ...range(0x0caa, 0x0cb3), + ...range(0x0cb5, 0x0cb9), + 0x0cbe, + ...range(0x0cc0, 0x0cc4), + ...range(0x0cc7, 0x0cc8), + ...range(0x0cca, 0x0ccb), + ...range(0x0cd5, 0x0cd6), + 0x0cde, + ...range(0x0ce0, 0x0ce1), + ...range(0x0ce6, 0x0cef), + ...range(0x0d02, 0x0d03), + ...range(0x0d05, 0x0d0c), + ...range(0x0d0e, 0x0d10), + ...range(0x0d12, 0x0d28), + ...range(0x0d2a, 0x0d39), + ...range(0x0d3e, 0x0d40), + ...range(0x0d46, 0x0d48), + ...range(0x0d4a, 0x0d4c), + 0x0d57, + ...range(0x0d60, 0x0d61), + ...range(0x0d66, 0x0d6f), + ...range(0x0d82, 0x0d83), + ...range(0x0d85, 0x0d96), + ...range(0x0d9a, 0x0db1), + ...range(0x0db3, 0x0dbb), + 0x0dbd, + ...range(0x0dc0, 0x0dc6), + ...range(0x0dcf, 0x0dd1), + ...range(0x0dd8, 0x0ddf), + ...range(0x0df2, 0x0df4), + ...range(0x0e01, 0x0e30), + ...range(0x0e32, 0x0e33), + ...range(0x0e40, 0x0e46), + ...range(0x0e4f, 0x0e5b), + ...range(0x0e81, 0x0e82), + 0x0e84, + ...range(0x0e87, 0x0e88), + 0x0e8a, + 0x0e8d, + ...range(0x0e94, 0x0e97), + ...range(0x0e99, 0x0e9f), + ...range(0x0ea1, 0x0ea3), + 0x0ea5, + 0x0ea7, + ...range(0x0eaa, 0x0eab), + ...range(0x0ead, 0x0eb0), + ...range(0x0eb2, 0x0eb3), + 0x0ebd, + ...range(0x0ec0, 0x0ec4), + 0x0ec6, + ...range(0x0ed0, 0x0ed9), + ...range(0x0edc, 0x0edd), + ...range(0x0f00, 0x0f17), + ...range(0x0f1a, 0x0f34), + 0x0f36, + 0x0f38, + ...range(0x0f3e, 0x0f47), + ...range(0x0f49, 0x0f6a), + 0x0f7f, + 0x0f85, + ...range(0x0f88, 0x0f8b), + ...range(0x0fbe, 0x0fc5), + ...range(0x0fc7, 0x0fcc), + 0x0fcf, + ...range(0x1000, 0x1021), + ...range(0x1023, 0x1027), + ...range(0x1029, 0x102a), + 0x102c, + 0x1031, + 0x1038, + ...range(0x1040, 0x1057), + ...range(0x10a0, 0x10c5), + ...range(0x10d0, 0x10f8), + 0x10fb, + ...range(0x1100, 0x1159), + ...range(0x115f, 0x11a2), + ...range(0x11a8, 0x11f9), + ...range(0x1200, 0x1206), + ...range(0x1208, 0x1246), + 0x1248, + ...range(0x124a, 0x124d), + ...range(0x1250, 0x1256), + 0x1258, + ...range(0x125a, 0x125d), + ...range(0x1260, 0x1286), + 0x1288, + ...range(0x128a, 0x128d), + ...range(0x1290, 0x12ae), + 0x12b0, + ...range(0x12b2, 0x12b5), + ...range(0x12b8, 0x12be), + 0x12c0, + ...range(0x12c2, 0x12c5), + ...range(0x12c8, 0x12ce), + ...range(0x12d0, 0x12d6), + ...range(0x12d8, 0x12ee), + ...range(0x12f0, 0x130e), + 0x1310, + ...range(0x1312, 0x1315), + ...range(0x1318, 0x131e), + ...range(0x1320, 0x1346), + ...range(0x1348, 0x135a), + ...range(0x1361, 0x137c), + ...range(0x13a0, 0x13f4), + ...range(0x1401, 0x1676), + ...range(0x1681, 0x169a), + ...range(0x16a0, 0x16f0), + ...range(0x1700, 0x170c), + ...range(0x170e, 0x1711), + ...range(0x1720, 0x1731), + ...range(0x1735, 0x1736), + ...range(0x1740, 0x1751), + ...range(0x1760, 0x176c), + ...range(0x176e, 0x1770), + ...range(0x1780, 0x17b6), + ...range(0x17be, 0x17c5), + ...range(0x17c7, 0x17c8), + ...range(0x17d4, 0x17da), + 0x17dc, + ...range(0x17e0, 0x17e9), + ...range(0x1810, 0x1819), + ...range(0x1820, 0x1877), + ...range(0x1880, 0x18a8), + ...range(0x1e00, 0x1e9b), + ...range(0x1ea0, 0x1ef9), + ...range(0x1f00, 0x1f15), + ...range(0x1f18, 0x1f1d), + ...range(0x1f20, 0x1f45), + ...range(0x1f48, 0x1f4d), + ...range(0x1f50, 0x1f57), + 0x1f59, + 0x1f5b, + 0x1f5d, + ...range(0x1f5f, 0x1f7d), + ...range(0x1f80, 0x1fb4), + ...range(0x1fb6, 0x1fbc), + 0x1fbe, + ...range(0x1fc2, 0x1fc4), + ...range(0x1fc6, 0x1fcc), + ...range(0x1fd0, 0x1fd3), + ...range(0x1fd6, 0x1fdb), + ...range(0x1fe0, 0x1fec), + ...range(0x1ff2, 0x1ff4), + ...range(0x1ff6, 0x1ffc), + 0x200e, + 0x2071, + 0x207f, + 0x2102, + 0x2107, + ...range(0x210a, 0x2113), + 0x2115, + ...range(0x2119, 0x211d), + 0x2124, + 0x2126, + 0x2128, + ...range(0x212a, 0x212d), + ...range(0x212f, 0x2131), + ...range(0x2133, 0x2139), + ...range(0x213d, 0x213f), + ...range(0x2145, 0x2149), + ...range(0x2160, 0x2183), + ...range(0x2336, 0x237a), + 0x2395, + ...range(0x249c, 0x24e9), + ...range(0x3005, 0x3007), + ...range(0x3021, 0x3029), + ...range(0x3031, 0x3035), + ...range(0x3038, 0x303c), + ...range(0x3041, 0x3096), + ...range(0x309d, 0x309f), + ...range(0x30a1, 0x30fa), + ...range(0x30fc, 0x30ff), + ...range(0x3105, 0x312c), + ...range(0x3131, 0x318e), + ...range(0x3190, 0x31b7), + ...range(0x31f0, 0x321c), + ...range(0x3220, 0x3243), + ...range(0x3260, 0x327b), + ...range(0x327f, 0x32b0), + ...range(0x32c0, 0x32cb), + ...range(0x32d0, 0x32fe), + ...range(0x3300, 0x3376), + ...range(0x337b, 0x33dd), + ...range(0x33e0, 0x33fe), + ...range(0x3400, 0x4db5), + ...range(0x4e00, 0x9fa5), + ...range(0xa000, 0xa48c), + ...range(0xac00, 0xd7a3), + ...range(0xd800, 0xfa2d), + ...range(0xfa30, 0xfa6a), + ...range(0xfb00, 0xfb06), + ...range(0xfb13, 0xfb17), + ...range(0xff21, 0xff3a), + ...range(0xff41, 0xff5a), + ...range(0xff66, 0xffbe), + ...range(0xffc2, 0xffc7), + ...range(0xffca, 0xffcf), + ...range(0xffd2, 0xffd7), + ...range(0xffda, 0xffdc), + ...range(0x10300, 0x1031e), + ...range(0x10320, 0x10323), + ...range(0x10330, 0x1034a), + ...range(0x10400, 0x10425), + ...range(0x10428, 0x1044d), + ...range(0x1d000, 0x1d0f5), + ...range(0x1d100, 0x1d126), + ...range(0x1d12a, 0x1d166), + ...range(0x1d16a, 0x1d172), + ...range(0x1d183, 0x1d184), + ...range(0x1d18c, 0x1d1a9), + ...range(0x1d1ae, 0x1d1dd), + ...range(0x1d400, 0x1d454), + ...range(0x1d456, 0x1d49c), + ...range(0x1d49e, 0x1d49f), + 0x1d4a2, + ...range(0x1d4a5, 0x1d4a6), + ...range(0x1d4a9, 0x1d4ac), + ...range(0x1d4ae, 0x1d4b9), + 0x1d4bb, + ...range(0x1d4bd, 0x1d4c0), + ...range(0x1d4c2, 0x1d4c3), + ...range(0x1d4c5, 0x1d505), + ...range(0x1d507, 0x1d50a), + ...range(0x1d50d, 0x1d514), + ...range(0x1d516, 0x1d51c), + ...range(0x1d51e, 0x1d539), + ...range(0x1d53b, 0x1d53e), + ...range(0x1d540, 0x1d544), + 0x1d546, + ...range(0x1d54a, 0x1d550), + ...range(0x1d552, 0x1d6a3), + ...range(0x1d6a8, 0x1d7c9), + ...range(0x20000, 0x2a6d6), + ...range(0x2f800, 0x2fa1d), + ...range(0xf0000, 0xffffd), + ...range(0x100000, 0x10fffd), +]); + +module.exports = { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +}; diff --git a/node_modules/saslprep/lib/memory-code-points.js b/node_modules/saslprep/lib/memory-code-points.js new file mode 100644 index 0000000..cb0289c --- /dev/null +++ b/node_modules/saslprep/lib/memory-code-points.js @@ -0,0 +1,39 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const bitfield = require('sparse-bitfield'); + +/* eslint-disable-next-line security/detect-non-literal-fs-filename */ +const memory = fs.readFileSync(path.resolve(__dirname, '../code-points.mem')); +let offset = 0; + +/** + * Loads each code points sequence from buffer. + * @returns {bitfield} + */ +function read() { + const size = memory.readUInt32BE(offset); + offset += 4; + + const codepoints = memory.slice(offset, offset + size); + offset += size; + + return bitfield({ buffer: codepoints }); +} + +const unassigned_code_points = read(); +const commonly_mapped_to_nothing = read(); +const non_ASCII_space_characters = read(); +const prohibited_characters = read(); +const bidirectional_r_al = read(); +const bidirectional_l = read(); + +module.exports = { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +}; diff --git a/node_modules/saslprep/lib/util.js b/node_modules/saslprep/lib/util.js new file mode 100644 index 0000000..506bdc9 --- /dev/null +++ b/node_modules/saslprep/lib/util.js @@ -0,0 +1,21 @@ +'use strict'; + +/** + * Create an array of numbers. + * @param {number} from + * @param {number} to + * @returns {number[]} + */ +function range(from, to) { + // TODO: make this inlined. + const list = new Array(to - from + 1); + + for (let i = 0; i < list.length; i += 1) { + list[i] = from + i; + } + return list; +} + +module.exports = { + range, +}; diff --git a/node_modules/saslprep/package.json b/node_modules/saslprep/package.json new file mode 100644 index 0000000..23c3562 --- /dev/null +++ b/node_modules/saslprep/package.json @@ -0,0 +1,72 @@ +{ + "name": "saslprep", + "version": "1.0.3", + "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013.", + "main": "index.js", + "scripts": { + "test": "npm run lint && npm run unit-test", + "lint": "npx eslint --quiet .", + "unit-test": "npx jest", + "gen-code-points": "node generate-code-points.js > code-points.mem" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/reklatsmasters/saslprep.git" + }, + "keywords": [ + "sasl", + "saslprep", + "stringprep", + "rfc4013", + "4013" + ], + "author": "Dmitry Tsvettsikh ", + "license": "MIT", + "bugs": { + "url": "https://github.com/reklatsmasters/saslprep/issues" + }, + "engines": { + "node": ">=6" + }, + "homepage": "https://github.com/reklatsmasters/saslprep#readme", + "devDependencies": { + "@nodertc/eslint-config": "^0.2.1", + "eslint": "^5.16.0", + "jest": "^23.6.0", + "prettier": "^1.14.3" + }, + "dependencies": { + "sparse-bitfield": "^3.0.3" + }, + "eslintConfig": { + "extends": "@nodertc", + "rules": { + "camelcase": "off", + "no-continue": "off" + }, + "overrides": [ + { + "files": [ + "test/*.js" + ], + "env": { + "jest": true + }, + "rules": { + "require-jsdoc": "off" + } + } + ] + }, + "jest": { + "modulePaths": [ + "" + ], + "testMatch": [ + "**/test/*.js" + ], + "testPathIgnorePatterns": [ + "/node_modules/" + ] + } +} diff --git a/node_modules/saslprep/readme.md b/node_modules/saslprep/readme.md new file mode 100644 index 0000000..8ff3d70 --- /dev/null +++ b/node_modules/saslprep/readme.md @@ -0,0 +1,31 @@ +# saslprep +[![Build Status](https://travis-ci.org/reklatsmasters/saslprep.svg?branch=master)](https://travis-ci.org/reklatsmasters/saslprep) +[![npm](https://img.shields.io/npm/v/saslprep.svg)](https://npmjs.org/package/saslprep) +[![node](https://img.shields.io/node/v/saslprep.svg)](https://npmjs.org/package/saslprep) +[![license](https://img.shields.io/npm/l/saslprep.svg)](https://npmjs.org/package/saslprep) +[![downloads](https://img.shields.io/npm/dm/saslprep.svg)](https://npmjs.org/package/saslprep) + +Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013) + +### Usage + +```js +const saslprep = require('saslprep') + +saslprep('password\u00AD') // password +saslprep('password\u0007') // Error: prohibited character +``` + +### API + +##### `saslprep(input: String, opts: Options): String` + +Normalize user name or password. + +##### `Options.allowUnassigned: bool` + +A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default. + +## License + +MIT, 2017-2019 (c) Dmitriy Tsvettsikh diff --git a/node_modules/saslprep/test/index.js b/node_modules/saslprep/test/index.js new file mode 100644 index 0000000..80c71af --- /dev/null +++ b/node_modules/saslprep/test/index.js @@ -0,0 +1,76 @@ +'use strict'; + +const saslprep = require('..'); + +const chr = String.fromCodePoint; + +test('should work with liatin letters', () => { + const str = 'user'; + expect(saslprep(str)).toEqual(str); +}); + +test('should work be case preserved', () => { + const str = 'USER'; + expect(saslprep(str)).toEqual(str); +}); + +test('should work with high code points (> U+FFFF)', () => { + const str = '\uD83D\uDE00'; + expect(saslprep(str, { allowUnassigned: true })).toEqual(str); +}); + +test('should remove `mapped to nothing` characters', () => { + expect(saslprep('I\u00ADX')).toEqual('IX'); +}); + +test('should replace `Non-ASCII space characters` with space', () => { + expect(saslprep('a\u00A0b')).toEqual('a\u0020b'); +}); + +test('should normalize as NFKC', () => { + expect(saslprep('\u00AA')).toEqual('a'); + expect(saslprep('\u2168')).toEqual('IX'); +}); + +test('should throws when prohibited characters', () => { + // C.2.1 ASCII control characters + expect(() => saslprep('a\u007Fb')).toThrow(); + + // C.2.2 Non-ASCII control characters + expect(() => saslprep('a\u06DDb')).toThrow(); + + // C.3 Private use + expect(() => saslprep('a\uE000b')).toThrow(); + + // C.4 Non-character code points + expect(() => saslprep(`a${chr(0x1fffe)}b`)).toThrow(); + + // C.5 Surrogate codes + expect(() => saslprep('a\uD800b')).toThrow(); + + // C.6 Inappropriate for plain text + expect(() => saslprep('a\uFFF9b')).toThrow(); + + // C.7 Inappropriate for canonical representation + expect(() => saslprep('a\u2FF0b')).toThrow(); + + // C.8 Change display properties or are deprecated + expect(() => saslprep('a\u200Eb')).toThrow(); + + // C.9 Tagging characters + expect(() => saslprep(`a${chr(0xe0001)}b`)).toThrow(); +}); + +test('should not containt RandALCat and LCat bidi', () => { + expect(() => saslprep('a\u06DD\u00AAb')).toThrow(); +}); + +test('RandALCat should be first and last', () => { + expect(() => saslprep('\u0627\u0031\u0628')).not.toThrow(); + expect(() => saslprep('\u0627\u0031')).toThrow(); +}); + +test('should handle unassigned code points', () => { + expect(() => saslprep('a\u0487')).toThrow(); + expect(() => saslprep('a\u0487', { allowUnassigned: true })).not.toThrow(); +}); diff --git a/node_modules/saslprep/test/util.js b/node_modules/saslprep/test/util.js new file mode 100644 index 0000000..355db3f --- /dev/null +++ b/node_modules/saslprep/test/util.js @@ -0,0 +1,16 @@ +'use strict'; + +const { setFlagsFromString } = require('v8'); +const { range } = require('../lib/util'); + +// 984 by default. +setFlagsFromString('--stack_size=500'); + +test('should work', () => { + const list = range(1, 3); + expect(list).toEqual([1, 2, 3]); +}); + +test('should work for large ranges', () => { + expect(() => range(1, 1e6)).not.toThrow(); +}); diff --git a/node_modules/semver/CHANGELOG.md b/node_modules/semver/CHANGELOG.md new file mode 100644 index 0000000..220af17 --- /dev/null +++ b/node_modules/semver/CHANGELOG.md @@ -0,0 +1,111 @@ +# changes log + +## 7.3.0 + +* Add `subset(r1, r2)` method to determine if `r1` range is entirely + contained by `r2` range. + +## 7.2.3 + +* Fix handling of `includePrelease` mode where version ranges like `1.0.0 - + 2.0.0` would include `3.0.0-pre` and not `1.0.0-pre`. + +## 7.2.2 + +* Fix bug where `2.0.0-pre` would be included in `^1.0.0` if + `includePrerelease` was set to true. + +## 7.2.0 + +* Add `simplifyRange` method to attempt to generate a more human-readable + range expression that is equivalent to a supplied range, for a given set + of versions. + +## 7.1.2 + +* Remove fancy lazy-loading logic, as it was causing problems for webpack + users. + +## 7.1.0 + +* Add `require('semver/preload')` to load the entire module without using + lazy getter methods. + +## 7.0.0 + +* Refactor module into separate files for better tree-shaking +* Drop support for very old node versions, use const/let, `=>` functions, + and classes. + +## 6.3.0 + +* Expose the token enum on the exports + +## 6.2.0 + +* Coerce numbers to strings when passed to semver.coerce() +* Add `rtl` option to coerce from right to left + +## 6.1.3 + +* Handle X-ranges properly in includePrerelease mode + +## 6.1.2 + +* Do not throw when testing invalid version strings + +## 6.1.1 + +* Add options support for semver.coerce() +* Handle undefined version passed to Range.test + +## 6.1.0 + +* Add semver.compareBuild function +* Support `*` in semver.intersects + +## 6.0 + +* Fix `intersects` logic. + + This is technically a bug fix, but since it is also a change to behavior + that may require users updating their code, it is marked as a major + version increment. + +## 5.7 + +* Add `minVersion` method + +## 5.6 + +* Move boolean `loose` param to an options object, with + backwards-compatibility protection. +* Add ability to opt out of special prerelease version handling with + the `includePrerelease` option flag. + +## 5.5 + +* Add version coercion capabilities + +## 5.4 + +* Add intersection checking + +## 5.3 + +* Add `minSatisfying` method + +## 5.2 + +* Add `prerelease(v)` that returns prerelease components + +## 5.1 + +* Add Backus-Naur for ranges +* Remove excessively cute inspection methods + +## 5.0 + +* Remove AMD/Browserified build artifacts +* Fix ltr and gtr when using the `*` range +* Fix for range `*` with a prerelease identifier diff --git a/node_modules/semver/LICENSE b/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/semver/README.md b/node_modules/semver/README.md new file mode 100644 index 0000000..9bef045 --- /dev/null +++ b/node_modules/semver/README.md @@ -0,0 +1,566 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +You can also just load the module for the function that you care about, if +you'd like to minimize your footprint. + +```js +// load the whole API at once in a single object +const semver = require('semver') + +// or just load the bits you need +// all of them listed here, just pick and choose what you want + +// classes +const SemVer = require('semver/classes/semver') +const Comparator = require('semver/classes/comparator') +const Range = require('semver/classes/range') + +// functions for working with versions +const semverParse = require('semver/functions/parse') +const semverValid = require('semver/functions/valid') +const semverClean = require('semver/functions/clean') +const semverInc = require('semver/functions/inc') +const semverDiff = require('semver/functions/diff') +const semverMajor = require('semver/functions/major') +const semverMinor = require('semver/functions/minor') +const semverPatch = require('semver/functions/patch') +const semverPrerelease = require('semver/functions/prerelease') +const semverCompare = require('semver/functions/compare') +const semverRcompare = require('semver/functions/rcompare') +const semverCompareLoose = require('semver/functions/compare-loose') +const semverCompareBuild = require('semver/functions/compare-build') +const semverSort = require('semver/functions/sort') +const semverRsort = require('semver/functions/rsort') + +// low-level comparators between versions +const semverGt = require('semver/functions/gt') +const semverLt = require('semver/functions/lt') +const semverEq = require('semver/functions/eq') +const semverNeq = require('semver/functions/neq') +const semverGte = require('semver/functions/gte') +const semverLte = require('semver/functions/lte') +const semverCmp = require('semver/functions/cmp') +const semverCoerce = require('semver/functions/coerce') + +// working with ranges +const semverSatisfies = require('semver/functions/satisfies') +const semverMaxSatisfying = require('semver/ranges/max-satisfying') +const semverMinSatisfying = require('semver/ranges/min-satisfying') +const semverToComparators = require('semver/ranges/to-comparators') +const semverMinVersion = require('semver/ranges/min-version') +const semverValidRange = require('semver/ranges/valid') +const semverOutside = require('semver/ranges/outside') +const semverGtr = require('semver/ranges/gtr') +const semverLtr = require('semver/ranges/ltr') +const semverIntersects = require('semver/ranges/intersects') +const simplifyRange = require('semver/ranges/simplify') +const rangeSubset = require('semver/ranges/subset') +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0-0` +* `^0.2.3` := `>=0.2.3 <0.3.0-0` +* `^0.0.3` := `>=0.0.3 <0.0.4-0` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0-0` +* `^0.0.x` := `>=0.0.0 <0.1.0-0` +* `^0.0` := `>=0.0.0 <0.1.0-0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0-0` +* `^0.x` := `>=0.0.0 <1.0.0-0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect +* `simplifyRange(versions, range)`: Return a "simplified" range that + matches the same items in `versions` list as the range specified. Note + that it does *not* guarantee that it would match the same versions in all + cases, only for the set of versions provided. This is useful when + generating ranges by joining together multiple versions with `||` + programmatically, to provide the user with something a bit more + ergonomic. If the provided range is shorter in string-length than the + generated range, then that is returned. +* `subset(subRange, superRange)`: Return `true` if the `subRange` range is + entirely contained by the `superRange` range. + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided +version is not valid a null will be returned. This does not work for +ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `2.1.5` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` + +## Exported Modules + + + +You may pull in just the part of this semver utility that you need, if you +are sensitive to packing and tree-shaking concerns. The main +`require('semver')` export uses getter functions to lazily load the parts +of the API that are used. + +The following modules are available: + +* `require('semver')` +* `require('semver/classes')` +* `require('semver/classes/comparator')` +* `require('semver/classes/range')` +* `require('semver/classes/semver')` +* `require('semver/functions/clean')` +* `require('semver/functions/cmp')` +* `require('semver/functions/coerce')` +* `require('semver/functions/compare')` +* `require('semver/functions/compare-build')` +* `require('semver/functions/compare-loose')` +* `require('semver/functions/diff')` +* `require('semver/functions/eq')` +* `require('semver/functions/gt')` +* `require('semver/functions/gte')` +* `require('semver/functions/inc')` +* `require('semver/functions/lt')` +* `require('semver/functions/lte')` +* `require('semver/functions/major')` +* `require('semver/functions/minor')` +* `require('semver/functions/neq')` +* `require('semver/functions/parse')` +* `require('semver/functions/patch')` +* `require('semver/functions/prerelease')` +* `require('semver/functions/rcompare')` +* `require('semver/functions/rsort')` +* `require('semver/functions/satisfies')` +* `require('semver/functions/sort')` +* `require('semver/functions/valid')` +* `require('semver/ranges/gtr')` +* `require('semver/ranges/intersects')` +* `require('semver/ranges/ltr')` +* `require('semver/ranges/max-satisfying')` +* `require('semver/ranges/min-satisfying')` +* `require('semver/ranges/min-version')` +* `require('semver/ranges/outside')` +* `require('semver/ranges/to-comparators')` +* `require('semver/ranges/valid')` diff --git a/node_modules/semver/bin/semver.js b/node_modules/semver/bin/semver.js new file mode 100644 index 0000000..73fe295 --- /dev/null +++ b/node_modules/semver/bin/semver.js @@ -0,0 +1,173 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +const argv = process.argv.slice(2) + +let versions = [] + +const range = [] + +let inc = null + +const version = require('../package.json').version + +let loose = false + +let includePrerelease = false + +let coerce = false + +let rtl = false + +let identifier + +const semver = require('../') + +let reverse = false + +const options = {} + +const main = () => { + if (!argv.length) return help() + while (argv.length) { + let a = argv.shift() + const indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + const options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl } + + versions = versions.map((v) => { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter((v) => { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (let i = 0, l = range.length; i < l; i++) { + versions = versions.filter((v) => { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + + +const failInc = () => { + console.error('--inc can only be used on a single version with no range') + fail() +} + +const fail = () => process.exit(1) + +const success = () => { + const compare = reverse ? 'rcompare' : 'compare' + versions.sort((a, b) => { + return semver[compare](a, b, options) + }).map((v) => { + return semver.clean(v, options) + }).map((v) => { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach((v, i, _) => { console.log(v) }) +} + +const help = () => console.log( +`SemVer ${version} + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them.`) + +main() diff --git a/node_modules/semver/classes/comparator.js b/node_modules/semver/classes/comparator.js new file mode 100644 index 0000000..dbbef2d --- /dev/null +++ b/node_modules/semver/classes/comparator.js @@ -0,0 +1,135 @@ +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + const sameSemVer = this.semver.version === comp.semver.version + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<') + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>') + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } +} + +module.exports = Comparator + +const parseOptions = require('../internal/parse-options') +const {re, t} = require('../internal/re') +const cmp = require('../functions/cmp') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const Range = require('./range') diff --git a/node_modules/semver/classes/index.js b/node_modules/semver/classes/index.js new file mode 100644 index 0000000..198b84d --- /dev/null +++ b/node_modules/semver/classes/index.js @@ -0,0 +1,5 @@ +module.exports = { + SemVer: require('./semver.js'), + Range: require('./range.js'), + Comparator: require('./comparator.js') +} diff --git a/node_modules/semver/classes/range.js b/node_modules/semver/classes/range.js new file mode 100644 index 0000000..aa04f6b --- /dev/null +++ b/node_modules/semver/classes/range.js @@ -0,0 +1,510 @@ +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.format() + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) + this.set = [first] + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } + + this.format() + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim() + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim() + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(',') + const memoKey = `parseRange:${memoOpts}:${range}` + const cached = cache.get(memoKey) + if (cached) + return cached + + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[t.COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator(comp, this.options)) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const l = rangeList.length + const rangeMap = new Map() + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete('') + + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} +module.exports = Range + +const LRU = require('lru-cache') +const cache = new LRU({ max: 1000 }) + +const parseOptions = require('../internal/parse-options') +const Comparator = require('./comparator') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const { + re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace +} = require('../internal/re') + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' ') + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' ') + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') + pr = '-0' + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp.trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } + + return (`${from} ${to}`).trim() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} diff --git a/node_modules/semver/classes/semver.js b/node_modules/semver/classes/semver.js new file mode 100644 index 0000000..ed81a7e --- /dev/null +++ b/node_modules/semver/classes/semver.js @@ -0,0 +1,287 @@ +const debug = require('../internal/debug') +const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') +const { re, t } = require('../internal/re') + +const parseOptions = require('../internal/parse-options') +const { compareIdentifiers } = require('../internal/identifiers') +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.format() + this.raw = this.version + return this + } +} + +module.exports = SemVer diff --git a/node_modules/semver/functions/clean.js b/node_modules/semver/functions/clean.js new file mode 100644 index 0000000..811fe6b --- /dev/null +++ b/node_modules/semver/functions/clean.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean diff --git a/node_modules/semver/functions/cmp.js b/node_modules/semver/functions/cmp.js new file mode 100644 index 0000000..3b89db7 --- /dev/null +++ b/node_modules/semver/functions/cmp.js @@ -0,0 +1,48 @@ +const eq = require('./eq') +const neq = require('./neq') +const gt = require('./gt') +const gte = require('./gte') +const lt = require('./lt') +const lte = require('./lte') + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp diff --git a/node_modules/semver/functions/coerce.js b/node_modules/semver/functions/coerce.js new file mode 100644 index 0000000..106ca71 --- /dev/null +++ b/node_modules/semver/functions/coerce.js @@ -0,0 +1,51 @@ +const SemVer = require('../classes/semver') +const parse = require('./parse') +const {re, t} = require('../internal/re') + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next + while ((next = re[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + re[t.COERCERTL].lastIndex = -1 + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) +} +module.exports = coerce diff --git a/node_modules/semver/functions/compare-build.js b/node_modules/semver/functions/compare-build.js new file mode 100644 index 0000000..9eb881b --- /dev/null +++ b/node_modules/semver/functions/compare-build.js @@ -0,0 +1,7 @@ +const SemVer = require('../classes/semver') +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild diff --git a/node_modules/semver/functions/compare-loose.js b/node_modules/semver/functions/compare-loose.js new file mode 100644 index 0000000..4881fbe --- /dev/null +++ b/node_modules/semver/functions/compare-loose.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose diff --git a/node_modules/semver/functions/compare.js b/node_modules/semver/functions/compare.js new file mode 100644 index 0000000..748b7af --- /dev/null +++ b/node_modules/semver/functions/compare.js @@ -0,0 +1,5 @@ +const SemVer = require('../classes/semver') +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare diff --git a/node_modules/semver/functions/diff.js b/node_modules/semver/functions/diff.js new file mode 100644 index 0000000..87200ef --- /dev/null +++ b/node_modules/semver/functions/diff.js @@ -0,0 +1,23 @@ +const parse = require('./parse') +const eq = require('./eq') + +const diff = (version1, version2) => { + if (eq(version1, version2)) { + return null + } else { + const v1 = parse(version1) + const v2 = parse(version2) + const hasPre = v1.prerelease.length || v2.prerelease.length + const prefix = hasPre ? 'pre' : '' + const defaultResult = hasPre ? 'prerelease' : '' + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} +module.exports = diff diff --git a/node_modules/semver/functions/eq.js b/node_modules/semver/functions/eq.js new file mode 100644 index 0000000..271fed9 --- /dev/null +++ b/node_modules/semver/functions/eq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq diff --git a/node_modules/semver/functions/gt.js b/node_modules/semver/functions/gt.js new file mode 100644 index 0000000..d9b2156 --- /dev/null +++ b/node_modules/semver/functions/gt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt diff --git a/node_modules/semver/functions/gte.js b/node_modules/semver/functions/gte.js new file mode 100644 index 0000000..5aeaa63 --- /dev/null +++ b/node_modules/semver/functions/gte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte diff --git a/node_modules/semver/functions/inc.js b/node_modules/semver/functions/inc.js new file mode 100644 index 0000000..aa4d83a --- /dev/null +++ b/node_modules/semver/functions/inc.js @@ -0,0 +1,15 @@ +const SemVer = require('../classes/semver') + +const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options + options = undefined + } + + try { + return new SemVer(version, options).inc(release, identifier).version + } catch (er) { + return null + } +} +module.exports = inc diff --git a/node_modules/semver/functions/lt.js b/node_modules/semver/functions/lt.js new file mode 100644 index 0000000..b440ab7 --- /dev/null +++ b/node_modules/semver/functions/lt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt diff --git a/node_modules/semver/functions/lte.js b/node_modules/semver/functions/lte.js new file mode 100644 index 0000000..6dcc956 --- /dev/null +++ b/node_modules/semver/functions/lte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte diff --git a/node_modules/semver/functions/major.js b/node_modules/semver/functions/major.js new file mode 100644 index 0000000..4283165 --- /dev/null +++ b/node_modules/semver/functions/major.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major diff --git a/node_modules/semver/functions/minor.js b/node_modules/semver/functions/minor.js new file mode 100644 index 0000000..57b3455 --- /dev/null +++ b/node_modules/semver/functions/minor.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor diff --git a/node_modules/semver/functions/neq.js b/node_modules/semver/functions/neq.js new file mode 100644 index 0000000..f944c01 --- /dev/null +++ b/node_modules/semver/functions/neq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq diff --git a/node_modules/semver/functions/parse.js b/node_modules/semver/functions/parse.js new file mode 100644 index 0000000..11f20f0 --- /dev/null +++ b/node_modules/semver/functions/parse.js @@ -0,0 +1,33 @@ +const {MAX_LENGTH} = require('../internal/constants') +const { re, t } = require('../internal/re') +const SemVer = require('../classes/semver') + +const parseOptions = require('../internal/parse-options') +const parse = (version, options) => { + options = parseOptions(options) + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re[t.LOOSE] : re[t.FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +module.exports = parse diff --git a/node_modules/semver/functions/patch.js b/node_modules/semver/functions/patch.js new file mode 100644 index 0000000..63afca2 --- /dev/null +++ b/node_modules/semver/functions/patch.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch diff --git a/node_modules/semver/functions/prerelease.js b/node_modules/semver/functions/prerelease.js new file mode 100644 index 0000000..06aa132 --- /dev/null +++ b/node_modules/semver/functions/prerelease.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease diff --git a/node_modules/semver/functions/rcompare.js b/node_modules/semver/functions/rcompare.js new file mode 100644 index 0000000..0ac509e --- /dev/null +++ b/node_modules/semver/functions/rcompare.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare diff --git a/node_modules/semver/functions/rsort.js b/node_modules/semver/functions/rsort.js new file mode 100644 index 0000000..82404c5 --- /dev/null +++ b/node_modules/semver/functions/rsort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort diff --git a/node_modules/semver/functions/satisfies.js b/node_modules/semver/functions/satisfies.js new file mode 100644 index 0000000..50af1c1 --- /dev/null +++ b/node_modules/semver/functions/satisfies.js @@ -0,0 +1,10 @@ +const Range = require('../classes/range') +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies diff --git a/node_modules/semver/functions/sort.js b/node_modules/semver/functions/sort.js new file mode 100644 index 0000000..4d10917 --- /dev/null +++ b/node_modules/semver/functions/sort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort diff --git a/node_modules/semver/functions/valid.js b/node_modules/semver/functions/valid.js new file mode 100644 index 0000000..f27bae1 --- /dev/null +++ b/node_modules/semver/functions/valid.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid diff --git a/node_modules/semver/index.js b/node_modules/semver/index.js new file mode 100644 index 0000000..57e2ae6 --- /dev/null +++ b/node_modules/semver/index.js @@ -0,0 +1,48 @@ +// just pre-load all the stuff that index.js lazily exports +const internalRe = require('./internal/re') +module.exports = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: require('./internal/constants').SEMVER_SPEC_VERSION, + SemVer: require('./classes/semver'), + compareIdentifiers: require('./internal/identifiers').compareIdentifiers, + rcompareIdentifiers: require('./internal/identifiers').rcompareIdentifiers, + parse: require('./functions/parse'), + valid: require('./functions/valid'), + clean: require('./functions/clean'), + inc: require('./functions/inc'), + diff: require('./functions/diff'), + major: require('./functions/major'), + minor: require('./functions/minor'), + patch: require('./functions/patch'), + prerelease: require('./functions/prerelease'), + compare: require('./functions/compare'), + rcompare: require('./functions/rcompare'), + compareLoose: require('./functions/compare-loose'), + compareBuild: require('./functions/compare-build'), + sort: require('./functions/sort'), + rsort: require('./functions/rsort'), + gt: require('./functions/gt'), + lt: require('./functions/lt'), + eq: require('./functions/eq'), + neq: require('./functions/neq'), + gte: require('./functions/gte'), + lte: require('./functions/lte'), + cmp: require('./functions/cmp'), + coerce: require('./functions/coerce'), + Comparator: require('./classes/comparator'), + Range: require('./classes/range'), + satisfies: require('./functions/satisfies'), + toComparators: require('./ranges/to-comparators'), + maxSatisfying: require('./ranges/max-satisfying'), + minSatisfying: require('./ranges/min-satisfying'), + minVersion: require('./ranges/min-version'), + validRange: require('./ranges/valid'), + outside: require('./ranges/outside'), + gtr: require('./ranges/gtr'), + ltr: require('./ranges/ltr'), + intersects: require('./ranges/intersects'), + simplifyRange: require('./ranges/simplify'), + subset: require('./ranges/subset'), +} diff --git a/node_modules/semver/internal/constants.js b/node_modules/semver/internal/constants.js new file mode 100644 index 0000000..49df215 --- /dev/null +++ b/node_modules/semver/internal/constants.js @@ -0,0 +1,17 @@ +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +module.exports = { + SEMVER_SPEC_VERSION, + MAX_LENGTH, + MAX_SAFE_INTEGER, + MAX_SAFE_COMPONENT_LENGTH +} diff --git a/node_modules/semver/internal/debug.js b/node_modules/semver/internal/debug.js new file mode 100644 index 0000000..1c00e13 --- /dev/null +++ b/node_modules/semver/internal/debug.js @@ -0,0 +1,9 @@ +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug diff --git a/node_modules/semver/internal/identifiers.js b/node_modules/semver/internal/identifiers.js new file mode 100644 index 0000000..ed13094 --- /dev/null +++ b/node_modules/semver/internal/identifiers.js @@ -0,0 +1,23 @@ +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers +} diff --git a/node_modules/semver/internal/parse-options.js b/node_modules/semver/internal/parse-options.js new file mode 100644 index 0000000..42d2ebd --- /dev/null +++ b/node_modules/semver/internal/parse-options.js @@ -0,0 +1,11 @@ +// parse out just the options we care about so we always get a consistent +// obj with keys in a consistent order. +const opts = ['includePrerelease', 'loose', 'rtl'] +const parseOptions = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true + return options + }, {}) +module.exports = parseOptions diff --git a/node_modules/semver/internal/re.js b/node_modules/semver/internal/re.js new file mode 100644 index 0000000..54d4176 --- /dev/null +++ b/node_modules/semver/internal/re.js @@ -0,0 +1,182 @@ +const { MAX_SAFE_COMPONENT_LENGTH } = require('./constants') +const debug = require('./debug') +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const src = exports.src = [] +const t = exports.t = {} +let R = 0 + +const createToken = (name, value, isGlobal) => { + const index = R++ + debug(index, value) + t[name] = index + src[index] = value + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*') + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+') + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$') diff --git a/node_modules/semver/package.json b/node_modules/semver/package.json new file mode 100644 index 0000000..4e11541 --- /dev/null +++ b/node_modules/semver/package.json @@ -0,0 +1,41 @@ +{ + "name": "semver", + "version": "7.3.5", + "description": "The semantic version parser used by npm.", + "main": "index.js", + "scripts": { + "test": "tap", + "snap": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --follow-tags" + }, + "devDependencies": { + "tap": "^14.10.7" + }, + "license": "ISC", + "repository": "https://github.com/npm/node-semver", + "bin": { + "semver": "bin/semver.js" + }, + "files": [ + "bin/**/*.js", + "range.bnf", + "classes/**/*.js", + "functions/**/*.js", + "internal/**/*.js", + "ranges/**/*.js", + "index.js", + "preload.js" + ], + "tap": { + "check-coverage": true, + "coverage-map": "map.js" + }, + "engines": { + "node": ">=10" + }, + "dependencies": { + "lru-cache": "^6.0.0" + } +} diff --git a/node_modules/semver/preload.js b/node_modules/semver/preload.js new file mode 100644 index 0000000..947cd4f --- /dev/null +++ b/node_modules/semver/preload.js @@ -0,0 +1,2 @@ +// XXX remove in v8 or beyond +module.exports = require('./index.js') diff --git a/node_modules/semver/range.bnf b/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/semver/ranges/gtr.js b/node_modules/semver/ranges/gtr.js new file mode 100644 index 0000000..db7e355 --- /dev/null +++ b/node_modules/semver/ranges/gtr.js @@ -0,0 +1,4 @@ +// Determine if version is greater than all the versions possible in the range. +const outside = require('./outside') +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr diff --git a/node_modules/semver/ranges/intersects.js b/node_modules/semver/ranges/intersects.js new file mode 100644 index 0000000..3d1a6f3 --- /dev/null +++ b/node_modules/semver/ranges/intersects.js @@ -0,0 +1,7 @@ +const Range = require('../classes/range') +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} +module.exports = intersects diff --git a/node_modules/semver/ranges/ltr.js b/node_modules/semver/ranges/ltr.js new file mode 100644 index 0000000..528a885 --- /dev/null +++ b/node_modules/semver/ranges/ltr.js @@ -0,0 +1,4 @@ +const outside = require('./outside') +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr diff --git a/node_modules/semver/ranges/max-satisfying.js b/node_modules/semver/ranges/max-satisfying.js new file mode 100644 index 0000000..6e3d993 --- /dev/null +++ b/node_modules/semver/ranges/max-satisfying.js @@ -0,0 +1,25 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying diff --git a/node_modules/semver/ranges/min-satisfying.js b/node_modules/semver/ranges/min-satisfying.js new file mode 100644 index 0000000..9b60974 --- /dev/null +++ b/node_modules/semver/ranges/min-satisfying.js @@ -0,0 +1,24 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying diff --git a/node_modules/semver/ranges/min-version.js b/node_modules/semver/ranges/min-version.js new file mode 100644 index 0000000..2fac412 --- /dev/null +++ b/node_modules/semver/ranges/min-version.js @@ -0,0 +1,60 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const gt = require('../functions/gt') + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) + minver = setMin + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} +module.exports = minVersion diff --git a/node_modules/semver/ranges/outside.js b/node_modules/semver/ranges/outside.js new file mode 100644 index 0000000..2a4b0a1 --- /dev/null +++ b/node_modules/semver/ranges/outside.js @@ -0,0 +1,80 @@ +const SemVer = require('../classes/semver') +const Comparator = require('../classes/comparator') +const {ANY} = Comparator +const Range = require('../classes/range') +const satisfies = require('../functions/satisfies') +const gt = require('../functions/gt') +const lt = require('../functions/lt') +const lte = require('../functions/lte') +const gte = require('../functions/gte') + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +module.exports = outside diff --git a/node_modules/semver/ranges/simplify.js b/node_modules/semver/ranges/simplify.js new file mode 100644 index 0000000..b792f97 --- /dev/null +++ b/node_modules/semver/ranges/simplify.js @@ -0,0 +1,44 @@ +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') +module.exports = (versions, range, options) => { + const set = [] + let min = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!min) + min = version + } else { + if (prev) { + set.push([min, prev]) + } + prev = null + min = null + } + } + if (min) + set.push([min, null]) + + const ranges = [] + for (const [min, max] of set) { + if (min === max) + ranges.push(min) + else if (!max && min === v[0]) + ranges.push('*') + else if (!max) + ranges.push(`>=${min}`) + else if (min === v[0]) + ranges.push(`<=${max}`) + else + ranges.push(`${min} - ${max}`) + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} diff --git a/node_modules/semver/ranges/subset.js b/node_modules/semver/ranges/subset.js new file mode 100644 index 0000000..532fd13 --- /dev/null +++ b/node_modules/semver/ranges/subset.js @@ -0,0 +1,222 @@ +const Range = require('../classes/range.js') +const Comparator = require('../classes/comparator.js') +const { ANY } = Comparator +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') + +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true + + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) + continue OUTER + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true +} + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ] + else + sub = [ new Comparator('>=0.0.0') ] + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ] + } + + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options) + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options) + else + eqSet.add(c.semver) + } + + if (eqSet.size > 1) + return null + + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null + + if (lt && !satisfies(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false + } + + return true + } + + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false + + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true +} + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +} + +module.exports = subset diff --git a/node_modules/semver/ranges/to-comparators.js b/node_modules/semver/ranges/to-comparators.js new file mode 100644 index 0000000..6c8bc7e --- /dev/null +++ b/node_modules/semver/ranges/to-comparators.js @@ -0,0 +1,8 @@ +const Range = require('../classes/range') + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators diff --git a/node_modules/semver/ranges/valid.js b/node_modules/semver/ranges/valid.js new file mode 100644 index 0000000..365f356 --- /dev/null +++ b/node_modules/semver/ranges/valid.js @@ -0,0 +1,11 @@ +const Range = require('../classes/range') +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange diff --git a/node_modules/send/HISTORY.md b/node_modules/send/HISTORY.md new file mode 100644 index 0000000..d14ac06 --- /dev/null +++ b/node_modules/send/HISTORY.md @@ -0,0 +1,496 @@ +0.17.1 / 2019-05-10 +=================== + + * Set stricter CSP header in redirect & error responses + * deps: range-parser@~1.2.1 + +0.17.0 / 2019-05-03 +=================== + + * deps: http-errors@~1.7.2 + - Set constructor name when possible + - Use `toidentifier` module to make class names + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: mime@1.6.0 + - Add extensions for JPEG-2000 images + - Add new `font/*` types from IANA + - Add WASM mapping + - Update `.bdoc` to `application/bdoc` + - Update `.bmp` to `image/bmp` + - Update `.m4a` to `audio/mp4` + - Update `.rtf` to `application/rtf` + - Update `.wav` to `audio/wav` + - Update `.xml` to `application/xml` + - Update generic extensions to `application/octet-stream`: + `.deb`, `.dll`, `.dmg`, `.exe`, `.iso`, `.msi` + - Use mime-score module to resolve extension conflicts + * deps: ms@2.1.1 + - Add `week`/`w` support + - Fix negative number handling + * deps: statuses@~1.5.0 + * perf: remove redundant `path.normalize` call + +0.16.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in default error & redirects + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +0.16.1 / 2017-09-29 +=================== + + * Fix regression in edge-case behavior for empty `path` + +0.16.0 / 2017-09-27 +=================== + + * Add `immutable` option + * Fix missing `` in default error & redirects + * Use instance methods on steam to check for listeners + * deps: mime@1.4.1 + - Add 70 new types for file extensions + - Set charset as "UTF-8" for .js and .json + * perf: improve path validation speed + +0.15.6 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: improve `If-Match` token parsing + +0.15.5 / 2017-09-20 +=================== + + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + +0.15.4 / 2017-08-05 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + +0.15.3 / 2017-05-16 +=================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: ms@2.0.0 + +0.15.2 / 2017-04-26 +=================== + + * deps: debug@2.6.4 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@0.7.3 + * deps: ms@1.0.0 + +0.15.1 / 2017-03-04 +=================== + + * Fix issue when `Date.parse` does not return `NaN` on invalid date + * Fix strict violation in broken environments + +0.15.0 / 2017-02-25 +=================== + + * Support `If-Match` and `If-Unmodified-Since` headers + * Add `res` and `path` arguments to `directory` event + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Send complete HTML document in redirect & error responses + * Set default CSP header in redirect & error responses + * Use `res.getHeaderNames()` when available + * Use `res.headersSent` when available + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + +0.14.2 / 2017-01-23 +=================== + + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: ms@0.7.2 + * deps: statuses@~1.3.1 + +0.14.1 / 2016-06-09 +=================== + + * Fix redirect error when `path` contains raw non-URL characters + * Fix redirect when `path` starts with multiple forward slashes + +0.14.0 / 2016-06-06 +=================== + + * Add `acceptRanges` option + * Add `cacheControl` option + * Attempt to combine multiple ranges into single range + * Correctly inherit from `Stream` class + * Fix `Content-Range` header in 416 responses when using `start`/`end` options + * Fix `Content-Range` header missing from default 416 responses + * Ignore non-byte `Range` headers + * deps: http-errors@~1.5.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - Support new code `421 Misdirected Request` + - Use `setprototypeof` module to replace `__proto__` setting + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: range-parser@~1.2.0 + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: statuses@~1.3.0 + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: remove argument reassignment + +0.13.2 / 2016-03-05 +=================== + + * Fix invalid `Content-Type` header when `send.mime.default_type` unset + +0.13.1 / 2016-01-16 +=================== + + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: destroy@~1.0.4 + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: range-parser@~1.0.3 + - perf: enable strict mode + +0.13.0 / 2015-06-16 +=================== + + * Allow Node.js HTTP server to set `Date` response header + * Fix incorrectly removing `Content-Location` on 304 response + * Improve the default redirect response headers + * Send appropriate headers on default error response + * Use `http-errors` for standard emitted errors + * Use `statuses` instead of `http` module for status messages + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Improve stat performance by removing hashing + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove unnecessary array allocations + +0.12.3 / 2015-05-13 +=================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: ms@0.7.1 + - Prevent extraordinarily long inputs + * deps: on-finished@~2.2.1 + +0.12.2 / 2015-03-13 +=================== + + * Throw errors early for invalid `extensions` or `index` options + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.12.1 / 2015-02-17 +=================== + + * Fix regression sending zero-length files + +0.12.0 / 2015-02-16 +=================== + + * Always read the stat size from the file + * Fix mutating passed-in `options` + * deps: mime@1.3.4 + +0.11.1 / 2015-01-20 +=================== + + * Fix `root` path disclosure + +0.11.0 / 2015-01-05 +=================== + + * deps: debug@~2.1.1 + * deps: etag@~1.5.1 + - deps: crc@3.2.1 + * deps: ms@0.7.0 + - Add `milliseconds` + - Add `msecs` + - Add `secs` + - Add `mins` + - Add `hrs` + - Add `yrs` + * deps: on-finished@~2.2.0 + +0.10.1 / 2014-10-22 +=================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.10.0 / 2014-10-15 +=================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + +0.9.3 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + - Support "fake" stats objects + +0.9.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: range-parser@~1.0.2 + +0.9.1 / 2014-09-07 +================== + + * deps: fresh@0.2.4 + +0.9.0 / 2014-09-07 +================== + + * Add `lastModified` option + * Use `etag` to generate `ETag` header + * deps: debug@~2.0.0 + +0.8.5 / 2014-09-04 +================== + + * Fix malicious path detection for empty string path + +0.8.4 / 2014-09-04 +================== + + * Fix a path traversal issue when using `root` + +0.8.3 / 2014-08-16 +================== + + * deps: destroy@1.0.3 + - renamed from dethroy + * deps: on-finished@2.1.0 + +0.8.2 / 2014-08-14 +================== + + * Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: dethroy@1.0.2 + +0.8.1 / 2014-08-05 +================== + + * Fix `extensions` behavior when file already has extension + +0.8.0 / 2014-08-05 +================== + + * Add `extensions` option + +0.7.4 / 2014-08-04 +================== + + * Fix serving index files without root dir + +0.7.3 / 2014-07-29 +================== + + * Fix incorrect 403 on Windows and Node.js 0.11 + +0.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +0.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +0.7.0 / 2014-07-20 +================== + + * Deprecate `hidden` option; use `dotfiles` option + * Add `dotfiles` option + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + +0.6.0 / 2014-07-11 +================== + + * Deprecate `from` option; use `root` option + * Deprecate `send.etag()` -- use `etag` in `options` + * Deprecate `send.hidden()` -- use `hidden` in `options` + * Deprecate `send.index()` -- use `index` in `options` + * Deprecate `send.maxage()` -- use `maxAge` in `options` + * Deprecate `send.root()` -- use `root` in `options` + * Cap `maxAge` value to 1 year + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.5.0 / 2014-06-28 +================== + + * Accept string for `maxAge` (converted by `ms`) + * Add `headers` event + * Include link in default redirect response + * Use `EventEmitter.listenerCount` to count listeners + +0.4.3 / 2014-06-11 +================== + + * Do not throw un-catchable error on file open race condition + * Use `escape-html` for HTML escaping + * deps: debug@1.0.2 + - fix some debugging output colors on node.js 0.8 + * deps: finished@1.2.2 + * deps: fresh@0.2.2 + +0.4.2 / 2014-06-09 +================== + + * fix "event emitter leak" warnings + * deps: debug@1.0.1 + * deps: finished@1.2.1 + +0.4.1 / 2014-06-02 +================== + + * Send `max-age` in `Cache-Control` in correct format + +0.4.0 / 2014-05-27 +================== + + * Calculate ETag with md5 for reduced collisions + * Fix wrong behavior when index file matches directory + * Ignore stream errors after request ends + - Goodbye `EBADF, read` + * Skip directories in index file search + * deps: debug@0.8.1 + +0.3.0 / 2014-04-24 +================== + + * Fix sending files with dots without root set + * Coerce option types + * Accept API options in options object + * Set etags to "weak" + * Include file path in etag + * Make "Can't set headers after they are sent." catchable + * Send full entity-body for multi range requests + * Default directory access to 403 when index disabled + * Support multiple index paths + * Support "If-Range" header + * Control whether to generate etags + * deps: mime@1.2.11 + +0.2.0 / 2014-01-29 +================== + + * update range-parser and fresh + +0.1.4 / 2013-08-11 +================== + + * update fresh + +0.1.3 / 2013-07-08 +================== + + * Revert "Fix fd leak" + +0.1.2 / 2013-07-03 +================== + + * Fix fd leak + +0.1.0 / 2012-08-25 +================== + + * add options parameter to send() that is passed to fs.createReadStream() [kanongil] + +0.0.4 / 2012-08-16 +================== + + * allow custom "Accept-Ranges" definition + +0.0.3 / 2012-07-16 +================== + + * fix normalization of the root directory. Closes #3 + +0.0.2 / 2012-07-09 +================== + + * add passing of req explicitly for now (YUCK) + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/send/LICENSE b/node_modules/send/LICENSE new file mode 100644 index 0000000..4aa69e8 --- /dev/null +++ b/node_modules/send/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2014-2016 Douglas Christopher Wilson + +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/send/README.md b/node_modules/send/README.md new file mode 100644 index 0000000..179e8c3 --- /dev/null +++ b/node_modules/send/README.md @@ -0,0 +1,329 @@ +# send + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Send is a library for streaming files from the file system as a http response +supporting partial responses (Ranges), conditional-GET negotiation (If-Match, +If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage, +and granular events which may be leveraged to take appropriate actions in your +application or framework. + +Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static). + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install send +``` + +## API + + + +```js +var send = require('send') +``` + +### send(req, path, [options]) + +Create a new `SendStream` for the given path to send to a `res`. The `req` is +the Node.js HTTP request and the `path` is a urlencoded path to send (urlencoded, +not the actual file-system path). + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + +Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Send a 403 for any request for a dotfile. + - `'ignore'` Pretend like the dotfile does not exist and 404. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### end + +Byte offset at which the stream ends, defaults to the length of the file +minus 1. The end is inclusive in the stream, meaning `end: 3` will include +the 4th byte in the stream. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +If a given file doesn't exist, try appending one of the given extensions, +in the given order. By default, this is disabled (set to `false`). An +example value that will serve extension-less HTML files: `['html', 'htm']`. +This is skipped if the requested file already has an extension. + +##### immutable + +Enable or diable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default send supports "index.html" files, to disable this +set `false` or to supply a new index pass a string or an array +in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. +This can also be a string accepted by the +[ms](https://www.npmjs.org/package/ms#readme) module. + +##### root + +Serve files relative to `path`. + +##### start + +Byte offset at which the stream starts, defaults to 0. The start is inclusive, +meaning `start: 2` will include the 3rd byte in the stream. + +#### Events + +The `SendStream` is an event emitter and will emit the following events: + + - `error` an error occurred `(err)` + - `directory` a directory was requested `(res, path)` + - `file` a file was requested `(path, stat)` + - `headers` the headers are about to be set on a file `(res, path, stat)` + - `stream` file streaming has started `(stream)` + - `end` streaming has completed + +#### .pipe + +The `pipe` method is used to pipe the response into the Node.js HTTP response +object, typically `send(req, path, options).pipe(res)`. + +### .mime + +The `mime` export is the global instance of of the +[`mime` npm module](https://www.npmjs.com/package/mime). + +This is used to configure the MIME types that are associated with file extensions +as well as other options for how to resolve the MIME type of a file (like the +default type to use for an unknown file extension). + +## Error-handling + +By default when no `error` listeners are present an automatic response will be +made, otherwise you have full control over the response, aka you may show a 5xx +page etc. + +## Caching + +It does _not_ perform internal caching, you should use a reverse proxy cache +such as Varnish for this, or those fancy things called CDNs. If your +application is small enough that it would benefit from single-node memory +caching, it's small enough that it does not need caching at all ;). + +## Debugging + +To enable `debug()` instrumentation output export __DEBUG__: + +``` +$ DEBUG=send node app +``` + +## Running tests + +``` +$ npm install +$ npm test +``` + +## Examples + +### Serve a specific file + +This simple example will send a specific file to all requests. + +```js +var http = require('http') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, '/path/to/index.html') + .pipe(res) +}) + +server.listen(3000) +``` + +### Serve all files from a directory + +This simple example will just serve up all the files in a +given directory as the top-level. For example, a request +`GET /foo.txt` will send back `/www/public/foo.txt`. + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .pipe(res) +}) + +server.listen(3000) +``` + +### Custom file types + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +// Default unknown types to text/plain +send.mime.default_type = 'text/plain' + +// Add a custom type +send.mime.define({ + 'application/x-my-type': ['x-mt', 'x-mtt'] +}) + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .pipe(res) +}) + +server.listen(3000) +``` + +### Custom directory index view + +This is a example of serving up a structure of directories with a +custom function to render a listing of a directory. + +```js +var http = require('http') +var fs = require('fs') +var parseUrl = require('parseurl') +var send = require('send') + +// Transfer arbitrary files from within /www/example.com/public/* +// with a custom handler for directory listing +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { index: false, root: '/www/public' }) + .once('directory', directory) + .pipe(res) +}) + +server.listen(3000) + +// Custom directory handler +function directory (res, path) { + var stream = this + + // redirect to trailing slash for consistent url + if (!stream.hasTrailingSlash()) { + return stream.redirect(path) + } + + // get directory list + fs.readdir(path, function onReaddir (err, list) { + if (err) return stream.error(err) + + // render an index for the directory + res.setHeader('Content-Type', 'text/plain; charset=UTF-8') + res.end(list.join('\n') + '\n') + }) +} +``` + +### Serving from a root directory with custom error-handling + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + // your custom error-handling logic: + function error (err) { + res.statusCode = err.status || 500 + res.end(err.message) + } + + // your custom headers + function headers (res, path, stat) { + // serve all files for download + res.setHeader('Content-Disposition', 'attachment') + } + + // your custom directory handling logic: + function redirect () { + res.statusCode = 301 + res.setHeader('Location', req.url + '/') + res.end('Redirecting to ' + req.url + '/') + } + + // transfer arbitrary files from within + // /www/example.com/public/* + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .on('error', error) + .on('directory', redirect) + .on('headers', headers) + .pipe(res) +}) + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/send/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/send +[coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/send/master +[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master +[node-image]: https://badgen.net/npm/node/send +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/send +[npm-url]: https://npmjs.org/package/send +[npm-version-image]: https://badgen.net/npm/v/send +[travis-image]: https://badgen.net/travis/pillarjs/send/master?label=linux +[travis-url]: https://travis-ci.org/pillarjs/send diff --git a/node_modules/send/index.js b/node_modules/send/index.js new file mode 100644 index 0000000..fca2112 --- /dev/null +++ b/node_modules/send/index.js @@ -0,0 +1,1129 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('send') +var deprecate = require('depd')('send') +var destroy = require('destroy') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var etag = require('etag') +var fresh = require('fresh') +var fs = require('fs') +var mime = require('mime') +var ms = require('ms') +var onFinished = require('on-finished') +var parseRange = require('range-parser') +var path = require('path') +var statuses = require('statuses') +var Stream = require('stream') +var util = require('util') + +/** + * Path function references. + * @private + */ + +var extname = path.extname +var join = path.join +var normalize = path.normalize +var resolve = path.resolve +var sep = path.sep + +/** + * Regular expression for identifying a bytes Range header. + * @private + */ + +var BYTES_RANGE_REGEXP = /^ *bytes=/ + +/** + * Maximum value allowed for the max age. + * @private + */ + +var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year + +/** + * Regular expression to match a path with a directory up component. + * @private + */ + +var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = send +module.exports.mime = mime + +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {object} req + * @param {string} path + * @param {object} [options] + * @return {SendStream} + * @public + */ + +function send (req, path, options) { + return new SendStream(req, path, options) +} + +/** + * Initialize a `SendStream` with the given `path`. + * + * @param {Request} req + * @param {String} path + * @param {object} [options] + * @private + */ + +function SendStream (req, path, options) { + Stream.call(this) + + var opts = options || {} + + this.options = opts + this.path = path + this.req = req + + this._acceptRanges = opts.acceptRanges !== undefined + ? Boolean(opts.acceptRanges) + : true + + this._cacheControl = opts.cacheControl !== undefined + ? Boolean(opts.cacheControl) + : true + + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) + : true + + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles + : 'ignore' + + if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + this._hidden = Boolean(opts.hidden) + + if (opts.hidden !== undefined) { + deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') + } + + // legacy support + if (opts.dotfiles === undefined) { + this._dotfiles = undefined + } + + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') + : [] + + this._immutable = opts.immutable !== undefined + ? Boolean(opts.immutable) + : false + + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') + : ['index.html'] + + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) + : true + + this._maxage = opts.maxAge || opts.maxage + this._maxage = typeof this._maxage === 'string' + ? ms(this._maxage) + : Number(this._maxage) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 + + this._root = opts.root + ? resolve(opts.root) + : null + + if (!this._root && opts.from) { + this.from(opts.from) + } +} + +/** + * Inherits from `Stream`. + */ + +util.inherits(SendStream, Stream) + +/** + * Enable or disable etag generation. + * + * @param {Boolean} val + * @return {SendStream} + * @api public + */ + +SendStream.prototype.etag = deprecate.function(function etag (val) { + this._etag = Boolean(val) + debug('etag %s', this._etag) + return this +}, 'send.etag: pass etag as option') + +/** + * Enable or disable "hidden" (dot) files. + * + * @param {Boolean} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.hidden = deprecate.function(function hidden (val) { + this._hidden = Boolean(val) + this._dotfiles = undefined + debug('hidden %s', this._hidden) + return this +}, 'send.hidden: use dotfiles option') + +/** + * Set index `paths`, set to a falsy + * value to disable index support. + * + * @param {String|Boolean|Array} paths + * @return {SendStream} + * @api public + */ + +SendStream.prototype.index = deprecate.function(function index (paths) { + var index = !paths ? [] : normalizeList(paths, 'paths argument') + debug('index %o', paths) + this._index = index + return this +}, 'send.index: pass index as option') + +/** + * Set root `path`. + * + * @param {String} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.root = function root (path) { + this._root = resolve(String(path)) + debug('root %s', this._root) + return this +} + +SendStream.prototype.from = deprecate.function(SendStream.prototype.root, + 'send.from: pass root as option') + +SendStream.prototype.root = deprecate.function(SendStream.prototype.root, + 'send.root: pass root as option') + +/** + * Set max-age to `maxAge`. + * + * @param {Number} maxAge + * @return {SendStream} + * @api public + */ + +SendStream.prototype.maxage = deprecate.function(function maxage (maxAge) { + this._maxage = typeof maxAge === 'string' + ? ms(maxAge) + : Number(maxAge) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 + debug('max-age %d', this._maxage) + return this +}, 'send.maxage: pass maxAge as option') + +/** + * Emit error with `status`. + * + * @param {number} status + * @param {Error} [err] + * @private + */ + +SendStream.prototype.error = function error (status, err) { + // emit if listeners instead of responding + if (hasListeners(this, 'error')) { + return this.emit('error', createError(status, err, { + expose: false + })) + } + + var res = this.res + var msg = statuses[status] || String(status) + var doc = createHtmlDocument('Error', escapeHtml(msg)) + + // clear existing headers + clearHeaders(res) + + // add error headers + if (err && err.headers) { + setHeaders(res, err.headers) + } + + // send basic response + res.statusCode = status + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(doc) +} + +/** + * Check if the pathname ends with "/". + * + * @return {boolean} + * @private + */ + +SendStream.prototype.hasTrailingSlash = function hasTrailingSlash () { + return this.path[this.path.length - 1] === '/' +} + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isConditionalGET = function isConditionalGET () { + return this.req.headers['if-match'] || + this.req.headers['if-unmodified-since'] || + this.req.headers['if-none-match'] || + this.req.headers['if-modified-since'] +} + +/** + * Check if the request preconditions failed. + * + * @return {boolean} + * @private + */ + +SendStream.prototype.isPreconditionFailure = function isPreconditionFailure () { + var req = this.req + var res = this.res + + // if-match + var match = req.headers['if-match'] + if (match) { + var etag = res.getHeader('ETag') + return !etag || (match !== '*' && parseTokenList(match).every(function (match) { + return match !== etag && match !== 'W/' + etag && 'W/' + match !== etag + })) + } + + // if-unmodified-since + var unmodifiedSince = parseHttpDate(req.headers['if-unmodified-since']) + if (!isNaN(unmodifiedSince)) { + var lastModified = parseHttpDate(res.getHeader('Last-Modified')) + return isNaN(lastModified) || lastModified > unmodifiedSince + } + + return false +} + +/** + * Strip content-* header fields. + * + * @private + */ + +SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields () { + var res = this.res + var headers = getHeaderNames(res) + + for (var i = 0; i < headers.length; i++) { + var header = headers[i] + if (header.substr(0, 8) === 'content-' && header !== 'content-location') { + res.removeHeader(header) + } + } +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +SendStream.prototype.notModified = function notModified () { + var res = this.res + debug('not modified') + this.removeContentHeaderFields() + res.statusCode = 304 + res.end() +} + +/** + * Raise error that headers already sent. + * + * @api private + */ + +SendStream.prototype.headersAlreadySent = function headersAlreadySent () { + var err = new Error('Can\'t set headers after they are sent.') + debug('headers already sent') + this.error(500, err) +} + +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isCachable = function isCachable () { + var statusCode = this.res.statusCode + return (statusCode >= 200 && statusCode < 300) || + statusCode === 304 +} + +/** + * Handle stat() error. + * + * @param {Error} error + * @private + */ + +SendStream.prototype.onStatError = function onStatError (error) { + switch (error.code) { + case 'ENAMETOOLONG': + case 'ENOENT': + case 'ENOTDIR': + this.error(404, error) + break + default: + this.error(500, error) + break + } +} + +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isFresh = function isFresh () { + return fresh(this.req.headers, { + 'etag': this.res.getHeader('ETag'), + 'last-modified': this.res.getHeader('Last-Modified') + }) +} + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isRangeFresh = function isRangeFresh () { + var ifRange = this.req.headers['if-range'] + + if (!ifRange) { + return true + } + + // if-range as etag + if (ifRange.indexOf('"') !== -1) { + var etag = this.res.getHeader('ETag') + return Boolean(etag && ifRange.indexOf(etag) !== -1) + } + + // if-range as modified date + var lastModified = this.res.getHeader('Last-Modified') + return parseHttpDate(lastModified) <= parseHttpDate(ifRange) +} + +/** + * Redirect to path. + * + * @param {string} path + * @private + */ + +SendStream.prototype.redirect = function redirect (path) { + var res = this.res + + if (hasListeners(this, 'directory')) { + this.emit('directory', res, path) + return + } + + if (this.hasTrailingSlash()) { + this.error(403) + return + } + + var loc = encodeUrl(collapseLeadingSlashes(this.path + '/')) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + + escapeHtml(loc) + '') + + // redirect + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) +} + +/** + * Pipe to `res. + * + * @param {Stream} res + * @return {Stream} res + * @api public + */ + +SendStream.prototype.pipe = function pipe (res) { + // root path + var root = this._root + + // references + this.res = res + + // decode the path + var path = decode(this.path) + if (path === -1) { + this.error(400) + return res + } + + // null byte(s) + if (~path.indexOf('\0')) { + this.error(400) + return res + } + + var parts + if (root !== null) { + // normalize + if (path) { + path = normalize('.' + sep + path) + } + + // malicious path + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = path.split(sep) + + // join / normalize from optional root dir + path = normalize(join(root, path)) + } else { + // ".." is malicious without "root" + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + // dotfile handling + if (containsDotFile(parts)) { + var access = this._dotfiles + + // legacy support + if (access === undefined) { + access = parts[parts.length - 1][0] === '.' + ? (this._hidden ? 'allow' : 'ignore') + : 'allow' + } + + debug('%s dotfile "%s"', access, path) + switch (access) { + case 'allow': + break + case 'deny': + this.error(403) + return res + case 'ignore': + default: + this.error(404) + return res + } + } + + // index file support + if (this._index.length && this.hasTrailingSlash()) { + this.sendIndex(path) + return res + } + + this.sendFile(path) + return res +} + +/** + * Transfer `path`. + * + * @param {String} path + * @api public + */ + +SendStream.prototype.send = function send (path, stat) { + var len = stat.size + var options = this.options + var opts = {} + var res = this.res + var req = this.req + var ranges = req.headers.range + var offset = options.start || 0 + + if (headersSent(res)) { + // impossible to send now + this.headersAlreadySent() + return + } + + debug('pipe "%s"', path) + + // set header fields + this.setHeader(path, stat) + + // set content-type + this.type(path) + + // conditional GET support + if (this.isConditionalGET()) { + if (this.isPreconditionFailure()) { + this.error(412) + return + } + + if (this.isCachable() && this.isFresh()) { + this.notModified() + return + } + } + + // adjust len to start/end options + len = Math.max(0, len - offset) + if (options.end !== undefined) { + var bytes = options.end - offset + 1 + if (len > bytes) len = bytes + } + + // Range support + if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) { + // parse + ranges = parseRange(len, ranges, { + combine: true + }) + + // If-Range support + if (!this.isRangeFresh()) { + debug('range stale') + ranges = -2 + } + + // unsatisfiable + if (ranges === -1) { + debug('range unsatisfiable') + + // Content-Range + res.setHeader('Content-Range', contentRange('bytes', len)) + + // 416 Requested Range Not Satisfiable + return this.error(416, { + headers: { 'Content-Range': res.getHeader('Content-Range') } + }) + } + + // valid (syntactically invalid/multiple ranges are treated as a regular response) + if (ranges !== -2 && ranges.length === 1) { + debug('range %j', ranges) + + // Content-Range + res.statusCode = 206 + res.setHeader('Content-Range', contentRange('bytes', len, ranges[0])) + + // adjust for requested range + offset += ranges[0].start + len = ranges[0].end - ranges[0].start + 1 + } + } + + // clone options + for (var prop in options) { + opts[prop] = options[prop] + } + + // set read options + opts.start = offset + opts.end = Math.max(offset, offset + len - 1) + + // content-length + res.setHeader('Content-Length', len) + + // HEAD support + if (req.method === 'HEAD') { + res.end() + return + } + + this.stream(path, opts) +} + +/** + * Transfer file for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendFile = function sendFile (path) { + var i = 0 + var self = this + + debug('stat "%s"', path) + fs.stat(path, function onstat (err, stat) { + if (err && err.code === 'ENOENT' && !extname(path) && path[path.length - 1] !== sep) { + // not found, check extensions + return next(err) + } + if (err) return self.onStatError(err) + if (stat.isDirectory()) return self.redirect(path) + self.emit('file', path, stat) + self.send(path, stat) + }) + + function next (err) { + if (self._extensions.length <= i) { + return err + ? self.onStatError(err) + : self.error(404) + } + + var p = path + '.' + self._extensions[i++] + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } +} + +/** + * Transfer index for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendIndex = function sendIndex (path) { + var i = -1 + var self = this + + function next (err) { + if (++i >= self._index.length) { + if (err) return self.onStatError(err) + return self.error(404) + } + + var p = join(path, self._index[i]) + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } + + next() +} + +/** + * Stream `path` to the response. + * + * @param {String} path + * @param {Object} options + * @api private + */ + +SendStream.prototype.stream = function stream (path, options) { + // TODO: this is all lame, refactor meeee + var finished = false + var self = this + var res = this.res + + // pipe + var stream = fs.createReadStream(path, options) + this.emit('stream', stream) + stream.pipe(res) + + // response finished, done with the fd + onFinished(res, function onfinished () { + finished = true + destroy(stream) + }) + + // error handling code-smell + stream.on('error', function onerror (err) { + // request already finished + if (finished) return + + // clean up stream + finished = true + destroy(stream) + + // error + self.onStatError(err) + }) + + // end + stream.on('end', function onend () { + self.emit('end') + }) +} + +/** + * Set content-type based on `path` + * if it hasn't been explicitly set. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.type = function type (path) { + var res = this.res + + if (res.getHeader('Content-Type')) return + + var type = mime.lookup(path) + + if (!type) { + debug('no content-type') + return + } + + var charset = mime.charsets.lookup(type) + + debug('content-type %s', type) + res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')) +} + +/** + * Set response header fields, most + * fields may be pre-defined. + * + * @param {String} path + * @param {Object} stat + * @api private + */ + +SendStream.prototype.setHeader = function setHeader (path, stat) { + var res = this.res + + this.emit('headers', res, path, stat) + + if (this._acceptRanges && !res.getHeader('Accept-Ranges')) { + debug('accept ranges') + res.setHeader('Accept-Ranges', 'bytes') + } + + if (this._cacheControl && !res.getHeader('Cache-Control')) { + var cacheControl = 'public, max-age=' + Math.floor(this._maxage / 1000) + + if (this._immutable) { + cacheControl += ', immutable' + } + + debug('cache-control %s', cacheControl) + res.setHeader('Cache-Control', cacheControl) + } + + if (this._lastModified && !res.getHeader('Last-Modified')) { + var modified = stat.mtime.toUTCString() + debug('modified %s', modified) + res.setHeader('Last-Modified', modified) + } + + if (this._etag && !res.getHeader('ETag')) { + var val = etag(stat) + debug('etag %s', val) + res.setHeader('ETag', val) + } +} + +/** + * Clear all headers from a response. + * + * @param {object} res + * @private + */ + +function clearHeaders (res) { + var headers = getHeaderNames(res) + + for (var i = 0; i < headers.length; i++) { + res.removeHeader(headers[i]) + } +} + +/** + * Collapse all leading slashes into a single slash + * + * @param {string} str + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str[i] !== '/') { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ + +function containsDotFile (parts) { + for (var i = 0; i < parts.length; i++) { + var part = parts[i] + if (part.length > 1 && part[0] === '.') { + return true + } + } + + return false +} + +/** + * Create a Content-Range header. + * + * @param {string} type + * @param {number} size + * @param {array} [range] + */ + +function contentRange (type, size, range) { + return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size +} + +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * decodeURIComponent. + * + * Allows V8 to only deoptimize this fn instead of all + * of send(). + * + * @param {String} path + * @api private + */ + +function decode (path) { + try { + return decodeURIComponent(path) + } catch (err) { + return -1 + } +} + +/** + * Get the header names on a respnse. + * + * @param {object} res + * @returns {array[string]} + * @private + */ + +function getHeaderNames (res) { + return typeof res.getHeaderNames !== 'function' + ? Object.keys(res._headers || {}) + : res.getHeaderNames() +} + +/** + * Determine if emitter has listeners of a given type. + * + * The way to do this check is done three different ways in Node.js >= 0.8 + * so this consolidates them into a minimal set using instance methods. + * + * @param {EventEmitter} emitter + * @param {string} type + * @returns {boolean} + * @private + */ + +function hasListeners (emitter, type) { + var count = typeof emitter.listenerCount !== 'function' + ? emitter.listeners(type).length + : emitter.listenerCount(type) + + return count > 0 +} + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +function normalizeList (val, name) { + var list = [].concat(val || []) + + for (var i = 0; i < list.length; i++) { + if (typeof list[i] !== 'string') { + throw new TypeError(name + ' must be array of strings or false') + } + } + + return list +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(str.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(str.substring(start, end)) + + return list +} + +/** + * Set an object of headers on a response. + * + * @param {object} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + var keys = Object.keys(headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} diff --git a/node_modules/send/node_modules/ms/index.js b/node_modules/send/node_modules/ms/index.js new file mode 100644 index 0000000..7229750 --- /dev/null +++ b/node_modules/send/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/send/node_modules/ms/license.md b/node_modules/send/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/send/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/send/node_modules/ms/package.json b/node_modules/send/node_modules/ms/package.json new file mode 100644 index 0000000..fc28cb3 --- /dev/null +++ b/node_modules/send/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.1.1", + "description": "Tiny millisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.12.1", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1" + } +} diff --git a/node_modules/send/node_modules/ms/readme.md b/node_modules/send/node_modules/ms/readme.md new file mode 100644 index 0000000..bb76729 --- /dev/null +++ b/node_modules/send/node_modules/ms/readme.md @@ -0,0 +1,60 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/send/package.json b/node_modules/send/package.json new file mode 100644 index 0000000..2ba9c06 --- /dev/null +++ b/node_modules/send/package.json @@ -0,0 +1,61 @@ +{ + "name": "send", + "description": "Better streaming static file server with Range and conditional-GET support", + "version": "0.17.1", + "author": "TJ Holowaychuk ", + "contributors": [ + "Douglas Christopher Wilson ", + "James Wyatt Cready ", + "Jesús Leganés Combarro " + ], + "license": "MIT", + "repository": "pillarjs/send", + "keywords": [ + "static", + "file", + "server" + ], + "dependencies": { + "debug": "2.6.9", + "depd": "~1.1.2", + "destroy": "~1.0.4", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "~1.7.2", + "mime": "1.6.0", + "ms": "2.1.1", + "on-finished": "~2.3.0", + "range-parser": "~1.2.1", + "statuses": "~1.5.0" + }, + "devDependencies": { + "after": "0.8.2", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "6.1.4", + "supertest": "4.0.2" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --check-leaks --reporter spec --bail", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot" + } +} diff --git a/node_modules/serve-static/HISTORY.md b/node_modules/serve-static/HISTORY.md new file mode 100644 index 0000000..7203e4f --- /dev/null +++ b/node_modules/serve-static/HISTORY.md @@ -0,0 +1,451 @@ +1.14.1 / 2019-05-10 +=================== + + * Set stricter CSP header in redirect response + * deps: send@0.17.1 + - deps: range-parser@~1.2.1 + +1.14.0 / 2019-05-07 +=================== + + * deps: parseurl@~1.3.3 + * deps: send@0.17.0 + - deps: http-errors@~1.7.2 + - deps: mime@1.6.0 + - deps: ms@2.1.1 + - deps: statuses@~1.5.0 + - perf: remove redundant `path.normalize` call + +1.13.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in redirects + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: send@0.16.2 + - deps: depd@~1.1.2 + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + +1.13.1 / 2017-09-29 +=================== + + * Fix regression when `root` is incorrectly set to a file + * deps: send@0.16.1 + +1.13.0 / 2017-09-27 +=================== + + * deps: send@0.16.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Fix missing `` in default error & redirects + - Set charset as "UTF-8" for .js and .json + - Use instance methods on steam to check for listeners + - deps: mime@1.4.1 + - perf: improve path validation speed + +1.12.6 / 2017-09-22 +=================== + + * deps: send@0.15.6 + - deps: debug@2.6.9 + - perf: improve `If-Match` token parsing + * perf: improve slash collapsing + +1.12.5 / 2017-09-21 +=================== + + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: send@0.15.5 + - Fix handling of modified headers with invalid dates + - deps: etag@~1.8.1 + - deps: fresh@0.5.2 + +1.12.4 / 2017-08-05 +=================== + + * deps: send@0.15.4 + - deps: debug@2.6.8 + - deps: depd@~1.1.1 + - deps: http-errors@~1.6.2 + +1.12.3 / 2017-05-16 +=================== + + * deps: send@0.15.3 + - deps: debug@2.6.7 + +1.12.2 / 2017-04-26 +=================== + + * deps: send@0.15.2 + - deps: debug@2.6.4 + +1.12.1 / 2017-03-04 +=================== + + * deps: send@0.15.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - Fix strict violation in broken environments + +1.12.0 / 2017-02-25 +=================== + + * Send complete HTML document in redirect response + * Set default CSP header in redirect response + * deps: send@0.15.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: debug@2.6.1 + - deps: etag@~1.8.0 + - deps: fresh@0.5.0 + - deps: http-errors@~1.6.1 + +1.11.2 / 2017-01-23 +=================== + + * deps: send@0.14.2 + - deps: http-errors@~1.5.1 + - deps: ms@0.7.2 + - deps: statuses@~1.3.1 + +1.11.1 / 2016-06-10 +=================== + + * Fix redirect error when `req.url` contains raw non-URL characters + * deps: send@0.14.1 + +1.11.0 / 2016-06-07 +=================== + + * Use status code 301 for redirects + * deps: send@0.14.0 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Correctly inherit from `Stream` class + - Fix `Content-Range` header in 416 responses when using `start`/`end` options + - Fix `Content-Range` header missing from default 416 responses + - Ignore non-byte `Range` headers + - deps: http-errors@~1.5.0 + - deps: range-parser@~1.2.0 + - deps: statuses@~1.3.0 + - perf: remove argument reassignment + +1.10.3 / 2016-05-30 +=================== + + * deps: send@0.13.2 + - Fix invalid `Content-Type` header when `send.mime.default_type` unset + +1.10.2 / 2016-01-19 +=================== + + * deps: parseurl@~1.3.1 + - perf: enable strict mode + +1.10.1 / 2016-01-16 +=================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + +1.10.0 / 2015-06-17 +=================== + + * Add `fallthrough` option + - Allows declaring this middleware is the final destination + - Provides better integration with Express patterns + * Fix reading options from options prototype + * Improve the default redirect response headers + * deps: escape-html@1.0.2 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * perf: enable strict mode + * perf: remove argument reassignment + +1.9.3 / 2015-05-14 +================== + + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +1.9.2 / 2015-03-14 +================== + + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +1.9.1 / 2015-02-17 +================== + + * deps: send@0.12.1 + - Fix regression sending zero-length files + +1.9.0 / 2015-02-16 +================== + + * deps: send@0.12.0 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +1.8.1 / 2015-01-20 +================== + + * Fix redirect loop in Node.js 0.11.14 + * deps: send@0.11.1 + - Fix root path disclosure + +1.8.0 / 2015-01-05 +================== + + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +1.7.2 / 2015-01-02 +================== + + * Fix potential open redirect when mounted at root + +1.7.1 / 2014-10-22 +================== + + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +1.7.0 / 2014-10-15 +================== + + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +1.6.5 / 2015-02-04 +================== + + * Fix potential open redirect when mounted at root + - Back-ported from v1.7.2 + +1.6.4 / 2014-10-08 +================== + + * Fix redirect loop when index file serving disabled + +1.6.3 / 2014-09-24 +================== + + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +1.6.2 / 2014-09-15 +================== + + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +1.6.1 / 2014-09-07 +================== + + * deps: send@0.9.1 + - deps: fresh@0.2.4 + +1.6.0 / 2014-09-07 +================== + + * deps: send@0.9.0 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + +1.5.4 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +1.5.3 / 2014-08-17 +================== + + * deps: send@0.8.3 + +1.5.2 / 2014-08-14 +================== + + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +1.5.1 / 2014-08-09 +================== + + * Fix parsing of weird `req.originalUrl` values + * deps: parseurl@~1.3.0 + * deps: utils-merge@1.0.0 + +1.5.0 / 2014-08-05 +================== + + * deps: send@0.8.1 + - Add `extensions` option + +1.4.4 / 2014-08-04 +================== + + * deps: send@0.7.4 + - Fix serving index files without root dir + +1.4.3 / 2014-07-29 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + +1.4.2 / 2014-07-27 +================== + + * deps: send@0.7.2 + - deps: depd@0.4.4 + +1.4.1 / 2014-07-26 +================== + + * deps: send@0.7.1 + - deps: depd@0.4.3 + +1.4.0 / 2014-07-21 +================== + + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +1.3.2 / 2014-07-11 +================== + + * deps: send@0.6.0 + - Cap `maxAge` value to 1 year + - deps: debug@1.0.3 + +1.3.1 / 2014-07-09 +================== + + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +1.3.0 / 2014-06-28 +================== + + * Add `setHeaders` option + * Include HTML link in redirect response + * deps: send@0.5.0 + - Accept string for `maxAge` (converted by `ms`) + +1.2.3 / 2014-06-11 +================== + + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +1.2.2 / 2014-06-09 +================== + + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + +1.2.1 / 2014-06-02 +================== + + * use `escape-html` for escaping + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +1.2.0 / 2014-05-29 +================== + + * deps: send@0.4.0 + - Calculate ETag with md5 for reduced collisions + - Fix wrong behavior when index file matches directory + - Ignore stream errors after request ends + - Skip directories in index file search + - deps: debug@0.8.1 + +1.1.0 / 2014-04-24 +================== + + * Accept options directly to `send` module + * deps: send@0.3.0 + +1.0.4 / 2014-04-07 +================== + + * Resolve relative paths at middleware setup + * Use parseurl to parse the URL from request + +1.0.3 / 2014-03-20 +================== + + * Do not rely on connect-like environments + +1.0.2 / 2014-03-06 +================== + + * deps: send@0.2.0 + +1.0.1 / 2014-03-05 +================== + + * Add mime export for back-compat + +1.0.0 / 2014-03-05 +================== + + * Genesis from `connect` diff --git a/node_modules/serve-static/LICENSE b/node_modules/serve-static/LICENSE new file mode 100644 index 0000000..cbe62e8 --- /dev/null +++ b/node_modules/serve-static/LICENSE @@ -0,0 +1,25 @@ +(The MIT License) + +Copyright (c) 2010 Sencha Inc. +Copyright (c) 2011 LearnBoost +Copyright (c) 2011 TJ Holowaychuk +Copyright (c) 2014-2016 Douglas Christopher Wilson + +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/serve-static/README.md b/node_modules/serve-static/README.md new file mode 100644 index 0000000..7cce428 --- /dev/null +++ b/node_modules/serve-static/README.md @@ -0,0 +1,259 @@ +# serve-static + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install serve-static +``` + +## API + + + +```js +var serveStatic = require('serve-static') +``` + +### serveStatic(root, options) + +Create a new middleware function to serve files from within a given root +directory. The file to serve will be determined by combining `req.url` +with the provided root directory. When a file is not found, instead of +sending a 404 response, this module will instead call `next()` to move on +to the next middleware, allowing for stacking and fall-backs. + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + + Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Deny a request for a dotfile and 403/`next()`. + - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. + +The default value is similar to `'ignore'`, with the exception that this +default will not ignore the files within a directory that begins with a dot. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +Set file extension fallbacks. When set, if a file is not found, the given +extensions will be added to the file name and search for. The first that +exists will be served. Example: `['html', 'htm']`. + +The default value is `false`. + +##### fallthrough + +Set the middleware to have client errors fall-through as just unhandled +requests, otherwise forward a client error. The difference is that client +errors like a bad request or a request to a non-existent file will cause +this middleware to simply `next()` to your next middleware when this value +is `true`. When this value is `false`, these errors (even 404s), will invoke +`next(err)`. + +Typically `true` is desired such that multiple physical directories can be +mapped to the same web address or for routes to fill in non-existent files. + +The value `false` can be used if this middleware is mounted at a path that +is designed to be strictly a single file system directory, which allows for +short-circuiting 404s for less overhead. This middleware will also reply to +all methods. + +The default value is `true`. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default this module will send "index.html" files in response to a request +on a directory. To disable this set `false` or to supply a new index pass a +string or an array in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. This +can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) +module. + +##### redirect + +Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. + +##### setHeaders + +Function to set custom headers on response. Alterations to the headers need to +occur synchronously. The function is called as `fn(res, path, stat)`, where +the arguments are: + + - `res` the response object + - `path` the file path that is being sent + - `stat` the stat object of the file that is being sent + +## Examples + +### Serve files with vanilla node.js http server + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { 'index': ['index.html', 'index.htm'] }) + +// Create server +var server = http.createServer(function onRequest (req, res) { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serve all files as downloads + +```js +var contentDisposition = require('content-disposition') +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { + 'index': false, + 'setHeaders': setHeaders +}) + +// Set header to force download +function setHeaders (res, path) { + res.setHeader('Content-Disposition', contentDisposition(path)) +} + +// Create server +var server = http.createServer(function onRequest (req, res) { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serving using express + +#### Simple + +This is a simple example of using Express. + +```js +var express = require('express') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic('public/ftp', { 'index': ['default.html', 'default.htm'] })) +app.listen(3000) +``` + +#### Multiple roots + +This example shows a simple way to search through multiple directories. +Files are look for in `public-optimized/` first, then `public/` second as +a fallback. + +```js +var express = require('express') +var path = require('path') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(path.join(__dirname, 'public-optimized'))) +app.use(serveStatic(path.join(__dirname, 'public'))) +app.listen(3000) +``` + +#### Different settings for paths + +This example shows how to set a different max age depending on the served +file type. In this example, HTML files are not cached, while everything else +is for 1 day. + +```js +var express = require('express') +var path = require('path') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(path.join(__dirname, 'public'), { + maxAge: '1d', + setHeaders: setCustomCacheControl +})) + +app.listen(3000) + +function setCustomCacheControl (res, path) { + if (serveStatic.mime.lookup(path) === 'text/html') { + // Custom Cache-Control for HTML files + res.setHeader('Cache-Control', 'public, max-age=0') + } +} +``` + +## License + +[MIT](LICENSE) + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/serve-static/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-static +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/serve-static/master +[coveralls-url]: https://coveralls.io/r/expressjs/serve-static?branch=master +[node-image]: https://badgen.net/npm/node/serve-static +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/serve-static +[npm-url]: https://npmjs.org/package/serve-static +[npm-version-image]: https://badgen.net/npm/v/serve-static +[travis-image]: https://badgen.net/travis/expressjs/serve-static/master?label=linux +[travis-url]: https://travis-ci.org/expressjs/serve-static diff --git a/node_modules/serve-static/index.js b/node_modules/serve-static/index.js new file mode 100644 index 0000000..b7d3984 --- /dev/null +++ b/node_modules/serve-static/index.js @@ -0,0 +1,210 @@ +/*! + * serve-static + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var parseUrl = require('parseurl') +var resolve = require('path').resolve +var send = require('send') +var url = require('url') + +/** + * Module exports. + * @public + */ + +module.exports = serveStatic +module.exports.mime = send.mime + +/** + * @param {string} root + * @param {object} [options] + * @return {function} + * @public + */ + +function serveStatic (root, options) { + if (!root) { + throw new TypeError('root path required') + } + + if (typeof root !== 'string') { + throw new TypeError('root path must be a string') + } + + // copy options object + var opts = Object.create(options || null) + + // fall-though + var fallthrough = opts.fallthrough !== false + + // default redirect + var redirect = opts.redirect !== false + + // headers listener + var setHeaders = opts.setHeaders + + if (setHeaders && typeof setHeaders !== 'function') { + throw new TypeError('option setHeaders must be function') + } + + // setup options for send + opts.maxage = opts.maxage || opts.maxAge || 0 + opts.root = resolve(root) + + // construct directory listener + var onDirectory = redirect + ? createRedirectDirectoryListener() + : createNotFoundDirectoryListener() + + return function serveStatic (req, res, next) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + if (fallthrough) { + return next() + } + + // method not allowed + res.statusCode = 405 + res.setHeader('Allow', 'GET, HEAD') + res.setHeader('Content-Length', '0') + res.end() + return + } + + var forwardError = !fallthrough + var originalUrl = parseUrl.original(req) + var path = parseUrl(req).pathname + + // make sure redirect occurs at mount + if (path === '/' && originalUrl.pathname.substr(-1) !== '/') { + path = '' + } + + // create send stream + var stream = send(req, path, opts) + + // add directory handler + stream.on('directory', onDirectory) + + // add headers listener + if (setHeaders) { + stream.on('headers', setHeaders) + } + + // add file listener for fallthrough + if (fallthrough) { + stream.on('file', function onFile () { + // once file is determined, always forward error + forwardError = true + }) + } + + // forward errors + stream.on('error', function error (err) { + if (forwardError || !(err.statusCode < 500)) { + next(err) + return + } + + next() + }) + + // pipe + stream.pipe(res) + } +} + +/** + * Collapse all leading slashes into a single slash + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) !== 0x2f /* / */) { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Create a directory listener that just 404s. + * @private + */ + +function createNotFoundDirectoryListener () { + return function notFound () { + this.error(404) + } +} + +/** + * Create a directory listener that performs a redirect. + * @private + */ + +function createRedirectDirectoryListener () { + return function redirect (res) { + if (this.hasTrailingSlash()) { + this.error(404) + return + } + + // get original URL + var originalUrl = parseUrl.original(this.req) + + // append trailing slash + originalUrl.path = null + originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') + + // reformat the URL + var loc = encodeUrl(url.format(originalUrl)) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + + escapeHtml(loc) + '') + + // send redirect response + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) + } +} diff --git a/node_modules/serve-static/package.json b/node_modules/serve-static/package.json new file mode 100644 index 0000000..a60c83f --- /dev/null +++ b/node_modules/serve-static/package.json @@ -0,0 +1,42 @@ +{ + "name": "serve-static", + "description": "Serve static files", + "version": "1.14.1", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "expressjs/serve-static", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.17.1" + }, + "devDependencies": { + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "6.1.4", + "safe-buffer": "5.1.2", + "supertest": "4.0.2" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/set-blocking/CHANGELOG.md b/node_modules/set-blocking/CHANGELOG.md new file mode 100644 index 0000000..03bf591 --- /dev/null +++ b/node_modules/set-blocking/CHANGELOG.md @@ -0,0 +1,26 @@ +# 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. + + +# [2.0.0](https://github.com/yargs/set-blocking/compare/v1.0.0...v2.0.0) (2016-05-17) + + +### Features + +* add an isTTY check ([#3](https://github.com/yargs/set-blocking/issues/3)) ([66ce277](https://github.com/yargs/set-blocking/commit/66ce277)) + + +### BREAKING CHANGES + +* stdio/stderr will not be set to blocking if isTTY === false + + + + +# 1.0.0 (2016-05-14) + + +### Features + +* implemented shim for stream._handle.setBlocking ([6bde0c0](https://github.com/yargs/set-blocking/commit/6bde0c0)) diff --git a/node_modules/set-blocking/LICENSE.txt b/node_modules/set-blocking/LICENSE.txt new file mode 100644 index 0000000..836440b --- /dev/null +++ b/node_modules/set-blocking/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/set-blocking/README.md b/node_modules/set-blocking/README.md new file mode 100644 index 0000000..e93b420 --- /dev/null +++ b/node_modules/set-blocking/README.md @@ -0,0 +1,31 @@ +# set-blocking + +[![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) +[![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) +[![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) + +set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. + +```js +const setBlocking = require('set-blocking') +setBlocking(true) +console.log(someLargeStringToOutput) +``` + +## Historical Context/Word of Warning + +This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on +newer versions of Node.js (`0.12+`), truncating terminal output. + +You should be mindful of the side-effects caused by using `set-blocking`: + +* if your module sets blocking to `true`, it will effect other modules + consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call + `setBlocking(true)` once we already know we are about to call `process.exit(code)`. +* this patch will not apply to subprocesses spawned with `isTTY = true`, this is + the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). + +## License + +ISC diff --git a/node_modules/set-blocking/index.js b/node_modules/set-blocking/index.js new file mode 100644 index 0000000..6f78774 --- /dev/null +++ b/node_modules/set-blocking/index.js @@ -0,0 +1,7 @@ +module.exports = function (blocking) { + [process.stdout, process.stderr].forEach(function (stream) { + if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') { + stream._handle.setBlocking(blocking) + } + }) +} diff --git a/node_modules/set-blocking/package.json b/node_modules/set-blocking/package.json new file mode 100644 index 0000000..c082db7 --- /dev/null +++ b/node_modules/set-blocking/package.json @@ -0,0 +1,42 @@ +{ + "name": "set-blocking", + "version": "2.0.0", + "description": "set blocking stdio and stderr ensuring that terminal output does not truncate", + "main": "index.js", + "scripts": { + "pretest": "standard", + "test": "nyc mocha ./test/*.js", + "coverage": "nyc report --reporter=text-lcov | coveralls", + "version": "standard-version" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/yargs/set-blocking.git" + }, + "keywords": [ + "flush", + "terminal", + "blocking", + "shim", + "stdio", + "stderr" + ], + "author": "Ben Coe ", + "license": "ISC", + "bugs": { + "url": "https://github.com/yargs/set-blocking/issues" + }, + "homepage": "https://github.com/yargs/set-blocking#readme", + "devDependencies": { + "chai": "^3.5.0", + "coveralls": "^2.11.9", + "mocha": "^2.4.5", + "nyc": "^6.4.4", + "standard": "^7.0.1", + "standard-version": "^2.2.1" + }, + "files": [ + "index.js", + "LICENSE.txt" + ] +} \ No newline at end of file diff --git a/node_modules/setprototypeof/LICENSE b/node_modules/setprototypeof/LICENSE new file mode 100644 index 0000000..61afa2f --- /dev/null +++ b/node_modules/setprototypeof/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, Wes Todd + +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/setprototypeof/README.md b/node_modules/setprototypeof/README.md new file mode 100644 index 0000000..f120044 --- /dev/null +++ b/node_modules/setprototypeof/README.md @@ -0,0 +1,31 @@ +# Polyfill for `Object.setPrototypeOf` + +[![NPM Version](https://img.shields.io/npm/v/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![NPM Downloads](https://img.shields.io/npm/dm/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/standard/standard) + +A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. + +## Usage: + +``` +$ npm install --save setprototypeof +``` + +```javascript +var setPrototypeOf = require('setprototypeof') + +var obj = {} +setPrototypeOf(obj, { + foo: function () { + return 'bar' + } +}) +obj.foo() // bar +``` + +TypeScript is also supported: + +```typescript +import setPrototypeOf = require('setprototypeof') +``` diff --git a/node_modules/setprototypeof/index.d.ts b/node_modules/setprototypeof/index.d.ts new file mode 100644 index 0000000..f108ecd --- /dev/null +++ b/node_modules/setprototypeof/index.d.ts @@ -0,0 +1,2 @@ +declare function setPrototypeOf(o: any, proto: object | null): any; +export = setPrototypeOf; diff --git a/node_modules/setprototypeof/index.js b/node_modules/setprototypeof/index.js new file mode 100644 index 0000000..81fd5d7 --- /dev/null +++ b/node_modules/setprototypeof/index.js @@ -0,0 +1,17 @@ +'use strict' +/* eslint no-proto: 0 */ +module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties) + +function setProtoOf (obj, proto) { + obj.__proto__ = proto + return obj +} + +function mixinProperties (obj, proto) { + for (var prop in proto) { + if (!obj.hasOwnProperty(prop)) { + obj[prop] = proto[prop] + } + } + return obj +} diff --git a/node_modules/setprototypeof/package.json b/node_modules/setprototypeof/package.json new file mode 100644 index 0000000..41368e1 --- /dev/null +++ b/node_modules/setprototypeof/package.json @@ -0,0 +1,36 @@ +{ + "name": "setprototypeof", + "version": "1.1.1", + "description": "A small polyfill for Object.setprototypeof", + "main": "index.js", + "typings": "index.d.ts", + "scripts": { + "test": "standard && mocha", + "testallversions": "npm run node010 && npm run node4 && npm run node6 && npm run node9 && npm run node11", + "testversion": "docker run -it --rm -v $(PWD):/usr/src/app -w /usr/src/app node:${NODE_VER} npm install mocha@${MOCHA_VER:-latest} && npm t", + "node010": "NODE_VER=0.10 MOCHA_VER=3 npm run testversion", + "node4": "NODE_VER=4 npm run testversion", + "node6": "NODE_VER=6 npm run testversion", + "node9": "NODE_VER=9 npm run testversion", + "node11": "NODE_VER=11 npm run testversion" + }, + "repository": { + "type": "git", + "url": "https://github.com/wesleytodd/setprototypeof.git" + }, + "keywords": [ + "polyfill", + "object", + "setprototypeof" + ], + "author": "Wes Todd", + "license": "ISC", + "bugs": { + "url": "https://github.com/wesleytodd/setprototypeof/issues" + }, + "homepage": "https://github.com/wesleytodd/setprototypeof", + "devDependencies": { + "mocha": "^5.2.0", + "standard": "^12.0.1" + } +} diff --git a/node_modules/setprototypeof/test/index.js b/node_modules/setprototypeof/test/index.js new file mode 100644 index 0000000..afeb4dd --- /dev/null +++ b/node_modules/setprototypeof/test/index.js @@ -0,0 +1,24 @@ +'use strict' +/* eslint-env mocha */ +/* eslint no-proto: 0 */ +var assert = require('assert') +var setPrototypeOf = require('..') + +describe('setProtoOf(obj, proto)', function () { + it('should merge objects', function () { + var obj = { a: 1, b: 2 } + var proto = { b: 3, c: 4 } + var mergeObj = setPrototypeOf(obj, proto) + + if (Object.getPrototypeOf) { + assert.strictEqual(Object.getPrototypeOf(obj), proto) + } else if ({ __proto__: [] } instanceof Array) { + assert.strictEqual(obj.__proto__, proto) + } else { + assert.strictEqual(obj.a, 1) + assert.strictEqual(obj.b, 2) + assert.strictEqual(obj.c, 4) + } + assert.strictEqual(mergeObj, obj) + }) +}) diff --git a/node_modules/sift/MIT-LICENSE.txt b/node_modules/sift/MIT-LICENSE.txt new file mode 100644 index 0000000..c080d2e --- /dev/null +++ b/node_modules/sift/MIT-LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2015 Craig Condon + +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/sift/README.md b/node_modules/sift/README.md new file mode 100644 index 0000000..4eb62ef --- /dev/null +++ b/node_modules/sift/README.md @@ -0,0 +1,465 @@ +**Installation**: `npm install sift`, or `yarn add sift` + +## Sift is a tiny library for using MongoDB queries in Javascript + +[![Build Status](https://secure.travis-ci.org/crcn/sift.js.png)](https://secure.travis-ci.org/crcn/sift.js) + + + + +**For extended documentation, checkout http://docs.mongodb.org/manual/reference/operator/query/** + +## Features: + +- Supported operators: [\$in](#in), [\$nin](#nin), [\$exists](#exists), [\$gte](#gte), [\$gt](#gt), [\$lte](#lte), [\$lt](#lt), [\$eq](#eq), [\$ne](#ne), [\$mod](#mod), [\$all](#all), [\$and](#and), [\$or](#or), [\$nor](#nor), [\$not](#not), [\$size](#size), [\$type](#type), [\$regex](#regex), [\$where](#where), [\$elemMatch](#elemmatch) +- Regexp searches +- Supports node.js, and web +- Custom Operations +- Tree-shaking (omitting functionality from web app bundles) + +## Examples + +```javascript +import sift from "sift"; + +//intersecting arrays +const result1 = ["hello", "sifted", "array!"].filter( + sift({ $in: ["hello", "world"] }) +); //['hello'] + +//regexp filter +const result2 = ["craig", "john", "jake"].filter(sift(/^j/)); //['john','jake'] + +// function filter +const testFilter = sift({ + //you can also filter against functions + name: function(value) { + return value.length == 5; + } +}); + +const result3 = [ + { + name: "craig" + }, + { + name: "john" + }, + { + name: "jake" + } +].filter(testFilter); // filtered: [{ name: 'craig' }] + +//you can test *single values* against your custom sifter +testFilter({ name: "sarah" }); //true +testFilter({ name: "tim" }); //false +``` + +## API + +### sift(query: MongoQuery, options?: Options): Function + +Creates a filter with all of the built-in MongoDB query operations. + +- `query` - the filter to use against the target array +- `options` + - `operations` - [custom operations](#custom-operations) + - `compare` - compares difference between two values + +Example: + +```javascript +import sift from "sift"; + +const test = sift({ $gt: 5 })); + +console.log(test(6)); // true +console.log(test(4)); // false + +[3, 4, 5, 6, 7].filter(sift({ $exists: true })); // [6, 7] +``` + +### createQueryTester(query: Query, options?: Options): Function + +Creates a filter function **without** built-in MongoDB query operations. This is useful +if you're looking to omit certain operations from application bundles. See [Omitting built-in operations](#omitting-built-in-operations) for more info. + +```javascript +import { createQueryTester, $eq, $in } from "sift"; +const filter = createQueryTester({ $eq: 5 }, { operations: { $eq, $in } }); +``` + +### createEqualsOperation(params: any, ownerQuery: Query, options: Options): Operation + +Used for [custom operations](#custom-operations). + +```javascript +import { createQueryTester, createEqualsOperation, $eq, $in } from "sift"; +const filter = createQueryTester( + { $mod: 5 }, + { + operations: { + $something(mod, ownerQuery, options) { + return createEqualsOperation( + value => value % mod === 0, + ownerQuery, + options + ); + } + } + } +); +filter(10); // true +filter(11); // false +``` + +## Supported Operators + +See MongoDB's [advanced queries](http://www.mongodb.org/display/DOCS/Advanced+Queries) for more info. + +### \$in + +array value must be _\$in_ the given query: + +Intersecting two arrays: + +```javascript +//filtered: ['Brazil'] +["Brazil", "Haiti", "Peru", "Chile"].filter( + sift({ $in: ["Costa Rica", "Brazil"] }) +); +``` + +Here's another example. This acts more like the \$or operator: + +```javascript +[{ name: "Craig", location: "Brazil" }].filter( + sift({ location: { $in: ["Costa Rica", "Brazil"] } }) +); +``` + +### \$nin + +Opposite of \$in: + +```javascript +//filtered: ['Haiti','Peru','Chile'] +["Brazil", "Haiti", "Peru", "Chile"].filter( + sift({ $nin: ["Costa Rica", "Brazil"] }) +); +``` + +### \$exists + +Checks if whether a value exists: + +```javascript +//filtered: ['Craig','Tim'] +sift({ $exists: true })(["Craig", null, "Tim"]); +``` + +You can also filter out values that don't exist + +```javascript +//filtered: [{ name: "Tim" }] +[{ name: "Craig", city: "Minneapolis" }, { name: "Tim" }].filter( + sift({ city: { $exists: false } }) +); +``` + +### \$gte + +Checks if a number is >= value: + +```javascript +//filtered: [2, 3] +[0, 1, 2, 3].filter(sift({ $gte: 2 })); +``` + +### \$gt + +Checks if a number is > value: + +```javascript +//filtered: [3] +[0, 1, 2, 3].filter(sift({ $gt: 2 })); +``` + +### \$lte + +Checks if a number is <= value. + +```javascript +//filtered: [0, 1, 2] +[0, 1, 2, 3].filter(sift({ $lte: 2 })); +``` + +### \$lt + +Checks if number is < value. + +```javascript +//filtered: [0, 1] +[0, 1, 2, 3].filter(sift({ $lt: 2 })); +``` + +### \$eq + +Checks if `query === value`. Note that **\$eq can be omitted**. For **\$eq**, and **\$ne** + +```javascript +//filtered: [{ state: 'MN' }] +[{ state: "MN" }, { state: "CA" }, { state: "WI" }].filter( + sift({ state: { $eq: "MN" } }) +); +``` + +Or: + +```javascript +//filtered: [{ state: 'MN' }] +[{ state: "MN" }, { state: "CA" }, { state: "WI" }].filter( + sift({ state: "MN" }) +); +``` + +### \$ne + +Checks if `query !== value`. + +```javascript +//filtered: [{ state: 'CA' }, { state: 'WI'}] +[{ state: "MN" }, { state: "CA" }, { state: "WI" }].filter( + sift({ state: { $ne: "MN" } }) +); +``` + +### \$mod + +Modulus: + +```javascript +//filtered: [300, 600] +[100, 200, 300, 400, 500, 600].filter(sift({ $mod: [3, 0] })); +``` + +### \$all + +values must match **everything** in array: + +```javascript +//filtered: [ { tags: ['books','programming','travel' ]} ] +[ + { tags: ["books", "programming", "travel"] }, + { tags: ["travel", "cooking"] } +].filter(sift({ tags: { $all: ["books", "programming"] } })); +``` + +### \$and + +ability to use an array of expressions. All expressions must test true. + +```javascript +//filtered: [ { name: 'Craig', state: 'MN' }] + +[ + { name: "Craig", state: "MN" }, + { name: "Tim", state: "MN" }, + { name: "Joe", state: "CA" } +].filter(sift({ $and: [{ name: "Craig" }, { state: "MN" }] })); +``` + +### \$or + +OR array of expressions. + +```javascript +//filtered: [ { name: 'Craig', state: 'MN' }, { name: 'Tim', state: 'MN' }] +[ + { name: "Craig", state: "MN" }, + { name: "Tim", state: "MN" }, + { name: "Joe", state: "CA" } +].filter(sift({ $or: [{ name: "Craig" }, { state: "MN" }] })); +``` + +### \$nor + +opposite of or: + +```javascript +//filtered: [ { name: 'Tim', state: 'MN' }, { name: 'Joe', state: 'CA' }] +[ + { name: "Craig", state: "MN" }, + { name: "Tim", state: "MN" }, + { name: "Joe", state: "CA" } +].filter(sift({ $nor: [{ name: "Craig" }, { state: "MN" }] })); +``` + +### \$size + +Matches an array - must match given size: + +```javascript +//filtered: ['food','cooking'] +[{ tags: ["food", "cooking"] }, { tags: ["traveling"] }].filter( + sift({ tags: { $size: 2 } }) +); +``` + +### \$type + +Matches a values based on the type + +```javascript +[new Date(), 4342, "hello world"].filter(sift({ $type: Date })); //returns single date +[new Date(), 4342, "hello world"].filter(sift({ $type: String })); //returns ['hello world'] +``` + +### \$regex + +Matches values based on the given regular expression + +```javascript +["frank", "fred", "sam", "frost"].filter( + sift({ $regex: /^f/i, $nin: ["frank"] }) +); // ["fred", "frost"] +["frank", "fred", "sam", "frost"].filter( + sift({ $regex: "^f", $options: "i", $nin: ["frank"] }) +); // ["fred", "frost"] +``` + +### \$where + +Matches based on some javascript comparison + +```javascript +[{ name: "frank" }, { name: "joe" }].filter( + sift({ $where: "this.name === 'frank'" }) +); // ["frank"] +[{ name: "frank" }, { name: "joe" }].filter( + sift({ + $where: function() { + return this.name === "frank"; + } + }) +); // ["frank"] +``` + +### \$elemMatch + +Matches elements of array + +```javascript +var bills = [ + { + month: "july", + casts: [ + { + id: 1, + value: 200 + }, + { + id: 2, + value: 1000 + } + ] + }, + { + month: "august", + casts: [ + { + id: 3, + value: 1000 + }, + { + id: 4, + value: 4000 + } + ] + } +]; + +var result = bills.filter( + sift({ + casts: { + $elemMatch: { + value: { $gt: 1000 } + } + } + }) +); // {month:'august', casts:[{id:3, value: 1000},{id: 4, value: 4000}]} +``` + +### \$not + +Not expression: + +```javascript +["craig", "tim", "jake"].filter(sift({ $not: { $in: ["craig", "tim"] } })); //['jake'] +["craig", "tim", "jake"].filter(sift({ $not: { $size: 5 } })); //['tim','jake'] +``` + +### Date comparison + +Mongodb allows you to do date comparisons like so: + +```javascript +db.collection.find({ createdAt: { $gte: "2018-03-22T06:00:00Z" } }); +``` + +In Sift, you'll need to specify a Date object: + +```javascript +collection.find( + sift({ createdAt: { $gte: new Date("2018-03-22T06:00:00Z") } }) +); +``` + +## Custom behavior + +Sift works like MongoDB out of the box, but you're also able to modify the behavior to suite your needs. + +#### Custom operations + +You can register your own custom operations. Here's an example: + +```javascript +import sift, { createEqualsOperation } from "sift"; + +var filter = sift( + { + $customMod: 2 + }, + { + operations: { + $customMod(params, ownerQuery, options) { + return createEqualsOperation( + value => value % params !== 0, + ownerQuery, + options + ); + } + } + } +); + +[1, 2, 3, 4, 5].filter(filter); // 1, 3, 5 +``` + +#### Omitting built-in operations + +You can create a filter function that omits the built-in operations like so: + +```javascript +import { createQueryTester, $in, $all, $nin, $lt } from "sift"; +const test = createQueryTester( + { + $eq: 10 + }, + { $in, $all, $nin, $lt } +); + +[1, 2, 3, 4, 10].filter(test); +``` + +For bundlers like `Webpack` and `Rollup`, operations that aren't used are omitted from application bundles via tree-shaking. diff --git a/node_modules/sift/changelog.md b/node_modules/sift/changelog.md new file mode 100644 index 0000000..8eccb28 --- /dev/null +++ b/node_modules/sift/changelog.md @@ -0,0 +1,77 @@ +## 13.1.0 + +- Added stronger types for queries: https://github.com/crcn/sift.js/issues/197 + +## 13.0.0 + +- Fix behavior discrepancy with Mongo: https://github.com/crcn/sift.js/issues/196 + +## 12.0.0 + +- Fix bug where \$elemMatch tested objects: e.g: `sift({a: {$elemMatch: 1}})({ a: { b: 1}})`. \$elemMatch now expects arrays based on Mongodb syntax. E.g: `sift({a: {$elemMatch: 1}})({ a: { b: 1}})` + +## 11.0.0 + +- new custom operations syntax (see API readme) +- null & undefined are not treated equally (change has been added to keep spec as functionality as possible to MongoDB) +- `select` option has been removed +- `compare` option now expects `boolean` return value instead of an integer +- nested queries are no-longer supported +- `expressions` option is now `operations` +- `operations` parameter now expects new operations API +- ImmutableJS support removed for now +- Remove bower support + +## 9.0.0 + +- (behavior change) toJSON works for vanilla objects. + +## 8.5.1 + +- Fix dependency vulnerability +- Fix #158 + +## 8.5.0 + +- Added `comparable` option (fix https://github.com/crcn/sift.js/issues/156) + +## 8.4.0 + +- Added `compare` option (fix https://github.com/crcn/sift.js/issues/155) + +## 8.3.2 + +- Query _properties_ now excpect exact object shape (based on https://github.com/crcn/sift.js/issues/152). E.g: `[{a: { b: 1}}, {a: { b: 1, c: 2}}]].filter(sift({ a: { b: 1} })) === [{a: {b: 1}]`, and `[{a: 1, b: 1}, {a: 1}]].filter(sift({ a: 1 })) === [{a: 1, b: 1}, {a: 1}]`. + +## 8.0.0 + +- DEPRECATED `indexOf` in favor of `array.findIndex(sift(query))` +- second param is now `options` instead of select function. E.g: `sift(query, { expressions: customExpressions, select: selectValue })` +- DEPRECATED `sift(query, array)`. You must now use `array.filter(sift(query))` +- Queries now expect exact object shape (based on https://github.com/crcn/sift.js/issues/117). E.g: `[{a: 1, b: 1}, {a: 1}]].filter(sift({ a: 1 })) === [{a: 1}]` + +### 7.0.0 + +- Remove global `*.use()` function. +- converted to ES6 + +### 3.3.x + +- `$in` now uses `toString()` when evaluating objects. Fixes #116. + +#### 2.x + +- `use()` now uses a different format: + +```javascript +sift.use({ + $operator: function(a) { + return function(b) { + // compare here + }; + } +}); +``` + +- all operators are traversable now +- fix #58. diff --git a/node_modules/sift/es/index.js b/node_modules/sift/es/index.js new file mode 100644 index 0000000..6f28748 --- /dev/null +++ b/node_modules/sift/es/index.js @@ -0,0 +1,528 @@ +const typeChecker = (type) => { + const typeString = "[object " + type + "]"; + return function (value) { + return getClassName(value) === typeString; + }; +}; +const getClassName = value => Object.prototype.toString.call(value); +const comparable = (value) => { + if (value instanceof Date) { + return value.getTime(); + } + else if (isArray(value)) { + return value.map(comparable); + } + else if (value && typeof value.toJSON === "function") { + return value.toJSON(); + } + return value; +}; +const isArray = typeChecker("Array"); +const isObject = typeChecker("Object"); +const isFunction = typeChecker("Function"); +const isVanillaObject = value => { + return (value && + (value.constructor === Object || + value.constructor === Array || + value.constructor.toString() === "function Object() { [native code] }" || + value.constructor.toString() === "function Array() { [native code] }") && + !value.toJSON); +}; +const equals = (a, b) => { + if (a == null && a == b) { + return true; + } + if (a === b) { + return true; + } + if (Object.prototype.toString.call(a) !== Object.prototype.toString.call(b)) { + return false; + } + if (isArray(a)) { + if (a.length !== b.length) { + return false; + } + for (let i = 0, { length } = a; i < length; i++) { + if (!equals(a[i], b[i])) + return false; + } + return true; + } + else if (isObject(a)) { + if (Object.keys(a).length !== Object.keys(b).length) { + return false; + } + for (const key in a) { + if (!equals(a[key], b[key])) + return false; + } + return true; + } + return false; +}; + +/** + * Walks through each value given the context - used for nested operations. E.g: + * { "person.address": { $eq: "blarg" }} + */ +const walkKeyPathValues = (item, keyPath, next, depth, key, owner) => { + const currentKey = keyPath[depth]; + // if array, then try matching. Might fall through for cases like: + // { $eq: [1, 2, 3] }, [ 1, 2, 3 ]. + if (isArray(item) && isNaN(Number(currentKey))) { + for (let i = 0, { length } = item; i < length; i++) { + // if FALSE is returned, then terminate walker. For operations, this simply + // means that the search critera was met. + if (!walkKeyPathValues(item[i], keyPath, next, depth, i, item)) { + return false; + } + } + } + if (depth === keyPath.length || item == null) { + return next(item, key, owner); + } + return walkKeyPathValues(item[currentKey], keyPath, next, depth + 1, currentKey, item); +}; +class BaseOperation { + constructor(params, owneryQuery, options) { + this.params = params; + this.owneryQuery = owneryQuery; + this.options = options; + this.init(); + } + init() { } + reset() { + this.done = false; + this.keep = false; + } +} +class NamedBaseOperation extends BaseOperation { + constructor(params, owneryQuery, options, name) { + super(params, owneryQuery, options); + this.name = name; + } +} +class GroupOperation extends BaseOperation { + constructor(params, owneryQuery, options, children) { + super(params, owneryQuery, options); + this.children = children; + } + /** + */ + reset() { + this.keep = false; + this.done = false; + for (let i = 0, { length } = this.children; i < length; i++) { + this.children[i].reset(); + } + } + /** + */ + childrenNext(item, key, owner) { + let done = true; + let keep = true; + for (let i = 0, { length } = this.children; i < length; i++) { + const childOperation = this.children[i]; + childOperation.next(item, key, owner); + if (!childOperation.keep) { + keep = false; + } + if (childOperation.done) { + if (!childOperation.keep) { + break; + } + } + else { + done = false; + } + } + this.done = done; + this.keep = keep; + } +} +class NamedGroupOperation extends GroupOperation { + constructor(params, owneryQuery, options, children, name) { + super(params, owneryQuery, options, children); + this.name = name; + } +} +class QueryOperation extends GroupOperation { + /** + */ + next(item, key, parent) { + this.childrenNext(item, key, parent); + } +} +class NestedOperation extends GroupOperation { + constructor(keyPath, params, owneryQuery, options, children) { + super(params, owneryQuery, options, children); + this.keyPath = keyPath; + /** + */ + this._nextNestedValue = (value, key, owner) => { + this.childrenNext(value, key, owner); + return !this.done; + }; + } + /** + */ + next(item, key, parent) { + walkKeyPathValues(item, this.keyPath, this._nextNestedValue, 0, key, parent); + } +} +const createTester = (a, compare) => { + if (a instanceof Function) { + return a; + } + if (a instanceof RegExp) { + return b => { + const result = typeof b === "string" && a.test(b); + a.lastIndex = 0; + return result; + }; + } + const comparableA = comparable(a); + return b => compare(comparableA, comparable(b)); +}; +class EqualsOperation extends BaseOperation { + init() { + this._test = createTester(this.params, this.options.compare); + } + next(item, key, parent) { + if (!Array.isArray(parent) || parent.hasOwnProperty(key)) { + if (this._test(item, key, parent)) { + this.done = true; + this.keep = true; + } + } + } +} +const createEqualsOperation = (params, owneryQuery, options) => new EqualsOperation(params, owneryQuery, options); +class NopeOperation extends BaseOperation { + next() { + this.done = true; + this.keep = false; + } +} +const numericalOperationCreator = (createNumericalOperation) => (params, owneryQuery, options, name) => { + if (params == null) { + return new NopeOperation(params, owneryQuery, options); + } + return createNumericalOperation(params, owneryQuery, options, name); +}; +const numericalOperation = (createTester) => numericalOperationCreator((params, owneryQuery, options) => { + const typeofParams = typeof comparable(params); + const test = createTester(params); + return new EqualsOperation(b => { + return typeof comparable(b) === typeofParams && test(b); + }, owneryQuery, options); +}); +const createNamedOperation = (name, params, parentQuery, options) => { + const operationCreator = options.operations[name]; + if (!operationCreator) { + throw new Error(`Unsupported operation: ${name}`); + } + return operationCreator(params, parentQuery, options, name); +}; +const containsOperation = (query) => { + for (const key in query) { + if (key.charAt(0) === "$") + return true; + } + return false; +}; +const createNestedOperation = (keyPath, nestedQuery, owneryQuery, options) => { + if (containsOperation(nestedQuery)) { + const [selfOperations, nestedOperations] = createQueryOperations(nestedQuery, options); + if (nestedOperations.length) { + throw new Error(`Property queries must contain only operations, or exact objects.`); + } + return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, selfOperations); + } + return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, [ + new EqualsOperation(nestedQuery, owneryQuery, options) + ]); +}; +const createQueryOperation = (query, owneryQuery = null, { compare, operations } = {}) => { + const options = { + compare: compare || equals, + operations: Object.assign({}, operations || {}) + }; + const [selfOperations, nestedOperations] = createQueryOperations(query, options); + const ops = []; + if (selfOperations.length) { + ops.push(new NestedOperation([], query, owneryQuery, options, selfOperations)); + } + ops.push(...nestedOperations); + if (ops.length === 1) { + return ops[0]; + } + return new QueryOperation(query, owneryQuery, options, ops); +}; +const createQueryOperations = (query, options) => { + const selfOperations = []; + const nestedOperations = []; + if (!isVanillaObject(query)) { + selfOperations.push(new EqualsOperation(query, query, options)); + return [selfOperations, nestedOperations]; + } + for (const key in query) { + if (key.charAt(0) === "$") { + const op = createNamedOperation(key, query[key], query, options); + // probably just a flag for another operation (like $options) + if (op != null) { + selfOperations.push(op); + } + } + else { + nestedOperations.push(createNestedOperation(key.split("."), query[key], query, options)); + } + } + return [selfOperations, nestedOperations]; +}; +const createOperationTester = (operation) => (item, key, owner) => { + operation.reset(); + operation.next(item, key, owner); + return operation.keep; +}; +const createQueryTester = (query, options = {}) => { + return createOperationTester(createQueryOperation(query, null, options)); +}; + +class $Ne extends NamedBaseOperation { + init() { + this._test = createTester(this.params, this.options.compare); + } + reset() { + super.reset(); + this.keep = true; + } + next(item) { + if (this._test(item)) { + this.done = true; + this.keep = false; + } + } +} +// https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ +class $ElemMatch extends NamedBaseOperation { + init() { + this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); + } + reset() { + super.reset(); + this._queryOperation.reset(); + } + next(item) { + if (isArray(item)) { + for (let i = 0, { length } = item; i < length; i++) { + // reset query operation since item being tested needs to pass _all_ query + // operations for it to be a success + this._queryOperation.reset(); + // check item + this._queryOperation.next(item[i], i, item); + this.keep = this.keep || this._queryOperation.keep; + } + this.done = true; + } + else { + this.done = false; + this.keep = false; + } + } +} +class $Not extends NamedBaseOperation { + init() { + this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); + } + reset() { + this._queryOperation.reset(); + } + next(item, key, owner) { + this._queryOperation.next(item, key, owner); + this.done = this._queryOperation.done; + this.keep = !this._queryOperation.keep; + } +} +class $Size extends NamedBaseOperation { + init() { } + next(item) { + if (isArray(item) && item.length === this.params) { + this.done = true; + this.keep = true; + } + // if (parent && parent.length === this.params) { + // this.done = true; + // this.keep = true; + // } + } +} +class $Or extends NamedBaseOperation { + init() { + this._ops = this.params.map(op => createQueryOperation(op, null, this.options)); + } + reset() { + this.done = false; + this.keep = false; + for (let i = 0, { length } = this._ops; i < length; i++) { + this._ops[i].reset(); + } + } + next(item, key, owner) { + let done = false; + let success = false; + for (let i = 0, { length } = this._ops; i < length; i++) { + const op = this._ops[i]; + op.next(item, key, owner); + if (op.keep) { + done = true; + success = op.keep; + break; + } + } + this.keep = success; + this.done = done; + } +} +class $Nor extends $Or { + next(item, key, owner) { + super.next(item, key, owner); + this.keep = !this.keep; + } +} +class $In extends NamedBaseOperation { + init() { + this._testers = this.params.map(value => { + if (containsOperation(value)) { + throw new Error(`cannot nest $ under ${this.constructor.name.toLowerCase()}`); + } + return createTester(value, this.options.compare); + }); + } + next(item, key, owner) { + let done = false; + let success = false; + for (let i = 0, { length } = this._testers; i < length; i++) { + const test = this._testers[i]; + if (test(item)) { + done = true; + success = true; + break; + } + } + this.keep = success; + this.done = done; + } +} +class $Nin extends $In { + next(item, key, owner) { + super.next(item, key, owner); + this.keep = !this.keep; + } +} +class $Exists extends NamedBaseOperation { + next(item, key, owner) { + if (owner.hasOwnProperty(key) === this.params) { + this.done = true; + this.keep = true; + } + } +} +class $And extends NamedGroupOperation { + constructor(params, owneryQuery, options, name) { + super(params, owneryQuery, options, params.map(query => createQueryOperation(query, owneryQuery, options)), name); + } + next(item, key, owner) { + this.childrenNext(item, key, owner); + } +} +const $eq = (params, owneryQuery, options) => new EqualsOperation(params, owneryQuery, options); +const $ne = (params, owneryQuery, options, name) => new $Ne(params, owneryQuery, options, name); +const $or = (params, owneryQuery, options, name) => new $Or(params, owneryQuery, options, name); +const $nor = (params, owneryQuery, options, name) => new $Nor(params, owneryQuery, options, name); +const $elemMatch = (params, owneryQuery, options, name) => new $ElemMatch(params, owneryQuery, options, name); +const $nin = (params, owneryQuery, options, name) => new $Nin(params, owneryQuery, options, name); +const $in = (params, owneryQuery, options, name) => new $In(params, owneryQuery, options, name); +const $lt = numericalOperation(params => b => b < params); +const $lte = numericalOperation(params => b => b <= params); +const $gt = numericalOperation(params => b => b > params); +const $gte = numericalOperation(params => b => b >= params); +const $mod = ([mod, equalsValue], owneryQuery, options) => new EqualsOperation(b => comparable(b) % mod === equalsValue, owneryQuery, options); +const $exists = (params, owneryQuery, options, name) => new $Exists(params, owneryQuery, options, name); +const $regex = (pattern, owneryQuery, options) => new EqualsOperation(new RegExp(pattern, owneryQuery.$options), owneryQuery, options); +const $not = (params, owneryQuery, options, name) => new $Not(params, owneryQuery, options, name); +const typeAliases = { + number: v => typeof v === "number", + string: v => typeof v === "string", + bool: v => typeof v === "boolean", + array: v => Array.isArray(v), + null: v => v === null, + timestamp: v => v instanceof Date +}; +const $type = (clazz, owneryQuery, options) => new EqualsOperation(b => { + if (typeof clazz === "string") { + if (!typeAliases[clazz]) { + throw new Error(`Type alias does not exist`); + } + return typeAliases[clazz](b); + } + return b != null ? b instanceof clazz || b.constructor === clazz : false; +}, owneryQuery, options); +const $and = (params, ownerQuery, options, name) => new $And(params, ownerQuery, options, name); +const $all = $and; +const $size = (params, ownerQuery, options) => new $Size(params, ownerQuery, options, "$size"); +const $options = () => null; +const $where = (params, ownerQuery, options) => { + let test; + if (isFunction(params)) { + test = params; + } + else if (!process.env.CSP_ENABLED) { + test = new Function("obj", "return " + params); + } + else { + throw new Error(`In CSP mode, sift does not support strings in "$where" condition`); + } + return new EqualsOperation(b => test.bind(b)(b), ownerQuery, options); +}; + +var defaultOperations = /*#__PURE__*/Object.freeze({ + __proto__: null, + $Size: $Size, + $eq: $eq, + $ne: $ne, + $or: $or, + $nor: $nor, + $elemMatch: $elemMatch, + $nin: $nin, + $in: $in, + $lt: $lt, + $lte: $lte, + $gt: $gt, + $gte: $gte, + $mod: $mod, + $exists: $exists, + $regex: $regex, + $not: $not, + $type: $type, + $and: $and, + $all: $all, + $size: $size, + $options: $options, + $where: $where +}); + +const createDefaultQueryOperation = (query, ownerQuery, { compare, operations } = {}) => { + return createQueryOperation(query, ownerQuery, { + compare: compare, + operations: Object.assign({}, defaultOperations, operations || {}) + }); +}; +const createDefaultQueryTester = (query, options = {}) => { + const op = createDefaultQueryOperation(query, null, options); + return createOperationTester(op); +}; + +export default createDefaultQueryTester; +export { $Size, $all, $and, $elemMatch, $eq, $exists, $gt, $gte, $in, $lt, $lte, $mod, $ne, $nin, $nor, $not, $options, $or, $regex, $size, $type, $where, EqualsOperation, createDefaultQueryOperation, createEqualsOperation, createOperationTester, createQueryOperation, createQueryTester }; +//# sourceMappingURL=index.js.map diff --git a/node_modules/sift/es/index.js.map b/node_modules/sift/es/index.js.map new file mode 100644 index 0000000..7e4c6f5 --- /dev/null +++ b/node_modules/sift/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/utils.ts","../src/core.ts","../src/operations.ts","../src/index.ts"],"sourcesContent":[null,null,null,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C,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;AACxE;;;;;;;;;;;;;;;;;;;;;;;;;;;;MCxUM,2BAA2B,GAAG,CAClC,KAAqB,EACrB,UAAe,EACf,EAAE,OAAO,EAAE,UAAU,KAAuB,EAAE;IAE9C,OAAO,oBAAoB,CAAC,KAAK,EAAE,UAAU,EAAE;QAC7C,OAAO,EAAE,OAAO;QAChB,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,iBAAiB,EAAE,UAAU,IAAI,EAAE,CAAC;KACnE,CAAC,CAAC;AACL,EAAE;AAEF,MAAM,wBAAwB,GAAG,CAC/B,KAAqB,EACrB,UAA4B,EAAE;IAE9B,MAAM,EAAE,GAAG,2BAA2B,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IAC7D,OAAO,qBAAqB,CAAC,EAAE,CAAC,CAAC;AACnC,CAAC;;;;;"} \ No newline at end of file diff --git a/node_modules/sift/es5m/index.js b/node_modules/sift/es5m/index.js new file mode 100644 index 0000000..62af37b --- /dev/null +++ b/node_modules/sift/es5m/index.js @@ -0,0 +1,652 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var typeChecker = function (type) { + var typeString = "[object " + type + "]"; + return function (value) { + return getClassName(value) === typeString; + }; +}; +var getClassName = function (value) { return Object.prototype.toString.call(value); }; +var comparable = function (value) { + if (value instanceof Date) { + return value.getTime(); + } + else if (isArray(value)) { + return value.map(comparable); + } + else if (value && typeof value.toJSON === "function") { + return value.toJSON(); + } + return value; +}; +var isArray = typeChecker("Array"); +var isObject = typeChecker("Object"); +var isFunction = typeChecker("Function"); +var isVanillaObject = function (value) { + return (value && + (value.constructor === Object || + value.constructor === Array || + value.constructor.toString() === "function Object() { [native code] }" || + value.constructor.toString() === "function Array() { [native code] }") && + !value.toJSON); +}; +var equals = function (a, b) { + if (a == null && a == b) { + return true; + } + if (a === b) { + return true; + } + if (Object.prototype.toString.call(a) !== Object.prototype.toString.call(b)) { + return false; + } + if (isArray(a)) { + if (a.length !== b.length) { + return false; + } + for (var i = 0, length_1 = a.length; i < length_1; i++) { + if (!equals(a[i], b[i])) + return false; + } + return true; + } + else if (isObject(a)) { + if (Object.keys(a).length !== Object.keys(b).length) { + return false; + } + for (var key in a) { + if (!equals(a[key], b[key])) + return false; + } + return true; + } + return false; +}; + +/** + * Walks through each value given the context - used for nested operations. E.g: + * { "person.address": { $eq: "blarg" }} + */ +var walkKeyPathValues = function (item, keyPath, next, depth, key, owner) { + var currentKey = keyPath[depth]; + // if array, then try matching. Might fall through for cases like: + // { $eq: [1, 2, 3] }, [ 1, 2, 3 ]. + if (isArray(item) && isNaN(Number(currentKey))) { + for (var i = 0, length_1 = item.length; i < length_1; i++) { + // if FALSE is returned, then terminate walker. For operations, this simply + // means that the search critera was met. + if (!walkKeyPathValues(item[i], keyPath, next, depth, i, item)) { + return false; + } + } + } + if (depth === keyPath.length || item == null) { + return next(item, key, owner); + } + return walkKeyPathValues(item[currentKey], keyPath, next, depth + 1, currentKey, item); +}; +var BaseOperation = /** @class */ (function () { + function BaseOperation(params, owneryQuery, options) { + this.params = params; + this.owneryQuery = owneryQuery; + this.options = options; + this.init(); + } + BaseOperation.prototype.init = function () { }; + BaseOperation.prototype.reset = function () { + this.done = false; + this.keep = false; + }; + return BaseOperation; +}()); +var NamedBaseOperation = /** @class */ (function (_super) { + __extends(NamedBaseOperation, _super); + function NamedBaseOperation(params, owneryQuery, options, name) { + var _this = _super.call(this, params, owneryQuery, options) || this; + _this.name = name; + return _this; + } + return NamedBaseOperation; +}(BaseOperation)); +var GroupOperation = /** @class */ (function (_super) { + __extends(GroupOperation, _super); + function GroupOperation(params, owneryQuery, options, children) { + var _this = _super.call(this, params, owneryQuery, options) || this; + _this.children = children; + return _this; + } + /** + */ + GroupOperation.prototype.reset = function () { + this.keep = false; + this.done = false; + for (var i = 0, length_2 = this.children.length; i < length_2; i++) { + this.children[i].reset(); + } + }; + /** + */ + GroupOperation.prototype.childrenNext = function (item, key, owner) { + var done = true; + var keep = true; + for (var i = 0, length_3 = this.children.length; i < length_3; i++) { + var childOperation = this.children[i]; + childOperation.next(item, key, owner); + if (!childOperation.keep) { + keep = false; + } + if (childOperation.done) { + if (!childOperation.keep) { + break; + } + } + else { + done = false; + } + } + this.done = done; + this.keep = keep; + }; + return GroupOperation; +}(BaseOperation)); +var NamedGroupOperation = /** @class */ (function (_super) { + __extends(NamedGroupOperation, _super); + function NamedGroupOperation(params, owneryQuery, options, children, name) { + var _this = _super.call(this, params, owneryQuery, options, children) || this; + _this.name = name; + return _this; + } + return NamedGroupOperation; +}(GroupOperation)); +var QueryOperation = /** @class */ (function (_super) { + __extends(QueryOperation, _super); + function QueryOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + */ + QueryOperation.prototype.next = function (item, key, parent) { + this.childrenNext(item, key, parent); + }; + return QueryOperation; +}(GroupOperation)); +var NestedOperation = /** @class */ (function (_super) { + __extends(NestedOperation, _super); + function NestedOperation(keyPath, params, owneryQuery, options, children) { + var _this = _super.call(this, params, owneryQuery, options, children) || this; + _this.keyPath = keyPath; + /** + */ + _this._nextNestedValue = function (value, key, owner) { + _this.childrenNext(value, key, owner); + return !_this.done; + }; + return _this; + } + /** + */ + NestedOperation.prototype.next = function (item, key, parent) { + walkKeyPathValues(item, this.keyPath, this._nextNestedValue, 0, key, parent); + }; + return NestedOperation; +}(GroupOperation)); +var createTester = function (a, compare) { + if (a instanceof Function) { + return a; + } + if (a instanceof RegExp) { + return function (b) { + var result = typeof b === "string" && a.test(b); + a.lastIndex = 0; + return result; + }; + } + var comparableA = comparable(a); + return function (b) { return compare(comparableA, comparable(b)); }; +}; +var EqualsOperation = /** @class */ (function (_super) { + __extends(EqualsOperation, _super); + function EqualsOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + EqualsOperation.prototype.init = function () { + this._test = createTester(this.params, this.options.compare); + }; + EqualsOperation.prototype.next = function (item, key, parent) { + if (!Array.isArray(parent) || parent.hasOwnProperty(key)) { + if (this._test(item, key, parent)) { + this.done = true; + this.keep = true; + } + } + }; + return EqualsOperation; +}(BaseOperation)); +var createEqualsOperation = function (params, owneryQuery, options) { return new EqualsOperation(params, owneryQuery, options); }; +var NopeOperation = /** @class */ (function (_super) { + __extends(NopeOperation, _super); + function NopeOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + NopeOperation.prototype.next = function () { + this.done = true; + this.keep = false; + }; + return NopeOperation; +}(BaseOperation)); +var numericalOperationCreator = function (createNumericalOperation) { return function (params, owneryQuery, options, name) { + if (params == null) { + return new NopeOperation(params, owneryQuery, options); + } + return createNumericalOperation(params, owneryQuery, options, name); +}; }; +var numericalOperation = function (createTester) { + return numericalOperationCreator(function (params, owneryQuery, options) { + var typeofParams = typeof comparable(params); + var test = createTester(params); + return new EqualsOperation(function (b) { + return typeof comparable(b) === typeofParams && test(b); + }, owneryQuery, options); + }); +}; +var createNamedOperation = function (name, params, parentQuery, options) { + var operationCreator = options.operations[name]; + if (!operationCreator) { + throw new Error("Unsupported operation: " + name); + } + return operationCreator(params, parentQuery, options, name); +}; +var containsOperation = function (query) { + for (var key in query) { + if (key.charAt(0) === "$") + return true; + } + return false; +}; +var createNestedOperation = function (keyPath, nestedQuery, owneryQuery, options) { + if (containsOperation(nestedQuery)) { + var _a = createQueryOperations(nestedQuery, options), selfOperations = _a[0], nestedOperations = _a[1]; + if (nestedOperations.length) { + throw new Error("Property queries must contain only operations, or exact objects."); + } + return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, selfOperations); + } + return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, [ + new EqualsOperation(nestedQuery, owneryQuery, options) + ]); +}; +var createQueryOperation = function (query, owneryQuery, _a) { + if (owneryQuery === void 0) { owneryQuery = null; } + var _b = _a === void 0 ? {} : _a, compare = _b.compare, operations = _b.operations; + var options = { + compare: compare || equals, + operations: Object.assign({}, operations || {}) + }; + var _c = createQueryOperations(query, options), selfOperations = _c[0], nestedOperations = _c[1]; + var ops = []; + if (selfOperations.length) { + ops.push(new NestedOperation([], query, owneryQuery, options, selfOperations)); + } + ops.push.apply(ops, nestedOperations); + if (ops.length === 1) { + return ops[0]; + } + return new QueryOperation(query, owneryQuery, options, ops); +}; +var createQueryOperations = function (query, options) { + var selfOperations = []; + var nestedOperations = []; + if (!isVanillaObject(query)) { + selfOperations.push(new EqualsOperation(query, query, options)); + return [selfOperations, nestedOperations]; + } + for (var key in query) { + if (key.charAt(0) === "$") { + var op = createNamedOperation(key, query[key], query, options); + // probably just a flag for another operation (like $options) + if (op != null) { + selfOperations.push(op); + } + } + else { + nestedOperations.push(createNestedOperation(key.split("."), query[key], query, options)); + } + } + return [selfOperations, nestedOperations]; +}; +var createOperationTester = function (operation) { return function (item, key, owner) { + operation.reset(); + operation.next(item, key, owner); + return operation.keep; +}; }; +var createQueryTester = function (query, options) { + if (options === void 0) { options = {}; } + return createOperationTester(createQueryOperation(query, null, options)); +}; + +var $Ne = /** @class */ (function (_super) { + __extends($Ne, _super); + function $Ne() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Ne.prototype.init = function () { + this._test = createTester(this.params, this.options.compare); + }; + $Ne.prototype.reset = function () { + _super.prototype.reset.call(this); + this.keep = true; + }; + $Ne.prototype.next = function (item) { + if (this._test(item)) { + this.done = true; + this.keep = false; + } + }; + return $Ne; +}(NamedBaseOperation)); +// https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ +var $ElemMatch = /** @class */ (function (_super) { + __extends($ElemMatch, _super); + function $ElemMatch() { + return _super !== null && _super.apply(this, arguments) || this; + } + $ElemMatch.prototype.init = function () { + this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); + }; + $ElemMatch.prototype.reset = function () { + _super.prototype.reset.call(this); + this._queryOperation.reset(); + }; + $ElemMatch.prototype.next = function (item) { + if (isArray(item)) { + for (var i = 0, length_1 = item.length; i < length_1; i++) { + // reset query operation since item being tested needs to pass _all_ query + // operations for it to be a success + this._queryOperation.reset(); + // check item + this._queryOperation.next(item[i], i, item); + this.keep = this.keep || this._queryOperation.keep; + } + this.done = true; + } + else { + this.done = false; + this.keep = false; + } + }; + return $ElemMatch; +}(NamedBaseOperation)); +var $Not = /** @class */ (function (_super) { + __extends($Not, _super); + function $Not() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Not.prototype.init = function () { + this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); + }; + $Not.prototype.reset = function () { + this._queryOperation.reset(); + }; + $Not.prototype.next = function (item, key, owner) { + this._queryOperation.next(item, key, owner); + this.done = this._queryOperation.done; + this.keep = !this._queryOperation.keep; + }; + return $Not; +}(NamedBaseOperation)); +var $Size = /** @class */ (function (_super) { + __extends($Size, _super); + function $Size() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Size.prototype.init = function () { }; + $Size.prototype.next = function (item) { + if (isArray(item) && item.length === this.params) { + this.done = true; + this.keep = true; + } + // if (parent && parent.length === this.params) { + // this.done = true; + // this.keep = true; + // } + }; + return $Size; +}(NamedBaseOperation)); +var $Or = /** @class */ (function (_super) { + __extends($Or, _super); + function $Or() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Or.prototype.init = function () { + var _this = this; + this._ops = this.params.map(function (op) { + return createQueryOperation(op, null, _this.options); + }); + }; + $Or.prototype.reset = function () { + this.done = false; + this.keep = false; + for (var i = 0, length_2 = this._ops.length; i < length_2; i++) { + this._ops[i].reset(); + } + }; + $Or.prototype.next = function (item, key, owner) { + var done = false; + var success = false; + for (var i = 0, length_3 = this._ops.length; i < length_3; i++) { + var op = this._ops[i]; + op.next(item, key, owner); + if (op.keep) { + done = true; + success = op.keep; + break; + } + } + this.keep = success; + this.done = done; + }; + return $Or; +}(NamedBaseOperation)); +var $Nor = /** @class */ (function (_super) { + __extends($Nor, _super); + function $Nor() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Nor.prototype.next = function (item, key, owner) { + _super.prototype.next.call(this, item, key, owner); + this.keep = !this.keep; + }; + return $Nor; +}($Or)); +var $In = /** @class */ (function (_super) { + __extends($In, _super); + function $In() { + return _super !== null && _super.apply(this, arguments) || this; + } + $In.prototype.init = function () { + var _this = this; + this._testers = this.params.map(function (value) { + if (containsOperation(value)) { + throw new Error("cannot nest $ under " + _this.constructor.name.toLowerCase()); + } + return createTester(value, _this.options.compare); + }); + }; + $In.prototype.next = function (item, key, owner) { + var done = false; + var success = false; + for (var i = 0, length_4 = this._testers.length; i < length_4; i++) { + var test = this._testers[i]; + if (test(item)) { + done = true; + success = true; + break; + } + } + this.keep = success; + this.done = done; + }; + return $In; +}(NamedBaseOperation)); +var $Nin = /** @class */ (function (_super) { + __extends($Nin, _super); + function $Nin() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Nin.prototype.next = function (item, key, owner) { + _super.prototype.next.call(this, item, key, owner); + this.keep = !this.keep; + }; + return $Nin; +}($In)); +var $Exists = /** @class */ (function (_super) { + __extends($Exists, _super); + function $Exists() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Exists.prototype.next = function (item, key, owner) { + if (owner.hasOwnProperty(key) === this.params) { + this.done = true; + this.keep = true; + } + }; + return $Exists; +}(NamedBaseOperation)); +var $And = /** @class */ (function (_super) { + __extends($And, _super); + function $And(params, owneryQuery, options, name) { + return _super.call(this, params, owneryQuery, options, params.map(function (query) { return createQueryOperation(query, owneryQuery, options); }), name) || this; + } + $And.prototype.next = function (item, key, owner) { + this.childrenNext(item, key, owner); + }; + return $And; +}(NamedGroupOperation)); +var $eq = function (params, owneryQuery, options) { + return new EqualsOperation(params, owneryQuery, options); +}; +var $ne = function (params, owneryQuery, options, name) { return new $Ne(params, owneryQuery, options, name); }; +var $or = function (params, owneryQuery, options, name) { return new $Or(params, owneryQuery, options, name); }; +var $nor = function (params, owneryQuery, options, name) { return new $Nor(params, owneryQuery, options, name); }; +var $elemMatch = function (params, owneryQuery, options, name) { return new $ElemMatch(params, owneryQuery, options, name); }; +var $nin = function (params, owneryQuery, options, name) { return new $Nin(params, owneryQuery, options, name); }; +var $in = function (params, owneryQuery, options, name) { return new $In(params, owneryQuery, options, name); }; +var $lt = numericalOperation(function (params) { return function (b) { return b < params; }; }); +var $lte = numericalOperation(function (params) { return function (b) { return b <= params; }; }); +var $gt = numericalOperation(function (params) { return function (b) { return b > params; }; }); +var $gte = numericalOperation(function (params) { return function (b) { return b >= params; }; }); +var $mod = function (_a, owneryQuery, options) { + var mod = _a[0], equalsValue = _a[1]; + return new EqualsOperation(function (b) { return comparable(b) % mod === equalsValue; }, owneryQuery, options); +}; +var $exists = function (params, owneryQuery, options, name) { return new $Exists(params, owneryQuery, options, name); }; +var $regex = function (pattern, owneryQuery, options) { + return new EqualsOperation(new RegExp(pattern, owneryQuery.$options), owneryQuery, options); +}; +var $not = function (params, owneryQuery, options, name) { return new $Not(params, owneryQuery, options, name); }; +var typeAliases = { + number: function (v) { return typeof v === "number"; }, + string: function (v) { return typeof v === "string"; }, + bool: function (v) { return typeof v === "boolean"; }, + array: function (v) { return Array.isArray(v); }, + null: function (v) { return v === null; }, + timestamp: function (v) { return v instanceof Date; } +}; +var $type = function (clazz, owneryQuery, options) { + return new EqualsOperation(function (b) { + if (typeof clazz === "string") { + if (!typeAliases[clazz]) { + throw new Error("Type alias does not exist"); + } + return typeAliases[clazz](b); + } + return b != null ? b instanceof clazz || b.constructor === clazz : false; + }, owneryQuery, options); +}; +var $and = function (params, ownerQuery, options, name) { return new $And(params, ownerQuery, options, name); }; +var $all = $and; +var $size = function (params, ownerQuery, options) { return new $Size(params, ownerQuery, options, "$size"); }; +var $options = function () { return null; }; +var $where = function (params, ownerQuery, options) { + var test; + if (isFunction(params)) { + test = params; + } + else if (!process.env.CSP_ENABLED) { + test = new Function("obj", "return " + params); + } + else { + throw new Error("In CSP mode, sift does not support strings in \"$where\" condition"); + } + return new EqualsOperation(function (b) { return test.bind(b)(b); }, ownerQuery, options); +}; + +var defaultOperations = /*#__PURE__*/Object.freeze({ + __proto__: null, + $Size: $Size, + $eq: $eq, + $ne: $ne, + $or: $or, + $nor: $nor, + $elemMatch: $elemMatch, + $nin: $nin, + $in: $in, + $lt: $lt, + $lte: $lte, + $gt: $gt, + $gte: $gte, + $mod: $mod, + $exists: $exists, + $regex: $regex, + $not: $not, + $type: $type, + $and: $and, + $all: $all, + $size: $size, + $options: $options, + $where: $where +}); + +var createDefaultQueryOperation = function (query, ownerQuery, _a) { + var _b = _a === void 0 ? {} : _a, compare = _b.compare, operations = _b.operations; + return createQueryOperation(query, ownerQuery, { + compare: compare, + operations: Object.assign({}, defaultOperations, operations || {}) + }); +}; +var createDefaultQueryTester = function (query, options) { + if (options === void 0) { options = {}; } + var op = createDefaultQueryOperation(query, null, options); + return createOperationTester(op); +}; + +export default createDefaultQueryTester; +export { $Size, $all, $and, $elemMatch, $eq, $exists, $gt, $gte, $in, $lt, $lte, $mod, $ne, $nin, $nor, $not, $options, $or, $regex, $size, $type, $where, EqualsOperation, createDefaultQueryOperation, createEqualsOperation, createOperationTester, createQueryOperation, createQueryTester }; +//# sourceMappingURL=index.js.map diff --git a/node_modules/sift/es5m/index.js.map b/node_modules/sift/es5m/index.js.map new file mode 100644 index 0000000..9e9228d --- /dev/null +++ b/node_modules/sift/es5m/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/core.ts","../src/operations.ts","../src/index.ts"],"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 */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\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, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\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 (Object.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, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC,EAAE;AACnC,IAAI,aAAa,GAAG,MAAM,CAAC,cAAc;AACzC,SAAS,EAAE,SAAS,EAAE,EAAE,EAAE,YAAY,KAAK,IAAI,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,CAAC;AACpF,QAAQ,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACnF,IAAI,OAAO,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAC/B,CAAC,CAAC;AACF;AACO,SAAS,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE;AAChC,IAAI,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACxB,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AAC,MAAM,CAAC,EAAE;QACtB,IAAI,GAAG,MAAM,CAAC;KACf;SAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,EAAE;QACnC,IAAI,GAAG,IAAI,QAAQ,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAAC,CAAC;KAChD;SAAM;QACL,MAAM,IAAI,KAAK,CACb,oEAAkE,CACnE,CAAC;KACH;IAED,OAAO,IAAI,eAAe,CAAC,UAAA,CAAC,IAAI,OAAA,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAA,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;AACxE;;;;;;;;;;;;;;;;;;;;;;;;;;;;ICxUM,2BAA2B,GAAG,UAClC,KAAqB,EACrB,UAAe,EACf,EAA8C;QAA9C,4BAA8C,EAA5C,oBAAO,EAAE,0BAAU;IAErB,OAAO,oBAAoB,CAAC,KAAK,EAAE,UAAU,EAAE;QAC7C,OAAO,EAAE,OAAO;QAChB,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,iBAAiB,EAAE,UAAU,IAAI,EAAE,CAAC;KACnE,CAAC,CAAC;AACL,EAAE;AAEF,IAAM,wBAAwB,GAAG,UAC/B,KAAqB,EACrB,OAA8B;IAA9B,wBAAA,EAAA,YAA8B;IAE9B,IAAM,EAAE,GAAG,2BAA2B,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IAC7D,OAAO,qBAAqB,CAAC,EAAE,CAAC,CAAC;AACnC,CAAC;;;;;"} \ No newline at end of file diff --git a/node_modules/sift/index.d.ts b/node_modules/sift/index.d.ts new file mode 100644 index 0000000..2b82571 --- /dev/null +++ b/node_modules/sift/index.d.ts @@ -0,0 +1,4 @@ +import sift from "./lib"; + +export default sift; +export * from "./lib"; diff --git a/node_modules/sift/index.js b/node_modules/sift/index.js new file mode 100644 index 0000000..449294a --- /dev/null +++ b/node_modules/sift/index.js @@ -0,0 +1,4 @@ +const lib = require("./lib"); + +module.exports = lib.default; +Object.assign(module.exports, lib); diff --git a/node_modules/sift/lib/core.d.ts b/node_modules/sift/lib/core.d.ts new file mode 100644 index 0000000..35f1a39 --- /dev/null +++ b/node_modules/sift/lib/core.d.ts @@ -0,0 +1,115 @@ +import { Key, Comparator } from "./utils"; +export interface Operation { + readonly keep: boolean; + readonly done: boolean; + reset(): any; + next(item: TItem, key?: Key, owner?: any): any; +} +export declare type Tester = (item: any, key?: Key, owner?: any) => boolean; +export interface NamedOperation { + name: string; +} +export declare type OperationCreator = (params: any, parentQuery: any, options: Options, name: string) => Operation; +declare type BasicValueQuery = { + $eq?: TValue; + $ne?: TValue; + $lt?: TValue; + $gt?: TValue; + $lte?: TValue; + $gte?: TValue; + $in?: TValue[]; + $nin?: TValue[]; + $all?: TValue[]; + $mod?: [number, number]; + $exists?: boolean; + $regex?: string | RegExp; + $size?: number; + $where?: ((this: TValue) => boolean) | string; + $options?: "i" | "g" | "m" | "u"; + $type?: Function; + $not?: NestedQuery; + $or?: NestedQuery[]; + $nor?: NestedQuery[]; + $and?: NestedQuery[]; +}; +declare type ArrayValueQuery = { + $elemMatch?: Query; +} & BasicValueQuery; +declare type Unpacked = T extends (infer U)[] ? U : T; +declare type ValueQuery = TValue extends Array ? ArrayValueQuery> : BasicValueQuery; +declare type NotObject = string | number | Date | boolean | Array; +declare type ShapeQuery = TItemSchema extends NotObject ? {} : { + [k in keyof TItemSchema]?: TItemSchema[k] | ValueQuery; +}; +declare type NestedQuery = ValueQuery & ShapeQuery; +export declare type Query = TItemSchema | RegExp | NestedQuery; +declare abstract class BaseOperation implements Operation { + readonly params: TParams; + readonly owneryQuery: any; + readonly options: Options; + keep: boolean; + done: boolean; + constructor(params: TParams, owneryQuery: any, options: Options); + protected init(): void; + reset(): void; + abstract next(item: any, key: Key, parent: any): any; +} +export declare abstract class NamedBaseOperation extends BaseOperation implements NamedOperation { + readonly name: string; + constructor(params: TParams, owneryQuery: any, options: Options, name: string); +} +declare abstract class GroupOperation extends BaseOperation { + readonly children: Operation[]; + keep: boolean; + done: boolean; + constructor(params: any, owneryQuery: any, options: Options, children: Operation[]); + /** + */ + reset(): void; + abstract next(item: any, key: Key, owner: any): any; + /** + */ + protected childrenNext(item: any, key: Key, owner: any): void; +} +export declare abstract class NamedGroupOperation extends GroupOperation implements NamedOperation { + readonly name: string; + constructor(params: any, owneryQuery: any, options: Options, children: Operation[], name: string); +} +export declare class QueryOperation extends GroupOperation { + /** + */ + next(item: TItem, key: Key, parent: any): void; +} +export declare class NestedOperation extends GroupOperation { + readonly keyPath: Key[]; + constructor(keyPath: Key[], params: any, owneryQuery: any, options: Options, children: Operation[]); + /** + */ + next(item: any, key: Key, parent: any): void; + /** + */ + private _nextNestedValue; +} +export declare const createTester: (a: any, compare: Comparator) => any; +export declare class EqualsOperation extends BaseOperation { + private _test; + init(): void; + next(item: any, key: Key, parent: any): void; +} +export declare const createEqualsOperation: (params: any, owneryQuery: any, options: Options) => EqualsOperation; +export declare class NopeOperation extends BaseOperation { + next(): void; +} +export declare const numericalOperationCreator: (createNumericalOperation: OperationCreator) => (params: any, owneryQuery: any, options: Options, name: string) => Operation | NopeOperation; +export declare const numericalOperation: (createTester: (any: any) => Tester) => (params: any, owneryQuery: any, options: Options, name: string) => Operation | NopeOperation; +export declare type Options = { + operations: { + [identifier: string]: OperationCreator; + }; + compare: (a: any, b: any) => boolean; +}; +export declare const containsOperation: (query: any) => boolean; +export declare const createQueryOperation: (query: Query, owneryQuery?: any, { compare, operations }?: Partial) => QueryOperation; +export declare const createOperationTester: (operation: Operation) => (item: TItem, key?: string | number, owner?: any) => boolean; +export declare const createQueryTester: (query: Query, options?: Partial) => (item: TItem, key?: string | number, owner?: any) => boolean; +export {}; diff --git a/node_modules/sift/lib/index.d.ts b/node_modules/sift/lib/index.d.ts new file mode 100644 index 0000000..632fa0a --- /dev/null +++ b/node_modules/sift/lib/index.d.ts @@ -0,0 +1,6 @@ +import { Query, Options, createQueryTester, EqualsOperation, createQueryOperation, createEqualsOperation, createOperationTester } from "./core"; +declare const createDefaultQueryOperation: (query: Query, ownerQuery: any, { compare, operations }?: Partial) => import("./core").QueryOperation; +declare const createDefaultQueryTester: (query: Query, options?: Partial) => (item: unknown, key?: string | number, owner?: any) => boolean; +export { Query, EqualsOperation, createQueryTester, createOperationTester, createDefaultQueryOperation, createEqualsOperation, createQueryOperation }; +export * from "./operations"; +export default createDefaultQueryTester; diff --git a/node_modules/sift/lib/index.js b/node_modules/sift/lib/index.js new file mode 100644 index 0000000..9f8a650 --- /dev/null +++ b/node_modules/sift/lib/index.js @@ -0,0 +1,689 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.sift = {})); +}(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 */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var typeChecker = function (type) { + var typeString = "[object " + type + "]"; + return function (value) { + return getClassName(value) === typeString; + }; + }; + var getClassName = function (value) { return Object.prototype.toString.call(value); }; + var comparable = function (value) { + if (value instanceof Date) { + return value.getTime(); + } + else if (isArray(value)) { + return value.map(comparable); + } + else if (value && typeof value.toJSON === "function") { + return value.toJSON(); + } + return value; + }; + var isArray = typeChecker("Array"); + var isObject = typeChecker("Object"); + var isFunction = typeChecker("Function"); + var isVanillaObject = function (value) { + return (value && + (value.constructor === Object || + value.constructor === Array || + value.constructor.toString() === "function Object() { [native code] }" || + value.constructor.toString() === "function Array() { [native code] }") && + !value.toJSON); + }; + var equals = function (a, b) { + if (a == null && a == b) { + return true; + } + if (a === b) { + return true; + } + if (Object.prototype.toString.call(a) !== Object.prototype.toString.call(b)) { + return false; + } + if (isArray(a)) { + if (a.length !== b.length) { + return false; + } + for (var i = 0, length_1 = a.length; i < length_1; i++) { + if (!equals(a[i], b[i])) + return false; + } + return true; + } + else if (isObject(a)) { + if (Object.keys(a).length !== Object.keys(b).length) { + return false; + } + for (var key in a) { + if (!equals(a[key], b[key])) + return false; + } + return true; + } + return false; + }; + + /** + * Walks through each value given the context - used for nested operations. E.g: + * { "person.address": { $eq: "blarg" }} + */ + var walkKeyPathValues = function (item, keyPath, next, depth, key, owner) { + var currentKey = keyPath[depth]; + // if array, then try matching. Might fall through for cases like: + // { $eq: [1, 2, 3] }, [ 1, 2, 3 ]. + if (isArray(item) && isNaN(Number(currentKey))) { + for (var i = 0, length_1 = item.length; i < length_1; i++) { + // if FALSE is returned, then terminate walker. For operations, this simply + // means that the search critera was met. + if (!walkKeyPathValues(item[i], keyPath, next, depth, i, item)) { + return false; + } + } + } + if (depth === keyPath.length || item == null) { + return next(item, key, owner); + } + return walkKeyPathValues(item[currentKey], keyPath, next, depth + 1, currentKey, item); + }; + var BaseOperation = /** @class */ (function () { + function BaseOperation(params, owneryQuery, options) { + this.params = params; + this.owneryQuery = owneryQuery; + this.options = options; + this.init(); + } + BaseOperation.prototype.init = function () { }; + BaseOperation.prototype.reset = function () { + this.done = false; + this.keep = false; + }; + return BaseOperation; + }()); + var NamedBaseOperation = /** @class */ (function (_super) { + __extends(NamedBaseOperation, _super); + function NamedBaseOperation(params, owneryQuery, options, name) { + var _this = _super.call(this, params, owneryQuery, options) || this; + _this.name = name; + return _this; + } + return NamedBaseOperation; + }(BaseOperation)); + var GroupOperation = /** @class */ (function (_super) { + __extends(GroupOperation, _super); + function GroupOperation(params, owneryQuery, options, children) { + var _this = _super.call(this, params, owneryQuery, options) || this; + _this.children = children; + return _this; + } + /** + */ + GroupOperation.prototype.reset = function () { + this.keep = false; + this.done = false; + for (var i = 0, length_2 = this.children.length; i < length_2; i++) { + this.children[i].reset(); + } + }; + /** + */ + GroupOperation.prototype.childrenNext = function (item, key, owner) { + var done = true; + var keep = true; + for (var i = 0, length_3 = this.children.length; i < length_3; i++) { + var childOperation = this.children[i]; + childOperation.next(item, key, owner); + if (!childOperation.keep) { + keep = false; + } + if (childOperation.done) { + if (!childOperation.keep) { + break; + } + } + else { + done = false; + } + } + this.done = done; + this.keep = keep; + }; + return GroupOperation; + }(BaseOperation)); + var NamedGroupOperation = /** @class */ (function (_super) { + __extends(NamedGroupOperation, _super); + function NamedGroupOperation(params, owneryQuery, options, children, name) { + var _this = _super.call(this, params, owneryQuery, options, children) || this; + _this.name = name; + return _this; + } + return NamedGroupOperation; + }(GroupOperation)); + var QueryOperation = /** @class */ (function (_super) { + __extends(QueryOperation, _super); + function QueryOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + */ + QueryOperation.prototype.next = function (item, key, parent) { + this.childrenNext(item, key, parent); + }; + return QueryOperation; + }(GroupOperation)); + var NestedOperation = /** @class */ (function (_super) { + __extends(NestedOperation, _super); + function NestedOperation(keyPath, params, owneryQuery, options, children) { + var _this = _super.call(this, params, owneryQuery, options, children) || this; + _this.keyPath = keyPath; + /** + */ + _this._nextNestedValue = function (value, key, owner) { + _this.childrenNext(value, key, owner); + return !_this.done; + }; + return _this; + } + /** + */ + NestedOperation.prototype.next = function (item, key, parent) { + walkKeyPathValues(item, this.keyPath, this._nextNestedValue, 0, key, parent); + }; + return NestedOperation; + }(GroupOperation)); + var createTester = function (a, compare) { + if (a instanceof Function) { + return a; + } + if (a instanceof RegExp) { + return function (b) { + var result = typeof b === "string" && a.test(b); + a.lastIndex = 0; + return result; + }; + } + var comparableA = comparable(a); + return function (b) { return compare(comparableA, comparable(b)); }; + }; + var EqualsOperation = /** @class */ (function (_super) { + __extends(EqualsOperation, _super); + function EqualsOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + EqualsOperation.prototype.init = function () { + this._test = createTester(this.params, this.options.compare); + }; + EqualsOperation.prototype.next = function (item, key, parent) { + if (!Array.isArray(parent) || parent.hasOwnProperty(key)) { + if (this._test(item, key, parent)) { + this.done = true; + this.keep = true; + } + } + }; + return EqualsOperation; + }(BaseOperation)); + var createEqualsOperation = function (params, owneryQuery, options) { return new EqualsOperation(params, owneryQuery, options); }; + var NopeOperation = /** @class */ (function (_super) { + __extends(NopeOperation, _super); + function NopeOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + NopeOperation.prototype.next = function () { + this.done = true; + this.keep = false; + }; + return NopeOperation; + }(BaseOperation)); + var numericalOperationCreator = function (createNumericalOperation) { return function (params, owneryQuery, options, name) { + if (params == null) { + return new NopeOperation(params, owneryQuery, options); + } + return createNumericalOperation(params, owneryQuery, options, name); + }; }; + var numericalOperation = function (createTester) { + return numericalOperationCreator(function (params, owneryQuery, options) { + var typeofParams = typeof comparable(params); + var test = createTester(params); + return new EqualsOperation(function (b) { + return typeof comparable(b) === typeofParams && test(b); + }, owneryQuery, options); + }); + }; + var createNamedOperation = function (name, params, parentQuery, options) { + var operationCreator = options.operations[name]; + if (!operationCreator) { + throw new Error("Unsupported operation: " + name); + } + return operationCreator(params, parentQuery, options, name); + }; + var containsOperation = function (query) { + for (var key in query) { + if (key.charAt(0) === "$") + return true; + } + return false; + }; + var createNestedOperation = function (keyPath, nestedQuery, owneryQuery, options) { + if (containsOperation(nestedQuery)) { + var _a = createQueryOperations(nestedQuery, options), selfOperations = _a[0], nestedOperations = _a[1]; + if (nestedOperations.length) { + throw new Error("Property queries must contain only operations, or exact objects."); + } + return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, selfOperations); + } + return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, [ + new EqualsOperation(nestedQuery, owneryQuery, options) + ]); + }; + var createQueryOperation = function (query, owneryQuery, _a) { + if (owneryQuery === void 0) { owneryQuery = null; } + var _b = _a === void 0 ? {} : _a, compare = _b.compare, operations = _b.operations; + var options = { + compare: compare || equals, + operations: Object.assign({}, operations || {}) + }; + var _c = createQueryOperations(query, options), selfOperations = _c[0], nestedOperations = _c[1]; + var ops = []; + if (selfOperations.length) { + ops.push(new NestedOperation([], query, owneryQuery, options, selfOperations)); + } + ops.push.apply(ops, nestedOperations); + if (ops.length === 1) { + return ops[0]; + } + return new QueryOperation(query, owneryQuery, options, ops); + }; + var createQueryOperations = function (query, options) { + var selfOperations = []; + var nestedOperations = []; + if (!isVanillaObject(query)) { + selfOperations.push(new EqualsOperation(query, query, options)); + return [selfOperations, nestedOperations]; + } + for (var key in query) { + if (key.charAt(0) === "$") { + var op = createNamedOperation(key, query[key], query, options); + // probably just a flag for another operation (like $options) + if (op != null) { + selfOperations.push(op); + } + } + else { + nestedOperations.push(createNestedOperation(key.split("."), query[key], query, options)); + } + } + return [selfOperations, nestedOperations]; + }; + var createOperationTester = function (operation) { return function (item, key, owner) { + operation.reset(); + operation.next(item, key, owner); + return operation.keep; + }; }; + var createQueryTester = function (query, options) { + if (options === void 0) { options = {}; } + return createOperationTester(createQueryOperation(query, null, options)); + }; + + var $Ne = /** @class */ (function (_super) { + __extends($Ne, _super); + function $Ne() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Ne.prototype.init = function () { + this._test = createTester(this.params, this.options.compare); + }; + $Ne.prototype.reset = function () { + _super.prototype.reset.call(this); + this.keep = true; + }; + $Ne.prototype.next = function (item) { + if (this._test(item)) { + this.done = true; + this.keep = false; + } + }; + return $Ne; + }(NamedBaseOperation)); + // https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ + var $ElemMatch = /** @class */ (function (_super) { + __extends($ElemMatch, _super); + function $ElemMatch() { + return _super !== null && _super.apply(this, arguments) || this; + } + $ElemMatch.prototype.init = function () { + this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); + }; + $ElemMatch.prototype.reset = function () { + _super.prototype.reset.call(this); + this._queryOperation.reset(); + }; + $ElemMatch.prototype.next = function (item) { + if (isArray(item)) { + for (var i = 0, length_1 = item.length; i < length_1; i++) { + // reset query operation since item being tested needs to pass _all_ query + // operations for it to be a success + this._queryOperation.reset(); + // check item + this._queryOperation.next(item[i], i, item); + this.keep = this.keep || this._queryOperation.keep; + } + this.done = true; + } + else { + this.done = false; + this.keep = false; + } + }; + return $ElemMatch; + }(NamedBaseOperation)); + var $Not = /** @class */ (function (_super) { + __extends($Not, _super); + function $Not() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Not.prototype.init = function () { + this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); + }; + $Not.prototype.reset = function () { + this._queryOperation.reset(); + }; + $Not.prototype.next = function (item, key, owner) { + this._queryOperation.next(item, key, owner); + this.done = this._queryOperation.done; + this.keep = !this._queryOperation.keep; + }; + return $Not; + }(NamedBaseOperation)); + var $Size = /** @class */ (function (_super) { + __extends($Size, _super); + function $Size() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Size.prototype.init = function () { }; + $Size.prototype.next = function (item) { + if (isArray(item) && item.length === this.params) { + this.done = true; + this.keep = true; + } + // if (parent && parent.length === this.params) { + // this.done = true; + // this.keep = true; + // } + }; + return $Size; + }(NamedBaseOperation)); + var $Or = /** @class */ (function (_super) { + __extends($Or, _super); + function $Or() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Or.prototype.init = function () { + var _this = this; + this._ops = this.params.map(function (op) { + return createQueryOperation(op, null, _this.options); + }); + }; + $Or.prototype.reset = function () { + this.done = false; + this.keep = false; + for (var i = 0, length_2 = this._ops.length; i < length_2; i++) { + this._ops[i].reset(); + } + }; + $Or.prototype.next = function (item, key, owner) { + var done = false; + var success = false; + for (var i = 0, length_3 = this._ops.length; i < length_3; i++) { + var op = this._ops[i]; + op.next(item, key, owner); + if (op.keep) { + done = true; + success = op.keep; + break; + } + } + this.keep = success; + this.done = done; + }; + return $Or; + }(NamedBaseOperation)); + var $Nor = /** @class */ (function (_super) { + __extends($Nor, _super); + function $Nor() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Nor.prototype.next = function (item, key, owner) { + _super.prototype.next.call(this, item, key, owner); + this.keep = !this.keep; + }; + return $Nor; + }($Or)); + var $In = /** @class */ (function (_super) { + __extends($In, _super); + function $In() { + return _super !== null && _super.apply(this, arguments) || this; + } + $In.prototype.init = function () { + var _this = this; + this._testers = this.params.map(function (value) { + if (containsOperation(value)) { + throw new Error("cannot nest $ under " + _this.constructor.name.toLowerCase()); + } + return createTester(value, _this.options.compare); + }); + }; + $In.prototype.next = function (item, key, owner) { + var done = false; + var success = false; + for (var i = 0, length_4 = this._testers.length; i < length_4; i++) { + var test = this._testers[i]; + if (test(item)) { + done = true; + success = true; + break; + } + } + this.keep = success; + this.done = done; + }; + return $In; + }(NamedBaseOperation)); + var $Nin = /** @class */ (function (_super) { + __extends($Nin, _super); + function $Nin() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Nin.prototype.next = function (item, key, owner) { + _super.prototype.next.call(this, item, key, owner); + this.keep = !this.keep; + }; + return $Nin; + }($In)); + var $Exists = /** @class */ (function (_super) { + __extends($Exists, _super); + function $Exists() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Exists.prototype.next = function (item, key, owner) { + if (owner.hasOwnProperty(key) === this.params) { + this.done = true; + this.keep = true; + } + }; + return $Exists; + }(NamedBaseOperation)); + var $And = /** @class */ (function (_super) { + __extends($And, _super); + function $And(params, owneryQuery, options, name) { + return _super.call(this, params, owneryQuery, options, params.map(function (query) { return createQueryOperation(query, owneryQuery, options); }), name) || this; + } + $And.prototype.next = function (item, key, owner) { + this.childrenNext(item, key, owner); + }; + return $And; + }(NamedGroupOperation)); + var $eq = function (params, owneryQuery, options) { + return new EqualsOperation(params, owneryQuery, options); + }; + var $ne = function (params, owneryQuery, options, name) { return new $Ne(params, owneryQuery, options, name); }; + var $or = function (params, owneryQuery, options, name) { return new $Or(params, owneryQuery, options, name); }; + var $nor = function (params, owneryQuery, options, name) { return new $Nor(params, owneryQuery, options, name); }; + var $elemMatch = function (params, owneryQuery, options, name) { return new $ElemMatch(params, owneryQuery, options, name); }; + var $nin = function (params, owneryQuery, options, name) { return new $Nin(params, owneryQuery, options, name); }; + var $in = function (params, owneryQuery, options, name) { return new $In(params, owneryQuery, options, name); }; + var $lt = numericalOperation(function (params) { return function (b) { return b < params; }; }); + var $lte = numericalOperation(function (params) { return function (b) { return b <= params; }; }); + var $gt = numericalOperation(function (params) { return function (b) { return b > params; }; }); + var $gte = numericalOperation(function (params) { return function (b) { return b >= params; }; }); + var $mod = function (_a, owneryQuery, options) { + var mod = _a[0], equalsValue = _a[1]; + return new EqualsOperation(function (b) { return comparable(b) % mod === equalsValue; }, owneryQuery, options); + }; + var $exists = function (params, owneryQuery, options, name) { return new $Exists(params, owneryQuery, options, name); }; + var $regex = function (pattern, owneryQuery, options) { + return new EqualsOperation(new RegExp(pattern, owneryQuery.$options), owneryQuery, options); + }; + var $not = function (params, owneryQuery, options, name) { return new $Not(params, owneryQuery, options, name); }; + var typeAliases = { + number: function (v) { return typeof v === "number"; }, + string: function (v) { return typeof v === "string"; }, + bool: function (v) { return typeof v === "boolean"; }, + array: function (v) { return Array.isArray(v); }, + null: function (v) { return v === null; }, + timestamp: function (v) { return v instanceof Date; } + }; + var $type = function (clazz, owneryQuery, options) { + return new EqualsOperation(function (b) { + if (typeof clazz === "string") { + if (!typeAliases[clazz]) { + throw new Error("Type alias does not exist"); + } + return typeAliases[clazz](b); + } + return b != null ? b instanceof clazz || b.constructor === clazz : false; + }, owneryQuery, options); + }; + var $and = function (params, ownerQuery, options, name) { return new $And(params, ownerQuery, options, name); }; + var $all = $and; + var $size = function (params, ownerQuery, options) { return new $Size(params, ownerQuery, options, "$size"); }; + var $options = function () { return null; }; + var $where = function (params, ownerQuery, options) { + var test; + if (isFunction(params)) { + test = params; + } + else if (!process.env.CSP_ENABLED) { + test = new Function("obj", "return " + params); + } + else { + throw new Error("In CSP mode, sift does not support strings in \"$where\" condition"); + } + return new EqualsOperation(function (b) { return test.bind(b)(b); }, ownerQuery, options); + }; + + var defaultOperations = /*#__PURE__*/Object.freeze({ + __proto__: null, + $Size: $Size, + $eq: $eq, + $ne: $ne, + $or: $or, + $nor: $nor, + $elemMatch: $elemMatch, + $nin: $nin, + $in: $in, + $lt: $lt, + $lte: $lte, + $gt: $gt, + $gte: $gte, + $mod: $mod, + $exists: $exists, + $regex: $regex, + $not: $not, + $type: $type, + $and: $and, + $all: $all, + $size: $size, + $options: $options, + $where: $where + }); + + var createDefaultQueryOperation = function (query, ownerQuery, _a) { + var _b = _a === void 0 ? {} : _a, compare = _b.compare, operations = _b.operations; + return createQueryOperation(query, ownerQuery, { + compare: compare, + operations: Object.assign({}, defaultOperations, operations || {}) + }); + }; + var createDefaultQueryTester = function (query, options) { + if (options === void 0) { options = {}; } + var op = createDefaultQueryOperation(query, null, options); + return createOperationTester(op); + }; + + exports.$Size = $Size; + exports.$all = $all; + exports.$and = $and; + exports.$elemMatch = $elemMatch; + exports.$eq = $eq; + exports.$exists = $exists; + exports.$gt = $gt; + exports.$gte = $gte; + exports.$in = $in; + exports.$lt = $lt; + exports.$lte = $lte; + exports.$mod = $mod; + exports.$ne = $ne; + exports.$nin = $nin; + exports.$nor = $nor; + exports.$not = $not; + exports.$options = $options; + exports.$or = $or; + exports.$regex = $regex; + exports.$size = $size; + exports.$type = $type; + exports.$where = $where; + exports.EqualsOperation = EqualsOperation; + exports.createDefaultQueryOperation = createDefaultQueryOperation; + exports.createEqualsOperation = createEqualsOperation; + exports.createOperationTester = createOperationTester; + exports.createQueryOperation = createQueryOperation; + exports.createQueryTester = createQueryTester; + exports.default = createDefaultQueryTester; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=index.js.map diff --git a/node_modules/sift/lib/index.js.map b/node_modules/sift/lib/index.js.map new file mode 100644 index 0000000..a9afdbb --- /dev/null +++ b/node_modules/sift/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/core.ts","../src/operations.ts","../src/index.ts"],"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 */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\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, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\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 (Object.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, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null],"names":[],"mappings":";;;;;;IAAA;IACA;AACA;IACA;IACA;AACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;AACA;IACA,IAAI,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC,EAAE;IACnC,IAAI,aAAa,GAAG,MAAM,CAAC,cAAc;IACzC,SAAS,EAAE,SAAS,EAAE,EAAE,EAAE,YAAY,KAAK,IAAI,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,CAAC;IACpF,QAAQ,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACnF,IAAI,OAAO,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAC/B,CAAC,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lib/operations.d.ts b/node_modules/sift/lib/operations.d.ts new file mode 100644 index 0000000..296a96f --- /dev/null +++ b/node_modules/sift/lib/operations.d.ts @@ -0,0 +1,70 @@ +import { NamedBaseOperation, EqualsOperation, Options, Operation, Query, NamedGroupOperation } from "./core"; +import { Key } from "./utils"; +declare class $Ne extends NamedBaseOperation { + private _test; + init(): void; + reset(): void; + next(item: any): void; +} +declare class $ElemMatch extends NamedBaseOperation> { + private _queryOperation; + init(): void; + reset(): void; + next(item: any): void; +} +declare class $Not extends NamedBaseOperation> { + private _queryOperation; + init(): void; + reset(): void; + next(item: any, key: Key, owner: any): void; +} +export declare class $Size extends NamedBaseOperation { + init(): void; + next(item: any): void; +} +declare class $Or extends NamedBaseOperation { + private _ops; + init(): void; + reset(): void; + next(item: any, key: Key, owner: any): void; +} +declare class $Nor extends $Or { + next(item: any, key: Key, owner: any): void; +} +declare class $In extends NamedBaseOperation { + private _testers; + init(): void; + next(item: any, key: Key, owner: any): void; +} +declare class $Nin extends $In { + next(item: any, key: Key, owner: any): void; +} +declare class $Exists extends NamedBaseOperation { + next(item: any, key: Key, owner: any): void; +} +declare class $And extends NamedGroupOperation { + constructor(params: Query[], owneryQuery: Query, options: Options, name: string); + next(item: any, key: Key, owner: any): void; +} +export declare const $eq: (params: any, owneryQuery: any, options: Options) => EqualsOperation; +export declare const $ne: (params: any, owneryQuery: any, options: Options, name: string) => $Ne; +export declare const $or: (params: any[], owneryQuery: any, options: Options, name: string) => $Or; +export declare const $nor: (params: any[], owneryQuery: any, options: Options, name: string) => $Nor; +export declare const $elemMatch: (params: any, owneryQuery: any, options: Options, name: string) => $ElemMatch; +export declare const $nin: (params: any, owneryQuery: any, options: Options, name: string) => $Nin; +export declare const $in: (params: any, owneryQuery: any, options: Options, name: string) => $In; +export declare const $lt: (params: any, owneryQuery: any, options: Options, name: string) => Operation | import("./core").NopeOperation; +export declare const $lte: (params: any, owneryQuery: any, options: Options, name: string) => Operation | import("./core").NopeOperation; +export declare const $gt: (params: any, owneryQuery: any, options: Options, name: string) => Operation | import("./core").NopeOperation; +export declare const $gte: (params: any, owneryQuery: any, options: Options, name: string) => Operation | import("./core").NopeOperation; +export declare const $mod: ([mod, equalsValue]: number[], owneryQuery: any, options: Options) => EqualsOperation<(b: any) => boolean>; +export declare const $exists: (params: boolean, owneryQuery: any, options: Options, name: string) => $Exists; +export declare const $regex: (pattern: string, owneryQuery: any, options: Options) => EqualsOperation; +export declare const $not: (params: any, owneryQuery: any, options: Options, name: string) => $Not; +export declare const $type: (clazz: TimerHandler, owneryQuery: any, options: Options) => EqualsOperation<(b: any) => any>; +export declare const $and: (params: any[], ownerQuery: any, options: Options, name: string) => $And; +export declare const $all: (params: any[], ownerQuery: any, options: Options, name: string) => $And; +export declare const $size: (params: number, ownerQuery: any, options: Options) => $Size; +export declare const $options: () => any; +export declare const $where: (params: TimerHandler, ownerQuery: any, options: Options) => EqualsOperation<(b: any) => any>; +export {}; diff --git a/node_modules/sift/lib/utils.d.ts b/node_modules/sift/lib/utils.d.ts new file mode 100644 index 0000000..422a292 --- /dev/null +++ b/node_modules/sift/lib/utils.d.ts @@ -0,0 +1,9 @@ +export declare type Key = string | number; +export declare type Comparator = (a: any, b: any) => boolean; +export declare const typeChecker: (type: any) => (value: any) => value is TType; +export declare const comparable: (value: any) => any; +export declare const isArray: (value: any) => value is any[]; +export declare const isObject: (value: any) => value is Object; +export declare const isFunction: (value: any) => value is Function; +export declare const isVanillaObject: (value: any) => boolean; +export declare const equals: (a: any, b: any) => boolean; diff --git a/node_modules/sift/package.json b/node_modules/sift/package.json new file mode 100644 index 0000000..4954e20 --- /dev/null +++ b/node_modules/sift/package.json @@ -0,0 +1,61 @@ +{ + "name": "sift", + "description": "MongoDB query filtering in JavaScript", + "version": "13.5.2", + "repository": "crcn/sift.js", + "sideEffects": false, + "author": { + "name": "Craig Condon", + "email": "craig.j.condon@gmail.com" + }, + "license": "MIT", + "engines": {}, + "typings": "./index.d.ts", + "husky": { + "hooks": { + "pre-commit": "pretty-quick --staged" + } + }, + "devDependencies": { + "@rollup/plugin-replace": "^2.3.2", + "@rollup/plugin-typescript": "^4.1.1", + "@types/node": "^13.7.0", + "bson": "^4.0.3", + "eval": "^0.1.4", + "husky": "^1.2.1", + "immutable": "^3.7.6", + "mocha": "8.3.2", + "mongodb": "^3.6.6", + "prettier": "1.15.3", + "pretty-quick": "^1.11.1", + "rimraf": "^3.0.2", + "rollup": "^2.7.2", + "rollup-plugin-terser": "^7.0.2", + "tslib": "^2.0.0", + "typescript": "^3.8.3" + }, + "main": "./index.js", + "module": "./es5m/index.js", + "es2015": "./es/index.js", + "scripts": { + "clean": "rimraf lib es5m es", + "prebuild": "npm run clean && npm run build:types", + "build": "rollup -c", + "build:types": "tsc -p tsconfig.json --emitDeclarationOnly --outDir lib", + "test": "npm run test:spec && npm run test:types", + "test:spec": "mocha ./test -R spec", + "test:types": "cd test && tsc types.ts --noEmit", + "prepublishOnly": "npm run build && npm run test" + }, + "files": [ + "es", + "es5m", + "lib", + "*.d.ts", + "*.js.map", + "index.js", + "sift.csp.min.js", + "sift.min.js", + "MIT-LICENSE.txt" + ] +} diff --git a/node_modules/sift/sift.csp.min.js b/node_modules/sift/sift.csp.min.js new file mode 100644 index 0000000..9b89893 --- /dev/null +++ b/node_modules/sift/sift.csp.min.js @@ -0,0 +1,686 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.sift = {})); +}(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 */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var typeChecker = function (type) { + var typeString = "[object " + type + "]"; + return function (value) { + return getClassName(value) === typeString; + }; + }; + var getClassName = function (value) { return Object.prototype.toString.call(value); }; + var comparable = function (value) { + if (value instanceof Date) { + return value.getTime(); + } + else if (isArray(value)) { + return value.map(comparable); + } + else if (value && typeof value.toJSON === "function") { + return value.toJSON(); + } + return value; + }; + var isArray = typeChecker("Array"); + var isObject = typeChecker("Object"); + var isFunction = typeChecker("Function"); + var isVanillaObject = function (value) { + return (value && + (value.constructor === Object || + value.constructor === Array || + value.constructor.toString() === "function Object() { [native code] }" || + value.constructor.toString() === "function Array() { [native code] }") && + !value.toJSON); + }; + var equals = function (a, b) { + if (a == null && a == b) { + return true; + } + if (a === b) { + return true; + } + if (Object.prototype.toString.call(a) !== Object.prototype.toString.call(b)) { + return false; + } + if (isArray(a)) { + if (a.length !== b.length) { + return false; + } + for (var i = 0, length_1 = a.length; i < length_1; i++) { + if (!equals(a[i], b[i])) + return false; + } + return true; + } + else if (isObject(a)) { + if (Object.keys(a).length !== Object.keys(b).length) { + return false; + } + for (var key in a) { + if (!equals(a[key], b[key])) + return false; + } + return true; + } + return false; + }; + + /** + * Walks through each value given the context - used for nested operations. E.g: + * { "person.address": { $eq: "blarg" }} + */ + var walkKeyPathValues = function (item, keyPath, next, depth, key, owner) { + var currentKey = keyPath[depth]; + // if array, then try matching. Might fall through for cases like: + // { $eq: [1, 2, 3] }, [ 1, 2, 3 ]. + if (isArray(item) && isNaN(Number(currentKey))) { + for (var i = 0, length_1 = item.length; i < length_1; i++) { + // if FALSE is returned, then terminate walker. For operations, this simply + // means that the search critera was met. + if (!walkKeyPathValues(item[i], keyPath, next, depth, i, item)) { + return false; + } + } + } + if (depth === keyPath.length || item == null) { + return next(item, key, owner); + } + return walkKeyPathValues(item[currentKey], keyPath, next, depth + 1, currentKey, item); + }; + var BaseOperation = /** @class */ (function () { + function BaseOperation(params, owneryQuery, options) { + this.params = params; + this.owneryQuery = owneryQuery; + this.options = options; + this.init(); + } + BaseOperation.prototype.init = function () { }; + BaseOperation.prototype.reset = function () { + this.done = false; + this.keep = false; + }; + return BaseOperation; + }()); + var NamedBaseOperation = /** @class */ (function (_super) { + __extends(NamedBaseOperation, _super); + function NamedBaseOperation(params, owneryQuery, options, name) { + var _this = _super.call(this, params, owneryQuery, options) || this; + _this.name = name; + return _this; + } + return NamedBaseOperation; + }(BaseOperation)); + var GroupOperation = /** @class */ (function (_super) { + __extends(GroupOperation, _super); + function GroupOperation(params, owneryQuery, options, children) { + var _this = _super.call(this, params, owneryQuery, options) || this; + _this.children = children; + return _this; + } + /** + */ + GroupOperation.prototype.reset = function () { + this.keep = false; + this.done = false; + for (var i = 0, length_2 = this.children.length; i < length_2; i++) { + this.children[i].reset(); + } + }; + /** + */ + GroupOperation.prototype.childrenNext = function (item, key, owner) { + var done = true; + var keep = true; + for (var i = 0, length_3 = this.children.length; i < length_3; i++) { + var childOperation = this.children[i]; + childOperation.next(item, key, owner); + if (!childOperation.keep) { + keep = false; + } + if (childOperation.done) { + if (!childOperation.keep) { + break; + } + } + else { + done = false; + } + } + this.done = done; + this.keep = keep; + }; + return GroupOperation; + }(BaseOperation)); + var NamedGroupOperation = /** @class */ (function (_super) { + __extends(NamedGroupOperation, _super); + function NamedGroupOperation(params, owneryQuery, options, children, name) { + var _this = _super.call(this, params, owneryQuery, options, children) || this; + _this.name = name; + return _this; + } + return NamedGroupOperation; + }(GroupOperation)); + var QueryOperation = /** @class */ (function (_super) { + __extends(QueryOperation, _super); + function QueryOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + */ + QueryOperation.prototype.next = function (item, key, parent) { + this.childrenNext(item, key, parent); + }; + return QueryOperation; + }(GroupOperation)); + var NestedOperation = /** @class */ (function (_super) { + __extends(NestedOperation, _super); + function NestedOperation(keyPath, params, owneryQuery, options, children) { + var _this = _super.call(this, params, owneryQuery, options, children) || this; + _this.keyPath = keyPath; + /** + */ + _this._nextNestedValue = function (value, key, owner) { + _this.childrenNext(value, key, owner); + return !_this.done; + }; + return _this; + } + /** + */ + NestedOperation.prototype.next = function (item, key, parent) { + walkKeyPathValues(item, this.keyPath, this._nextNestedValue, 0, key, parent); + }; + return NestedOperation; + }(GroupOperation)); + var createTester = function (a, compare) { + if (a instanceof Function) { + return a; + } + if (a instanceof RegExp) { + return function (b) { + var result = typeof b === "string" && a.test(b); + a.lastIndex = 0; + return result; + }; + } + var comparableA = comparable(a); + return function (b) { return compare(comparableA, comparable(b)); }; + }; + var EqualsOperation = /** @class */ (function (_super) { + __extends(EqualsOperation, _super); + function EqualsOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + EqualsOperation.prototype.init = function () { + this._test = createTester(this.params, this.options.compare); + }; + EqualsOperation.prototype.next = function (item, key, parent) { + if (!Array.isArray(parent) || parent.hasOwnProperty(key)) { + if (this._test(item, key, parent)) { + this.done = true; + this.keep = true; + } + } + }; + return EqualsOperation; + }(BaseOperation)); + var createEqualsOperation = function (params, owneryQuery, options) { return new EqualsOperation(params, owneryQuery, options); }; + var NopeOperation = /** @class */ (function (_super) { + __extends(NopeOperation, _super); + function NopeOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + NopeOperation.prototype.next = function () { + this.done = true; + this.keep = false; + }; + return NopeOperation; + }(BaseOperation)); + var numericalOperationCreator = function (createNumericalOperation) { return function (params, owneryQuery, options, name) { + if (params == null) { + return new NopeOperation(params, owneryQuery, options); + } + return createNumericalOperation(params, owneryQuery, options, name); + }; }; + var numericalOperation = function (createTester) { + return numericalOperationCreator(function (params, owneryQuery, options) { + var typeofParams = typeof comparable(params); + var test = createTester(params); + return new EqualsOperation(function (b) { + return typeof comparable(b) === typeofParams && test(b); + }, owneryQuery, options); + }); + }; + var createNamedOperation = function (name, params, parentQuery, options) { + var operationCreator = options.operations[name]; + if (!operationCreator) { + throw new Error("Unsupported operation: " + name); + } + return operationCreator(params, parentQuery, options, name); + }; + var containsOperation = function (query) { + for (var key in query) { + if (key.charAt(0) === "$") + return true; + } + return false; + }; + var createNestedOperation = function (keyPath, nestedQuery, owneryQuery, options) { + if (containsOperation(nestedQuery)) { + var _a = createQueryOperations(nestedQuery, options), selfOperations = _a[0], nestedOperations = _a[1]; + if (nestedOperations.length) { + throw new Error("Property queries must contain only operations, or exact objects."); + } + return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, selfOperations); + } + return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, [ + new EqualsOperation(nestedQuery, owneryQuery, options) + ]); + }; + var createQueryOperation = function (query, owneryQuery, _a) { + if (owneryQuery === void 0) { owneryQuery = null; } + var _b = _a === void 0 ? {} : _a, compare = _b.compare, operations = _b.operations; + var options = { + compare: compare || equals, + operations: Object.assign({}, operations || {}) + }; + var _c = createQueryOperations(query, options), selfOperations = _c[0], nestedOperations = _c[1]; + var ops = []; + if (selfOperations.length) { + ops.push(new NestedOperation([], query, owneryQuery, options, selfOperations)); + } + ops.push.apply(ops, nestedOperations); + if (ops.length === 1) { + return ops[0]; + } + return new QueryOperation(query, owneryQuery, options, ops); + }; + var createQueryOperations = function (query, options) { + var selfOperations = []; + var nestedOperations = []; + if (!isVanillaObject(query)) { + selfOperations.push(new EqualsOperation(query, query, options)); + return [selfOperations, nestedOperations]; + } + for (var key in query) { + if (key.charAt(0) === "$") { + var op = createNamedOperation(key, query[key], query, options); + // probably just a flag for another operation (like $options) + if (op != null) { + selfOperations.push(op); + } + } + else { + nestedOperations.push(createNestedOperation(key.split("."), query[key], query, options)); + } + } + return [selfOperations, nestedOperations]; + }; + var createOperationTester = function (operation) { return function (item, key, owner) { + operation.reset(); + operation.next(item, key, owner); + return operation.keep; + }; }; + var createQueryTester = function (query, options) { + if (options === void 0) { options = {}; } + return createOperationTester(createQueryOperation(query, null, options)); + }; + + var $Ne = /** @class */ (function (_super) { + __extends($Ne, _super); + function $Ne() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Ne.prototype.init = function () { + this._test = createTester(this.params, this.options.compare); + }; + $Ne.prototype.reset = function () { + _super.prototype.reset.call(this); + this.keep = true; + }; + $Ne.prototype.next = function (item) { + if (this._test(item)) { + this.done = true; + this.keep = false; + } + }; + return $Ne; + }(NamedBaseOperation)); + // https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ + var $ElemMatch = /** @class */ (function (_super) { + __extends($ElemMatch, _super); + function $ElemMatch() { + return _super !== null && _super.apply(this, arguments) || this; + } + $ElemMatch.prototype.init = function () { + this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); + }; + $ElemMatch.prototype.reset = function () { + _super.prototype.reset.call(this); + this._queryOperation.reset(); + }; + $ElemMatch.prototype.next = function (item) { + if (isArray(item)) { + for (var i = 0, length_1 = item.length; i < length_1; i++) { + // reset query operation since item being tested needs to pass _all_ query + // operations for it to be a success + this._queryOperation.reset(); + // check item + this._queryOperation.next(item[i], i, item); + this.keep = this.keep || this._queryOperation.keep; + } + this.done = true; + } + else { + this.done = false; + this.keep = false; + } + }; + return $ElemMatch; + }(NamedBaseOperation)); + var $Not = /** @class */ (function (_super) { + __extends($Not, _super); + function $Not() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Not.prototype.init = function () { + this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); + }; + $Not.prototype.reset = function () { + this._queryOperation.reset(); + }; + $Not.prototype.next = function (item, key, owner) { + this._queryOperation.next(item, key, owner); + this.done = this._queryOperation.done; + this.keep = !this._queryOperation.keep; + }; + return $Not; + }(NamedBaseOperation)); + var $Size = /** @class */ (function (_super) { + __extends($Size, _super); + function $Size() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Size.prototype.init = function () { }; + $Size.prototype.next = function (item) { + if (isArray(item) && item.length === this.params) { + this.done = true; + this.keep = true; + } + // if (parent && parent.length === this.params) { + // this.done = true; + // this.keep = true; + // } + }; + return $Size; + }(NamedBaseOperation)); + var $Or = /** @class */ (function (_super) { + __extends($Or, _super); + function $Or() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Or.prototype.init = function () { + var _this = this; + this._ops = this.params.map(function (op) { + return createQueryOperation(op, null, _this.options); + }); + }; + $Or.prototype.reset = function () { + this.done = false; + this.keep = false; + for (var i = 0, length_2 = this._ops.length; i < length_2; i++) { + this._ops[i].reset(); + } + }; + $Or.prototype.next = function (item, key, owner) { + var done = false; + var success = false; + for (var i = 0, length_3 = this._ops.length; i < length_3; i++) { + var op = this._ops[i]; + op.next(item, key, owner); + if (op.keep) { + done = true; + success = op.keep; + break; + } + } + this.keep = success; + this.done = done; + }; + return $Or; + }(NamedBaseOperation)); + var $Nor = /** @class */ (function (_super) { + __extends($Nor, _super); + function $Nor() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Nor.prototype.next = function (item, key, owner) { + _super.prototype.next.call(this, item, key, owner); + this.keep = !this.keep; + }; + return $Nor; + }($Or)); + var $In = /** @class */ (function (_super) { + __extends($In, _super); + function $In() { + return _super !== null && _super.apply(this, arguments) || this; + } + $In.prototype.init = function () { + var _this = this; + this._testers = this.params.map(function (value) { + if (containsOperation(value)) { + throw new Error("cannot nest $ under " + _this.constructor.name.toLowerCase()); + } + return createTester(value, _this.options.compare); + }); + }; + $In.prototype.next = function (item, key, owner) { + var done = false; + var success = false; + for (var i = 0, length_4 = this._testers.length; i < length_4; i++) { + var test = this._testers[i]; + if (test(item)) { + done = true; + success = true; + break; + } + } + this.keep = success; + this.done = done; + }; + return $In; + }(NamedBaseOperation)); + var $Nin = /** @class */ (function (_super) { + __extends($Nin, _super); + function $Nin() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Nin.prototype.next = function (item, key, owner) { + _super.prototype.next.call(this, item, key, owner); + this.keep = !this.keep; + }; + return $Nin; + }($In)); + var $Exists = /** @class */ (function (_super) { + __extends($Exists, _super); + function $Exists() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Exists.prototype.next = function (item, key, owner) { + if (owner.hasOwnProperty(key) === this.params) { + this.done = true; + this.keep = true; + } + }; + return $Exists; + }(NamedBaseOperation)); + var $And = /** @class */ (function (_super) { + __extends($And, _super); + function $And(params, owneryQuery, options, name) { + return _super.call(this, params, owneryQuery, options, params.map(function (query) { return createQueryOperation(query, owneryQuery, options); }), name) || this; + } + $And.prototype.next = function (item, key, owner) { + this.childrenNext(item, key, owner); + }; + return $And; + }(NamedGroupOperation)); + var $eq = function (params, owneryQuery, options) { + return new EqualsOperation(params, owneryQuery, options); + }; + var $ne = function (params, owneryQuery, options, name) { return new $Ne(params, owneryQuery, options, name); }; + var $or = function (params, owneryQuery, options, name) { return new $Or(params, owneryQuery, options, name); }; + var $nor = function (params, owneryQuery, options, name) { return new $Nor(params, owneryQuery, options, name); }; + var $elemMatch = function (params, owneryQuery, options, name) { return new $ElemMatch(params, owneryQuery, options, name); }; + var $nin = function (params, owneryQuery, options, name) { return new $Nin(params, owneryQuery, options, name); }; + var $in = function (params, owneryQuery, options, name) { return new $In(params, owneryQuery, options, name); }; + var $lt = numericalOperation(function (params) { return function (b) { return b < params; }; }); + var $lte = numericalOperation(function (params) { return function (b) { return b <= params; }; }); + var $gt = numericalOperation(function (params) { return function (b) { return b > params; }; }); + var $gte = numericalOperation(function (params) { return function (b) { return b >= params; }; }); + var $mod = function (_a, owneryQuery, options) { + var mod = _a[0], equalsValue = _a[1]; + return new EqualsOperation(function (b) { return comparable(b) % mod === equalsValue; }, owneryQuery, options); + }; + var $exists = function (params, owneryQuery, options, name) { return new $Exists(params, owneryQuery, options, name); }; + var $regex = function (pattern, owneryQuery, options) { + return new EqualsOperation(new RegExp(pattern, owneryQuery.$options), owneryQuery, options); + }; + var $not = function (params, owneryQuery, options, name) { return new $Not(params, owneryQuery, options, name); }; + var typeAliases = { + number: function (v) { return typeof v === "number"; }, + string: function (v) { return typeof v === "string"; }, + bool: function (v) { return typeof v === "boolean"; }, + array: function (v) { return Array.isArray(v); }, + null: function (v) { return v === null; }, + timestamp: function (v) { return v instanceof Date; } + }; + var $type = function (clazz, owneryQuery, options) { + return new EqualsOperation(function (b) { + if (typeof clazz === "string") { + if (!typeAliases[clazz]) { + throw new Error("Type alias does not exist"); + } + return typeAliases[clazz](b); + } + return b != null ? b instanceof clazz || b.constructor === clazz : false; + }, owneryQuery, options); + }; + var $and = function (params, ownerQuery, options, name) { return new $And(params, ownerQuery, options, name); }; + var $all = $and; + var $size = function (params, ownerQuery, options) { return new $Size(params, ownerQuery, options, "$size"); }; + var $options = function () { return null; }; + var $where = function (params, ownerQuery, options) { + var test; + if (isFunction(params)) { + test = params; + } + else { + throw new Error("In CSP mode, sift does not support strings in \"$where\" condition"); + } + return new EqualsOperation(function (b) { return test.bind(b)(b); }, ownerQuery, options); + }; + + var defaultOperations = /*#__PURE__*/Object.freeze({ + __proto__: null, + $Size: $Size, + $eq: $eq, + $ne: $ne, + $or: $or, + $nor: $nor, + $elemMatch: $elemMatch, + $nin: $nin, + $in: $in, + $lt: $lt, + $lte: $lte, + $gt: $gt, + $gte: $gte, + $mod: $mod, + $exists: $exists, + $regex: $regex, + $not: $not, + $type: $type, + $and: $and, + $all: $all, + $size: $size, + $options: $options, + $where: $where + }); + + var createDefaultQueryOperation = function (query, ownerQuery, _a) { + var _b = _a === void 0 ? {} : _a, compare = _b.compare, operations = _b.operations; + return createQueryOperation(query, ownerQuery, { + compare: compare, + operations: Object.assign({}, defaultOperations, operations || {}) + }); + }; + var createDefaultQueryTester = function (query, options) { + if (options === void 0) { options = {}; } + var op = createDefaultQueryOperation(query, null, options); + return createOperationTester(op); + }; + + exports.$Size = $Size; + exports.$all = $all; + exports.$and = $and; + exports.$elemMatch = $elemMatch; + exports.$eq = $eq; + exports.$exists = $exists; + exports.$gt = $gt; + exports.$gte = $gte; + exports.$in = $in; + exports.$lt = $lt; + exports.$lte = $lte; + exports.$mod = $mod; + exports.$ne = $ne; + exports.$nin = $nin; + exports.$nor = $nor; + exports.$not = $not; + exports.$options = $options; + exports.$or = $or; + exports.$regex = $regex; + exports.$size = $size; + exports.$type = $type; + exports.$where = $where; + exports.EqualsOperation = EqualsOperation; + exports.createDefaultQueryOperation = createDefaultQueryOperation; + exports.createEqualsOperation = createEqualsOperation; + exports.createOperationTester = createOperationTester; + exports.createQueryOperation = createQueryOperation; + exports.createQueryTester = createQueryTester; + exports.default = createDefaultQueryTester; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=sift.csp.min.js.map diff --git a/node_modules/sift/sift.csp.min.js.map b/node_modules/sift/sift.csp.min.js.map new file mode 100644 index 0000000..5fbb0b3 --- /dev/null +++ b/node_modules/sift/sift.csp.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sift.csp.min.js","sources":["node_modules/tslib/tslib.es6.js","src/utils.ts","src/core.ts","src/operations.ts","src/index.ts"],"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 */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\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, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\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 (Object.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, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null],"names":[],"mappings":";;;;;;IAAA;IACA;AACA;IACA;IACA;AACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;AACA;IACA,IAAI,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC,EAAE;IACnC,IAAI,aAAa,GAAG,MAAM,CAAC,cAAc;IACzC,SAAS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,UAC/B,KAAqB,EACrB,OAA8B;QAA9B,wBAAA,EAAA,YAA8B;QAE9B,IAAM,EAAE,GAAG,2BAA2B,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAC7D,OAAO,qBAAqB,CAAC,EAAE,CAAC,CAAC;IACnC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/sift/sift.min.js b/node_modules/sift/sift.min.js new file mode 100644 index 0000000..a02ffcb --- /dev/null +++ b/node_modules/sift/sift.min.js @@ -0,0 +1,16 @@ +!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((n=n||self).sift={})}(this,(function(n){"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. + ***************************************************************************** */var t=function(n,r){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,t){n.__proto__=t}||function(n,t){for(var r in t)t.hasOwnProperty(r)&&(n[r]=t[r])})(n,r)};function r(n,r){function i(){this.constructor=n}t(n,r),n.prototype=null===r?Object.create(r):(i.prototype=r.prototype,new i)}var i=function(n){var t="[object "+n+"]";return function(n){return u(n)===t}},u=function(n){return Object.prototype.toString.call(n)},e=function(n){return n instanceof Date?n.getTime():o(n)?n.map(e):n&&"function"==typeof n.toJSON?n.toJSON():n},o=i("Array"),f=i("Object"),c=i("Function"),s=function(n,t){if(null==n&&n==t)return!0;if(n===t)return!0;if(Object.prototype.toString.call(n)!==Object.prototype.toString.call(t))return!1;if(o(n)){if(n.length!==t.length)return!1;for(var r=0,i=n.length;rn}})),L=j((function(n){return function(t){return t>=n}})),Q=function(n,t,r){var i=n[0],u=n[1];return new d((function(n){return e(n)%i===u}),t,r)},V=function(n,t,r,i){return new P(n,t,r,i)},W=function(n,t,r){return new d(new RegExp(n,t.$options),t,r)},X=function(n,t,r,i){return new z(n,t,r,i)},Y={number:function(n){return"number"==typeof n},string:function(n){return"string"==typeof n},bool:function(n){return"boolean"==typeof n},array:function(n){return Array.isArray(n)},null:function(n){return null===n},timestamp:function(n){return n instanceof Date}},Z=function(n,t,r){return new d((function(t){if("string"==typeof n){if(!Y[n])throw new Error("Type alias does not exist");return Y[n](t)}return null!=t&&(t instanceof n||t.constructor===n)}),t,r)},nn=function(n,t,r,i){return new R(n,t,r,i)},tn=nn,rn=function(n,t,r){return new F(n,t,r,"$size")},un=function(){return null},en=function(n,t,r){var i;if(c(n))i=n;else{if(process.env.CSP_ENABLED)throw new Error('In CSP mode, sift does not support strings in "$where" condition');i=new Function("obj","return "+n)}return new d((function(n){return i.bind(n)(n)}),t,r)},on=Object.freeze({__proto__:null,$Size:F,$eq:S,$ne:C,$or:I,$nor:T,$elemMatch:U,$nin:B,$in:G,$lt:H,$lte:J,$gt:K,$gte:L,$mod:Q,$exists:V,$regex:W,$not:X,$type:Z,$and:nn,$all:tn,$size:rn,$options:un,$where:en}),fn=function(n,t,r){var i=void 0===r?{}:r,u=i.compare,e=i.operations;return _(n,t,{compare:u,operations:Object.assign({},on,e||{})})};n.$Size=F,n.$all=tn,n.$and=nn,n.$elemMatch=U,n.$eq=S,n.$exists=V,n.$gt=K,n.$gte=L,n.$in=G,n.$lt=H,n.$lte=J,n.$mod=Q,n.$ne=C,n.$nin=B,n.$nor=T,n.$not=X,n.$options=un,n.$or=I,n.$regex=W,n.$size=rn,n.$type=Z,n.$where=en,n.EqualsOperation=d,n.createDefaultQueryOperation=fn,n.createEqualsOperation=function(n,t,r){return new d(n,t,r)},n.createOperationTester=E,n.createQueryOperation=_,n.createQueryTester=function(n,t){return void 0===t&&(t={}),E(_(n,null,t))},n.default=function(n,t){void 0===t&&(t={});var r=fn(n,null,t);return E(r)},Object.defineProperty(n,"l",{value:!0})})); +//# sourceMappingURL=sift.min.js.map diff --git a/node_modules/sift/sift.min.js.map b/node_modules/sift/sift.min.js.map new file mode 100644 index 0000000..f979cf1 --- /dev/null +++ b/node_modules/sift/sift.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sift.min.js","sources":["node_modules/tslib/tslib.es6.js","src/utils.ts","src/core.ts","src/operations.ts","src/index.ts"],"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 */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\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, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\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 (Object.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, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","hasOwnProperty","__extends","__","this","constructor","prototype","create","typeChecker","type","typeString","value","getClassName","toString","call","comparable","Date","getTime","isArray","map","toJSON","isObject","isFunction","equals","a","length","i","length_1","keys","key","walkKeyPathValues","item","keyPath","next","depth","owner","currentKey","isNaN","Number","params","owneryQuery","options","init","BaseOperation","done","keep","name","_super","_this","children","GroupOperation","length_2","reset","length_3","childOperation","QueryOperation","parent","childrenNext","NestedOperation","_nextNestedValue","createTester","compare","Function","RegExp","result","test","lastIndex","comparableA","EqualsOperation","_test","NopeOperation","numericalOperation","createNumericalOperation","typeofParams","createNamedOperation","parentQuery","operationCreator","operations","Error","containsOperation","query","charAt","createNestedOperation","nestedQuery","_a","selfOperations","createQueryOperation","_b","assign","_c","nestedOperations","ops","push","createQueryOperations","op","split","createOperationTester","operation","$Ne","NamedBaseOperation","$ElemMatch","_queryOperation","$Not","$Size","$Or","_ops","success","$Nor","$In","_testers","toLowerCase","length_4","$Nin","$Exists","$And","NamedGroupOperation","$eq","$ne","$or","$nor","$elemMatch","$nin","$in","$lt","$lte","$gt","$gte","$mod","mod","equalsValue","$exists","$regex","pattern","$options","$not","typeAliases","number","v","string","bool","array","null","timestamp","$type","clazz","$and","ownerQuery","$all","$size","$where","process","env","CSP_ENABLED","bind","createDefaultQueryOperation","defaultOperations"],"mappings":";;;;;;;;;;;;;;oFAgBA,IAAIA,EAAgB,SAASC,EAAGC,GAI5B,OAHAF,EAAgBG,OAAOC,gBAClB,CAAEC,UAAW,cAAgBC,OAAS,SAAUL,EAAGC,GAAKD,EAAEI,UAAYH,IACvE,SAAUD,EAAGC,GAAK,IAAK,IAAIK,KAAKL,EAAOA,EAAEM,eAAeD,KAAIN,EAAEM,GAAKL,EAAEK,MACpDN,EAAGC,IAGrB,SAASO,EAAUR,EAAGC,GAEzB,SAASQ,IAAOC,KAAKC,YAAcX,EADnCD,EAAcC,EAAGC,GAEjBD,EAAEY,UAAkB,OAANX,EAAaC,OAAOW,OAAOZ,IAAMQ,EAAGG,UAAYX,EAAEW,UAAW,IAAIH,GCxB5E,IAAMK,EAAc,SAAQC,GACjC,IAAMC,EAAa,WAAaD,EAAO,IACvC,OAAO,SAASE,GACd,OAAOC,EAAaD,KAAWD,IAI7BE,EAAe,SAAAD,GAAS,OAAAf,OAAOU,UAAUO,SAASC,KAAKH,IAEhDI,EAAa,SAACJ,GACzB,OAAIA,aAAiBK,KACZL,EAAMM,UACJC,EAAQP,GACVA,EAAMQ,IAAIJ,GACRJ,GAAiC,mBAAjBA,EAAMS,OACxBT,EAAMS,SAGRT,GAGIO,EAAUV,EAAwB,SAClCa,EAAWb,EAAoB,UAC/Bc,EAAad,EAAsB,YAYnCe,EAAS,SAACC,EAAG7B,GACxB,GAAS,MAAL6B,GAAaA,GAAK7B,EACpB,OAAO,EAET,GAAI6B,IAAM7B,EAC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file mode 100644 index 0000000..eead04a --- /dev/null +++ b/node_modules/signal-exit/LICENSE.txt @@ -0,0 +1,16 @@ +The ISC License + +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/signal-exit/README.md b/node_modules/signal-exit/README.md new file mode 100644 index 0000000..f9c7c00 --- /dev/null +++ b/node_modules/signal-exit/README.md @@ -0,0 +1,39 @@ +# signal-exit + +[![Build Status](https://travis-ci.org/tapjs/signal-exit.png)](https://travis-ci.org/tapjs/signal-exit) +[![Coverage](https://coveralls.io/repos/tapjs/signal-exit/badge.svg?branch=master)](https://coveralls.io/r/tapjs/signal-exit?branch=master) +[![NPM version](https://img.shields.io/npm/v/signal-exit.svg)](https://www.npmjs.com/package/signal-exit) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) + +When you want to fire an event no matter how a process exits: + +* reaching the end of execution. +* explicitly having `process.exit(code)` called. +* having `process.kill(pid, sig)` called. +* receiving a fatal signal from outside the process + +Use `signal-exit`. + +```js +var onExit = require('signal-exit') + +onExit(function (code, signal) { + console.log('process exited!') +}) +``` + +## API + +`var remove = onExit(function (code, signal) {}, options)` + +The return value of the function is a function that will remove the +handler. + +Note that the function *only* fires for signals if the signal would +cause the process to exit. That is, there are no other listeners, and +it is a fatal signal. + +## Options + +* `alwaysLast`: Run this handler after any other signal or exit + handlers. This causes `process.emit` to be monkeypatched. diff --git a/node_modules/signal-exit/index.js b/node_modules/signal-exit/index.js new file mode 100644 index 0000000..a79b1d2 --- /dev/null +++ b/node_modules/signal-exit/index.js @@ -0,0 +1,200 @@ +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +// grab a reference to node's real process object right away +var process = global.process + +const processOk = function (process) { + return process && + typeof process === 'object' && + typeof process.removeListener === 'function' && + typeof process.emit === 'function' && + typeof process.reallyExit === 'function' && + typeof process.listeners === 'function' && + typeof process.kill === 'function' && + typeof process.pid === 'number' && + typeof process.on === 'function' +} + +// some kind of non-node environment, just no-op +/* istanbul ignore if */ +if (!processOk(process)) { + module.exports = function () {} +} else { + var assert = require('assert') + var signals = require('./signals.js') + var isWin = /^win/i.test(process.platform) + + var EE = require('events') + /* istanbul ignore if */ + if (typeof EE !== 'function') { + EE = EE.EventEmitter + } + + var emitter + if (process.__signal_exit_emitter__) { + emitter = process.__signal_exit_emitter__ + } else { + emitter = process.__signal_exit_emitter__ = new EE() + emitter.count = 0 + emitter.emitted = {} + } + + // Because this emitter is a global, we have to check to see if a + // previous version of this library failed to enable infinite listeners. + // I know what you're about to say. But literally everything about + // signal-exit is a compromise with evil. Get used to it. + if (!emitter.infinite) { + emitter.setMaxListeners(Infinity) + emitter.infinite = true + } + + module.exports = function (cb, opts) { + /* istanbul ignore if */ + if (!processOk(global.process)) { + return + } + assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') + + if (loaded === false) { + load() + } + + var ev = 'exit' + if (opts && opts.alwaysLast) { + ev = 'afterexit' + } + + var remove = function () { + emitter.removeListener(ev, cb) + if (emitter.listeners('exit').length === 0 && + emitter.listeners('afterexit').length === 0) { + unload() + } + } + emitter.on(ev, cb) + + return remove + } + + var unload = function unload () { + if (!loaded || !processOk(global.process)) { + return + } + loaded = false + + signals.forEach(function (sig) { + try { + process.removeListener(sig, sigListeners[sig]) + } catch (er) {} + }) + process.emit = originalProcessEmit + process.reallyExit = originalProcessReallyExit + emitter.count -= 1 + } + module.exports.unload = unload + + var emit = function emit (event, code, signal) { + /* istanbul ignore if */ + if (emitter.emitted[event]) { + return + } + emitter.emitted[event] = true + emitter.emit(event, code, signal) + } + + // { : , ... } + var sigListeners = {} + signals.forEach(function (sig) { + sigListeners[sig] = function listener () { + /* istanbul ignore if */ + if (!processOk(global.process)) { + return + } + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + var listeners = process.listeners(sig) + if (listeners.length === emitter.count) { + unload() + emit('exit', null, sig) + /* istanbul ignore next */ + emit('afterexit', null, sig) + /* istanbul ignore next */ + if (isWin && sig === 'SIGHUP') { + // "SIGHUP" throws an `ENOSYS` error on Windows, + // so use a supported signal instead + sig = 'SIGINT' + } + /* istanbul ignore next */ + process.kill(process.pid, sig) + } + } + }) + + module.exports.signals = function () { + return signals + } + + var loaded = false + + var load = function load () { + if (loaded || !processOk(global.process)) { + return + } + loaded = true + + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + emitter.count += 1 + + signals = signals.filter(function (sig) { + try { + process.on(sig, sigListeners[sig]) + return true + } catch (er) { + return false + } + }) + + process.emit = processEmit + process.reallyExit = processReallyExit + } + module.exports.load = load + + var originalProcessReallyExit = process.reallyExit + var processReallyExit = function processReallyExit (code) { + /* istanbul ignore if */ + if (!processOk(global.process)) { + return + } + process.exitCode = code || /* istanbul ignore next */ 0 + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + /* istanbul ignore next */ + originalProcessReallyExit.call(process, process.exitCode) + } + + var originalProcessEmit = process.emit + var processEmit = function processEmit (ev, arg) { + if (ev === 'exit' && processOk(global.process)) { + /* istanbul ignore else */ + if (arg !== undefined) { + process.exitCode = arg + } + var ret = originalProcessEmit.apply(this, arguments) + /* istanbul ignore next */ + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + /* istanbul ignore next */ + return ret + } else { + return originalProcessEmit.apply(this, arguments) + } + } +} diff --git a/node_modules/signal-exit/package.json b/node_modules/signal-exit/package.json new file mode 100644 index 0000000..3e6ee68 --- /dev/null +++ b/node_modules/signal-exit/package.json @@ -0,0 +1,38 @@ +{ + "name": "signal-exit", + "version": "3.0.6", + "description": "when you want to fire an event no matter how a process exits.", + "main": "index.js", + "scripts": { + "test": "tap", + "snap": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags" + }, + "files": [ + "index.js", + "signals.js" + ], + "repository": { + "type": "git", + "url": "https://github.com/tapjs/signal-exit.git" + }, + "keywords": [ + "signal", + "exit" + ], + "author": "Ben Coe ", + "license": "ISC", + "bugs": { + "url": "https://github.com/tapjs/signal-exit/issues" + }, + "homepage": "https://github.com/tapjs/signal-exit", + "devDependencies": { + "chai": "^3.5.0", + "coveralls": "^3.1.1", + "nyc": "^15.1.0", + "standard-version": "^9.3.1", + "tap": "^15.1.1" + } +} diff --git a/node_modules/signal-exit/signals.js b/node_modules/signal-exit/signals.js new file mode 100644 index 0000000..3bd67a8 --- /dev/null +++ b/node_modules/signal-exit/signals.js @@ -0,0 +1,53 @@ +// This is not the set of all possible signals. +// +// It IS, however, the set of all signals that trigger +// an exit on either Linux or BSD systems. Linux is a +// superset of the signal names supported on BSD, and +// the unknown signals just fail to register, so we can +// catch that easily enough. +// +// Don't bother with SIGKILL. It's uncatchable, which +// means that we can't fire any callbacks anyway. +// +// If a user does happen to register a handler on a non- +// fatal signal like SIGWINCH or something, and then +// exit, it'll end up firing `process.emit('exit')`, so +// the handler will be fired anyway. +// +// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised +// artificially, inherently leave the process in a +// state from which it is not safe to try and enter JS +// listeners. +module.exports = [ + 'SIGABRT', + 'SIGALRM', + 'SIGHUP', + 'SIGINT', + 'SIGTERM' +] + +if (process.platform !== 'win32') { + module.exports.push( + 'SIGVTALRM', + 'SIGXCPU', + 'SIGXFSZ', + 'SIGUSR2', + 'SIGTRAP', + 'SIGSYS', + 'SIGQUIT', + 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ) +} + +if (process.platform === 'linux') { + module.exports.push( + 'SIGIO', + 'SIGPOLL', + 'SIGPWR', + 'SIGSTKFLT', + 'SIGUNUSED' + ) +} diff --git a/node_modules/sliced/History.md b/node_modules/sliced/History.md new file mode 100644 index 0000000..e45cefe --- /dev/null +++ b/node_modules/sliced/History.md @@ -0,0 +1,41 @@ + +1.0.1 / 2015-07-14 +================== + + * fixed; missing file introduced in 4f5cea1 + +1.0.0 / 2015-07-12 +================== + + * Remove unnecessary files from npm package - #6 via joaquimserafim + * updated readme stats + +0.0.5 / 2013-02-05 +================== + + * optimization: remove use of arguments [jkroso](https://github.com/jkroso) + * add scripts to component.json [jkroso](https://github.com/jkroso) + * tests; remove time for travis + +0.0.4 / 2013-01-07 +================== + + * added component.json #1 [jkroso](https://github.com/jkroso) + * reversed array loop #1 [jkroso](https://github.com/jkroso) + * remove fn params + +0.0.3 / 2012-09-29 +================== + + * faster with negative start args + +0.0.2 / 2012-09-29 +================== + + * support full [].slice semantics + +0.0.1 / 2012-09-29 +=================== + + * initial release + diff --git a/node_modules/sliced/LICENSE b/node_modules/sliced/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/node_modules/sliced/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/sliced/README.md b/node_modules/sliced/README.md new file mode 100644 index 0000000..b6ff85e --- /dev/null +++ b/node_modules/sliced/README.md @@ -0,0 +1,62 @@ +#sliced +========== + +A faster alternative to `[].slice.call(arguments)`. + +[![Build Status](https://secure.travis-ci.org/aheckmann/sliced.png)](http://travis-ci.org/aheckmann/sliced) + +Example output from [benchmark.js](https://github.com/bestiejs/benchmark.js) + + Array.prototype.slice.call x 1,401,820 ops/sec ±2.16% (90 runs sampled) + [].slice.call x 1,313,116 ops/sec ±2.04% (96 runs sampled) + cached slice.call x 10,297,910 ops/sec ±1.81% (96 runs sampled) + sliced x 19,906,019 ops/sec ±1.23% (89 runs sampled) + fastest is sliced + + Array.prototype.slice.call(arguments, 1) x 1,373,238 ops/sec ±1.84% (95 runs sampled) + [].slice.call(arguments, 1) x 1,395,336 ops/sec ±1.36% (93 runs sampled) + cached slice.call(arguments, 1) x 9,926,018 ops/sec ±1.67% (92 runs sampled) + sliced(arguments, 1) x 20,747,990 ops/sec ±1.16% (93 runs sampled) + fastest is sliced(arguments, 1) + + Array.prototype.slice.call(arguments, -1) x 1,319,908 ops/sec ±2.12% (91 runs sampled) + [].slice.call(arguments, -1) x 1,336,170 ops/sec ±1.33% (97 runs sampled) + cached slice.call(arguments, -1) x 10,078,718 ops/sec ±1.21% (98 runs sampled) + sliced(arguments, -1) x 20,471,474 ops/sec ±1.81% (92 runs sampled) + fastest is sliced(arguments, -1) + + Array.prototype.slice.call(arguments, -2, -10) x 1,369,246 ops/sec ±1.68% (97 runs sampled) + [].slice.call(arguments, -2, -10) x 1,387,935 ops/sec ±1.70% (95 runs sampled) + cached slice.call(arguments, -2, -10) x 9,593,428 ops/sec ±1.23% (97 runs sampled) + sliced(arguments, -2, -10) x 23,178,931 ops/sec ±1.70% (92 runs sampled) + fastest is sliced(arguments, -2, -10) + + Array.prototype.slice.call(arguments, -2, -1) x 1,441,300 ops/sec ±1.26% (98 runs sampled) + [].slice.call(arguments, -2, -1) x 1,410,326 ops/sec ±1.96% (93 runs sampled) + cached slice.call(arguments, -2, -1) x 9,854,419 ops/sec ±1.02% (97 runs sampled) + sliced(arguments, -2, -1) x 22,550,801 ops/sec ±1.86% (91 runs sampled) + fastest is sliced(arguments, -2, -1) + +_Benchmark [source](https://github.com/aheckmann/sliced/blob/master/bench.js)._ + +##Usage + +`sliced` accepts the same arguments as `Array#slice` so you can easily swap it out. + +```js +function zing () { + var slow = [].slice.call(arguments, 1, 8); + var args = slice(arguments, 1, 8); + + var slow = Array.prototype.slice.call(arguments); + var args = slice(arguments); + // etc +} +``` + +## install + + npm install sliced + + +[LICENSE](https://github.com/aheckmann/sliced/blob/master/LICENSE) diff --git a/node_modules/sliced/index.js b/node_modules/sliced/index.js new file mode 100644 index 0000000..d88c85b --- /dev/null +++ b/node_modules/sliced/index.js @@ -0,0 +1,33 @@ + +/** + * An Array.prototype.slice.call(arguments) alternative + * + * @param {Object} args something with a length + * @param {Number} slice + * @param {Number} sliceEnd + * @api public + */ + +module.exports = function (args, slice, sliceEnd) { + var ret = []; + var len = args.length; + + if (0 === len) return ret; + + var start = slice < 0 + ? Math.max(0, slice + len) + : slice || 0; + + if (sliceEnd !== undefined) { + len = sliceEnd < 0 + ? sliceEnd + len + : sliceEnd + } + + while (len-- > start) { + ret[len - start] = args[len]; + } + + return ret; +} + diff --git a/node_modules/sliced/package.json b/node_modules/sliced/package.json new file mode 100644 index 0000000..6dda2bb --- /dev/null +++ b/node_modules/sliced/package.json @@ -0,0 +1,30 @@ +{ + "name": "sliced", + "version": "1.0.1", + "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", + "main": "index.js", + "files": [ + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/sliced" + }, + "keywords": [ + "arguments", + "slice", + "array" + ], + "author": "Aaron Heckmann ", + "license": "MIT", + "devDependencies": { + "mocha": "1.5.0", + "benchmark": "~1.0.0" + }, + "dependencies": {} +} diff --git a/node_modules/sparse-bitfield/.npmignore b/node_modules/sparse-bitfield/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/sparse-bitfield/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/sparse-bitfield/.travis.yml b/node_modules/sparse-bitfield/.travis.yml new file mode 100644 index 0000000..c042821 --- /dev/null +++ b/node_modules/sparse-bitfield/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - '4.0' + - '5.0' diff --git a/node_modules/sparse-bitfield/LICENSE b/node_modules/sparse-bitfield/LICENSE new file mode 100644 index 0000000..bae9da7 --- /dev/null +++ b/node_modules/sparse-bitfield/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/sparse-bitfield/README.md b/node_modules/sparse-bitfield/README.md new file mode 100644 index 0000000..7b6b8f9 --- /dev/null +++ b/node_modules/sparse-bitfield/README.md @@ -0,0 +1,62 @@ +# sparse-bitfield + +Bitfield implementation that allocates a series of 1kb buffers to support sparse bitfields +without allocating a massive buffer. If you want to simple implementation of a flat bitfield +see the [bitfield](https://github.com/fb55/bitfield) module. + +This module is mostly useful if you need a big bitfield where you won't nessecarily set every bit. + +``` +npm install sparse-bitfield +``` + +[![build status](http://img.shields.io/travis/mafintosh/sparse-bitfield.svg?style=flat)](http://travis-ci.org/mafintosh/sparse-bitfield) + +## Usage + +``` js +var bitfield = require('sparse-bitfield') +var bits = bitfield() + +bits.set(0, true) // set first bit +bits.set(1, true) // set second bit +bits.set(1000000000000, true) // set the 1.000.000.000.000th bit +``` + +Running the above example will allocate two 1kb buffers internally. +Each 1kb buffer can hold information about 8192 bits so the first one will be used to store information about the first two bits and the second will be used to store the 1.000.000.000.000th bit. + +## API + +#### `var bits = bitfield([options])` + +Create a new bitfield. Options include + +``` js +{ + pageSize: 1024, // how big should the partial buffers be + buffer: anExistingBitfield, + trackUpdates: false // track when pages are being updated in the pager +} +``` + +#### `bits.set(index, value)` + +Set a bit to true or false. + +#### `bits.get(index)` + +Get the value of a bit. + +#### `bits.pages` + +A [memory-pager](https://github.com/mafintosh/memory-pager) instance that is managing the underlying memory. +If you set `trackUpdates` to true in the constructor you can use `.lastUpdate()` on this instance to get the last updated memory page. + +#### `var buffer = bits.toBuffer()` + +Get a single buffer representing the entire bitfield. + +## License + +MIT diff --git a/node_modules/sparse-bitfield/index.js b/node_modules/sparse-bitfield/index.js new file mode 100644 index 0000000..ff458c9 --- /dev/null +++ b/node_modules/sparse-bitfield/index.js @@ -0,0 +1,95 @@ +var pager = require('memory-pager') + +module.exports = Bitfield + +function Bitfield (opts) { + if (!(this instanceof Bitfield)) return new Bitfield(opts) + if (!opts) opts = {} + if (Buffer.isBuffer(opts)) opts = {buffer: opts} + + this.pageOffset = opts.pageOffset || 0 + this.pageSize = opts.pageSize || 1024 + this.pages = opts.pages || pager(this.pageSize) + + this.byteLength = this.pages.length * this.pageSize + this.length = 8 * this.byteLength + + if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two') + + this._trackUpdates = !!opts.trackUpdates + this._pageMask = this.pageSize - 1 + + if (opts.buffer) { + for (var i = 0; i < opts.buffer.length; i += this.pageSize) { + this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)) + } + this.byteLength = opts.buffer.length + this.length = 8 * this.byteLength + } +} + +Bitfield.prototype.get = function (i) { + var o = i & 7 + var j = (i - o) / 8 + + return !!(this.getByte(j) & (128 >> o)) +} + +Bitfield.prototype.getByte = function (i) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, true) + + return page ? page.buffer[o + this.pageOffset] : 0 +} + +Bitfield.prototype.set = function (i, v) { + var o = i & 7 + var j = (i - o) / 8 + var b = this.getByte(j) + + return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) +} + +Bitfield.prototype.toBuffer = function () { + var all = alloc(this.pages.length * this.pageSize) + + for (var i = 0; i < this.pages.length; i++) { + var next = this.pages.get(i, true) + var allOffset = i * this.pageSize + if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize) + } + + return all +} + +Bitfield.prototype.setByte = function (i, b) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, false) + + o += this.pageOffset + + if (page.buffer[o] === b) return false + page.buffer[o] = b + + if (i >= this.byteLength) { + this.byteLength = i + 1 + this.length = this.byteLength * 8 + } + + if (this._trackUpdates) this.pages.updated(page) + + return true +} + +function alloc (n) { + if (Buffer.alloc) return Buffer.alloc(n) + var b = new Buffer(n) + b.fill(0) + return b +} + +function powerOfTwo (x) { + return !(x & (x - 1)) +} diff --git a/node_modules/sparse-bitfield/package.json b/node_modules/sparse-bitfield/package.json new file mode 100644 index 0000000..092a23f --- /dev/null +++ b/node_modules/sparse-bitfield/package.json @@ -0,0 +1,27 @@ +{ + "name": "sparse-bitfield", + "version": "3.0.3", + "description": "Bitfield that allocates a series of small buffers to support sparse bits without allocating a massive buffer", + "main": "index.js", + "dependencies": { + "memory-pager": "^1.0.2" + }, + "devDependencies": { + "buffer-alloc": "^1.1.0", + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/sparse-bitfield.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/sparse-bitfield/issues" + }, + "homepage": "https://github.com/mafintosh/sparse-bitfield" +} diff --git a/node_modules/sparse-bitfield/test.js b/node_modules/sparse-bitfield/test.js new file mode 100644 index 0000000..ae42ef4 --- /dev/null +++ b/node_modules/sparse-bitfield/test.js @@ -0,0 +1,79 @@ +var alloc = require('buffer-alloc') +var tape = require('tape') +var bitfield = require('./') + +tape('set and get', function (t) { + var bits = bitfield() + + t.same(bits.get(0), false, 'first bit is false') + bits.set(0, true) + t.same(bits.get(0), true, 'first bit is true') + t.same(bits.get(1), false, 'second bit is false') + bits.set(0, false) + t.same(bits.get(0), false, 'first bit is reset') + t.end() +}) + +tape('set large and get', function (t) { + var bits = bitfield() + + t.same(bits.get(9999999999999), false, 'large bit is false') + bits.set(9999999999999, true) + t.same(bits.get(9999999999999), true, 'large bit is true') + t.same(bits.get(9999999999999 + 1), false, 'large bit + 1 is false') + bits.set(9999999999999, false) + t.same(bits.get(9999999999999), false, 'large bit is reset') + t.end() +}) + +tape('get and set buffer', function (t) { + var bits = bitfield({trackUpdates: true}) + + t.same(bits.pages.get(0, true), undefined) + t.same(bits.pages.get(Math.floor(9999999999999 / 8 / 1024), true), undefined) + bits.set(9999999999999, true) + + var bits2 = bitfield() + var upd = bits.pages.lastUpdate() + bits2.pages.set(Math.floor(upd.offset / 1024), upd.buffer) + t.same(bits2.get(9999999999999), true, 'bit is set') + t.end() +}) + +tape('toBuffer', function (t) { + var bits = bitfield() + + t.same(bits.toBuffer(), alloc(0)) + + bits.set(0, true) + + t.same(bits.toBuffer(), bits.pages.get(0).buffer) + + bits.set(9000, true) + + t.same(bits.toBuffer(), Buffer.concat([bits.pages.get(0).buffer, bits.pages.get(1).buffer])) + t.end() +}) + +tape('pass in buffer', function (t) { + var bits = bitfield() + + bits.set(0, true) + bits.set(9000, true) + + var clone = bitfield(bits.toBuffer()) + + t.same(clone.get(0), true) + t.same(clone.get(9000), true) + t.end() +}) + +tape('set small buffer', function (t) { + var buf = alloc(1) + buf[0] = 255 + var bits = bitfield(buf) + + t.same(bits.get(0), true) + t.same(bits.pages.get(0).buffer.length, bits.pageSize) + t.end() +}) diff --git a/node_modules/statuses/HISTORY.md b/node_modules/statuses/HISTORY.md new file mode 100644 index 0000000..a1977b2 --- /dev/null +++ b/node_modules/statuses/HISTORY.md @@ -0,0 +1,65 @@ +1.5.0 / 2018-03-27 +================== + + * Add `103 Early Hints` + +1.4.0 / 2017-10-20 +================== + + * Add `STATUS_CODES` export + +1.3.1 / 2016-11-11 +================== + + * Fix return type in JSDoc + +1.3.0 / 2016-05-17 +================== + + * Add `421 Misdirected Request` + * perf: enable strict mode + +1.2.1 / 2015-02-01 +================== + + * Fix message for status 451 + - `451 Unavailable For Legal Reasons` + +1.2.0 / 2014-09-28 +================== + + * Add `208 Already Repored` + * Add `226 IM Used` + * Add `306 (Unused)` + * Add `415 Unable For Legal Reasons` + * Add `508 Loop Detected` + +1.1.1 / 2014-09-24 +================== + + * Add missing 308 to `codes.json` + +1.1.0 / 2014-09-21 +================== + + * Add `codes.json` for universal support + +1.0.4 / 2014-08-20 +================== + + * Package cleanup + +1.0.3 / 2014-06-08 +================== + + * Add 308 to `.redirect` category + +1.0.2 / 2014-03-13 +================== + + * Add `.retry` category + +1.0.1 / 2014-03-12 +================== + + * Initial release diff --git a/node_modules/statuses/LICENSE b/node_modules/statuses/LICENSE new file mode 100644 index 0000000..28a3161 --- /dev/null +++ b/node_modules/statuses/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2016 Douglas Christopher Wilson + +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/statuses/README.md b/node_modules/statuses/README.md new file mode 100644 index 0000000..0fe5720 --- /dev/null +++ b/node_modules/statuses/README.md @@ -0,0 +1,127 @@ +# Statuses + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP status utility for node. + +This module provides a list of status codes and messages sourced from +a few different projects: + + * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) + * The [Node.js project](https://nodejs.org/) + * The [NGINX project](https://www.nginx.com/) + * The [Apache HTTP Server project](https://httpd.apache.org/) + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install statuses +``` + +## API + + + +```js +var status = require('statuses') +``` + +### var code = status(Integer || String) + +If `Integer` or `String` is a valid HTTP code or status message, then the +appropriate `code` will be returned. Otherwise, an error will be thrown. + + + +```js +status(403) // => 403 +status('403') // => 403 +status('forbidden') // => 403 +status('Forbidden') // => 403 +status(306) // throws, as it's not supported by node.js +``` + +### status.STATUS_CODES + +Returns an object which maps status codes to status messages, in +the same format as the +[Node.js http module](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### var msg = status[code] + +Map of `code` to `status message`. `undefined` for invalid `code`s. + + + +```js +status[404] // => 'Not Found' +``` + +### var code = status[msg] + +Map of `status message` to `code`. `msg` can either be title-cased or +lower-cased. `undefined` for invalid `status message`s. + + + +```js +status['not found'] // => 404 +status['Not Found'] // => 404 +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + + + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + + + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + + + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +[npm-image]: https://img.shields.io/npm/v/statuses.svg +[npm-url]: https://npmjs.org/package/statuses +[node-version-image]: https://img.shields.io/node/v/statuses.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/statuses.svg +[travis-url]: https://travis-ci.org/jshttp/statuses +[coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[downloads-image]: https://img.shields.io/npm/dm/statuses.svg +[downloads-url]: https://npmjs.org/package/statuses diff --git a/node_modules/statuses/codes.json b/node_modules/statuses/codes.json new file mode 100644 index 0000000..a09283a --- /dev/null +++ b/node_modules/statuses/codes.json @@ -0,0 +1,66 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "(Unused)", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} diff --git a/node_modules/statuses/index.js b/node_modules/statuses/index.js new file mode 100644 index 0000000..4df469a --- /dev/null +++ b/node_modules/statuses/index.js @@ -0,0 +1,113 @@ +/*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var codes = require('./codes.json') + +/** + * Module exports. + * @public + */ + +module.exports = status + +// status code to message map +status.STATUS_CODES = codes + +// array of status codes +status.codes = populateStatusesMap(status, codes) + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true +} + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true +} + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true +} + +/** + * Populate the statuses map for given codes. + * @private + */ + +function populateStatusesMap (statuses, codes) { + var arr = [] + + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code] + var status = Number(code) + + // Populate properties + statuses[status] = message + statuses[message] = status + statuses[message.toLowerCase()] = status + + // Add to array + arr.push(status) + }) + + return arr +} + +/** + * Get the status code. + * + * Given a number, this will throw if it is not a known status + * code, otherwise the code will be returned. Given a string, + * the string will be parsed for a number and return the code + * if valid, otherwise will lookup the code assuming this is + * the status message. + * + * @param {string|number} code + * @returns {number} + * @public + */ + +function status (code) { + if (typeof code === 'number') { + if (!status[code]) throw new Error('invalid status code: ' + code) + return code + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + if (!status[n]) throw new Error('invalid status code: ' + n) + return n + } + + n = status[code.toLowerCase()] + if (!n) throw new Error('invalid status message: "' + code + '"') + return n +} diff --git a/node_modules/statuses/package.json b/node_modules/statuses/package.json new file mode 100644 index 0000000..7595e2b --- /dev/null +++ b/node_modules/statuses/package.json @@ -0,0 +1,48 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "1.5.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "jshttp/statuses", + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "HISTORY.md", + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "1.2.4", + "eslint": "4.19.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.9.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.7.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5", + "raw-body": "2.3.2", + "stream-to-array": "2.3.0" + }, + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build.js", + "fetch": "node scripts/fetch-apache.js && node scripts/fetch-iana.js && node scripts/fetch-nginx.js && node scripts/fetch-node.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "update": "npm run fetch && npm run build" + } +} 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/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..778edb2 --- /dev/null +++ b/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node 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. +""" + diff --git a/node_modules/string_decoder/README.md b/node_modules/string_decoder/README.md new file mode 100644 index 0000000..5fd5831 --- /dev/null +++ b/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/node_modules/string_decoder/lib/string_decoder.js b/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 0000000..2e89e63 --- /dev/null +++ b/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/node_modules/string_decoder/node_modules/safe-buffer/LICENSE b/node_modules/string_decoder/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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_decoder/node_modules/safe-buffer/README.md b/node_modules/string_decoder/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +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'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +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 to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that 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(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +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(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +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 to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` 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()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.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); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts b/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): 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'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/string_decoder/node_modules/safe-buffer/index.js b/node_modules/string_decoder/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..f8d3ec9 --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/string_decoder/node_modules/safe-buffer/package.json b/node_modules/string_decoder/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..f2869e2 --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/package.json @@ -0,0 +1,51 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/string_decoder/package.json b/node_modules/string_decoder/package.json new file mode 100644 index 0000000..b2bb141 --- /dev/null +++ b/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "1.3.0", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "files": [ + "lib" + ], + "dependencies": { + "safe-buffer": "~5.2.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} 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/tar/LICENSE b/node_modules/tar/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/tar/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/tar/README.md b/node_modules/tar/README.md new file mode 100644 index 0000000..42afb1a --- /dev/null +++ b/node_modules/tar/README.md @@ -0,0 +1,1042 @@ +# node-tar + +[Fast](./benchmarks) and full-featured Tar for Node.js + +The API is designed to mimic the behavior of `tar(1)` on unix systems. +If you are familiar with how tar works, most of this will hopefully be +straightforward for you. If not, then hopefully this module can teach +you useful unix skills that may come in handy someday :) + +## Background + +A "tar file" or "tarball" is an archive of file system entries +(directories, files, links, etc.) The name comes from "tape archive". +If you run `man tar` on almost any Unix command line, you'll learn +quite a bit about what it can do, and its history. + +Tar has 5 main top-level commands: + +* `c` Create an archive +* `r` Replace entries within an archive +* `u` Update entries within an archive (ie, replace if they're newer) +* `t` List out the contents of an archive +* `x` Extract an archive to disk + +The other flags and options modify how this top level function works. + +## High-Level API + +These 5 functions are the high-level API. All of them have a +single-character name (for unix nerds familiar with `tar(1)`) as well +as a long name (for everyone else). + +All the high-level functions take the following arguments, all three +of which are optional and may be omitted. + +1. `options` - An optional object specifying various options +2. `paths` - An array of paths to add or extract +3. `callback` - Called when the command is completed, if async. (If + sync or no file specified, providing a callback throws a + `TypeError`.) + +If the command is sync (ie, if `options.sync=true`), then the +callback is not allowed, since the action will be completed immediately. + +If a `file` argument is specified, and the command is async, then a +`Promise` is returned. In this case, if async, a callback may be +provided which is called when the command is completed. + +If a `file` option is not specified, then a stream is returned. For +`create`, this is a readable stream of the generated archive. For +`list` and `extract` this is a writable stream that an archive should +be written into. If a file is not specified, then a callback is not +allowed, because you're already getting a stream to work with. + +`replace` and `update` only work on existing archives, and so require +a `file` argument. + +Sync commands without a file argument return a stream that acts on its +input immediately in the same tick. For readable streams, this means +that all of the data is immediately available by calling +`stream.read()`. For writable streams, it will be acted upon as soon +as it is provided, but this can be at any time. + +### Warnings and Errors + +Tar emits warnings and errors for recoverable and unrecoverable situations, +respectively. In many cases, a warning only affects a single entry in an +archive, or is simply informing you that it's modifying an entry to comply +with the settings provided. + +Unrecoverable warnings will always raise an error (ie, emit `'error'` on +streaming actions, throw for non-streaming sync actions, reject the +returned Promise for non-streaming async operations, or call a provided +callback with an `Error` as the first argument). Recoverable errors will +raise an error only if `strict: true` is set in the options. + +Respond to (recoverable) warnings by listening to the `warn` event. +Handlers receive 3 arguments: + +- `code` String. One of the error codes below. This may not match + `data.code`, which preserves the original error code from fs and zlib. +- `message` String. More details about the error. +- `data` Metadata about the error. An `Error` object for errors raised by + fs and zlib. All fields are attached to errors raisd by tar. Typically + contains the following fields, as relevant: + - `tarCode` The tar error code. + - `code` Either the tar error code, or the error code set by the + underlying system. + - `file` The archive file being read or written. + - `cwd` Working directory for creation and extraction operations. + - `entry` The entry object (if it could be created) for `TAR_ENTRY_INFO`, + `TAR_ENTRY_INVALID`, and `TAR_ENTRY_ERROR` warnings. + - `header` The header object (if it could be created, and the entry could + not be created) for `TAR_ENTRY_INFO` and `TAR_ENTRY_INVALID` warnings. + - `recoverable` Boolean. If `false`, then the warning will emit an + `error`, even in non-strict mode. + +#### Error Codes + +* `TAR_ENTRY_INFO` An informative error indicating that an entry is being + modified, but otherwise processed normally. For example, removing `/` or + `C:\` from absolute paths if `preservePaths` is not set. + +* `TAR_ENTRY_INVALID` An indication that a given entry is not a valid tar + archive entry, and will be skipped. This occurs when: + - a checksum fails, + - a `linkpath` is missing for a link type, or + - a `linkpath` is provided for a non-link type. + + If every entry in a parsed archive raises an `TAR_ENTRY_INVALID` error, + then the archive is presumed to be unrecoverably broken, and + `TAR_BAD_ARCHIVE` will be raised. + +* `TAR_ENTRY_ERROR` The entry appears to be a valid tar archive entry, but + encountered an error which prevented it from being unpacked. This occurs + when: + - an unrecoverable fs error happens during unpacking, + - an entry has `..` in the path and `preservePaths` is not set, or + - an entry is extracting through a symbolic link, when `preservePaths` is + not set. + +* `TAR_ENTRY_UNSUPPORTED` An indication that a given entry is + a valid archive entry, but of a type that is unsupported, and so will be + skipped in archive creation or extracting. + +* `TAR_ABORT` When parsing gzipped-encoded archives, the parser will + abort the parse process raise a warning for any zlib errors encountered. + Aborts are considered unrecoverable for both parsing and unpacking. + +* `TAR_BAD_ARCHIVE` The archive file is totally hosed. This can happen for + a number of reasons, and always occurs at the end of a parse or extract: + + - An entry body was truncated before seeing the full number of bytes. + - The archive contained only invalid entries, indicating that it is + likely not an archive, or at least, not an archive this library can + parse. + + `TAR_BAD_ARCHIVE` is considered informative for parse operations, but + unrecoverable for extraction. Note that, if encountered at the end of an + extraction, tar WILL still have extracted as much it could from the + archive, so there may be some garbage files to clean up. + +Errors that occur deeper in the system (ie, either the filesystem or zlib) +will have their error codes left intact, and a `tarCode` matching one of +the above will be added to the warning metadata or the raised error object. + +Errors generated by tar will have one of the above codes set as the +`error.code` field as well, but since errors originating in zlib or fs will +have their original codes, it's better to read `error.tarCode` if you wish +to see how tar is handling the issue. + +### Examples + +The API mimics the `tar(1)` command line functionality, with aliases +for more human-readable option and function names. The goal is that +if you know how to use `tar(1)` in Unix, then you know how to use +`require('tar')` in JavaScript. + +To replicate `tar czf my-tarball.tgz files and folders`, you'd do: + +```js +tar.c( + { + gzip: , + file: 'my-tarball.tgz' + }, + ['some', 'files', 'and', 'folders'] +).then(_ => { .. tarball has been created .. }) +``` + +To replicate `tar cz files and folders > my-tarball.tgz`, you'd do: + +```js +tar.c( // or tar.create + { + gzip: + }, + ['some', 'files', 'and', 'folders'] +).pipe(fs.createWriteStream('my-tarball.tgz')) +``` + +To replicate `tar xf my-tarball.tgz` you'd do: + +```js +tar.x( // or tar.extract( + { + file: 'my-tarball.tgz' + } +).then(_=> { .. tarball has been dumped in cwd .. }) +``` + +To replicate `cat my-tarball.tgz | tar x -C some-dir --strip=1`: + +```js +fs.createReadStream('my-tarball.tgz').pipe( + tar.x({ + strip: 1, + C: 'some-dir' // alias for cwd:'some-dir', also ok + }) +) +``` + +To replicate `tar tf my-tarball.tgz`, do this: + +```js +tar.t({ + file: 'my-tarball.tgz', + onentry: entry => { .. do whatever with it .. } +}) +``` + +To replicate `cat my-tarball.tgz | tar t` do: + +```js +fs.createReadStream('my-tarball.tgz') + .pipe(tar.t()) + .on('entry', entry => { .. do whatever with it .. }) +``` + +To do anything synchronous, add `sync: true` to the options. Note +that sync functions don't take a callback and don't return a promise. +When the function returns, it's already done. Sync methods without a +file argument return a sync stream, which flushes immediately. But, +of course, it still won't be done until you `.end()` it. + +To filter entries, add `filter: ` to the options. +Tar-creating methods call the filter with `filter(path, stat)`. +Tar-reading methods (including extraction) call the filter with +`filter(path, entry)`. The filter is called in the `this`-context of +the `Pack` or `Unpack` stream object. + +The arguments list to `tar t` and `tar x` specify a list of filenames +to extract or list, so they're equivalent to a filter that tests if +the file is in the list. + +For those who _aren't_ fans of tar's single-character command names: + +``` +tar.c === tar.create +tar.r === tar.replace (appends to archive, file is required) +tar.u === tar.update (appends if newer, file is required) +tar.x === tar.extract +tar.t === tar.list +``` + +Keep reading for all the command descriptions and options, as well as +the low-level API that they are built on. + +### tar.c(options, fileList, callback) [alias: tar.create] + +Create a tarball archive. + +The `fileList` is an array of paths to add to the tarball. Adding a +directory also adds its children recursively. + +An entry in `fileList` that starts with an `@` symbol is a tar archive +whose entries will be added. To add a file that starts with `@`, +prepend it with `./`. + +The following options are supported: + +- `file` Write the tarball archive to the specified filename. If this + is specified, then the callback will be fired when the file has been + written, and a promise will be returned that resolves when the file + is written. If a filename is not specified, then a Readable Stream + will be returned which will emit the file data. [Alias: `f`] +- `sync` Act synchronously. If this is set, then any provided file + will be fully written after the call to `tar.c`. If this is set, + and a file is not provided, then the resulting stream will already + have the data ready to `read` or `emit('data')` as soon as you + request it. +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") +- `strict` Treat warnings as crash-worthy errors. Default false. +- `cwd` The current working directory for creating the archive. + Defaults to `process.cwd()`. [Alias: `C`] +- `prefix` A path portion to prefix onto the entries in the archive. +- `gzip` Set to any truthy value to create a gzipped archive, or an + object with settings for `zlib.Gzip()` [Alias: `z`] +- `filter` A function that gets called with `(path, stat)` for each + entry being added. Return `true` to add the entry to the archive, + or `false` to omit it. +- `portable` Omit metadata that is system-specific: `ctime`, `atime`, + `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note + that `mtime` is still included, because this is necessary for other + time-based operations. Additionally, `mode` is set to a "reasonable + default" for most unix systems, based on a `umask` value of `0o22`. +- `preservePaths` Allow absolute paths. By default, `/` is stripped + from absolute paths. [Alias: `P`] +- `mode` The mode to set on the created file archive +- `noDirRecurse` Do not recursively archive the contents of + directories. [Alias: `n`] +- `follow` Set to true to pack the targets of symbolic links. Without + this option, symbolic links are archived as such. [Alias: `L`, `h`] +- `noPax` Suppress pax extended headers. Note that this means that + long paths and linkpaths will be truncated, and large or negative + numeric values may be interpreted incorrectly. +- `noMtime` Set to true to omit writing `mtime` values for entries. + Note that this prevents using other mtime-based features like + `tar.update` or the `keepNewer` option with the resulting tar archive. + [Alias: `m`, `no-mtime`] +- `mtime` Set to a `Date` object to force a specific `mtime` for + everything added to the archive. Overridden by `noMtime`. + +The following options are mostly internal, but can be modified in some +advanced use cases, such as re-using caches between runs. + +- `linkCache` A Map object containing the device and inode value for + any file whose nlink is > 1, to identify hard links. +- `statCache` A Map object that caches calls `lstat`. +- `readdirCache` A Map object that caches calls to `readdir`. +- `jobs` A number specifying how many concurrent jobs to run. + Defaults to 4. +- `maxReadSize` The maximum buffer size for `fs.read()` operations. + Defaults to 16 MB. + +### tar.x(options, fileList, callback) [alias: tar.extract] + +Extract a tarball archive. + +The `fileList` is an array of paths to extract from the tarball. If +no paths are provided, then all the entries are extracted. + +If the archive is gzipped, then tar will detect this and unzip it. + +Note that all directories that are created will be forced to be +writable, readable, and listable by their owner, to avoid cases where +a directory prevents extraction of child entries by virtue of its +mode. + +Most extraction errors will cause a `warn` event to be emitted. If +the `cwd` is missing, or not a directory, then the extraction will +fail completely. + +The following options are supported: + +- `cwd` Extract files relative to the specified directory. Defaults + to `process.cwd()`. If provided, this must exist and must be a + directory. [Alias: `C`] +- `file` The archive file to extract. If not specified, then a + Writable stream is returned where the archive data should be + written. [Alias: `f`] +- `sync` Create files and directories synchronously. +- `strict` Treat warnings as crash-worthy errors. Default false. +- `filter` A function that gets called with `(path, entry)` for each + entry being unpacked. Return `true` to unpack the entry from the + archive, or `false` to skip it. +- `newer` Set to true to keep the existing file on disk if it's newer + than the file in the archive. [Alias: `keep-newer`, + `keep-newer-files`] +- `keep` Do not overwrite existing files. In particular, if a file + appears more than once in an archive, later copies will not + overwrite earlier copies. [Alias: `k`, `keep-existing`] +- `preservePaths` Allow absolute paths, paths containing `..`, and + extracting through symbolic links. By default, `/` is stripped from + absolute paths, `..` paths are not extracted, and any file whose + location would be modified by a symbolic link is not extracted. + [Alias: `P`] +- `unlink` Unlink files before creating them. Without this option, + tar overwrites existing files, which preserves existing hardlinks. + With this option, existing hardlinks will be broken, as will any + symlink that would affect the location of an extracted file. [Alias: + `U`] +- `strip` Remove the specified number of leading path elements. + Pathnames with fewer elements will be silently skipped. Note that + the pathname is edited after applying the filter, but before + security checks. [Alias: `strip-components`, `stripComponents`] +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") +- `preserveOwner` If true, tar will set the `uid` and `gid` of + extracted entries to the `uid` and `gid` fields in the archive. + This defaults to true when run as root, and false otherwise. If + false, then files and directories will be set with the owner and + group of the user running the process. This is similar to `-p` in + `tar(1)`, but ACLs and other system-specific data is never unpacked + in this implementation, and modes are set by default already. + [Alias: `p`] +- `uid` Set to a number to force ownership of all extracted files and + folders, and all implicitly created directories, to be owned by the + specified user id, regardless of the `uid` field in the archive. + Cannot be used along with `preserveOwner`. Requires also setting a + `gid` option. +- `gid` Set to a number to force ownership of all extracted files and + folders, and all implicitly created directories, to be owned by the + specified group id, regardless of the `gid` field in the archive. + Cannot be used along with `preserveOwner`. Requires also setting a + `uid` option. +- `noMtime` Set to true to omit writing `mtime` value for extracted + entries. [Alias: `m`, `no-mtime`] +- `transform` Provide a function that takes an `entry` object, and + returns a stream, or any falsey value. If a stream is provided, + then that stream's data will be written instead of the contents of + the archive entry. If a falsey value is provided, then the entry is + written to disk as normal. (To exclude items from extraction, use + the `filter` option described above.) +- `onentry` A function that gets called with `(entry)` for each entry + that passes the filter. +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") +- `noChmod` Set to true to omit calling `fs.chmod()` to ensure that the + extracted file matches the entry mode. This also suppresses the call to + `process.umask()` to determine the default umask value, since tar will + extract with whatever mode is provided, and let the process `umask` apply + normally. + +The following options are mostly internal, but can be modified in some +advanced use cases, such as re-using caches between runs. + +- `maxReadSize` The maximum buffer size for `fs.read()` operations. + Defaults to 16 MB. +- `umask` Filter the modes of entries like `process.umask()`. +- `dmode` Default mode for directories +- `fmode` Default mode for files +- `dirCache` A Map object of which directories exist. +- `maxMetaEntrySize` The maximum size of meta entries that is + supported. Defaults to 1 MB. + +Note that using an asynchronous stream type with the `transform` +option will cause undefined behavior in sync extractions. +[MiniPass](http://npm.im/minipass)-based streams are designed for this +use case. + +### tar.t(options, fileList, callback) [alias: tar.list] + +List the contents of a tarball archive. + +The `fileList` is an array of paths to list from the tarball. If +no paths are provided, then all the entries are listed. + +If the archive is gzipped, then tar will detect this and unzip it. + +Returns an event emitter that emits `entry` events with +`tar.ReadEntry` objects. However, they don't emit `'data'` or `'end'` +events. (If you want to get actual readable entries, use the +`tar.Parse` class instead.) + +The following options are supported: + +- `cwd` Extract files relative to the specified directory. Defaults + to `process.cwd()`. [Alias: `C`] +- `file` The archive file to list. If not specified, then a + Writable stream is returned where the archive data should be + written. [Alias: `f`] +- `sync` Read the specified file synchronously. (This has no effect + when a file option isn't specified, because entries are emitted as + fast as they are parsed from the stream anyway.) +- `strict` Treat warnings as crash-worthy errors. Default false. +- `filter` A function that gets called with `(path, entry)` for each + entry being listed. Return `true` to emit the entry from the + archive, or `false` to skip it. +- `onentry` A function that gets called with `(entry)` for each entry + that passes the filter. This is important for when both `file` and + `sync` are set, because it will be called synchronously. +- `maxReadSize` The maximum buffer size for `fs.read()` operations. + Defaults to 16 MB. +- `noResume` By default, `entry` streams are resumed immediately after + the call to `onentry`. Set `noResume: true` to suppress this + behavior. Note that by opting into this, the stream will never + complete until the entry data is consumed. +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") + +### tar.u(options, fileList, callback) [alias: tar.update] + +Add files to an archive if they are newer than the entry already in +the tarball archive. + +The `fileList` is an array of paths to add to the tarball. Adding a +directory also adds its children recursively. + +An entry in `fileList` that starts with an `@` symbol is a tar archive +whose entries will be added. To add a file that starts with `@`, +prepend it with `./`. + +The following options are supported: + +- `file` Required. Write the tarball archive to the specified + filename. [Alias: `f`] +- `sync` Act synchronously. If this is set, then any provided file + will be fully written after the call to `tar.c`. +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") +- `strict` Treat warnings as crash-worthy errors. Default false. +- `cwd` The current working directory for adding entries to the + archive. Defaults to `process.cwd()`. [Alias: `C`] +- `prefix` A path portion to prefix onto the entries in the archive. +- `gzip` Set to any truthy value to create a gzipped archive, or an + object with settings for `zlib.Gzip()` [Alias: `z`] +- `filter` A function that gets called with `(path, stat)` for each + entry being added. Return `true` to add the entry to the archive, + or `false` to omit it. +- `portable` Omit metadata that is system-specific: `ctime`, `atime`, + `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note + that `mtime` is still included, because this is necessary for other + time-based operations. Additionally, `mode` is set to a "reasonable + default" for most unix systems, based on a `umask` value of `0o22`. +- `preservePaths` Allow absolute paths. By default, `/` is stripped + from absolute paths. [Alias: `P`] +- `maxReadSize` The maximum buffer size for `fs.read()` operations. + Defaults to 16 MB. +- `noDirRecurse` Do not recursively archive the contents of + directories. [Alias: `n`] +- `follow` Set to true to pack the targets of symbolic links. Without + this option, symbolic links are archived as such. [Alias: `L`, `h`] +- `noPax` Suppress pax extended headers. Note that this means that + long paths and linkpaths will be truncated, and large or negative + numeric values may be interpreted incorrectly. +- `noMtime` Set to true to omit writing `mtime` values for entries. + Note that this prevents using other mtime-based features like + `tar.update` or the `keepNewer` option with the resulting tar archive. + [Alias: `m`, `no-mtime`] +- `mtime` Set to a `Date` object to force a specific `mtime` for + everything added to the archive. Overridden by `noMtime`. + +### tar.r(options, fileList, callback) [alias: tar.replace] + +Add files to an existing archive. Because later entries override +earlier entries, this effectively replaces any existing entries. + +The `fileList` is an array of paths to add to the tarball. Adding a +directory also adds its children recursively. + +An entry in `fileList` that starts with an `@` symbol is a tar archive +whose entries will be added. To add a file that starts with `@`, +prepend it with `./`. + +The following options are supported: + +- `file` Required. Write the tarball archive to the specified + filename. [Alias: `f`] +- `sync` Act synchronously. If this is set, then any provided file + will be fully written after the call to `tar.c`. +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") +- `strict` Treat warnings as crash-worthy errors. Default false. +- `cwd` The current working directory for adding entries to the + archive. Defaults to `process.cwd()`. [Alias: `C`] +- `prefix` A path portion to prefix onto the entries in the archive. +- `gzip` Set to any truthy value to create a gzipped archive, or an + object with settings for `zlib.Gzip()` [Alias: `z`] +- `filter` A function that gets called with `(path, stat)` for each + entry being added. Return `true` to add the entry to the archive, + or `false` to omit it. +- `portable` Omit metadata that is system-specific: `ctime`, `atime`, + `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note + that `mtime` is still included, because this is necessary for other + time-based operations. Additionally, `mode` is set to a "reasonable + default" for most unix systems, based on a `umask` value of `0o22`. +- `preservePaths` Allow absolute paths. By default, `/` is stripped + from absolute paths. [Alias: `P`] +- `maxReadSize` The maximum buffer size for `fs.read()` operations. + Defaults to 16 MB. +- `noDirRecurse` Do not recursively archive the contents of + directories. [Alias: `n`] +- `follow` Set to true to pack the targets of symbolic links. Without + this option, symbolic links are archived as such. [Alias: `L`, `h`] +- `noPax` Suppress pax extended headers. Note that this means that + long paths and linkpaths will be truncated, and large or negative + numeric values may be interpreted incorrectly. +- `noMtime` Set to true to omit writing `mtime` values for entries. + Note that this prevents using other mtime-based features like + `tar.update` or the `keepNewer` option with the resulting tar archive. + [Alias: `m`, `no-mtime`] +- `mtime` Set to a `Date` object to force a specific `mtime` for + everything added to the archive. Overridden by `noMtime`. + + +## Low-Level API + +### class tar.Pack + +A readable tar stream. + +Has all the standard readable stream interface stuff. `'data'` and +`'end'` events, `read()` method, `pause()` and `resume()`, etc. + +#### constructor(options) + +The following options are supported: + +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") +- `strict` Treat warnings as crash-worthy errors. Default false. +- `cwd` The current working directory for creating the archive. + Defaults to `process.cwd()`. +- `prefix` A path portion to prefix onto the entries in the archive. +- `gzip` Set to any truthy value to create a gzipped archive, or an + object with settings for `zlib.Gzip()` +- `filter` A function that gets called with `(path, stat)` for each + entry being added. Return `true` to add the entry to the archive, + or `false` to omit it. +- `portable` Omit metadata that is system-specific: `ctime`, `atime`, + `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note + that `mtime` is still included, because this is necessary for other + time-based operations. Additionally, `mode` is set to a "reasonable + default" for most unix systems, based on a `umask` value of `0o22`. +- `preservePaths` Allow absolute paths. By default, `/` is stripped + from absolute paths. +- `linkCache` A Map object containing the device and inode value for + any file whose nlink is > 1, to identify hard links. +- `statCache` A Map object that caches calls `lstat`. +- `readdirCache` A Map object that caches calls to `readdir`. +- `jobs` A number specifying how many concurrent jobs to run. + Defaults to 4. +- `maxReadSize` The maximum buffer size for `fs.read()` operations. + Defaults to 16 MB. +- `noDirRecurse` Do not recursively archive the contents of + directories. +- `follow` Set to true to pack the targets of symbolic links. Without + this option, symbolic links are archived as such. +- `noPax` Suppress pax extended headers. Note that this means that + long paths and linkpaths will be truncated, and large or negative + numeric values may be interpreted incorrectly. +- `noMtime` Set to true to omit writing `mtime` values for entries. + Note that this prevents using other mtime-based features like + `tar.update` or the `keepNewer` option with the resulting tar archive. +- `mtime` Set to a `Date` object to force a specific `mtime` for + everything added to the archive. Overridden by `noMtime`. + +#### add(path) + +Adds an entry to the archive. Returns the Pack stream. + +#### write(path) + +Adds an entry to the archive. Returns true if flushed. + +#### end() + +Finishes the archive. + +### class tar.Pack.Sync + +Synchronous version of `tar.Pack`. + +### class tar.Unpack + +A writable stream that unpacks a tar archive onto the file system. + +All the normal writable stream stuff is supported. `write()` and +`end()` methods, `'drain'` events, etc. + +Note that all directories that are created will be forced to be +writable, readable, and listable by their owner, to avoid cases where +a directory prevents extraction of child entries by virtue of its +mode. + +`'close'` is emitted when it's done writing stuff to the file system. + +Most unpack errors will cause a `warn` event to be emitted. If the +`cwd` is missing, or not a directory, then an error will be emitted. + +#### constructor(options) + +- `cwd` Extract files relative to the specified directory. Defaults + to `process.cwd()`. If provided, this must exist and must be a + directory. +- `filter` A function that gets called with `(path, entry)` for each + entry being unpacked. Return `true` to unpack the entry from the + archive, or `false` to skip it. +- `newer` Set to true to keep the existing file on disk if it's newer + than the file in the archive. +- `keep` Do not overwrite existing files. In particular, if a file + appears more than once in an archive, later copies will not + overwrite earlier copies. +- `preservePaths` Allow absolute paths, paths containing `..`, and + extracting through symbolic links. By default, `/` is stripped from + absolute paths, `..` paths are not extracted, and any file whose + location would be modified by a symbolic link is not extracted. +- `unlink` Unlink files before creating them. Without this option, + tar overwrites existing files, which preserves existing hardlinks. + With this option, existing hardlinks will be broken, as will any + symlink that would affect the location of an extracted file. +- `strip` Remove the specified number of leading path elements. + Pathnames with fewer elements will be silently skipped. Note that + the pathname is edited after applying the filter, but before + security checks. +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") +- `umask` Filter the modes of entries like `process.umask()`. +- `dmode` Default mode for directories +- `fmode` Default mode for files +- `dirCache` A Map object of which directories exist. +- `maxMetaEntrySize` The maximum size of meta entries that is + supported. Defaults to 1 MB. +- `preserveOwner` If true, tar will set the `uid` and `gid` of + extracted entries to the `uid` and `gid` fields in the archive. + This defaults to true when run as root, and false otherwise. If + false, then files and directories will be set with the owner and + group of the user running the process. This is similar to `-p` in + `tar(1)`, but ACLs and other system-specific data is never unpacked + in this implementation, and modes are set by default already. +- `win32` True if on a windows platform. Causes behavior where + filenames containing `<|>?` chars are converted to + windows-compatible values while being unpacked. +- `uid` Set to a number to force ownership of all extracted files and + folders, and all implicitly created directories, to be owned by the + specified user id, regardless of the `uid` field in the archive. + Cannot be used along with `preserveOwner`. Requires also setting a + `gid` option. +- `gid` Set to a number to force ownership of all extracted files and + folders, and all implicitly created directories, to be owned by the + specified group id, regardless of the `gid` field in the archive. + Cannot be used along with `preserveOwner`. Requires also setting a + `uid` option. +- `noMtime` Set to true to omit writing `mtime` value for extracted + entries. +- `transform` Provide a function that takes an `entry` object, and + returns a stream, or any falsey value. If a stream is provided, + then that stream's data will be written instead of the contents of + the archive entry. If a falsey value is provided, then the entry is + written to disk as normal. (To exclude items from extraction, use + the `filter` option described above.) +- `strict` Treat warnings as crash-worthy errors. Default false. +- `onentry` A function that gets called with `(entry)` for each entry + that passes the filter. +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") +- `noChmod` Set to true to omit calling `fs.chmod()` to ensure that the + extracted file matches the entry mode. This also suppresses the call to + `process.umask()` to determine the default umask value, since tar will + extract with whatever mode is provided, and let the process `umask` apply + normally. + +### class tar.Unpack.Sync + +Synchronous version of `tar.Unpack`. + +Note that using an asynchronous stream type with the `transform` +option will cause undefined behavior in sync unpack streams. +[MiniPass](http://npm.im/minipass)-based streams are designed for this +use case. + +### class tar.Parse + +A writable stream that parses a tar archive stream. All the standard +writable stream stuff is supported. + +If the archive is gzipped, then tar will detect this and unzip it. + +Emits `'entry'` events with `tar.ReadEntry` objects, which are +themselves readable streams that you can pipe wherever. + +Each `entry` will not emit until the one before it is flushed through, +so make sure to either consume the data (with `on('data', ...)` or +`.pipe(...)`) or throw it away with `.resume()` to keep the stream +flowing. + +#### constructor(options) + +Returns an event emitter that emits `entry` events with +`tar.ReadEntry` objects. + +The following options are supported: + +- `strict` Treat warnings as crash-worthy errors. Default false. +- `filter` A function that gets called with `(path, entry)` for each + entry being listed. Return `true` to emit the entry from the + archive, or `false` to skip it. +- `onentry` A function that gets called with `(entry)` for each entry + that passes the filter. +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") + +#### abort(error) + +Stop all parsing activities. This is called when there are zlib +errors. It also emits an unrecoverable warning with the error provided. + +### class tar.ReadEntry extends [MiniPass](http://npm.im/minipass) + +A representation of an entry that is being read out of a tar archive. + +It has the following fields: + +- `extended` The extended metadata object provided to the constructor. +- `globalExtended` The global extended metadata object provided to the + constructor. +- `remain` The number of bytes remaining to be written into the + stream. +- `blockRemain` The number of 512-byte blocks remaining to be written + into the stream. +- `ignore` Whether this entry should be ignored. +- `meta` True if this represents metadata about the next entry, false + if it represents a filesystem object. +- All the fields from the header, extended header, and global extended + header are added to the ReadEntry object. So it has `path`, `type`, + `size`, `mode`, and so on. + +#### constructor(header, extended, globalExtended) + +Create a new ReadEntry object with the specified header, extended +header, and global extended header values. + +### class tar.WriteEntry extends [MiniPass](http://npm.im/minipass) + +A representation of an entry that is being written from the file +system into a tar archive. + +Emits data for the Header, and for the Pax Extended Header if one is +required, as well as any body data. + +Creating a WriteEntry for a directory does not also create +WriteEntry objects for all of the directory contents. + +It has the following fields: + +- `path` The path field that will be written to the archive. By + default, this is also the path from the cwd to the file system + object. +- `portable` Omit metadata that is system-specific: `ctime`, `atime`, + `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note + that `mtime` is still included, because this is necessary for other + time-based operations. Additionally, `mode` is set to a "reasonable + default" for most unix systems, based on a `umask` value of `0o22`. +- `myuid` If supported, the uid of the user running the current + process. +- `myuser` The `env.USER` string if set, or `''`. Set as the entry + `uname` field if the file's `uid` matches `this.myuid`. +- `maxReadSize` The maximum buffer size for `fs.read()` operations. + Defaults to 1 MB. +- `linkCache` A Map object containing the device and inode value for + any file whose nlink is > 1, to identify hard links. +- `statCache` A Map object that caches calls `lstat`. +- `preservePaths` Allow absolute paths. By default, `/` is stripped + from absolute paths. +- `cwd` The current working directory for creating the archive. + Defaults to `process.cwd()`. +- `absolute` The absolute path to the entry on the filesystem. By + default, this is `path.resolve(this.cwd, this.path)`, but it can be + overridden explicitly. +- `strict` Treat warnings as crash-worthy errors. Default false. +- `win32` True if on a windows platform. Causes behavior where paths + replace `\` with `/` and filenames containing the windows-compatible + forms of `<|>?:` characters are converted to actual `<|>?:` characters + in the archive. +- `noPax` Suppress pax extended headers. Note that this means that + long paths and linkpaths will be truncated, and large or negative + numeric values may be interpreted incorrectly. +- `noMtime` Set to true to omit writing `mtime` values for entries. + Note that this prevents using other mtime-based features like + `tar.update` or the `keepNewer` option with the resulting tar archive. + + +#### constructor(path, options) + +`path` is the path of the entry as it is written in the archive. + +The following options are supported: + +- `portable` Omit metadata that is system-specific: `ctime`, `atime`, + `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note + that `mtime` is still included, because this is necessary for other + time-based operations. Additionally, `mode` is set to a "reasonable + default" for most unix systems, based on a `umask` value of `0o22`. +- `maxReadSize` The maximum buffer size for `fs.read()` operations. + Defaults to 1 MB. +- `linkCache` A Map object containing the device and inode value for + any file whose nlink is > 1, to identify hard links. +- `statCache` A Map object that caches calls `lstat`. +- `preservePaths` Allow absolute paths. By default, `/` is stripped + from absolute paths. +- `cwd` The current working directory for creating the archive. + Defaults to `process.cwd()`. +- `absolute` The absolute path to the entry on the filesystem. By + default, this is `path.resolve(this.cwd, this.path)`, but it can be + overridden explicitly. +- `strict` Treat warnings as crash-worthy errors. Default false. +- `win32` True if on a windows platform. Causes behavior where paths + replace `\` with `/`. +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") +- `noMtime` Set to true to omit writing `mtime` values for entries. + Note that this prevents using other mtime-based features like + `tar.update` or the `keepNewer` option with the resulting tar archive. +- `umask` Set to restrict the modes on the entries in the archive, + somewhat like how umask works on file creation. Defaults to + `process.umask()` on unix systems, or `0o22` on Windows. + +#### warn(message, data) + +If strict, emit an error with the provided message. + +Othewise, emit a `'warn'` event with the provided message and data. + +### class tar.WriteEntry.Sync + +Synchronous version of tar.WriteEntry + +### class tar.WriteEntry.Tar + +A version of tar.WriteEntry that gets its data from a tar.ReadEntry +instead of from the filesystem. + +#### constructor(readEntry, options) + +`readEntry` is the entry being read out of another archive. + +The following options are supported: + +- `portable` Omit metadata that is system-specific: `ctime`, `atime`, + `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note + that `mtime` is still included, because this is necessary for other + time-based operations. Additionally, `mode` is set to a "reasonable + default" for most unix systems, based on a `umask` value of `0o22`. +- `preservePaths` Allow absolute paths. By default, `/` is stripped + from absolute paths. +- `strict` Treat warnings as crash-worthy errors. Default false. +- `onwarn` A function that will get called with `(code, message, data)` for + any warnings encountered. (See "Warnings and Errors") +- `noMtime` Set to true to omit writing `mtime` values for entries. + Note that this prevents using other mtime-based features like + `tar.update` or the `keepNewer` option with the resulting tar archive. + +### class tar.Header + +A class for reading and writing header blocks. + +It has the following fields: + +- `nullBlock` True if decoding a block which is entirely composed of + `0x00` null bytes. (Useful because tar files are terminated by + at least 2 null blocks.) +- `cksumValid` True if the checksum in the header is valid, false + otherwise. +- `needPax` True if the values, as encoded, will require a Pax + extended header. +- `path` The path of the entry. +- `mode` The 4 lowest-order octal digits of the file mode. That is, + read/write/execute permissions for world, group, and owner, and the + setuid, setgid, and sticky bits. +- `uid` Numeric user id of the file owner +- `gid` Numeric group id of the file owner +- `size` Size of the file in bytes +- `mtime` Modified time of the file +- `cksum` The checksum of the header. This is generated by adding all + the bytes of the header block, treating the checksum field itself as + all ascii space characters (that is, `0x20`). +- `type` The human-readable name of the type of entry this represents, + or the alphanumeric key if unknown. +- `typeKey` The alphanumeric key for the type of entry this header + represents. +- `linkpath` The target of Link and SymbolicLink entries. +- `uname` Human-readable user name of the file owner +- `gname` Human-readable group name of the file owner +- `devmaj` The major portion of the device number. Always `0` for + files, directories, and links. +- `devmin` The minor portion of the device number. Always `0` for + files, directories, and links. +- `atime` File access time. +- `ctime` File change time. + +#### constructor(data, [offset=0]) + +`data` is optional. It is either a Buffer that should be interpreted +as a tar Header starting at the specified offset and continuing for +512 bytes, or a data object of keys and values to set on the header +object, and eventually encode as a tar Header. + +#### decode(block, offset) + +Decode the provided buffer starting at the specified offset. + +Buffer length must be greater than 512 bytes. + +#### set(data) + +Set the fields in the data object. + +#### encode(buffer, offset) + +Encode the header fields into the buffer at the specified offset. + +Returns `this.needPax` to indicate whether a Pax Extended Header is +required to properly encode the specified data. + +### class tar.Pax + +An object representing a set of key-value pairs in an Pax extended +header entry. + +It has the following fields. Where the same name is used, they have +the same semantics as the tar.Header field of the same name. + +- `global` True if this represents a global extended header, or false + if it is for a single entry. +- `atime` +- `charset` +- `comment` +- `ctime` +- `gid` +- `gname` +- `linkpath` +- `mtime` +- `path` +- `size` +- `uid` +- `uname` +- `dev` +- `ino` +- `nlink` + +#### constructor(object, global) + +Set the fields set in the object. `global` is a boolean that defaults +to false. + +#### encode() + +Return a Buffer containing the header and body for the Pax extended +header entry, or `null` if there is nothing to encode. + +#### encodeBody() + +Return a string representing the body of the pax extended header +entry. + +#### encodeField(fieldName) + +Return a string representing the key/value encoding for the specified +fieldName, or `''` if the field is unset. + +### tar.Pax.parse(string, extended, global) + +Return a new Pax object created by parsing the contents of the string +provided. + +If the `extended` object is set, then also add the fields from that +object. (This is necessary because multiple metadata entries can +occur in sequence.) + +### tar.types + +A translation table for the `type` field in tar headers. + +#### tar.types.name.get(code) + +Get the human-readable name for a given alphanumeric code. + +#### tar.types.code.get(name) + +Get the alphanumeric code for a given human-readable name. diff --git a/node_modules/tar/index.js b/node_modules/tar/index.js new file mode 100644 index 0000000..c9ae06e --- /dev/null +++ b/node_modules/tar/index.js @@ -0,0 +1,18 @@ +'use strict' + +// high-level commands +exports.c = exports.create = require('./lib/create.js') +exports.r = exports.replace = require('./lib/replace.js') +exports.t = exports.list = require('./lib/list.js') +exports.u = exports.update = require('./lib/update.js') +exports.x = exports.extract = require('./lib/extract.js') + +// classes +exports.Pack = require('./lib/pack.js') +exports.Unpack = require('./lib/unpack.js') +exports.Parse = require('./lib/parse.js') +exports.ReadEntry = require('./lib/read-entry.js') +exports.WriteEntry = require('./lib/write-entry.js') +exports.Header = require('./lib/header.js') +exports.Pax = require('./lib/pax.js') +exports.types = require('./lib/types.js') diff --git a/node_modules/tar/lib/create.js b/node_modules/tar/lib/create.js new file mode 100644 index 0000000..d033640 --- /dev/null +++ b/node_modules/tar/lib/create.js @@ -0,0 +1,104 @@ +'use strict' + +// tar -c +const hlo = require('./high-level-opt.js') + +const Pack = require('./pack.js') +const fsm = require('fs-minipass') +const t = require('./list.js') +const path = require('path') + +module.exports = (opt_, files, cb) => { + if (typeof files === 'function') + cb = files + + if (Array.isArray(opt_)) + files = opt_, opt_ = {} + + if (!files || !Array.isArray(files) || !files.length) + throw new TypeError('no files or directories specified') + + files = Array.from(files) + + const opt = hlo(opt_) + + if (opt.sync && typeof cb === 'function') + throw new TypeError('callback not supported for sync tar functions') + + if (!opt.file && typeof cb === 'function') + throw new TypeError('callback only supported with file option') + + return opt.file && opt.sync ? createFileSync(opt, files) + : opt.file ? createFile(opt, files, cb) + : opt.sync ? createSync(opt, files) + : create(opt, files) +} + +const createFileSync = (opt, files) => { + const p = new Pack.Sync(opt) + const stream = new fsm.WriteStreamSync(opt.file, { + mode: opt.mode || 0o666, + }) + p.pipe(stream) + addFilesSync(p, files) +} + +const createFile = (opt, files, cb) => { + const p = new Pack(opt) + const stream = new fsm.WriteStream(opt.file, { + mode: opt.mode || 0o666, + }) + p.pipe(stream) + + const promise = new Promise((res, rej) => { + stream.on('error', rej) + stream.on('close', res) + p.on('error', rej) + }) + + addFilesAsync(p, files) + + return cb ? promise.then(cb, cb) : promise +} + +const addFilesSync = (p, files) => { + files.forEach(file => { + if (file.charAt(0) === '@') { + t({ + file: path.resolve(p.cwd, file.substr(1)), + sync: true, + noResume: true, + onentry: entry => p.add(entry), + }) + } else + p.add(file) + }) + p.end() +} + +const addFilesAsync = (p, files) => { + while (files.length) { + const file = files.shift() + if (file.charAt(0) === '@') { + return t({ + file: path.resolve(p.cwd, file.substr(1)), + noResume: true, + onentry: entry => p.add(entry), + }).then(_ => addFilesAsync(p, files)) + } else + p.add(file) + } + p.end() +} + +const createSync = (opt, files) => { + const p = new Pack.Sync(opt) + addFilesSync(p, files) + return p +} + +const create = (opt, files) => { + const p = new Pack(opt) + addFilesAsync(p, files) + return p +} diff --git a/node_modules/tar/lib/extract.js b/node_modules/tar/lib/extract.js new file mode 100644 index 0000000..98e946e --- /dev/null +++ b/node_modules/tar/lib/extract.js @@ -0,0 +1,107 @@ +'use strict' + +// tar -x +const hlo = require('./high-level-opt.js') +const Unpack = require('./unpack.js') +const fs = require('fs') +const fsm = require('fs-minipass') +const path = require('path') +const stripSlash = require('./strip-trailing-slashes.js') + +module.exports = (opt_, files, cb) => { + if (typeof opt_ === 'function') + cb = opt_, files = null, opt_ = {} + else if (Array.isArray(opt_)) + files = opt_, opt_ = {} + + if (typeof files === 'function') + cb = files, files = null + + if (!files) + files = [] + else + files = Array.from(files) + + const opt = hlo(opt_) + + if (opt.sync && typeof cb === 'function') + throw new TypeError('callback not supported for sync tar functions') + + if (!opt.file && typeof cb === 'function') + throw new TypeError('callback only supported with file option') + + if (files.length) + filesFilter(opt, files) + + return opt.file && opt.sync ? extractFileSync(opt) + : opt.file ? extractFile(opt, cb) + : opt.sync ? extractSync(opt) + : extract(opt) +} + +// construct a filter that limits the file entries listed +// include child entries if a dir is included +const filesFilter = (opt, files) => { + const map = new Map(files.map(f => [stripSlash(f), true])) + const filter = opt.filter + + const mapHas = (file, r) => { + const root = r || path.parse(file).root || '.' + const ret = file === root ? false + : map.has(file) ? map.get(file) + : mapHas(path.dirname(file), root) + + map.set(file, ret) + return ret + } + + opt.filter = filter + ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) + : file => mapHas(stripSlash(file)) +} + +const extractFileSync = opt => { + const u = new Unpack.Sync(opt) + + const file = opt.file + const stat = fs.statSync(file) + // This trades a zero-byte read() syscall for a stat + // However, it will usually result in less memory allocation + const readSize = opt.maxReadSize || 16 * 1024 * 1024 + const stream = new fsm.ReadStreamSync(file, { + readSize: readSize, + size: stat.size, + }) + stream.pipe(u) +} + +const extractFile = (opt, cb) => { + const u = new Unpack(opt) + const readSize = opt.maxReadSize || 16 * 1024 * 1024 + + const file = opt.file + const p = new Promise((resolve, reject) => { + u.on('error', reject) + u.on('close', resolve) + + // This trades a zero-byte read() syscall for a stat + // However, it will usually result in less memory allocation + fs.stat(file, (er, stat) => { + if (er) + reject(er) + else { + const stream = new fsm.ReadStream(file, { + readSize: readSize, + size: stat.size, + }) + stream.on('error', reject) + stream.pipe(u) + } + }) + }) + return cb ? p.then(cb, cb) : p +} + +const extractSync = opt => new Unpack.Sync(opt) + +const extract = opt => new Unpack(opt) diff --git a/node_modules/tar/lib/get-write-flag.js b/node_modules/tar/lib/get-write-flag.js new file mode 100644 index 0000000..e869599 --- /dev/null +++ b/node_modules/tar/lib/get-write-flag.js @@ -0,0 +1,20 @@ +// Get the appropriate flag to use for creating files +// We use fmap on Windows platforms for files less than +// 512kb. This is a fairly low limit, but avoids making +// things slower in some cases. Since most of what this +// library is used for is extracting tarballs of many +// relatively small files in npm packages and the like, +// it can be a big boost on Windows platforms. +// Only supported in Node v12.9.0 and above. +const platform = process.env.__FAKE_PLATFORM__ || process.platform +const isWindows = platform === 'win32' +const fs = global.__FAKE_TESTING_FS__ || require('fs') + +/* istanbul ignore next */ +const { O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP = 0 } = fs.constants + +const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP +const fMapLimit = 512 * 1024 +const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY +module.exports = !fMapEnabled ? () => 'w' + : size => size < fMapLimit ? fMapFlag : 'w' diff --git a/node_modules/tar/lib/header.js b/node_modules/tar/lib/header.js new file mode 100644 index 0000000..1295040 --- /dev/null +++ b/node_modules/tar/lib/header.js @@ -0,0 +1,288 @@ +'use strict' +// parse a 512-byte header block to a data object, or vice-versa +// encode returns `true` if a pax extended header is needed, because +// the data could not be faithfully encoded in a simple header. +// (Also, check header.needPax to see if it needs a pax header.) + +const types = require('./types.js') +const pathModule = require('path').posix +const large = require('./large-numbers.js') + +const SLURP = Symbol('slurp') +const TYPE = Symbol('type') + +class Header { + constructor (data, off, ex, gex) { + this.cksumValid = false + this.needPax = false + this.nullBlock = false + + this.block = null + this.path = null + this.mode = null + this.uid = null + this.gid = null + this.size = null + this.mtime = null + this.cksum = null + this[TYPE] = '0' + this.linkpath = null + this.uname = null + this.gname = null + this.devmaj = 0 + this.devmin = 0 + this.atime = null + this.ctime = null + + if (Buffer.isBuffer(data)) + this.decode(data, off || 0, ex, gex) + else if (data) + this.set(data) + } + + decode (buf, off, ex, gex) { + if (!off) + off = 0 + + if (!buf || !(buf.length >= off + 512)) + throw new Error('need 512 bytes for header') + + this.path = decString(buf, off, 100) + this.mode = decNumber(buf, off + 100, 8) + this.uid = decNumber(buf, off + 108, 8) + this.gid = decNumber(buf, off + 116, 8) + this.size = decNumber(buf, off + 124, 12) + this.mtime = decDate(buf, off + 136, 12) + this.cksum = decNumber(buf, off + 148, 12) + + // if we have extended or global extended headers, apply them now + // See https://github.com/npm/node-tar/pull/187 + this[SLURP](ex) + this[SLURP](gex, true) + + // old tar versions marked dirs as a file with a trailing / + this[TYPE] = decString(buf, off + 156, 1) + if (this[TYPE] === '') + this[TYPE] = '0' + if (this[TYPE] === '0' && this.path.substr(-1) === '/') + this[TYPE] = '5' + + // tar implementations sometimes incorrectly put the stat(dir).size + // as the size in the tarball, even though Directory entries are + // not able to have any body at all. In the very rare chance that + // it actually DOES have a body, we weren't going to do anything with + // it anyway, and it'll just be a warning about an invalid header. + if (this[TYPE] === '5') + this.size = 0 + + this.linkpath = decString(buf, off + 157, 100) + if (buf.slice(off + 257, off + 265).toString() === 'ustar\u000000') { + this.uname = decString(buf, off + 265, 32) + this.gname = decString(buf, off + 297, 32) + this.devmaj = decNumber(buf, off + 329, 8) + this.devmin = decNumber(buf, off + 337, 8) + if (buf[off + 475] !== 0) { + // definitely a prefix, definitely >130 chars. + const prefix = decString(buf, off + 345, 155) + this.path = prefix + '/' + this.path + } else { + const prefix = decString(buf, off + 345, 130) + if (prefix) + this.path = prefix + '/' + this.path + this.atime = decDate(buf, off + 476, 12) + this.ctime = decDate(buf, off + 488, 12) + } + } + + let sum = 8 * 0x20 + for (let i = off; i < off + 148; i++) + sum += buf[i] + + for (let i = off + 156; i < off + 512; i++) + sum += buf[i] + + this.cksumValid = sum === this.cksum + if (this.cksum === null && sum === 8 * 0x20) + this.nullBlock = true + } + + [SLURP] (ex, global) { + for (const k in ex) { + // we slurp in everything except for the path attribute in + // a global extended header, because that's weird. + if (ex[k] !== null && ex[k] !== undefined && + !(global && k === 'path')) + this[k] = ex[k] + } + } + + encode (buf, off) { + if (!buf) { + buf = this.block = Buffer.alloc(512) + off = 0 + } + + if (!off) + off = 0 + + if (!(buf.length >= off + 512)) + throw new Error('need 512 bytes for header') + + const prefixSize = this.ctime || this.atime ? 130 : 155 + const split = splitPrefix(this.path || '', prefixSize) + const path = split[0] + const prefix = split[1] + this.needPax = split[2] + + this.needPax = encString(buf, off, 100, path) || this.needPax + this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax + this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax + this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax + this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax + this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax + buf[off + 156] = this[TYPE].charCodeAt(0) + this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax + buf.write('ustar\u000000', off + 257, 8) + this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax + this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax + this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax + this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax + this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax + if (buf[off + 475] !== 0) + this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax + else { + this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax + this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax + this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax + } + + let sum = 8 * 0x20 + for (let i = off; i < off + 148; i++) + sum += buf[i] + + for (let i = off + 156; i < off + 512; i++) + sum += buf[i] + + this.cksum = sum + encNumber(buf, off + 148, 8, this.cksum) + this.cksumValid = true + + return this.needPax + } + + set (data) { + for (const i in data) { + if (data[i] !== null && data[i] !== undefined) + this[i] = data[i] + } + } + + get type () { + return types.name.get(this[TYPE]) || this[TYPE] + } + + get typeKey () { + return this[TYPE] + } + + set type (type) { + if (types.code.has(type)) + this[TYPE] = types.code.get(type) + else + this[TYPE] = type + } +} + +const splitPrefix = (p, prefixSize) => { + const pathSize = 100 + let pp = p + let prefix = '' + let ret + const root = pathModule.parse(p).root || '.' + + if (Buffer.byteLength(pp) < pathSize) + ret = [pp, prefix, false] + else { + // first set prefix to the dir, and path to the base + prefix = pathModule.dirname(pp) + pp = pathModule.basename(pp) + + do { + // both fit! + if (Buffer.byteLength(pp) <= pathSize && + Buffer.byteLength(prefix) <= prefixSize) + ret = [pp, prefix, false] + + // prefix fits in prefix, but path doesn't fit in path + else if (Buffer.byteLength(pp) > pathSize && + Buffer.byteLength(prefix) <= prefixSize) + ret = [pp.substr(0, pathSize - 1), prefix, true] + + else { + // make path take a bit from prefix + pp = pathModule.join(pathModule.basename(prefix), pp) + prefix = pathModule.dirname(prefix) + } + } while (prefix !== root && !ret) + + // at this point, found no resolution, just truncate + if (!ret) + ret = [p.substr(0, pathSize - 1), '', true] + } + return ret +} + +const decString = (buf, off, size) => + buf.slice(off, off + size).toString('utf8').replace(/\0.*/, '') + +const decDate = (buf, off, size) => + numToDate(decNumber(buf, off, size)) + +const numToDate = num => num === null ? null : new Date(num * 1000) + +const decNumber = (buf, off, size) => + buf[off] & 0x80 ? large.parse(buf.slice(off, off + size)) + : decSmallNumber(buf, off, size) + +const nanNull = value => isNaN(value) ? null : value + +const decSmallNumber = (buf, off, size) => + nanNull(parseInt( + buf.slice(off, off + size) + .toString('utf8').replace(/\0.*$/, '').trim(), 8)) + +// the maximum encodable as a null-terminated octal, by field size +const MAXNUM = { + 12: 0o77777777777, + 8: 0o7777777, +} + +const encNumber = (buf, off, size, number) => + number === null ? false : + number > MAXNUM[size] || number < 0 + ? (large.encode(number, buf.slice(off, off + size)), true) + : (encSmallNumber(buf, off, size, number), false) + +const encSmallNumber = (buf, off, size, number) => + buf.write(octalString(number, size), off, size, 'ascii') + +const octalString = (number, size) => + padOctal(Math.floor(number).toString(8), size) + +const padOctal = (string, size) => + (string.length === size - 1 ? string + : new Array(size - string.length - 1).join('0') + string + ' ') + '\0' + +const encDate = (buf, off, size, date) => + date === null ? false : + encNumber(buf, off, size, date.getTime() / 1000) + +// enough to fill the longest string we've got +const NULLS = new Array(156).join('\0') +// pad with nulls, return true if it's longer or non-ascii +const encString = (buf, off, size, string) => + string === null ? false : + (buf.write(string + NULLS, off, size, 'utf8'), + string.length !== Buffer.byteLength(string) || string.length > size) + +module.exports = Header diff --git a/node_modules/tar/lib/high-level-opt.js b/node_modules/tar/lib/high-level-opt.js new file mode 100644 index 0000000..40e4418 --- /dev/null +++ b/node_modules/tar/lib/high-level-opt.js @@ -0,0 +1,29 @@ +'use strict' + +// turn tar(1) style args like `C` into the more verbose things like `cwd` + +const argmap = new Map([ + ['C', 'cwd'], + ['f', 'file'], + ['z', 'gzip'], + ['P', 'preservePaths'], + ['U', 'unlink'], + ['strip-components', 'strip'], + ['stripComponents', 'strip'], + ['keep-newer', 'newer'], + ['keepNewer', 'newer'], + ['keep-newer-files', 'newer'], + ['keepNewerFiles', 'newer'], + ['k', 'keep'], + ['keep-existing', 'keep'], + ['keepExisting', 'keep'], + ['m', 'noMtime'], + ['no-mtime', 'noMtime'], + ['p', 'preserveOwner'], + ['L', 'follow'], + ['h', 'follow'], +]) + +module.exports = opt => opt ? Object.keys(opt).map(k => [ + argmap.has(k) ? argmap.get(k) : k, opt[k], +]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {} diff --git a/node_modules/tar/lib/large-numbers.js b/node_modules/tar/lib/large-numbers.js new file mode 100644 index 0000000..dd6f690 --- /dev/null +++ b/node_modules/tar/lib/large-numbers.js @@ -0,0 +1,99 @@ +'use strict' +// Tar can encode large and negative numbers using a leading byte of +// 0xff for negative, and 0x80 for positive. + +const encode = (num, buf) => { + if (!Number.isSafeInteger(num)) + // The number is so large that javascript cannot represent it with integer + // precision. + throw Error('cannot encode number outside of javascript safe integer range') + else if (num < 0) + encodeNegative(num, buf) + else + encodePositive(num, buf) + return buf +} + +const encodePositive = (num, buf) => { + buf[0] = 0x80 + + for (var i = buf.length; i > 1; i--) { + buf[i - 1] = num & 0xff + num = Math.floor(num / 0x100) + } +} + +const encodeNegative = (num, buf) => { + buf[0] = 0xff + var flipped = false + num = num * -1 + for (var i = buf.length; i > 1; i--) { + var byte = num & 0xff + num = Math.floor(num / 0x100) + if (flipped) + buf[i - 1] = onesComp(byte) + else if (byte === 0) + buf[i - 1] = 0 + else { + flipped = true + buf[i - 1] = twosComp(byte) + } + } +} + +const parse = (buf) => { + const pre = buf[0] + const value = pre === 0x80 ? pos(buf.slice(1, buf.length)) + : pre === 0xff ? twos(buf) + : null + if (value === null) + throw Error('invalid base256 encoding') + + if (!Number.isSafeInteger(value)) + // The number is so large that javascript cannot represent it with integer + // precision. + throw Error('parsed number outside of javascript safe integer range') + + return value +} + +const twos = (buf) => { + var len = buf.length + var sum = 0 + var flipped = false + for (var i = len - 1; i > -1; i--) { + var byte = buf[i] + var f + if (flipped) + f = onesComp(byte) + else if (byte === 0) + f = byte + else { + flipped = true + f = twosComp(byte) + } + if (f !== 0) + sum -= f * Math.pow(256, len - i - 1) + } + return sum +} + +const pos = (buf) => { + var len = buf.length + var sum = 0 + for (var i = len - 1; i > -1; i--) { + var byte = buf[i] + if (byte !== 0) + sum += byte * Math.pow(256, len - i - 1) + } + return sum +} + +const onesComp = byte => (0xff ^ byte) & 0xff + +const twosComp = byte => ((0xff ^ byte) + 1) & 0xff + +module.exports = { + encode, + parse, +} diff --git a/node_modules/tar/lib/list.js b/node_modules/tar/lib/list.js new file mode 100644 index 0000000..a0c1cf2 --- /dev/null +++ b/node_modules/tar/lib/list.js @@ -0,0 +1,132 @@ +'use strict' + +// XXX: This shares a lot in common with extract.js +// maybe some DRY opportunity here? + +// tar -t +const hlo = require('./high-level-opt.js') +const Parser = require('./parse.js') +const fs = require('fs') +const fsm = require('fs-minipass') +const path = require('path') +const stripSlash = require('./strip-trailing-slashes.js') + +module.exports = (opt_, files, cb) => { + if (typeof opt_ === 'function') + cb = opt_, files = null, opt_ = {} + else if (Array.isArray(opt_)) + files = opt_, opt_ = {} + + if (typeof files === 'function') + cb = files, files = null + + if (!files) + files = [] + else + files = Array.from(files) + + const opt = hlo(opt_) + + if (opt.sync && typeof cb === 'function') + throw new TypeError('callback not supported for sync tar functions') + + if (!opt.file && typeof cb === 'function') + throw new TypeError('callback only supported with file option') + + if (files.length) + filesFilter(opt, files) + + if (!opt.noResume) + onentryFunction(opt) + + return opt.file && opt.sync ? listFileSync(opt) + : opt.file ? listFile(opt, cb) + : list(opt) +} + +const onentryFunction = opt => { + const onentry = opt.onentry + opt.onentry = onentry ? e => { + onentry(e) + e.resume() + } : e => e.resume() +} + +// construct a filter that limits the file entries listed +// include child entries if a dir is included +const filesFilter = (opt, files) => { + const map = new Map(files.map(f => [stripSlash(f), true])) + const filter = opt.filter + + const mapHas = (file, r) => { + const root = r || path.parse(file).root || '.' + const ret = file === root ? false + : map.has(file) ? map.get(file) + : mapHas(path.dirname(file), root) + + map.set(file, ret) + return ret + } + + opt.filter = filter + ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) + : file => mapHas(stripSlash(file)) +} + +const listFileSync = opt => { + const p = list(opt) + const file = opt.file + let threw = true + let fd + try { + const stat = fs.statSync(file) + const readSize = opt.maxReadSize || 16 * 1024 * 1024 + if (stat.size < readSize) + p.end(fs.readFileSync(file)) + else { + let pos = 0 + const buf = Buffer.allocUnsafe(readSize) + fd = fs.openSync(file, 'r') + while (pos < stat.size) { + const bytesRead = fs.readSync(fd, buf, 0, readSize, pos) + pos += bytesRead + p.write(buf.slice(0, bytesRead)) + } + p.end() + } + threw = false + } finally { + if (threw && fd) { + try { + fs.closeSync(fd) + } catch (er) {} + } + } +} + +const listFile = (opt, cb) => { + const parse = new Parser(opt) + const readSize = opt.maxReadSize || 16 * 1024 * 1024 + + const file = opt.file + const p = new Promise((resolve, reject) => { + parse.on('error', reject) + parse.on('end', resolve) + + fs.stat(file, (er, stat) => { + if (er) + reject(er) + else { + const stream = new fsm.ReadStream(file, { + readSize: readSize, + size: stat.size, + }) + stream.on('error', reject) + stream.pipe(parse) + } + }) + }) + return cb ? p.then(cb, cb) : p +} + +const list = opt => new Parser(opt) diff --git a/node_modules/tar/lib/mkdir.js b/node_modules/tar/lib/mkdir.js new file mode 100644 index 0000000..a0719e6 --- /dev/null +++ b/node_modules/tar/lib/mkdir.js @@ -0,0 +1,213 @@ +'use strict' +// wrapper around mkdirp for tar's needs. + +// TODO: This should probably be a class, not functionally +// passing around state in a gazillion args. + +const mkdirp = require('mkdirp') +const fs = require('fs') +const path = require('path') +const chownr = require('chownr') +const normPath = require('./normalize-windows-path.js') + +class SymlinkError extends Error { + constructor (symlink, path) { + super('Cannot extract through symbolic link') + this.path = path + this.symlink = symlink + } + + get name () { + return 'SylinkError' + } +} + +class CwdError extends Error { + constructor (path, code) { + super(code + ': Cannot cd into \'' + path + '\'') + this.path = path + this.code = code + } + + get name () { + return 'CwdError' + } +} + +const cGet = (cache, key) => cache.get(normPath(key)) +const cSet = (cache, key, val) => cache.set(normPath(key), val) + +const checkCwd = (dir, cb) => { + fs.stat(dir, (er, st) => { + if (er || !st.isDirectory()) + er = new CwdError(dir, er && er.code || 'ENOTDIR') + cb(er) + }) +} + +module.exports = (dir, opt, cb) => { + dir = normPath(dir) + + // if there's any overlap between mask and mode, + // then we'll need an explicit chmod + const umask = opt.umask + const mode = opt.mode | 0o0700 + const needChmod = (mode & umask) !== 0 + + const uid = opt.uid + const gid = opt.gid + const doChown = typeof uid === 'number' && + typeof gid === 'number' && + (uid !== opt.processUid || gid !== opt.processGid) + + const preserve = opt.preserve + const unlink = opt.unlink + const cache = opt.cache + const cwd = normPath(opt.cwd) + + const done = (er, created) => { + if (er) + cb(er) + else { + cSet(cache, dir, true) + if (created && doChown) + chownr(created, uid, gid, er => done(er)) + else if (needChmod) + fs.chmod(dir, mode, cb) + else + cb() + } + } + + if (cache && cGet(cache, dir) === true) + return done() + + if (dir === cwd) + return checkCwd(dir, done) + + if (preserve) + return mkdirp(dir, {mode}).then(made => done(null, made), done) + + const sub = normPath(path.relative(cwd, dir)) + const parts = sub.split('/') + mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done) +} + +const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { + if (!parts.length) + return cb(null, created) + const p = parts.shift() + const part = normPath(path.resolve(base + '/' + p)) + if (cGet(cache, part)) + return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) +} + +const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => er => { + if (er) { + fs.lstat(part, (statEr, st) => { + if (statEr) { + statEr.path = statEr.path && normPath(statEr.path) + cb(statEr) + } else if (st.isDirectory()) + mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + else if (unlink) { + fs.unlink(part, er => { + if (er) + return cb(er) + fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) + }) + } else if (st.isSymbolicLink()) + return cb(new SymlinkError(part, part + '/' + parts.join('/'))) + else + cb(er) + }) + } else { + created = created || part + mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + } +} + +const checkCwdSync = dir => { + let ok = false + let code = 'ENOTDIR' + try { + ok = fs.statSync(dir).isDirectory() + } catch (er) { + code = er.code + } finally { + if (!ok) + throw new CwdError(dir, code) + } +} + +module.exports.sync = (dir, opt) => { + dir = normPath(dir) + // if there's any overlap between mask and mode, + // then we'll need an explicit chmod + const umask = opt.umask + const mode = opt.mode | 0o0700 + const needChmod = (mode & umask) !== 0 + + const uid = opt.uid + const gid = opt.gid + const doChown = typeof uid === 'number' && + typeof gid === 'number' && + (uid !== opt.processUid || gid !== opt.processGid) + + const preserve = opt.preserve + const unlink = opt.unlink + const cache = opt.cache + const cwd = normPath(opt.cwd) + + const done = (created) => { + cSet(cache, dir, true) + if (created && doChown) + chownr.sync(created, uid, gid) + if (needChmod) + fs.chmodSync(dir, mode) + } + + if (cache && cGet(cache, dir) === true) + return done() + + if (dir === cwd) { + checkCwdSync(cwd) + return done() + } + + if (preserve) + return done(mkdirp.sync(dir, mode)) + + const sub = normPath(path.relative(cwd, dir)) + const parts = sub.split('/') + let created = null + for (let p = parts.shift(), part = cwd; + p && (part += '/' + p); + p = parts.shift()) { + part = normPath(path.resolve(part)) + if (cGet(cache, part)) + continue + + try { + fs.mkdirSync(part, mode) + created = created || part + cSet(cache, part, true) + } catch (er) { + const st = fs.lstatSync(part) + if (st.isDirectory()) { + cSet(cache, part, true) + continue + } else if (unlink) { + fs.unlinkSync(part) + fs.mkdirSync(part, mode) + created = created || part + cSet(cache, part, true) + continue + } else if (st.isSymbolicLink()) + return new SymlinkError(part, part + '/' + parts.join('/')) + } + } + + return done(created) +} diff --git a/node_modules/tar/lib/mode-fix.js b/node_modules/tar/lib/mode-fix.js new file mode 100644 index 0000000..6a045ff --- /dev/null +++ b/node_modules/tar/lib/mode-fix.js @@ -0,0 +1,23 @@ +'use strict' +module.exports = (mode, isDir, portable) => { + mode &= 0o7777 + + // in portable mode, use the minimum reasonable umask + // if this system creates files with 0o664 by default + // (as some linux distros do), then we'll write the + // archive with 0o644 instead. Also, don't ever create + // a file that is not readable/writable by the owner. + if (portable) + mode = (mode | 0o600) & ~0o22 + + // if dirs are readable, then they should be listable + if (isDir) { + if (mode & 0o400) + mode |= 0o100 + if (mode & 0o40) + mode |= 0o10 + if (mode & 0o4) + mode |= 0o1 + } + return mode +} diff --git a/node_modules/tar/lib/normalize-unicode.js b/node_modules/tar/lib/normalize-unicode.js new file mode 100644 index 0000000..4aeb1d5 --- /dev/null +++ b/node_modules/tar/lib/normalize-unicode.js @@ -0,0 +1,11 @@ +// warning: extremely hot code path. +// This has been meticulously optimized for use +// within npm install on large package trees. +// Do not edit without careful benchmarking. +const normalizeCache = Object.create(null) +const {hasOwnProperty} = Object.prototype +module.exports = s => { + if (!hasOwnProperty.call(normalizeCache, s)) + normalizeCache[s] = s.normalize('NFKD') + return normalizeCache[s] +} diff --git a/node_modules/tar/lib/normalize-windows-path.js b/node_modules/tar/lib/normalize-windows-path.js new file mode 100644 index 0000000..eb13ba0 --- /dev/null +++ b/node_modules/tar/lib/normalize-windows-path.js @@ -0,0 +1,8 @@ +// on windows, either \ or / are valid directory separators. +// on unix, \ is a valid character in filenames. +// so, on windows, and only on windows, we replace all \ chars with /, +// so that we can use / as our one and only directory separator char. + +const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform +module.exports = platform !== 'win32' ? p => p + : p => p && p.replace(/\\/g, '/') diff --git a/node_modules/tar/lib/pack.js b/node_modules/tar/lib/pack.js new file mode 100644 index 0000000..9522c10 --- /dev/null +++ b/node_modules/tar/lib/pack.js @@ -0,0 +1,397 @@ +'use strict' + +// A readable tar stream creator +// Technically, this is a transform stream that you write paths into, +// and tar format comes out of. +// The `add()` method is like `write()` but returns this, +// and end() return `this` as well, so you can +// do `new Pack(opt).add('files').add('dir').end().pipe(output) +// You could also do something like: +// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar')) + +class PackJob { + constructor (path, absolute) { + this.path = path || './' + this.absolute = absolute + this.entry = null + this.stat = null + this.readdir = null + this.pending = false + this.ignore = false + this.piped = false + } +} + +const MiniPass = require('minipass') +const zlib = require('minizlib') +const ReadEntry = require('./read-entry.js') +const WriteEntry = require('./write-entry.js') +const WriteEntrySync = WriteEntry.Sync +const WriteEntryTar = WriteEntry.Tar +const Yallist = require('yallist') +const EOF = Buffer.alloc(1024) +const ONSTAT = Symbol('onStat') +const ENDED = Symbol('ended') +const QUEUE = Symbol('queue') +const CURRENT = Symbol('current') +const PROCESS = Symbol('process') +const PROCESSING = Symbol('processing') +const PROCESSJOB = Symbol('processJob') +const JOBS = Symbol('jobs') +const JOBDONE = Symbol('jobDone') +const ADDFSENTRY = Symbol('addFSEntry') +const ADDTARENTRY = Symbol('addTarEntry') +const STAT = Symbol('stat') +const READDIR = Symbol('readdir') +const ONREADDIR = Symbol('onreaddir') +const PIPE = Symbol('pipe') +const ENTRY = Symbol('entry') +const ENTRYOPT = Symbol('entryOpt') +const WRITEENTRYCLASS = Symbol('writeEntryClass') +const WRITE = Symbol('write') +const ONDRAIN = Symbol('ondrain') + +const fs = require('fs') +const path = require('path') +const warner = require('./warn-mixin.js') +const normPath = require('./normalize-windows-path.js') + +const Pack = warner(class Pack extends MiniPass { + constructor (opt) { + super(opt) + opt = opt || Object.create(null) + this.opt = opt + this.file = opt.file || '' + this.cwd = opt.cwd || process.cwd() + this.maxReadSize = opt.maxReadSize + this.preservePaths = !!opt.preservePaths + this.strict = !!opt.strict + this.noPax = !!opt.noPax + this.prefix = normPath(opt.prefix || '') + this.linkCache = opt.linkCache || new Map() + this.statCache = opt.statCache || new Map() + this.readdirCache = opt.readdirCache || new Map() + + this[WRITEENTRYCLASS] = WriteEntry + if (typeof opt.onwarn === 'function') + this.on('warn', opt.onwarn) + + this.portable = !!opt.portable + this.zip = null + if (opt.gzip) { + if (typeof opt.gzip !== 'object') + opt.gzip = {} + if (this.portable) + opt.gzip.portable = true + this.zip = new zlib.Gzip(opt.gzip) + this.zip.on('data', chunk => super.write(chunk)) + this.zip.on('end', _ => super.end()) + this.zip.on('drain', _ => this[ONDRAIN]()) + this.on('resume', _ => this.zip.resume()) + } else + this.on('drain', this[ONDRAIN]) + + this.noDirRecurse = !!opt.noDirRecurse + this.follow = !!opt.follow + this.noMtime = !!opt.noMtime + this.mtime = opt.mtime || null + + this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true + + this[QUEUE] = new Yallist() + this[JOBS] = 0 + this.jobs = +opt.jobs || 4 + this[PROCESSING] = false + this[ENDED] = false + } + + [WRITE] (chunk) { + return super.write(chunk) + } + + add (path) { + this.write(path) + return this + } + + end (path) { + if (path) + this.write(path) + this[ENDED] = true + this[PROCESS]() + return this + } + + write (path) { + if (this[ENDED]) + throw new Error('write after end') + + if (path instanceof ReadEntry) + this[ADDTARENTRY](path) + else + this[ADDFSENTRY](path) + return this.flowing + } + + [ADDTARENTRY] (p) { + const absolute = normPath(path.resolve(this.cwd, p.path)) + // in this case, we don't have to wait for the stat + if (!this.filter(p.path, p)) + p.resume() + else { + const job = new PackJob(p.path, absolute, false) + job.entry = new WriteEntryTar(p, this[ENTRYOPT](job)) + job.entry.on('end', _ => this[JOBDONE](job)) + this[JOBS] += 1 + this[QUEUE].push(job) + } + + this[PROCESS]() + } + + [ADDFSENTRY] (p) { + const absolute = normPath(path.resolve(this.cwd, p)) + this[QUEUE].push(new PackJob(p, absolute)) + this[PROCESS]() + } + + [STAT] (job) { + job.pending = true + this[JOBS] += 1 + const stat = this.follow ? 'stat' : 'lstat' + fs[stat](job.absolute, (er, stat) => { + job.pending = false + this[JOBS] -= 1 + if (er) + this.emit('error', er) + else + this[ONSTAT](job, stat) + }) + } + + [ONSTAT] (job, stat) { + this.statCache.set(job.absolute, stat) + job.stat = stat + + // now we have the stat, we can filter it. + if (!this.filter(job.path, stat)) + job.ignore = true + + this[PROCESS]() + } + + [READDIR] (job) { + job.pending = true + this[JOBS] += 1 + fs.readdir(job.absolute, (er, entries) => { + job.pending = false + this[JOBS] -= 1 + if (er) + return this.emit('error', er) + this[ONREADDIR](job, entries) + }) + } + + [ONREADDIR] (job, entries) { + this.readdirCache.set(job.absolute, entries) + job.readdir = entries + this[PROCESS]() + } + + [PROCESS] () { + if (this[PROCESSING]) + return + + this[PROCESSING] = true + for (let w = this[QUEUE].head; + w !== null && this[JOBS] < this.jobs; + w = w.next) { + this[PROCESSJOB](w.value) + if (w.value.ignore) { + const p = w.next + this[QUEUE].removeNode(w) + w.next = p + } + } + + this[PROCESSING] = false + + if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { + if (this.zip) + this.zip.end(EOF) + else { + super.write(EOF) + super.end() + } + } + } + + get [CURRENT] () { + return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value + } + + [JOBDONE] (job) { + this[QUEUE].shift() + this[JOBS] -= 1 + this[PROCESS]() + } + + [PROCESSJOB] (job) { + if (job.pending) + return + + if (job.entry) { + if (job === this[CURRENT] && !job.piped) + this[PIPE](job) + return + } + + if (!job.stat) { + if (this.statCache.has(job.absolute)) + this[ONSTAT](job, this.statCache.get(job.absolute)) + else + this[STAT](job) + } + if (!job.stat) + return + + // filtered out! + if (job.ignore) + return + + if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { + if (this.readdirCache.has(job.absolute)) + this[ONREADDIR](job, this.readdirCache.get(job.absolute)) + else + this[READDIR](job) + if (!job.readdir) + return + } + + // we know it doesn't have an entry, because that got checked above + job.entry = this[ENTRY](job) + if (!job.entry) { + job.ignore = true + return + } + + if (job === this[CURRENT] && !job.piped) + this[PIPE](job) + } + + [ENTRYOPT] (job) { + return { + onwarn: (code, msg, data) => this.warn(code, msg, data), + noPax: this.noPax, + cwd: this.cwd, + absolute: job.absolute, + preservePaths: this.preservePaths, + maxReadSize: this.maxReadSize, + strict: this.strict, + portable: this.portable, + linkCache: this.linkCache, + statCache: this.statCache, + noMtime: this.noMtime, + mtime: this.mtime, + prefix: this.prefix, + } + } + + [ENTRY] (job) { + this[JOBS] += 1 + try { + return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)) + .on('end', () => this[JOBDONE](job)) + .on('error', er => this.emit('error', er)) + } catch (er) { + this.emit('error', er) + } + } + + [ONDRAIN] () { + if (this[CURRENT] && this[CURRENT].entry) + this[CURRENT].entry.resume() + } + + // like .pipe() but using super, because our write() is special + [PIPE] (job) { + job.piped = true + + if (job.readdir) { + job.readdir.forEach(entry => { + const p = job.path + const base = p === './' ? '' : p.replace(/\/*$/, '/') + this[ADDFSENTRY](base + entry) + }) + } + + const source = job.entry + const zip = this.zip + + if (zip) { + source.on('data', chunk => { + if (!zip.write(chunk)) + source.pause() + }) + } else { + source.on('data', chunk => { + if (!super.write(chunk)) + source.pause() + }) + } + } + + pause () { + if (this.zip) + this.zip.pause() + return super.pause() + } +}) + +class PackSync extends Pack { + constructor (opt) { + super(opt) + this[WRITEENTRYCLASS] = WriteEntrySync + } + + // pause/resume are no-ops in sync streams. + pause () {} + resume () {} + + [STAT] (job) { + const stat = this.follow ? 'statSync' : 'lstatSync' + this[ONSTAT](job, fs[stat](job.absolute)) + } + + [READDIR] (job, stat) { + this[ONREADDIR](job, fs.readdirSync(job.absolute)) + } + + // gotta get it all in this tick + [PIPE] (job) { + const source = job.entry + const zip = this.zip + + if (job.readdir) { + job.readdir.forEach(entry => { + const p = job.path + const base = p === './' ? '' : p.replace(/\/*$/, '/') + this[ADDFSENTRY](base + entry) + }) + } + + if (zip) { + source.on('data', chunk => { + zip.write(chunk) + }) + } else { + source.on('data', chunk => { + super[WRITE](chunk) + }) + } + } +} + +Pack.Sync = PackSync + +module.exports = Pack diff --git a/node_modules/tar/lib/parse.js b/node_modules/tar/lib/parse.js new file mode 100644 index 0000000..b1b4e7e --- /dev/null +++ b/node_modules/tar/lib/parse.js @@ -0,0 +1,481 @@ +'use strict' + +// this[BUFFER] is the remainder of a chunk if we're waiting for +// the full 512 bytes of a header to come in. We will Buffer.concat() +// it to the next write(), which is a mem copy, but a small one. +// +// this[QUEUE] is a Yallist of entries that haven't been emitted +// yet this can only get filled up if the user keeps write()ing after +// a write() returns false, or does a write() with more than one entry +// +// We don't buffer chunks, we always parse them and either create an +// entry, or push it into the active entry. The ReadEntry class knows +// to throw data away if .ignore=true +// +// Shift entry off the buffer when it emits 'end', and emit 'entry' for +// the next one in the list. +// +// At any time, we're pushing body chunks into the entry at WRITEENTRY, +// and waiting for 'end' on the entry at READENTRY +// +// ignored entries get .resume() called on them straight away + +const warner = require('./warn-mixin.js') +const Header = require('./header.js') +const EE = require('events') +const Yallist = require('yallist') +const maxMetaEntrySize = 1024 * 1024 +const Entry = require('./read-entry.js') +const Pax = require('./pax.js') +const zlib = require('minizlib') + +const gzipHeader = Buffer.from([0x1f, 0x8b]) +const STATE = Symbol('state') +const WRITEENTRY = Symbol('writeEntry') +const READENTRY = Symbol('readEntry') +const NEXTENTRY = Symbol('nextEntry') +const PROCESSENTRY = Symbol('processEntry') +const EX = Symbol('extendedHeader') +const GEX = Symbol('globalExtendedHeader') +const META = Symbol('meta') +const EMITMETA = Symbol('emitMeta') +const BUFFER = Symbol('buffer') +const QUEUE = Symbol('queue') +const ENDED = Symbol('ended') +const EMITTEDEND = Symbol('emittedEnd') +const EMIT = Symbol('emit') +const UNZIP = Symbol('unzip') +const CONSUMECHUNK = Symbol('consumeChunk') +const CONSUMECHUNKSUB = Symbol('consumeChunkSub') +const CONSUMEBODY = Symbol('consumeBody') +const CONSUMEMETA = Symbol('consumeMeta') +const CONSUMEHEADER = Symbol('consumeHeader') +const CONSUMING = Symbol('consuming') +const BUFFERCONCAT = Symbol('bufferConcat') +const MAYBEEND = Symbol('maybeEnd') +const WRITING = Symbol('writing') +const ABORTED = Symbol('aborted') +const DONE = Symbol('onDone') +const SAW_VALID_ENTRY = Symbol('sawValidEntry') +const SAW_NULL_BLOCK = Symbol('sawNullBlock') +const SAW_EOF = Symbol('sawEOF') + +const noop = _ => true + +module.exports = warner(class Parser extends EE { + constructor (opt) { + opt = opt || {} + super(opt) + + this.file = opt.file || '' + + // set to boolean false when an entry starts. 1024 bytes of \0 + // is technically a valid tarball, albeit a boring one. + this[SAW_VALID_ENTRY] = null + + // these BADARCHIVE errors can't be detected early. listen on DONE. + this.on(DONE, _ => { + if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) { + // either less than 1 block of data, or all entries were invalid. + // Either way, probably not even a tarball. + this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format') + } + }) + + if (opt.ondone) + this.on(DONE, opt.ondone) + else { + this.on(DONE, _ => { + this.emit('prefinish') + this.emit('finish') + this.emit('end') + this.emit('close') + }) + } + + this.strict = !!opt.strict + this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize + this.filter = typeof opt.filter === 'function' ? opt.filter : noop + + // have to set this so that streams are ok piping into it + this.writable = true + this.readable = false + + this[QUEUE] = new Yallist() + this[BUFFER] = null + this[READENTRY] = null + this[WRITEENTRY] = null + this[STATE] = 'begin' + this[META] = '' + this[EX] = null + this[GEX] = null + this[ENDED] = false + this[UNZIP] = null + this[ABORTED] = false + this[SAW_NULL_BLOCK] = false + this[SAW_EOF] = false + if (typeof opt.onwarn === 'function') + this.on('warn', opt.onwarn) + if (typeof opt.onentry === 'function') + this.on('entry', opt.onentry) + } + + [CONSUMEHEADER] (chunk, position) { + if (this[SAW_VALID_ENTRY] === null) + this[SAW_VALID_ENTRY] = false + let header + try { + header = new Header(chunk, position, this[EX], this[GEX]) + } catch (er) { + return this.warn('TAR_ENTRY_INVALID', er) + } + + if (header.nullBlock) { + if (this[SAW_NULL_BLOCK]) { + this[SAW_EOF] = true + // ending an archive with no entries. pointless, but legal. + if (this[STATE] === 'begin') + this[STATE] = 'header' + this[EMIT]('eof') + } else { + this[SAW_NULL_BLOCK] = true + this[EMIT]('nullBlock') + } + } else { + this[SAW_NULL_BLOCK] = false + if (!header.cksumValid) + this.warn('TAR_ENTRY_INVALID', 'checksum failure', {header}) + else if (!header.path) + this.warn('TAR_ENTRY_INVALID', 'path is required', {header}) + else { + const type = header.type + if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) + this.warn('TAR_ENTRY_INVALID', 'linkpath required', {header}) + else if (!/^(Symbolic)?Link$/.test(type) && header.linkpath) + this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', {header}) + else { + const entry = this[WRITEENTRY] = new Entry(header, this[EX], this[GEX]) + + // we do this for meta & ignored entries as well, because they + // are still valid tar, or else we wouldn't know to ignore them + if (!this[SAW_VALID_ENTRY]) { + if (entry.remain) { + // this might be the one! + const onend = () => { + if (!entry.invalid) + this[SAW_VALID_ENTRY] = true + } + entry.on('end', onend) + } else + this[SAW_VALID_ENTRY] = true + } + + if (entry.meta) { + if (entry.size > this.maxMetaEntrySize) { + entry.ignore = true + this[EMIT]('ignoredEntry', entry) + this[STATE] = 'ignore' + entry.resume() + } else if (entry.size > 0) { + this[META] = '' + entry.on('data', c => this[META] += c) + this[STATE] = 'meta' + } + } else { + this[EX] = null + entry.ignore = entry.ignore || !this.filter(entry.path, entry) + + if (entry.ignore) { + // probably valid, just not something we care about + this[EMIT]('ignoredEntry', entry) + this[STATE] = entry.remain ? 'ignore' : 'header' + entry.resume() + } else { + if (entry.remain) + this[STATE] = 'body' + else { + this[STATE] = 'header' + entry.end() + } + + if (!this[READENTRY]) { + this[QUEUE].push(entry) + this[NEXTENTRY]() + } else + this[QUEUE].push(entry) + } + } + } + } + } + } + + [PROCESSENTRY] (entry) { + let go = true + + if (!entry) { + this[READENTRY] = null + go = false + } else if (Array.isArray(entry)) + this.emit.apply(this, entry) + else { + this[READENTRY] = entry + this.emit('entry', entry) + if (!entry.emittedEnd) { + entry.on('end', _ => this[NEXTENTRY]()) + go = false + } + } + + return go + } + + [NEXTENTRY] () { + do {} while (this[PROCESSENTRY](this[QUEUE].shift())) + + if (!this[QUEUE].length) { + // At this point, there's nothing in the queue, but we may have an + // entry which is being consumed (readEntry). + // If we don't, then we definitely can handle more data. + // If we do, and either it's flowing, or it has never had any data + // written to it, then it needs more. + // The only other possibility is that it has returned false from a + // write() call, so we wait for the next drain to continue. + const re = this[READENTRY] + const drainNow = !re || re.flowing || re.size === re.remain + if (drainNow) { + if (!this[WRITING]) + this.emit('drain') + } else + re.once('drain', _ => this.emit('drain')) + } + } + + [CONSUMEBODY] (chunk, position) { + // write up to but no more than writeEntry.blockRemain + const entry = this[WRITEENTRY] + const br = entry.blockRemain + const c = (br >= chunk.length && position === 0) ? chunk + : chunk.slice(position, position + br) + + entry.write(c) + + if (!entry.blockRemain) { + this[STATE] = 'header' + this[WRITEENTRY] = null + entry.end() + } + + return c.length + } + + [CONSUMEMETA] (chunk, position) { + const entry = this[WRITEENTRY] + const ret = this[CONSUMEBODY](chunk, position) + + // if we finished, then the entry is reset + if (!this[WRITEENTRY]) + this[EMITMETA](entry) + + return ret + } + + [EMIT] (ev, data, extra) { + if (!this[QUEUE].length && !this[READENTRY]) + this.emit(ev, data, extra) + else + this[QUEUE].push([ev, data, extra]) + } + + [EMITMETA] (entry) { + this[EMIT]('meta', this[META]) + switch (entry.type) { + case 'ExtendedHeader': + case 'OldExtendedHeader': + this[EX] = Pax.parse(this[META], this[EX], false) + break + + case 'GlobalExtendedHeader': + this[GEX] = Pax.parse(this[META], this[GEX], true) + break + + case 'NextFileHasLongPath': + case 'OldGnuLongPath': + this[EX] = this[EX] || Object.create(null) + this[EX].path = this[META].replace(/\0.*/, '') + break + + case 'NextFileHasLongLinkpath': + this[EX] = this[EX] || Object.create(null) + this[EX].linkpath = this[META].replace(/\0.*/, '') + break + + /* istanbul ignore next */ + default: throw new Error('unknown meta: ' + entry.type) + } + } + + abort (error) { + this[ABORTED] = true + this.emit('abort', error) + // always throws, even in non-strict mode + this.warn('TAR_ABORT', error, { recoverable: false }) + } + + write (chunk) { + if (this[ABORTED]) + return + + // first write, might be gzipped + if (this[UNZIP] === null && chunk) { + if (this[BUFFER]) { + chunk = Buffer.concat([this[BUFFER], chunk]) + this[BUFFER] = null + } + if (chunk.length < gzipHeader.length) { + this[BUFFER] = chunk + return true + } + for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) { + if (chunk[i] !== gzipHeader[i]) + this[UNZIP] = false + } + if (this[UNZIP] === null) { + const ended = this[ENDED] + this[ENDED] = false + this[UNZIP] = new zlib.Unzip() + this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk)) + this[UNZIP].on('error', er => this.abort(er)) + this[UNZIP].on('end', _ => { + this[ENDED] = true + this[CONSUMECHUNK]() + }) + this[WRITING] = true + const ret = this[UNZIP][ended ? 'end' : 'write'](chunk) + this[WRITING] = false + return ret + } + } + + this[WRITING] = true + if (this[UNZIP]) + this[UNZIP].write(chunk) + else + this[CONSUMECHUNK](chunk) + this[WRITING] = false + + // return false if there's a queue, or if the current entry isn't flowing + const ret = + this[QUEUE].length ? false : + this[READENTRY] ? this[READENTRY].flowing : + true + + // if we have no queue, then that means a clogged READENTRY + if (!ret && !this[QUEUE].length) + this[READENTRY].once('drain', _ => this.emit('drain')) + + return ret + } + + [BUFFERCONCAT] (c) { + if (c && !this[ABORTED]) + this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c + } + + [MAYBEEND] () { + if (this[ENDED] && + !this[EMITTEDEND] && + !this[ABORTED] && + !this[CONSUMING]) { + this[EMITTEDEND] = true + const entry = this[WRITEENTRY] + if (entry && entry.blockRemain) { + // truncated, likely a damaged file + const have = this[BUFFER] ? this[BUFFER].length : 0 + this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${ + entry.blockRemain} more bytes, only ${have} available)`, {entry}) + if (this[BUFFER]) + entry.write(this[BUFFER]) + entry.end() + } + this[EMIT](DONE) + } + } + + [CONSUMECHUNK] (chunk) { + if (this[CONSUMING]) + this[BUFFERCONCAT](chunk) + else if (!chunk && !this[BUFFER]) + this[MAYBEEND]() + else { + this[CONSUMING] = true + if (this[BUFFER]) { + this[BUFFERCONCAT](chunk) + const c = this[BUFFER] + this[BUFFER] = null + this[CONSUMECHUNKSUB](c) + } else + this[CONSUMECHUNKSUB](chunk) + + while (this[BUFFER] && + this[BUFFER].length >= 512 && + !this[ABORTED] && + !this[SAW_EOF]) { + const c = this[BUFFER] + this[BUFFER] = null + this[CONSUMECHUNKSUB](c) + } + this[CONSUMING] = false + } + + if (!this[BUFFER] || this[ENDED]) + this[MAYBEEND]() + } + + [CONSUMECHUNKSUB] (chunk) { + // we know that we are in CONSUMING mode, so anything written goes into + // the buffer. Advance the position and put any remainder in the buffer. + let position = 0 + const length = chunk.length + while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) { + switch (this[STATE]) { + case 'begin': + case 'header': + this[CONSUMEHEADER](chunk, position) + position += 512 + break + + case 'ignore': + case 'body': + position += this[CONSUMEBODY](chunk, position) + break + + case 'meta': + position += this[CONSUMEMETA](chunk, position) + break + + /* istanbul ignore next */ + default: + throw new Error('invalid state: ' + this[STATE]) + } + } + + if (position < length) { + if (this[BUFFER]) + this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]]) + else + this[BUFFER] = chunk.slice(position) + } + } + + end (chunk) { + if (!this[ABORTED]) { + if (this[UNZIP]) + this[UNZIP].end(chunk) + else { + this[ENDED] = true + this.write(chunk) + } + } + } +}) diff --git a/node_modules/tar/lib/path-reservations.js b/node_modules/tar/lib/path-reservations.js new file mode 100644 index 0000000..8183c45 --- /dev/null +++ b/node_modules/tar/lib/path-reservations.js @@ -0,0 +1,148 @@ +// A path exclusive reservation system +// reserve([list, of, paths], fn) +// When the fn is first in line for all its paths, it +// is called with a cb that clears the reservation. +// +// Used by async unpack to avoid clobbering paths in use, +// while still allowing maximal safe parallelization. + +const assert = require('assert') +const normalize = require('./normalize-unicode.js') +const stripSlashes = require('./strip-trailing-slashes.js') +const { join } = require('path') + +const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform +const isWindows = platform === 'win32' + +module.exports = () => { + // path => [function or Set] + // A Set object means a directory reservation + // A fn is a direct reservation on that path + const queues = new Map() + + // fn => {paths:[path,...], dirs:[path, ...]} + const reservations = new Map() + + // return a set of parent dirs for a given path + // '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d'] + const getDirs = path => { + const dirs = path.split('/').slice(0, -1).reduce((set, path) => { + if (set.length) + path = join(set[set.length - 1], path) + set.push(path || '/') + return set + }, []) + return dirs + } + + // functions currently running + const running = new Set() + + // return the queues for each path the function cares about + // fn => {paths, dirs} + const getQueues = fn => { + const res = reservations.get(fn) + /* istanbul ignore if - unpossible */ + if (!res) + throw new Error('function does not have any path reservations') + return { + paths: res.paths.map(path => queues.get(path)), + dirs: [...res.dirs].map(path => queues.get(path)), + } + } + + // check if fn is first in line for all its paths, and is + // included in the first set for all its dir queues + const check = fn => { + const {paths, dirs} = getQueues(fn) + return paths.every(q => q[0] === fn) && + dirs.every(q => q[0] instanceof Set && q[0].has(fn)) + } + + // run the function if it's first in line and not already running + const run = fn => { + if (running.has(fn) || !check(fn)) + return false + running.add(fn) + fn(() => clear(fn)) + return true + } + + const clear = fn => { + if (!running.has(fn)) + return false + + const { paths, dirs } = reservations.get(fn) + const next = new Set() + + paths.forEach(path => { + const q = queues.get(path) + assert.equal(q[0], fn) + if (q.length === 1) + queues.delete(path) + else { + q.shift() + if (typeof q[0] === 'function') + next.add(q[0]) + else + q[0].forEach(fn => next.add(fn)) + } + }) + + dirs.forEach(dir => { + const q = queues.get(dir) + assert(q[0] instanceof Set) + if (q[0].size === 1 && q.length === 1) + queues.delete(dir) + else if (q[0].size === 1) { + q.shift() + + // must be a function or else the Set would've been reused + next.add(q[0]) + } else + q[0].delete(fn) + }) + running.delete(fn) + + next.forEach(fn => run(fn)) + return true + } + + const reserve = (paths, fn) => { + // collide on matches across case and unicode normalization + // On windows, thanks to the magic of 8.3 shortnames, it is fundamentally + // impossible to determine whether two paths refer to the same thing on + // disk, without asking the kernel for a shortname. + // So, we just pretend that every path matches every other path here, + // effectively removing all parallelization on windows. + paths = isWindows ? ['win32 parallelization disabled'] : paths.map(p => { + // don't need normPath, because we skip this entirely for windows + return normalize(stripSlashes(join(p))).toLowerCase() + }) + + const dirs = new Set( + paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)) + ) + reservations.set(fn, {dirs, paths}) + paths.forEach(path => { + const q = queues.get(path) + if (!q) + queues.set(path, [fn]) + else + q.push(fn) + }) + dirs.forEach(dir => { + const q = queues.get(dir) + if (!q) + queues.set(dir, [new Set([fn])]) + else if (q[q.length - 1] instanceof Set) + q[q.length - 1].add(fn) + else + q.push(new Set([fn])) + }) + + return run(fn) + } + + return { check, reserve } +} diff --git a/node_modules/tar/lib/pax.js b/node_modules/tar/lib/pax.js new file mode 100644 index 0000000..7768c7b --- /dev/null +++ b/node_modules/tar/lib/pax.js @@ -0,0 +1,143 @@ +'use strict' +const Header = require('./header.js') +const path = require('path') + +class Pax { + constructor (obj, global) { + this.atime = obj.atime || null + this.charset = obj.charset || null + this.comment = obj.comment || null + this.ctime = obj.ctime || null + this.gid = obj.gid || null + this.gname = obj.gname || null + this.linkpath = obj.linkpath || null + this.mtime = obj.mtime || null + this.path = obj.path || null + this.size = obj.size || null + this.uid = obj.uid || null + this.uname = obj.uname || null + this.dev = obj.dev || null + this.ino = obj.ino || null + this.nlink = obj.nlink || null + this.global = global || false + } + + encode () { + const body = this.encodeBody() + if (body === '') + return null + + const bodyLen = Buffer.byteLength(body) + // round up to 512 bytes + // add 512 for header + const bufLen = 512 * Math.ceil(1 + bodyLen / 512) + const buf = Buffer.allocUnsafe(bufLen) + + // 0-fill the header section, it might not hit every field + for (let i = 0; i < 512; i++) + buf[i] = 0 + + new Header({ + // XXX split the path + // then the path should be PaxHeader + basename, but less than 99, + // prepend with the dirname + path: ('PaxHeader/' + path.basename(this.path)).slice(0, 99), + mode: this.mode || 0o644, + uid: this.uid || null, + gid: this.gid || null, + size: bodyLen, + mtime: this.mtime || null, + type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader', + linkpath: '', + uname: this.uname || '', + gname: this.gname || '', + devmaj: 0, + devmin: 0, + atime: this.atime || null, + ctime: this.ctime || null, + }).encode(buf) + + buf.write(body, 512, bodyLen, 'utf8') + + // null pad after the body + for (let i = bodyLen + 512; i < buf.length; i++) + buf[i] = 0 + + return buf + } + + encodeBody () { + return ( + this.encodeField('path') + + this.encodeField('ctime') + + this.encodeField('atime') + + this.encodeField('dev') + + this.encodeField('ino') + + this.encodeField('nlink') + + this.encodeField('charset') + + this.encodeField('comment') + + this.encodeField('gid') + + this.encodeField('gname') + + this.encodeField('linkpath') + + this.encodeField('mtime') + + this.encodeField('size') + + this.encodeField('uid') + + this.encodeField('uname') + ) + } + + encodeField (field) { + if (this[field] === null || this[field] === undefined) + return '' + const v = this[field] instanceof Date ? this[field].getTime() / 1000 + : this[field] + const s = ' ' + + (field === 'dev' || field === 'ino' || field === 'nlink' + ? 'SCHILY.' : '') + + field + '=' + v + '\n' + const byteLen = Buffer.byteLength(s) + // the digits includes the length of the digits in ascii base-10 + // so if it's 9 characters, then adding 1 for the 9 makes it 10 + // which makes it 11 chars. + let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1 + if (byteLen + digits >= Math.pow(10, digits)) + digits += 1 + const len = digits + byteLen + return len + s + } +} + +Pax.parse = (string, ex, g) => new Pax(merge(parseKV(string), ex), g) + +const merge = (a, b) => + b ? Object.keys(a).reduce((s, k) => (s[k] = a[k], s), b) : a + +const parseKV = string => + string + .replace(/\n$/, '') + .split('\n') + .reduce(parseKVLine, Object.create(null)) + +const parseKVLine = (set, line) => { + const n = parseInt(line, 10) + + // XXX Values with \n in them will fail this. + // Refactor to not be a naive line-by-line parse. + if (n !== Buffer.byteLength(line) + 1) + return set + + line = line.substr((n + ' ').length) + const kv = line.split('=') + const k = kv.shift().replace(/^SCHILY\.(dev|ino|nlink)/, '$1') + if (!k) + return set + + const v = kv.join('=') + set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) + ? new Date(v * 1000) + : /^[0-9]+$/.test(v) ? +v + : v + return set +} + +module.exports = Pax diff --git a/node_modules/tar/lib/read-entry.js b/node_modules/tar/lib/read-entry.js new file mode 100644 index 0000000..183a605 --- /dev/null +++ b/node_modules/tar/lib/read-entry.js @@ -0,0 +1,100 @@ +'use strict' +const MiniPass = require('minipass') +const normPath = require('./normalize-windows-path.js') + +const SLURP = Symbol('slurp') +module.exports = class ReadEntry extends MiniPass { + constructor (header, ex, gex) { + super() + // read entries always start life paused. this is to avoid the + // situation where Minipass's auto-ending empty streams results + // in an entry ending before we're ready for it. + this.pause() + this.extended = ex + this.globalExtended = gex + this.header = header + this.startBlockSize = 512 * Math.ceil(header.size / 512) + this.blockRemain = this.startBlockSize + this.remain = header.size + this.type = header.type + this.meta = false + this.ignore = false + switch (this.type) { + case 'File': + case 'OldFile': + case 'Link': + case 'SymbolicLink': + case 'CharacterDevice': + case 'BlockDevice': + case 'Directory': + case 'FIFO': + case 'ContiguousFile': + case 'GNUDumpDir': + break + + case 'NextFileHasLongLinkpath': + case 'NextFileHasLongPath': + case 'OldGnuLongPath': + case 'GlobalExtendedHeader': + case 'ExtendedHeader': + case 'OldExtendedHeader': + this.meta = true + break + + // NOTE: gnutar and bsdtar treat unrecognized types as 'File' + // it may be worth doing the same, but with a warning. + default: + this.ignore = true + } + + this.path = normPath(header.path) + this.mode = header.mode + if (this.mode) + this.mode = this.mode & 0o7777 + this.uid = header.uid + this.gid = header.gid + this.uname = header.uname + this.gname = header.gname + this.size = header.size + this.mtime = header.mtime + this.atime = header.atime + this.ctime = header.ctime + this.linkpath = normPath(header.linkpath) + this.uname = header.uname + this.gname = header.gname + + if (ex) + this[SLURP](ex) + if (gex) + this[SLURP](gex, true) + } + + write (data) { + const writeLen = data.length + if (writeLen > this.blockRemain) + throw new Error('writing more to entry than is appropriate') + + const r = this.remain + const br = this.blockRemain + this.remain = Math.max(0, r - writeLen) + this.blockRemain = Math.max(0, br - writeLen) + if (this.ignore) + return true + + if (r >= writeLen) + return super.write(data) + + // r < writeLen + return super.write(data.slice(0, r)) + } + + [SLURP] (ex, global) { + for (const k in ex) { + // we slurp in everything except for the path attribute in + // a global extended header, because that's weird. + if (ex[k] !== null && ex[k] !== undefined && + !(global && k === 'path')) + this[k] = k === 'path' || k === 'linkpath' ? normPath(ex[k]) : ex[k] + } + } +} diff --git a/node_modules/tar/lib/replace.js b/node_modules/tar/lib/replace.js new file mode 100644 index 0000000..1374f3f --- /dev/null +++ b/node_modules/tar/lib/replace.js @@ -0,0 +1,223 @@ +'use strict' + +// tar -r +const hlo = require('./high-level-opt.js') +const Pack = require('./pack.js') +const fs = require('fs') +const fsm = require('fs-minipass') +const t = require('./list.js') +const path = require('path') + +// starting at the head of the file, read a Header +// If the checksum is invalid, that's our position to start writing +// If it is, jump forward by the specified size (round up to 512) +// and try again. +// Write the new Pack stream starting there. + +const Header = require('./header.js') + +module.exports = (opt_, files, cb) => { + const opt = hlo(opt_) + + if (!opt.file) + throw new TypeError('file is required') + + if (opt.gzip) + throw new TypeError('cannot append to compressed archives') + + if (!files || !Array.isArray(files) || !files.length) + throw new TypeError('no files or directories specified') + + files = Array.from(files) + + return opt.sync ? replaceSync(opt, files) + : replace(opt, files, cb) +} + +const replaceSync = (opt, files) => { + const p = new Pack.Sync(opt) + + let threw = true + let fd + let position + + try { + try { + fd = fs.openSync(opt.file, 'r+') + } catch (er) { + if (er.code === 'ENOENT') + fd = fs.openSync(opt.file, 'w+') + else + throw er + } + + const st = fs.fstatSync(fd) + const headBuf = Buffer.alloc(512) + + POSITION: for (position = 0; position < st.size; position += 512) { + for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) { + bytes = fs.readSync( + fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos + ) + + if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) + throw new Error('cannot append to compressed archives') + + if (!bytes) + break POSITION + } + + const h = new Header(headBuf) + if (!h.cksumValid) + break + const entryBlockSize = 512 * Math.ceil(h.size / 512) + if (position + entryBlockSize + 512 > st.size) + break + // the 512 for the header we just parsed will be added as well + // also jump ahead all the blocks for the body + position += entryBlockSize + if (opt.mtimeCache) + opt.mtimeCache.set(h.path, h.mtime) + } + threw = false + + streamSync(opt, p, position, fd, files) + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } + } +} + +const streamSync = (opt, p, position, fd, files) => { + const stream = new fsm.WriteStreamSync(opt.file, { + fd: fd, + start: position, + }) + p.pipe(stream) + addFilesSync(p, files) +} + +const replace = (opt, files, cb) => { + files = Array.from(files) + const p = new Pack(opt) + + const getPos = (fd, size, cb_) => { + const cb = (er, pos) => { + if (er) + fs.close(fd, _ => cb_(er)) + else + cb_(null, pos) + } + + let position = 0 + if (size === 0) + return cb(null, 0) + + let bufPos = 0 + const headBuf = Buffer.alloc(512) + const onread = (er, bytes) => { + if (er) + return cb(er) + bufPos += bytes + if (bufPos < 512 && bytes) { + return fs.read( + fd, headBuf, bufPos, headBuf.length - bufPos, + position + bufPos, onread + ) + } + + if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) + return cb(new Error('cannot append to compressed archives')) + + // truncated header + if (bufPos < 512) + return cb(null, position) + + const h = new Header(headBuf) + if (!h.cksumValid) + return cb(null, position) + + const entryBlockSize = 512 * Math.ceil(h.size / 512) + if (position + entryBlockSize + 512 > size) + return cb(null, position) + + position += entryBlockSize + 512 + if (position >= size) + return cb(null, position) + + if (opt.mtimeCache) + opt.mtimeCache.set(h.path, h.mtime) + bufPos = 0 + fs.read(fd, headBuf, 0, 512, position, onread) + } + fs.read(fd, headBuf, 0, 512, position, onread) + } + + const promise = new Promise((resolve, reject) => { + p.on('error', reject) + let flag = 'r+' + const onopen = (er, fd) => { + if (er && er.code === 'ENOENT' && flag === 'r+') { + flag = 'w+' + return fs.open(opt.file, flag, onopen) + } + + if (er) + return reject(er) + + fs.fstat(fd, (er, st) => { + if (er) + return fs.close(fd, () => reject(er)) + + getPos(fd, st.size, (er, position) => { + if (er) + return reject(er) + const stream = new fsm.WriteStream(opt.file, { + fd: fd, + start: position, + }) + p.pipe(stream) + stream.on('error', reject) + stream.on('close', resolve) + addFilesAsync(p, files) + }) + }) + } + fs.open(opt.file, flag, onopen) + }) + + return cb ? promise.then(cb, cb) : promise +} + +const addFilesSync = (p, files) => { + files.forEach(file => { + if (file.charAt(0) === '@') { + t({ + file: path.resolve(p.cwd, file.substr(1)), + sync: true, + noResume: true, + onentry: entry => p.add(entry), + }) + } else + p.add(file) + }) + p.end() +} + +const addFilesAsync = (p, files) => { + while (files.length) { + const file = files.shift() + if (file.charAt(0) === '@') { + return t({ + file: path.resolve(p.cwd, file.substr(1)), + noResume: true, + onentry: entry => p.add(entry), + }).then(_ => addFilesAsync(p, files)) + } else + p.add(file) + } + p.end() +} diff --git a/node_modules/tar/lib/strip-absolute-path.js b/node_modules/tar/lib/strip-absolute-path.js new file mode 100644 index 0000000..1aa2d2a --- /dev/null +++ b/node_modules/tar/lib/strip-absolute-path.js @@ -0,0 +1,24 @@ +// unix absolute paths are also absolute on win32, so we use this for both +const { isAbsolute, parse } = require('path').win32 + +// returns [root, stripped] +// Note that windows will think that //x/y/z/a has a "root" of //x/y, and in +// those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip / +// explicitly if it's the first character. +// drive-specific relative paths on Windows get their root stripped off even +// though they are not absolute, so `c:../foo` becomes ['c:', '../foo'] +module.exports = path => { + let r = '' + + let parsed = parse(path) + while (isAbsolute(path) || parsed.root) { + // windows will think that //x/y/z has a "root" of //x/y/ + // but strip the //?/C:/ off of //?/C:/path + const root = path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ? '/' + : parsed.root + path = path.substr(root.length) + r += root + parsed = parse(path) + } + return [r, path] +} diff --git a/node_modules/tar/lib/strip-trailing-slashes.js b/node_modules/tar/lib/strip-trailing-slashes.js new file mode 100644 index 0000000..3e3ecec --- /dev/null +++ b/node_modules/tar/lib/strip-trailing-slashes.js @@ -0,0 +1,13 @@ +// warning: extremely hot code path. +// This has been meticulously optimized for use +// within npm install on large package trees. +// Do not edit without careful benchmarking. +module.exports = str => { + let i = str.length - 1 + let slashesStart = -1 + while (i > -1 && str.charAt(i) === '/') { + slashesStart = i + i-- + } + return slashesStart === -1 ? str : str.slice(0, slashesStart) +} diff --git a/node_modules/tar/lib/types.js b/node_modules/tar/lib/types.js new file mode 100644 index 0000000..7bfc254 --- /dev/null +++ b/node_modules/tar/lib/types.js @@ -0,0 +1,44 @@ +'use strict' +// map types from key to human-friendly name +exports.name = new Map([ + ['0', 'File'], + // same as File + ['', 'OldFile'], + ['1', 'Link'], + ['2', 'SymbolicLink'], + // Devices and FIFOs aren't fully supported + // they are parsed, but skipped when unpacking + ['3', 'CharacterDevice'], + ['4', 'BlockDevice'], + ['5', 'Directory'], + ['6', 'FIFO'], + // same as File + ['7', 'ContiguousFile'], + // pax headers + ['g', 'GlobalExtendedHeader'], + ['x', 'ExtendedHeader'], + // vendor-specific stuff + // skip + ['A', 'SolarisACL'], + // like 5, but with data, which should be skipped + ['D', 'GNUDumpDir'], + // metadata only, skip + ['I', 'Inode'], + // data = link path of next file + ['K', 'NextFileHasLongLinkpath'], + // data = path of next file + ['L', 'NextFileHasLongPath'], + // skip + ['M', 'ContinuationFile'], + // like L + ['N', 'OldGnuLongPath'], + // skip + ['S', 'SparseFile'], + // skip + ['V', 'TapeVolumeHeader'], + // like x + ['X', 'OldExtendedHeader'], +]) + +// map the other direction +exports.code = new Map(Array.from(exports.name).map(kv => [kv[1], kv[0]])) diff --git a/node_modules/tar/lib/unpack.js b/node_modules/tar/lib/unpack.js new file mode 100644 index 0000000..7d39dc0 --- /dev/null +++ b/node_modules/tar/lib/unpack.js @@ -0,0 +1,877 @@ +'use strict' + +// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet. +// but the path reservations are required to avoid race conditions where +// parallelized unpack ops may mess with one another, due to dependencies +// (like a Link depending on its target) or destructive operations (like +// clobbering an fs object to create one of a different type.) + +const assert = require('assert') +const Parser = require('./parse.js') +const fs = require('fs') +const fsm = require('fs-minipass') +const path = require('path') +const mkdir = require('./mkdir.js') +const wc = require('./winchars.js') +const pathReservations = require('./path-reservations.js') +const stripAbsolutePath = require('./strip-absolute-path.js') +const normPath = require('./normalize-windows-path.js') +const stripSlash = require('./strip-trailing-slashes.js') +const normalize = require('./normalize-unicode.js') + +const ONENTRY = Symbol('onEntry') +const CHECKFS = Symbol('checkFs') +const CHECKFS2 = Symbol('checkFs2') +const PRUNECACHE = Symbol('pruneCache') +const ISREUSABLE = Symbol('isReusable') +const MAKEFS = Symbol('makeFs') +const FILE = Symbol('file') +const DIRECTORY = Symbol('directory') +const LINK = Symbol('link') +const SYMLINK = Symbol('symlink') +const HARDLINK = Symbol('hardlink') +const UNSUPPORTED = Symbol('unsupported') +const CHECKPATH = Symbol('checkPath') +const MKDIR = Symbol('mkdir') +const ONERROR = Symbol('onError') +const PENDING = Symbol('pending') +const PEND = Symbol('pend') +const UNPEND = Symbol('unpend') +const ENDED = Symbol('ended') +const MAYBECLOSE = Symbol('maybeClose') +const SKIP = Symbol('skip') +const DOCHOWN = Symbol('doChown') +const UID = Symbol('uid') +const GID = Symbol('gid') +const CHECKED_CWD = Symbol('checkedCwd') +const crypto = require('crypto') +const getFlag = require('./get-write-flag.js') +const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform +const isWindows = platform === 'win32' + +// Unlinks on Windows are not atomic. +// +// This means that if you have a file entry, followed by another +// file entry with an identical name, and you cannot re-use the file +// (because it's a hardlink, or because unlink:true is set, or it's +// Windows, which does not have useful nlink values), then the unlink +// will be committed to the disk AFTER the new file has been written +// over the old one, deleting the new file. +// +// To work around this, on Windows systems, we rename the file and then +// delete the renamed file. It's a sloppy kludge, but frankly, I do not +// know of a better way to do this, given windows' non-atomic unlink +// semantics. +// +// See: https://github.com/npm/node-tar/issues/183 +/* istanbul ignore next */ +const unlinkFile = (path, cb) => { + if (!isWindows) + return fs.unlink(path, cb) + + const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') + fs.rename(path, name, er => { + if (er) + return cb(er) + fs.unlink(name, cb) + }) +} + +/* istanbul ignore next */ +const unlinkFileSync = path => { + if (!isWindows) + return fs.unlinkSync(path) + + const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') + fs.renameSync(path, name) + fs.unlinkSync(name) +} + +// this.gid, entry.gid, this.processUid +const uint32 = (a, b, c) => + a === a >>> 0 ? a + : b === b >>> 0 ? b + : c + +// clear the cache if it's a case-insensitive unicode-squashing match. +// we can't know if the current file system is case-sensitive or supports +// unicode fully, so we check for similarity on the maximally compatible +// representation. Err on the side of pruning, since all it's doing is +// preventing lstats, and it's not the end of the world if we get a false +// positive. +// Note that on windows, we always drop the entire cache whenever a +// symbolic link is encountered, because 8.3 filenames are impossible +// to reason about, and collisions are hazards rather than just failures. +const cacheKeyNormalize = path => normalize(stripSlash(normPath(path))) + .toLowerCase() + +const pruneCache = (cache, abs) => { + abs = cacheKeyNormalize(abs) + for (const path of cache.keys()) { + const pnorm = cacheKeyNormalize(path) + if (pnorm === abs || pnorm.indexOf(abs + '/') === 0) + cache.delete(path) + } +} + +const dropCache = cache => { + for (const key of cache.keys()) + cache.delete(key) +} + +class Unpack extends Parser { + constructor (opt) { + if (!opt) + opt = {} + + opt.ondone = _ => { + this[ENDED] = true + this[MAYBECLOSE]() + } + + super(opt) + + this[CHECKED_CWD] = false + + this.reservations = pathReservations() + + this.transform = typeof opt.transform === 'function' ? opt.transform : null + + this.writable = true + this.readable = false + + this[PENDING] = 0 + this[ENDED] = false + + this.dirCache = opt.dirCache || new Map() + + if (typeof opt.uid === 'number' || typeof opt.gid === 'number') { + // need both or neither + if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number') + throw new TypeError('cannot set owner without number uid and gid') + if (opt.preserveOwner) { + throw new TypeError( + 'cannot preserve owner in archive and also set owner explicitly') + } + this.uid = opt.uid + this.gid = opt.gid + this.setOwner = true + } else { + this.uid = null + this.gid = null + this.setOwner = false + } + + // default true for root + if (opt.preserveOwner === undefined && typeof opt.uid !== 'number') + this.preserveOwner = process.getuid && process.getuid() === 0 + else + this.preserveOwner = !!opt.preserveOwner + + this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? + process.getuid() : null + this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? + process.getgid() : null + + // mostly just for testing, but useful in some cases. + // Forcibly trigger a chown on every entry, no matter what + this.forceChown = opt.forceChown === true + + // turn > this[ONENTRY](entry)) + } + + // a bad or damaged archive is a warning for Parser, but an error + // when extracting. Mark those errors as unrecoverable, because + // the Unpack contract cannot be met. + warn (code, msg, data = {}) { + if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') + data.recoverable = false + return super.warn(code, msg, data) + } + + [MAYBECLOSE] () { + if (this[ENDED] && this[PENDING] === 0) { + this.emit('prefinish') + this.emit('finish') + this.emit('end') + this.emit('close') + } + } + + [CHECKPATH] (entry) { + if (this.strip) { + const parts = normPath(entry.path).split('/') + if (parts.length < this.strip) + return false + entry.path = parts.slice(this.strip).join('/') + + if (entry.type === 'Link') { + const linkparts = normPath(entry.linkpath).split('/') + if (linkparts.length >= this.strip) + entry.linkpath = linkparts.slice(this.strip).join('/') + else + return false + } + } + + if (!this.preservePaths) { + const p = normPath(entry.path) + const parts = p.split('/') + if (parts.includes('..') || isWindows && /^[a-z]:\.\.$/i.test(parts[0])) { + this.warn('TAR_ENTRY_ERROR', `path contains '..'`, { + entry, + path: p, + }) + return false + } + + // strip off the root + const [root, stripped] = stripAbsolutePath(p) + if (root) { + entry.path = stripped + this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute path`, { + entry, + path: p, + }) + } + } + + if (path.isAbsolute(entry.path)) + entry.absolute = normPath(path.resolve(entry.path)) + else + entry.absolute = normPath(path.resolve(this.cwd, entry.path)) + + // if we somehow ended up with a path that escapes the cwd, and we are + // not in preservePaths mode, then something is fishy! This should have + // been prevented above, so ignore this for coverage. + /* istanbul ignore if - defense in depth */ + if (!this.preservePaths && + entry.absolute.indexOf(this.cwd + '/') !== 0 && + entry.absolute !== this.cwd) { + this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', { + entry, + path: normPath(entry.path), + resolvedPath: entry.absolute, + cwd: this.cwd, + }) + return false + } + + // an archive can set properties on the extraction directory, but it + // may not replace the cwd with a different kind of thing entirely. + if (entry.absolute === this.cwd && + entry.type !== 'Directory' && + entry.type !== 'GNUDumpDir') + return false + + // only encode : chars that aren't drive letter indicators + if (this.win32) { + const { root: aRoot } = path.win32.parse(entry.absolute) + entry.absolute = aRoot + wc.encode(entry.absolute.substr(aRoot.length)) + const { root: pRoot } = path.win32.parse(entry.path) + entry.path = pRoot + wc.encode(entry.path.substr(pRoot.length)) + } + + return true + } + + [ONENTRY] (entry) { + if (!this[CHECKPATH](entry)) + return entry.resume() + + assert.equal(typeof entry.absolute, 'string') + + switch (entry.type) { + case 'Directory': + case 'GNUDumpDir': + if (entry.mode) + entry.mode = entry.mode | 0o700 + + case 'File': + case 'OldFile': + case 'ContiguousFile': + case 'Link': + case 'SymbolicLink': + return this[CHECKFS](entry) + + case 'CharacterDevice': + case 'BlockDevice': + case 'FIFO': + default: + return this[UNSUPPORTED](entry) + } + } + + [ONERROR] (er, entry) { + // Cwd has to exist, or else nothing works. That's serious. + // Other errors are warnings, which raise the error in strict + // mode, but otherwise continue on. + if (er.name === 'CwdError') + this.emit('error', er) + else { + this.warn('TAR_ENTRY_ERROR', er, {entry}) + this[UNPEND]() + entry.resume() + } + } + + [MKDIR] (dir, mode, cb) { + mkdir(normPath(dir), { + uid: this.uid, + gid: this.gid, + processUid: this.processUid, + processGid: this.processGid, + umask: this.processUmask, + preserve: this.preservePaths, + unlink: this.unlink, + cache: this.dirCache, + cwd: this.cwd, + mode: mode, + noChmod: this.noChmod, + }, cb) + } + + [DOCHOWN] (entry) { + // in preserve owner mode, chown if the entry doesn't match process + // in set owner mode, chown if setting doesn't match process + return this.forceChown || + this.preserveOwner && + (typeof entry.uid === 'number' && entry.uid !== this.processUid || + typeof entry.gid === 'number' && entry.gid !== this.processGid) + || + (typeof this.uid === 'number' && this.uid !== this.processUid || + typeof this.gid === 'number' && this.gid !== this.processGid) + } + + [UID] (entry) { + return uint32(this.uid, entry.uid, this.processUid) + } + + [GID] (entry) { + return uint32(this.gid, entry.gid, this.processGid) + } + + [FILE] (entry, fullyDone) { + const mode = entry.mode & 0o7777 || this.fmode + const stream = new fsm.WriteStream(entry.absolute, { + flags: getFlag(entry.size), + mode: mode, + autoClose: false, + }) + stream.on('error', er => { + if (stream.fd) + fs.close(stream.fd, () => {}) + + // flush all the data out so that we aren't left hanging + // if the error wasn't actually fatal. otherwise the parse + // is blocked, and we never proceed. + stream.write = () => true + this[ONERROR](er, entry) + fullyDone() + }) + + let actions = 1 + const done = er => { + if (er) { + /* istanbul ignore else - we should always have a fd by now */ + if (stream.fd) + fs.close(stream.fd, () => {}) + + this[ONERROR](er, entry) + fullyDone() + return + } + + if (--actions === 0) { + fs.close(stream.fd, er => { + if (er) + this[ONERROR](er, entry) + else + this[UNPEND]() + fullyDone() + }) + } + } + + stream.on('finish', _ => { + // if futimes fails, try utimes + // if utimes fails, fail with the original error + // same for fchown/chown + const abs = entry.absolute + const fd = stream.fd + + if (entry.mtime && !this.noMtime) { + actions++ + const atime = entry.atime || new Date() + const mtime = entry.mtime + fs.futimes(fd, atime, mtime, er => + er ? fs.utimes(abs, atime, mtime, er2 => done(er2 && er)) + : done()) + } + + if (this[DOCHOWN](entry)) { + actions++ + const uid = this[UID](entry) + const gid = this[GID](entry) + fs.fchown(fd, uid, gid, er => + er ? fs.chown(abs, uid, gid, er2 => done(er2 && er)) + : done()) + } + + done() + }) + + const tx = this.transform ? this.transform(entry) || entry : entry + if (tx !== entry) { + tx.on('error', er => { + this[ONERROR](er, entry) + fullyDone() + }) + entry.pipe(tx) + } + tx.pipe(stream) + } + + [DIRECTORY] (entry, fullyDone) { + const mode = entry.mode & 0o7777 || this.dmode + this[MKDIR](entry.absolute, mode, er => { + if (er) { + this[ONERROR](er, entry) + fullyDone() + return + } + + let actions = 1 + const done = _ => { + if (--actions === 0) { + fullyDone() + this[UNPEND]() + entry.resume() + } + } + + if (entry.mtime && !this.noMtime) { + actions++ + fs.utimes(entry.absolute, entry.atime || new Date(), entry.mtime, done) + } + + if (this[DOCHOWN](entry)) { + actions++ + fs.chown(entry.absolute, this[UID](entry), this[GID](entry), done) + } + + done() + }) + } + + [UNSUPPORTED] (entry) { + entry.unsupported = true + this.warn('TAR_ENTRY_UNSUPPORTED', + `unsupported entry type: ${entry.type}`, {entry}) + entry.resume() + } + + [SYMLINK] (entry, done) { + this[LINK](entry, entry.linkpath, 'symlink', done) + } + + [HARDLINK] (entry, done) { + const linkpath = normPath(path.resolve(this.cwd, entry.linkpath)) + this[LINK](entry, linkpath, 'link', done) + } + + [PEND] () { + this[PENDING]++ + } + + [UNPEND] () { + this[PENDING]-- + this[MAYBECLOSE]() + } + + [SKIP] (entry) { + this[UNPEND]() + entry.resume() + } + + // Check if we can reuse an existing filesystem entry safely and + // overwrite it, rather than unlinking and recreating + // Windows doesn't report a useful nlink, so we just never reuse entries + [ISREUSABLE] (entry, st) { + return entry.type === 'File' && + !this.unlink && + st.isFile() && + st.nlink <= 1 && + !isWindows + } + + // check if a thing is there, and if so, try to clobber it + [CHECKFS] (entry) { + this[PEND]() + const paths = [entry.path] + if (entry.linkpath) + paths.push(entry.linkpath) + this.reservations.reserve(paths, done => this[CHECKFS2](entry, done)) + } + + [PRUNECACHE] (entry) { + // if we are not creating a directory, and the path is in the dirCache, + // then that means we are about to delete the directory we created + // previously, and it is no longer going to be a directory, and neither + // is any of its children. + // If a symbolic link is encountered, all bets are off. There is no + // reasonable way to sanitize the cache in such a way we will be able to + // avoid having filesystem collisions. If this happens with a non-symlink + // entry, it'll just fail to unpack, but a symlink to a directory, using an + // 8.3 shortname or certain unicode attacks, can evade detection and lead + // to arbitrary writes to anywhere on the system. + if (entry.type === 'SymbolicLink') + dropCache(this.dirCache) + else if (entry.type !== 'Directory') + pruneCache(this.dirCache, entry.absolute) + } + + [CHECKFS2] (entry, fullyDone) { + this[PRUNECACHE](entry) + + const done = er => { + this[PRUNECACHE](entry) + fullyDone(er) + } + + const checkCwd = () => { + this[MKDIR](this.cwd, this.dmode, er => { + if (er) { + this[ONERROR](er, entry) + done() + return + } + this[CHECKED_CWD] = true + start() + }) + } + + const start = () => { + if (entry.absolute !== this.cwd) { + const parent = normPath(path.dirname(entry.absolute)) + if (parent !== this.cwd) { + return this[MKDIR](parent, this.dmode, er => { + if (er) { + this[ONERROR](er, entry) + done() + return + } + afterMakeParent() + }) + } + } + afterMakeParent() + } + + const afterMakeParent = () => { + fs.lstat(entry.absolute, (lstatEr, st) => { + if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { + this[SKIP](entry) + done() + return + } + if (lstatEr || this[ISREUSABLE](entry, st)) + return this[MAKEFS](null, entry, done) + + if (st.isDirectory()) { + if (entry.type === 'Directory') { + const needChmod = !this.noChmod && + entry.mode && + (st.mode & 0o7777) !== entry.mode + const afterChmod = er => this[MAKEFS](er, entry, done) + if (!needChmod) + return afterChmod() + return fs.chmod(entry.absolute, entry.mode, afterChmod) + } + // Not a dir entry, have to remove it. + // NB: the only way to end up with an entry that is the cwd + // itself, in such a way that == does not detect, is a + // tricky windows absolute path with UNC or 8.3 parts (and + // preservePaths:true, or else it will have been stripped). + // In that case, the user has opted out of path protections + // explicitly, so if they blow away the cwd, c'est la vie. + if (entry.absolute !== this.cwd) { + return fs.rmdir(entry.absolute, er => + this[MAKEFS](er, entry, done)) + } + } + + // not a dir, and not reusable + // don't remove if the cwd, we want that error + if (entry.absolute === this.cwd) + return this[MAKEFS](null, entry, done) + + unlinkFile(entry.absolute, er => + this[MAKEFS](er, entry, done)) + }) + } + + if (this[CHECKED_CWD]) + start() + else + checkCwd() + } + + [MAKEFS] (er, entry, done) { + if (er) { + this[ONERROR](er, entry) + done() + return + } + + switch (entry.type) { + case 'File': + case 'OldFile': + case 'ContiguousFile': + return this[FILE](entry, done) + + case 'Link': + return this[HARDLINK](entry, done) + + case 'SymbolicLink': + return this[SYMLINK](entry, done) + + case 'Directory': + case 'GNUDumpDir': + return this[DIRECTORY](entry, done) + } + } + + [LINK] (entry, linkpath, link, done) { + // XXX: get the type ('symlink' or 'junction') for windows + fs[link](linkpath, entry.absolute, er => { + if (er) + this[ONERROR](er, entry) + else { + this[UNPEND]() + entry.resume() + } + done() + }) + } +} + +const callSync = fn => { + try { + return [null, fn()] + } catch (er) { + return [er, null] + } +} +class UnpackSync extends Unpack { + [MAKEFS] (er, entry) { + return super[MAKEFS](er, entry, () => {}) + } + + [CHECKFS] (entry) { + this[PRUNECACHE](entry) + + if (!this[CHECKED_CWD]) { + const er = this[MKDIR](this.cwd, this.dmode) + if (er) + return this[ONERROR](er, entry) + this[CHECKED_CWD] = true + } + + // don't bother to make the parent if the current entry is the cwd, + // we've already checked it. + if (entry.absolute !== this.cwd) { + const parent = normPath(path.dirname(entry.absolute)) + if (parent !== this.cwd) { + const mkParent = this[MKDIR](parent, this.dmode) + if (mkParent) + return this[ONERROR](mkParent, entry) + } + } + + const [lstatEr, st] = callSync(() => fs.lstatSync(entry.absolute)) + if (st && (this.keep || this.newer && st.mtime > entry.mtime)) + return this[SKIP](entry) + + if (lstatEr || this[ISREUSABLE](entry, st)) + return this[MAKEFS](null, entry) + + if (st.isDirectory()) { + if (entry.type === 'Directory') { + const needChmod = !this.noChmod && + entry.mode && + (st.mode & 0o7777) !== entry.mode + const [er] = needChmod ? callSync(() => { + fs.chmodSync(entry.absolute, entry.mode) + }) : [] + return this[MAKEFS](er, entry) + } + // not a dir entry, have to remove it + const [er] = callSync(() => fs.rmdirSync(entry.absolute)) + this[MAKEFS](er, entry) + } + + // not a dir, and not reusable. + // don't remove if it's the cwd, since we want that error. + const [er] = entry.absolute === this.cwd ? [] + : callSync(() => unlinkFileSync(entry.absolute)) + this[MAKEFS](er, entry) + } + + [FILE] (entry, done) { + const mode = entry.mode & 0o7777 || this.fmode + + const oner = er => { + let closeError + try { + fs.closeSync(fd) + } catch (e) { + closeError = e + } + if (er || closeError) + this[ONERROR](er || closeError, entry) + done() + } + + let fd + try { + fd = fs.openSync(entry.absolute, getFlag(entry.size), mode) + } catch (er) { + return oner(er) + } + const tx = this.transform ? this.transform(entry) || entry : entry + if (tx !== entry) { + tx.on('error', er => this[ONERROR](er, entry)) + entry.pipe(tx) + } + + tx.on('data', chunk => { + try { + fs.writeSync(fd, chunk, 0, chunk.length) + } catch (er) { + oner(er) + } + }) + + tx.on('end', _ => { + let er = null + // try both, falling futimes back to utimes + // if either fails, handle the first error + if (entry.mtime && !this.noMtime) { + const atime = entry.atime || new Date() + const mtime = entry.mtime + try { + fs.futimesSync(fd, atime, mtime) + } catch (futimeser) { + try { + fs.utimesSync(entry.absolute, atime, mtime) + } catch (utimeser) { + er = futimeser + } + } + } + + if (this[DOCHOWN](entry)) { + const uid = this[UID](entry) + const gid = this[GID](entry) + + try { + fs.fchownSync(fd, uid, gid) + } catch (fchowner) { + try { + fs.chownSync(entry.absolute, uid, gid) + } catch (chowner) { + er = er || fchowner + } + } + } + + oner(er) + }) + } + + [DIRECTORY] (entry, done) { + const mode = entry.mode & 0o7777 || this.dmode + const er = this[MKDIR](entry.absolute, mode) + if (er) { + this[ONERROR](er, entry) + done() + return + } + if (entry.mtime && !this.noMtime) { + try { + fs.utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime) + } catch (er) {} + } + if (this[DOCHOWN](entry)) { + try { + fs.chownSync(entry.absolute, this[UID](entry), this[GID](entry)) + } catch (er) {} + } + done() + entry.resume() + } + + [MKDIR] (dir, mode) { + try { + return mkdir.sync(normPath(dir), { + uid: this.uid, + gid: this.gid, + processUid: this.processUid, + processGid: this.processGid, + umask: this.processUmask, + preserve: this.preservePaths, + unlink: this.unlink, + cache: this.dirCache, + cwd: this.cwd, + mode: mode, + }) + } catch (er) { + return er + } + } + + [LINK] (entry, linkpath, link, done) { + try { + fs[link + 'Sync'](linkpath, entry.absolute) + done() + entry.resume() + } catch (er) { + return this[ONERROR](er, entry) + } + } +} + +Unpack.Sync = UnpackSync +module.exports = Unpack diff --git a/node_modules/tar/lib/update.js b/node_modules/tar/lib/update.js new file mode 100644 index 0000000..a5784b7 --- /dev/null +++ b/node_modules/tar/lib/update.js @@ -0,0 +1,36 @@ +'use strict' + +// tar -u + +const hlo = require('./high-level-opt.js') +const r = require('./replace.js') +// just call tar.r with the filter and mtimeCache + +module.exports = (opt_, files, cb) => { + const opt = hlo(opt_) + + if (!opt.file) + throw new TypeError('file is required') + + if (opt.gzip) + throw new TypeError('cannot append to compressed archives') + + if (!files || !Array.isArray(files) || !files.length) + throw new TypeError('no files or directories specified') + + files = Array.from(files) + + mtimeFilter(opt) + return r(opt, files, cb) +} + +const mtimeFilter = opt => { + const filter = opt.filter + + if (!opt.mtimeCache) + opt.mtimeCache = new Map() + + opt.filter = filter ? (path, stat) => + filter(path, stat) && !(opt.mtimeCache.get(path) > stat.mtime) + : (path, stat) => !(opt.mtimeCache.get(path) > stat.mtime) +} diff --git a/node_modules/tar/lib/warn-mixin.js b/node_modules/tar/lib/warn-mixin.js new file mode 100644 index 0000000..aeebb53 --- /dev/null +++ b/node_modules/tar/lib/warn-mixin.js @@ -0,0 +1,21 @@ +'use strict' +module.exports = Base => class extends Base { + warn (code, message, data = {}) { + if (this.file) + data.file = this.file + if (this.cwd) + data.cwd = this.cwd + data.code = message instanceof Error && message.code || code + data.tarCode = code + if (!this.strict && data.recoverable !== false) { + if (message instanceof Error) { + data = Object.assign(message, data) + message = message.message + } + this.emit('warn', data.tarCode, message, data) + } else if (message instanceof Error) + this.emit('error', Object.assign(message, data)) + else + this.emit('error', Object.assign(new Error(`${code}: ${message}`), data)) + } +} diff --git a/node_modules/tar/lib/winchars.js b/node_modules/tar/lib/winchars.js new file mode 100644 index 0000000..ebcab4a --- /dev/null +++ b/node_modules/tar/lib/winchars.js @@ -0,0 +1,23 @@ +'use strict' + +// When writing files on Windows, translate the characters to their +// 0xf000 higher-encoded versions. + +const raw = [ + '|', + '<', + '>', + '?', + ':', +] + +const win = raw.map(char => + String.fromCharCode(0xf000 + char.charCodeAt(0))) + +const toWin = new Map(raw.map((char, i) => [char, win[i]])) +const toRaw = new Map(win.map((char, i) => [char, raw[i]])) + +module.exports = { + encode: s => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s), + decode: s => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s), +} diff --git a/node_modules/tar/lib/write-entry.js b/node_modules/tar/lib/write-entry.js new file mode 100644 index 0000000..3702f2a --- /dev/null +++ b/node_modules/tar/lib/write-entry.js @@ -0,0 +1,525 @@ +'use strict' +const MiniPass = require('minipass') +const Pax = require('./pax.js') +const Header = require('./header.js') +const fs = require('fs') +const path = require('path') +const normPath = require('./normalize-windows-path.js') +const stripSlash = require('./strip-trailing-slashes.js') + +const prefixPath = (path, prefix) => { + if (!prefix) + return normPath(path) + path = normPath(path).replace(/^\.(\/|$)/, '') + return stripSlash(prefix) + '/' + path +} + +const maxReadSize = 16 * 1024 * 1024 +const PROCESS = Symbol('process') +const FILE = Symbol('file') +const DIRECTORY = Symbol('directory') +const SYMLINK = Symbol('symlink') +const HARDLINK = Symbol('hardlink') +const HEADER = Symbol('header') +const READ = Symbol('read') +const LSTAT = Symbol('lstat') +const ONLSTAT = Symbol('onlstat') +const ONREAD = Symbol('onread') +const ONREADLINK = Symbol('onreadlink') +const OPENFILE = Symbol('openfile') +const ONOPENFILE = Symbol('onopenfile') +const CLOSE = Symbol('close') +const MODE = Symbol('mode') +const AWAITDRAIN = Symbol('awaitDrain') +const ONDRAIN = Symbol('ondrain') +const PREFIX = Symbol('prefix') +const HAD_ERROR = Symbol('hadError') +const warner = require('./warn-mixin.js') +const winchars = require('./winchars.js') +const stripAbsolutePath = require('./strip-absolute-path.js') + +const modeFix = require('./mode-fix.js') + +const WriteEntry = warner(class WriteEntry extends MiniPass { + constructor (p, opt) { + opt = opt || {} + super(opt) + if (typeof p !== 'string') + throw new TypeError('path is required') + this.path = normPath(p) + // suppress atime, ctime, uid, gid, uname, gname + this.portable = !!opt.portable + // until node has builtin pwnam functions, this'll have to do + this.myuid = process.getuid && process.getuid() || 0 + this.myuser = process.env.USER || '' + this.maxReadSize = opt.maxReadSize || maxReadSize + this.linkCache = opt.linkCache || new Map() + this.statCache = opt.statCache || new Map() + this.preservePaths = !!opt.preservePaths + this.cwd = normPath(opt.cwd || process.cwd()) + this.strict = !!opt.strict + this.noPax = !!opt.noPax + this.noMtime = !!opt.noMtime + this.mtime = opt.mtime || null + this.prefix = opt.prefix ? normPath(opt.prefix) : null + + this.fd = null + this.blockLen = null + this.blockRemain = null + this.buf = null + this.offset = null + this.length = null + this.pos = null + this.remain = null + + if (typeof opt.onwarn === 'function') + this.on('warn', opt.onwarn) + + let pathWarn = false + if (!this.preservePaths) { + const [root, stripped] = stripAbsolutePath(this.path) + if (root) { + this.path = stripped + pathWarn = root + } + } + + this.win32 = !!opt.win32 || process.platform === 'win32' + if (this.win32) { + // force the \ to / normalization, since we might not *actually* + // be on windows, but want \ to be considered a path separator. + this.path = winchars.decode(this.path.replace(/\\/g, '/')) + p = p.replace(/\\/g, '/') + } + + this.absolute = normPath(opt.absolute || path.resolve(this.cwd, p)) + + if (this.path === '') + this.path = './' + + if (pathWarn) { + this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { + entry: this, + path: pathWarn + this.path, + }) + } + + if (this.statCache.has(this.absolute)) + this[ONLSTAT](this.statCache.get(this.absolute)) + else + this[LSTAT]() + } + + emit (ev, ...data) { + if (ev === 'error') + this[HAD_ERROR] = true + return super.emit(ev, ...data) + } + + [LSTAT] () { + fs.lstat(this.absolute, (er, stat) => { + if (er) + return this.emit('error', er) + this[ONLSTAT](stat) + }) + } + + [ONLSTAT] (stat) { + this.statCache.set(this.absolute, stat) + this.stat = stat + if (!stat.isFile()) + stat.size = 0 + this.type = getType(stat) + this.emit('stat', stat) + this[PROCESS]() + } + + [PROCESS] () { + switch (this.type) { + case 'File': return this[FILE]() + case 'Directory': return this[DIRECTORY]() + case 'SymbolicLink': return this[SYMLINK]() + // unsupported types are ignored. + default: return this.end() + } + } + + [MODE] (mode) { + return modeFix(mode, this.type === 'Directory', this.portable) + } + + [PREFIX] (path) { + return prefixPath(path, this.prefix) + } + + [HEADER] () { + if (this.type === 'Directory' && this.portable) + this.noMtime = true + + this.header = new Header({ + path: this[PREFIX](this.path), + // only apply the prefix to hard links. + linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) + : this.linkpath, + // only the permissions and setuid/setgid/sticky bitflags + // not the higher-order bits that specify file type + mode: this[MODE](this.stat.mode), + uid: this.portable ? null : this.stat.uid, + gid: this.portable ? null : this.stat.gid, + size: this.stat.size, + mtime: this.noMtime ? null : this.mtime || this.stat.mtime, + type: this.type, + uname: this.portable ? null : + this.stat.uid === this.myuid ? this.myuser : '', + atime: this.portable ? null : this.stat.atime, + ctime: this.portable ? null : this.stat.ctime, + }) + + if (this.header.encode() && !this.noPax) { + super.write(new Pax({ + atime: this.portable ? null : this.header.atime, + ctime: this.portable ? null : this.header.ctime, + gid: this.portable ? null : this.header.gid, + mtime: this.noMtime ? null : this.mtime || this.header.mtime, + path: this[PREFIX](this.path), + linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) + : this.linkpath, + size: this.header.size, + uid: this.portable ? null : this.header.uid, + uname: this.portable ? null : this.header.uname, + dev: this.portable ? null : this.stat.dev, + ino: this.portable ? null : this.stat.ino, + nlink: this.portable ? null : this.stat.nlink, + }).encode()) + } + super.write(this.header.block) + } + + [DIRECTORY] () { + if (this.path.substr(-1) !== '/') + this.path += '/' + this.stat.size = 0 + this[HEADER]() + this.end() + } + + [SYMLINK] () { + fs.readlink(this.absolute, (er, linkpath) => { + if (er) + return this.emit('error', er) + this[ONREADLINK](linkpath) + }) + } + + [ONREADLINK] (linkpath) { + this.linkpath = normPath(linkpath) + this[HEADER]() + this.end() + } + + [HARDLINK] (linkpath) { + this.type = 'Link' + this.linkpath = normPath(path.relative(this.cwd, linkpath)) + this.stat.size = 0 + this[HEADER]() + this.end() + } + + [FILE] () { + if (this.stat.nlink > 1) { + const linkKey = this.stat.dev + ':' + this.stat.ino + if (this.linkCache.has(linkKey)) { + const linkpath = this.linkCache.get(linkKey) + if (linkpath.indexOf(this.cwd) === 0) + return this[HARDLINK](linkpath) + } + this.linkCache.set(linkKey, this.absolute) + } + + this[HEADER]() + if (this.stat.size === 0) + return this.end() + + this[OPENFILE]() + } + + [OPENFILE] () { + fs.open(this.absolute, 'r', (er, fd) => { + if (er) + return this.emit('error', er) + this[ONOPENFILE](fd) + }) + } + + [ONOPENFILE] (fd) { + this.fd = fd + if (this[HAD_ERROR]) + return this[CLOSE]() + + this.blockLen = 512 * Math.ceil(this.stat.size / 512) + this.blockRemain = this.blockLen + const bufLen = Math.min(this.blockLen, this.maxReadSize) + this.buf = Buffer.allocUnsafe(bufLen) + this.offset = 0 + this.pos = 0 + this.remain = this.stat.size + this.length = this.buf.length + this[READ]() + } + + [READ] () { + const { fd, buf, offset, length, pos } = this + fs.read(fd, buf, offset, length, pos, (er, bytesRead) => { + if (er) { + // ignoring the error from close(2) is a bad practice, but at + // this point we already have an error, don't need another one + return this[CLOSE](() => this.emit('error', er)) + } + this[ONREAD](bytesRead) + }) + } + + [CLOSE] (cb) { + fs.close(this.fd, cb) + } + + [ONREAD] (bytesRead) { + if (bytesRead <= 0 && this.remain > 0) { + const er = new Error('encountered unexpected EOF') + er.path = this.absolute + er.syscall = 'read' + er.code = 'EOF' + return this[CLOSE](() => this.emit('error', er)) + } + + if (bytesRead > this.remain) { + const er = new Error('did not encounter expected EOF') + er.path = this.absolute + er.syscall = 'read' + er.code = 'EOF' + return this[CLOSE](() => this.emit('error', er)) + } + + // null out the rest of the buffer, if we could fit the block padding + // at the end of this loop, we've incremented bytesRead and this.remain + // to be incremented up to the blockRemain level, as if we had expected + // to get a null-padded file, and read it until the end. then we will + // decrement both remain and blockRemain by bytesRead, and know that we + // reached the expected EOF, without any null buffer to append. + if (bytesRead === this.remain) { + for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) { + this.buf[i + this.offset] = 0 + bytesRead++ + this.remain++ + } + } + + const writeBuf = this.offset === 0 && bytesRead === this.buf.length ? + this.buf : this.buf.slice(this.offset, this.offset + bytesRead) + + const flushed = this.write(writeBuf) + if (!flushed) + this[AWAITDRAIN](() => this[ONDRAIN]()) + else + this[ONDRAIN]() + } + + [AWAITDRAIN] (cb) { + this.once('drain', cb) + } + + write (writeBuf) { + if (this.blockRemain < writeBuf.length) { + const er = new Error('writing more data than expected') + er.path = this.absolute + return this.emit('error', er) + } + this.remain -= writeBuf.length + this.blockRemain -= writeBuf.length + this.pos += writeBuf.length + this.offset += writeBuf.length + return super.write(writeBuf) + } + + [ONDRAIN] () { + if (!this.remain) { + if (this.blockRemain) + super.write(Buffer.alloc(this.blockRemain)) + return this[CLOSE](er => er ? this.emit('error', er) : this.end()) + } + + if (this.offset >= this.length) { + // if we only have a smaller bit left to read, alloc a smaller buffer + // otherwise, keep it the same length it was before. + this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length)) + this.offset = 0 + } + this.length = this.buf.length - this.offset + this[READ]() + } +}) + +class WriteEntrySync extends WriteEntry { + [LSTAT] () { + this[ONLSTAT](fs.lstatSync(this.absolute)) + } + + [SYMLINK] () { + this[ONREADLINK](fs.readlinkSync(this.absolute)) + } + + [OPENFILE] () { + this[ONOPENFILE](fs.openSync(this.absolute, 'r')) + } + + [READ] () { + let threw = true + try { + const { fd, buf, offset, length, pos } = this + const bytesRead = fs.readSync(fd, buf, offset, length, pos) + this[ONREAD](bytesRead) + threw = false + } finally { + // ignoring the error from close(2) is a bad practice, but at + // this point we already have an error, don't need another one + if (threw) { + try { + this[CLOSE](() => {}) + } catch (er) {} + } + } + } + + [AWAITDRAIN] (cb) { + cb() + } + + [CLOSE] (cb) { + fs.closeSync(this.fd) + cb() + } +} + +const WriteEntryTar = warner(class WriteEntryTar extends MiniPass { + constructor (readEntry, opt) { + opt = opt || {} + super(opt) + this.preservePaths = !!opt.preservePaths + this.portable = !!opt.portable + this.strict = !!opt.strict + this.noPax = !!opt.noPax + this.noMtime = !!opt.noMtime + + this.readEntry = readEntry + this.type = readEntry.type + if (this.type === 'Directory' && this.portable) + this.noMtime = true + + this.prefix = opt.prefix || null + + this.path = normPath(readEntry.path) + this.mode = this[MODE](readEntry.mode) + this.uid = this.portable ? null : readEntry.uid + this.gid = this.portable ? null : readEntry.gid + this.uname = this.portable ? null : readEntry.uname + this.gname = this.portable ? null : readEntry.gname + this.size = readEntry.size + this.mtime = this.noMtime ? null : opt.mtime || readEntry.mtime + this.atime = this.portable ? null : readEntry.atime + this.ctime = this.portable ? null : readEntry.ctime + this.linkpath = normPath(readEntry.linkpath) + + if (typeof opt.onwarn === 'function') + this.on('warn', opt.onwarn) + + let pathWarn = false + if (!this.preservePaths) { + const [root, stripped] = stripAbsolutePath(this.path) + if (root) { + this.path = stripped + pathWarn = root + } + } + + this.remain = readEntry.size + this.blockRemain = readEntry.startBlockSize + + this.header = new Header({ + path: this[PREFIX](this.path), + linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) + : this.linkpath, + // only the permissions and setuid/setgid/sticky bitflags + // not the higher-order bits that specify file type + mode: this.mode, + uid: this.portable ? null : this.uid, + gid: this.portable ? null : this.gid, + size: this.size, + mtime: this.noMtime ? null : this.mtime, + type: this.type, + uname: this.portable ? null : this.uname, + atime: this.portable ? null : this.atime, + ctime: this.portable ? null : this.ctime, + }) + + if (pathWarn) { + this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { + entry: this, + path: pathWarn + this.path, + }) + } + + if (this.header.encode() && !this.noPax) { + super.write(new Pax({ + atime: this.portable ? null : this.atime, + ctime: this.portable ? null : this.ctime, + gid: this.portable ? null : this.gid, + mtime: this.noMtime ? null : this.mtime, + path: this[PREFIX](this.path), + linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) + : this.linkpath, + size: this.size, + uid: this.portable ? null : this.uid, + uname: this.portable ? null : this.uname, + dev: this.portable ? null : this.readEntry.dev, + ino: this.portable ? null : this.readEntry.ino, + nlink: this.portable ? null : this.readEntry.nlink, + }).encode()) + } + + super.write(this.header.block) + readEntry.pipe(this) + } + + [PREFIX] (path) { + return prefixPath(path, this.prefix) + } + + [MODE] (mode) { + return modeFix(mode, this.type === 'Directory', this.portable) + } + + write (data) { + const writeLen = data.length + if (writeLen > this.blockRemain) + throw new Error('writing more to entry than is appropriate') + this.blockRemain -= writeLen + return super.write(data) + } + + end () { + if (this.blockRemain) + super.write(Buffer.alloc(this.blockRemain)) + return super.end() + } +}) + +WriteEntry.Sync = WriteEntrySync +WriteEntry.Tar = WriteEntryTar + +const getType = stat => + stat.isFile() ? 'File' + : stat.isDirectory() ? 'Directory' + : stat.isSymbolicLink() ? 'SymbolicLink' + : 'Unsupported' + +module.exports = WriteEntry diff --git a/node_modules/tar/package.json b/node_modules/tar/package.json new file mode 100644 index 0000000..9f9977a --- /dev/null +++ b/node_modules/tar/package.json @@ -0,0 +1,59 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "name": "tar", + "description": "tar for node", + "version": "6.1.11", + "repository": { + "type": "git", + "url": "https://github.com/npm/node-tar.git" + }, + "scripts": { + "test:posix": "tap", + "test:win32": "tap --lines=98 --branches=98 --statements=98 --functions=98", + "test": "node test/fixtures/test.js", + "posttest": "npm run lint", + "eslint": "eslint", + "lint": "npm run eslint -- test lib", + "lintfix": "npm run lint -- --fix", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "genparse": "node scripts/generate-parse-fixtures.js", + "bench": "for i in benchmarks/*/*.js; do echo $i; for j in {1..5}; do node $i || break; done; done" + }, + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^3.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "devDependencies": { + "chmodr": "^1.2.0", + "end-of-stream": "^1.4.3", + "eslint": "^7.17.0", + "eslint-plugin-import": "^2.22.1", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^4.2.1", + "eslint-plugin-standard": "^5.0.0", + "events-to-array": "^1.1.2", + "mutate-fs": "^2.1.1", + "rimraf": "^2.7.1", + "tap": "^15.0.9", + "tar-fs": "^1.16.3", + "tar-stream": "^1.6.2" + }, + "license": "ISC", + "engines": { + "node": ">= 10" + }, + "files": [ + "index.js", + "lib/*.js" + ], + "tap": { + "coverage-map": "map.js", + "check-coverage": true + } +} diff --git a/node_modules/toidentifier/LICENSE b/node_modules/toidentifier/LICENSE new file mode 100644 index 0000000..de22d15 --- /dev/null +++ b/node_modules/toidentifier/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Douglas Christopher Wilson + +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/toidentifier/README.md b/node_modules/toidentifier/README.md new file mode 100644 index 0000000..7c8794e --- /dev/null +++ b/node_modules/toidentifier/README.md @@ -0,0 +1,61 @@ +# toidentifier + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][codecov-image]][codecov-url] + +> Convert a string of words to a JavaScript identifier + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install toidentifier +``` + +## Example + +```js +var toIdentifier = require('toidentifier') + +console.log(toIdentifier('Bad Request')) +// => "BadRequest" +``` + +## API + +This CommonJS module exports a single default function: `toIdentifier`. + +### toIdentifier(string) + +Given a string as the argument, it will be transformed according to +the following rules and the new string will be returned: + +1. Split into words separated by space characters (`0x20`). +2. Upper case the first character of each word. +3. Join the words together with no separator. +4. Remove all non-word (`[0-9a-z_]`) characters. + +## License + +[MIT](LICENSE) + +[codecov-image]: https://img.shields.io/codecov/c/github/component/toidentifier.svg +[codecov-url]: https://codecov.io/gh/component/toidentifier +[downloads-image]: https://img.shields.io/npm/dm/toidentifier.svg +[downloads-url]: https://npmjs.org/package/toidentifier +[npm-image]: https://img.shields.io/npm/v/toidentifier.svg +[npm-url]: https://npmjs.org/package/toidentifier +[travis-image]: https://img.shields.io/travis/component/toidentifier/master.svg +[travis-url]: https://travis-ci.org/component/toidentifier + + +## + +[npm]: https://www.npmjs.com/ + +[yarn]: https://yarnpkg.com/ diff --git a/node_modules/toidentifier/index.js b/node_modules/toidentifier/index.js new file mode 100644 index 0000000..bba5411 --- /dev/null +++ b/node_modules/toidentifier/index.js @@ -0,0 +1,30 @@ +/*! + * toidentifier + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +module.exports = toIdentifier + +/** + * Trasform the given string into a JavaScript identifier + * + * @param {string} str + * @returns {string} + * @public + */ + +function toIdentifier (str) { + return str + .split(' ') + .map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }) + .join('') + .replace(/[^ _0-9a-z]/gi, '') +} diff --git a/node_modules/toidentifier/package.json b/node_modules/toidentifier/package.json new file mode 100644 index 0000000..3f78165 --- /dev/null +++ b/node_modules/toidentifier/package.json @@ -0,0 +1,34 @@ +{ + "name": "toidentifier", + "description": "Convert a string of words to a JavaScript identifier", + "version": "1.0.0", + "author": "Douglas Christopher Wilson ", + "contributors": [ + "Douglas Christopher Wilson ", + "Nick Baugh (http://niftylettuce.com/)" + ], + "repository": "component/toidentifier", + "devDependencies": { + "eslint": "4.19.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.11.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.7.0", + "eslint-plugin-standard": "3.1.0", + "mocha": "1.21.5", + "nyc": "11.8.0" + }, + "engines": { + "node": ">=0.6" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/tr46/LICENSE.md b/node_modules/tr46/LICENSE.md new file mode 100644 index 0000000..e90f20a --- /dev/null +++ b/node_modules/tr46/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Sebastian Mayr + +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/tr46/README.md b/node_modules/tr46/README.md new file mode 100644 index 0000000..4cb702c --- /dev/null +++ b/node_modules/tr46/README.md @@ -0,0 +1,72 @@ +# tr46 + +An JavaScript implementation of [Unicode Technical Standard #46: Unicode IDNA Compatibility Processing](https://unicode.org/reports/tr46/). + + +## Installation + +[Node.js](http://nodejs.org) ≥ 8 is required. To install, type this at the command line: +```shell +npm install tr46 +# or +yarn add tr46 +``` + + +## API + +### `toASCII(domainName[, options])` + +Converts a string of Unicode symbols to a case-folded Punycode string of ASCII symbols. + +Available options: +* [`checkBidi`](#checkBidi) +* [`checkHyphens`](#checkHyphens) +* [`checkJoiners`](#checkJoiners) +* [`processingOption`](#processingOption) +* [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) +* [`verifyDNSLength`](#verifyDNSLength) + +### `toUnicode(domainName[, options])` + +Converts a case-folded Punycode string of ASCII symbols to a string of Unicode symbols. + +Available options: +* [`checkBidi`](#checkBidi) +* [`checkHyphens`](#checkHyphens) +* [`checkJoiners`](#checkJoiners) +* [`processingOption`](#processingOption) +* [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) + + +## Options + +### `checkBidi` +Type: `Boolean` +Default value: `false` +When set to `true`, any bi-directional text within the input will be checked for validation. + +### `checkHyphens` +Type: `Boolean` +Default value: `false` +When set to `true`, the positions of any hyphen characters within the input will be checked for validation. + +### `checkJoiners` +Type: `Boolean` +Default value: `false` +When set to `true`, any word joiner characters within the input will be checked for validation. + +### `processingOption` +Type: `String` +Default value: `"nontransitional"` +When set to `"transitional"`, symbols within the input will be validated according to the older IDNA2003 protocol. When set to `"nontransitional"`, the current IDNA2008 protocol will be used. + +### `useSTD3ASCIIRules` +Type: `Boolean` +Default value: `false` +When set to `true`, input will be validated according to [STD3 Rules](http://unicode.org/reports/tr46/#STD3_Rules). + +### `verifyDNSLength` +Type: `Boolean` +Default value: `false` +When set to `true`, the length of each DNS label within the input will be checked for validation. diff --git a/node_modules/tr46/index.js b/node_modules/tr46/index.js new file mode 100644 index 0000000..9ba36d8 --- /dev/null +++ b/node_modules/tr46/index.js @@ -0,0 +1,297 @@ +"use strict"; + +const punycode = require("punycode"); +const regexes = require("./lib/regexes.js"); +const mappingTable = require("./lib/mappingTable.json"); +const { STATUS_MAPPING } = require("./lib/statusMapping.js"); + +function containsNonASCII(str) { + return /[^\x00-\x7F]/.test(str); +} + +function findStatus(val, { useSTD3ASCIIRules }) { + let start = 0; + let end = mappingTable.length - 1; + + while (start <= end) { + const mid = Math.floor((start + end) / 2); + + const target = mappingTable[mid]; + const min = Array.isArray(target[0]) ? target[0][0] : target[0]; + const max = Array.isArray(target[0]) ? target[0][1] : target[0]; + + if (min <= val && max >= val) { + if (useSTD3ASCIIRules && + (target[1] === STATUS_MAPPING.disallowed_STD3_valid || target[1] === STATUS_MAPPING.disallowed_STD3_mapped)) { + return [STATUS_MAPPING.disallowed, ...target.slice(2)]; + } else if (target[1] === STATUS_MAPPING.disallowed_STD3_valid) { + return [STATUS_MAPPING.valid, ...target.slice(2)]; + } else if (target[1] === STATUS_MAPPING.disallowed_STD3_mapped) { + return [STATUS_MAPPING.mapped, ...target.slice(2)]; + } + + return target.slice(1); + } else if (min > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return null; +} + +function mapChars(domainName, { useSTD3ASCIIRules, processingOption }) { + let hasError = false; + let processed = ""; + + for (const ch of domainName) { + const [status, mapping] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); + + switch (status) { + case STATUS_MAPPING.disallowed: + hasError = true; + processed += ch; + break; + case STATUS_MAPPING.ignored: + break; + case STATUS_MAPPING.mapped: + processed += mapping; + break; + case STATUS_MAPPING.deviation: + if (processingOption === "transitional") { + processed += mapping; + } else { + processed += ch; + } + break; + case STATUS_MAPPING.valid: + processed += ch; + break; + } + } + + return { + string: processed, + error: hasError + }; +} + +function validateLabel(label, { checkHyphens, checkBidi, checkJoiners, processingOption, useSTD3ASCIIRules }) { + if (label.normalize("NFC") !== label) { + return false; + } + + const codePoints = Array.from(label); + + if (checkHyphens) { + if ((codePoints[2] === "-" && codePoints[3] === "-") || + (label.startsWith("-") || label.endsWith("-"))) { + return false; + } + } + + if (label.includes(".") || + (codePoints.length > 0 && regexes.combiningMarks.test(codePoints[0]))) { + return false; + } + + for (const ch of codePoints) { + const [status] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); + if ((processingOption === "transitional" && status !== STATUS_MAPPING.valid) || + (processingOption === "nontransitional" && + status !== STATUS_MAPPING.valid && status !== STATUS_MAPPING.deviation)) { + return false; + } + } + + // https://tools.ietf.org/html/rfc5892#appendix-A + if (checkJoiners) { + let last = 0; + for (const [i, ch] of codePoints.entries()) { + if (ch === "\u200C" || ch === "\u200D") { + if (i > 0) { + if (regexes.combiningClassVirama.test(codePoints[i - 1])) { + continue; + } + if (ch === "\u200C") { + // TODO: make this more efficient + const next = codePoints.indexOf("\u200C", i + 1); + const test = next < 0 ? codePoints.slice(last) : codePoints.slice(last, next); + if (regexes.validZWNJ.test(test.join(""))) { + last = i + 1; + continue; + } + } + } + return false; + } + } + } + + // https://tools.ietf.org/html/rfc5893#section-2 + if (checkBidi) { + let rtl; + + // 1 + if (regexes.bidiS1LTR.test(codePoints[0])) { + rtl = false; + } else if (regexes.bidiS1RTL.test(codePoints[0])) { + rtl = true; + } else { + return false; + } + + if (rtl) { + // 2-4 + if (!regexes.bidiS2.test(label) || + !regexes.bidiS3.test(label) || + (regexes.bidiS4EN.test(label) && regexes.bidiS4AN.test(label))) { + return false; + } + } else if (!regexes.bidiS5.test(label) || + !regexes.bidiS6.test(label)) { // 5-6 + return false; + } + } + + return true; +} + +function isBidiDomain(labels) { + const domain = labels.map(label => { + if (label.startsWith("xn--")) { + try { + return punycode.decode(label.substring(4)); + } catch (err) { + return ""; + } + } + return label; + }).join("."); + return regexes.bidiDomain.test(domain); +} + +function processing(domainName, options) { + const { processingOption } = options; + + // 1. Map. + let { string, error } = mapChars(domainName, options); + + // 2. Normalize. + string = string.normalize("NFC"); + + // 3. Break. + const labels = string.split("."); + const isBidi = isBidiDomain(labels); + + // 4. Convert/Validate. + for (const [i, origLabel] of labels.entries()) { + let label = origLabel; + let curProcessing = processingOption; + if (label.startsWith("xn--")) { + try { + label = punycode.decode(label.substring(4)); + labels[i] = label; + } catch (err) { + error = true; + continue; + } + curProcessing = "nontransitional"; + } + + // No need to validate if we already know there is an error. + if (error) { + continue; + } + const validation = validateLabel(label, Object.assign({}, options, { + processingOption: curProcessing, + checkBidi: options.checkBidi && isBidi + })); + if (!validation) { + error = true; + } + } + + return { + string: labels.join("."), + error + }; +} + +function toASCII(domainName, { + checkHyphens = false, + checkBidi = false, + checkJoiners = false, + useSTD3ASCIIRules = false, + processingOption = "nontransitional", + verifyDNSLength = false +} = {}) { + if (processingOption !== "transitional" && processingOption !== "nontransitional") { + throw new RangeError("processingOption must be either transitional or nontransitional"); + } + + const result = processing(domainName, { + processingOption, + checkHyphens, + checkBidi, + checkJoiners, + useSTD3ASCIIRules + }); + let labels = result.string.split("."); + labels = labels.map(l => { + if (containsNonASCII(l)) { + try { + return "xn--" + punycode.encode(l); + } catch (e) { + result.error = true; + } + } + return l; + }); + + if (verifyDNSLength) { + const total = labels.join(".").length; + if (total > 253 || total === 0) { + result.error = true; + } + + for (let i = 0; i < labels.length; ++i) { + if (labels[i].length > 63 || labels[i].length === 0) { + result.error = true; + break; + } + } + } + + if (result.error) { + return null; + } + return labels.join("."); +} + +function toUnicode(domainName, { + checkHyphens = false, + checkBidi = false, + checkJoiners = false, + useSTD3ASCIIRules = false, + processingOption = "nontransitional" +} = {}) { + const result = processing(domainName, { + processingOption, + checkHyphens, + checkBidi, + checkJoiners, + useSTD3ASCIIRules + }); + + return { + domain: result.string, + error: result.error + }; +} + +module.exports = { + toASCII, + toUnicode +}; diff --git a/node_modules/tr46/lib/mappingTable.json b/node_modules/tr46/lib/mappingTable.json new file mode 100644 index 0000000..8ca8081 --- /dev/null +++ b/node_modules/tr46/lib/mappingTable.json @@ -0,0 +1 @@ +[[[0,44],4],[[45,46],2],[47,4],[[48,57],2],[[58,64],4],[65,1,"a"],[66,1,"b"],[67,1,"c"],[68,1,"d"],[69,1,"e"],[70,1,"f"],[71,1,"g"],[72,1,"h"],[73,1,"i"],[74,1,"j"],[75,1,"k"],[76,1,"l"],[77,1,"m"],[78,1,"n"],[79,1,"o"],[80,1,"p"],[81,1,"q"],[82,1,"r"],[83,1,"s"],[84,1,"t"],[85,1,"u"],[86,1,"v"],[87,1,"w"],[88,1,"x"],[89,1,"y"],[90,1,"z"],[[91,96],4],[[97,122],2],[[123,127],4],[[128,159],3],[160,5," "],[[161,167],2],[168,5," ̈"],[169,2],[170,1,"a"],[[171,172],2],[173,7],[174,2],[175,5," ̄"],[[176,177],2],[178,1,"2"],[179,1,"3"],[180,5," ́"],[181,1,"μ"],[182,2],[183,2],[184,5," ̧"],[185,1,"1"],[186,1,"o"],[187,2],[188,1,"1⁄4"],[189,1,"1⁄2"],[190,1,"3⁄4"],[191,2],[192,1,"à"],[193,1,"á"],[194,1,"â"],[195,1,"ã"],[196,1,"ä"],[197,1,"å"],[198,1,"æ"],[199,1,"ç"],[200,1,"è"],[201,1,"é"],[202,1,"ê"],[203,1,"ë"],[204,1,"ì"],[205,1,"í"],[206,1,"î"],[207,1,"ï"],[208,1,"ð"],[209,1,"ñ"],[210,1,"ò"],[211,1,"ó"],[212,1,"ô"],[213,1,"õ"],[214,1,"ö"],[215,2],[216,1,"ø"],[217,1,"ù"],[218,1,"ú"],[219,1,"û"],[220,1,"ü"],[221,1,"ý"],[222,1,"þ"],[223,6,"ss"],[[224,246],2],[247,2],[[248,255],2],[256,1,"ā"],[257,2],[258,1,"ă"],[259,2],[260,1,"ą"],[261,2],[262,1,"ć"],[263,2],[264,1,"ĉ"],[265,2],[266,1,"ċ"],[267,2],[268,1,"č"],[269,2],[270,1,"ď"],[271,2],[272,1,"đ"],[273,2],[274,1,"ē"],[275,2],[276,1,"ĕ"],[277,2],[278,1,"ė"],[279,2],[280,1,"ę"],[281,2],[282,1,"ě"],[283,2],[284,1,"ĝ"],[285,2],[286,1,"ğ"],[287,2],[288,1,"ġ"],[289,2],[290,1,"ģ"],[291,2],[292,1,"ĥ"],[293,2],[294,1,"ħ"],[295,2],[296,1,"ĩ"],[297,2],[298,1,"ī"],[299,2],[300,1,"ĭ"],[301,2],[302,1,"į"],[303,2],[304,1,"i̇"],[305,2],[[306,307],1,"ij"],[308,1,"ĵ"],[309,2],[310,1,"ķ"],[[311,312],2],[313,1,"ĺ"],[314,2],[315,1,"ļ"],[316,2],[317,1,"ľ"],[318,2],[[319,320],1,"l·"],[321,1,"ł"],[322,2],[323,1,"ń"],[324,2],[325,1,"ņ"],[326,2],[327,1,"ň"],[328,2],[329,1,"ʼn"],[330,1,"ŋ"],[331,2],[332,1,"ō"],[333,2],[334,1,"ŏ"],[335,2],[336,1,"ő"],[337,2],[338,1,"œ"],[339,2],[340,1,"ŕ"],[341,2],[342,1,"ŗ"],[343,2],[344,1,"ř"],[345,2],[346,1,"ś"],[347,2],[348,1,"ŝ"],[349,2],[350,1,"ş"],[351,2],[352,1,"š"],[353,2],[354,1,"ţ"],[355,2],[356,1,"ť"],[357,2],[358,1,"ŧ"],[359,2],[360,1,"ũ"],[361,2],[362,1,"ū"],[363,2],[364,1,"ŭ"],[365,2],[366,1,"ů"],[367,2],[368,1,"ű"],[369,2],[370,1,"ų"],[371,2],[372,1,"ŵ"],[373,2],[374,1,"ŷ"],[375,2],[376,1,"ÿ"],[377,1,"ź"],[378,2],[379,1,"ż"],[380,2],[381,1,"ž"],[382,2],[383,1,"s"],[384,2],[385,1,"ɓ"],[386,1,"ƃ"],[387,2],[388,1,"ƅ"],[389,2],[390,1,"ɔ"],[391,1,"ƈ"],[392,2],[393,1,"ɖ"],[394,1,"ɗ"],[395,1,"ƌ"],[[396,397],2],[398,1,"ǝ"],[399,1,"ə"],[400,1,"ɛ"],[401,1,"ƒ"],[402,2],[403,1,"ɠ"],[404,1,"ɣ"],[405,2],[406,1,"ɩ"],[407,1,"ɨ"],[408,1,"ƙ"],[[409,411],2],[412,1,"ɯ"],[413,1,"ɲ"],[414,2],[415,1,"ɵ"],[416,1,"ơ"],[417,2],[418,1,"ƣ"],[419,2],[420,1,"ƥ"],[421,2],[422,1,"ʀ"],[423,1,"ƨ"],[424,2],[425,1,"ʃ"],[[426,427],2],[428,1,"ƭ"],[429,2],[430,1,"ʈ"],[431,1,"ư"],[432,2],[433,1,"ʊ"],[434,1,"ʋ"],[435,1,"ƴ"],[436,2],[437,1,"ƶ"],[438,2],[439,1,"ʒ"],[440,1,"ƹ"],[[441,443],2],[444,1,"ƽ"],[[445,451],2],[[452,454],1,"dž"],[[455,457],1,"lj"],[[458,460],1,"nj"],[461,1,"ǎ"],[462,2],[463,1,"ǐ"],[464,2],[465,1,"ǒ"],[466,2],[467,1,"ǔ"],[468,2],[469,1,"ǖ"],[470,2],[471,1,"ǘ"],[472,2],[473,1,"ǚ"],[474,2],[475,1,"ǜ"],[[476,477],2],[478,1,"ǟ"],[479,2],[480,1,"ǡ"],[481,2],[482,1,"ǣ"],[483,2],[484,1,"ǥ"],[485,2],[486,1,"ǧ"],[487,2],[488,1,"ǩ"],[489,2],[490,1,"ǫ"],[491,2],[492,1,"ǭ"],[493,2],[494,1,"ǯ"],[[495,496],2],[[497,499],1,"dz"],[500,1,"ǵ"],[501,2],[502,1,"ƕ"],[503,1,"ƿ"],[504,1,"ǹ"],[505,2],[506,1,"ǻ"],[507,2],[508,1,"ǽ"],[509,2],[510,1,"ǿ"],[511,2],[512,1,"ȁ"],[513,2],[514,1,"ȃ"],[515,2],[516,1,"ȅ"],[517,2],[518,1,"ȇ"],[519,2],[520,1,"ȉ"],[521,2],[522,1,"ȋ"],[523,2],[524,1,"ȍ"],[525,2],[526,1,"ȏ"],[527,2],[528,1,"ȑ"],[529,2],[530,1,"ȓ"],[531,2],[532,1,"ȕ"],[533,2],[534,1,"ȗ"],[535,2],[536,1,"ș"],[537,2],[538,1,"ț"],[539,2],[540,1,"ȝ"],[541,2],[542,1,"ȟ"],[543,2],[544,1,"ƞ"],[545,2],[546,1,"ȣ"],[547,2],[548,1,"ȥ"],[549,2],[550,1,"ȧ"],[551,2],[552,1,"ȩ"],[553,2],[554,1,"ȫ"],[555,2],[556,1,"ȭ"],[557,2],[558,1,"ȯ"],[559,2],[560,1,"ȱ"],[561,2],[562,1,"ȳ"],[563,2],[[564,566],2],[[567,569],2],[570,1,"ⱥ"],[571,1,"ȼ"],[572,2],[573,1,"ƚ"],[574,1,"ⱦ"],[[575,576],2],[577,1,"ɂ"],[578,2],[579,1,"ƀ"],[580,1,"ʉ"],[581,1,"ʌ"],[582,1,"ɇ"],[583,2],[584,1,"ɉ"],[585,2],[586,1,"ɋ"],[587,2],[588,1,"ɍ"],[589,2],[590,1,"ɏ"],[591,2],[[592,680],2],[[681,685],2],[[686,687],2],[688,1,"h"],[689,1,"ɦ"],[690,1,"j"],[691,1,"r"],[692,1,"ɹ"],[693,1,"ɻ"],[694,1,"ʁ"],[695,1,"w"],[696,1,"y"],[[697,705],2],[[706,709],2],[[710,721],2],[[722,727],2],[728,5," ̆"],[729,5," ̇"],[730,5," ̊"],[731,5," ̨"],[732,5," ̃"],[733,5," ̋"],[734,2],[735,2],[736,1,"ɣ"],[737,1,"l"],[738,1,"s"],[739,1,"x"],[740,1,"ʕ"],[[741,745],2],[[746,747],2],[748,2],[749,2],[750,2],[[751,767],2],[[768,831],2],[832,1,"̀"],[833,1,"́"],[834,2],[835,1,"̓"],[836,1,"̈́"],[837,1,"ι"],[[838,846],2],[847,7],[[848,855],2],[[856,860],2],[[861,863],2],[[864,865],2],[866,2],[[867,879],2],[880,1,"ͱ"],[881,2],[882,1,"ͳ"],[883,2],[884,1,"ʹ"],[885,2],[886,1,"ͷ"],[887,2],[[888,889],3],[890,5," ι"],[[891,893],2],[894,5,";"],[895,1,"ϳ"],[[896,899],3],[900,5," ́"],[901,5," ̈́"],[902,1,"ά"],[903,1,"·"],[904,1,"έ"],[905,1,"ή"],[906,1,"ί"],[907,3],[908,1,"ό"],[909,3],[910,1,"ύ"],[911,1,"ώ"],[912,2],[913,1,"α"],[914,1,"β"],[915,1,"γ"],[916,1,"δ"],[917,1,"ε"],[918,1,"ζ"],[919,1,"η"],[920,1,"θ"],[921,1,"ι"],[922,1,"κ"],[923,1,"λ"],[924,1,"μ"],[925,1,"ν"],[926,1,"ξ"],[927,1,"ο"],[928,1,"π"],[929,1,"ρ"],[930,3],[931,1,"σ"],[932,1,"τ"],[933,1,"υ"],[934,1,"φ"],[935,1,"χ"],[936,1,"ψ"],[937,1,"ω"],[938,1,"ϊ"],[939,1,"ϋ"],[[940,961],2],[962,6,"σ"],[[963,974],2],[975,1,"ϗ"],[976,1,"β"],[977,1,"θ"],[978,1,"υ"],[979,1,"ύ"],[980,1,"ϋ"],[981,1,"φ"],[982,1,"π"],[983,2],[984,1,"ϙ"],[985,2],[986,1,"ϛ"],[987,2],[988,1,"ϝ"],[989,2],[990,1,"ϟ"],[991,2],[992,1,"ϡ"],[993,2],[994,1,"ϣ"],[995,2],[996,1,"ϥ"],[997,2],[998,1,"ϧ"],[999,2],[1000,1,"ϩ"],[1001,2],[1002,1,"ϫ"],[1003,2],[1004,1,"ϭ"],[1005,2],[1006,1,"ϯ"],[1007,2],[1008,1,"κ"],[1009,1,"ρ"],[1010,1,"σ"],[1011,2],[1012,1,"θ"],[1013,1,"ε"],[1014,2],[1015,1,"ϸ"],[1016,2],[1017,1,"σ"],[1018,1,"ϻ"],[1019,2],[1020,2],[1021,1,"ͻ"],[1022,1,"ͼ"],[1023,1,"ͽ"],[1024,1,"ѐ"],[1025,1,"ё"],[1026,1,"ђ"],[1027,1,"ѓ"],[1028,1,"є"],[1029,1,"ѕ"],[1030,1,"і"],[1031,1,"ї"],[1032,1,"ј"],[1033,1,"љ"],[1034,1,"њ"],[1035,1,"ћ"],[1036,1,"ќ"],[1037,1,"ѝ"],[1038,1,"ў"],[1039,1,"џ"],[1040,1,"а"],[1041,1,"б"],[1042,1,"в"],[1043,1,"г"],[1044,1,"д"],[1045,1,"е"],[1046,1,"ж"],[1047,1,"з"],[1048,1,"и"],[1049,1,"й"],[1050,1,"к"],[1051,1,"л"],[1052,1,"м"],[1053,1,"н"],[1054,1,"о"],[1055,1,"п"],[1056,1,"р"],[1057,1,"с"],[1058,1,"т"],[1059,1,"у"],[1060,1,"ф"],[1061,1,"х"],[1062,1,"ц"],[1063,1,"ч"],[1064,1,"ш"],[1065,1,"щ"],[1066,1,"ъ"],[1067,1,"ы"],[1068,1,"ь"],[1069,1,"э"],[1070,1,"ю"],[1071,1,"я"],[[1072,1103],2],[1104,2],[[1105,1116],2],[1117,2],[[1118,1119],2],[1120,1,"ѡ"],[1121,2],[1122,1,"ѣ"],[1123,2],[1124,1,"ѥ"],[1125,2],[1126,1,"ѧ"],[1127,2],[1128,1,"ѩ"],[1129,2],[1130,1,"ѫ"],[1131,2],[1132,1,"ѭ"],[1133,2],[1134,1,"ѯ"],[1135,2],[1136,1,"ѱ"],[1137,2],[1138,1,"ѳ"],[1139,2],[1140,1,"ѵ"],[1141,2],[1142,1,"ѷ"],[1143,2],[1144,1,"ѹ"],[1145,2],[1146,1,"ѻ"],[1147,2],[1148,1,"ѽ"],[1149,2],[1150,1,"ѿ"],[1151,2],[1152,1,"ҁ"],[1153,2],[1154,2],[[1155,1158],2],[1159,2],[[1160,1161],2],[1162,1,"ҋ"],[1163,2],[1164,1,"ҍ"],[1165,2],[1166,1,"ҏ"],[1167,2],[1168,1,"ґ"],[1169,2],[1170,1,"ғ"],[1171,2],[1172,1,"ҕ"],[1173,2],[1174,1,"җ"],[1175,2],[1176,1,"ҙ"],[1177,2],[1178,1,"қ"],[1179,2],[1180,1,"ҝ"],[1181,2],[1182,1,"ҟ"],[1183,2],[1184,1,"ҡ"],[1185,2],[1186,1,"ң"],[1187,2],[1188,1,"ҥ"],[1189,2],[1190,1,"ҧ"],[1191,2],[1192,1,"ҩ"],[1193,2],[1194,1,"ҫ"],[1195,2],[1196,1,"ҭ"],[1197,2],[1198,1,"ү"],[1199,2],[1200,1,"ұ"],[1201,2],[1202,1,"ҳ"],[1203,2],[1204,1,"ҵ"],[1205,2],[1206,1,"ҷ"],[1207,2],[1208,1,"ҹ"],[1209,2],[1210,1,"һ"],[1211,2],[1212,1,"ҽ"],[1213,2],[1214,1,"ҿ"],[1215,2],[1216,3],[1217,1,"ӂ"],[1218,2],[1219,1,"ӄ"],[1220,2],[1221,1,"ӆ"],[1222,2],[1223,1,"ӈ"],[1224,2],[1225,1,"ӊ"],[1226,2],[1227,1,"ӌ"],[1228,2],[1229,1,"ӎ"],[1230,2],[1231,2],[1232,1,"ӑ"],[1233,2],[1234,1,"ӓ"],[1235,2],[1236,1,"ӕ"],[1237,2],[1238,1,"ӗ"],[1239,2],[1240,1,"ә"],[1241,2],[1242,1,"ӛ"],[1243,2],[1244,1,"ӝ"],[1245,2],[1246,1,"ӟ"],[1247,2],[1248,1,"ӡ"],[1249,2],[1250,1,"ӣ"],[1251,2],[1252,1,"ӥ"],[1253,2],[1254,1,"ӧ"],[1255,2],[1256,1,"ө"],[1257,2],[1258,1,"ӫ"],[1259,2],[1260,1,"ӭ"],[1261,2],[1262,1,"ӯ"],[1263,2],[1264,1,"ӱ"],[1265,2],[1266,1,"ӳ"],[1267,2],[1268,1,"ӵ"],[1269,2],[1270,1,"ӷ"],[1271,2],[1272,1,"ӹ"],[1273,2],[1274,1,"ӻ"],[1275,2],[1276,1,"ӽ"],[1277,2],[1278,1,"ӿ"],[1279,2],[1280,1,"ԁ"],[1281,2],[1282,1,"ԃ"],[1283,2],[1284,1,"ԅ"],[1285,2],[1286,1,"ԇ"],[1287,2],[1288,1,"ԉ"],[1289,2],[1290,1,"ԋ"],[1291,2],[1292,1,"ԍ"],[1293,2],[1294,1,"ԏ"],[1295,2],[1296,1,"ԑ"],[1297,2],[1298,1,"ԓ"],[1299,2],[1300,1,"ԕ"],[1301,2],[1302,1,"ԗ"],[1303,2],[1304,1,"ԙ"],[1305,2],[1306,1,"ԛ"],[1307,2],[1308,1,"ԝ"],[1309,2],[1310,1,"ԟ"],[1311,2],[1312,1,"ԡ"],[1313,2],[1314,1,"ԣ"],[1315,2],[1316,1,"ԥ"],[1317,2],[1318,1,"ԧ"],[1319,2],[1320,1,"ԩ"],[1321,2],[1322,1,"ԫ"],[1323,2],[1324,1,"ԭ"],[1325,2],[1326,1,"ԯ"],[1327,2],[1328,3],[1329,1,"ա"],[1330,1,"բ"],[1331,1,"գ"],[1332,1,"դ"],[1333,1,"ե"],[1334,1,"զ"],[1335,1,"է"],[1336,1,"ը"],[1337,1,"թ"],[1338,1,"ժ"],[1339,1,"ի"],[1340,1,"լ"],[1341,1,"խ"],[1342,1,"ծ"],[1343,1,"կ"],[1344,1,"հ"],[1345,1,"ձ"],[1346,1,"ղ"],[1347,1,"ճ"],[1348,1,"մ"],[1349,1,"յ"],[1350,1,"ն"],[1351,1,"շ"],[1352,1,"ո"],[1353,1,"չ"],[1354,1,"պ"],[1355,1,"ջ"],[1356,1,"ռ"],[1357,1,"ս"],[1358,1,"վ"],[1359,1,"տ"],[1360,1,"ր"],[1361,1,"ց"],[1362,1,"ւ"],[1363,1,"փ"],[1364,1,"ք"],[1365,1,"օ"],[1366,1,"ֆ"],[[1367,1368],3],[1369,2],[[1370,1375],2],[1376,2],[[1377,1414],2],[1415,1,"եւ"],[1416,2],[1417,2],[1418,2],[[1419,1420],3],[[1421,1422],2],[1423,2],[1424,3],[[1425,1441],2],[1442,2],[[1443,1455],2],[[1456,1465],2],[1466,2],[[1467,1469],2],[1470,2],[1471,2],[1472,2],[[1473,1474],2],[1475,2],[1476,2],[1477,2],[1478,2],[1479,2],[[1480,1487],3],[[1488,1514],2],[[1515,1518],3],[1519,2],[[1520,1524],2],[[1525,1535],3],[[1536,1539],3],[1540,3],[1541,3],[[1542,1546],2],[1547,2],[1548,2],[[1549,1551],2],[[1552,1557],2],[[1558,1562],2],[1563,2],[1564,3],[1565,3],[1566,2],[1567,2],[1568,2],[[1569,1594],2],[[1595,1599],2],[1600,2],[[1601,1618],2],[[1619,1621],2],[[1622,1624],2],[[1625,1630],2],[1631,2],[[1632,1641],2],[[1642,1645],2],[[1646,1647],2],[[1648,1652],2],[1653,1,"اٴ"],[1654,1,"وٴ"],[1655,1,"ۇٴ"],[1656,1,"يٴ"],[[1657,1719],2],[[1720,1721],2],[[1722,1726],2],[1727,2],[[1728,1742],2],[1743,2],[[1744,1747],2],[1748,2],[[1749,1756],2],[1757,3],[1758,2],[[1759,1768],2],[1769,2],[[1770,1773],2],[[1774,1775],2],[[1776,1785],2],[[1786,1790],2],[1791,2],[[1792,1805],2],[1806,3],[1807,3],[[1808,1836],2],[[1837,1839],2],[[1840,1866],2],[[1867,1868],3],[[1869,1871],2],[[1872,1901],2],[[1902,1919],2],[[1920,1968],2],[1969,2],[[1970,1983],3],[[1984,2037],2],[[2038,2042],2],[[2043,2044],3],[2045,2],[[2046,2047],2],[[2048,2093],2],[[2094,2095],3],[[2096,2110],2],[2111,3],[[2112,2139],2],[[2140,2141],3],[2142,2],[2143,3],[[2144,2154],2],[[2155,2207],3],[2208,2],[2209,2],[[2210,2220],2],[[2221,2226],2],[[2227,2228],2],[2229,3],[[2230,2237],2],[[2238,2247],2],[[2248,2258],3],[2259,2],[[2260,2273],2],[2274,3],[2275,2],[[2276,2302],2],[2303,2],[2304,2],[[2305,2307],2],[2308,2],[[2309,2361],2],[[2362,2363],2],[[2364,2381],2],[2382,2],[2383,2],[[2384,2388],2],[2389,2],[[2390,2391],2],[2392,1,"क़"],[2393,1,"ख़"],[2394,1,"ग़"],[2395,1,"ज़"],[2396,1,"ड़"],[2397,1,"ढ़"],[2398,1,"फ़"],[2399,1,"य़"],[[2400,2403],2],[[2404,2405],2],[[2406,2415],2],[2416,2],[[2417,2418],2],[[2419,2423],2],[2424,2],[[2425,2426],2],[[2427,2428],2],[2429,2],[[2430,2431],2],[2432,2],[[2433,2435],2],[2436,3],[[2437,2444],2],[[2445,2446],3],[[2447,2448],2],[[2449,2450],3],[[2451,2472],2],[2473,3],[[2474,2480],2],[2481,3],[2482,2],[[2483,2485],3],[[2486,2489],2],[[2490,2491],3],[2492,2],[2493,2],[[2494,2500],2],[[2501,2502],3],[[2503,2504],2],[[2505,2506],3],[[2507,2509],2],[2510,2],[[2511,2518],3],[2519,2],[[2520,2523],3],[2524,1,"ড়"],[2525,1,"ঢ়"],[2526,3],[2527,1,"য়"],[[2528,2531],2],[[2532,2533],3],[[2534,2545],2],[[2546,2554],2],[2555,2],[2556,2],[2557,2],[2558,2],[[2559,2560],3],[2561,2],[2562,2],[2563,2],[2564,3],[[2565,2570],2],[[2571,2574],3],[[2575,2576],2],[[2577,2578],3],[[2579,2600],2],[2601,3],[[2602,2608],2],[2609,3],[2610,2],[2611,1,"ਲ਼"],[2612,3],[2613,2],[2614,1,"ਸ਼"],[2615,3],[[2616,2617],2],[[2618,2619],3],[2620,2],[2621,3],[[2622,2626],2],[[2627,2630],3],[[2631,2632],2],[[2633,2634],3],[[2635,2637],2],[[2638,2640],3],[2641,2],[[2642,2648],3],[2649,1,"ਖ਼"],[2650,1,"ਗ਼"],[2651,1,"ਜ਼"],[2652,2],[2653,3],[2654,1,"ਫ਼"],[[2655,2661],3],[[2662,2676],2],[2677,2],[2678,2],[[2679,2688],3],[[2689,2691],2],[2692,3],[[2693,2699],2],[2700,2],[2701,2],[2702,3],[[2703,2705],2],[2706,3],[[2707,2728],2],[2729,3],[[2730,2736],2],[2737,3],[[2738,2739],2],[2740,3],[[2741,2745],2],[[2746,2747],3],[[2748,2757],2],[2758,3],[[2759,2761],2],[2762,3],[[2763,2765],2],[[2766,2767],3],[2768,2],[[2769,2783],3],[2784,2],[[2785,2787],2],[[2788,2789],3],[[2790,2799],2],[2800,2],[2801,2],[[2802,2808],3],[2809,2],[[2810,2815],2],[2816,3],[[2817,2819],2],[2820,3],[[2821,2828],2],[[2829,2830],3],[[2831,2832],2],[[2833,2834],3],[[2835,2856],2],[2857,3],[[2858,2864],2],[2865,3],[[2866,2867],2],[2868,3],[2869,2],[[2870,2873],2],[[2874,2875],3],[[2876,2883],2],[2884,2],[[2885,2886],3],[[2887,2888],2],[[2889,2890],3],[[2891,2893],2],[[2894,2900],3],[2901,2],[[2902,2903],2],[[2904,2907],3],[2908,1,"ଡ଼"],[2909,1,"ଢ଼"],[2910,3],[[2911,2913],2],[[2914,2915],2],[[2916,2917],3],[[2918,2927],2],[2928,2],[2929,2],[[2930,2935],2],[[2936,2945],3],[[2946,2947],2],[2948,3],[[2949,2954],2],[[2955,2957],3],[[2958,2960],2],[2961,3],[[2962,2965],2],[[2966,2968],3],[[2969,2970],2],[2971,3],[2972,2],[2973,3],[[2974,2975],2],[[2976,2978],3],[[2979,2980],2],[[2981,2983],3],[[2984,2986],2],[[2987,2989],3],[[2990,2997],2],[2998,2],[[2999,3001],2],[[3002,3005],3],[[3006,3010],2],[[3011,3013],3],[[3014,3016],2],[3017,3],[[3018,3021],2],[[3022,3023],3],[3024,2],[[3025,3030],3],[3031,2],[[3032,3045],3],[3046,2],[[3047,3055],2],[[3056,3058],2],[[3059,3066],2],[[3067,3071],3],[3072,2],[[3073,3075],2],[3076,2],[[3077,3084],2],[3085,3],[[3086,3088],2],[3089,3],[[3090,3112],2],[3113,3],[[3114,3123],2],[3124,2],[[3125,3129],2],[[3130,3132],3],[3133,2],[[3134,3140],2],[3141,3],[[3142,3144],2],[3145,3],[[3146,3149],2],[[3150,3156],3],[[3157,3158],2],[3159,3],[[3160,3161],2],[3162,2],[[3163,3167],3],[[3168,3169],2],[[3170,3171],2],[[3172,3173],3],[[3174,3183],2],[[3184,3190],3],[3191,2],[[3192,3199],2],[3200,2],[3201,2],[[3202,3203],2],[3204,2],[[3205,3212],2],[3213,3],[[3214,3216],2],[3217,3],[[3218,3240],2],[3241,3],[[3242,3251],2],[3252,3],[[3253,3257],2],[[3258,3259],3],[[3260,3261],2],[[3262,3268],2],[3269,3],[[3270,3272],2],[3273,3],[[3274,3277],2],[[3278,3284],3],[[3285,3286],2],[[3287,3293],3],[3294,2],[3295,3],[[3296,3297],2],[[3298,3299],2],[[3300,3301],3],[[3302,3311],2],[3312,3],[[3313,3314],2],[[3315,3327],3],[3328,2],[3329,2],[[3330,3331],2],[3332,2],[[3333,3340],2],[3341,3],[[3342,3344],2],[3345,3],[[3346,3368],2],[3369,2],[[3370,3385],2],[3386,2],[[3387,3388],2],[3389,2],[[3390,3395],2],[3396,2],[3397,3],[[3398,3400],2],[3401,3],[[3402,3405],2],[3406,2],[3407,2],[[3408,3411],3],[[3412,3414],2],[3415,2],[[3416,3422],2],[3423,2],[[3424,3425],2],[[3426,3427],2],[[3428,3429],3],[[3430,3439],2],[[3440,3445],2],[[3446,3448],2],[3449,2],[[3450,3455],2],[3456,3],[3457,2],[[3458,3459],2],[3460,3],[[3461,3478],2],[[3479,3481],3],[[3482,3505],2],[3506,3],[[3507,3515],2],[3516,3],[3517,2],[[3518,3519],3],[[3520,3526],2],[[3527,3529],3],[3530,2],[[3531,3534],3],[[3535,3540],2],[3541,3],[3542,2],[3543,3],[[3544,3551],2],[[3552,3557],3],[[3558,3567],2],[[3568,3569],3],[[3570,3571],2],[3572,2],[[3573,3584],3],[[3585,3634],2],[3635,1,"ํา"],[[3636,3642],2],[[3643,3646],3],[3647,2],[[3648,3662],2],[3663,2],[[3664,3673],2],[[3674,3675],2],[[3676,3712],3],[[3713,3714],2],[3715,3],[3716,2],[3717,3],[3718,2],[[3719,3720],2],[3721,2],[3722,2],[3723,3],[3724,2],[3725,2],[[3726,3731],2],[[3732,3735],2],[3736,2],[[3737,3743],2],[3744,2],[[3745,3747],2],[3748,3],[3749,2],[3750,3],[3751,2],[[3752,3753],2],[[3754,3755],2],[3756,2],[[3757,3762],2],[3763,1,"ໍາ"],[[3764,3769],2],[3770,2],[[3771,3773],2],[[3774,3775],3],[[3776,3780],2],[3781,3],[3782,2],[3783,3],[[3784,3789],2],[[3790,3791],3],[[3792,3801],2],[[3802,3803],3],[3804,1,"ຫນ"],[3805,1,"ຫມ"],[[3806,3807],2],[[3808,3839],3],[3840,2],[[3841,3850],2],[3851,2],[3852,1,"་"],[[3853,3863],2],[[3864,3865],2],[[3866,3871],2],[[3872,3881],2],[[3882,3892],2],[3893,2],[3894,2],[3895,2],[3896,2],[3897,2],[[3898,3901],2],[[3902,3906],2],[3907,1,"གྷ"],[[3908,3911],2],[3912,3],[[3913,3916],2],[3917,1,"ཌྷ"],[[3918,3921],2],[3922,1,"དྷ"],[[3923,3926],2],[3927,1,"བྷ"],[[3928,3931],2],[3932,1,"ཛྷ"],[[3933,3944],2],[3945,1,"ཀྵ"],[3946,2],[[3947,3948],2],[[3949,3952],3],[[3953,3954],2],[3955,1,"ཱི"],[3956,2],[3957,1,"ཱུ"],[3958,1,"ྲྀ"],[3959,1,"ྲཱྀ"],[3960,1,"ླྀ"],[3961,1,"ླཱྀ"],[[3962,3968],2],[3969,1,"ཱྀ"],[[3970,3972],2],[3973,2],[[3974,3979],2],[[3980,3983],2],[[3984,3986],2],[3987,1,"ྒྷ"],[[3988,3989],2],[3990,2],[3991,2],[3992,3],[[3993,3996],2],[3997,1,"ྜྷ"],[[3998,4001],2],[4002,1,"ྡྷ"],[[4003,4006],2],[4007,1,"ྦྷ"],[[4008,4011],2],[4012,1,"ྫྷ"],[4013,2],[[4014,4016],2],[[4017,4023],2],[4024,2],[4025,1,"ྐྵ"],[[4026,4028],2],[4029,3],[[4030,4037],2],[4038,2],[[4039,4044],2],[4045,3],[4046,2],[4047,2],[[4048,4049],2],[[4050,4052],2],[[4053,4056],2],[[4057,4058],2],[[4059,4095],3],[[4096,4129],2],[4130,2],[[4131,4135],2],[4136,2],[[4137,4138],2],[4139,2],[[4140,4146],2],[[4147,4149],2],[[4150,4153],2],[[4154,4159],2],[[4160,4169],2],[[4170,4175],2],[[4176,4185],2],[[4186,4249],2],[[4250,4253],2],[[4254,4255],2],[[4256,4293],3],[4294,3],[4295,1,"ⴧ"],[[4296,4300],3],[4301,1,"ⴭ"],[[4302,4303],3],[[4304,4342],2],[[4343,4344],2],[[4345,4346],2],[4347,2],[4348,1,"ნ"],[[4349,4351],2],[[4352,4441],2],[[4442,4446],2],[[4447,4448],3],[[4449,4514],2],[[4515,4519],2],[[4520,4601],2],[[4602,4607],2],[[4608,4614],2],[4615,2],[[4616,4678],2],[4679,2],[4680,2],[4681,3],[[4682,4685],2],[[4686,4687],3],[[4688,4694],2],[4695,3],[4696,2],[4697,3],[[4698,4701],2],[[4702,4703],3],[[4704,4742],2],[4743,2],[4744,2],[4745,3],[[4746,4749],2],[[4750,4751],3],[[4752,4782],2],[4783,2],[4784,2],[4785,3],[[4786,4789],2],[[4790,4791],3],[[4792,4798],2],[4799,3],[4800,2],[4801,3],[[4802,4805],2],[[4806,4807],3],[[4808,4814],2],[4815,2],[[4816,4822],2],[4823,3],[[4824,4846],2],[4847,2],[[4848,4878],2],[4879,2],[4880,2],[4881,3],[[4882,4885],2],[[4886,4887],3],[[4888,4894],2],[4895,2],[[4896,4934],2],[4935,2],[[4936,4954],2],[[4955,4956],3],[[4957,4958],2],[4959,2],[4960,2],[[4961,4988],2],[[4989,4991],3],[[4992,5007],2],[[5008,5017],2],[[5018,5023],3],[[5024,5108],2],[5109,2],[[5110,5111],3],[5112,1,"Ᏸ"],[5113,1,"Ᏹ"],[5114,1,"Ᏺ"],[5115,1,"Ᏻ"],[5116,1,"Ᏼ"],[5117,1,"Ᏽ"],[[5118,5119],3],[5120,2],[[5121,5740],2],[[5741,5742],2],[[5743,5750],2],[[5751,5759],2],[5760,3],[[5761,5786],2],[[5787,5788],2],[[5789,5791],3],[[5792,5866],2],[[5867,5872],2],[[5873,5880],2],[[5881,5887],3],[[5888,5900],2],[5901,3],[[5902,5908],2],[[5909,5919],3],[[5920,5940],2],[[5941,5942],2],[[5943,5951],3],[[5952,5971],2],[[5972,5983],3],[[5984,5996],2],[5997,3],[[5998,6000],2],[6001,3],[[6002,6003],2],[[6004,6015],3],[[6016,6067],2],[[6068,6069],3],[[6070,6099],2],[[6100,6102],2],[6103,2],[[6104,6107],2],[6108,2],[6109,2],[[6110,6111],3],[[6112,6121],2],[[6122,6127],3],[[6128,6137],2],[[6138,6143],3],[[6144,6149],2],[6150,3],[[6151,6154],2],[[6155,6157],7],[6158,3],[6159,3],[[6160,6169],2],[[6170,6175],3],[[6176,6263],2],[6264,2],[[6265,6271],3],[[6272,6313],2],[6314,2],[[6315,6319],3],[[6320,6389],2],[[6390,6399],3],[[6400,6428],2],[[6429,6430],2],[6431,3],[[6432,6443],2],[[6444,6447],3],[[6448,6459],2],[[6460,6463],3],[6464,2],[[6465,6467],3],[[6468,6469],2],[[6470,6509],2],[[6510,6511],3],[[6512,6516],2],[[6517,6527],3],[[6528,6569],2],[[6570,6571],2],[[6572,6575],3],[[6576,6601],2],[[6602,6607],3],[[6608,6617],2],[6618,2],[[6619,6621],3],[[6622,6623],2],[[6624,6655],2],[[6656,6683],2],[[6684,6685],3],[[6686,6687],2],[[6688,6750],2],[6751,3],[[6752,6780],2],[[6781,6782],3],[[6783,6793],2],[[6794,6799],3],[[6800,6809],2],[[6810,6815],3],[[6816,6822],2],[6823,2],[[6824,6829],2],[[6830,6831],3],[[6832,6845],2],[6846,2],[[6847,6848],2],[[6849,6911],3],[[6912,6987],2],[[6988,6991],3],[[6992,7001],2],[[7002,7018],2],[[7019,7027],2],[[7028,7036],2],[[7037,7039],3],[[7040,7082],2],[[7083,7085],2],[[7086,7097],2],[[7098,7103],2],[[7104,7155],2],[[7156,7163],3],[[7164,7167],2],[[7168,7223],2],[[7224,7226],3],[[7227,7231],2],[[7232,7241],2],[[7242,7244],3],[[7245,7293],2],[[7294,7295],2],[7296,1,"в"],[7297,1,"д"],[7298,1,"о"],[7299,1,"с"],[[7300,7301],1,"т"],[7302,1,"ъ"],[7303,1,"ѣ"],[7304,1,"ꙋ"],[[7305,7311],3],[7312,1,"ა"],[7313,1,"ბ"],[7314,1,"გ"],[7315,1,"დ"],[7316,1,"ე"],[7317,1,"ვ"],[7318,1,"ზ"],[7319,1,"თ"],[7320,1,"ი"],[7321,1,"კ"],[7322,1,"ლ"],[7323,1,"მ"],[7324,1,"ნ"],[7325,1,"ო"],[7326,1,"პ"],[7327,1,"ჟ"],[7328,1,"რ"],[7329,1,"ს"],[7330,1,"ტ"],[7331,1,"უ"],[7332,1,"ფ"],[7333,1,"ქ"],[7334,1,"ღ"],[7335,1,"ყ"],[7336,1,"შ"],[7337,1,"ჩ"],[7338,1,"ც"],[7339,1,"ძ"],[7340,1,"წ"],[7341,1,"ჭ"],[7342,1,"ხ"],[7343,1,"ჯ"],[7344,1,"ჰ"],[7345,1,"ჱ"],[7346,1,"ჲ"],[7347,1,"ჳ"],[7348,1,"ჴ"],[7349,1,"ჵ"],[7350,1,"ჶ"],[7351,1,"ჷ"],[7352,1,"ჸ"],[7353,1,"ჹ"],[7354,1,"ჺ"],[[7355,7356],3],[7357,1,"ჽ"],[7358,1,"ჾ"],[7359,1,"ჿ"],[[7360,7367],2],[[7368,7375],3],[[7376,7378],2],[7379,2],[[7380,7410],2],[[7411,7414],2],[7415,2],[[7416,7417],2],[7418,2],[[7419,7423],3],[[7424,7467],2],[7468,1,"a"],[7469,1,"æ"],[7470,1,"b"],[7471,2],[7472,1,"d"],[7473,1,"e"],[7474,1,"ǝ"],[7475,1,"g"],[7476,1,"h"],[7477,1,"i"],[7478,1,"j"],[7479,1,"k"],[7480,1,"l"],[7481,1,"m"],[7482,1,"n"],[7483,2],[7484,1,"o"],[7485,1,"ȣ"],[7486,1,"p"],[7487,1,"r"],[7488,1,"t"],[7489,1,"u"],[7490,1,"w"],[7491,1,"a"],[7492,1,"ɐ"],[7493,1,"ɑ"],[7494,1,"ᴂ"],[7495,1,"b"],[7496,1,"d"],[7497,1,"e"],[7498,1,"ə"],[7499,1,"ɛ"],[7500,1,"ɜ"],[7501,1,"g"],[7502,2],[7503,1,"k"],[7504,1,"m"],[7505,1,"ŋ"],[7506,1,"o"],[7507,1,"ɔ"],[7508,1,"ᴖ"],[7509,1,"ᴗ"],[7510,1,"p"],[7511,1,"t"],[7512,1,"u"],[7513,1,"ᴝ"],[7514,1,"ɯ"],[7515,1,"v"],[7516,1,"ᴥ"],[7517,1,"β"],[7518,1,"γ"],[7519,1,"δ"],[7520,1,"φ"],[7521,1,"χ"],[7522,1,"i"],[7523,1,"r"],[7524,1,"u"],[7525,1,"v"],[7526,1,"β"],[7527,1,"γ"],[7528,1,"ρ"],[7529,1,"φ"],[7530,1,"χ"],[7531,2],[[7532,7543],2],[7544,1,"н"],[[7545,7578],2],[7579,1,"ɒ"],[7580,1,"c"],[7581,1,"ɕ"],[7582,1,"ð"],[7583,1,"ɜ"],[7584,1,"f"],[7585,1,"ɟ"],[7586,1,"ɡ"],[7587,1,"ɥ"],[7588,1,"ɨ"],[7589,1,"ɩ"],[7590,1,"ɪ"],[7591,1,"ᵻ"],[7592,1,"ʝ"],[7593,1,"ɭ"],[7594,1,"ᶅ"],[7595,1,"ʟ"],[7596,1,"ɱ"],[7597,1,"ɰ"],[7598,1,"ɲ"],[7599,1,"ɳ"],[7600,1,"ɴ"],[7601,1,"ɵ"],[7602,1,"ɸ"],[7603,1,"ʂ"],[7604,1,"ʃ"],[7605,1,"ƫ"],[7606,1,"ʉ"],[7607,1,"ʊ"],[7608,1,"ᴜ"],[7609,1,"ʋ"],[7610,1,"ʌ"],[7611,1,"z"],[7612,1,"ʐ"],[7613,1,"ʑ"],[7614,1,"ʒ"],[7615,1,"θ"],[[7616,7619],2],[[7620,7626],2],[[7627,7654],2],[[7655,7669],2],[[7670,7673],2],[7674,3],[7675,2],[7676,2],[7677,2],[[7678,7679],2],[7680,1,"ḁ"],[7681,2],[7682,1,"ḃ"],[7683,2],[7684,1,"ḅ"],[7685,2],[7686,1,"ḇ"],[7687,2],[7688,1,"ḉ"],[7689,2],[7690,1,"ḋ"],[7691,2],[7692,1,"ḍ"],[7693,2],[7694,1,"ḏ"],[7695,2],[7696,1,"ḑ"],[7697,2],[7698,1,"ḓ"],[7699,2],[7700,1,"ḕ"],[7701,2],[7702,1,"ḗ"],[7703,2],[7704,1,"ḙ"],[7705,2],[7706,1,"ḛ"],[7707,2],[7708,1,"ḝ"],[7709,2],[7710,1,"ḟ"],[7711,2],[7712,1,"ḡ"],[7713,2],[7714,1,"ḣ"],[7715,2],[7716,1,"ḥ"],[7717,2],[7718,1,"ḧ"],[7719,2],[7720,1,"ḩ"],[7721,2],[7722,1,"ḫ"],[7723,2],[7724,1,"ḭ"],[7725,2],[7726,1,"ḯ"],[7727,2],[7728,1,"ḱ"],[7729,2],[7730,1,"ḳ"],[7731,2],[7732,1,"ḵ"],[7733,2],[7734,1,"ḷ"],[7735,2],[7736,1,"ḹ"],[7737,2],[7738,1,"ḻ"],[7739,2],[7740,1,"ḽ"],[7741,2],[7742,1,"ḿ"],[7743,2],[7744,1,"ṁ"],[7745,2],[7746,1,"ṃ"],[7747,2],[7748,1,"ṅ"],[7749,2],[7750,1,"ṇ"],[7751,2],[7752,1,"ṉ"],[7753,2],[7754,1,"ṋ"],[7755,2],[7756,1,"ṍ"],[7757,2],[7758,1,"ṏ"],[7759,2],[7760,1,"ṑ"],[7761,2],[7762,1,"ṓ"],[7763,2],[7764,1,"ṕ"],[7765,2],[7766,1,"ṗ"],[7767,2],[7768,1,"ṙ"],[7769,2],[7770,1,"ṛ"],[7771,2],[7772,1,"ṝ"],[7773,2],[7774,1,"ṟ"],[7775,2],[7776,1,"ṡ"],[7777,2],[7778,1,"ṣ"],[7779,2],[7780,1,"ṥ"],[7781,2],[7782,1,"ṧ"],[7783,2],[7784,1,"ṩ"],[7785,2],[7786,1,"ṫ"],[7787,2],[7788,1,"ṭ"],[7789,2],[7790,1,"ṯ"],[7791,2],[7792,1,"ṱ"],[7793,2],[7794,1,"ṳ"],[7795,2],[7796,1,"ṵ"],[7797,2],[7798,1,"ṷ"],[7799,2],[7800,1,"ṹ"],[7801,2],[7802,1,"ṻ"],[7803,2],[7804,1,"ṽ"],[7805,2],[7806,1,"ṿ"],[7807,2],[7808,1,"ẁ"],[7809,2],[7810,1,"ẃ"],[7811,2],[7812,1,"ẅ"],[7813,2],[7814,1,"ẇ"],[7815,2],[7816,1,"ẉ"],[7817,2],[7818,1,"ẋ"],[7819,2],[7820,1,"ẍ"],[7821,2],[7822,1,"ẏ"],[7823,2],[7824,1,"ẑ"],[7825,2],[7826,1,"ẓ"],[7827,2],[7828,1,"ẕ"],[[7829,7833],2],[7834,1,"aʾ"],[7835,1,"ṡ"],[[7836,7837],2],[7838,1,"ss"],[7839,2],[7840,1,"ạ"],[7841,2],[7842,1,"ả"],[7843,2],[7844,1,"ấ"],[7845,2],[7846,1,"ầ"],[7847,2],[7848,1,"ẩ"],[7849,2],[7850,1,"ẫ"],[7851,2],[7852,1,"ậ"],[7853,2],[7854,1,"ắ"],[7855,2],[7856,1,"ằ"],[7857,2],[7858,1,"ẳ"],[7859,2],[7860,1,"ẵ"],[7861,2],[7862,1,"ặ"],[7863,2],[7864,1,"ẹ"],[7865,2],[7866,1,"ẻ"],[7867,2],[7868,1,"ẽ"],[7869,2],[7870,1,"ế"],[7871,2],[7872,1,"ề"],[7873,2],[7874,1,"ể"],[7875,2],[7876,1,"ễ"],[7877,2],[7878,1,"ệ"],[7879,2],[7880,1,"ỉ"],[7881,2],[7882,1,"ị"],[7883,2],[7884,1,"ọ"],[7885,2],[7886,1,"ỏ"],[7887,2],[7888,1,"ố"],[7889,2],[7890,1,"ồ"],[7891,2],[7892,1,"ổ"],[7893,2],[7894,1,"ỗ"],[7895,2],[7896,1,"ộ"],[7897,2],[7898,1,"ớ"],[7899,2],[7900,1,"ờ"],[7901,2],[7902,1,"ở"],[7903,2],[7904,1,"ỡ"],[7905,2],[7906,1,"ợ"],[7907,2],[7908,1,"ụ"],[7909,2],[7910,1,"ủ"],[7911,2],[7912,1,"ứ"],[7913,2],[7914,1,"ừ"],[7915,2],[7916,1,"ử"],[7917,2],[7918,1,"ữ"],[7919,2],[7920,1,"ự"],[7921,2],[7922,1,"ỳ"],[7923,2],[7924,1,"ỵ"],[7925,2],[7926,1,"ỷ"],[7927,2],[7928,1,"ỹ"],[7929,2],[7930,1,"ỻ"],[7931,2],[7932,1,"ỽ"],[7933,2],[7934,1,"ỿ"],[7935,2],[[7936,7943],2],[7944,1,"ἀ"],[7945,1,"ἁ"],[7946,1,"ἂ"],[7947,1,"ἃ"],[7948,1,"ἄ"],[7949,1,"ἅ"],[7950,1,"ἆ"],[7951,1,"ἇ"],[[7952,7957],2],[[7958,7959],3],[7960,1,"ἐ"],[7961,1,"ἑ"],[7962,1,"ἒ"],[7963,1,"ἓ"],[7964,1,"ἔ"],[7965,1,"ἕ"],[[7966,7967],3],[[7968,7975],2],[7976,1,"ἠ"],[7977,1,"ἡ"],[7978,1,"ἢ"],[7979,1,"ἣ"],[7980,1,"ἤ"],[7981,1,"ἥ"],[7982,1,"ἦ"],[7983,1,"ἧ"],[[7984,7991],2],[7992,1,"ἰ"],[7993,1,"ἱ"],[7994,1,"ἲ"],[7995,1,"ἳ"],[7996,1,"ἴ"],[7997,1,"ἵ"],[7998,1,"ἶ"],[7999,1,"ἷ"],[[8000,8005],2],[[8006,8007],3],[8008,1,"ὀ"],[8009,1,"ὁ"],[8010,1,"ὂ"],[8011,1,"ὃ"],[8012,1,"ὄ"],[8013,1,"ὅ"],[[8014,8015],3],[[8016,8023],2],[8024,3],[8025,1,"ὑ"],[8026,3],[8027,1,"ὓ"],[8028,3],[8029,1,"ὕ"],[8030,3],[8031,1,"ὗ"],[[8032,8039],2],[8040,1,"ὠ"],[8041,1,"ὡ"],[8042,1,"ὢ"],[8043,1,"ὣ"],[8044,1,"ὤ"],[8045,1,"ὥ"],[8046,1,"ὦ"],[8047,1,"ὧ"],[8048,2],[8049,1,"ά"],[8050,2],[8051,1,"έ"],[8052,2],[8053,1,"ή"],[8054,2],[8055,1,"ί"],[8056,2],[8057,1,"ό"],[8058,2],[8059,1,"ύ"],[8060,2],[8061,1,"ώ"],[[8062,8063],3],[8064,1,"ἀι"],[8065,1,"ἁι"],[8066,1,"ἂι"],[8067,1,"ἃι"],[8068,1,"ἄι"],[8069,1,"ἅι"],[8070,1,"ἆι"],[8071,1,"ἇι"],[8072,1,"ἀι"],[8073,1,"ἁι"],[8074,1,"ἂι"],[8075,1,"ἃι"],[8076,1,"ἄι"],[8077,1,"ἅι"],[8078,1,"ἆι"],[8079,1,"ἇι"],[8080,1,"ἠι"],[8081,1,"ἡι"],[8082,1,"ἢι"],[8083,1,"ἣι"],[8084,1,"ἤι"],[8085,1,"ἥι"],[8086,1,"ἦι"],[8087,1,"ἧι"],[8088,1,"ἠι"],[8089,1,"ἡι"],[8090,1,"ἢι"],[8091,1,"ἣι"],[8092,1,"ἤι"],[8093,1,"ἥι"],[8094,1,"ἦι"],[8095,1,"ἧι"],[8096,1,"ὠι"],[8097,1,"ὡι"],[8098,1,"ὢι"],[8099,1,"ὣι"],[8100,1,"ὤι"],[8101,1,"ὥι"],[8102,1,"ὦι"],[8103,1,"ὧι"],[8104,1,"ὠι"],[8105,1,"ὡι"],[8106,1,"ὢι"],[8107,1,"ὣι"],[8108,1,"ὤι"],[8109,1,"ὥι"],[8110,1,"ὦι"],[8111,1,"ὧι"],[[8112,8113],2],[8114,1,"ὰι"],[8115,1,"αι"],[8116,1,"άι"],[8117,3],[8118,2],[8119,1,"ᾶι"],[8120,1,"ᾰ"],[8121,1,"ᾱ"],[8122,1,"ὰ"],[8123,1,"ά"],[8124,1,"αι"],[8125,5," ̓"],[8126,1,"ι"],[8127,5," ̓"],[8128,5," ͂"],[8129,5," ̈͂"],[8130,1,"ὴι"],[8131,1,"ηι"],[8132,1,"ήι"],[8133,3],[8134,2],[8135,1,"ῆι"],[8136,1,"ὲ"],[8137,1,"έ"],[8138,1,"ὴ"],[8139,1,"ή"],[8140,1,"ηι"],[8141,5," ̓̀"],[8142,5," ̓́"],[8143,5," ̓͂"],[[8144,8146],2],[8147,1,"ΐ"],[[8148,8149],3],[[8150,8151],2],[8152,1,"ῐ"],[8153,1,"ῑ"],[8154,1,"ὶ"],[8155,1,"ί"],[8156,3],[8157,5," ̔̀"],[8158,5," ̔́"],[8159,5," ̔͂"],[[8160,8162],2],[8163,1,"ΰ"],[[8164,8167],2],[8168,1,"ῠ"],[8169,1,"ῡ"],[8170,1,"ὺ"],[8171,1,"ύ"],[8172,1,"ῥ"],[8173,5," ̈̀"],[8174,5," ̈́"],[8175,5,"`"],[[8176,8177],3],[8178,1,"ὼι"],[8179,1,"ωι"],[8180,1,"ώι"],[8181,3],[8182,2],[8183,1,"ῶι"],[8184,1,"ὸ"],[8185,1,"ό"],[8186,1,"ὼ"],[8187,1,"ώ"],[8188,1,"ωι"],[8189,5," ́"],[8190,5," ̔"],[8191,3],[[8192,8202],5," "],[8203,7],[[8204,8205],6,""],[[8206,8207],3],[8208,2],[8209,1,"‐"],[[8210,8214],2],[8215,5," ̳"],[[8216,8227],2],[[8228,8230],3],[8231,2],[[8232,8238],3],[8239,5," "],[[8240,8242],2],[8243,1,"′′"],[8244,1,"′′′"],[8245,2],[8246,1,"‵‵"],[8247,1,"‵‵‵"],[[8248,8251],2],[8252,5,"!!"],[8253,2],[8254,5," ̅"],[[8255,8262],2],[8263,5,"??"],[8264,5,"?!"],[8265,5,"!?"],[[8266,8269],2],[[8270,8274],2],[[8275,8276],2],[[8277,8278],2],[8279,1,"′′′′"],[[8280,8286],2],[8287,5," "],[8288,7],[[8289,8291],3],[8292,7],[8293,3],[[8294,8297],3],[[8298,8303],3],[8304,1,"0"],[8305,1,"i"],[[8306,8307],3],[8308,1,"4"],[8309,1,"5"],[8310,1,"6"],[8311,1,"7"],[8312,1,"8"],[8313,1,"9"],[8314,5,"+"],[8315,1,"−"],[8316,5,"="],[8317,5,"("],[8318,5,")"],[8319,1,"n"],[8320,1,"0"],[8321,1,"1"],[8322,1,"2"],[8323,1,"3"],[8324,1,"4"],[8325,1,"5"],[8326,1,"6"],[8327,1,"7"],[8328,1,"8"],[8329,1,"9"],[8330,5,"+"],[8331,1,"−"],[8332,5,"="],[8333,5,"("],[8334,5,")"],[8335,3],[8336,1,"a"],[8337,1,"e"],[8338,1,"o"],[8339,1,"x"],[8340,1,"ə"],[8341,1,"h"],[8342,1,"k"],[8343,1,"l"],[8344,1,"m"],[8345,1,"n"],[8346,1,"p"],[8347,1,"s"],[8348,1,"t"],[[8349,8351],3],[[8352,8359],2],[8360,1,"rs"],[[8361,8362],2],[8363,2],[8364,2],[[8365,8367],2],[[8368,8369],2],[[8370,8373],2],[[8374,8376],2],[8377,2],[8378,2],[[8379,8381],2],[8382,2],[8383,2],[[8384,8399],3],[[8400,8417],2],[[8418,8419],2],[[8420,8426],2],[8427,2],[[8428,8431],2],[8432,2],[[8433,8447],3],[8448,5,"a/c"],[8449,5,"a/s"],[8450,1,"c"],[8451,1,"°c"],[8452,2],[8453,5,"c/o"],[8454,5,"c/u"],[8455,1,"ɛ"],[8456,2],[8457,1,"°f"],[8458,1,"g"],[[8459,8462],1,"h"],[8463,1,"ħ"],[[8464,8465],1,"i"],[[8466,8467],1,"l"],[8468,2],[8469,1,"n"],[8470,1,"no"],[[8471,8472],2],[8473,1,"p"],[8474,1,"q"],[[8475,8477],1,"r"],[[8478,8479],2],[8480,1,"sm"],[8481,1,"tel"],[8482,1,"tm"],[8483,2],[8484,1,"z"],[8485,2],[8486,1,"ω"],[8487,2],[8488,1,"z"],[8489,2],[8490,1,"k"],[8491,1,"å"],[8492,1,"b"],[8493,1,"c"],[8494,2],[[8495,8496],1,"e"],[8497,1,"f"],[8498,3],[8499,1,"m"],[8500,1,"o"],[8501,1,"א"],[8502,1,"ב"],[8503,1,"ג"],[8504,1,"ד"],[8505,1,"i"],[8506,2],[8507,1,"fax"],[8508,1,"π"],[[8509,8510],1,"γ"],[8511,1,"π"],[8512,1,"∑"],[[8513,8516],2],[[8517,8518],1,"d"],[8519,1,"e"],[8520,1,"i"],[8521,1,"j"],[[8522,8523],2],[8524,2],[8525,2],[8526,2],[8527,2],[8528,1,"1⁄7"],[8529,1,"1⁄9"],[8530,1,"1⁄10"],[8531,1,"1⁄3"],[8532,1,"2⁄3"],[8533,1,"1⁄5"],[8534,1,"2⁄5"],[8535,1,"3⁄5"],[8536,1,"4⁄5"],[8537,1,"1⁄6"],[8538,1,"5⁄6"],[8539,1,"1⁄8"],[8540,1,"3⁄8"],[8541,1,"5⁄8"],[8542,1,"7⁄8"],[8543,1,"1⁄"],[8544,1,"i"],[8545,1,"ii"],[8546,1,"iii"],[8547,1,"iv"],[8548,1,"v"],[8549,1,"vi"],[8550,1,"vii"],[8551,1,"viii"],[8552,1,"ix"],[8553,1,"x"],[8554,1,"xi"],[8555,1,"xii"],[8556,1,"l"],[8557,1,"c"],[8558,1,"d"],[8559,1,"m"],[8560,1,"i"],[8561,1,"ii"],[8562,1,"iii"],[8563,1,"iv"],[8564,1,"v"],[8565,1,"vi"],[8566,1,"vii"],[8567,1,"viii"],[8568,1,"ix"],[8569,1,"x"],[8570,1,"xi"],[8571,1,"xii"],[8572,1,"l"],[8573,1,"c"],[8574,1,"d"],[8575,1,"m"],[[8576,8578],2],[8579,3],[8580,2],[[8581,8584],2],[8585,1,"0⁄3"],[[8586,8587],2],[[8588,8591],3],[[8592,8682],2],[[8683,8691],2],[[8692,8703],2],[[8704,8747],2],[8748,1,"∫∫"],[8749,1,"∫∫∫"],[8750,2],[8751,1,"∮∮"],[8752,1,"∮∮∮"],[[8753,8799],2],[8800,4],[[8801,8813],2],[[8814,8815],4],[[8816,8945],2],[[8946,8959],2],[8960,2],[8961,2],[[8962,9000],2],[9001,1,"〈"],[9002,1,"〉"],[[9003,9082],2],[9083,2],[9084,2],[[9085,9114],2],[[9115,9166],2],[[9167,9168],2],[[9169,9179],2],[[9180,9191],2],[9192,2],[[9193,9203],2],[[9204,9210],2],[[9211,9214],2],[9215,2],[[9216,9252],2],[[9253,9254],2],[[9255,9279],3],[[9280,9290],2],[[9291,9311],3],[9312,1,"1"],[9313,1,"2"],[9314,1,"3"],[9315,1,"4"],[9316,1,"5"],[9317,1,"6"],[9318,1,"7"],[9319,1,"8"],[9320,1,"9"],[9321,1,"10"],[9322,1,"11"],[9323,1,"12"],[9324,1,"13"],[9325,1,"14"],[9326,1,"15"],[9327,1,"16"],[9328,1,"17"],[9329,1,"18"],[9330,1,"19"],[9331,1,"20"],[9332,5,"(1)"],[9333,5,"(2)"],[9334,5,"(3)"],[9335,5,"(4)"],[9336,5,"(5)"],[9337,5,"(6)"],[9338,5,"(7)"],[9339,5,"(8)"],[9340,5,"(9)"],[9341,5,"(10)"],[9342,5,"(11)"],[9343,5,"(12)"],[9344,5,"(13)"],[9345,5,"(14)"],[9346,5,"(15)"],[9347,5,"(16)"],[9348,5,"(17)"],[9349,5,"(18)"],[9350,5,"(19)"],[9351,5,"(20)"],[[9352,9371],3],[9372,5,"(a)"],[9373,5,"(b)"],[9374,5,"(c)"],[9375,5,"(d)"],[9376,5,"(e)"],[9377,5,"(f)"],[9378,5,"(g)"],[9379,5,"(h)"],[9380,5,"(i)"],[9381,5,"(j)"],[9382,5,"(k)"],[9383,5,"(l)"],[9384,5,"(m)"],[9385,5,"(n)"],[9386,5,"(o)"],[9387,5,"(p)"],[9388,5,"(q)"],[9389,5,"(r)"],[9390,5,"(s)"],[9391,5,"(t)"],[9392,5,"(u)"],[9393,5,"(v)"],[9394,5,"(w)"],[9395,5,"(x)"],[9396,5,"(y)"],[9397,5,"(z)"],[9398,1,"a"],[9399,1,"b"],[9400,1,"c"],[9401,1,"d"],[9402,1,"e"],[9403,1,"f"],[9404,1,"g"],[9405,1,"h"],[9406,1,"i"],[9407,1,"j"],[9408,1,"k"],[9409,1,"l"],[9410,1,"m"],[9411,1,"n"],[9412,1,"o"],[9413,1,"p"],[9414,1,"q"],[9415,1,"r"],[9416,1,"s"],[9417,1,"t"],[9418,1,"u"],[9419,1,"v"],[9420,1,"w"],[9421,1,"x"],[9422,1,"y"],[9423,1,"z"],[9424,1,"a"],[9425,1,"b"],[9426,1,"c"],[9427,1,"d"],[9428,1,"e"],[9429,1,"f"],[9430,1,"g"],[9431,1,"h"],[9432,1,"i"],[9433,1,"j"],[9434,1,"k"],[9435,1,"l"],[9436,1,"m"],[9437,1,"n"],[9438,1,"o"],[9439,1,"p"],[9440,1,"q"],[9441,1,"r"],[9442,1,"s"],[9443,1,"t"],[9444,1,"u"],[9445,1,"v"],[9446,1,"w"],[9447,1,"x"],[9448,1,"y"],[9449,1,"z"],[9450,1,"0"],[[9451,9470],2],[9471,2],[[9472,9621],2],[[9622,9631],2],[[9632,9711],2],[[9712,9719],2],[[9720,9727],2],[[9728,9747],2],[[9748,9749],2],[[9750,9751],2],[9752,2],[9753,2],[[9754,9839],2],[[9840,9841],2],[[9842,9853],2],[[9854,9855],2],[[9856,9865],2],[[9866,9873],2],[[9874,9884],2],[9885,2],[[9886,9887],2],[[9888,9889],2],[[9890,9905],2],[9906,2],[[9907,9916],2],[[9917,9919],2],[[9920,9923],2],[[9924,9933],2],[9934,2],[[9935,9953],2],[9954,2],[9955,2],[[9956,9959],2],[[9960,9983],2],[9984,2],[[9985,9988],2],[9989,2],[[9990,9993],2],[[9994,9995],2],[[9996,10023],2],[10024,2],[[10025,10059],2],[10060,2],[10061,2],[10062,2],[[10063,10066],2],[[10067,10069],2],[10070,2],[10071,2],[[10072,10078],2],[[10079,10080],2],[[10081,10087],2],[[10088,10101],2],[[10102,10132],2],[[10133,10135],2],[[10136,10159],2],[10160,2],[[10161,10174],2],[10175,2],[[10176,10182],2],[[10183,10186],2],[10187,2],[10188,2],[10189,2],[[10190,10191],2],[[10192,10219],2],[[10220,10223],2],[[10224,10239],2],[[10240,10495],2],[[10496,10763],2],[10764,1,"∫∫∫∫"],[[10765,10867],2],[10868,5,"::="],[10869,5,"=="],[10870,5,"==="],[[10871,10971],2],[10972,1,"⫝̸"],[[10973,11007],2],[[11008,11021],2],[[11022,11027],2],[[11028,11034],2],[[11035,11039],2],[[11040,11043],2],[[11044,11084],2],[[11085,11087],2],[[11088,11092],2],[[11093,11097],2],[[11098,11123],2],[[11124,11125],3],[[11126,11157],2],[11158,3],[11159,2],[[11160,11193],2],[[11194,11196],2],[[11197,11208],2],[11209,2],[[11210,11217],2],[11218,2],[[11219,11243],2],[[11244,11247],2],[[11248,11262],2],[11263,2],[11264,1,"ⰰ"],[11265,1,"ⰱ"],[11266,1,"ⰲ"],[11267,1,"ⰳ"],[11268,1,"ⰴ"],[11269,1,"ⰵ"],[11270,1,"ⰶ"],[11271,1,"ⰷ"],[11272,1,"ⰸ"],[11273,1,"ⰹ"],[11274,1,"ⰺ"],[11275,1,"ⰻ"],[11276,1,"ⰼ"],[11277,1,"ⰽ"],[11278,1,"ⰾ"],[11279,1,"ⰿ"],[11280,1,"ⱀ"],[11281,1,"ⱁ"],[11282,1,"ⱂ"],[11283,1,"ⱃ"],[11284,1,"ⱄ"],[11285,1,"ⱅ"],[11286,1,"ⱆ"],[11287,1,"ⱇ"],[11288,1,"ⱈ"],[11289,1,"ⱉ"],[11290,1,"ⱊ"],[11291,1,"ⱋ"],[11292,1,"ⱌ"],[11293,1,"ⱍ"],[11294,1,"ⱎ"],[11295,1,"ⱏ"],[11296,1,"ⱐ"],[11297,1,"ⱑ"],[11298,1,"ⱒ"],[11299,1,"ⱓ"],[11300,1,"ⱔ"],[11301,1,"ⱕ"],[11302,1,"ⱖ"],[11303,1,"ⱗ"],[11304,1,"ⱘ"],[11305,1,"ⱙ"],[11306,1,"ⱚ"],[11307,1,"ⱛ"],[11308,1,"ⱜ"],[11309,1,"ⱝ"],[11310,1,"ⱞ"],[11311,3],[[11312,11358],2],[11359,3],[11360,1,"ⱡ"],[11361,2],[11362,1,"ɫ"],[11363,1,"ᵽ"],[11364,1,"ɽ"],[[11365,11366],2],[11367,1,"ⱨ"],[11368,2],[11369,1,"ⱪ"],[11370,2],[11371,1,"ⱬ"],[11372,2],[11373,1,"ɑ"],[11374,1,"ɱ"],[11375,1,"ɐ"],[11376,1,"ɒ"],[11377,2],[11378,1,"ⱳ"],[11379,2],[11380,2],[11381,1,"ⱶ"],[[11382,11383],2],[[11384,11387],2],[11388,1,"j"],[11389,1,"v"],[11390,1,"ȿ"],[11391,1,"ɀ"],[11392,1,"ⲁ"],[11393,2],[11394,1,"ⲃ"],[11395,2],[11396,1,"ⲅ"],[11397,2],[11398,1,"ⲇ"],[11399,2],[11400,1,"ⲉ"],[11401,2],[11402,1,"ⲋ"],[11403,2],[11404,1,"ⲍ"],[11405,2],[11406,1,"ⲏ"],[11407,2],[11408,1,"ⲑ"],[11409,2],[11410,1,"ⲓ"],[11411,2],[11412,1,"ⲕ"],[11413,2],[11414,1,"ⲗ"],[11415,2],[11416,1,"ⲙ"],[11417,2],[11418,1,"ⲛ"],[11419,2],[11420,1,"ⲝ"],[11421,2],[11422,1,"ⲟ"],[11423,2],[11424,1,"ⲡ"],[11425,2],[11426,1,"ⲣ"],[11427,2],[11428,1,"ⲥ"],[11429,2],[11430,1,"ⲧ"],[11431,2],[11432,1,"ⲩ"],[11433,2],[11434,1,"ⲫ"],[11435,2],[11436,1,"ⲭ"],[11437,2],[11438,1,"ⲯ"],[11439,2],[11440,1,"ⲱ"],[11441,2],[11442,1,"ⲳ"],[11443,2],[11444,1,"ⲵ"],[11445,2],[11446,1,"ⲷ"],[11447,2],[11448,1,"ⲹ"],[11449,2],[11450,1,"ⲻ"],[11451,2],[11452,1,"ⲽ"],[11453,2],[11454,1,"ⲿ"],[11455,2],[11456,1,"ⳁ"],[11457,2],[11458,1,"ⳃ"],[11459,2],[11460,1,"ⳅ"],[11461,2],[11462,1,"ⳇ"],[11463,2],[11464,1,"ⳉ"],[11465,2],[11466,1,"ⳋ"],[11467,2],[11468,1,"ⳍ"],[11469,2],[11470,1,"ⳏ"],[11471,2],[11472,1,"ⳑ"],[11473,2],[11474,1,"ⳓ"],[11475,2],[11476,1,"ⳕ"],[11477,2],[11478,1,"ⳗ"],[11479,2],[11480,1,"ⳙ"],[11481,2],[11482,1,"ⳛ"],[11483,2],[11484,1,"ⳝ"],[11485,2],[11486,1,"ⳟ"],[11487,2],[11488,1,"ⳡ"],[11489,2],[11490,1,"ⳣ"],[[11491,11492],2],[[11493,11498],2],[11499,1,"ⳬ"],[11500,2],[11501,1,"ⳮ"],[[11502,11505],2],[11506,1,"ⳳ"],[11507,2],[[11508,11512],3],[[11513,11519],2],[[11520,11557],2],[11558,3],[11559,2],[[11560,11564],3],[11565,2],[[11566,11567],3],[[11568,11621],2],[[11622,11623],2],[[11624,11630],3],[11631,1,"ⵡ"],[11632,2],[[11633,11646],3],[11647,2],[[11648,11670],2],[[11671,11679],3],[[11680,11686],2],[11687,3],[[11688,11694],2],[11695,3],[[11696,11702],2],[11703,3],[[11704,11710],2],[11711,3],[[11712,11718],2],[11719,3],[[11720,11726],2],[11727,3],[[11728,11734],2],[11735,3],[[11736,11742],2],[11743,3],[[11744,11775],2],[[11776,11799],2],[[11800,11803],2],[[11804,11805],2],[[11806,11822],2],[11823,2],[11824,2],[11825,2],[[11826,11835],2],[[11836,11842],2],[[11843,11844],2],[[11845,11849],2],[[11850,11854],2],[11855,2],[[11856,11858],2],[[11859,11903],3],[[11904,11929],2],[11930,3],[[11931,11934],2],[11935,1,"母"],[[11936,12018],2],[12019,1,"龟"],[[12020,12031],3],[12032,1,"一"],[12033,1,"丨"],[12034,1,"丶"],[12035,1,"丿"],[12036,1,"乙"],[12037,1,"亅"],[12038,1,"二"],[12039,1,"亠"],[12040,1,"人"],[12041,1,"儿"],[12042,1,"入"],[12043,1,"八"],[12044,1,"冂"],[12045,1,"冖"],[12046,1,"冫"],[12047,1,"几"],[12048,1,"凵"],[12049,1,"刀"],[12050,1,"力"],[12051,1,"勹"],[12052,1,"匕"],[12053,1,"匚"],[12054,1,"匸"],[12055,1,"十"],[12056,1,"卜"],[12057,1,"卩"],[12058,1,"厂"],[12059,1,"厶"],[12060,1,"又"],[12061,1,"口"],[12062,1,"囗"],[12063,1,"土"],[12064,1,"士"],[12065,1,"夂"],[12066,1,"夊"],[12067,1,"夕"],[12068,1,"大"],[12069,1,"女"],[12070,1,"子"],[12071,1,"宀"],[12072,1,"寸"],[12073,1,"小"],[12074,1,"尢"],[12075,1,"尸"],[12076,1,"屮"],[12077,1,"山"],[12078,1,"巛"],[12079,1,"工"],[12080,1,"己"],[12081,1,"巾"],[12082,1,"干"],[12083,1,"幺"],[12084,1,"广"],[12085,1,"廴"],[12086,1,"廾"],[12087,1,"弋"],[12088,1,"弓"],[12089,1,"彐"],[12090,1,"彡"],[12091,1,"彳"],[12092,1,"心"],[12093,1,"戈"],[12094,1,"戶"],[12095,1,"手"],[12096,1,"支"],[12097,1,"攴"],[12098,1,"文"],[12099,1,"斗"],[12100,1,"斤"],[12101,1,"方"],[12102,1,"无"],[12103,1,"日"],[12104,1,"曰"],[12105,1,"月"],[12106,1,"木"],[12107,1,"欠"],[12108,1,"止"],[12109,1,"歹"],[12110,1,"殳"],[12111,1,"毋"],[12112,1,"比"],[12113,1,"毛"],[12114,1,"氏"],[12115,1,"气"],[12116,1,"水"],[12117,1,"火"],[12118,1,"爪"],[12119,1,"父"],[12120,1,"爻"],[12121,1,"爿"],[12122,1,"片"],[12123,1,"牙"],[12124,1,"牛"],[12125,1,"犬"],[12126,1,"玄"],[12127,1,"玉"],[12128,1,"瓜"],[12129,1,"瓦"],[12130,1,"甘"],[12131,1,"生"],[12132,1,"用"],[12133,1,"田"],[12134,1,"疋"],[12135,1,"疒"],[12136,1,"癶"],[12137,1,"白"],[12138,1,"皮"],[12139,1,"皿"],[12140,1,"目"],[12141,1,"矛"],[12142,1,"矢"],[12143,1,"石"],[12144,1,"示"],[12145,1,"禸"],[12146,1,"禾"],[12147,1,"穴"],[12148,1,"立"],[12149,1,"竹"],[12150,1,"米"],[12151,1,"糸"],[12152,1,"缶"],[12153,1,"网"],[12154,1,"羊"],[12155,1,"羽"],[12156,1,"老"],[12157,1,"而"],[12158,1,"耒"],[12159,1,"耳"],[12160,1,"聿"],[12161,1,"肉"],[12162,1,"臣"],[12163,1,"自"],[12164,1,"至"],[12165,1,"臼"],[12166,1,"舌"],[12167,1,"舛"],[12168,1,"舟"],[12169,1,"艮"],[12170,1,"色"],[12171,1,"艸"],[12172,1,"虍"],[12173,1,"虫"],[12174,1,"血"],[12175,1,"行"],[12176,1,"衣"],[12177,1,"襾"],[12178,1,"見"],[12179,1,"角"],[12180,1,"言"],[12181,1,"谷"],[12182,1,"豆"],[12183,1,"豕"],[12184,1,"豸"],[12185,1,"貝"],[12186,1,"赤"],[12187,1,"走"],[12188,1,"足"],[12189,1,"身"],[12190,1,"車"],[12191,1,"辛"],[12192,1,"辰"],[12193,1,"辵"],[12194,1,"邑"],[12195,1,"酉"],[12196,1,"釆"],[12197,1,"里"],[12198,1,"金"],[12199,1,"長"],[12200,1,"門"],[12201,1,"阜"],[12202,1,"隶"],[12203,1,"隹"],[12204,1,"雨"],[12205,1,"靑"],[12206,1,"非"],[12207,1,"面"],[12208,1,"革"],[12209,1,"韋"],[12210,1,"韭"],[12211,1,"音"],[12212,1,"頁"],[12213,1,"風"],[12214,1,"飛"],[12215,1,"食"],[12216,1,"首"],[12217,1,"香"],[12218,1,"馬"],[12219,1,"骨"],[12220,1,"高"],[12221,1,"髟"],[12222,1,"鬥"],[12223,1,"鬯"],[12224,1,"鬲"],[12225,1,"鬼"],[12226,1,"魚"],[12227,1,"鳥"],[12228,1,"鹵"],[12229,1,"鹿"],[12230,1,"麥"],[12231,1,"麻"],[12232,1,"黃"],[12233,1,"黍"],[12234,1,"黑"],[12235,1,"黹"],[12236,1,"黽"],[12237,1,"鼎"],[12238,1,"鼓"],[12239,1,"鼠"],[12240,1,"鼻"],[12241,1,"齊"],[12242,1,"齒"],[12243,1,"龍"],[12244,1,"龜"],[12245,1,"龠"],[[12246,12271],3],[[12272,12283],3],[[12284,12287],3],[12288,5," "],[12289,2],[12290,1,"."],[[12291,12292],2],[[12293,12295],2],[[12296,12329],2],[[12330,12333],2],[[12334,12341],2],[12342,1,"〒"],[12343,2],[12344,1,"十"],[12345,1,"卄"],[12346,1,"卅"],[12347,2],[12348,2],[12349,2],[12350,2],[12351,2],[12352,3],[[12353,12436],2],[[12437,12438],2],[[12439,12440],3],[[12441,12442],2],[12443,5," ゙"],[12444,5," ゚"],[[12445,12446],2],[12447,1,"より"],[12448,2],[[12449,12542],2],[12543,1,"コト"],[[12544,12548],3],[[12549,12588],2],[12589,2],[12590,2],[12591,2],[12592,3],[12593,1,"ᄀ"],[12594,1,"ᄁ"],[12595,1,"ᆪ"],[12596,1,"ᄂ"],[12597,1,"ᆬ"],[12598,1,"ᆭ"],[12599,1,"ᄃ"],[12600,1,"ᄄ"],[12601,1,"ᄅ"],[12602,1,"ᆰ"],[12603,1,"ᆱ"],[12604,1,"ᆲ"],[12605,1,"ᆳ"],[12606,1,"ᆴ"],[12607,1,"ᆵ"],[12608,1,"ᄚ"],[12609,1,"ᄆ"],[12610,1,"ᄇ"],[12611,1,"ᄈ"],[12612,1,"ᄡ"],[12613,1,"ᄉ"],[12614,1,"ᄊ"],[12615,1,"ᄋ"],[12616,1,"ᄌ"],[12617,1,"ᄍ"],[12618,1,"ᄎ"],[12619,1,"ᄏ"],[12620,1,"ᄐ"],[12621,1,"ᄑ"],[12622,1,"ᄒ"],[12623,1,"ᅡ"],[12624,1,"ᅢ"],[12625,1,"ᅣ"],[12626,1,"ᅤ"],[12627,1,"ᅥ"],[12628,1,"ᅦ"],[12629,1,"ᅧ"],[12630,1,"ᅨ"],[12631,1,"ᅩ"],[12632,1,"ᅪ"],[12633,1,"ᅫ"],[12634,1,"ᅬ"],[12635,1,"ᅭ"],[12636,1,"ᅮ"],[12637,1,"ᅯ"],[12638,1,"ᅰ"],[12639,1,"ᅱ"],[12640,1,"ᅲ"],[12641,1,"ᅳ"],[12642,1,"ᅴ"],[12643,1,"ᅵ"],[12644,3],[12645,1,"ᄔ"],[12646,1,"ᄕ"],[12647,1,"ᇇ"],[12648,1,"ᇈ"],[12649,1,"ᇌ"],[12650,1,"ᇎ"],[12651,1,"ᇓ"],[12652,1,"ᇗ"],[12653,1,"ᇙ"],[12654,1,"ᄜ"],[12655,1,"ᇝ"],[12656,1,"ᇟ"],[12657,1,"ᄝ"],[12658,1,"ᄞ"],[12659,1,"ᄠ"],[12660,1,"ᄢ"],[12661,1,"ᄣ"],[12662,1,"ᄧ"],[12663,1,"ᄩ"],[12664,1,"ᄫ"],[12665,1,"ᄬ"],[12666,1,"ᄭ"],[12667,1,"ᄮ"],[12668,1,"ᄯ"],[12669,1,"ᄲ"],[12670,1,"ᄶ"],[12671,1,"ᅀ"],[12672,1,"ᅇ"],[12673,1,"ᅌ"],[12674,1,"ᇱ"],[12675,1,"ᇲ"],[12676,1,"ᅗ"],[12677,1,"ᅘ"],[12678,1,"ᅙ"],[12679,1,"ᆄ"],[12680,1,"ᆅ"],[12681,1,"ᆈ"],[12682,1,"ᆑ"],[12683,1,"ᆒ"],[12684,1,"ᆔ"],[12685,1,"ᆞ"],[12686,1,"ᆡ"],[12687,3],[[12688,12689],2],[12690,1,"一"],[12691,1,"二"],[12692,1,"三"],[12693,1,"四"],[12694,1,"上"],[12695,1,"中"],[12696,1,"下"],[12697,1,"甲"],[12698,1,"乙"],[12699,1,"丙"],[12700,1,"丁"],[12701,1,"天"],[12702,1,"地"],[12703,1,"人"],[[12704,12727],2],[[12728,12730],2],[[12731,12735],2],[[12736,12751],2],[[12752,12771],2],[[12772,12783],3],[[12784,12799],2],[12800,5,"(ᄀ)"],[12801,5,"(ᄂ)"],[12802,5,"(ᄃ)"],[12803,5,"(ᄅ)"],[12804,5,"(ᄆ)"],[12805,5,"(ᄇ)"],[12806,5,"(ᄉ)"],[12807,5,"(ᄋ)"],[12808,5,"(ᄌ)"],[12809,5,"(ᄎ)"],[12810,5,"(ᄏ)"],[12811,5,"(ᄐ)"],[12812,5,"(ᄑ)"],[12813,5,"(ᄒ)"],[12814,5,"(가)"],[12815,5,"(나)"],[12816,5,"(다)"],[12817,5,"(라)"],[12818,5,"(마)"],[12819,5,"(바)"],[12820,5,"(사)"],[12821,5,"(아)"],[12822,5,"(자)"],[12823,5,"(차)"],[12824,5,"(카)"],[12825,5,"(타)"],[12826,5,"(파)"],[12827,5,"(하)"],[12828,5,"(주)"],[12829,5,"(오전)"],[12830,5,"(오후)"],[12831,3],[12832,5,"(一)"],[12833,5,"(二)"],[12834,5,"(三)"],[12835,5,"(四)"],[12836,5,"(五)"],[12837,5,"(六)"],[12838,5,"(七)"],[12839,5,"(八)"],[12840,5,"(九)"],[12841,5,"(十)"],[12842,5,"(月)"],[12843,5,"(火)"],[12844,5,"(水)"],[12845,5,"(木)"],[12846,5,"(金)"],[12847,5,"(土)"],[12848,5,"(日)"],[12849,5,"(株)"],[12850,5,"(有)"],[12851,5,"(社)"],[12852,5,"(名)"],[12853,5,"(特)"],[12854,5,"(財)"],[12855,5,"(祝)"],[12856,5,"(労)"],[12857,5,"(代)"],[12858,5,"(呼)"],[12859,5,"(学)"],[12860,5,"(監)"],[12861,5,"(企)"],[12862,5,"(資)"],[12863,5,"(協)"],[12864,5,"(祭)"],[12865,5,"(休)"],[12866,5,"(自)"],[12867,5,"(至)"],[12868,1,"問"],[12869,1,"幼"],[12870,1,"文"],[12871,1,"箏"],[[12872,12879],2],[12880,1,"pte"],[12881,1,"21"],[12882,1,"22"],[12883,1,"23"],[12884,1,"24"],[12885,1,"25"],[12886,1,"26"],[12887,1,"27"],[12888,1,"28"],[12889,1,"29"],[12890,1,"30"],[12891,1,"31"],[12892,1,"32"],[12893,1,"33"],[12894,1,"34"],[12895,1,"35"],[12896,1,"ᄀ"],[12897,1,"ᄂ"],[12898,1,"ᄃ"],[12899,1,"ᄅ"],[12900,1,"ᄆ"],[12901,1,"ᄇ"],[12902,1,"ᄉ"],[12903,1,"ᄋ"],[12904,1,"ᄌ"],[12905,1,"ᄎ"],[12906,1,"ᄏ"],[12907,1,"ᄐ"],[12908,1,"ᄑ"],[12909,1,"ᄒ"],[12910,1,"가"],[12911,1,"나"],[12912,1,"다"],[12913,1,"라"],[12914,1,"마"],[12915,1,"바"],[12916,1,"사"],[12917,1,"아"],[12918,1,"자"],[12919,1,"차"],[12920,1,"카"],[12921,1,"타"],[12922,1,"파"],[12923,1,"하"],[12924,1,"참고"],[12925,1,"주의"],[12926,1,"우"],[12927,2],[12928,1,"一"],[12929,1,"二"],[12930,1,"三"],[12931,1,"四"],[12932,1,"五"],[12933,1,"六"],[12934,1,"七"],[12935,1,"八"],[12936,1,"九"],[12937,1,"十"],[12938,1,"月"],[12939,1,"火"],[12940,1,"水"],[12941,1,"木"],[12942,1,"金"],[12943,1,"土"],[12944,1,"日"],[12945,1,"株"],[12946,1,"有"],[12947,1,"社"],[12948,1,"名"],[12949,1,"特"],[12950,1,"財"],[12951,1,"祝"],[12952,1,"労"],[12953,1,"秘"],[12954,1,"男"],[12955,1,"女"],[12956,1,"適"],[12957,1,"優"],[12958,1,"印"],[12959,1,"注"],[12960,1,"項"],[12961,1,"休"],[12962,1,"写"],[12963,1,"正"],[12964,1,"上"],[12965,1,"中"],[12966,1,"下"],[12967,1,"左"],[12968,1,"右"],[12969,1,"医"],[12970,1,"宗"],[12971,1,"学"],[12972,1,"監"],[12973,1,"企"],[12974,1,"資"],[12975,1,"協"],[12976,1,"夜"],[12977,1,"36"],[12978,1,"37"],[12979,1,"38"],[12980,1,"39"],[12981,1,"40"],[12982,1,"41"],[12983,1,"42"],[12984,1,"43"],[12985,1,"44"],[12986,1,"45"],[12987,1,"46"],[12988,1,"47"],[12989,1,"48"],[12990,1,"49"],[12991,1,"50"],[12992,1,"1月"],[12993,1,"2月"],[12994,1,"3月"],[12995,1,"4月"],[12996,1,"5月"],[12997,1,"6月"],[12998,1,"7月"],[12999,1,"8月"],[13000,1,"9月"],[13001,1,"10月"],[13002,1,"11月"],[13003,1,"12月"],[13004,1,"hg"],[13005,1,"erg"],[13006,1,"ev"],[13007,1,"ltd"],[13008,1,"ア"],[13009,1,"イ"],[13010,1,"ウ"],[13011,1,"エ"],[13012,1,"オ"],[13013,1,"カ"],[13014,1,"キ"],[13015,1,"ク"],[13016,1,"ケ"],[13017,1,"コ"],[13018,1,"サ"],[13019,1,"シ"],[13020,1,"ス"],[13021,1,"セ"],[13022,1,"ソ"],[13023,1,"タ"],[13024,1,"チ"],[13025,1,"ツ"],[13026,1,"テ"],[13027,1,"ト"],[13028,1,"ナ"],[13029,1,"ニ"],[13030,1,"ヌ"],[13031,1,"ネ"],[13032,1,"ノ"],[13033,1,"ハ"],[13034,1,"ヒ"],[13035,1,"フ"],[13036,1,"ヘ"],[13037,1,"ホ"],[13038,1,"マ"],[13039,1,"ミ"],[13040,1,"ム"],[13041,1,"メ"],[13042,1,"モ"],[13043,1,"ヤ"],[13044,1,"ユ"],[13045,1,"ヨ"],[13046,1,"ラ"],[13047,1,"リ"],[13048,1,"ル"],[13049,1,"レ"],[13050,1,"ロ"],[13051,1,"ワ"],[13052,1,"ヰ"],[13053,1,"ヱ"],[13054,1,"ヲ"],[13055,1,"令和"],[13056,1,"アパート"],[13057,1,"アルファ"],[13058,1,"アンペア"],[13059,1,"アール"],[13060,1,"イニング"],[13061,1,"インチ"],[13062,1,"ウォン"],[13063,1,"エスクード"],[13064,1,"エーカー"],[13065,1,"オンス"],[13066,1,"オーム"],[13067,1,"カイリ"],[13068,1,"カラット"],[13069,1,"カロリー"],[13070,1,"ガロン"],[13071,1,"ガンマ"],[13072,1,"ギガ"],[13073,1,"ギニー"],[13074,1,"キュリー"],[13075,1,"ギルダー"],[13076,1,"キロ"],[13077,1,"キログラム"],[13078,1,"キロメートル"],[13079,1,"キロワット"],[13080,1,"グラム"],[13081,1,"グラムトン"],[13082,1,"クルゼイロ"],[13083,1,"クローネ"],[13084,1,"ケース"],[13085,1,"コルナ"],[13086,1,"コーポ"],[13087,1,"サイクル"],[13088,1,"サンチーム"],[13089,1,"シリング"],[13090,1,"センチ"],[13091,1,"セント"],[13092,1,"ダース"],[13093,1,"デシ"],[13094,1,"ドル"],[13095,1,"トン"],[13096,1,"ナノ"],[13097,1,"ノット"],[13098,1,"ハイツ"],[13099,1,"パーセント"],[13100,1,"パーツ"],[13101,1,"バーレル"],[13102,1,"ピアストル"],[13103,1,"ピクル"],[13104,1,"ピコ"],[13105,1,"ビル"],[13106,1,"ファラッド"],[13107,1,"フィート"],[13108,1,"ブッシェル"],[13109,1,"フラン"],[13110,1,"ヘクタール"],[13111,1,"ペソ"],[13112,1,"ペニヒ"],[13113,1,"ヘルツ"],[13114,1,"ペンス"],[13115,1,"ページ"],[13116,1,"ベータ"],[13117,1,"ポイント"],[13118,1,"ボルト"],[13119,1,"ホン"],[13120,1,"ポンド"],[13121,1,"ホール"],[13122,1,"ホーン"],[13123,1,"マイクロ"],[13124,1,"マイル"],[13125,1,"マッハ"],[13126,1,"マルク"],[13127,1,"マンション"],[13128,1,"ミクロン"],[13129,1,"ミリ"],[13130,1,"ミリバール"],[13131,1,"メガ"],[13132,1,"メガトン"],[13133,1,"メートル"],[13134,1,"ヤード"],[13135,1,"ヤール"],[13136,1,"ユアン"],[13137,1,"リットル"],[13138,1,"リラ"],[13139,1,"ルピー"],[13140,1,"ルーブル"],[13141,1,"レム"],[13142,1,"レントゲン"],[13143,1,"ワット"],[13144,1,"0点"],[13145,1,"1点"],[13146,1,"2点"],[13147,1,"3点"],[13148,1,"4点"],[13149,1,"5点"],[13150,1,"6点"],[13151,1,"7点"],[13152,1,"8点"],[13153,1,"9点"],[13154,1,"10点"],[13155,1,"11点"],[13156,1,"12点"],[13157,1,"13点"],[13158,1,"14点"],[13159,1,"15点"],[13160,1,"16点"],[13161,1,"17点"],[13162,1,"18点"],[13163,1,"19点"],[13164,1,"20点"],[13165,1,"21点"],[13166,1,"22点"],[13167,1,"23点"],[13168,1,"24点"],[13169,1,"hpa"],[13170,1,"da"],[13171,1,"au"],[13172,1,"bar"],[13173,1,"ov"],[13174,1,"pc"],[13175,1,"dm"],[13176,1,"dm2"],[13177,1,"dm3"],[13178,1,"iu"],[13179,1,"平成"],[13180,1,"昭和"],[13181,1,"大正"],[13182,1,"明治"],[13183,1,"株式会社"],[13184,1,"pa"],[13185,1,"na"],[13186,1,"μa"],[13187,1,"ma"],[13188,1,"ka"],[13189,1,"kb"],[13190,1,"mb"],[13191,1,"gb"],[13192,1,"cal"],[13193,1,"kcal"],[13194,1,"pf"],[13195,1,"nf"],[13196,1,"μf"],[13197,1,"μg"],[13198,1,"mg"],[13199,1,"kg"],[13200,1,"hz"],[13201,1,"khz"],[13202,1,"mhz"],[13203,1,"ghz"],[13204,1,"thz"],[13205,1,"μl"],[13206,1,"ml"],[13207,1,"dl"],[13208,1,"kl"],[13209,1,"fm"],[13210,1,"nm"],[13211,1,"μm"],[13212,1,"mm"],[13213,1,"cm"],[13214,1,"km"],[13215,1,"mm2"],[13216,1,"cm2"],[13217,1,"m2"],[13218,1,"km2"],[13219,1,"mm3"],[13220,1,"cm3"],[13221,1,"m3"],[13222,1,"km3"],[13223,1,"m∕s"],[13224,1,"m∕s2"],[13225,1,"pa"],[13226,1,"kpa"],[13227,1,"mpa"],[13228,1,"gpa"],[13229,1,"rad"],[13230,1,"rad∕s"],[13231,1,"rad∕s2"],[13232,1,"ps"],[13233,1,"ns"],[13234,1,"μs"],[13235,1,"ms"],[13236,1,"pv"],[13237,1,"nv"],[13238,1,"μv"],[13239,1,"mv"],[13240,1,"kv"],[13241,1,"mv"],[13242,1,"pw"],[13243,1,"nw"],[13244,1,"μw"],[13245,1,"mw"],[13246,1,"kw"],[13247,1,"mw"],[13248,1,"kω"],[13249,1,"mω"],[13250,3],[13251,1,"bq"],[13252,1,"cc"],[13253,1,"cd"],[13254,1,"c∕kg"],[13255,3],[13256,1,"db"],[13257,1,"gy"],[13258,1,"ha"],[13259,1,"hp"],[13260,1,"in"],[13261,1,"kk"],[13262,1,"km"],[13263,1,"kt"],[13264,1,"lm"],[13265,1,"ln"],[13266,1,"log"],[13267,1,"lx"],[13268,1,"mb"],[13269,1,"mil"],[13270,1,"mol"],[13271,1,"ph"],[13272,3],[13273,1,"ppm"],[13274,1,"pr"],[13275,1,"sr"],[13276,1,"sv"],[13277,1,"wb"],[13278,1,"v∕m"],[13279,1,"a∕m"],[13280,1,"1日"],[13281,1,"2日"],[13282,1,"3日"],[13283,1,"4日"],[13284,1,"5日"],[13285,1,"6日"],[13286,1,"7日"],[13287,1,"8日"],[13288,1,"9日"],[13289,1,"10日"],[13290,1,"11日"],[13291,1,"12日"],[13292,1,"13日"],[13293,1,"14日"],[13294,1,"15日"],[13295,1,"16日"],[13296,1,"17日"],[13297,1,"18日"],[13298,1,"19日"],[13299,1,"20日"],[13300,1,"21日"],[13301,1,"22日"],[13302,1,"23日"],[13303,1,"24日"],[13304,1,"25日"],[13305,1,"26日"],[13306,1,"27日"],[13307,1,"28日"],[13308,1,"29日"],[13309,1,"30日"],[13310,1,"31日"],[13311,1,"gal"],[[13312,19893],2],[[19894,19903],2],[[19904,19967],2],[[19968,40869],2],[[40870,40891],2],[[40892,40899],2],[[40900,40907],2],[40908,2],[[40909,40917],2],[[40918,40938],2],[[40939,40943],2],[[40944,40956],2],[[40957,40959],3],[[40960,42124],2],[[42125,42127],3],[[42128,42145],2],[[42146,42147],2],[[42148,42163],2],[42164,2],[[42165,42176],2],[42177,2],[[42178,42180],2],[42181,2],[42182,2],[[42183,42191],3],[[42192,42237],2],[[42238,42239],2],[[42240,42508],2],[[42509,42511],2],[[42512,42539],2],[[42540,42559],3],[42560,1,"ꙁ"],[42561,2],[42562,1,"ꙃ"],[42563,2],[42564,1,"ꙅ"],[42565,2],[42566,1,"ꙇ"],[42567,2],[42568,1,"ꙉ"],[42569,2],[42570,1,"ꙋ"],[42571,2],[42572,1,"ꙍ"],[42573,2],[42574,1,"ꙏ"],[42575,2],[42576,1,"ꙑ"],[42577,2],[42578,1,"ꙓ"],[42579,2],[42580,1,"ꙕ"],[42581,2],[42582,1,"ꙗ"],[42583,2],[42584,1,"ꙙ"],[42585,2],[42586,1,"ꙛ"],[42587,2],[42588,1,"ꙝ"],[42589,2],[42590,1,"ꙟ"],[42591,2],[42592,1,"ꙡ"],[42593,2],[42594,1,"ꙣ"],[42595,2],[42596,1,"ꙥ"],[42597,2],[42598,1,"ꙧ"],[42599,2],[42600,1,"ꙩ"],[42601,2],[42602,1,"ꙫ"],[42603,2],[42604,1,"ꙭ"],[[42605,42607],2],[[42608,42611],2],[[42612,42619],2],[[42620,42621],2],[42622,2],[42623,2],[42624,1,"ꚁ"],[42625,2],[42626,1,"ꚃ"],[42627,2],[42628,1,"ꚅ"],[42629,2],[42630,1,"ꚇ"],[42631,2],[42632,1,"ꚉ"],[42633,2],[42634,1,"ꚋ"],[42635,2],[42636,1,"ꚍ"],[42637,2],[42638,1,"ꚏ"],[42639,2],[42640,1,"ꚑ"],[42641,2],[42642,1,"ꚓ"],[42643,2],[42644,1,"ꚕ"],[42645,2],[42646,1,"ꚗ"],[42647,2],[42648,1,"ꚙ"],[42649,2],[42650,1,"ꚛ"],[42651,2],[42652,1,"ъ"],[42653,1,"ь"],[42654,2],[42655,2],[[42656,42725],2],[[42726,42735],2],[[42736,42737],2],[[42738,42743],2],[[42744,42751],3],[[42752,42774],2],[[42775,42778],2],[[42779,42783],2],[[42784,42785],2],[42786,1,"ꜣ"],[42787,2],[42788,1,"ꜥ"],[42789,2],[42790,1,"ꜧ"],[42791,2],[42792,1,"ꜩ"],[42793,2],[42794,1,"ꜫ"],[42795,2],[42796,1,"ꜭ"],[42797,2],[42798,1,"ꜯ"],[[42799,42801],2],[42802,1,"ꜳ"],[42803,2],[42804,1,"ꜵ"],[42805,2],[42806,1,"ꜷ"],[42807,2],[42808,1,"ꜹ"],[42809,2],[42810,1,"ꜻ"],[42811,2],[42812,1,"ꜽ"],[42813,2],[42814,1,"ꜿ"],[42815,2],[42816,1,"ꝁ"],[42817,2],[42818,1,"ꝃ"],[42819,2],[42820,1,"ꝅ"],[42821,2],[42822,1,"ꝇ"],[42823,2],[42824,1,"ꝉ"],[42825,2],[42826,1,"ꝋ"],[42827,2],[42828,1,"ꝍ"],[42829,2],[42830,1,"ꝏ"],[42831,2],[42832,1,"ꝑ"],[42833,2],[42834,1,"ꝓ"],[42835,2],[42836,1,"ꝕ"],[42837,2],[42838,1,"ꝗ"],[42839,2],[42840,1,"ꝙ"],[42841,2],[42842,1,"ꝛ"],[42843,2],[42844,1,"ꝝ"],[42845,2],[42846,1,"ꝟ"],[42847,2],[42848,1,"ꝡ"],[42849,2],[42850,1,"ꝣ"],[42851,2],[42852,1,"ꝥ"],[42853,2],[42854,1,"ꝧ"],[42855,2],[42856,1,"ꝩ"],[42857,2],[42858,1,"ꝫ"],[42859,2],[42860,1,"ꝭ"],[42861,2],[42862,1,"ꝯ"],[42863,2],[42864,1,"ꝯ"],[[42865,42872],2],[42873,1,"ꝺ"],[42874,2],[42875,1,"ꝼ"],[42876,2],[42877,1,"ᵹ"],[42878,1,"ꝿ"],[42879,2],[42880,1,"ꞁ"],[42881,2],[42882,1,"ꞃ"],[42883,2],[42884,1,"ꞅ"],[42885,2],[42886,1,"ꞇ"],[[42887,42888],2],[[42889,42890],2],[42891,1,"ꞌ"],[42892,2],[42893,1,"ɥ"],[42894,2],[42895,2],[42896,1,"ꞑ"],[42897,2],[42898,1,"ꞓ"],[42899,2],[[42900,42901],2],[42902,1,"ꞗ"],[42903,2],[42904,1,"ꞙ"],[42905,2],[42906,1,"ꞛ"],[42907,2],[42908,1,"ꞝ"],[42909,2],[42910,1,"ꞟ"],[42911,2],[42912,1,"ꞡ"],[42913,2],[42914,1,"ꞣ"],[42915,2],[42916,1,"ꞥ"],[42917,2],[42918,1,"ꞧ"],[42919,2],[42920,1,"ꞩ"],[42921,2],[42922,1,"ɦ"],[42923,1,"ɜ"],[42924,1,"ɡ"],[42925,1,"ɬ"],[42926,1,"ɪ"],[42927,2],[42928,1,"ʞ"],[42929,1,"ʇ"],[42930,1,"ʝ"],[42931,1,"ꭓ"],[42932,1,"ꞵ"],[42933,2],[42934,1,"ꞷ"],[42935,2],[42936,1,"ꞹ"],[42937,2],[42938,1,"ꞻ"],[42939,2],[42940,1,"ꞽ"],[42941,2],[42942,1,"ꞿ"],[42943,2],[[42944,42945],3],[42946,1,"ꟃ"],[42947,2],[42948,1,"ꞔ"],[42949,1,"ʂ"],[42950,1,"ᶎ"],[42951,1,"ꟈ"],[42952,2],[42953,1,"ꟊ"],[42954,2],[[42955,42996],3],[42997,1,"ꟶ"],[42998,2],[42999,2],[43000,1,"ħ"],[43001,1,"œ"],[43002,2],[[43003,43007],2],[[43008,43047],2],[[43048,43051],2],[43052,2],[[43053,43055],3],[[43056,43065],2],[[43066,43071],3],[[43072,43123],2],[[43124,43127],2],[[43128,43135],3],[[43136,43204],2],[43205,2],[[43206,43213],3],[[43214,43215],2],[[43216,43225],2],[[43226,43231],3],[[43232,43255],2],[[43256,43258],2],[43259,2],[43260,2],[43261,2],[[43262,43263],2],[[43264,43309],2],[[43310,43311],2],[[43312,43347],2],[[43348,43358],3],[43359,2],[[43360,43388],2],[[43389,43391],3],[[43392,43456],2],[[43457,43469],2],[43470,3],[[43471,43481],2],[[43482,43485],3],[[43486,43487],2],[[43488,43518],2],[43519,3],[[43520,43574],2],[[43575,43583],3],[[43584,43597],2],[[43598,43599],3],[[43600,43609],2],[[43610,43611],3],[[43612,43615],2],[[43616,43638],2],[[43639,43641],2],[[43642,43643],2],[[43644,43647],2],[[43648,43714],2],[[43715,43738],3],[[43739,43741],2],[[43742,43743],2],[[43744,43759],2],[[43760,43761],2],[[43762,43766],2],[[43767,43776],3],[[43777,43782],2],[[43783,43784],3],[[43785,43790],2],[[43791,43792],3],[[43793,43798],2],[[43799,43807],3],[[43808,43814],2],[43815,3],[[43816,43822],2],[43823,3],[[43824,43866],2],[43867,2],[43868,1,"ꜧ"],[43869,1,"ꬷ"],[43870,1,"ɫ"],[43871,1,"ꭒ"],[[43872,43875],2],[[43876,43877],2],[[43878,43879],2],[43880,2],[43881,1,"ʍ"],[[43882,43883],2],[[43884,43887],3],[43888,1,"Ꭰ"],[43889,1,"Ꭱ"],[43890,1,"Ꭲ"],[43891,1,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"],[43960,1,"Ꮸ"],[43961,1,"Ꮹ"],[43962,1,"Ꮺ"],[43963,1,"Ꮻ"],[43964,1,"Ꮼ"],[43965,1,"Ꮽ"],[43966,1,"Ꮾ"],[43967,1,"Ꮿ"],[[43968,44010],2],[44011,2],[[44012,44013],2],[[44014,44015],3],[[44016,44025],2],[[44026,44031],3],[[44032,55203],2],[[55204,55215],3],[[55216,55238],2],[[55239,55242],3],[[55243,55291],2],[[55292,55295],3],[[55296,57343],3],[[57344,63743],3],[63744,1,"豈"],[63745,1,"更"],[63746,1,"車"],[63747,1,"賈"],[63748,1,"滑"],[63749,1,"串"],[63750,1,"句"],[[63751,63752],1,"龜"],[63753,1,"契"],[63754,1,"金"],[63755,1,"喇"],[63756,1,"奈"],[63757,1,"懶"],[63758,1,"癩"],[63759,1,"羅"],[63760,1,"蘿"],[63761,1,"螺"],[63762,1,"裸"],[63763,1,"邏"],[63764,1,"樂"],[63765,1,"洛"],[63766,1,"烙"],[63767,1,"珞"],[63768,1,"落"],[63769,1,"酪"],[63770,1,"駱"],[63771,1,"亂"],[63772,1,"卵"],[63773,1,"欄"],[63774,1,"爛"],[63775,1,"蘭"],[63776,1,"鸞"],[63777,1,"嵐"],[63778,1,"濫"],[63779,1,"藍"],[63780,1,"襤"],[63781,1,"拉"],[63782,1,"臘"],[63783,1,"蠟"],[63784,1,"廊"],[63785,1,"朗"],[63786,1,"浪"],[63787,1,"狼"],[63788,1,"郎"],[63789,1,"來"],[63790,1,"冷"],[63791,1,"勞"],[63792,1,"擄"],[63793,1,"櫓"],[63794,1,"爐"],[63795,1,"盧"],[63796,1,"老"],[63797,1,"蘆"],[63798,1,"虜"],[63799,1,"路"],[63800,1,"露"],[63801,1,"魯"],[63802,1,"鷺"],[63803,1,"碌"],[63804,1,"祿"],[63805,1,"綠"],[63806,1,"菉"],[63807,1,"錄"],[63808,1,"鹿"],[63809,1,"論"],[63810,1,"壟"],[63811,1,"弄"],[63812,1,"籠"],[63813,1,"聾"],[63814,1,"牢"],[63815,1,"磊"],[63816,1,"賂"],[63817,1,"雷"],[63818,1,"壘"],[63819,1,"屢"],[63820,1,"樓"],[63821,1,"淚"],[63822,1,"漏"],[63823,1,"累"],[63824,1,"縷"],[63825,1,"陋"],[63826,1,"勒"],[63827,1,"肋"],[63828,1,"凜"],[63829,1,"凌"],[63830,1,"稜"],[63831,1,"綾"],[63832,1,"菱"],[63833,1,"陵"],[63834,1,"讀"],[63835,1,"拏"],[63836,1,"樂"],[63837,1,"諾"],[63838,1,"丹"],[63839,1,"寧"],[63840,1,"怒"],[63841,1,"率"],[63842,1,"異"],[63843,1,"北"],[63844,1,"磻"],[63845,1,"便"],[63846,1,"復"],[63847,1,"不"],[63848,1,"泌"],[63849,1,"數"],[63850,1,"索"],[63851,1,"參"],[63852,1,"塞"],[63853,1,"省"],[63854,1,"葉"],[63855,1,"說"],[63856,1,"殺"],[63857,1,"辰"],[63858,1,"沈"],[63859,1,"拾"],[63860,1,"若"],[63861,1,"掠"],[63862,1,"略"],[63863,1,"亮"],[63864,1,"兩"],[63865,1,"凉"],[63866,1,"梁"],[63867,1,"糧"],[63868,1,"良"],[63869,1,"諒"],[63870,1,"量"],[63871,1,"勵"],[63872,1,"呂"],[63873,1,"女"],[63874,1,"廬"],[63875,1,"旅"],[63876,1,"濾"],[63877,1,"礪"],[63878,1,"閭"],[63879,1,"驪"],[63880,1,"麗"],[63881,1,"黎"],[63882,1,"力"],[63883,1,"曆"],[63884,1,"歷"],[63885,1,"轢"],[63886,1,"年"],[63887,1,"憐"],[63888,1,"戀"],[63889,1,"撚"],[63890,1,"漣"],[63891,1,"煉"],[63892,1,"璉"],[63893,1,"秊"],[63894,1,"練"],[63895,1,"聯"],[63896,1,"輦"],[63897,1,"蓮"],[63898,1,"連"],[63899,1,"鍊"],[63900,1,"列"],[63901,1,"劣"],[63902,1,"咽"],[63903,1,"烈"],[63904,1,"裂"],[63905,1,"說"],[63906,1,"廉"],[63907,1,"念"],[63908,1,"捻"],[63909,1,"殮"],[63910,1,"簾"],[63911,1,"獵"],[63912,1,"令"],[63913,1,"囹"],[63914,1,"寧"],[63915,1,"嶺"],[63916,1,"怜"],[63917,1,"玲"],[63918,1,"瑩"],[63919,1,"羚"],[63920,1,"聆"],[63921,1,"鈴"],[63922,1,"零"],[63923,1,"靈"],[63924,1,"領"],[63925,1,"例"],[63926,1,"禮"],[63927,1,"醴"],[63928,1,"隸"],[63929,1,"惡"],[63930,1,"了"],[63931,1,"僚"],[63932,1,"寮"],[63933,1,"尿"],[63934,1,"料"],[63935,1,"樂"],[63936,1,"燎"],[63937,1,"療"],[63938,1,"蓼"],[63939,1,"遼"],[63940,1,"龍"],[63941,1,"暈"],[63942,1,"阮"],[63943,1,"劉"],[63944,1,"杻"],[63945,1,"柳"],[63946,1,"流"],[63947,1,"溜"],[63948,1,"琉"],[63949,1,"留"],[63950,1,"硫"],[63951,1,"紐"],[63952,1,"類"],[63953,1,"六"],[63954,1,"戮"],[63955,1,"陸"],[63956,1,"倫"],[63957,1,"崙"],[63958,1,"淪"],[63959,1,"輪"],[63960,1,"律"],[63961,1,"慄"],[63962,1,"栗"],[63963,1,"率"],[63964,1,"隆"],[63965,1,"利"],[63966,1,"吏"],[63967,1,"履"],[63968,1,"易"],[63969,1,"李"],[63970,1,"梨"],[63971,1,"泥"],[63972,1,"理"],[63973,1,"痢"],[63974,1,"罹"],[63975,1,"裏"],[63976,1,"裡"],[63977,1,"里"],[63978,1,"離"],[63979,1,"匿"],[63980,1,"溺"],[63981,1,"吝"],[63982,1,"燐"],[63983,1,"璘"],[63984,1,"藺"],[63985,1,"隣"],[63986,1,"鱗"],[63987,1,"麟"],[63988,1,"林"],[63989,1,"淋"],[63990,1,"臨"],[63991,1,"立"],[63992,1,"笠"],[63993,1,"粒"],[63994,1,"狀"],[63995,1,"炙"],[63996,1,"識"],[63997,1,"什"],[63998,1,"茶"],[63999,1,"刺"],[64000,1,"切"],[64001,1,"度"],[64002,1,"拓"],[64003,1,"糖"],[64004,1,"宅"],[64005,1,"洞"],[64006,1,"暴"],[64007,1,"輻"],[64008,1,"行"],[64009,1,"降"],[64010,1,"見"],[64011,1,"廓"],[64012,1,"兀"],[64013,1,"嗀"],[[64014,64015],2],[64016,1,"塚"],[64017,2],[64018,1,"晴"],[[64019,64020],2],[64021,1,"凞"],[64022,1,"猪"],[64023,1,"益"],[64024,1,"礼"],[64025,1,"神"],[64026,1,"祥"],[64027,1,"福"],[64028,1,"靖"],[64029,1,"精"],[64030,1,"羽"],[64031,2],[64032,1,"蘒"],[64033,2],[64034,1,"諸"],[[64035,64036],2],[64037,1,"逸"],[64038,1,"都"],[[64039,64041],2],[64042,1,"飯"],[64043,1,"飼"],[64044,1,"館"],[64045,1,"鶴"],[64046,1,"郞"],[64047,1,"隷"],[64048,1,"侮"],[64049,1,"僧"],[64050,1,"免"],[64051,1,"勉"],[64052,1,"勤"],[64053,1,"卑"],[64054,1,"喝"],[64055,1,"嘆"],[64056,1,"器"],[64057,1,"塀"],[64058,1,"墨"],[64059,1,"層"],[64060,1,"屮"],[64061,1,"悔"],[64062,1,"慨"],[64063,1,"憎"],[64064,1,"懲"],[64065,1,"敏"],[64066,1,"既"],[64067,1,"暑"],[64068,1,"梅"],[64069,1,"海"],[64070,1,"渚"],[64071,1,"漢"],[64072,1,"煮"],[64073,1,"爫"],[64074,1,"琢"],[64075,1,"碑"],[64076,1,"社"],[64077,1,"祉"],[64078,1,"祈"],[64079,1,"祐"],[64080,1,"祖"],[64081,1,"祝"],[64082,1,"禍"],[64083,1,"禎"],[64084,1,"穀"],[64085,1,"突"],[64086,1,"節"],[64087,1,"練"],[64088,1,"縉"],[64089,1,"繁"],[64090,1,"署"],[64091,1,"者"],[64092,1,"臭"],[[64093,64094],1,"艹"],[64095,1,"著"],[64096,1,"褐"],[64097,1,"視"],[64098,1,"謁"],[64099,1,"謹"],[64100,1,"賓"],[64101,1,"贈"],[64102,1,"辶"],[64103,1,"逸"],[64104,1,"難"],[64105,1,"響"],[64106,1,"頻"],[64107,1,"恵"],[64108,1,"𤋮"],[64109,1,"舘"],[[64110,64111],3],[64112,1,"並"],[64113,1,"况"],[64114,1,"全"],[64115,1,"侀"],[64116,1,"充"],[64117,1,"冀"],[64118,1,"勇"],[64119,1,"勺"],[64120,1,"喝"],[64121,1,"啕"],[64122,1,"喙"],[64123,1,"嗢"],[64124,1,"塚"],[64125,1,"墳"],[64126,1,"奄"],[64127,1,"奔"],[64128,1,"婢"],[64129,1,"嬨"],[64130,1,"廒"],[64131,1,"廙"],[64132,1,"彩"],[64133,1,"徭"],[64134,1,"惘"],[64135,1,"慎"],[64136,1,"愈"],[64137,1,"憎"],[64138,1,"慠"],[64139,1,"懲"],[64140,1,"戴"],[64141,1,"揄"],[64142,1,"搜"],[64143,1,"摒"],[64144,1,"敖"],[64145,1,"晴"],[64146,1,"朗"],[64147,1,"望"],[64148,1,"杖"],[64149,1,"歹"],[64150,1,"殺"],[64151,1,"流"],[64152,1,"滛"],[64153,1,"滋"],[64154,1,"漢"],[64155,1,"瀞"],[64156,1,"煮"],[64157,1,"瞧"],[64158,1,"爵"],[64159,1,"犯"],[64160,1,"猪"],[64161,1,"瑱"],[64162,1,"甆"],[64163,1,"画"],[64164,1,"瘝"],[64165,1,"瘟"],[64166,1,"益"],[64167,1,"盛"],[64168,1,"直"],[64169,1,"睊"],[64170,1,"着"],[64171,1,"磌"],[64172,1,"窱"],[64173,1,"節"],[64174,1,"类"],[64175,1,"絛"],[64176,1,"練"],[64177,1,"缾"],[64178,1,"者"],[64179,1,"荒"],[64180,1,"華"],[64181,1,"蝹"],[64182,1,"襁"],[64183,1,"覆"],[64184,1,"視"],[64185,1,"調"],[64186,1,"諸"],[64187,1,"請"],[64188,1,"謁"],[64189,1,"諾"],[64190,1,"諭"],[64191,1,"謹"],[64192,1,"變"],[64193,1,"贈"],[64194,1,"輸"],[64195,1,"遲"],[64196,1,"醙"],[64197,1,"鉶"],[64198,1,"陼"],[64199,1,"難"],[64200,1,"靖"],[64201,1,"韛"],[64202,1,"響"],[64203,1,"頋"],[64204,1,"頻"],[64205,1,"鬒"],[64206,1,"龜"],[64207,1,"𢡊"],[64208,1,"𢡄"],[64209,1,"𣏕"],[64210,1,"㮝"],[64211,1,"䀘"],[64212,1,"䀹"],[64213,1,"𥉉"],[64214,1,"𥳐"],[64215,1,"𧻓"],[64216,1,"齃"],[64217,1,"龎"],[[64218,64255],3],[64256,1,"ff"],[64257,1,"fi"],[64258,1,"fl"],[64259,1,"ffi"],[64260,1,"ffl"],[[64261,64262],1,"st"],[[64263,64274],3],[64275,1,"մն"],[64276,1,"մե"],[64277,1,"մի"],[64278,1,"վն"],[64279,1,"մխ"],[[64280,64284],3],[64285,1,"יִ"],[64286,2],[64287,1,"ײַ"],[64288,1,"ע"],[64289,1,"א"],[64290,1,"ד"],[64291,1,"ה"],[64292,1,"כ"],[64293,1,"ל"],[64294,1,"ם"],[64295,1,"ר"],[64296,1,"ת"],[64297,5,"+"],[64298,1,"שׁ"],[64299,1,"שׂ"],[64300,1,"שּׁ"],[64301,1,"שּׂ"],[64302,1,"אַ"],[64303,1,"אָ"],[64304,1,"אּ"],[64305,1,"בּ"],[64306,1,"גּ"],[64307,1,"דּ"],[64308,1,"הּ"],[64309,1,"וּ"],[64310,1,"זּ"],[64311,3],[64312,1,"טּ"],[64313,1,"יּ"],[64314,1,"ךּ"],[64315,1,"כּ"],[64316,1,"לּ"],[64317,3],[64318,1,"מּ"],[64319,3],[64320,1,"נּ"],[64321,1,"סּ"],[64322,3],[64323,1,"ףּ"],[64324,1,"פּ"],[64325,3],[64326,1,"צּ"],[64327,1,"קּ"],[64328,1,"רּ"],[64329,1,"שּ"],[64330,1,"תּ"],[64331,1,"וֹ"],[64332,1,"בֿ"],[64333,1,"כֿ"],[64334,1,"פֿ"],[64335,1,"אל"],[[64336,64337],1,"ٱ"],[[64338,64341],1,"ٻ"],[[64342,64345],1,"پ"],[[64346,64349],1,"ڀ"],[[64350,64353],1,"ٺ"],[[64354,64357],1,"ٿ"],[[64358,64361],1,"ٹ"],[[64362,64365],1,"ڤ"],[[64366,64369],1,"ڦ"],[[64370,64373],1,"ڄ"],[[64374,64377],1,"ڃ"],[[64378,64381],1,"چ"],[[64382,64385],1,"ڇ"],[[64386,64387],1,"ڍ"],[[64388,64389],1,"ڌ"],[[64390,64391],1,"ڎ"],[[64392,64393],1,"ڈ"],[[64394,64395],1,"ژ"],[[64396,64397],1,"ڑ"],[[64398,64401],1,"ک"],[[64402,64405],1,"گ"],[[64406,64409],1,"ڳ"],[[64410,64413],1,"ڱ"],[[64414,64415],1,"ں"],[[64416,64419],1,"ڻ"],[[64420,64421],1,"ۀ"],[[64422,64425],1,"ہ"],[[64426,64429],1,"ھ"],[[64430,64431],1,"ے"],[[64432,64433],1,"ۓ"],[[64434,64449],2],[[64450,64466],3],[[64467,64470],1,"ڭ"],[[64471,64472],1,"ۇ"],[[64473,64474],1,"ۆ"],[[64475,64476],1,"ۈ"],[64477,1,"ۇٴ"],[[64478,64479],1,"ۋ"],[[64480,64481],1,"ۅ"],[[64482,64483],1,"ۉ"],[[64484,64487],1,"ې"],[[64488,64489],1,"ى"],[[64490,64491],1,"ئا"],[[64492,64493],1,"ئە"],[[64494,64495],1,"ئو"],[[64496,64497],1,"ئۇ"],[[64498,64499],1,"ئۆ"],[[64500,64501],1,"ئۈ"],[[64502,64504],1,"ئې"],[[64505,64507],1,"ئى"],[[64508,64511],1,"ی"],[64512,1,"ئج"],[64513,1,"ئح"],[64514,1,"ئم"],[64515,1,"ئى"],[64516,1,"ئي"],[64517,1,"بج"],[64518,1,"بح"],[64519,1,"بخ"],[64520,1,"بم"],[64521,1,"بى"],[64522,1,"بي"],[64523,1,"تج"],[64524,1,"تح"],[64525,1,"تخ"],[64526,1,"تم"],[64527,1,"تى"],[64528,1,"تي"],[64529,1,"ثج"],[64530,1,"ثم"],[64531,1,"ثى"],[64532,1,"ثي"],[64533,1,"جح"],[64534,1,"جم"],[64535,1,"حج"],[64536,1,"حم"],[64537,1,"خج"],[64538,1,"خح"],[64539,1,"خم"],[64540,1,"سج"],[64541,1,"سح"],[64542,1,"سخ"],[64543,1,"سم"],[64544,1,"صح"],[64545,1,"صم"],[64546,1,"ضج"],[64547,1,"ضح"],[64548,1,"ضخ"],[64549,1,"ضم"],[64550,1,"طح"],[64551,1,"طم"],[64552,1,"ظم"],[64553,1,"عج"],[64554,1,"عم"],[64555,1,"غج"],[64556,1,"غم"],[64557,1,"فج"],[64558,1,"فح"],[64559,1,"فخ"],[64560,1,"فم"],[64561,1,"فى"],[64562,1,"في"],[64563,1,"قح"],[64564,1,"قم"],[64565,1,"قى"],[64566,1,"قي"],[64567,1,"كا"],[64568,1,"كج"],[64569,1,"كح"],[64570,1,"كخ"],[64571,1,"كل"],[64572,1,"كم"],[64573,1,"كى"],[64574,1,"كي"],[64575,1,"لج"],[64576,1,"لح"],[64577,1,"لخ"],[64578,1,"لم"],[64579,1,"لى"],[64580,1,"لي"],[64581,1,"مج"],[64582,1,"مح"],[64583,1,"مخ"],[64584,1,"مم"],[64585,1,"مى"],[64586,1,"مي"],[64587,1,"نج"],[64588,1,"نح"],[64589,1,"نخ"],[64590,1,"نم"],[64591,1,"نى"],[64592,1,"ني"],[64593,1,"هج"],[64594,1,"هم"],[64595,1,"هى"],[64596,1,"هي"],[64597,1,"يج"],[64598,1,"يح"],[64599,1,"يخ"],[64600,1,"يم"],[64601,1,"يى"],[64602,1,"يي"],[64603,1,"ذٰ"],[64604,1,"رٰ"],[64605,1,"ىٰ"],[64606,5," ٌّ"],[64607,5," ٍّ"],[64608,5," َّ"],[64609,5," ُّ"],[64610,5," ِّ"],[64611,5," ّٰ"],[64612,1,"ئر"],[64613,1,"ئز"],[64614,1,"ئم"],[64615,1,"ئن"],[64616,1,"ئى"],[64617,1,"ئي"],[64618,1,"بر"],[64619,1,"بز"],[64620,1,"بم"],[64621,1,"بن"],[64622,1,"بى"],[64623,1,"بي"],[64624,1,"تر"],[64625,1,"تز"],[64626,1,"تم"],[64627,1,"تن"],[64628,1,"تى"],[64629,1,"تي"],[64630,1,"ثر"],[64631,1,"ثز"],[64632,1,"ثم"],[64633,1,"ثن"],[64634,1,"ثى"],[64635,1,"ثي"],[64636,1,"فى"],[64637,1,"في"],[64638,1,"قى"],[64639,1,"قي"],[64640,1,"كا"],[64641,1,"كل"],[64642,1,"كم"],[64643,1,"كى"],[64644,1,"كي"],[64645,1,"لم"],[64646,1,"لى"],[64647,1,"لي"],[64648,1,"ما"],[64649,1,"مم"],[64650,1,"نر"],[64651,1,"نز"],[64652,1,"نم"],[64653,1,"نن"],[64654,1,"نى"],[64655,1,"ني"],[64656,1,"ىٰ"],[64657,1,"ير"],[64658,1,"يز"],[64659,1,"يم"],[64660,1,"ين"],[64661,1,"يى"],[64662,1,"يي"],[64663,1,"ئج"],[64664,1,"ئح"],[64665,1,"ئخ"],[64666,1,"ئم"],[64667,1,"ئه"],[64668,1,"بج"],[64669,1,"بح"],[64670,1,"بخ"],[64671,1,"بم"],[64672,1,"به"],[64673,1,"تج"],[64674,1,"تح"],[64675,1,"تخ"],[64676,1,"تم"],[64677,1,"ته"],[64678,1,"ثم"],[64679,1,"جح"],[64680,1,"جم"],[64681,1,"حج"],[64682,1,"حم"],[64683,1,"خج"],[64684,1,"خم"],[64685,1,"سج"],[64686,1,"سح"],[64687,1,"سخ"],[64688,1,"سم"],[64689,1,"صح"],[64690,1,"صخ"],[64691,1,"صم"],[64692,1,"ضج"],[64693,1,"ضح"],[64694,1,"ضخ"],[64695,1,"ضم"],[64696,1,"طح"],[64697,1,"ظم"],[64698,1,"عج"],[64699,1,"عم"],[64700,1,"غج"],[64701,1,"غم"],[64702,1,"فج"],[64703,1,"فح"],[64704,1,"فخ"],[64705,1,"فم"],[64706,1,"قح"],[64707,1,"قم"],[64708,1,"كج"],[64709,1,"كح"],[64710,1,"كخ"],[64711,1,"كل"],[64712,1,"كم"],[64713,1,"لج"],[64714,1,"لح"],[64715,1,"لخ"],[64716,1,"لم"],[64717,1,"له"],[64718,1,"مج"],[64719,1,"مح"],[64720,1,"مخ"],[64721,1,"مم"],[64722,1,"نج"],[64723,1,"نح"],[64724,1,"نخ"],[64725,1,"نم"],[64726,1,"نه"],[64727,1,"هج"],[64728,1,"هم"],[64729,1,"هٰ"],[64730,1,"يج"],[64731,1,"يح"],[64732,1,"يخ"],[64733,1,"يم"],[64734,1,"يه"],[64735,1,"ئم"],[64736,1,"ئه"],[64737,1,"بم"],[64738,1,"به"],[64739,1,"تم"],[64740,1,"ته"],[64741,1,"ثم"],[64742,1,"ثه"],[64743,1,"سم"],[64744,1,"سه"],[64745,1,"شم"],[64746,1,"شه"],[64747,1,"كل"],[64748,1,"كم"],[64749,1,"لم"],[64750,1,"نم"],[64751,1,"نه"],[64752,1,"يم"],[64753,1,"يه"],[64754,1,"ـَّ"],[64755,1,"ـُّ"],[64756,1,"ـِّ"],[64757,1,"طى"],[64758,1,"طي"],[64759,1,"عى"],[64760,1,"عي"],[64761,1,"غى"],[64762,1,"غي"],[64763,1,"سى"],[64764,1,"سي"],[64765,1,"شى"],[64766,1,"شي"],[64767,1,"حى"],[64768,1,"حي"],[64769,1,"جى"],[64770,1,"جي"],[64771,1,"خى"],[64772,1,"خي"],[64773,1,"صى"],[64774,1,"صي"],[64775,1,"ضى"],[64776,1,"ضي"],[64777,1,"شج"],[64778,1,"شح"],[64779,1,"شخ"],[64780,1,"شم"],[64781,1,"شر"],[64782,1,"سر"],[64783,1,"صر"],[64784,1,"ضر"],[64785,1,"طى"],[64786,1,"طي"],[64787,1,"عى"],[64788,1,"عي"],[64789,1,"غى"],[64790,1,"غي"],[64791,1,"سى"],[64792,1,"سي"],[64793,1,"شى"],[64794,1,"شي"],[64795,1,"حى"],[64796,1,"حي"],[64797,1,"جى"],[64798,1,"جي"],[64799,1,"خى"],[64800,1,"خي"],[64801,1,"صى"],[64802,1,"صي"],[64803,1,"ضى"],[64804,1,"ضي"],[64805,1,"شج"],[64806,1,"شح"],[64807,1,"شخ"],[64808,1,"شم"],[64809,1,"شر"],[64810,1,"سر"],[64811,1,"صر"],[64812,1,"ضر"],[64813,1,"شج"],[64814,1,"شح"],[64815,1,"شخ"],[64816,1,"شم"],[64817,1,"سه"],[64818,1,"شه"],[64819,1,"طم"],[64820,1,"سج"],[64821,1,"سح"],[64822,1,"سخ"],[64823,1,"شج"],[64824,1,"شح"],[64825,1,"شخ"],[64826,1,"طم"],[64827,1,"ظم"],[[64828,64829],1,"اً"],[[64830,64831],2],[[64832,64847],3],[64848,1,"تجم"],[[64849,64850],1,"تحج"],[64851,1,"تحم"],[64852,1,"تخم"],[64853,1,"تمج"],[64854,1,"تمح"],[64855,1,"تمخ"],[[64856,64857],1,"جمح"],[64858,1,"حمي"],[64859,1,"حمى"],[64860,1,"سحج"],[64861,1,"سجح"],[64862,1,"سجى"],[[64863,64864],1,"سمح"],[64865,1,"سمج"],[[64866,64867],1,"سمم"],[[64868,64869],1,"صحح"],[64870,1,"صمم"],[[64871,64872],1,"شحم"],[64873,1,"شجي"],[[64874,64875],1,"شمخ"],[[64876,64877],1,"شمم"],[64878,1,"ضحى"],[[64879,64880],1,"ضخم"],[[64881,64882],1,"طمح"],[64883,1,"طمم"],[64884,1,"طمي"],[64885,1,"عجم"],[[64886,64887],1,"عمم"],[64888,1,"عمى"],[64889,1,"غمم"],[64890,1,"غمي"],[64891,1,"غمى"],[[64892,64893],1,"فخم"],[64894,1,"قمح"],[64895,1,"قمم"],[64896,1,"لحم"],[64897,1,"لحي"],[64898,1,"لحى"],[[64899,64900],1,"لجج"],[[64901,64902],1,"لخم"],[[64903,64904],1,"لمح"],[64905,1,"محج"],[64906,1,"محم"],[64907,1,"محي"],[64908,1,"مجح"],[64909,1,"مجم"],[64910,1,"مخج"],[64911,1,"مخم"],[[64912,64913],3],[64914,1,"مجخ"],[64915,1,"همج"],[64916,1,"همم"],[64917,1,"نحم"],[64918,1,"نحى"],[[64919,64920],1,"نجم"],[64921,1,"نجى"],[64922,1,"نمي"],[64923,1,"نمى"],[[64924,64925],1,"يمم"],[64926,1,"بخي"],[64927,1,"تجي"],[64928,1,"تجى"],[64929,1,"تخي"],[64930,1,"تخى"],[64931,1,"تمي"],[64932,1,"تمى"],[64933,1,"جمي"],[64934,1,"جحى"],[64935,1,"جمى"],[64936,1,"سخى"],[64937,1,"صحي"],[64938,1,"شحي"],[64939,1,"ضحي"],[64940,1,"لجي"],[64941,1,"لمي"],[64942,1,"يحي"],[64943,1,"يجي"],[64944,1,"يمي"],[64945,1,"ممي"],[64946,1,"قمي"],[64947,1,"نحي"],[64948,1,"قمح"],[64949,1,"لحم"],[64950,1,"عمي"],[64951,1,"كمي"],[64952,1,"نجح"],[64953,1,"مخي"],[64954,1,"لجم"],[64955,1,"كمم"],[64956,1,"لجم"],[64957,1,"نجح"],[64958,1,"جحي"],[64959,1,"حجي"],[64960,1,"مجي"],[64961,1,"فمي"],[64962,1,"بحي"],[64963,1,"كمم"],[64964,1,"عجم"],[64965,1,"صمم"],[64966,1,"سخي"],[64967,1,"نجي"],[[64968,64975],3],[[64976,65007],3],[65008,1,"صلے"],[65009,1,"قلے"],[65010,1,"الله"],[65011,1,"اكبر"],[65012,1,"محمد"],[65013,1,"صلعم"],[65014,1,"رسول"],[65015,1,"عليه"],[65016,1,"وسلم"],[65017,1,"صلى"],[65018,5,"صلى الله عليه وسلم"],[65019,5,"جل جلاله"],[65020,1,"ریال"],[65021,2],[[65022,65023],3],[[65024,65039],7],[65040,5,","],[65041,1,"、"],[65042,3],[65043,5,":"],[65044,5,";"],[65045,5,"!"],[65046,5,"?"],[65047,1,"〖"],[65048,1,"〗"],[65049,3],[[65050,65055],3],[[65056,65059],2],[[65060,65062],2],[[65063,65069],2],[[65070,65071],2],[65072,3],[65073,1,"—"],[65074,1,"–"],[[65075,65076],5,"_"],[65077,5,"("],[65078,5,")"],[65079,5,"{"],[65080,5,"}"],[65081,1,"〔"],[65082,1,"〕"],[65083,1,"【"],[65084,1,"】"],[65085,1,"《"],[65086,1,"》"],[65087,1,"〈"],[65088,1,"〉"],[65089,1,"「"],[65090,1,"」"],[65091,1,"『"],[65092,1,"』"],[[65093,65094],2],[65095,5,"["],[65096,5,"]"],[[65097,65100],5," ̅"],[[65101,65103],5,"_"],[65104,5,","],[65105,1,"、"],[65106,3],[65107,3],[65108,5,";"],[65109,5,":"],[65110,5,"?"],[65111,5,"!"],[65112,1,"—"],[65113,5,"("],[65114,5,")"],[65115,5,"{"],[65116,5,"}"],[65117,1,"〔"],[65118,1,"〕"],[65119,5,"#"],[65120,5,"&"],[65121,5,"*"],[65122,5,"+"],[65123,1,"-"],[65124,5,"<"],[65125,5,">"],[65126,5,"="],[65127,3],[65128,5,"\\"],[65129,5,"$"],[65130,5,"%"],[65131,5,"@"],[[65132,65135],3],[65136,5," ً"],[65137,1,"ـً"],[65138,5," ٌ"],[65139,2],[65140,5," ٍ"],[65141,3],[65142,5," َ"],[65143,1,"ـَ"],[65144,5," ُ"],[65145,1,"ـُ"],[65146,5," ِ"],[65147,1,"ـِ"],[65148,5," ّ"],[65149,1,"ـّ"],[65150,5," ْ"],[65151,1,"ـْ"],[65152,1,"ء"],[[65153,65154],1,"آ"],[[65155,65156],1,"أ"],[[65157,65158],1,"ؤ"],[[65159,65160],1,"إ"],[[65161,65164],1,"ئ"],[[65165,65166],1,"ا"],[[65167,65170],1,"ب"],[[65171,65172],1,"ة"],[[65173,65176],1,"ت"],[[65177,65180],1,"ث"],[[65181,65184],1,"ج"],[[65185,65188],1,"ح"],[[65189,65192],1,"خ"],[[65193,65194],1,"د"],[[65195,65196],1,"ذ"],[[65197,65198],1,"ر"],[[65199,65200],1,"ز"],[[65201,65204],1,"س"],[[65205,65208],1,"ش"],[[65209,65212],1,"ص"],[[65213,65216],1,"ض"],[[65217,65220],1,"ط"],[[65221,65224],1,"ظ"],[[65225,65228],1,"ع"],[[65229,65232],1,"غ"],[[65233,65236],1,"ف"],[[65237,65240],1,"ق"],[[65241,65244],1,"ك"],[[65245,65248],1,"ل"],[[65249,65252],1,"م"],[[65253,65256],1,"ن"],[[65257,65260],1,"ه"],[[65261,65262],1,"و"],[[65263,65264],1,"ى"],[[65265,65268],1,"ي"],[[65269,65270],1,"لآ"],[[65271,65272],1,"لأ"],[[65273,65274],1,"لإ"],[[65275,65276],1,"لا"],[[65277,65278],3],[65279,7],[65280,3],[65281,5,"!"],[65282,5,"\""],[65283,5,"#"],[65284,5,"$"],[65285,5,"%"],[65286,5,"&"],[65287,5,"'"],[65288,5,"("],[65289,5,")"],[65290,5,"*"],[65291,5,"+"],[65292,5,","],[65293,1,"-"],[65294,1,"."],[65295,5,"/"],[65296,1,"0"],[65297,1,"1"],[65298,1,"2"],[65299,1,"3"],[65300,1,"4"],[65301,1,"5"],[65302,1,"6"],[65303,1,"7"],[65304,1,"8"],[65305,1,"9"],[65306,5,":"],[65307,5,";"],[65308,5,"<"],[65309,5,"="],[65310,5,">"],[65311,5,"?"],[65312,5,"@"],[65313,1,"a"],[65314,1,"b"],[65315,1,"c"],[65316,1,"d"],[65317,1,"e"],[65318,1,"f"],[65319,1,"g"],[65320,1,"h"],[65321,1,"i"],[65322,1,"j"],[65323,1,"k"],[65324,1,"l"],[65325,1,"m"],[65326,1,"n"],[65327,1,"o"],[65328,1,"p"],[65329,1,"q"],[65330,1,"r"],[65331,1,"s"],[65332,1,"t"],[65333,1,"u"],[65334,1,"v"],[65335,1,"w"],[65336,1,"x"],[65337,1,"y"],[65338,1,"z"],[65339,5,"["],[65340,5,"\\"],[65341,5,"]"],[65342,5,"^"],[65343,5,"_"],[65344,5,"`"],[65345,1,"a"],[65346,1,"b"],[65347,1,"c"],[65348,1,"d"],[65349,1,"e"],[65350,1,"f"],[65351,1,"g"],[65352,1,"h"],[65353,1,"i"],[65354,1,"j"],[65355,1,"k"],[65356,1,"l"],[65357,1,"m"],[65358,1,"n"],[65359,1,"o"],[65360,1,"p"],[65361,1,"q"],[65362,1,"r"],[65363,1,"s"],[65364,1,"t"],[65365,1,"u"],[65366,1,"v"],[65367,1,"w"],[65368,1,"x"],[65369,1,"y"],[65370,1,"z"],[65371,5,"{"],[65372,5,"|"],[65373,5,"}"],[65374,5,"~"],[65375,1,"⦅"],[65376,1,"⦆"],[65377,1,"."],[65378,1,"「"],[65379,1,"」"],[65380,1,"、"],[65381,1,"・"],[65382,1,"ヲ"],[65383,1,"ァ"],[65384,1,"ィ"],[65385,1,"ゥ"],[65386,1,"ェ"],[65387,1,"ォ"],[65388,1,"ャ"],[65389,1,"ュ"],[65390,1,"ョ"],[65391,1,"ッ"],[65392,1,"ー"],[65393,1,"ア"],[65394,1,"イ"],[65395,1,"ウ"],[65396,1,"エ"],[65397,1,"オ"],[65398,1,"カ"],[65399,1,"キ"],[65400,1,"ク"],[65401,1,"ケ"],[65402,1,"コ"],[65403,1,"サ"],[65404,1,"シ"],[65405,1,"ス"],[65406,1,"セ"],[65407,1,"ソ"],[65408,1,"タ"],[65409,1,"チ"],[65410,1,"ツ"],[65411,1,"テ"],[65412,1,"ト"],[65413,1,"ナ"],[65414,1,"ニ"],[65415,1,"ヌ"],[65416,1,"ネ"],[65417,1,"ノ"],[65418,1,"ハ"],[65419,1,"ヒ"],[65420,1,"フ"],[65421,1,"ヘ"],[65422,1,"ホ"],[65423,1,"マ"],[65424,1,"ミ"],[65425,1,"ム"],[65426,1,"メ"],[65427,1,"モ"],[65428,1,"ヤ"],[65429,1,"ユ"],[65430,1,"ヨ"],[65431,1,"ラ"],[65432,1,"リ"],[65433,1,"ル"],[65434,1,"レ"],[65435,1,"ロ"],[65436,1,"ワ"],[65437,1,"ン"],[65438,1,"゙"],[65439,1,"゚"],[65440,3],[65441,1,"ᄀ"],[65442,1,"ᄁ"],[65443,1,"ᆪ"],[65444,1,"ᄂ"],[65445,1,"ᆬ"],[65446,1,"ᆭ"],[65447,1,"ᄃ"],[65448,1,"ᄄ"],[65449,1,"ᄅ"],[65450,1,"ᆰ"],[65451,1,"ᆱ"],[65452,1,"ᆲ"],[65453,1,"ᆳ"],[65454,1,"ᆴ"],[65455,1,"ᆵ"],[65456,1,"ᄚ"],[65457,1,"ᄆ"],[65458,1,"ᄇ"],[65459,1,"ᄈ"],[65460,1,"ᄡ"],[65461,1,"ᄉ"],[65462,1,"ᄊ"],[65463,1,"ᄋ"],[65464,1,"ᄌ"],[65465,1,"ᄍ"],[65466,1,"ᄎ"],[65467,1,"ᄏ"],[65468,1,"ᄐ"],[65469,1,"ᄑ"],[65470,1,"ᄒ"],[[65471,65473],3],[65474,1,"ᅡ"],[65475,1,"ᅢ"],[65476,1,"ᅣ"],[65477,1,"ᅤ"],[65478,1,"ᅥ"],[65479,1,"ᅦ"],[[65480,65481],3],[65482,1,"ᅧ"],[65483,1,"ᅨ"],[65484,1,"ᅩ"],[65485,1,"ᅪ"],[65486,1,"ᅫ"],[65487,1,"ᅬ"],[[65488,65489],3],[65490,1,"ᅭ"],[65491,1,"ᅮ"],[65492,1,"ᅯ"],[65493,1,"ᅰ"],[65494,1,"ᅱ"],[65495,1,"ᅲ"],[[65496,65497],3],[65498,1,"ᅳ"],[65499,1,"ᅴ"],[65500,1,"ᅵ"],[[65501,65503],3],[65504,1,"¢"],[65505,1,"£"],[65506,1,"¬"],[65507,5," ̄"],[65508,1,"¦"],[65509,1,"¥"],[65510,1,"₩"],[65511,3],[65512,1,"│"],[65513,1,"←"],[65514,1,"↑"],[65515,1,"→"],[65516,1,"↓"],[65517,1,"■"],[65518,1,"○"],[[65519,65528],3],[[65529,65531],3],[65532,3],[65533,3],[[65534,65535],3],[[65536,65547],2],[65548,3],[[65549,65574],2],[65575,3],[[65576,65594],2],[65595,3],[[65596,65597],2],[65598,3],[[65599,65613],2],[[65614,65615],3],[[65616,65629],2],[[65630,65663],3],[[65664,65786],2],[[65787,65791],3],[[65792,65794],2],[[65795,65798],3],[[65799,65843],2],[[65844,65846],3],[[65847,65855],2],[[65856,65930],2],[[65931,65932],2],[[65933,65934],2],[65935,3],[[65936,65947],2],[65948,2],[[65949,65951],3],[65952,2],[[65953,65999],3],[[66000,66044],2],[66045,2],[[66046,66175],3],[[66176,66204],2],[[66205,66207],3],[[66208,66256],2],[[66257,66271],3],[66272,2],[[66273,66299],2],[[66300,66303],3],[[66304,66334],2],[66335,2],[[66336,66339],2],[[66340,66348],3],[[66349,66351],2],[[66352,66368],2],[66369,2],[[66370,66377],2],[66378,2],[[66379,66383],3],[[66384,66426],2],[[66427,66431],3],[[66432,66461],2],[66462,3],[66463,2],[[66464,66499],2],[[66500,66503],3],[[66504,66511],2],[[66512,66517],2],[[66518,66559],3],[66560,1,"𐐨"],[66561,1,"𐐩"],[66562,1,"𐐪"],[66563,1,"𐐫"],[66564,1,"𐐬"],[66565,1,"𐐭"],[66566,1,"𐐮"],[66567,1,"𐐯"],[66568,1,"𐐰"],[66569,1,"𐐱"],[66570,1,"𐐲"],[66571,1,"𐐳"],[66572,1,"𐐴"],[66573,1,"𐐵"],[66574,1,"𐐶"],[66575,1,"𐐷"],[66576,1,"𐐸"],[66577,1,"𐐹"],[66578,1,"𐐺"],[66579,1,"𐐻"],[66580,1,"𐐼"],[66581,1,"𐐽"],[66582,1,"𐐾"],[66583,1,"𐐿"],[66584,1,"𐑀"],[66585,1,"𐑁"],[66586,1,"𐑂"],[66587,1,"𐑃"],[66588,1,"𐑄"],[66589,1,"𐑅"],[66590,1,"𐑆"],[66591,1,"𐑇"],[66592,1,"𐑈"],[66593,1,"𐑉"],[66594,1,"𐑊"],[66595,1,"𐑋"],[66596,1,"𐑌"],[66597,1,"𐑍"],[66598,1,"𐑎"],[66599,1,"𐑏"],[[66600,66637],2],[[66638,66717],2],[[66718,66719],3],[[66720,66729],2],[[66730,66735],3],[66736,1,"𐓘"],[66737,1,"𐓙"],[66738,1,"𐓚"],[66739,1,"𐓛"],[66740,1,"𐓜"],[66741,1,"𐓝"],[66742,1,"𐓞"],[66743,1,"𐓟"],[66744,1,"𐓠"],[66745,1,"𐓡"],[66746,1,"𐓢"],[66747,1,"𐓣"],[66748,1,"𐓤"],[66749,1,"𐓥"],[66750,1,"𐓦"],[66751,1,"𐓧"],[66752,1,"𐓨"],[66753,1,"𐓩"],[66754,1,"𐓪"],[66755,1,"𐓫"],[66756,1,"𐓬"],[66757,1,"𐓭"],[66758,1,"𐓮"],[66759,1,"𐓯"],[66760,1,"𐓰"],[66761,1,"𐓱"],[66762,1,"𐓲"],[66763,1,"𐓳"],[66764,1,"𐓴"],[66765,1,"𐓵"],[66766,1,"𐓶"],[66767,1,"𐓷"],[66768,1,"𐓸"],[66769,1,"𐓹"],[66770,1,"𐓺"],[66771,1,"𐓻"],[[66772,66775],3],[[66776,66811],2],[[66812,66815],3],[[66816,66855],2],[[66856,66863],3],[[66864,66915],2],[[66916,66926],3],[66927,2],[[66928,67071],3],[[67072,67382],2],[[67383,67391],3],[[67392,67413],2],[[67414,67423],3],[[67424,67431],2],[[67432,67583],3],[[67584,67589],2],[[67590,67591],3],[67592,2],[67593,3],[[67594,67637],2],[67638,3],[[67639,67640],2],[[67641,67643],3],[67644,2],[[67645,67646],3],[67647,2],[[67648,67669],2],[67670,3],[[67671,67679],2],[[67680,67702],2],[[67703,67711],2],[[67712,67742],2],[[67743,67750],3],[[67751,67759],2],[[67760,67807],3],[[67808,67826],2],[67827,3],[[67828,67829],2],[[67830,67834],3],[[67835,67839],2],[[67840,67861],2],[[67862,67865],2],[[67866,67867],2],[[67868,67870],3],[67871,2],[[67872,67897],2],[[67898,67902],3],[67903,2],[[67904,67967],3],[[67968,68023],2],[[68024,68027],3],[[68028,68029],2],[[68030,68031],2],[[68032,68047],2],[[68048,68049],3],[[68050,68095],2],[[68096,68099],2],[68100,3],[[68101,68102],2],[[68103,68107],3],[[68108,68115],2],[68116,3],[[68117,68119],2],[68120,3],[[68121,68147],2],[[68148,68149],2],[[68150,68151],3],[[68152,68154],2],[[68155,68158],3],[68159,2],[[68160,68167],2],[68168,2],[[68169,68175],3],[[68176,68184],2],[[68185,68191],3],[[68192,68220],2],[[68221,68223],2],[[68224,68252],2],[[68253,68255],2],[[68256,68287],3],[[68288,68295],2],[68296,2],[[68297,68326],2],[[68327,68330],3],[[68331,68342],2],[[68343,68351],3],[[68352,68405],2],[[68406,68408],3],[[68409,68415],2],[[68416,68437],2],[[68438,68439],3],[[68440,68447],2],[[68448,68466],2],[[68467,68471],3],[[68472,68479],2],[[68480,68497],2],[[68498,68504],3],[[68505,68508],2],[[68509,68520],3],[[68521,68527],2],[[68528,68607],3],[[68608,68680],2],[[68681,68735],3],[68736,1,"𐳀"],[68737,1,"𐳁"],[68738,1,"𐳂"],[68739,1,"𐳃"],[68740,1,"𐳄"],[68741,1,"𐳅"],[68742,1,"𐳆"],[68743,1,"𐳇"],[68744,1,"𐳈"],[68745,1,"𐳉"],[68746,1,"𐳊"],[68747,1,"𐳋"],[68748,1,"𐳌"],[68749,1,"𐳍"],[68750,1,"𐳎"],[68751,1,"𐳏"],[68752,1,"𐳐"],[68753,1,"𐳑"],[68754,1,"𐳒"],[68755,1,"𐳓"],[68756,1,"𐳔"],[68757,1,"𐳕"],[68758,1,"𐳖"],[68759,1,"𐳗"],[68760,1,"𐳘"],[68761,1,"𐳙"],[68762,1,"𐳚"],[68763,1,"𐳛"],[68764,1,"𐳜"],[68765,1,"𐳝"],[68766,1,"𐳞"],[68767,1,"𐳟"],[68768,1,"𐳠"],[68769,1,"𐳡"],[68770,1,"𐳢"],[68771,1,"𐳣"],[68772,1,"𐳤"],[68773,1,"𐳥"],[68774,1,"𐳦"],[68775,1,"𐳧"],[68776,1,"𐳨"],[68777,1,"𐳩"],[68778,1,"𐳪"],[68779,1,"𐳫"],[68780,1,"𐳬"],[68781,1,"𐳭"],[68782,1,"𐳮"],[68783,1,"𐳯"],[68784,1,"𐳰"],[68785,1,"𐳱"],[68786,1,"𐳲"],[[68787,68799],3],[[68800,68850],2],[[68851,68857],3],[[68858,68863],2],[[68864,68903],2],[[68904,68911],3],[[68912,68921],2],[[68922,69215],3],[[69216,69246],2],[69247,3],[[69248,69289],2],[69290,3],[[69291,69292],2],[69293,2],[[69294,69295],3],[[69296,69297],2],[[69298,69375],3],[[69376,69404],2],[[69405,69414],2],[69415,2],[[69416,69423],3],[[69424,69456],2],[[69457,69465],2],[[69466,69551],3],[[69552,69572],2],[[69573,69579],2],[[69580,69599],3],[[69600,69622],2],[[69623,69631],3],[[69632,69702],2],[[69703,69709],2],[[69710,69713],3],[[69714,69733],2],[[69734,69743],2],[[69744,69758],3],[69759,2],[[69760,69818],2],[[69819,69820],2],[69821,3],[[69822,69825],2],[[69826,69836],3],[69837,3],[[69838,69839],3],[[69840,69864],2],[[69865,69871],3],[[69872,69881],2],[[69882,69887],3],[[69888,69940],2],[69941,3],[[69942,69951],2],[[69952,69955],2],[[69956,69958],2],[69959,2],[[69960,69967],3],[[69968,70003],2],[[70004,70005],2],[70006,2],[[70007,70015],3],[[70016,70084],2],[[70085,70088],2],[[70089,70092],2],[70093,2],[[70094,70095],2],[[70096,70105],2],[70106,2],[70107,2],[70108,2],[[70109,70111],2],[70112,3],[[70113,70132],2],[[70133,70143],3],[[70144,70161],2],[70162,3],[[70163,70199],2],[[70200,70205],2],[70206,2],[[70207,70271],3],[[70272,70278],2],[70279,3],[70280,2],[70281,3],[[70282,70285],2],[70286,3],[[70287,70301],2],[70302,3],[[70303,70312],2],[70313,2],[[70314,70319],3],[[70320,70378],2],[[70379,70383],3],[[70384,70393],2],[[70394,70399],3],[70400,2],[[70401,70403],2],[70404,3],[[70405,70412],2],[[70413,70414],3],[[70415,70416],2],[[70417,70418],3],[[70419,70440],2],[70441,3],[[70442,70448],2],[70449,3],[[70450,70451],2],[70452,3],[[70453,70457],2],[70458,3],[70459,2],[[70460,70468],2],[[70469,70470],3],[[70471,70472],2],[[70473,70474],3],[[70475,70477],2],[[70478,70479],3],[70480,2],[[70481,70486],3],[70487,2],[[70488,70492],3],[[70493,70499],2],[[70500,70501],3],[[70502,70508],2],[[70509,70511],3],[[70512,70516],2],[[70517,70655],3],[[70656,70730],2],[[70731,70735],2],[[70736,70745],2],[70746,2],[70747,2],[70748,3],[70749,2],[70750,2],[70751,2],[[70752,70753],2],[[70754,70783],3],[[70784,70853],2],[70854,2],[70855,2],[[70856,70863],3],[[70864,70873],2],[[70874,71039],3],[[71040,71093],2],[[71094,71095],3],[[71096,71104],2],[[71105,71113],2],[[71114,71127],2],[[71128,71133],2],[[71134,71167],3],[[71168,71232],2],[[71233,71235],2],[71236,2],[[71237,71247],3],[[71248,71257],2],[[71258,71263],3],[[71264,71276],2],[[71277,71295],3],[[71296,71351],2],[71352,2],[[71353,71359],3],[[71360,71369],2],[[71370,71423],3],[[71424,71449],2],[71450,2],[[71451,71452],3],[[71453,71467],2],[[71468,71471],3],[[71472,71481],2],[[71482,71487],2],[[71488,71679],3],[[71680,71738],2],[71739,2],[[71740,71839],3],[71840,1,"𑣀"],[71841,1,"𑣁"],[71842,1,"𑣂"],[71843,1,"𑣃"],[71844,1,"𑣄"],[71845,1,"𑣅"],[71846,1,"𑣆"],[71847,1,"𑣇"],[71848,1,"𑣈"],[71849,1,"𑣉"],[71850,1,"𑣊"],[71851,1,"𑣋"],[71852,1,"𑣌"],[71853,1,"𑣍"],[71854,1,"𑣎"],[71855,1,"𑣏"],[71856,1,"𑣐"],[71857,1,"𑣑"],[71858,1,"𑣒"],[71859,1,"𑣓"],[71860,1,"𑣔"],[71861,1,"𑣕"],[71862,1,"𑣖"],[71863,1,"𑣗"],[71864,1,"𑣘"],[71865,1,"𑣙"],[71866,1,"𑣚"],[71867,1,"𑣛"],[71868,1,"𑣜"],[71869,1,"𑣝"],[71870,1,"𑣞"],[71871,1,"𑣟"],[[71872,71913],2],[[71914,71922],2],[[71923,71934],3],[71935,2],[[71936,71942],2],[[71943,71944],3],[71945,2],[[71946,71947],3],[[71948,71955],2],[71956,3],[[71957,71958],2],[71959,3],[[71960,71989],2],[71990,3],[[71991,71992],2],[[71993,71994],3],[[71995,72003],2],[[72004,72006],2],[[72007,72015],3],[[72016,72025],2],[[72026,72095],3],[[72096,72103],2],[[72104,72105],3],[[72106,72151],2],[[72152,72153],3],[[72154,72161],2],[72162,2],[[72163,72164],2],[[72165,72191],3],[[72192,72254],2],[[72255,72262],2],[72263,2],[[72264,72271],3],[[72272,72323],2],[[72324,72325],2],[[72326,72345],2],[[72346,72348],2],[72349,2],[[72350,72354],2],[[72355,72383],3],[[72384,72440],2],[[72441,72703],3],[[72704,72712],2],[72713,3],[[72714,72758],2],[72759,3],[[72760,72768],2],[[72769,72773],2],[[72774,72783],3],[[72784,72793],2],[[72794,72812],2],[[72813,72815],3],[[72816,72817],2],[[72818,72847],2],[[72848,72849],3],[[72850,72871],2],[72872,3],[[72873,72886],2],[[72887,72959],3],[[72960,72966],2],[72967,3],[[72968,72969],2],[72970,3],[[72971,73014],2],[[73015,73017],3],[73018,2],[73019,3],[[73020,73021],2],[73022,3],[[73023,73031],2],[[73032,73039],3],[[73040,73049],2],[[73050,73055],3],[[73056,73061],2],[73062,3],[[73063,73064],2],[73065,3],[[73066,73102],2],[73103,3],[[73104,73105],2],[73106,3],[[73107,73112],2],[[73113,73119],3],[[73120,73129],2],[[73130,73439],3],[[73440,73462],2],[[73463,73464],2],[[73465,73647],3],[73648,2],[[73649,73663],3],[[73664,73713],2],[[73714,73726],3],[73727,2],[[73728,74606],2],[[74607,74648],2],[74649,2],[[74650,74751],3],[[74752,74850],2],[[74851,74862],2],[74863,3],[[74864,74867],2],[74868,2],[[74869,74879],3],[[74880,75075],2],[[75076,77823],3],[[77824,78894],2],[78895,3],[[78896,78904],3],[[78905,82943],3],[[82944,83526],2],[[83527,92159],3],[[92160,92728],2],[[92729,92735],3],[[92736,92766],2],[92767,3],[[92768,92777],2],[[92778,92781],3],[[92782,92783],2],[[92784,92879],3],[[92880,92909],2],[[92910,92911],3],[[92912,92916],2],[92917,2],[[92918,92927],3],[[92928,92982],2],[[92983,92991],2],[[92992,92995],2],[[92996,92997],2],[[92998,93007],3],[[93008,93017],2],[93018,3],[[93019,93025],2],[93026,3],[[93027,93047],2],[[93048,93052],3],[[93053,93071],2],[[93072,93759],3],[93760,1,"𖹠"],[93761,1,"𖹡"],[93762,1,"𖹢"],[93763,1,"𖹣"],[93764,1,"𖹤"],[93765,1,"𖹥"],[93766,1,"𖹦"],[93767,1,"𖹧"],[93768,1,"𖹨"],[93769,1,"𖹩"],[93770,1,"𖹪"],[93771,1,"𖹫"],[93772,1,"𖹬"],[93773,1,"𖹭"],[93774,1,"𖹮"],[93775,1,"𖹯"],[93776,1,"𖹰"],[93777,1,"𖹱"],[93778,1,"𖹲"],[93779,1,"𖹳"],[93780,1,"𖹴"],[93781,1,"𖹵"],[93782,1,"𖹶"],[93783,1,"𖹷"],[93784,1,"𖹸"],[93785,1,"𖹹"],[93786,1,"𖹺"],[93787,1,"𖹻"],[93788,1,"𖹼"],[93789,1,"𖹽"],[93790,1,"𖹾"],[93791,1,"𖹿"],[[93792,93823],2],[[93824,93850],2],[[93851,93951],3],[[93952,94020],2],[[94021,94026],2],[[94027,94030],3],[94031,2],[[94032,94078],2],[[94079,94087],2],[[94088,94094],3],[[94095,94111],2],[[94112,94175],3],[94176,2],[94177,2],[94178,2],[94179,2],[94180,2],[[94181,94191],3],[[94192,94193],2],[[94194,94207],3],[[94208,100332],2],[[100333,100337],2],[[100338,100343],2],[[100344,100351],3],[[100352,101106],2],[[101107,101589],2],[[101590,101631],3],[[101632,101640],2],[[101641,110591],3],[[110592,110593],2],[[110594,110878],2],[[110879,110927],3],[[110928,110930],2],[[110931,110947],3],[[110948,110951],2],[[110952,110959],3],[[110960,111355],2],[[111356,113663],3],[[113664,113770],2],[[113771,113775],3],[[113776,113788],2],[[113789,113791],3],[[113792,113800],2],[[113801,113807],3],[[113808,113817],2],[[113818,113819],3],[113820,2],[[113821,113822],2],[113823,2],[[113824,113827],7],[[113828,118783],3],[[118784,119029],2],[[119030,119039],3],[[119040,119078],2],[[119079,119080],3],[119081,2],[[119082,119133],2],[119134,1,"𝅗𝅥"],[119135,1,"𝅘𝅥"],[119136,1,"𝅘𝅥𝅮"],[119137,1,"𝅘𝅥𝅯"],[119138,1,"𝅘𝅥𝅰"],[119139,1,"𝅘𝅥𝅱"],[119140,1,"𝅘𝅥𝅲"],[[119141,119154],2],[[119155,119162],3],[[119163,119226],2],[119227,1,"𝆹𝅥"],[119228,1,"𝆺𝅥"],[119229,1,"𝆹𝅥𝅮"],[119230,1,"𝆺𝅥𝅮"],[119231,1,"𝆹𝅥𝅯"],[119232,1,"𝆺𝅥𝅯"],[[119233,119261],2],[[119262,119272],2],[[119273,119295],3],[[119296,119365],2],[[119366,119519],3],[[119520,119539],2],[[119540,119551],3],[[119552,119638],2],[[119639,119647],3],[[119648,119665],2],[[119666,119672],2],[[119673,119807],3],[119808,1,"a"],[119809,1,"b"],[119810,1,"c"],[119811,1,"d"],[119812,1,"e"],[119813,1,"f"],[119814,1,"g"],[119815,1,"h"],[119816,1,"i"],[119817,1,"j"],[119818,1,"k"],[119819,1,"l"],[119820,1,"m"],[119821,1,"n"],[119822,1,"o"],[119823,1,"p"],[119824,1,"q"],[119825,1,"r"],[119826,1,"s"],[119827,1,"t"],[119828,1,"u"],[119829,1,"v"],[119830,1,"w"],[119831,1,"x"],[119832,1,"y"],[119833,1,"z"],[119834,1,"a"],[119835,1,"b"],[119836,1,"c"],[119837,1,"d"],[119838,1,"e"],[119839,1,"f"],[119840,1,"g"],[119841,1,"h"],[119842,1,"i"],[119843,1,"j"],[119844,1,"k"],[119845,1,"l"],[119846,1,"m"],[119847,1,"n"],[119848,1,"o"],[119849,1,"p"],[119850,1,"q"],[119851,1,"r"],[119852,1,"s"],[119853,1,"t"],[119854,1,"u"],[119855,1,"v"],[119856,1,"w"],[119857,1,"x"],[119858,1,"y"],[119859,1,"z"],[119860,1,"a"],[119861,1,"b"],[119862,1,"c"],[119863,1,"d"],[119864,1,"e"],[119865,1,"f"],[119866,1,"g"],[119867,1,"h"],[119868,1,"i"],[119869,1,"j"],[119870,1,"k"],[119871,1,"l"],[119872,1,"m"],[119873,1,"n"],[119874,1,"o"],[119875,1,"p"],[119876,1,"q"],[119877,1,"r"],[119878,1,"s"],[119879,1,"t"],[119880,1,"u"],[119881,1,"v"],[119882,1,"w"],[119883,1,"x"],[119884,1,"y"],[119885,1,"z"],[119886,1,"a"],[119887,1,"b"],[119888,1,"c"],[119889,1,"d"],[119890,1,"e"],[119891,1,"f"],[119892,1,"g"],[119893,3],[119894,1,"i"],[119895,1,"j"],[119896,1,"k"],[119897,1,"l"],[119898,1,"m"],[119899,1,"n"],[119900,1,"o"],[119901,1,"p"],[119902,1,"q"],[119903,1,"r"],[119904,1,"s"],[119905,1,"t"],[119906,1,"u"],[119907,1,"v"],[119908,1,"w"],[119909,1,"x"],[119910,1,"y"],[119911,1,"z"],[119912,1,"a"],[119913,1,"b"],[119914,1,"c"],[119915,1,"d"],[119916,1,"e"],[119917,1,"f"],[119918,1,"g"],[119919,1,"h"],[119920,1,"i"],[119921,1,"j"],[119922,1,"k"],[119923,1,"l"],[119924,1,"m"],[119925,1,"n"],[119926,1,"o"],[119927,1,"p"],[119928,1,"q"],[119929,1,"r"],[119930,1,"s"],[119931,1,"t"],[119932,1,"u"],[119933,1,"v"],[119934,1,"w"],[119935,1,"x"],[119936,1,"y"],[119937,1,"z"],[119938,1,"a"],[119939,1,"b"],[119940,1,"c"],[119941,1,"d"],[119942,1,"e"],[119943,1,"f"],[119944,1,"g"],[119945,1,"h"],[119946,1,"i"],[119947,1,"j"],[119948,1,"k"],[119949,1,"l"],[119950,1,"m"],[119951,1,"n"],[119952,1,"o"],[119953,1,"p"],[119954,1,"q"],[119955,1,"r"],[119956,1,"s"],[119957,1,"t"],[119958,1,"u"],[119959,1,"v"],[119960,1,"w"],[119961,1,"x"],[119962,1,"y"],[119963,1,"z"],[119964,1,"a"],[119965,3],[119966,1,"c"],[119967,1,"d"],[[119968,119969],3],[119970,1,"g"],[[119971,119972],3],[119973,1,"j"],[119974,1,"k"],[[119975,119976],3],[119977,1,"n"],[119978,1,"o"],[119979,1,"p"],[119980,1,"q"],[119981,3],[119982,1,"s"],[119983,1,"t"],[119984,1,"u"],[119985,1,"v"],[119986,1,"w"],[119987,1,"x"],[119988,1,"y"],[119989,1,"z"],[119990,1,"a"],[119991,1,"b"],[119992,1,"c"],[119993,1,"d"],[119994,3],[119995,1,"f"],[119996,3],[119997,1,"h"],[119998,1,"i"],[119999,1,"j"],[120000,1,"k"],[120001,1,"l"],[120002,1,"m"],[120003,1,"n"],[120004,3],[120005,1,"p"],[120006,1,"q"],[120007,1,"r"],[120008,1,"s"],[120009,1,"t"],[120010,1,"u"],[120011,1,"v"],[120012,1,"w"],[120013,1,"x"],[120014,1,"y"],[120015,1,"z"],[120016,1,"a"],[120017,1,"b"],[120018,1,"c"],[120019,1,"d"],[120020,1,"e"],[120021,1,"f"],[120022,1,"g"],[120023,1,"h"],[120024,1,"i"],[120025,1,"j"],[120026,1,"k"],[120027,1,"l"],[120028,1,"m"],[120029,1,"n"],[120030,1,"o"],[120031,1,"p"],[120032,1,"q"],[120033,1,"r"],[120034,1,"s"],[120035,1,"t"],[120036,1,"u"],[120037,1,"v"],[120038,1,"w"],[120039,1,"x"],[120040,1,"y"],[120041,1,"z"],[120042,1,"a"],[120043,1,"b"],[120044,1,"c"],[120045,1,"d"],[120046,1,"e"],[120047,1,"f"],[120048,1,"g"],[120049,1,"h"],[120050,1,"i"],[120051,1,"j"],[120052,1,"k"],[120053,1,"l"],[120054,1,"m"],[120055,1,"n"],[120056,1,"o"],[120057,1,"p"],[120058,1,"q"],[120059,1,"r"],[120060,1,"s"],[120061,1,"t"],[120062,1,"u"],[120063,1,"v"],[120064,1,"w"],[120065,1,"x"],[120066,1,"y"],[120067,1,"z"],[120068,1,"a"],[120069,1,"b"],[120070,3],[120071,1,"d"],[120072,1,"e"],[120073,1,"f"],[120074,1,"g"],[[120075,120076],3],[120077,1,"j"],[120078,1,"k"],[120079,1,"l"],[120080,1,"m"],[120081,1,"n"],[120082,1,"o"],[120083,1,"p"],[120084,1,"q"],[120085,3],[120086,1,"s"],[120087,1,"t"],[120088,1,"u"],[120089,1,"v"],[120090,1,"w"],[120091,1,"x"],[120092,1,"y"],[120093,3],[120094,1,"a"],[120095,1,"b"],[120096,1,"c"],[120097,1,"d"],[120098,1,"e"],[120099,1,"f"],[120100,1,"g"],[120101,1,"h"],[120102,1,"i"],[120103,1,"j"],[120104,1,"k"],[120105,1,"l"],[120106,1,"m"],[120107,1,"n"],[120108,1,"o"],[120109,1,"p"],[120110,1,"q"],[120111,1,"r"],[120112,1,"s"],[120113,1,"t"],[120114,1,"u"],[120115,1,"v"],[120116,1,"w"],[120117,1,"x"],[120118,1,"y"],[120119,1,"z"],[120120,1,"a"],[120121,1,"b"],[120122,3],[120123,1,"d"],[120124,1,"e"],[120125,1,"f"],[120126,1,"g"],[120127,3],[120128,1,"i"],[120129,1,"j"],[120130,1,"k"],[120131,1,"l"],[120132,1,"m"],[120133,3],[120134,1,"o"],[[120135,120137],3],[120138,1,"s"],[120139,1,"t"],[120140,1,"u"],[120141,1,"v"],[120142,1,"w"],[120143,1,"x"],[120144,1,"y"],[120145,3],[120146,1,"a"],[120147,1,"b"],[120148,1,"c"],[120149,1,"d"],[120150,1,"e"],[120151,1,"f"],[120152,1,"g"],[120153,1,"h"],[120154,1,"i"],[120155,1,"j"],[120156,1,"k"],[120157,1,"l"],[120158,1,"m"],[120159,1,"n"],[120160,1,"o"],[120161,1,"p"],[120162,1,"q"],[120163,1,"r"],[120164,1,"s"],[120165,1,"t"],[120166,1,"u"],[120167,1,"v"],[120168,1,"w"],[120169,1,"x"],[120170,1,"y"],[120171,1,"z"],[120172,1,"a"],[120173,1,"b"],[120174,1,"c"],[120175,1,"d"],[120176,1,"e"],[120177,1,"f"],[120178,1,"g"],[120179,1,"h"],[120180,1,"i"],[120181,1,"j"],[120182,1,"k"],[120183,1,"l"],[120184,1,"m"],[120185,1,"n"],[120186,1,"o"],[120187,1,"p"],[120188,1,"q"],[120189,1,"r"],[120190,1,"s"],[120191,1,"t"],[120192,1,"u"],[120193,1,"v"],[120194,1,"w"],[120195,1,"x"],[120196,1,"y"],[120197,1,"z"],[120198,1,"a"],[120199,1,"b"],[120200,1,"c"],[120201,1,"d"],[120202,1,"e"],[120203,1,"f"],[120204,1,"g"],[120205,1,"h"],[120206,1,"i"],[120207,1,"j"],[120208,1,"k"],[120209,1,"l"],[120210,1,"m"],[120211,1,"n"],[120212,1,"o"],[120213,1,"p"],[120214,1,"q"],[120215,1,"r"],[120216,1,"s"],[120217,1,"t"],[120218,1,"u"],[120219,1,"v"],[120220,1,"w"],[120221,1,"x"],[120222,1,"y"],[120223,1,"z"],[120224,1,"a"],[120225,1,"b"],[120226,1,"c"],[120227,1,"d"],[120228,1,"e"],[120229,1,"f"],[120230,1,"g"],[120231,1,"h"],[120232,1,"i"],[120233,1,"j"],[120234,1,"k"],[120235,1,"l"],[120236,1,"m"],[120237,1,"n"],[120238,1,"o"],[120239,1,"p"],[120240,1,"q"],[120241,1,"r"],[120242,1,"s"],[120243,1,"t"],[120244,1,"u"],[120245,1,"v"],[120246,1,"w"],[120247,1,"x"],[120248,1,"y"],[120249,1,"z"],[120250,1,"a"],[120251,1,"b"],[120252,1,"c"],[120253,1,"d"],[120254,1,"e"],[120255,1,"f"],[120256,1,"g"],[120257,1,"h"],[120258,1,"i"],[120259,1,"j"],[120260,1,"k"],[120261,1,"l"],[120262,1,"m"],[120263,1,"n"],[120264,1,"o"],[120265,1,"p"],[120266,1,"q"],[120267,1,"r"],[120268,1,"s"],[120269,1,"t"],[120270,1,"u"],[120271,1,"v"],[120272,1,"w"],[120273,1,"x"],[120274,1,"y"],[120275,1,"z"],[120276,1,"a"],[120277,1,"b"],[120278,1,"c"],[120279,1,"d"],[120280,1,"e"],[120281,1,"f"],[120282,1,"g"],[120283,1,"h"],[120284,1,"i"],[120285,1,"j"],[120286,1,"k"],[120287,1,"l"],[120288,1,"m"],[120289,1,"n"],[120290,1,"o"],[120291,1,"p"],[120292,1,"q"],[120293,1,"r"],[120294,1,"s"],[120295,1,"t"],[120296,1,"u"],[120297,1,"v"],[120298,1,"w"],[120299,1,"x"],[120300,1,"y"],[120301,1,"z"],[120302,1,"a"],[120303,1,"b"],[120304,1,"c"],[120305,1,"d"],[120306,1,"e"],[120307,1,"f"],[120308,1,"g"],[120309,1,"h"],[120310,1,"i"],[120311,1,"j"],[120312,1,"k"],[120313,1,"l"],[120314,1,"m"],[120315,1,"n"],[120316,1,"o"],[120317,1,"p"],[120318,1,"q"],[120319,1,"r"],[120320,1,"s"],[120321,1,"t"],[120322,1,"u"],[120323,1,"v"],[120324,1,"w"],[120325,1,"x"],[120326,1,"y"],[120327,1,"z"],[120328,1,"a"],[120329,1,"b"],[120330,1,"c"],[120331,1,"d"],[120332,1,"e"],[120333,1,"f"],[120334,1,"g"],[120335,1,"h"],[120336,1,"i"],[120337,1,"j"],[120338,1,"k"],[120339,1,"l"],[120340,1,"m"],[120341,1,"n"],[120342,1,"o"],[120343,1,"p"],[120344,1,"q"],[120345,1,"r"],[120346,1,"s"],[120347,1,"t"],[120348,1,"u"],[120349,1,"v"],[120350,1,"w"],[120351,1,"x"],[120352,1,"y"],[120353,1,"z"],[120354,1,"a"],[120355,1,"b"],[120356,1,"c"],[120357,1,"d"],[120358,1,"e"],[120359,1,"f"],[120360,1,"g"],[120361,1,"h"],[120362,1,"i"],[120363,1,"j"],[120364,1,"k"],[120365,1,"l"],[120366,1,"m"],[120367,1,"n"],[120368,1,"o"],[120369,1,"p"],[120370,1,"q"],[120371,1,"r"],[120372,1,"s"],[120373,1,"t"],[120374,1,"u"],[120375,1,"v"],[120376,1,"w"],[120377,1,"x"],[120378,1,"y"],[120379,1,"z"],[120380,1,"a"],[120381,1,"b"],[120382,1,"c"],[120383,1,"d"],[120384,1,"e"],[120385,1,"f"],[120386,1,"g"],[120387,1,"h"],[120388,1,"i"],[120389,1,"j"],[120390,1,"k"],[120391,1,"l"],[120392,1,"m"],[120393,1,"n"],[120394,1,"o"],[120395,1,"p"],[120396,1,"q"],[120397,1,"r"],[120398,1,"s"],[120399,1,"t"],[120400,1,"u"],[120401,1,"v"],[120402,1,"w"],[120403,1,"x"],[120404,1,"y"],[120405,1,"z"],[120406,1,"a"],[120407,1,"b"],[120408,1,"c"],[120409,1,"d"],[120410,1,"e"],[120411,1,"f"],[120412,1,"g"],[120413,1,"h"],[120414,1,"i"],[120415,1,"j"],[120416,1,"k"],[120417,1,"l"],[120418,1,"m"],[120419,1,"n"],[120420,1,"o"],[120421,1,"p"],[120422,1,"q"],[120423,1,"r"],[120424,1,"s"],[120425,1,"t"],[120426,1,"u"],[120427,1,"v"],[120428,1,"w"],[120429,1,"x"],[120430,1,"y"],[120431,1,"z"],[120432,1,"a"],[120433,1,"b"],[120434,1,"c"],[120435,1,"d"],[120436,1,"e"],[120437,1,"f"],[120438,1,"g"],[120439,1,"h"],[120440,1,"i"],[120441,1,"j"],[120442,1,"k"],[120443,1,"l"],[120444,1,"m"],[120445,1,"n"],[120446,1,"o"],[120447,1,"p"],[120448,1,"q"],[120449,1,"r"],[120450,1,"s"],[120451,1,"t"],[120452,1,"u"],[120453,1,"v"],[120454,1,"w"],[120455,1,"x"],[120456,1,"y"],[120457,1,"z"],[120458,1,"a"],[120459,1,"b"],[120460,1,"c"],[120461,1,"d"],[120462,1,"e"],[120463,1,"f"],[120464,1,"g"],[120465,1,"h"],[120466,1,"i"],[120467,1,"j"],[120468,1,"k"],[120469,1,"l"],[120470,1,"m"],[120471,1,"n"],[120472,1,"o"],[120473,1,"p"],[120474,1,"q"],[120475,1,"r"],[120476,1,"s"],[120477,1,"t"],[120478,1,"u"],[120479,1,"v"],[120480,1,"w"],[120481,1,"x"],[120482,1,"y"],[120483,1,"z"],[120484,1,"ı"],[120485,1,"ȷ"],[[120486,120487],3],[120488,1,"α"],[120489,1,"β"],[120490,1,"γ"],[120491,1,"δ"],[120492,1,"ε"],[120493,1,"ζ"],[120494,1,"η"],[120495,1,"θ"],[120496,1,"ι"],[120497,1,"κ"],[120498,1,"λ"],[120499,1,"μ"],[120500,1,"ν"],[120501,1,"ξ"],[120502,1,"ο"],[120503,1,"π"],[120504,1,"ρ"],[120505,1,"θ"],[120506,1,"σ"],[120507,1,"τ"],[120508,1,"υ"],[120509,1,"φ"],[120510,1,"χ"],[120511,1,"ψ"],[120512,1,"ω"],[120513,1,"∇"],[120514,1,"α"],[120515,1,"β"],[120516,1,"γ"],[120517,1,"δ"],[120518,1,"ε"],[120519,1,"ζ"],[120520,1,"η"],[120521,1,"θ"],[120522,1,"ι"],[120523,1,"κ"],[120524,1,"λ"],[120525,1,"μ"],[120526,1,"ν"],[120527,1,"ξ"],[120528,1,"ο"],[120529,1,"π"],[120530,1,"ρ"],[[120531,120532],1,"σ"],[120533,1,"τ"],[120534,1,"υ"],[120535,1,"φ"],[120536,1,"χ"],[120537,1,"ψ"],[120538,1,"ω"],[120539,1,"∂"],[120540,1,"ε"],[120541,1,"θ"],[120542,1,"κ"],[120543,1,"φ"],[120544,1,"ρ"],[120545,1,"π"],[120546,1,"α"],[120547,1,"β"],[120548,1,"γ"],[120549,1,"δ"],[120550,1,"ε"],[120551,1,"ζ"],[120552,1,"η"],[120553,1,"θ"],[120554,1,"ι"],[120555,1,"κ"],[120556,1,"λ"],[120557,1,"μ"],[120558,1,"ν"],[120559,1,"ξ"],[120560,1,"ο"],[120561,1,"π"],[120562,1,"ρ"],[120563,1,"θ"],[120564,1,"σ"],[120565,1,"τ"],[120566,1,"υ"],[120567,1,"φ"],[120568,1,"χ"],[120569,1,"ψ"],[120570,1,"ω"],[120571,1,"∇"],[120572,1,"α"],[120573,1,"β"],[120574,1,"γ"],[120575,1,"δ"],[120576,1,"ε"],[120577,1,"ζ"],[120578,1,"η"],[120579,1,"θ"],[120580,1,"ι"],[120581,1,"κ"],[120582,1,"λ"],[120583,1,"μ"],[120584,1,"ν"],[120585,1,"ξ"],[120586,1,"ο"],[120587,1,"π"],[120588,1,"ρ"],[[120589,120590],1,"σ"],[120591,1,"τ"],[120592,1,"υ"],[120593,1,"φ"],[120594,1,"χ"],[120595,1,"ψ"],[120596,1,"ω"],[120597,1,"∂"],[120598,1,"ε"],[120599,1,"θ"],[120600,1,"κ"],[120601,1,"φ"],[120602,1,"ρ"],[120603,1,"π"],[120604,1,"α"],[120605,1,"β"],[120606,1,"γ"],[120607,1,"δ"],[120608,1,"ε"],[120609,1,"ζ"],[120610,1,"η"],[120611,1,"θ"],[120612,1,"ι"],[120613,1,"κ"],[120614,1,"λ"],[120615,1,"μ"],[120616,1,"ν"],[120617,1,"ξ"],[120618,1,"ο"],[120619,1,"π"],[120620,1,"ρ"],[120621,1,"θ"],[120622,1,"σ"],[120623,1,"τ"],[120624,1,"υ"],[120625,1,"φ"],[120626,1,"χ"],[120627,1,"ψ"],[120628,1,"ω"],[120629,1,"∇"],[120630,1,"α"],[120631,1,"β"],[120632,1,"γ"],[120633,1,"δ"],[120634,1,"ε"],[120635,1,"ζ"],[120636,1,"η"],[120637,1,"θ"],[120638,1,"ι"],[120639,1,"κ"],[120640,1,"λ"],[120641,1,"μ"],[120642,1,"ν"],[120643,1,"ξ"],[120644,1,"ο"],[120645,1,"π"],[120646,1,"ρ"],[[120647,120648],1,"σ"],[120649,1,"τ"],[120650,1,"υ"],[120651,1,"φ"],[120652,1,"χ"],[120653,1,"ψ"],[120654,1,"ω"],[120655,1,"∂"],[120656,1,"ε"],[120657,1,"θ"],[120658,1,"κ"],[120659,1,"φ"],[120660,1,"ρ"],[120661,1,"π"],[120662,1,"α"],[120663,1,"β"],[120664,1,"γ"],[120665,1,"δ"],[120666,1,"ε"],[120667,1,"ζ"],[120668,1,"η"],[120669,1,"θ"],[120670,1,"ι"],[120671,1,"κ"],[120672,1,"λ"],[120673,1,"μ"],[120674,1,"ν"],[120675,1,"ξ"],[120676,1,"ο"],[120677,1,"π"],[120678,1,"ρ"],[120679,1,"θ"],[120680,1,"σ"],[120681,1,"τ"],[120682,1,"υ"],[120683,1,"φ"],[120684,1,"χ"],[120685,1,"ψ"],[120686,1,"ω"],[120687,1,"∇"],[120688,1,"α"],[120689,1,"β"],[120690,1,"γ"],[120691,1,"δ"],[120692,1,"ε"],[120693,1,"ζ"],[120694,1,"η"],[120695,1,"θ"],[120696,1,"ι"],[120697,1,"κ"],[120698,1,"λ"],[120699,1,"μ"],[120700,1,"ν"],[120701,1,"ξ"],[120702,1,"ο"],[120703,1,"π"],[120704,1,"ρ"],[[120705,120706],1,"σ"],[120707,1,"τ"],[120708,1,"υ"],[120709,1,"φ"],[120710,1,"χ"],[120711,1,"ψ"],[120712,1,"ω"],[120713,1,"∂"],[120714,1,"ε"],[120715,1,"θ"],[120716,1,"κ"],[120717,1,"φ"],[120718,1,"ρ"],[120719,1,"π"],[120720,1,"α"],[120721,1,"β"],[120722,1,"γ"],[120723,1,"δ"],[120724,1,"ε"],[120725,1,"ζ"],[120726,1,"η"],[120727,1,"θ"],[120728,1,"ι"],[120729,1,"κ"],[120730,1,"λ"],[120731,1,"μ"],[120732,1,"ν"],[120733,1,"ξ"],[120734,1,"ο"],[120735,1,"π"],[120736,1,"ρ"],[120737,1,"θ"],[120738,1,"σ"],[120739,1,"τ"],[120740,1,"υ"],[120741,1,"φ"],[120742,1,"χ"],[120743,1,"ψ"],[120744,1,"ω"],[120745,1,"∇"],[120746,1,"α"],[120747,1,"β"],[120748,1,"γ"],[120749,1,"δ"],[120750,1,"ε"],[120751,1,"ζ"],[120752,1,"η"],[120753,1,"θ"],[120754,1,"ι"],[120755,1,"κ"],[120756,1,"λ"],[120757,1,"μ"],[120758,1,"ν"],[120759,1,"ξ"],[120760,1,"ο"],[120761,1,"π"],[120762,1,"ρ"],[[120763,120764],1,"σ"],[120765,1,"τ"],[120766,1,"υ"],[120767,1,"φ"],[120768,1,"χ"],[120769,1,"ψ"],[120770,1,"ω"],[120771,1,"∂"],[120772,1,"ε"],[120773,1,"θ"],[120774,1,"κ"],[120775,1,"φ"],[120776,1,"ρ"],[120777,1,"π"],[[120778,120779],1,"ϝ"],[[120780,120781],3],[120782,1,"0"],[120783,1,"1"],[120784,1,"2"],[120785,1,"3"],[120786,1,"4"],[120787,1,"5"],[120788,1,"6"],[120789,1,"7"],[120790,1,"8"],[120791,1,"9"],[120792,1,"0"],[120793,1,"1"],[120794,1,"2"],[120795,1,"3"],[120796,1,"4"],[120797,1,"5"],[120798,1,"6"],[120799,1,"7"],[120800,1,"8"],[120801,1,"9"],[120802,1,"0"],[120803,1,"1"],[120804,1,"2"],[120805,1,"3"],[120806,1,"4"],[120807,1,"5"],[120808,1,"6"],[120809,1,"7"],[120810,1,"8"],[120811,1,"9"],[120812,1,"0"],[120813,1,"1"],[120814,1,"2"],[120815,1,"3"],[120816,1,"4"],[120817,1,"5"],[120818,1,"6"],[120819,1,"7"],[120820,1,"8"],[120821,1,"9"],[120822,1,"0"],[120823,1,"1"],[120824,1,"2"],[120825,1,"3"],[120826,1,"4"],[120827,1,"5"],[120828,1,"6"],[120829,1,"7"],[120830,1,"8"],[120831,1,"9"],[[120832,121343],2],[[121344,121398],2],[[121399,121402],2],[[121403,121452],2],[[121453,121460],2],[121461,2],[[121462,121475],2],[121476,2],[[121477,121483],2],[[121484,121498],3],[[121499,121503],2],[121504,3],[[121505,121519],2],[[121520,122879],3],[[122880,122886],2],[122887,3],[[122888,122904],2],[[122905,122906],3],[[122907,122913],2],[122914,3],[[122915,122916],2],[122917,3],[[122918,122922],2],[[122923,123135],3],[[123136,123180],2],[[123181,123183],3],[[123184,123197],2],[[123198,123199],3],[[123200,123209],2],[[123210,123213],3],[123214,2],[123215,2],[[123216,123583],3],[[123584,123641],2],[[123642,123646],3],[123647,2],[[123648,124927],3],[[124928,125124],2],[[125125,125126],3],[[125127,125135],2],[[125136,125142],2],[[125143,125183],3],[125184,1,"𞤢"],[125185,1,"𞤣"],[125186,1,"𞤤"],[125187,1,"𞤥"],[125188,1,"𞤦"],[125189,1,"𞤧"],[125190,1,"𞤨"],[125191,1,"𞤩"],[125192,1,"𞤪"],[125193,1,"𞤫"],[125194,1,"𞤬"],[125195,1,"𞤭"],[125196,1,"𞤮"],[125197,1,"𞤯"],[125198,1,"𞤰"],[125199,1,"𞤱"],[125200,1,"𞤲"],[125201,1,"𞤳"],[125202,1,"𞤴"],[125203,1,"𞤵"],[125204,1,"𞤶"],[125205,1,"𞤷"],[125206,1,"𞤸"],[125207,1,"𞤹"],[125208,1,"𞤺"],[125209,1,"𞤻"],[125210,1,"𞤼"],[125211,1,"𞤽"],[125212,1,"𞤾"],[125213,1,"𞤿"],[125214,1,"𞥀"],[125215,1,"𞥁"],[125216,1,"𞥂"],[125217,1,"𞥃"],[[125218,125258],2],[125259,2],[[125260,125263],3],[[125264,125273],2],[[125274,125277],3],[[125278,125279],2],[[125280,126064],3],[[126065,126132],2],[[126133,126208],3],[[126209,126269],2],[[126270,126463],3],[126464,1,"ا"],[126465,1,"ب"],[126466,1,"ج"],[126467,1,"د"],[126468,3],[126469,1,"و"],[126470,1,"ز"],[126471,1,"ح"],[126472,1,"ط"],[126473,1,"ي"],[126474,1,"ك"],[126475,1,"ل"],[126476,1,"م"],[126477,1,"ن"],[126478,1,"س"],[126479,1,"ع"],[126480,1,"ف"],[126481,1,"ص"],[126482,1,"ق"],[126483,1,"ر"],[126484,1,"ش"],[126485,1,"ت"],[126486,1,"ث"],[126487,1,"خ"],[126488,1,"ذ"],[126489,1,"ض"],[126490,1,"ظ"],[126491,1,"غ"],[126492,1,"ٮ"],[126493,1,"ں"],[126494,1,"ڡ"],[126495,1,"ٯ"],[126496,3],[126497,1,"ب"],[126498,1,"ج"],[126499,3],[126500,1,"ه"],[[126501,126502],3],[126503,1,"ح"],[126504,3],[126505,1,"ي"],[126506,1,"ك"],[126507,1,"ل"],[126508,1,"م"],[126509,1,"ن"],[126510,1,"س"],[126511,1,"ع"],[126512,1,"ف"],[126513,1,"ص"],[126514,1,"ق"],[126515,3],[126516,1,"ش"],[126517,1,"ت"],[126518,1,"ث"],[126519,1,"خ"],[126520,3],[126521,1,"ض"],[126522,3],[126523,1,"غ"],[[126524,126529],3],[126530,1,"ج"],[[126531,126534],3],[126535,1,"ح"],[126536,3],[126537,1,"ي"],[126538,3],[126539,1,"ل"],[126540,3],[126541,1,"ن"],[126542,1,"س"],[126543,1,"ع"],[126544,3],[126545,1,"ص"],[126546,1,"ق"],[126547,3],[126548,1,"ش"],[[126549,126550],3],[126551,1,"خ"],[126552,3],[126553,1,"ض"],[126554,3],[126555,1,"غ"],[126556,3],[126557,1,"ں"],[126558,3],[126559,1,"ٯ"],[126560,3],[126561,1,"ب"],[126562,1,"ج"],[126563,3],[126564,1,"ه"],[[126565,126566],3],[126567,1,"ح"],[126568,1,"ط"],[126569,1,"ي"],[126570,1,"ك"],[126571,3],[126572,1,"م"],[126573,1,"ن"],[126574,1,"س"],[126575,1,"ع"],[126576,1,"ف"],[126577,1,"ص"],[126578,1,"ق"],[126579,3],[126580,1,"ش"],[126581,1,"ت"],[126582,1,"ث"],[126583,1,"خ"],[126584,3],[126585,1,"ض"],[126586,1,"ظ"],[126587,1,"غ"],[126588,1,"ٮ"],[126589,3],[126590,1,"ڡ"],[126591,3],[126592,1,"ا"],[126593,1,"ب"],[126594,1,"ج"],[126595,1,"د"],[126596,1,"ه"],[126597,1,"و"],[126598,1,"ز"],[126599,1,"ح"],[126600,1,"ط"],[126601,1,"ي"],[126602,3],[126603,1,"ل"],[126604,1,"م"],[126605,1,"ن"],[126606,1,"س"],[126607,1,"ع"],[126608,1,"ف"],[126609,1,"ص"],[126610,1,"ق"],[126611,1,"ر"],[126612,1,"ش"],[126613,1,"ت"],[126614,1,"ث"],[126615,1,"خ"],[126616,1,"ذ"],[126617,1,"ض"],[126618,1,"ظ"],[126619,1,"غ"],[[126620,126624],3],[126625,1,"ب"],[126626,1,"ج"],[126627,1,"د"],[126628,3],[126629,1,"و"],[126630,1,"ز"],[126631,1,"ح"],[126632,1,"ط"],[126633,1,"ي"],[126634,3],[126635,1,"ل"],[126636,1,"م"],[126637,1,"ن"],[126638,1,"س"],[126639,1,"ع"],[126640,1,"ف"],[126641,1,"ص"],[126642,1,"ق"],[126643,1,"ر"],[126644,1,"ش"],[126645,1,"ت"],[126646,1,"ث"],[126647,1,"خ"],[126648,1,"ذ"],[126649,1,"ض"],[126650,1,"ظ"],[126651,1,"غ"],[[126652,126703],3],[[126704,126705],2],[[126706,126975],3],[[126976,127019],2],[[127020,127023],3],[[127024,127123],2],[[127124,127135],3],[[127136,127150],2],[[127151,127152],3],[[127153,127166],2],[127167,2],[127168,3],[[127169,127183],2],[127184,3],[[127185,127199],2],[[127200,127221],2],[[127222,127231],3],[127232,3],[127233,5,"0,"],[127234,5,"1,"],[127235,5,"2,"],[127236,5,"3,"],[127237,5,"4,"],[127238,5,"5,"],[127239,5,"6,"],[127240,5,"7,"],[127241,5,"8,"],[127242,5,"9,"],[[127243,127244],2],[[127245,127247],2],[127248,5,"(a)"],[127249,5,"(b)"],[127250,5,"(c)"],[127251,5,"(d)"],[127252,5,"(e)"],[127253,5,"(f)"],[127254,5,"(g)"],[127255,5,"(h)"],[127256,5,"(i)"],[127257,5,"(j)"],[127258,5,"(k)"],[127259,5,"(l)"],[127260,5,"(m)"],[127261,5,"(n)"],[127262,5,"(o)"],[127263,5,"(p)"],[127264,5,"(q)"],[127265,5,"(r)"],[127266,5,"(s)"],[127267,5,"(t)"],[127268,5,"(u)"],[127269,5,"(v)"],[127270,5,"(w)"],[127271,5,"(x)"],[127272,5,"(y)"],[127273,5,"(z)"],[127274,1,"〔s〕"],[127275,1,"c"],[127276,1,"r"],[127277,1,"cd"],[127278,1,"wz"],[127279,2],[127280,1,"a"],[127281,1,"b"],[127282,1,"c"],[127283,1,"d"],[127284,1,"e"],[127285,1,"f"],[127286,1,"g"],[127287,1,"h"],[127288,1,"i"],[127289,1,"j"],[127290,1,"k"],[127291,1,"l"],[127292,1,"m"],[127293,1,"n"],[127294,1,"o"],[127295,1,"p"],[127296,1,"q"],[127297,1,"r"],[127298,1,"s"],[127299,1,"t"],[127300,1,"u"],[127301,1,"v"],[127302,1,"w"],[127303,1,"x"],[127304,1,"y"],[127305,1,"z"],[127306,1,"hv"],[127307,1,"mv"],[127308,1,"sd"],[127309,1,"ss"],[127310,1,"ppv"],[127311,1,"wc"],[[127312,127318],2],[127319,2],[[127320,127326],2],[127327,2],[[127328,127337],2],[127338,1,"mc"],[127339,1,"md"],[127340,1,"mr"],[[127341,127343],2],[[127344,127352],2],[127353,2],[127354,2],[[127355,127356],2],[[127357,127358],2],[127359,2],[[127360,127369],2],[[127370,127373],2],[[127374,127375],2],[127376,1,"dj"],[[127377,127386],2],[[127387,127404],2],[127405,2],[[127406,127461],3],[[127462,127487],2],[127488,1,"ほか"],[127489,1,"ココ"],[127490,1,"サ"],[[127491,127503],3],[127504,1,"手"],[127505,1,"字"],[127506,1,"双"],[127507,1,"デ"],[127508,1,"二"],[127509,1,"多"],[127510,1,"解"],[127511,1,"天"],[127512,1,"交"],[127513,1,"映"],[127514,1,"無"],[127515,1,"料"],[127516,1,"前"],[127517,1,"後"],[127518,1,"再"],[127519,1,"新"],[127520,1,"初"],[127521,1,"終"],[127522,1,"生"],[127523,1,"販"],[127524,1,"声"],[127525,1,"吹"],[127526,1,"演"],[127527,1,"投"],[127528,1,"捕"],[127529,1,"一"],[127530,1,"三"],[127531,1,"遊"],[127532,1,"左"],[127533,1,"中"],[127534,1,"右"],[127535,1,"指"],[127536,1,"走"],[127537,1,"打"],[127538,1,"禁"],[127539,1,"空"],[127540,1,"合"],[127541,1,"満"],[127542,1,"有"],[127543,1,"月"],[127544,1,"申"],[127545,1,"割"],[127546,1,"営"],[127547,1,"配"],[[127548,127551],3],[127552,1,"〔本〕"],[127553,1,"〔三〕"],[127554,1,"〔二〕"],[127555,1,"〔安〕"],[127556,1,"〔点〕"],[127557,1,"〔打〕"],[127558,1,"〔盗〕"],[127559,1,"〔勝〕"],[127560,1,"〔敗〕"],[[127561,127567],3],[127568,1,"得"],[127569,1,"可"],[[127570,127583],3],[[127584,127589],2],[[127590,127743],3],[[127744,127776],2],[[127777,127788],2],[[127789,127791],2],[[127792,127797],2],[127798,2],[[127799,127868],2],[127869,2],[[127870,127871],2],[[127872,127891],2],[[127892,127903],2],[[127904,127940],2],[127941,2],[[127942,127946],2],[[127947,127950],2],[[127951,127955],2],[[127956,127967],2],[[127968,127984],2],[[127985,127991],2],[[127992,127999],2],[[128000,128062],2],[128063,2],[128064,2],[128065,2],[[128066,128247],2],[128248,2],[[128249,128252],2],[[128253,128254],2],[128255,2],[[128256,128317],2],[[128318,128319],2],[[128320,128323],2],[[128324,128330],2],[[128331,128335],2],[[128336,128359],2],[[128360,128377],2],[128378,2],[[128379,128419],2],[128420,2],[[128421,128506],2],[[128507,128511],2],[128512,2],[[128513,128528],2],[128529,2],[[128530,128532],2],[128533,2],[128534,2],[128535,2],[128536,2],[128537,2],[128538,2],[128539,2],[[128540,128542],2],[128543,2],[[128544,128549],2],[[128550,128551],2],[[128552,128555],2],[128556,2],[128557,2],[[128558,128559],2],[[128560,128563],2],[128564,2],[[128565,128576],2],[[128577,128578],2],[[128579,128580],2],[[128581,128591],2],[[128592,128639],2],[[128640,128709],2],[[128710,128719],2],[128720,2],[[128721,128722],2],[[128723,128724],2],[128725,2],[[128726,128727],2],[[128728,128735],3],[[128736,128748],2],[[128749,128751],3],[[128752,128755],2],[[128756,128758],2],[[128759,128760],2],[128761,2],[128762,2],[[128763,128764],2],[[128765,128767],3],[[128768,128883],2],[[128884,128895],3],[[128896,128980],2],[[128981,128984],2],[[128985,128991],3],[[128992,129003],2],[[129004,129023],3],[[129024,129035],2],[[129036,129039],3],[[129040,129095],2],[[129096,129103],3],[[129104,129113],2],[[129114,129119],3],[[129120,129159],2],[[129160,129167],3],[[129168,129197],2],[[129198,129199],3],[[129200,129201],2],[[129202,129279],3],[[129280,129291],2],[129292,2],[[129293,129295],2],[[129296,129304],2],[[129305,129310],2],[129311,2],[[129312,129319],2],[[129320,129327],2],[129328,2],[[129329,129330],2],[[129331,129342],2],[129343,2],[[129344,129355],2],[129356,2],[[129357,129359],2],[[129360,129374],2],[[129375,129387],2],[[129388,129392],2],[129393,2],[129394,2],[[129395,129398],2],[[129399,129400],2],[129401,3],[129402,2],[129403,2],[[129404,129407],2],[[129408,129412],2],[[129413,129425],2],[[129426,129431],2],[[129432,129442],2],[[129443,129444],2],[[129445,129450],2],[[129451,129453],2],[[129454,129455],2],[[129456,129465],2],[[129466,129471],2],[129472,2],[[129473,129474],2],[[129475,129482],2],[129483,2],[129484,3],[[129485,129487],2],[[129488,129510],2],[[129511,129535],2],[[129536,129619],2],[[129620,129631],3],[[129632,129645],2],[[129646,129647],3],[[129648,129651],2],[129652,2],[[129653,129655],3],[[129656,129658],2],[[129659,129663],3],[[129664,129666],2],[[129667,129670],2],[[129671,129679],3],[[129680,129685],2],[[129686,129704],2],[[129705,129711],3],[[129712,129718],2],[[129719,129727],3],[[129728,129730],2],[[129731,129743],3],[[129744,129750],2],[[129751,129791],3],[[129792,129938],2],[129939,3],[[129940,129994],2],[[129995,130031],3],[130032,1,"0"],[130033,1,"1"],[130034,1,"2"],[130035,1,"3"],[130036,1,"4"],[130037,1,"5"],[130038,1,"6"],[130039,1,"7"],[130040,1,"8"],[130041,1,"9"],[[130042,131069],3],[[131070,131071],3],[[131072,173782],2],[[173783,173789],2],[[173790,173823],3],[[173824,177972],2],[[177973,177983],3],[[177984,178205],2],[[178206,178207],3],[[178208,183969],2],[[183970,183983],3],[[183984,191456],2],[[191457,194559],3],[194560,1,"丽"],[194561,1,"丸"],[194562,1,"乁"],[194563,1,"𠄢"],[194564,1,"你"],[194565,1,"侮"],[194566,1,"侻"],[194567,1,"倂"],[194568,1,"偺"],[194569,1,"備"],[194570,1,"僧"],[194571,1,"像"],[194572,1,"㒞"],[194573,1,"𠘺"],[194574,1,"免"],[194575,1,"兔"],[194576,1,"兤"],[194577,1,"具"],[194578,1,"𠔜"],[194579,1,"㒹"],[194580,1,"內"],[194581,1,"再"],[194582,1,"𠕋"],[194583,1,"冗"],[194584,1,"冤"],[194585,1,"仌"],[194586,1,"冬"],[194587,1,"况"],[194588,1,"𩇟"],[194589,1,"凵"],[194590,1,"刃"],[194591,1,"㓟"],[194592,1,"刻"],[194593,1,"剆"],[194594,1,"割"],[194595,1,"剷"],[194596,1,"㔕"],[194597,1,"勇"],[194598,1,"勉"],[194599,1,"勤"],[194600,1,"勺"],[194601,1,"包"],[194602,1,"匆"],[194603,1,"北"],[194604,1,"卉"],[194605,1,"卑"],[194606,1,"博"],[194607,1,"即"],[194608,1,"卽"],[[194609,194611],1,"卿"],[194612,1,"𠨬"],[194613,1,"灰"],[194614,1,"及"],[194615,1,"叟"],[194616,1,"𠭣"],[194617,1,"叫"],[194618,1,"叱"],[194619,1,"吆"],[194620,1,"咞"],[194621,1,"吸"],[194622,1,"呈"],[194623,1,"周"],[194624,1,"咢"],[194625,1,"哶"],[194626,1,"唐"],[194627,1,"啓"],[194628,1,"啣"],[[194629,194630],1,"善"],[194631,1,"喙"],[194632,1,"喫"],[194633,1,"喳"],[194634,1,"嗂"],[194635,1,"圖"],[194636,1,"嘆"],[194637,1,"圗"],[194638,1,"噑"],[194639,1,"噴"],[194640,1,"切"],[194641,1,"壮"],[194642,1,"城"],[194643,1,"埴"],[194644,1,"堍"],[194645,1,"型"],[194646,1,"堲"],[194647,1,"報"],[194648,1,"墬"],[194649,1,"𡓤"],[194650,1,"売"],[194651,1,"壷"],[194652,1,"夆"],[194653,1,"多"],[194654,1,"夢"],[194655,1,"奢"],[194656,1,"𡚨"],[194657,1,"𡛪"],[194658,1,"姬"],[194659,1,"娛"],[194660,1,"娧"],[194661,1,"姘"],[194662,1,"婦"],[194663,1,"㛮"],[194664,3],[194665,1,"嬈"],[[194666,194667],1,"嬾"],[194668,1,"𡧈"],[194669,1,"寃"],[194670,1,"寘"],[194671,1,"寧"],[194672,1,"寳"],[194673,1,"𡬘"],[194674,1,"寿"],[194675,1,"将"],[194676,3],[194677,1,"尢"],[194678,1,"㞁"],[194679,1,"屠"],[194680,1,"屮"],[194681,1,"峀"],[194682,1,"岍"],[194683,1,"𡷤"],[194684,1,"嵃"],[194685,1,"𡷦"],[194686,1,"嵮"],[194687,1,"嵫"],[194688,1,"嵼"],[194689,1,"巡"],[194690,1,"巢"],[194691,1,"㠯"],[194692,1,"巽"],[194693,1,"帨"],[194694,1,"帽"],[194695,1,"幩"],[194696,1,"㡢"],[194697,1,"𢆃"],[194698,1,"㡼"],[194699,1,"庰"],[194700,1,"庳"],[194701,1,"庶"],[194702,1,"廊"],[194703,1,"𪎒"],[194704,1,"廾"],[[194705,194706],1,"𢌱"],[194707,1,"舁"],[[194708,194709],1,"弢"],[194710,1,"㣇"],[194711,1,"𣊸"],[194712,1,"𦇚"],[194713,1,"形"],[194714,1,"彫"],[194715,1,"㣣"],[194716,1,"徚"],[194717,1,"忍"],[194718,1,"志"],[194719,1,"忹"],[194720,1,"悁"],[194721,1,"㤺"],[194722,1,"㤜"],[194723,1,"悔"],[194724,1,"𢛔"],[194725,1,"惇"],[194726,1,"慈"],[194727,1,"慌"],[194728,1,"慎"],[194729,1,"慌"],[194730,1,"慺"],[194731,1,"憎"],[194732,1,"憲"],[194733,1,"憤"],[194734,1,"憯"],[194735,1,"懞"],[194736,1,"懲"],[194737,1,"懶"],[194738,1,"成"],[194739,1,"戛"],[194740,1,"扝"],[194741,1,"抱"],[194742,1,"拔"],[194743,1,"捐"],[194744,1,"𢬌"],[194745,1,"挽"],[194746,1,"拼"],[194747,1,"捨"],[194748,1,"掃"],[194749,1,"揤"],[194750,1,"𢯱"],[194751,1,"搢"],[194752,1,"揅"],[194753,1,"掩"],[194754,1,"㨮"],[194755,1,"摩"],[194756,1,"摾"],[194757,1,"撝"],[194758,1,"摷"],[194759,1,"㩬"],[194760,1,"敏"],[194761,1,"敬"],[194762,1,"𣀊"],[194763,1,"旣"],[194764,1,"書"],[194765,1,"晉"],[194766,1,"㬙"],[194767,1,"暑"],[194768,1,"㬈"],[194769,1,"㫤"],[194770,1,"冒"],[194771,1,"冕"],[194772,1,"最"],[194773,1,"暜"],[194774,1,"肭"],[194775,1,"䏙"],[194776,1,"朗"],[194777,1,"望"],[194778,1,"朡"],[194779,1,"杞"],[194780,1,"杓"],[194781,1,"𣏃"],[194782,1,"㭉"],[194783,1,"柺"],[194784,1,"枅"],[194785,1,"桒"],[194786,1,"梅"],[194787,1,"𣑭"],[194788,1,"梎"],[194789,1,"栟"],[194790,1,"椔"],[194791,1,"㮝"],[194792,1,"楂"],[194793,1,"榣"],[194794,1,"槪"],[194795,1,"檨"],[194796,1,"𣚣"],[194797,1,"櫛"],[194798,1,"㰘"],[194799,1,"次"],[194800,1,"𣢧"],[194801,1,"歔"],[194802,1,"㱎"],[194803,1,"歲"],[194804,1,"殟"],[194805,1,"殺"],[194806,1,"殻"],[194807,1,"𣪍"],[194808,1,"𡴋"],[194809,1,"𣫺"],[194810,1,"汎"],[194811,1,"𣲼"],[194812,1,"沿"],[194813,1,"泍"],[194814,1,"汧"],[194815,1,"洖"],[194816,1,"派"],[194817,1,"海"],[194818,1,"流"],[194819,1,"浩"],[194820,1,"浸"],[194821,1,"涅"],[194822,1,"𣴞"],[194823,1,"洴"],[194824,1,"港"],[194825,1,"湮"],[194826,1,"㴳"],[194827,1,"滋"],[194828,1,"滇"],[194829,1,"𣻑"],[194830,1,"淹"],[194831,1,"潮"],[194832,1,"𣽞"],[194833,1,"𣾎"],[194834,1,"濆"],[194835,1,"瀹"],[194836,1,"瀞"],[194837,1,"瀛"],[194838,1,"㶖"],[194839,1,"灊"],[194840,1,"災"],[194841,1,"灷"],[194842,1,"炭"],[194843,1,"𠔥"],[194844,1,"煅"],[194845,1,"𤉣"],[194846,1,"熜"],[194847,3],[194848,1,"爨"],[194849,1,"爵"],[194850,1,"牐"],[194851,1,"𤘈"],[194852,1,"犀"],[194853,1,"犕"],[194854,1,"𤜵"],[194855,1,"𤠔"],[194856,1,"獺"],[194857,1,"王"],[194858,1,"㺬"],[194859,1,"玥"],[[194860,194861],1,"㺸"],[194862,1,"瑇"],[194863,1,"瑜"],[194864,1,"瑱"],[194865,1,"璅"],[194866,1,"瓊"],[194867,1,"㼛"],[194868,1,"甤"],[194869,1,"𤰶"],[194870,1,"甾"],[194871,1,"𤲒"],[194872,1,"異"],[194873,1,"𢆟"],[194874,1,"瘐"],[194875,1,"𤾡"],[194876,1,"𤾸"],[194877,1,"𥁄"],[194878,1,"㿼"],[194879,1,"䀈"],[194880,1,"直"],[194881,1,"𥃳"],[194882,1,"𥃲"],[194883,1,"𥄙"],[194884,1,"𥄳"],[194885,1,"眞"],[[194886,194887],1,"真"],[194888,1,"睊"],[194889,1,"䀹"],[194890,1,"瞋"],[194891,1,"䁆"],[194892,1,"䂖"],[194893,1,"𥐝"],[194894,1,"硎"],[194895,1,"碌"],[194896,1,"磌"],[194897,1,"䃣"],[194898,1,"𥘦"],[194899,1,"祖"],[194900,1,"𥚚"],[194901,1,"𥛅"],[194902,1,"福"],[194903,1,"秫"],[194904,1,"䄯"],[194905,1,"穀"],[194906,1,"穊"],[194907,1,"穏"],[194908,1,"𥥼"],[[194909,194910],1,"𥪧"],[194911,3],[194912,1,"䈂"],[194913,1,"𥮫"],[194914,1,"篆"],[194915,1,"築"],[194916,1,"䈧"],[194917,1,"𥲀"],[194918,1,"糒"],[194919,1,"䊠"],[194920,1,"糨"],[194921,1,"糣"],[194922,1,"紀"],[194923,1,"𥾆"],[194924,1,"絣"],[194925,1,"䌁"],[194926,1,"緇"],[194927,1,"縂"],[194928,1,"繅"],[194929,1,"䌴"],[194930,1,"𦈨"],[194931,1,"𦉇"],[194932,1,"䍙"],[194933,1,"𦋙"],[194934,1,"罺"],[194935,1,"𦌾"],[194936,1,"羕"],[194937,1,"翺"],[194938,1,"者"],[194939,1,"𦓚"],[194940,1,"𦔣"],[194941,1,"聠"],[194942,1,"𦖨"],[194943,1,"聰"],[194944,1,"𣍟"],[194945,1,"䏕"],[194946,1,"育"],[194947,1,"脃"],[194948,1,"䐋"],[194949,1,"脾"],[194950,1,"媵"],[194951,1,"𦞧"],[194952,1,"𦞵"],[194953,1,"𣎓"],[194954,1,"𣎜"],[194955,1,"舁"],[194956,1,"舄"],[194957,1,"辞"],[194958,1,"䑫"],[194959,1,"芑"],[194960,1,"芋"],[194961,1,"芝"],[194962,1,"劳"],[194963,1,"花"],[194964,1,"芳"],[194965,1,"芽"],[194966,1,"苦"],[194967,1,"𦬼"],[194968,1,"若"],[194969,1,"茝"],[194970,1,"荣"],[194971,1,"莭"],[194972,1,"茣"],[194973,1,"莽"],[194974,1,"菧"],[194975,1,"著"],[194976,1,"荓"],[194977,1,"菊"],[194978,1,"菌"],[194979,1,"菜"],[194980,1,"𦰶"],[194981,1,"𦵫"],[194982,1,"𦳕"],[194983,1,"䔫"],[194984,1,"蓱"],[194985,1,"蓳"],[194986,1,"蔖"],[194987,1,"𧏊"],[194988,1,"蕤"],[194989,1,"𦼬"],[194990,1,"䕝"],[194991,1,"䕡"],[194992,1,"𦾱"],[194993,1,"𧃒"],[194994,1,"䕫"],[194995,1,"虐"],[194996,1,"虜"],[194997,1,"虧"],[194998,1,"虩"],[194999,1,"蚩"],[195000,1,"蚈"],[195001,1,"蜎"],[195002,1,"蛢"],[195003,1,"蝹"],[195004,1,"蜨"],[195005,1,"蝫"],[195006,1,"螆"],[195007,3],[195008,1,"蟡"],[195009,1,"蠁"],[195010,1,"䗹"],[195011,1,"衠"],[195012,1,"衣"],[195013,1,"𧙧"],[195014,1,"裗"],[195015,1,"裞"],[195016,1,"䘵"],[195017,1,"裺"],[195018,1,"㒻"],[195019,1,"𧢮"],[195020,1,"𧥦"],[195021,1,"䚾"],[195022,1,"䛇"],[195023,1,"誠"],[195024,1,"諭"],[195025,1,"變"],[195026,1,"豕"],[195027,1,"𧲨"],[195028,1,"貫"],[195029,1,"賁"],[195030,1,"贛"],[195031,1,"起"],[195032,1,"𧼯"],[195033,1,"𠠄"],[195034,1,"跋"],[195035,1,"趼"],[195036,1,"跰"],[195037,1,"𠣞"],[195038,1,"軔"],[195039,1,"輸"],[195040,1,"𨗒"],[195041,1,"𨗭"],[195042,1,"邔"],[195043,1,"郱"],[195044,1,"鄑"],[195045,1,"𨜮"],[195046,1,"鄛"],[195047,1,"鈸"],[195048,1,"鋗"],[195049,1,"鋘"],[195050,1,"鉼"],[195051,1,"鏹"],[195052,1,"鐕"],[195053,1,"𨯺"],[195054,1,"開"],[195055,1,"䦕"],[195056,1,"閷"],[195057,1,"𨵷"],[195058,1,"䧦"],[195059,1,"雃"],[195060,1,"嶲"],[195061,1,"霣"],[195062,1,"𩅅"],[195063,1,"𩈚"],[195064,1,"䩮"],[195065,1,"䩶"],[195066,1,"韠"],[195067,1,"𩐊"],[195068,1,"䪲"],[195069,1,"𩒖"],[[195070,195071],1,"頋"],[195072,1,"頩"],[195073,1,"𩖶"],[195074,1,"飢"],[195075,1,"䬳"],[195076,1,"餩"],[195077,1,"馧"],[195078,1,"駂"],[195079,1,"駾"],[195080,1,"䯎"],[195081,1,"𩬰"],[195082,1,"鬒"],[195083,1,"鱀"],[195084,1,"鳽"],[195085,1,"䳎"],[195086,1,"䳭"],[195087,1,"鵧"],[195088,1,"𪃎"],[195089,1,"䳸"],[195090,1,"𪄅"],[195091,1,"𪈎"],[195092,1,"𪊑"],[195093,1,"麻"],[195094,1,"䵖"],[195095,1,"黹"],[195096,1,"黾"],[195097,1,"鼅"],[195098,1,"鼏"],[195099,1,"鼖"],[195100,1,"鼻"],[195101,1,"𪘀"],[[195102,196605],3],[[196606,196607],3],[[196608,201546],2],[[201547,262141],3],[[262142,262143],3],[[262144,327677],3],[[327678,327679],3],[[327680,393213],3],[[393214,393215],3],[[393216,458749],3],[[458750,458751],3],[[458752,524285],3],[[524286,524287],3],[[524288,589821],3],[[589822,589823],3],[[589824,655357],3],[[655358,655359],3],[[655360,720893],3],[[720894,720895],3],[[720896,786429],3],[[786430,786431],3],[[786432,851965],3],[[851966,851967],3],[[851968,917501],3],[[917502,917503],3],[917504,3],[917505,3],[[917506,917535],3],[[917536,917631],3],[[917632,917759],3],[[917760,917999],7],[[918000,983037],3],[[983038,983039],3],[[983040,1048573],3],[[1048574,1048575],3],[[1048576,1114109],3],[[1114110,1114111],3]] \ No newline at end of file diff --git a/node_modules/tr46/lib/regexes.js b/node_modules/tr46/lib/regexes.js new file mode 100644 index 0000000..9728941 --- /dev/null +++ b/node_modules/tr46/lib/regexes.js @@ -0,0 +1,29 @@ +"use strict"; + +const combiningMarks = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1AC0\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{11000}-\u{11002}\u{11038}-\u{11046}\u{1107F}-\u{11082}\u{110B0}-\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{11134}\u{11145}\u{11146}\u{11173}\u{11180}-\u{11182}\u{111B3}-\u{111C0}\u{111C9}-\u{111CC}\u{111CE}\u{111CF}\u{1122C}-\u{11237}\u{1123E}\u{112DF}-\u{112EA}\u{11300}-\u{11303}\u{1133B}\u{1133C}\u{1133E}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11357}\u{11362}\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11435}-\u{11446}\u{1145E}\u{114B0}-\u{114C3}\u{115AF}-\u{115B5}\u{115B8}-\u{115C0}\u{115DC}\u{115DD}\u{11630}-\u{11640}\u{116AB}-\u{116B7}\u{1171D}-\u{1172B}\u{1182C}-\u{1183A}\u{11930}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{1193E}\u{11940}\u{11942}\u{11943}\u{119D1}-\u{119D7}\u{119DA}-\u{119E0}\u{119E4}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A39}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A5B}\u{11A8A}-\u{11A99}\u{11C2F}-\u{11C36}\u{11C38}-\u{11C3F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D8A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D97}\u{11EF3}-\u{11EF6}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F51}-\u{16F87}\u{16F8F}-\u{16F92}\u{16FE4}\u{16FF0}\u{16FF1}\u{1BC9D}\u{1BC9E}\u{1D165}-\u{1D169}\u{1D16D}-\u{1D172}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]/u; +const combiningClassVirama = /[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D3B\u0D3C\u0D4D\u0DCA\u0E3A\u0EBA\u0F84\u1039\u103A\u1714\u1734\u17D2\u1A60\u1B44\u1BAA\u1BAB\u1BF2\u1BF3\u2D7F\uA806\uA8C4\uA953\uA9C0\uAAF6\uABED\u{10A3F}\u{11046}\u{1107F}\u{110B9}\u{11133}\u{11134}\u{111C0}\u{11235}\u{112EA}\u{1134D}\u{11442}\u{114C2}\u{115BF}\u{1163F}\u{116B6}\u{1172B}\u{11839}\u{119E0}\u{11A34}\u{11A47}\u{11A99}\u{11C3F}\u{11D44}\u{11D45}\u{11D97}]/u; +const validZWNJ = /[\u0620\u0626\u0628\u062A-\u062E\u0633-\u063F\u0641-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u08A0-\u08A9\u08AF\u08B0\u08B3\u08B4\u08B6-\u08B8\u08BA-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA872\u{10AC0}-\u{10AC4}\u{10ACD}\u{10AD3}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{10D00}-\u{10D21}\u{10D23}\u{10F30}-\u{10F32}\u{10F34}-\u{10F44}\u{10F51}-\u{10F53}\u{1E900}-\u{1E943}][\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*\u200C[\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*[\u0620\u0622-\u063F\u0641-\u064A\u066E\u066F\u0671-\u0673\u0675-\u06D3\u06D5\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u077F\u07CA-\u07EA\u0840-\u0855\u0860\u0862-\u0865\u0867-\u086A\u08A0-\u08AC\u08AE-\u08B4\u08B6-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA871\u{10AC0}-\u{10AC5}\u{10AC7}\u{10AC9}\u{10ACA}\u{10ACE}-\u{10AD6}\u{10AD8}-\u{10AE1}\u{10AE4}\u{10AEB}-\u{10AEF}\u{10B80}-\u{10B91}\u{10BA9}-\u{10BAE}\u{10D01}-\u{10D23}\u{10F30}-\u{10F44}\u{10F51}-\u{10F54}\u{1E900}-\u{1E943}]/u; +const bidiDomain = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u08E2\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; +const bidiS1LTR = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1735\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4B\u1B50-\u1B6A\u1B74-\u1B7C\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{1173F}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1B000}-\u{1B11E}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6DD}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u; +const bidiS1RTL = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; +const bidiS2 = /^[\0-\x08\x0E-\x1B!-@\[-`\{-\x84\x86-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02B9\u02BA\u02C2-\u02CF\u02D2-\u02DF\u02E5-\u02ED\u02EF-\u036F\u0374\u0375\u037E\u0384\u0385\u0387\u03F6\u0483-\u0489\u058A\u058D-\u058F\u0591-\u05C7\u05D0-\u05EA\u05EF-\u05F4\u0600-\u061C\u061E-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u07FD-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u08D3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09F2\u09F3\u09FB\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AF1\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0BF3-\u0BFA\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C78-\u0C7E\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E3F\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39-\u0F3D\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1390-\u1399\u1400\u169B\u169C\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DB\u17DD\u17F0-\u17F9\u1800-\u180E\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1940\u1944\u1945\u19DE-\u19FF\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1AC0\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u200B-\u200D\u200F-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2070\u2074-\u207E\u2080-\u208E\u20A0-\u20BF\u20D0-\u20F0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u2150-\u215F\u2189-\u218B\u2190-\u2335\u237B-\u2394\u2396-\u2426\u2440-\u244A\u2460-\u249B\u24EA-\u26AB\u26AD-\u27FF\u2900-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF9-\u2CFF\u2D7F\u2DE0-\u2E52\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u3004\u3008-\u3020\u302A-\u302D\u3030\u3036\u3037\u303D-\u303F\u3099-\u309C\u30A0\u30FB\u31C0-\u31E3\u321D\u321E\u3250-\u325F\u327C-\u327E\u32B1-\u32BF\u32CC-\u32CF\u3377-\u337A\u33DE\u33DF\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA60D-\uA60F\uA66F-\uA67F\uA69E\uA69F\uA6F0\uA6F1\uA700-\uA721\uA788\uA802\uA806\uA80B\uA825\uA826\uA828-\uA82C\uA838\uA839\uA874-\uA877\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uAB6A\uAB6B\uABE5\uABE8\uABED\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3F\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFD\uFE00-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFEFF\uFF01-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10101}\u{10140}-\u{1018C}\u{10190}-\u{1019C}\u{101A0}\u{101FD}\u{102E0}-\u{102FB}\u{10376}-\u{1037A}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{1091F}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A38}-\u{10A3A}\u{10A3F}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE6}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B39}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D27}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAB}-\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F59}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{11001}\u{11038}-\u{11046}\u{11052}-\u{11065}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{11660}-\u{1166C}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11FD5}-\u{11FF1}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE2}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D200}-\u{1D245}\u{1D300}-\u{1D356}\u{1D6DB}\u{1D715}\u{1D74F}\u{1D789}\u{1D7C3}\u{1D7CE}-\u{1D7FF}\u{1DA00}-\u{1DA36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u{1F7E0}-\u{1F7EB}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}\u{1F8B1}\u{1F900}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBCA}\u{1FBF0}-\u{1FBF9}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*$/u; +const bidiS3 = /[0-9\xB2\xB3\xB9\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u08E2\u200F\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\u{102E1}-\u{102FB}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1D7CE}-\u{1D7FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1AC0\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; +const bidiS4EN = /[0-9\xB2\xB3\xB9\u06F0-\u06F9\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFF10-\uFF19\u{102E1}-\u{102FB}\u{1D7CE}-\u{1D7FF}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}]/u; +const bidiS4AN = /[\u0600-\u0605\u0660-\u0669\u066B\u066C\u06DD\u08E2\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}]/u; +const bidiS5 = /^[\0-\x08\x0E-\x1B!-\x84\x86-\u0377\u037A-\u037F\u0384-\u038A\u038C\u038E-\u03A1\u03A3-\u052F\u0531-\u0556\u0559-\u058A\u058D-\u058F\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0606\u0607\u0609\u060A\u060C\u060E-\u061A\u064B-\u065F\u066A\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07F6-\u07F9\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u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E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4F\u0D54-\u0D63\u0D66-\u0D7F\u0D81-\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E3A\u0E3F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FDA\u1000-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u137C\u1380-\u1399\u13A0-\u13F5\u13F8-\u13FD\u1400-\u167F\u1681-\u169C\u16A0-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1736\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17DD\u17E0-\u17E9\u17F0-\u17F9\u1800-\u180E\u1810-\u1819\u1820-\u1878\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1940\u1944-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u19DE-\u1A1B\u1A1E-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1AB0-\u1AC0\u1B00-\u1B4B\u1B50-\u1B7C\u1B80-\u1BF3\u1BFC-\u1C37\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD0-\u1CFA\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEF\u1FF2-\u1FF4\u1FF6-\u1FFE\u200B-\u200E\u2010-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2071\u2074-\u208E\u2090-\u209C\u20A0-\u20BF\u20D0-\u20F0\u2100-\u218B\u2190-\u2426\u2440-\u244A\u2460-\u2B73\u2B76-\u2B95\u2B97-\u2C2E\u2C30-\u2C5E\u2C60-\u2CF3\u2CF9-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2E52\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u303F\u3041-\u3096\u3099-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31E3\u31F0-\u321E\u3220-\u9FFC\uA000-\uA48C\uA490-\uA4C6\uA4D0-\uA62B\uA640-\uA6F7\uA700-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA82C\uA830-\uA839\uA840-\uA877\uA880-\uA8C5\uA8CE-\uA8D9\uA8E0-\uA953\uA95F-\uA97C\uA980-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA5C-\uAAC2\uAADB-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB6B\uAB70-\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1E\uFB29\uFD3E\uFD3F\uFDFD\uFE00-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFEFF\uFF01-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}-\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1018E}\u{10190}-\u{1019C}\u{101A0}\u{101D0}-\u{101FD}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E0}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{1037A}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{1091F}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10B39}-\u{10B3F}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{11000}-\u{1104D}\u{11052}-\u{1106F}\u{1107F}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11100}-\u{11134}\u{11136}-\u{11147}\u{11150}-\u{11176}\u{11180}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1123E}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112EA}\u{112F0}-\u{112F9}\u{11300}-\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133B}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11400}-\u{1145B}\u{1145D}-\u{11461}\u{11480}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B5}\u{115B8}-\u{115DD}\u{11600}-\u{11644}\u{11650}-\u{11659}\u{11660}-\u{1166C}\u{11680}-\u{116B8}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{1171D}-\u{1172B}\u{11730}-\u{1173F}\u{11800}-\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D7}\u{119DA}-\u{119E4}\u{11A00}-\u{11A47}\u{11A50}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C36}\u{11C38}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D47}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FF1}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF0}-\u{16AF5}\u{16B00}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F4F}-\u{16F87}\u{16F8F}-\u{16F9F}\u{16FE0}-\u{16FE4}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1B000}-\u{1B11E}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}-\u{1BCA3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D1E8}\u{1D200}-\u{1D245}\u{1D2E0}-\u{1D2F3}\u{1D300}-\u{1D356}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D7CB}\u{1D7CE}-\u{1DA8B}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E100}-\u{1E12C}\u{1E130}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E2C0}-\u{1E2F9}\u{1E2FF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F1AD}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6E0}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D8}\u{1F7E0}-\u{1F7EB}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}\u{1F8B1}\u{1F900}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBCA}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DD}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]*$/u; +const bidiS6 = /[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u06F0-\u06F9\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u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10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1735\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4B\u1B50-\u1B6A\u1B74-\u1B7C\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u2488-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E1}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{1173F}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1B000}-\u{1B11E}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D7CE}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1F100}-\u{1F10A}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DD}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1AC0\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; + +module.exports = { + combiningMarks, + combiningClassVirama, + validZWNJ, + bidiDomain, + bidiS1LTR, + bidiS1RTL, + bidiS2, + bidiS3, + bidiS4EN, + bidiS4AN, + bidiS5, + bidiS6 +}; diff --git a/node_modules/tr46/lib/statusMapping.js b/node_modules/tr46/lib/statusMapping.js new file mode 100644 index 0000000..1c962c2 --- /dev/null +++ b/node_modules/tr46/lib/statusMapping.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports.STATUS_MAPPING = { + mapped: 1, + valid: 2, + disallowed: 3, + disallowed_STD3_valid: 4, // eslint-disable-line camelcase + disallowed_STD3_mapped: 5, // eslint-disable-line camelcase + deviation: 6, + ignored: 7 +}; diff --git a/node_modules/tr46/package.json b/node_modules/tr46/package.json new file mode 100644 index 0000000..72a4df3 --- /dev/null +++ b/node_modules/tr46/package.json @@ -0,0 +1,46 @@ +{ + "name": "tr46", + "version": "2.1.0", + "engines": { + "node": ">=8" + }, + "description": "An implementation of the Unicode UTS #46: Unicode IDNA Compatibility Processing", + "main": "index.js", + "files": [ + "index.js", + "lib/mappingTable.json", + "lib/regexes.js", + "lib/statusMapping.js" + ], + "scripts": { + "test": "mocha", + "lint": "eslint .", + "pretest": "node scripts/getLatestTests.js", + "prepublish": "node scripts/generateMappingTable.js && node scripts/generateRegexes.js" + }, + "repository": "https://github.com/jsdom/tr46", + "keywords": [ + "unicode", + "tr46", + "uts46", + "punycode", + "url", + "whatwg" + ], + "author": "Sebastian Mayr ", + "contributors": [ + "Timothy Gu " + ], + "license": "MIT", + "dependencies": { + "punycode": "^2.1.1" + }, + "devDependencies": { + "eslint": "^7.27.0", + "mocha": "^8.4.0", + "node-fetch": "^2.6.0", + "regenerate": "^1.4.2", + "unicode-13.0.0": "^0.8.0" + }, + "unicodeVersion": "13.0.0" +} diff --git a/node_modules/type-is/HISTORY.md b/node_modules/type-is/HISTORY.md new file mode 100644 index 0000000..8de21f7 --- /dev/null +++ b/node_modules/type-is/HISTORY.md @@ -0,0 +1,259 @@ +1.6.18 / 2019-04-26 +=================== + + * Fix regression passing request object to `typeis.is` + +1.6.17 / 2019-04-25 +=================== + + * deps: mime-types@~2.1.24 + - Add Apple file extensions from IANA + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add extension `.owl` to `application/rdf+xml` + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add extensions from IANA for `image/*` types + - Add extensions from IANA for `model/*` types + - Add extensions to HEIC image types + - Add new mime types + - Add `text/mdx` with extension `.mdx` + * perf: prevent internal `throw` on invalid type + +1.6.16 / 2018-02-16 +=================== + + * deps: mime-types@~2.1.18 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add extension `.mjs` to `application/javascript` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add glTF types and extensions + - Add new mime types + - Update extensions `.md` and `.markdown` to be `text/markdown` + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +1.6.15 / 2017-03-31 +=================== + + * deps: mime-types@~2.1.15 + - Add new mime types + +1.6.14 / 2016-11-18 +=================== + + * deps: mime-types@~2.1.13 + - Add new mime types + +1.6.13 / 2016-05-18 +=================== + + * deps: mime-types@~2.1.11 + - Add new mime types + +1.6.12 / 2016-02-28 +=================== + + * deps: mime-types@~2.1.10 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +1.6.3 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - Add new mime types + * perf: reduce try block size + * perf: remove bitwise operations + +1.6.2 / 2015-05-10 +================== + + * deps: mime-types@~2.0.11 + - Add new mime types + +1.6.1 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - Add new mime types + +1.6.0 / 2015-02-12 +================== + + * fix false-positives in `hasBody` `Transfer-Encoding` check + * support wildcard for both type and subtype (`*/*`) + +1.5.7 / 2015-02-09 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/node_modules/type-is/LICENSE b/node_modules/type-is/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/node_modules/type-is/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/type-is/README.md b/node_modules/type-is/README.md new file mode 100644 index 0000000..b85ef8f --- /dev/null +++ b/node_modules/type-is/README.md @@ -0,0 +1,170 @@ +# type-is + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Infer the content-type of a request. + +### Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install type-is +``` + +## API + +```js +var http = require('http') +var typeis = require('type-is') + +http.createServer(function (req, res) { + var istext = typeis(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### typeis(request, types) + +Checks if the `request` is one of the `types`. If the request has no body, +even if there is a `Content-Type` header, then `null` is returned. If the +`Content-Type` header is invalid or does not matches any of the `types`, then +`false` is returned. Otherwise, a string of the type that matched is returned. + +The `request` argument is expected to be a Node.js HTTP request. The `types` +argument is an array of type strings. + +Each type in the `types` array can be one of the following: + +- A file extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. + The full mime type will be returned if matched. +- A suffix such as `+json`. This can be combined with a wildcard such as + `*/vnd+json` or `application/*+json`. The full mime type will be returned + if matched. + +Some examples to illustrate the inputs and returned value: + + + +```js +// req.headers.content-type = 'application/json' + +typeis(req, ['json']) // => 'json' +typeis(req, ['html', 'json']) // => 'json' +typeis(req, ['application/*']) // => 'application/json' +typeis(req, ['application/json']) // => 'application/json' + +typeis(req, ['html']) // => false +``` + +### typeis.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existence works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + + + +```js +if (typeis.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### typeis.is(mediaType, types) + +Checks if the `mediaType` is one of the `types`. If the `mediaType` is invalid +or does not matches any of the `types`, then `false` is returned. Otherwise, a +string of the type that matched is returned. + +The `mediaType` argument is expected to be a +[media type](https://tools.ietf.org/html/rfc6838) string. The `types` argument +is an array of type strings. + +Each type in the `types` array can be one of the following: + +- A file extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. + The full mime type will be returned if matched. +- A suffix such as `+json`. This can be combined with a wildcard such as + `*/vnd+json` or `application/*+json`. The full mime type will be returned + if matched. + +Some examples to illustrate the inputs and returned value: + + + +```js +var mediaType = 'application/json' + +typeis.is(mediaType, ['json']) // => 'json' +typeis.is(mediaType, ['html', 'json']) // => 'json' +typeis.is(mediaType, ['application/*']) // => 'application/json' +typeis.is(mediaType, ['application/json']) // => 'application/json' + +typeis.is(mediaType, ['html']) // => false +``` + +## Examples + +### Example body parser + +```js +var express = require('express') +var typeis = require('type-is') + +var app = express() + +app.use(function bodyParser (req, res, next) { + if (!typeis.hasBody(req)) { + return next() + } + + switch (typeis(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + case 'json': + // parse json body + throw new Error('implement json body parsing') + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + default: + // 415 error code + res.statusCode = 415 + res.end() + break + } +}) +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/type-is/master +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[node-version-image]: https://badgen.net/npm/node/type-is +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/type-is +[npm-url]: https://npmjs.org/package/type-is +[npm-version-image]: https://badgen.net/npm/v/type-is +[travis-image]: https://badgen.net/travis/jshttp/type-is/master +[travis-url]: https://travis-ci.org/jshttp/type-is diff --git a/node_modules/type-is/index.js b/node_modules/type-is/index.js new file mode 100644 index 0000000..890ad76 --- /dev/null +++ b/node_modules/type-is/index.js @@ -0,0 +1,266 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var typer = require('media-typer') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis (value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody (req) { + return req.headers['transfer-encoding'] !== undefined || + !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +function typeofrequest (req, types_) { + var types = types_ + + // no body + if (!hasbody(req)) { + return null + } + + // support flattened arguments + if (arguments.length > 2) { + types = new Array(arguments.length - 1) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @private + */ + +function normalize (type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @private + */ + +function mimeMatch (expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // validate suffix wildcard + if (expectedParts[1].substr(0, 2) === '*+') { + return expectedParts[1].length <= actualParts[1].length + 1 && + expectedParts[1].substr(1) === actualParts[1].substr(1 - expectedParts[1].length) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +function normalizeType (value) { + // parse the type + var type = typer.parse(value) + + // remove the parameters + type.parameters = undefined + + // reformat it + return typer.format(type) +} + +/** + * Try to normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +function tryNormalizeType (value) { + if (!value) { + return null + } + + try { + return normalizeType(value) + } catch (err) { + return null + } +} diff --git a/node_modules/type-is/package.json b/node_modules/type-is/package.json new file mode 100644 index 0000000..97ba5f1 --- /dev/null +++ b/node_modules/type-is/package.json @@ -0,0 +1,45 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "1.6.18", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/type-is", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "devDependencies": { + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "mocha": "6.1.4", + "nyc": "14.0.0" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + }, + "keywords": [ + "content", + "type", + "checking" + ] +} diff --git a/node_modules/unpipe/HISTORY.md b/node_modules/unpipe/HISTORY.md new file mode 100644 index 0000000..85e0f8d --- /dev/null +++ b/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/node_modules/unpipe/LICENSE b/node_modules/unpipe/LICENSE new file mode 100644 index 0000000..aed0138 --- /dev/null +++ b/node_modules/unpipe/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +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/unpipe/README.md b/node_modules/unpipe/README.md new file mode 100644 index 0000000..e536ad2 --- /dev/null +++ b/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/node_modules/unpipe/index.js b/node_modules/unpipe/index.js new file mode 100644 index 0000000..15c3d97 --- /dev/null +++ b/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/node_modules/unpipe/package.json b/node_modules/unpipe/package.json new file mode 100644 index 0000000..a2b7358 --- /dev/null +++ b/node_modules/unpipe/package.json @@ -0,0 +1,27 @@ +{ + "name": "unpipe", + "description": "Unpipe a stream from all destinations", + "version": "1.0.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "stream-utils/unpipe", + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/util-deprecate/History.md b/node_modules/util-deprecate/History.md new file mode 100644 index 0000000..acc8675 --- /dev/null +++ b/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/node_modules/util-deprecate/LICENSE b/node_modules/util-deprecate/LICENSE new file mode 100644 index 0000000..6a60e8c --- /dev/null +++ b/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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/util-deprecate/README.md b/node_modules/util-deprecate/README.md new file mode 100644 index 0000000..75622fa --- /dev/null +++ b/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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/util-deprecate/browser.js b/node_modules/util-deprecate/browser.js new file mode 100644 index 0000000..549ae2f --- /dev/null +++ b/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} diff --git a/node_modules/util-deprecate/node.js b/node_modules/util-deprecate/node.js new file mode 100644 index 0000000..5e6fcff --- /dev/null +++ b/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/node_modules/util-deprecate/package.json b/node_modules/util-deprecate/package.json new file mode 100644 index 0000000..2e79f89 --- /dev/null +++ b/node_modules/util-deprecate/package.json @@ -0,0 +1,27 @@ +{ + "name": "util-deprecate", + "version": "1.0.2", + "description": "The Node.js `util.deprecate()` function with browser support", + "main": "node.js", + "browser": "browser.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "homepage": "https://github.com/TooTallNate/util-deprecate" +} diff --git a/node_modules/utils-merge/.npmignore b/node_modules/utils-merge/.npmignore new file mode 100644 index 0000000..3e53844 --- /dev/null +++ b/node_modules/utils-merge/.npmignore @@ -0,0 +1,9 @@ +CONTRIBUTING.md +Makefile +docs/ +examples/ +reports/ +test/ + +.jshintrc +.travis.yml diff --git a/node_modules/utils-merge/LICENSE b/node_modules/utils-merge/LICENSE new file mode 100644 index 0000000..76f6d08 --- /dev/null +++ b/node_modules/utils-merge/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013-2017 Jared Hanson + +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/utils-merge/README.md b/node_modules/utils-merge/README.md new file mode 100644 index 0000000..0cb7117 --- /dev/null +++ b/node_modules/utils-merge/README.md @@ -0,0 +1,34 @@ +# utils-merge + +[![Version](https://img.shields.io/npm/v/utils-merge.svg?label=version)](https://www.npmjs.com/package/utils-merge) +[![Build](https://img.shields.io/travis/jaredhanson/utils-merge.svg)](https://travis-ci.org/jaredhanson/utils-merge) +[![Quality](https://img.shields.io/codeclimate/github/jaredhanson/utils-merge.svg?label=quality)](https://codeclimate.com/github/jaredhanson/utils-merge) +[![Coverage](https://img.shields.io/coveralls/jaredhanson/utils-merge.svg)](https://coveralls.io/r/jaredhanson/utils-merge) +[![Dependencies](https://img.shields.io/david/jaredhanson/utils-merge.svg)](https://david-dm.org/jaredhanson/utils-merge) + + +Merges the properties from a source object into a destination object. + +## Install + +```bash +$ npm install utils-merge +``` + +## Usage + +```javascript +var a = { foo: 'bar' } + , b = { bar: 'baz' }; + +merge(a, b); +// => { foo: 'bar', bar: 'baz' } +``` + +## License + +[The MIT License](http://opensource.org/licenses/MIT) + +Copyright (c) 2013-2017 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> + + Sponsor diff --git a/node_modules/utils-merge/index.js b/node_modules/utils-merge/index.js new file mode 100644 index 0000000..4265c69 --- /dev/null +++ b/node_modules/utils-merge/index.js @@ -0,0 +1,23 @@ +/** + * Merge object b with object a. + * + * var a = { foo: 'bar' } + * , b = { bar: 'baz' }; + * + * merge(a, b); + * // => { foo: 'bar', bar: 'baz' } + * + * @param {Object} a + * @param {Object} b + * @return {Object} + * @api public + */ + +exports = module.exports = function(a, b){ + if (a && b) { + for (var key in b) { + a[key] = b[key]; + } + } + return a; +}; diff --git a/node_modules/utils-merge/package.json b/node_modules/utils-merge/package.json new file mode 100644 index 0000000..e36b078 --- /dev/null +++ b/node_modules/utils-merge/package.json @@ -0,0 +1,40 @@ +{ + "name": "utils-merge", + "version": "1.0.1", + "description": "merge() utility function", + "keywords": [ + "util" + ], + "author": { + "name": "Jared Hanson", + "email": "jaredhanson@gmail.com", + "url": "http://www.jaredhanson.net/" + }, + "repository": { + "type": "git", + "url": "git://github.com/jaredhanson/utils-merge.git" + }, + "bugs": { + "url": "http://github.com/jaredhanson/utils-merge/issues" + }, + "license": "MIT", + "licenses": [ + { + "type": "MIT", + "url": "http://opensource.org/licenses/MIT" + } + ], + "main": "./index", + "dependencies": {}, + "devDependencies": { + "make-node": "0.3.x", + "mocha": "1.x.x", + "chai": "1.x.x" + }, + "engines": { + "node": ">= 0.4.0" + }, + "scripts": { + "test": "node_modules/.bin/mocha --reporter spec --require test/bootstrap/node test/*.test.js" + } +} diff --git a/node_modules/validator/LICENSE b/node_modules/validator/LICENSE new file mode 100644 index 0000000..4e49a38 --- /dev/null +++ b/node_modules/validator/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2018 Chris O'Hara + +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/validator/README.md b/node_modules/validator/README.md new file mode 100644 index 0000000..2cf6505 --- /dev/null +++ b/node_modules/validator/README.md @@ -0,0 +1,274 @@ +# validator.js + +[![NPM version][npm-image]][npm-url] +[![CI][ci-image]][ci-url] +[![Coverage][codecov-image]][codecov-url] +[![Downloads][downloads-image]][npm-url] +[![Backers on Open Collective](https://opencollective.com/validatorjs/backers/badge.svg)](#backers) +[![Sponsors on Open Collective](https://opencollective.com/validatorjs/sponsors/badge.svg)](#sponsors) +[![Gitter](https://badges.gitter.im/validatorjs/community.svg)](https://gitter.im/validatorjs/community) + +A library of string validators and sanitizers. + +## Strings only + +**This library validates and sanitizes strings only.** + +If you're not sure if your input is a string, coerce it using `input + ''`. +Passing anything other than a string will result in an error. + +## Installation and Usage + +### Server-side usage + +Install the library with `npm install validator` + +#### No ES6 + +```javascript +var validator = require('validator'); + +validator.isEmail('foo@bar.com'); //=> true +``` + +#### ES6 + +```javascript +import validator from 'validator'; +``` + +Or, import only a subset of the library: + +```javascript +import isEmail from 'validator/lib/isEmail'; +``` + +#### Tree-shakeable ES imports + +```javascript +import isEmail from 'validator/es/lib/isEmail'; +``` + +### Client-side usage + +The library can be loaded either as a standalone script, or through an [AMD][amd]-compatible loader + +```html + + +``` + +The library can also be installed through [bower][bower] + +```bash +$ bower install validator-js +``` + +CDN + +```html + +``` + +## Contributors + +[Become a backer](https://opencollective.com/validatorjs#backer) + +[Become a sponsor](https://opencollective.com/validatorjs#sponsor) + +Thank you to the people who have already contributed: + + + +## Validators + +Here is a list of the validators currently available. + +Validator | Description +--------------------------------------- | -------------------------------------- +**contains(str, seed [, options ])** | check if the string contains the seed.

`options` is an object that defaults to `{ ignoreCase: false, minOccurrences: 1 }`.
Options:
`ignoreCase`: Ignore case when doing comparison, default false
`minOccurences`: Minimum number of occurrences for the seed in the string. Defaults to 1. +**equals(str, comparison)** | check if the string matches the comparison. +**isAfter(str [, date])** | check if the string is a date that's after the specified date (defaults to now). +**isAlpha(str [, locale, options])** | check if the string contains only letters (a-zA-Z).

Locale is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fa-IR', 'fi-FI', 'fr-CA', 'fr-FR', 'he', 'hi-IN', 'hu-HU', 'it-IT', 'ku-IQ', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sl-SI', 'sk-SK', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`) and defaults to `en-US`. Locale list is `validator.isAlphaLocales`. options is an optional object that can be supplied with the following key(s): ignore which can either be a String or RegExp of characters to be ignored e.g. " -" will ignore spaces and -'s. +**isAlphanumeric(str [, locale, options])** | check if the string contains only letters and numbers (a-zA-Z0-9).

Locale is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fa-IR', 'fi-FI', 'fr-CA', 'fr-FR', 'he', 'hi-IN', 'hu-HU', 'it-IT', 'ku-IQ', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sl-SI', 'sk-SK', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`) and defaults to `en-US`. Locale list is `validator.isAlphanumericLocales`. options is an optional object that can be supplied with the following key(s): ignore which can either be a String or RegExp of characters to be ignored e.g. " -" will ignore spaces and -'s. +**isAscii(str)** | check if the string contains ASCII chars only. +**isBase32(str)** | check if a string is base32 encoded. +**isBase58(str)** | check if a string is base58 encoded. +**isBase64(str [, options])** | check if a string is base64 encoded. options is optional and defaults to `{urlSafe: false}`
when `urlSafe` is true it tests the given base64 encoded string is [url safe](https://base64.guru/standards/base64url) +**isBefore(str [, date])** | check if the string is a date that's before the specified date. +**isBIC(str)** | check if a string is a BIC (Bank Identification Code) or SWIFT code. +**isBoolean(str [, options])** | check if a string is a boolean.
`options` is an object which defaults to `{ loose: false }`. If loose is is set to false, the validator will strictly match ['true', 'false', '0', '1']. If loose is set to true, the validator will also match 'yes', 'no', and will match a valid boolean string of any case. (eg: ['true', 'True', 'TRUE']). +**isBtcAddress(str)** | check if the string is a valid BTC address. +**isByteLength(str [, options])** | check if the string's length (in UTF-8 bytes) falls in a range.

`options` is an object which defaults to `{min:0, max: undefined}`. +**isCreditCard(str)** | check if the string is a credit card. +**isCurrency(str [, options])** | check if the string is a valid currency amount.

`options` is an object which defaults to `{symbol: '$', require_symbol: false, allow_space_after_symbol: false, symbol_after_digits: false, allow_negatives: true, parens_for_negatives: false, negative_sign_before_digits: false, negative_sign_after_digits: false, allow_negative_sign_placeholder: false, thousands_separator: ',', decimal_separator: '.', allow_decimal: true, require_decimal: false, digits_after_decimal: [2], allow_space_after_digits: false}`.
**Note:** The array `digits_after_decimal` is filled with the exact number of digits allowed not a range, for example a range 1 to 3 will be given as [1, 2, 3]. +**isDataURI(str)** | check if the string is a [data uri format](https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs). +**isDate(input [, options])** | Check if the input is a valid date. e.g. [`2002-07-15`, new Date()].

`options` is an object which can contain the keys `format`, `strictMode` and/or `delimiters`

`format` is a string and defaults to `YYYY/MM/DD`.

`strictMode` is a boolean and defaults to `false`. If `strictMode` is set to true, the validator will reject inputs different from `format`.

`delimiters` is an array of allowed date delimiters and defaults to `['/', '-']`. +**isDecimal(str [, options])** | check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc.

`options` is an object which defaults to `{force_decimal: false, decimal_digits: '1,', locale: 'en-US'}`

`locale` determine the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fa', 'fa-AF', 'fa-IR', 'fr-FR', 'fr-CA', 'hu-HU', 'id-ID', 'it-IT', 'ku-IQ', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pl-Pl', 'pt-BR', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA', 'vi-VN']`.
**Note:** `decimal_digits` is given as a range like '1,3', a specific value like '3' or min like '1,'. +**isDivisibleBy(str, number)** | check if the string is a number that's divisible by another. +**isEAN(str)** | check if the string is an EAN (European Article Number). +**isEmail(str [, options])** | check if the string is an email.

`options` is an object which defaults to `{ allow_display_name: false, require_display_name: false, allow_utf8_local_part: true, require_tld: true, allow_ip_domain: false, domain_specific_validation: false, blacklisted_chars: '', host_blacklist: [] }`. If `allow_display_name` is set to true, the validator will also match `Display Name `. If `require_display_name` is set to true, the validator will reject strings without the format `Display Name `. If `allow_utf8_local_part` is set to false, the validator will not allow any non-English UTF8 character in email address' local part. If `require_tld` is set to false, e-mail addresses without having TLD in their domain will also be matched. If `ignore_max_length` is set to true, the validator will not check for the standard max length of an email. If `allow_ip_domain` is set to true, the validator will allow IP addresses in the host part. If `domain_specific_validation` is true, some additional validation will be enabled, e.g. disallowing certain syntactically valid email addresses that are rejected by GMail. If `blacklisted_chars` receives a string, then the validator will reject emails that include any of the characters in the string, in the name part. If `host_blacklist` is set to an array of strings and the part of the email after the `@` symbol matches one of the strings defined in it, the validation fails. +**isEmpty(str [, options])** | check if the string has a length of zero.

`options` is an object which defaults to `{ ignore_whitespace:false }`. +**isEthereumAddress(str)** | check if the string is an [Ethereum](https://ethereum.org/) address using basic regex. Does not validate address checksums. +**isFloat(str [, options])** | check if the string is a float.

`options` is an object which can contain the keys `min`, `max`, `gt`, and/or `lt` to validate the float is within boundaries (e.g. `{ min: 7.22, max: 9.55 }`) it also has `locale` as an option.

`min` and `max` are equivalent to 'greater or equal' and 'less or equal', respectively while `gt` and `lt` are their strict counterparts.

`locale` determine the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-CA', 'fr-FR', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`. Locale list is `validator.isFloatLocales`. +**isFQDN(str [, options])** | check if the string is a fully qualified domain name (e.g. domain.com).

`options` is an object which defaults to `{ require_tld: true, allow_underscores: false, allow_trailing_dot: false, allow_numeric_tld: false, allow_wildcard: false }`. If `allow_wildcard` is set to true, the validator will allow domain starting with `*.` (e.g. `*.example.com` or `*.shop.example.com`). +**isFullWidth(str)** | check if the string contains any full-width chars. +**isHalfWidth(str)** | check if the string contains any half-width chars. +**isHash(str, algorithm)** | check if the string is a hash of type algorithm.

Algorithm is one of `['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b']` +**isHexadecimal(str)** | check if the string is a hexadecimal number. +**isHexColor(str)** | check if the string is a hexadecimal color. +**isHSL(str)** | check if the string is an HSL (hue, saturation, lightness, optional alpha) color based on [CSS Colors Level 4 specification](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).

Comma-separated format supported. Space-separated format supported with the exception of a few edge cases (ex: `hsl(200grad+.1%62%/1)`). +**isIBAN(str)** | check if a string is a IBAN (International Bank Account Number). +**isIdentityCard(str [, locale])** | check if the string is a valid identity card code.

`locale` is one of `['LK', 'PL', 'ES', 'FI', 'IN', 'IT', 'IR', 'MZ', 'NO', 'TH', 'zh-TW', 'he-IL', 'ar-LY', 'ar-TN', 'zh-CN']` OR `'any'`. If 'any' is used, function will check if any of the locals match.

Defaults to 'any'. +**isIMEI(str [, options]))** | check if the string is a valid IMEI number. Imei should be of format `###############` or `##-######-######-#`.

`options` is an object which can contain the keys `allow_hyphens`. Defaults to first format . If allow_hyphens is set to true, the validator will validate the second format. +**isIn(str, values)** | check if the string is in a array of allowed values. +**isInt(str [, options])** | check if the string is an integer.

`options` is an object which can contain the keys `min` and/or `max` to check the integer is within boundaries (e.g. `{ min: 10, max: 99 }`). `options` can also contain the key `allow_leading_zeroes`, which when set to false will disallow integer values with leading zeroes (e.g. `{ allow_leading_zeroes: false }`). Finally, `options` can contain the keys `gt` and/or `lt` which will enforce integers being greater than or less than, respectively, the value provided (e.g. `{gt: 1, lt: 4}` for a number between 1 and 4). +**isIP(str [, version])** | check if the string is an IP (version 4 or 6). +**isIPRange(str [, version])** | check if the string is an IP Range (version 4 or 6). +**isISBN(str [, version])** | check if the string is an ISBN (version 10 or 13). +**isISIN(str)** | check if the string is an [ISIN][ISIN] (stock/security identifier). +**isISO8601(str)** | check if the string is a valid [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date.
`options` is an object which defaults to `{ strict: false, strictSeparator: false }`. If `strict` is true, date strings with invalid dates like `2009-02-29` will be invalid. If `strictSeparator` is true, date strings with date and time separated by anything other than a T will be invalid. +**isISO31661Alpha2(str)** | check if the string is a valid [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) officially assigned country code. +**isISO31661Alpha3(str)** | check if the string is a valid [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) officially assigned country code. +**isISO4217(str)** | check if the string is a valid [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) officially assigned currency code. +**isISRC(str)** | check if the string is a [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code). +**isISSN(str [, options])** | check if the string is an [ISSN](https://en.wikipedia.org/wiki/International_Standard_Serial_Number).

`options` is an object which defaults to `{ case_sensitive: false, require_hyphen: false }`. If `case_sensitive` is true, ISSNs with a lowercase `'x'` as the check digit are rejected. +**isJSON(str [, options])** | check if the string is valid JSON (note: uses JSON.parse).

`options` is an object which defaults to `{ allow_primitives: false }`. If `allow_primitives` is true, the primitives 'true', 'false' and 'null' are accepted as valid JSON values. +**isJWT(str)** | check if the string is valid JWT token. +**isLatLong(str [, options])** | check if the string is a valid latitude-longitude coordinate in the format `lat,long` or `lat, long`.

`options` is an object that defaults to `{ checkDMS: false }`. Pass `checkDMS` as `true` to validate DMS(degrees, minutes, and seconds) latitude-longitude format. +**isLength(str [, options])** | check if the string's length falls in a range.

`options` is an object which defaults to `{min:0, max: undefined}`. Note: this function takes into account surrogate pairs. +**isLicensePlate(str [, locale])** | check if string matches the format of a country's license plate.

(locale is one of `['cs-CZ', 'de-DE', 'de-LI', 'fi-FI', pt-PT', 'sq-AL', 'pt-BR']` or `any`) +**isLocale(str)** | check if the string is a locale +**isLowercase(str)** | check if the string is lowercase. +**isMACAddress(str)** | check if the string is a MAC address.

`options` is an object which defaults to `{no_separators: false}`. If `no_separators` is true, the validator will allow MAC addresses without separators. Also, it allows the use of hyphens, spaces or dots e.g '01 02 03 04 05 ab', '01-02-03-04-05-ab' or '0102.0304.05ab'. +**isMagnetURI(str)** | check if the string is a [magnet uri format](https://en.wikipedia.org/wiki/Magnet_URI_scheme). +**isMD5(str)** | check if the string is a MD5 hash.

Please note that you can also use the `isHash(str, 'md5')` function. Keep in mind that MD5 has some collision weaknesses compared to other algorithms (e.g., SHA). +**isMimeType(str)** | check if the string matches to a valid [MIME type](https://en.wikipedia.org/wiki/Media_type) format +**isMobilePhone(str [, locale [, options]])** | check if the string is a mobile phone number,

(locale is either an array of locales (e.g `['sk-SK', 'sr-RS']`) OR one of `['am-Am', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', ar-JO', 'ar-KW', 'ar-PS', 'ar-SA', 'ar-SY', 'ar-TN', 'az-AZ', 'az-LY', 'az-LB', 'bs-BA', 'be-BY', 'bg-BG', 'bn-BD', 'ca-AD', 'cs-CZ', 'da-DK', 'de-DE', 'de-AT', 'de-CH', 'de-LU', 'dv-MV', 'el-GR', 'en-AU', 'en-BM', 'en-BW', 'en-CA', 'en-GB', 'en-GG', 'en-GH', 'en-GY', 'en-HK', 'en-MO', 'en-IE', 'en-IN', 'en-KE', 'en-KI', 'en-MT', 'en-MU', 'en-NG', 'en-NZ', 'en-PK', 'en-PH', 'en-RW', 'en-SG', 'en-SL', 'en-UG', 'en-US', 'en-TZ', 'en-ZA', 'en-ZM', 'en-ZW', 'es-AR', 'es-BO', 'es-CL', 'es-CO', 'es-CR', 'es-CU', 'es-DO', 'es-HN', 'es-PE', 'es-EC', 'es-ES', 'es-MX', 'es-PA', 'es-PY', 'es-SV', 'es-UY', 'es-VE', 'et-EE', 'fa-IR', 'fi-FI', 'fj-FJ', 'fo-FO', 'fr-BE', 'fr-BF', 'fr-FR', 'fr-GF', 'fr-GP', 'fr-MQ', 'fr-PF', 'fr-RE', 'ga-IE', 'he-IL', 'hu-HU', 'id-ID', 'it-IT', 'it-SM', 'ja-JP', 'ka-GE', 'kk-KZ', 'kl-GL', 'ko-KR', 'lt-LT', 'ms-MY', ''mz-MZ', nb-NO', 'ne-NP', 'nl-BE', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'pt-AO', 'ro-RO', 'ru-RU', 'si-LK' 'sl-SI', 'sk-SK', 'sq-AL', 'sr-RS', 'sv-SE', 'tg-TJ', 'th-TH', 'tk-TM', 'tr-TR', 'uk-UA', 'uz-UZ', 'vi-VN', 'zh-CN', 'zh-HK', 'zh-MO', 'zh-TW', 'dz-BT']` OR defaults to 'any'. If 'any' or a falsey value is used, function will check if any of the locales match).

`options` is an optional object that can be supplied with the following keys: `strictMode`, if this is set to `true`, the mobile phone number must be supplied with the country code and therefore must start with `+`. Locale list is `validator.isMobilePhoneLocales`. +**isMongoId(str)** | check if the string is a valid hex-encoded representation of a [MongoDB ObjectId][mongoid]. +**isMultibyte(str)** | check if the string contains one or more multibyte chars. +**isNumeric(str [, options])** | check if the string contains only numbers.

`options` is an object which defaults to `{no_symbols: false}` it also has locale as an option. If `no_symbols` is true, the validator will reject numeric strings that feature a symbol (e.g. `+`, `-`, or `.`).

`locale` determine the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-FR', 'fr-CA', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`. +**isOctal(str)** | check if the string is a valid octal number. +**isPassportNumber(str, countryCode)** | check if the string is a valid passport number.

(countryCode is one of `[ 'AM', 'AR', 'AT', 'AU', 'BE', 'BG', 'BY', 'BR', 'CA', 'CH', 'CN', 'CY', 'CZ', 'DE', 'DK', 'DZ', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HR', 'HU', 'IE' 'IN', 'IR', 'ID', 'IS', 'IT', 'JP', 'KR', 'LT', 'LU', 'LV', 'LY', 'MT', 'MY', 'MZ', 'NL', 'PL', 'PT', 'RO', 'RU', 'SE', 'SL', 'SK', 'TR', 'UA', 'US' ]`. +**isPort(str)** | check if the string is a valid port number. +**isPostalCode(str, locale)** | check if the string is a postal code,

(locale is one of `[ 'AD', 'AT', 'AU', 'AZ', 'BE', 'BG', 'BR', 'BY', 'CA', 'CH', 'CN', 'CZ', 'DE', 'DK', 'DO', 'DZ', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HR', 'HT', 'HU', 'ID', 'IE' 'IL', 'IN', 'IR', 'IS', 'IT', 'JP', 'KE', 'KR', 'LI', 'LK', 'LT', 'LU', 'LV', 'MT', 'MX', 'MY', 'NL', 'NO', 'NP', 'NZ', 'PL', 'PR', 'PT', 'RO', 'RU', 'SA', 'SE', 'SG', 'SI', 'TH', 'TN', 'TW', 'UA', 'US', 'ZA', 'ZM' ]` OR 'any'. If 'any' is used, function will check if any of the locals match. Locale list is `validator.isPostalCodeLocales`.). +**isRFC3339(str)** | check if the string is a valid [RFC 3339](https://tools.ietf.org/html/rfc3339) date. +**isRgbColor(str [, includePercentValues])** | check if the string is a rgb or rgba color.

`includePercentValues` defaults to `true`. If you don't want to allow to set `rgb` or `rgba` values with percents, like `rgb(5%,5%,5%)`, or `rgba(90%,90%,90%,.3)`, then set it to false. +**isSemVer(str)** | check if the string is a Semantic Versioning Specification (SemVer). +**isSurrogatePair(str)** | check if the string contains any surrogate pairs chars. +**isUppercase(str)** | check if the string is uppercase. +**isSlug** | Check if the string is of type slug. `Options` allow a single hyphen between string. e.g. [`cn-cn`, `cn-c-c`] +**isStrongPassword(str [, options])** | Check if a password is strong or not. Allows for custom requirements or scoring rules. If `returnScore` is true, then the function returns an integer score for the password rather than a boolean.
Default options:
`{ minLength: 8, minLowercase: 1, minUppercase: 1, minNumbers: 1, minSymbols: 1, returnScore: false, pointsPerUnique: 1, pointsPerRepeat: 0.5, pointsForContainingLower: 10, pointsForContainingUpper: 10, pointsForContainingNumber: 10, pointsForContainingSymbol: 10 }` +**isTaxID(str, locale)** | Check if the given value is a valid Tax Identification Number. Default locale is `en-US`.

More info about exact TIN support can be found in `src/lib/isTaxID.js`

Supported locales: `[ 'bg-BG', 'cs-CZ', 'de-AT', 'de-DE', 'dk-DK', 'el-CY', 'el-GR', 'en-GB', 'en-IE', 'en-US', 'es-ES', 'et-EE', 'fi-FI', 'fr-BE', 'fr-FR', 'fr-LU', 'hr-HR', 'hu-HU', 'it-IT', 'lb-LU', 'lt-LT', 'lv-LV' 'mt-MT', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-BR', 'pt-PT', 'ro-RO', 'sk-SK', 'sl-SI', 'sv-SE' ]` +**isURL(str [, options])** | check if the string is an URL.

`options` is an object which defaults to `{ protocols: ['http','https','ftp'], require_tld: true, require_protocol: false, require_host: true, require_port: false, require_valid_protocol: true, allow_underscores: false, host_whitelist: false, host_blacklist: false, allow_trailing_dot: false, allow_protocol_relative_urls: false, allow_fragments: true, allow_query_components: true, disallow_auth: false, validate_length: true }`.

require_protocol - if set as true isURL will return false if protocol is not present in the URL.
require_valid_protocol - isURL will check if the URL's protocol is present in the protocols option.
protocols - valid protocols can be modified with this option.
require_host - if set as false isURL will not check if host is present in the URL.
require_port - if set as true isURL will check if port is present in the URL.
allow_protocol_relative_urls - if set as true protocol relative URLs will be allowed.
allow_fragments - if set as false isURL will return false if fragments are present.
allow_query_components - if set as false isURL will return false if query components are present.
validate_length - if set as false isURL will skip string length validation (2083 characters is IE max URL length). +**isUUID(str [, version])** | check if the string is a UUID (version 1, 2, 3, 4 or 5). +**isVariableWidth(str)** | check if the string contains a mixture of full and half-width chars. +**isVAT(str, countryCode)** | checks that the string is a [valid VAT number](https://en.wikipedia.org/wiki/VAT_identification_number) if validation is available for the given country code matching [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2).

Available country codes: `[ 'GB', 'IT','NL' ]`. +**isWhitelisted(str, chars)** | checks characters if they appear in the whitelist. +**matches(str, pattern [, modifiers])** | check if string matches the pattern.

Either `matches('foo', /foo/i)` or `matches('foo', 'foo', 'i')`. + +## Sanitizers + +Here is a list of the sanitizers currently available. + +Sanitizer | Description +-------------------------------------- | ------------------------------- +**blacklist(input, chars)** | remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `blacklist(input, '\\[\\]')`. +**escape(input)** | replace `<`, `>`, `&`, `'`, `"` and `/` with HTML entities. +**ltrim(input [, chars])** | trim characters from the left-side of the input. +**normalizeEmail(email [, options])** | canonicalizes an email address. (This doesn't validate that the input is an email, if you want to validate the email use isEmail beforehand)

`options` is an object with the following keys and default values:
  • *all_lowercase: true* - Transforms the local part (before the @ symbol) of all email addresses to lowercase. Please note that this may violate RFC 5321, which gives providers the possibility to treat the local part of email addresses in a case sensitive way (although in practice most - yet not all - providers don't). The domain part of the email address is always lowercased, as it's case insensitive per RFC 1035.
  • *gmail_lowercase: true* - GMail addresses are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, GMail addresses are lowercased regardless of the value of this setting.
  • *gmail_remove_dots: true*: Removes dots from the local part of the email address, as GMail ignores them (e.g. "john.doe" and "johndoe" are considered equal).
  • *gmail_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@gmail.com" becomes "foo@gmail.com").
  • *gmail_convert_googlemaildotcom: true*: Converts addresses with domain @googlemail.com to @gmail.com, as they're equivalent.
  • *outlookdotcom_lowercase: true* - Outlook.com addresses (including Windows Live and Hotmail) are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, Outlook.com addresses are lowercased regardless of the value of this setting.
  • *outlookdotcom_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@outlook.com" becomes "foo@outlook.com").
  • *yahoo_lowercase: true* - Yahoo Mail addresses are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, Yahoo Mail addresses are lowercased regardless of the value of this setting.
  • *yahoo_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "-" sign (e.g. "foo-bar@yahoo.com" becomes "foo@yahoo.com").
  • *icloud_lowercase: true* - iCloud addresses (including MobileMe) are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, iCloud addresses are lowercased regardless of the value of this setting.
  • *icloud_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@icloud.com" becomes "foo@icloud.com").
+**rtrim(input [, chars])** | trim characters from the right-side of the input. +**stripLow(input [, keep_new_lines])** | remove characters with a numerical value < 32 and 127, mostly control characters. If `keep_new_lines` is `true`, newline characters are preserved (`\n` and `\r`, hex `0xA` and `0xD`). Unicode-safe in JavaScript. +**toBoolean(input [, strict])** | convert the input string to a boolean. Everything except for `'0'`, `'false'` and `''` returns `true`. In strict mode only `'1'` and `'true'` return `true`. +**toDate(input)** | convert the input string to a date, or `null` if the input is not a date. +**toFloat(input)** | convert the input string to a float, or `NaN` if the input is not a float. +**toInt(input [, radix])** | convert the input string to an integer, or `NaN` if the input is not an integer. +**trim(input [, chars])** | trim characters (whitespace by default) from both sides of the input. +**unescape(input)** | replaces HTML encoded entities with `<`, `>`, `&`, `'`, `"` and `/`. +**whitelist(input, chars)** | remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `whitelist(input, '\\[\\]')`. + +### XSS Sanitization + +XSS sanitization was removed from the library in [2d5d6999](https://github.com/validatorjs/validator.js/commit/2d5d6999541add350fb396ef02dc42ca3215049e). + +For an alternative, have a look at Yahoo's [xss-filters library](https://github.com/yahoo/xss-filters) or at [DOMPurify](https://github.com/cure53/DOMPurify). + +## Contributing + +In general, we follow the "fork-and-pull" Git workflow. + +1. Fork the repo on GitHub +2. Clone the project to your own machine +3. Work on your fork + 1. Make your changes and additions + - Most of your changes should be focused on `src/` and `test/` folders and/or `README.md`. + - Files such as `validator.js`, `validator.min.js` and files in `lib/` folder are autogenerated when running tests (`npm test`) and need not to be changed **manually**. + 2. Change or add tests if needed + 3. Run tests and make sure they pass + 4. Add changes to README.md if needed +4. Commit changes to your own branch +5. **Make sure** you merge the latest from "upstream" and resolve conflicts if there is any +6. Repeat step 3(3) above +7. Push your work back up to your fork +8. Submit a Pull request so that we can review your changes + +## Tests + +Tests are using mocha, to run the tests use: + +```sh +$ npm test +``` + +## Maintainers + +- [chriso](https://github.com/chriso) - **Chris O'Hara** (author) +- [profnandaa](https://github.com/profnandaa) - **Anthony Nandaa** + +## Reading + +Remember, validating can be troublesome sometimes. See [A list of articles about programming assumptions commonly made that aren't true](https://github.com/jameslk/awesome-falsehoods). + +## License (MIT) + +``` +Copyright (c) 2018 Chris O'Hara + +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. +``` + +[downloads-image]: http://img.shields.io/npm/dm/validator.svg + +[npm-url]: https://npmjs.org/package/validator +[npm-image]: http://img.shields.io/npm/v/validator.svg + +[codecov-url]: https://codecov.io/gh/validatorjs/validator.js +[codecov-image]: https://codecov.io/gh/validatorjs/validator.js/branch/master/graph/badge.svg + +[ci-url]: https://github.com/validatorjs/validator.js/actions?query=workflow%3ACI +[ci-image]: https://github.com/validatorjs/validator.js/workflows/CI/badge.svg?branch=master + +[amd]: http://requirejs.org/docs/whyamd.html +[bower]: http://bower.io/ + +[mongoid]: http://docs.mongodb.org/manual/reference/object-id/ +[ISIN]: https://en.wikipedia.org/wiki/International_Securities_Identification_Number diff --git a/node_modules/validator/es/index.js b/node_modules/validator/es/index.js new file mode 100644 index 0000000..ed4eb79 --- /dev/null +++ b/node_modules/validator/es/index.js @@ -0,0 +1,198 @@ +import toDate from './lib/toDate'; +import toFloat from './lib/toFloat'; +import toInt from './lib/toInt'; +import toBoolean from './lib/toBoolean'; +import equals from './lib/equals'; +import contains from './lib/contains'; +import matches from './lib/matches'; +import isEmail from './lib/isEmail'; +import isURL from './lib/isURL'; +import isMACAddress from './lib/isMACAddress'; +import isIP from './lib/isIP'; +import isIPRange from './lib/isIPRange'; +import isFQDN from './lib/isFQDN'; +import isDate from './lib/isDate'; +import isBoolean from './lib/isBoolean'; +import isLocale from './lib/isLocale'; +import isAlpha, { locales as isAlphaLocales } from './lib/isAlpha'; +import isAlphanumeric, { locales as isAlphanumericLocales } from './lib/isAlphanumeric'; +import isNumeric from './lib/isNumeric'; +import isPassportNumber from './lib/isPassportNumber'; +import isPort from './lib/isPort'; +import isLowercase from './lib/isLowercase'; +import isUppercase from './lib/isUppercase'; +import isIMEI from './lib/isIMEI'; +import isAscii from './lib/isAscii'; +import isFullWidth from './lib/isFullWidth'; +import isHalfWidth from './lib/isHalfWidth'; +import isVariableWidth from './lib/isVariableWidth'; +import isMultibyte from './lib/isMultibyte'; +import isSemVer from './lib/isSemVer'; +import isSurrogatePair from './lib/isSurrogatePair'; +import isInt from './lib/isInt'; +import isFloat, { locales as isFloatLocales } from './lib/isFloat'; +import isDecimal from './lib/isDecimal'; +import isHexadecimal from './lib/isHexadecimal'; +import isOctal from './lib/isOctal'; +import isDivisibleBy from './lib/isDivisibleBy'; +import isHexColor from './lib/isHexColor'; +import isRgbColor from './lib/isRgbColor'; +import isHSL from './lib/isHSL'; +import isISRC from './lib/isISRC'; +import isIBAN, { locales as ibanLocales } from './lib/isIBAN'; +import isBIC from './lib/isBIC'; +import isMD5 from './lib/isMD5'; +import isHash from './lib/isHash'; +import isJWT from './lib/isJWT'; +import isJSON from './lib/isJSON'; +import isEmpty from './lib/isEmpty'; +import isLength from './lib/isLength'; +import isByteLength from './lib/isByteLength'; +import isUUID from './lib/isUUID'; +import isMongoId from './lib/isMongoId'; +import isAfter from './lib/isAfter'; +import isBefore from './lib/isBefore'; +import isIn from './lib/isIn'; +import isCreditCard from './lib/isCreditCard'; +import isIdentityCard from './lib/isIdentityCard'; +import isEAN from './lib/isEAN'; +import isISIN from './lib/isISIN'; +import isISBN from './lib/isISBN'; +import isISSN from './lib/isISSN'; +import isTaxID from './lib/isTaxID'; +import isMobilePhone, { locales as isMobilePhoneLocales } from './lib/isMobilePhone'; +import isEthereumAddress from './lib/isEthereumAddress'; +import isCurrency from './lib/isCurrency'; +import isBtcAddress from './lib/isBtcAddress'; +import isISO8601 from './lib/isISO8601'; +import isRFC3339 from './lib/isRFC3339'; +import isISO31661Alpha2 from './lib/isISO31661Alpha2'; +import isISO31661Alpha3 from './lib/isISO31661Alpha3'; +import isISO4217 from './lib/isISO4217'; +import isBase32 from './lib/isBase32'; +import isBase58 from './lib/isBase58'; +import isBase64 from './lib/isBase64'; +import isDataURI from './lib/isDataURI'; +import isMagnetURI from './lib/isMagnetURI'; +import isMimeType from './lib/isMimeType'; +import isLatLong from './lib/isLatLong'; +import isPostalCode, { locales as isPostalCodeLocales } from './lib/isPostalCode'; +import ltrim from './lib/ltrim'; +import rtrim from './lib/rtrim'; +import trim from './lib/trim'; +import escape from './lib/escape'; +import unescape from './lib/unescape'; +import stripLow from './lib/stripLow'; +import whitelist from './lib/whitelist'; +import blacklist from './lib/blacklist'; +import isWhitelisted from './lib/isWhitelisted'; +import normalizeEmail from './lib/normalizeEmail'; +import isSlug from './lib/isSlug'; +import isLicensePlate from './lib/isLicensePlate'; +import isStrongPassword from './lib/isStrongPassword'; +import isVAT from './lib/isVAT'; +var version = '13.7.0'; +var validator = { + version: version, + toDate: toDate, + toFloat: toFloat, + toInt: toInt, + toBoolean: toBoolean, + equals: equals, + contains: contains, + matches: matches, + isEmail: isEmail, + isURL: isURL, + isMACAddress: isMACAddress, + isIP: isIP, + isIPRange: isIPRange, + isFQDN: isFQDN, + isBoolean: isBoolean, + isIBAN: isIBAN, + isBIC: isBIC, + isAlpha: isAlpha, + isAlphaLocales: isAlphaLocales, + isAlphanumeric: isAlphanumeric, + isAlphanumericLocales: isAlphanumericLocales, + isNumeric: isNumeric, + isPassportNumber: isPassportNumber, + isPort: isPort, + isLowercase: isLowercase, + isUppercase: isUppercase, + isAscii: isAscii, + isFullWidth: isFullWidth, + isHalfWidth: isHalfWidth, + isVariableWidth: isVariableWidth, + isMultibyte: isMultibyte, + isSemVer: isSemVer, + isSurrogatePair: isSurrogatePair, + isInt: isInt, + isIMEI: isIMEI, + isFloat: isFloat, + isFloatLocales: isFloatLocales, + isDecimal: isDecimal, + isHexadecimal: isHexadecimal, + isOctal: isOctal, + isDivisibleBy: isDivisibleBy, + isHexColor: isHexColor, + isRgbColor: isRgbColor, + isHSL: isHSL, + isISRC: isISRC, + isMD5: isMD5, + isHash: isHash, + isJWT: isJWT, + isJSON: isJSON, + isEmpty: isEmpty, + isLength: isLength, + isLocale: isLocale, + isByteLength: isByteLength, + isUUID: isUUID, + isMongoId: isMongoId, + isAfter: isAfter, + isBefore: isBefore, + isIn: isIn, + isCreditCard: isCreditCard, + isIdentityCard: isIdentityCard, + isEAN: isEAN, + isISIN: isISIN, + isISBN: isISBN, + isISSN: isISSN, + isMobilePhone: isMobilePhone, + isMobilePhoneLocales: isMobilePhoneLocales, + isPostalCode: isPostalCode, + isPostalCodeLocales: isPostalCodeLocales, + isEthereumAddress: isEthereumAddress, + isCurrency: isCurrency, + isBtcAddress: isBtcAddress, + isISO8601: isISO8601, + isRFC3339: isRFC3339, + isISO31661Alpha2: isISO31661Alpha2, + isISO31661Alpha3: isISO31661Alpha3, + isISO4217: isISO4217, + isBase32: isBase32, + isBase58: isBase58, + isBase64: isBase64, + isDataURI: isDataURI, + isMagnetURI: isMagnetURI, + isMimeType: isMimeType, + isLatLong: isLatLong, + ltrim: ltrim, + rtrim: rtrim, + trim: trim, + escape: escape, + unescape: unescape, + stripLow: stripLow, + whitelist: whitelist, + blacklist: blacklist, + isWhitelisted: isWhitelisted, + normalizeEmail: normalizeEmail, + toString: toString, + isSlug: isSlug, + isStrongPassword: isStrongPassword, + isTaxID: isTaxID, + isDate: isDate, + isLicensePlate: isLicensePlate, + isVAT: isVAT, + ibanLocales: ibanLocales +}; +export default validator; \ No newline at end of file diff --git a/node_modules/validator/es/lib/alpha.js b/node_modules/validator/es/lib/alpha.js new file mode 100644 index 0000000..a1a9a76 --- /dev/null +++ b/node_modules/validator/es/lib/alpha.js @@ -0,0 +1,123 @@ +export var alpha = { + 'en-US': /^[A-Z]+$/i, + 'az-AZ': /^[A-VXYZÇƏĞİıÖŞÜ]+$/i, + 'bg-BG': /^[А-Я]+$/i, + 'cs-CZ': /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i, + 'da-DK': /^[A-ZÆØÅ]+$/i, + 'de-DE': /^[A-ZÄÖÜß]+$/i, + 'el-GR': /^[Α-ώ]+$/i, + 'es-ES': /^[A-ZÁÉÍÑÓÚÜ]+$/i, + 'fa-IR': /^[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهی]+$/i, + 'fi-FI': /^[A-ZÅÄÖ]+$/i, + 'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i, + 'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i, + 'nb-NO': /^[A-ZÆØÅ]+$/i, + 'nl-NL': /^[A-ZÁÉËÏÓÖÜÚ]+$/i, + 'nn-NO': /^[A-ZÆØÅ]+$/i, + 'hu-HU': /^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i, + 'pl-PL': /^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i, + 'pt-PT': /^[A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i, + 'ru-RU': /^[А-ЯЁ]+$/i, + 'sl-SI': /^[A-ZČĆĐŠŽ]+$/i, + 'sk-SK': /^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i, + 'sr-RS@latin': /^[A-ZČĆŽŠĐ]+$/i, + 'sr-RS': /^[А-ЯЂЈЉЊЋЏ]+$/i, + 'sv-SE': /^[A-ZÅÄÖ]+$/i, + 'th-TH': /^[ก-๐\s]+$/i, + 'tr-TR': /^[A-ZÇĞİıÖŞÜ]+$/i, + 'uk-UA': /^[А-ЩЬЮЯЄIЇҐі]+$/i, + 'vi-VN': /^[A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$/i, + 'ku-IQ': /^[ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i, + ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/, + he: /^[א-ת]+$/, + fa: /^['آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی']+$/i, + 'hi-IN': /^[\u0900-\u0961]+[\u0972-\u097F]*$/i +}; +export var alphanumeric = { + 'en-US': /^[0-9A-Z]+$/i, + 'az-AZ': /^[0-9A-VXYZÇƏĞİıÖŞÜ]+$/i, + 'bg-BG': /^[0-9А-Я]+$/i, + 'cs-CZ': /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i, + 'da-DK': /^[0-9A-ZÆØÅ]+$/i, + 'de-DE': /^[0-9A-ZÄÖÜß]+$/i, + 'el-GR': /^[0-9Α-ω]+$/i, + 'es-ES': /^[0-9A-ZÁÉÍÑÓÚÜ]+$/i, + 'fi-FI': /^[0-9A-ZÅÄÖ]+$/i, + 'fr-FR': /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i, + 'it-IT': /^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i, + 'hu-HU': /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i, + 'nb-NO': /^[0-9A-ZÆØÅ]+$/i, + 'nl-NL': /^[0-9A-ZÁÉËÏÓÖÜÚ]+$/i, + 'nn-NO': /^[0-9A-ZÆØÅ]+$/i, + 'pl-PL': /^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$/i, + 'pt-PT': /^[0-9A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i, + 'ru-RU': /^[0-9А-ЯЁ]+$/i, + 'sl-SI': /^[0-9A-ZČĆĐŠŽ]+$/i, + 'sk-SK': /^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i, + 'sr-RS@latin': /^[0-9A-ZČĆŽŠĐ]+$/i, + 'sr-RS': /^[0-9А-ЯЂЈЉЊЋЏ]+$/i, + 'sv-SE': /^[0-9A-ZÅÄÖ]+$/i, + 'th-TH': /^[ก-๙\s]+$/i, + 'tr-TR': /^[0-9A-ZÇĞİıÖŞÜ]+$/i, + 'uk-UA': /^[0-9А-ЩЬЮЯЄIЇҐі]+$/i, + 'ku-IQ': /^[٠١٢٣٤٥٦٧٨٩0-9ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i, + 'vi-VN': /^[0-9A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$/i, + ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/, + he: /^[0-9א-ת]+$/, + fa: /^['0-9آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی۱۲۳۴۵۶۷۸۹۰']+$/i, + 'hi-IN': /^[\u0900-\u0963]+[\u0966-\u097F]*$/i +}; +export var decimal = { + 'en-US': '.', + ar: '٫' +}; +export var englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM']; + +for (var locale, i = 0; i < englishLocales.length; i++) { + locale = "en-".concat(englishLocales[i]); + alpha[locale] = alpha['en-US']; + alphanumeric[locale] = alphanumeric['en-US']; + decimal[locale] = decimal['en-US']; +} // Source: http://www.localeplanet.com/java/ + + +export var arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE']; + +for (var _locale, _i = 0; _i < arabicLocales.length; _i++) { + _locale = "ar-".concat(arabicLocales[_i]); + alpha[_locale] = alpha.ar; + alphanumeric[_locale] = alphanumeric.ar; + decimal[_locale] = decimal.ar; +} + +export var farsiLocales = ['IR', 'AF']; + +for (var _locale2, _i2 = 0; _i2 < farsiLocales.length; _i2++) { + _locale2 = "fa-".concat(farsiLocales[_i2]); + alphanumeric[_locale2] = alphanumeric.fa; + decimal[_locale2] = decimal.ar; +} // Source: https://en.wikipedia.org/wiki/Decimal_mark + + +export var dotDecimal = ['ar-EG', 'ar-LB', 'ar-LY']; +export var commaDecimal = ['bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-ZM', 'es-ES', 'fr-CA', 'fr-FR', 'id-ID', 'it-IT', 'ku-IQ', 'hi-IN', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA', 'vi-VN']; + +for (var _i3 = 0; _i3 < dotDecimal.length; _i3++) { + decimal[dotDecimal[_i3]] = decimal['en-US']; +} + +for (var _i4 = 0; _i4 < commaDecimal.length; _i4++) { + decimal[commaDecimal[_i4]] = ','; +} + +alpha['fr-CA'] = alpha['fr-FR']; +alphanumeric['fr-CA'] = alphanumeric['fr-FR']; +alpha['pt-BR'] = alpha['pt-PT']; +alphanumeric['pt-BR'] = alphanumeric['pt-PT']; +decimal['pt-BR'] = decimal['pt-PT']; // see #862 + +alpha['pl-Pl'] = alpha['pl-PL']; +alphanumeric['pl-Pl'] = alphanumeric['pl-PL']; +decimal['pl-Pl'] = decimal['pl-PL']; // see #1455 + +alpha['fa-AF'] = alpha.fa; \ No newline at end of file diff --git a/node_modules/validator/es/lib/blacklist.js b/node_modules/validator/es/lib/blacklist.js new file mode 100644 index 0000000..77c0e5c --- /dev/null +++ b/node_modules/validator/es/lib/blacklist.js @@ -0,0 +1,5 @@ +import assertString from './util/assertString'; +export default function blacklist(str, chars) { + assertString(str); + return str.replace(new RegExp("[".concat(chars, "]+"), 'g'), ''); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/contains.js b/node_modules/validator/es/lib/contains.js new file mode 100644 index 0000000..bf654b8 --- /dev/null +++ b/node_modules/validator/es/lib/contains.js @@ -0,0 +1,17 @@ +import assertString from './util/assertString'; +import toString from './util/toString'; +import merge from './util/merge'; +var defaulContainsOptions = { + ignoreCase: false, + minOccurrences: 1 +}; +export default function contains(str, elem, options) { + assertString(str); + options = merge(options, defaulContainsOptions); + + if (options.ignoreCase) { + return str.toLowerCase().split(toString(elem).toLowerCase()).length > options.minOccurrences; + } + + return str.split(toString(elem)).length > options.minOccurrences; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/equals.js b/node_modules/validator/es/lib/equals.js new file mode 100644 index 0000000..87a9ded --- /dev/null +++ b/node_modules/validator/es/lib/equals.js @@ -0,0 +1,5 @@ +import assertString from './util/assertString'; +export default function equals(str, comparison) { + assertString(str); + return str === comparison; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/escape.js b/node_modules/validator/es/lib/escape.js new file mode 100644 index 0000000..e9bb6de --- /dev/null +++ b/node_modules/validator/es/lib/escape.js @@ -0,0 +1,5 @@ +import assertString from './util/assertString'; +export default function escape(str) { + assertString(str); + return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>').replace(/\//g, '/').replace(/\\/g, '\').replace(/`/g, '`'); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isAfter.js b/node_modules/validator/es/lib/isAfter.js new file mode 100644 index 0000000..b99cfa4 --- /dev/null +++ b/node_modules/validator/es/lib/isAfter.js @@ -0,0 +1,9 @@ +import assertString from './util/assertString'; +import toDate from './toDate'; +export default function isAfter(str) { + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date()); + assertString(str); + var comparison = toDate(date); + var original = toDate(str); + return !!(original && comparison && original > comparison); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isAlpha.js b/node_modules/validator/es/lib/isAlpha.js new file mode 100644 index 0000000..5214b74 --- /dev/null +++ b/node_modules/validator/es/lib/isAlpha.js @@ -0,0 +1,26 @@ +import assertString from './util/assertString'; +import { alpha } from './alpha'; +export default function isAlpha(_str) { + var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + assertString(_str); + var str = _str; + var ignore = options.ignore; + + if (ignore) { + if (ignore instanceof RegExp) { + str = str.replace(ignore, ''); + } else if (typeof ignore === 'string') { + str = str.replace(new RegExp("[".concat(ignore.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'), "]"), 'g'), ''); // escape regex for ignore + } else { + throw new Error('ignore should be instance of a String or RegExp'); + } + } + + if (locale in alpha) { + return alpha[locale].test(str); + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} +export var locales = Object.keys(alpha); \ No newline at end of file diff --git a/node_modules/validator/es/lib/isAlphanumeric.js b/node_modules/validator/es/lib/isAlphanumeric.js new file mode 100644 index 0000000..b0556e5 --- /dev/null +++ b/node_modules/validator/es/lib/isAlphanumeric.js @@ -0,0 +1,26 @@ +import assertString from './util/assertString'; +import { alphanumeric } from './alpha'; +export default function isAlphanumeric(_str) { + var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + assertString(_str); + var str = _str; + var ignore = options.ignore; + + if (ignore) { + if (ignore instanceof RegExp) { + str = str.replace(ignore, ''); + } else if (typeof ignore === 'string') { + str = str.replace(new RegExp("[".concat(ignore.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'), "]"), 'g'), ''); // escape regex for ignore + } else { + throw new Error('ignore should be instance of a String or RegExp'); + } + } + + if (locale in alphanumeric) { + return alphanumeric[locale].test(str); + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} +export var locales = Object.keys(alphanumeric); \ No newline at end of file diff --git a/node_modules/validator/es/lib/isAscii.js b/node_modules/validator/es/lib/isAscii.js new file mode 100644 index 0000000..e322121 --- /dev/null +++ b/node_modules/validator/es/lib/isAscii.js @@ -0,0 +1,10 @@ +import assertString from './util/assertString'; +/* eslint-disable no-control-regex */ + +var ascii = /^[\x00-\x7F]+$/; +/* eslint-enable no-control-regex */ + +export default function isAscii(str) { + assertString(str); + return ascii.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isBIC.js b/node_modules/validator/es/lib/isBIC.js new file mode 100644 index 0000000..8434a71 --- /dev/null +++ b/node_modules/validator/es/lib/isBIC.js @@ -0,0 +1,14 @@ +import assertString from './util/assertString'; +import { CountryCodes } from './isISO31661Alpha2'; // https://en.wikipedia.org/wiki/ISO_9362 + +var isBICReg = /^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$/; +export default function isBIC(str) { + assertString(str); // toUpperCase() should be removed when a new major version goes out that changes + // the regex to [A-Z] (per the spec). + + if (!CountryCodes.has(str.slice(4, 6).toUpperCase())) { + return false; + } + + return isBICReg.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isBase32.js b/node_modules/validator/es/lib/isBase32.js new file mode 100644 index 0000000..d018f80 --- /dev/null +++ b/node_modules/validator/es/lib/isBase32.js @@ -0,0 +1,12 @@ +import assertString from './util/assertString'; +var base32 = /^[A-Z2-7]+=*$/; +export default function isBase32(str) { + assertString(str); + var len = str.length; + + if (len % 8 === 0 && base32.test(str)) { + return true; + } + + return false; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isBase58.js b/node_modules/validator/es/lib/isBase58.js new file mode 100644 index 0000000..863bbe9 --- /dev/null +++ b/node_modules/validator/es/lib/isBase58.js @@ -0,0 +1,12 @@ +import assertString from './util/assertString'; // Accepted chars - 123456789ABCDEFGH JKLMN PQRSTUVWXYZabcdefghijk mnopqrstuvwxyz + +var base58Reg = /^[A-HJ-NP-Za-km-z1-9]*$/; +export default function isBase58(str) { + assertString(str); + + if (base58Reg.test(str)) { + return true; + } + + return false; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isBase64.js b/node_modules/validator/es/lib/isBase64.js new file mode 100644 index 0000000..04467fc --- /dev/null +++ b/node_modules/validator/es/lib/isBase64.js @@ -0,0 +1,23 @@ +import assertString from './util/assertString'; +import merge from './util/merge'; +var notBase64 = /[^A-Z0-9+\/=]/i; +var urlSafeBase64 = /^[A-Z0-9_\-]*$/i; +var defaultBase64Options = { + urlSafe: false +}; +export default function isBase64(str, options) { + assertString(str); + options = merge(options, defaultBase64Options); + var len = str.length; + + if (options.urlSafe) { + return urlSafeBase64.test(str); + } + + if (len % 4 !== 0 || notBase64.test(str)) { + return false; + } + + var firstPaddingChar = str.indexOf('='); + return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '='; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isBefore.js b/node_modules/validator/es/lib/isBefore.js new file mode 100644 index 0000000..794dbab --- /dev/null +++ b/node_modules/validator/es/lib/isBefore.js @@ -0,0 +1,9 @@ +import assertString from './util/assertString'; +import toDate from './toDate'; +export default function isBefore(str) { + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date()); + assertString(str); + var comparison = toDate(date); + var original = toDate(str); + return !!(original && comparison && original < comparison); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isBoolean.js b/node_modules/validator/es/lib/isBoolean.js new file mode 100644 index 0000000..c0be07a --- /dev/null +++ b/node_modules/validator/es/lib/isBoolean.js @@ -0,0 +1,16 @@ +import assertString from './util/assertString'; +var defaultOptions = { + loose: false +}; +var strictBooleans = ['true', 'false', '1', '0']; +var looseBooleans = [].concat(strictBooleans, ['yes', 'no']); +export default function isBoolean(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultOptions; + assertString(str); + + if (options.loose) { + return looseBooleans.includes(str.toLowerCase()); + } + + return strictBooleans.includes(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isBtcAddress.js b/node_modules/validator/es/lib/isBtcAddress.js new file mode 100644 index 0000000..e29c912 --- /dev/null +++ b/node_modules/validator/es/lib/isBtcAddress.js @@ -0,0 +1,13 @@ +import assertString from './util/assertString'; // supports Bech32 addresses + +var bech32 = /^(bc1)[a-z0-9]{25,39}$/; +var base58 = /^(1|3)[A-HJ-NP-Za-km-z1-9]{25,39}$/; +export default function isBtcAddress(str) { + assertString(str); // check for bech32 + + if (str.startsWith('bc1')) { + return bech32.test(str); + } + + return base58.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isByteLength.js b/node_modules/validator/es/lib/isByteLength.js new file mode 100644 index 0000000..eee2543 --- /dev/null +++ b/node_modules/validator/es/lib/isByteLength.js @@ -0,0 +1,22 @@ +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +import assertString from './util/assertString'; +/* eslint-disable prefer-rest-params */ + +export default function isByteLength(str, options) { + assertString(str); + var min; + var max; + + if (_typeof(options) === 'object') { + min = options.min || 0; + max = options.max; + } else { + // backwards compatibility: isByteLength(str, min [, max]) + min = arguments[1]; + max = arguments[2]; + } + + var len = encodeURI(str).split(/%..|./).length - 1; + return len >= min && (typeof max === 'undefined' || len <= max); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isCreditCard.js b/node_modules/validator/es/lib/isCreditCard.js new file mode 100644 index 0000000..f1beb2d --- /dev/null +++ b/node_modules/validator/es/lib/isCreditCard.js @@ -0,0 +1,40 @@ +import assertString from './util/assertString'; +/* eslint-disable max-len */ + +var creditCard = /^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/; +/* eslint-enable max-len */ + +export default function isCreditCard(str) { + assertString(str); + var sanitized = str.replace(/[- ]+/g, ''); + + if (!creditCard.test(sanitized)) { + return false; + } + + var sum = 0; + var digit; + var tmpNum; + var shouldDouble; + + for (var i = sanitized.length - 1; i >= 0; i--) { + digit = sanitized.substring(i, i + 1); + tmpNum = parseInt(digit, 10); + + if (shouldDouble) { + tmpNum *= 2; + + if (tmpNum >= 10) { + sum += tmpNum % 10 + 1; + } else { + sum += tmpNum; + } + } else { + sum += tmpNum; + } + + shouldDouble = !shouldDouble; + } + + return !!(sum % 10 === 0 ? sanitized : false); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isCurrency.js b/node_modules/validator/es/lib/isCurrency.js new file mode 100644 index 0000000..519ee19 --- /dev/null +++ b/node_modules/validator/es/lib/isCurrency.js @@ -0,0 +1,77 @@ +import merge from './util/merge'; +import assertString from './util/assertString'; + +function currencyRegex(options) { + var decimal_digits = "\\d{".concat(options.digits_after_decimal[0], "}"); + options.digits_after_decimal.forEach(function (digit, index) { + if (index !== 0) decimal_digits = "".concat(decimal_digits, "|\\d{").concat(digit, "}"); + }); + var symbol = "(".concat(options.symbol.replace(/\W/, function (m) { + return "\\".concat(m); + }), ")").concat(options.require_symbol ? '' : '?'), + negative = '-?', + whole_dollar_amount_without_sep = '[1-9]\\d*', + whole_dollar_amount_with_sep = "[1-9]\\d{0,2}(\\".concat(options.thousands_separator, "\\d{3})*"), + valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep], + whole_dollar_amount = "(".concat(valid_whole_dollar_amounts.join('|'), ")?"), + decimal_amount = "(\\".concat(options.decimal_separator, "(").concat(decimal_digits, "))").concat(options.require_decimal ? '' : '?'); + var pattern = whole_dollar_amount + (options.allow_decimal || options.require_decimal ? decimal_amount : ''); // default is negative sign before symbol, but there are two other options (besides parens) + + if (options.allow_negatives && !options.parens_for_negatives) { + if (options.negative_sign_after_digits) { + pattern += negative; + } else if (options.negative_sign_before_digits) { + pattern = negative + pattern; + } + } // South African Rand, for example, uses R 123 (space) and R-123 (no space) + + + if (options.allow_negative_sign_placeholder) { + pattern = "( (?!\\-))?".concat(pattern); + } else if (options.allow_space_after_symbol) { + pattern = " ?".concat(pattern); + } else if (options.allow_space_after_digits) { + pattern += '( (?!$))?'; + } + + if (options.symbol_after_digits) { + pattern += symbol; + } else { + pattern = symbol + pattern; + } + + if (options.allow_negatives) { + if (options.parens_for_negatives) { + pattern = "(\\(".concat(pattern, "\\)|").concat(pattern, ")"); + } else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) { + pattern = negative + pattern; + } + } // ensure there's a dollar and/or decimal amount, and that + // it doesn't start with a space or a negative sign followed by a space + + + return new RegExp("^(?!-? )(?=.*\\d)".concat(pattern, "$")); +} + +var default_currency_options = { + symbol: '$', + require_symbol: false, + allow_space_after_symbol: false, + symbol_after_digits: false, + allow_negatives: true, + parens_for_negatives: false, + negative_sign_before_digits: false, + negative_sign_after_digits: false, + allow_negative_sign_placeholder: false, + thousands_separator: ',', + decimal_separator: '.', + allow_decimal: true, + require_decimal: false, + digits_after_decimal: [2], + allow_space_after_digits: false +}; +export default function isCurrency(str, options) { + assertString(str); + options = merge(options, default_currency_options); + return currencyRegex(options).test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isDataURI.js b/node_modules/validator/es/lib/isDataURI.js new file mode 100644 index 0000000..a32d05e --- /dev/null +++ b/node_modules/validator/es/lib/isDataURI.js @@ -0,0 +1,39 @@ +import assertString from './util/assertString'; +var validMediaType = /^[a-z]+\/[a-z0-9\-\+]+$/i; +var validAttribute = /^[a-z\-]+=[a-z0-9\-]+$/i; +var validData = /^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$/i; +export default function isDataURI(str) { + assertString(str); + var data = str.split(','); + + if (data.length < 2) { + return false; + } + + var attributes = data.shift().trim().split(';'); + var schemeAndMediaType = attributes.shift(); + + if (schemeAndMediaType.substr(0, 5) !== 'data:') { + return false; + } + + var mediaType = schemeAndMediaType.substr(5); + + if (mediaType !== '' && !validMediaType.test(mediaType)) { + return false; + } + + for (var i = 0; i < attributes.length; i++) { + if (!(i === attributes.length - 1 && attributes[i].toLowerCase() === 'base64') && !validAttribute.test(attributes[i])) { + return false; + } + } + + for (var _i = 0; _i < data.length; _i++) { + if (!validData.test(data[_i])) { + return false; + } + } + + return true; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isDate.js b/node_modules/validator/es/lib/isDate.js new file mode 100644 index 0000000..c4d0d08 --- /dev/null +++ b/node_modules/validator/es/lib/isDate.js @@ -0,0 +1,86 @@ +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +import merge from './util/merge'; +var default_date_options = { + format: 'YYYY/MM/DD', + delimiters: ['/', '-'], + strictMode: false +}; + +function isValidFormat(format) { + return /(^(y{4}|y{2})[.\/-](m{1,2})[.\/-](d{1,2})$)|(^(m{1,2})[.\/-](d{1,2})[.\/-]((y{4}|y{2})$))|(^(d{1,2})[.\/-](m{1,2})[.\/-]((y{4}|y{2})$))/gi.test(format); +} + +function zip(date, format) { + var zippedArr = [], + len = Math.min(date.length, format.length); + + for (var i = 0; i < len; i++) { + zippedArr.push([date[i], format[i]]); + } + + return zippedArr; +} + +export default function isDate(input, options) { + if (typeof options === 'string') { + // Allow backward compatbility for old format isDate(input [, format]) + options = merge({ + format: options + }, default_date_options); + } else { + options = merge(options, default_date_options); + } + + if (typeof input === 'string' && isValidFormat(options.format)) { + var formatDelimiter = options.delimiters.find(function (delimiter) { + return options.format.indexOf(delimiter) !== -1; + }); + var dateDelimiter = options.strictMode ? formatDelimiter : options.delimiters.find(function (delimiter) { + return input.indexOf(delimiter) !== -1; + }); + var dateAndFormat = zip(input.split(dateDelimiter), options.format.toLowerCase().split(formatDelimiter)); + var dateObj = {}; + + var _iterator = _createForOfIteratorHelper(dateAndFormat), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _step$value = _slicedToArray(_step.value, 2), + dateWord = _step$value[0], + formatWord = _step$value[1]; + + if (dateWord.length !== formatWord.length) { + return false; + } + + dateObj[formatWord.charAt(0)] = dateWord; + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + + return new Date("".concat(dateObj.m, "/").concat(dateObj.d, "/").concat(dateObj.y)).getDate() === +dateObj.d; + } + + if (!options.strictMode) { + return Object.prototype.toString.call(input) === '[object Date]' && isFinite(input); + } + + return false; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isDecimal.js b/node_modules/validator/es/lib/isDecimal.js new file mode 100644 index 0000000..597f42c --- /dev/null +++ b/node_modules/validator/es/lib/isDecimal.js @@ -0,0 +1,26 @@ +import merge from './util/merge'; +import assertString from './util/assertString'; +import includes from './util/includes'; +import { decimal } from './alpha'; + +function decimalRegExp(options) { + var regExp = new RegExp("^[-+]?([0-9]+)?(\\".concat(decimal[options.locale], "[0-9]{").concat(options.decimal_digits, "})").concat(options.force_decimal ? '' : '?', "$")); + return regExp; +} + +var default_decimal_options = { + force_decimal: false, + decimal_digits: '1,', + locale: 'en-US' +}; +var blacklist = ['', '-', '+']; +export default function isDecimal(str, options) { + assertString(str); + options = merge(options, default_decimal_options); + + if (options.locale in decimal) { + return !includes(blacklist, str.replace(/ /g, '')) && decimalRegExp(options).test(str); + } + + throw new Error("Invalid locale '".concat(options.locale, "'")); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isDivisibleBy.js b/node_modules/validator/es/lib/isDivisibleBy.js new file mode 100644 index 0000000..f71d5f4 --- /dev/null +++ b/node_modules/validator/es/lib/isDivisibleBy.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +import toFloat from './toFloat'; +export default function isDivisibleBy(str, num) { + assertString(str); + return toFloat(str) % parseInt(num, 10) === 0; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isEAN.js b/node_modules/validator/es/lib/isEAN.js new file mode 100644 index 0000000..246db93 --- /dev/null +++ b/node_modules/validator/es/lib/isEAN.js @@ -0,0 +1,72 @@ +/** + * The most commonly used EAN standard is + * the thirteen-digit EAN-13, while the + * less commonly used 8-digit EAN-8 barcode was + * introduced for use on small packages. + * Also EAN/UCC-14 is used for Grouping of individual + * trade items above unit level(Intermediate, Carton or Pallet). + * For more info about EAN-14 checkout: https://www.gtin.info/itf-14-barcodes/ + * EAN consists of: + * GS1 prefix, manufacturer code, product code and check digit + * Reference: https://en.wikipedia.org/wiki/International_Article_Number + * Reference: https://www.gtin.info/ + */ +import assertString from './util/assertString'; +/** + * Define EAN Lenghts; 8 for EAN-8; 13 for EAN-13; 14 for EAN-14 + * and Regular Expression for valid EANs (EAN-8, EAN-13, EAN-14), + * with exact numberic matching of 8 or 13 or 14 digits [0-9] + */ + +var LENGTH_EAN_8 = 8; +var LENGTH_EAN_14 = 14; +var validEanRegex = /^(\d{8}|\d{13}|\d{14})$/; +/** + * Get position weight given: + * EAN length and digit index/position + * + * @param {number} length + * @param {number} index + * @return {number} + */ + +function getPositionWeightThroughLengthAndIndex(length, index) { + if (length === LENGTH_EAN_8 || length === LENGTH_EAN_14) { + return index % 2 === 0 ? 3 : 1; + } + + return index % 2 === 0 ? 1 : 3; +} +/** + * Calculate EAN Check Digit + * Reference: https://en.wikipedia.org/wiki/International_Article_Number#Calculation_of_checksum_digit + * + * @param {string} ean + * @return {number} + */ + + +function calculateCheckDigit(ean) { + var checksum = ean.slice(0, -1).split('').map(function (_char, index) { + return Number(_char) * getPositionWeightThroughLengthAndIndex(ean.length, index); + }).reduce(function (acc, partialSum) { + return acc + partialSum; + }, 0); + var remainder = 10 - checksum % 10; + return remainder < 10 ? remainder : 0; +} +/** + * Check if string is valid EAN: + * Matches EAN-8/EAN-13/EAN-14 regex + * Has valid check digit. + * + * @param {string} str + * @return {boolean} + */ + + +export default function isEAN(str) { + assertString(str); + var actualCheckDigit = Number(str.slice(-1)); + return validEanRegex.test(str) && actualCheckDigit === calculateCheckDigit(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isEmail.js b/node_modules/validator/es/lib/isEmail.js new file mode 100644 index 0000000..d44c1ac --- /dev/null +++ b/node_modules/validator/es/lib/isEmail.js @@ -0,0 +1,180 @@ +import assertString from './util/assertString'; +import merge from './util/merge'; +import isByteLength from './isByteLength'; +import isFQDN from './isFQDN'; +import isIP from './isIP'; +var default_email_options = { + allow_display_name: false, + require_display_name: false, + allow_utf8_local_part: true, + require_tld: true, + blacklisted_chars: '', + ignore_max_length: false, + host_blacklist: [] +}; +/* eslint-disable max-len */ + +/* eslint-disable no-control-regex */ + +var splitNameAddress = /^([^\x00-\x1F\x7F-\x9F\cX]+)]/.test(display_name_without_quotes); + + if (contains_illegal) { + // if contains illegal characters, + // must to be enclosed in double-quotes, otherwise it's not a valid display name + if (display_name_without_quotes === display_name) { + return false; + } // the quotes in display name must start with character symbol \ + + + var all_start_with_back_slash = display_name_without_quotes.split('"').length === display_name_without_quotes.split('\\"').length; + + if (!all_start_with_back_slash) { + return false; + } + } + + return true; +} + +export default function isEmail(str, options) { + assertString(str); + options = merge(options, default_email_options); + + if (options.require_display_name || options.allow_display_name) { + var display_email = str.match(splitNameAddress); + + if (display_email) { + var display_name = display_email[1]; // Remove display name and angle brackets to get email address + // Can be done in the regex but will introduce a ReDOS (See #1597 for more info) + + str = str.replace(display_name, '').replace(/(^<|>$)/g, ''); // sometimes need to trim the last space to get the display name + // because there may be a space between display name and email address + // eg. myname + // the display name is `myname` instead of `myname `, so need to trim the last space + + if (display_name.endsWith(' ')) { + display_name = display_name.substr(0, display_name.length - 1); + } + + if (!validateDisplayName(display_name)) { + return false; + } + } else if (options.require_display_name) { + return false; + } + } + + if (!options.ignore_max_length && str.length > defaultMaxEmailLength) { + return false; + } + + var parts = str.split('@'); + var domain = parts.pop(); + var lower_domain = domain.toLowerCase(); + + if (options.host_blacklist.includes(lower_domain)) { + return false; + } + + var user = parts.join('@'); + + if (options.domain_specific_validation && (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com')) { + /* + Previously we removed dots for gmail addresses before validating. + This was removed because it allows `multiple..dots@gmail.com` + to be reported as valid, but it is not. + Gmail only normalizes single dots, removing them from here is pointless, + should be done in normalizeEmail + */ + user = user.toLowerCase(); // Removing sub-address from username before gmail validation + + var username = user.split('+')[0]; // Dots are not included in gmail length restriction + + if (!isByteLength(username.replace(/\./g, ''), { + min: 6, + max: 30 + })) { + return false; + } + + var _user_parts = username.split('.'); + + for (var i = 0; i < _user_parts.length; i++) { + if (!gmailUserPart.test(_user_parts[i])) { + return false; + } + } + } + + if (options.ignore_max_length === false && (!isByteLength(user, { + max: 64 + }) || !isByteLength(domain, { + max: 254 + }))) { + return false; + } + + if (!isFQDN(domain, { + require_tld: options.require_tld + })) { + if (!options.allow_ip_domain) { + return false; + } + + if (!isIP(domain)) { + if (!domain.startsWith('[') || !domain.endsWith(']')) { + return false; + } + + var noBracketdomain = domain.substr(1, domain.length - 2); + + if (noBracketdomain.length === 0 || !isIP(noBracketdomain)) { + return false; + } + } + } + + if (user[0] === '"') { + user = user.slice(1, user.length - 1); + return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user); + } + + var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart; + var user_parts = user.split('.'); + + for (var _i = 0; _i < user_parts.length; _i++) { + if (!pattern.test(user_parts[_i])) { + return false; + } + } + + if (options.blacklisted_chars) { + if (user.search(new RegExp("[".concat(options.blacklisted_chars, "]+"), 'g')) !== -1) return false; + } + + return true; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isEmpty.js b/node_modules/validator/es/lib/isEmpty.js new file mode 100644 index 0000000..79e29f7 --- /dev/null +++ b/node_modules/validator/es/lib/isEmpty.js @@ -0,0 +1,10 @@ +import assertString from './util/assertString'; +import merge from './util/merge'; +var default_is_empty_options = { + ignore_whitespace: false +}; +export default function isEmpty(str, options) { + assertString(str); + options = merge(options, default_is_empty_options); + return (options.ignore_whitespace ? str.trim().length : str.length) === 0; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isEthereumAddress.js b/node_modules/validator/es/lib/isEthereumAddress.js new file mode 100644 index 0000000..9c70f64 --- /dev/null +++ b/node_modules/validator/es/lib/isEthereumAddress.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +var eth = /^(0x)[0-9a-f]{40}$/i; +export default function isEthereumAddress(str) { + assertString(str); + return eth.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isFQDN.js b/node_modules/validator/es/lib/isFQDN.js new file mode 100644 index 0000000..b63f737 --- /dev/null +++ b/node_modules/validator/es/lib/isFQDN.js @@ -0,0 +1,74 @@ +import assertString from './util/assertString'; +import merge from './util/merge'; +var default_fqdn_options = { + require_tld: true, + allow_underscores: false, + allow_trailing_dot: false, + allow_numeric_tld: false, + allow_wildcard: false +}; +export default function isFQDN(str, options) { + assertString(str); + options = merge(options, default_fqdn_options); + /* Remove the optional trailing dot before checking validity */ + + if (options.allow_trailing_dot && str[str.length - 1] === '.') { + str = str.substring(0, str.length - 1); + } + /* Remove the optional wildcard before checking validity */ + + + if (options.allow_wildcard === true && str.indexOf('*.') === 0) { + str = str.substring(2); + } + + var parts = str.split('.'); + var tld = parts[parts.length - 1]; + + if (options.require_tld) { + // disallow fqdns without tld + if (parts.length < 2) { + return false; + } + + if (!/^([a-z\u00A1-\u00A8\u00AA-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) { + return false; + } // disallow spaces + + + if (/\s/.test(tld)) { + return false; + } + } // reject numeric TLDs + + + if (!options.allow_numeric_tld && /^\d+$/.test(tld)) { + return false; + } + + return parts.every(function (part) { + if (part.length > 63) { + return false; + } + + if (!/^[a-z_\u00a1-\uffff0-9-]+$/i.test(part)) { + return false; + } // disallow full-width chars + + + if (/[\uff01-\uff5e]/.test(part)) { + return false; + } // disallow parts starting or ending with hyphen + + + if (/^-|-$/.test(part)) { + return false; + } + + if (!options.allow_underscores && /_/.test(part)) { + return false; + } + + return true; + }); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isFloat.js b/node_modules/validator/es/lib/isFloat.js new file mode 100644 index 0000000..069873b --- /dev/null +++ b/node_modules/validator/es/lib/isFloat.js @@ -0,0 +1,16 @@ +import assertString from './util/assertString'; +import { decimal } from './alpha'; +export default function isFloat(str, options) { + assertString(str); + options = options || {}; + + var _float = new RegExp("^(?:[-+])?(?:[0-9]+)?(?:\\".concat(options.locale ? decimal[options.locale] : '.', "[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$")); + + if (str === '' || str === '.' || str === '-' || str === '+') { + return false; + } + + var value = parseFloat(str.replace(',', '.')); + return _float.test(str) && (!options.hasOwnProperty('min') || value >= options.min) && (!options.hasOwnProperty('max') || value <= options.max) && (!options.hasOwnProperty('lt') || value < options.lt) && (!options.hasOwnProperty('gt') || value > options.gt); +} +export var locales = Object.keys(decimal); \ No newline at end of file diff --git a/node_modules/validator/es/lib/isFullWidth.js b/node_modules/validator/es/lib/isFullWidth.js new file mode 100644 index 0000000..ae54629 --- /dev/null +++ b/node_modules/validator/es/lib/isFullWidth.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +export var fullWidth = /[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/; +export default function isFullWidth(str) { + assertString(str); + return fullWidth.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isHSL.js b/node_modules/validator/es/lib/isHSL.js new file mode 100644 index 0000000..7efe8e9 --- /dev/null +++ b/node_modules/validator/es/lib/isHSL.js @@ -0,0 +1,14 @@ +import assertString from './util/assertString'; +var hslComma = /^hsla?\(((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?))(deg|grad|rad|turn)?(,(\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%){2}(,((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%?))?\)$/i; +var hslSpace = /^hsla?\(((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?))(deg|grad|rad|turn)?(\s(\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%){2}\s?(\/\s((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%?)\s?)?\)$/i; +export default function isHSL(str) { + assertString(str); // Strip duplicate spaces before calling the validation regex (See #1598 for more info) + + var strippedStr = str.replace(/\s+/g, ' ').replace(/\s?(hsla?\(|\)|,)\s?/ig, '$1'); + + if (strippedStr.indexOf(',') !== -1) { + return hslComma.test(strippedStr); + } + + return hslSpace.test(strippedStr); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isHalfWidth.js b/node_modules/validator/es/lib/isHalfWidth.js new file mode 100644 index 0000000..b0c8795 --- /dev/null +++ b/node_modules/validator/es/lib/isHalfWidth.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +export var halfWidth = /[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/; +export default function isHalfWidth(str) { + assertString(str); + return halfWidth.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isHash.js b/node_modules/validator/es/lib/isHash.js new file mode 100644 index 0000000..3495486 --- /dev/null +++ b/node_modules/validator/es/lib/isHash.js @@ -0,0 +1,21 @@ +import assertString from './util/assertString'; +var lengths = { + md5: 32, + md4: 32, + sha1: 40, + sha256: 64, + sha384: 96, + sha512: 128, + ripemd128: 32, + ripemd160: 40, + tiger128: 32, + tiger160: 40, + tiger192: 48, + crc32: 8, + crc32b: 8 +}; +export default function isHash(str, algorithm) { + assertString(str); + var hash = new RegExp("^[a-fA-F0-9]{".concat(lengths[algorithm], "}$")); + return hash.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isHexColor.js b/node_modules/validator/es/lib/isHexColor.js new file mode 100644 index 0000000..72eab2c --- /dev/null +++ b/node_modules/validator/es/lib/isHexColor.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +var hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i; +export default function isHexColor(str) { + assertString(str); + return hexcolor.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isHexadecimal.js b/node_modules/validator/es/lib/isHexadecimal.js new file mode 100644 index 0000000..6654de4 --- /dev/null +++ b/node_modules/validator/es/lib/isHexadecimal.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +var hexadecimal = /^(0x|0h)?[0-9A-F]+$/i; +export default function isHexadecimal(str) { + assertString(str); + return hexadecimal.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isIBAN.js b/node_modules/validator/es/lib/isIBAN.js new file mode 100644 index 0000000..0c97a01 --- /dev/null +++ b/node_modules/validator/es/lib/isIBAN.js @@ -0,0 +1,138 @@ +import assertString from './util/assertString'; +/** + * List of country codes with + * corresponding IBAN regular expression + * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number + */ + +var ibanRegexThroughCountryCode = { + AD: /^(AD[0-9]{2})\d{8}[A-Z0-9]{12}$/, + AE: /^(AE[0-9]{2})\d{3}\d{16}$/, + AL: /^(AL[0-9]{2})\d{8}[A-Z0-9]{16}$/, + AT: /^(AT[0-9]{2})\d{16}$/, + AZ: /^(AZ[0-9]{2})[A-Z0-9]{4}\d{20}$/, + BA: /^(BA[0-9]{2})\d{16}$/, + BE: /^(BE[0-9]{2})\d{12}$/, + BG: /^(BG[0-9]{2})[A-Z]{4}\d{6}[A-Z0-9]{8}$/, + BH: /^(BH[0-9]{2})[A-Z]{4}[A-Z0-9]{14}$/, + BR: /^(BR[0-9]{2})\d{23}[A-Z]{1}[A-Z0-9]{1}$/, + BY: /^(BY[0-9]{2})[A-Z0-9]{4}\d{20}$/, + CH: /^(CH[0-9]{2})\d{5}[A-Z0-9]{12}$/, + CR: /^(CR[0-9]{2})\d{18}$/, + CY: /^(CY[0-9]{2})\d{8}[A-Z0-9]{16}$/, + CZ: /^(CZ[0-9]{2})\d{20}$/, + DE: /^(DE[0-9]{2})\d{18}$/, + DK: /^(DK[0-9]{2})\d{14}$/, + DO: /^(DO[0-9]{2})[A-Z]{4}\d{20}$/, + EE: /^(EE[0-9]{2})\d{16}$/, + EG: /^(EG[0-9]{2})\d{25}$/, + ES: /^(ES[0-9]{2})\d{20}$/, + FI: /^(FI[0-9]{2})\d{14}$/, + FO: /^(FO[0-9]{2})\d{14}$/, + FR: /^(FR[0-9]{2})\d{10}[A-Z0-9]{11}\d{2}$/, + GB: /^(GB[0-9]{2})[A-Z]{4}\d{14}$/, + GE: /^(GE[0-9]{2})[A-Z0-9]{2}\d{16}$/, + GI: /^(GI[0-9]{2})[A-Z]{4}[A-Z0-9]{15}$/, + GL: /^(GL[0-9]{2})\d{14}$/, + GR: /^(GR[0-9]{2})\d{7}[A-Z0-9]{16}$/, + GT: /^(GT[0-9]{2})[A-Z0-9]{4}[A-Z0-9]{20}$/, + HR: /^(HR[0-9]{2})\d{17}$/, + HU: /^(HU[0-9]{2})\d{24}$/, + IE: /^(IE[0-9]{2})[A-Z0-9]{4}\d{14}$/, + IL: /^(IL[0-9]{2})\d{19}$/, + IQ: /^(IQ[0-9]{2})[A-Z]{4}\d{15}$/, + IR: /^(IR[0-9]{2})0\d{2}0\d{18}$/, + IS: /^(IS[0-9]{2})\d{22}$/, + IT: /^(IT[0-9]{2})[A-Z]{1}\d{10}[A-Z0-9]{12}$/, + JO: /^(JO[0-9]{2})[A-Z]{4}\d{22}$/, + KW: /^(KW[0-9]{2})[A-Z]{4}[A-Z0-9]{22}$/, + KZ: /^(KZ[0-9]{2})\d{3}[A-Z0-9]{13}$/, + LB: /^(LB[0-9]{2})\d{4}[A-Z0-9]{20}$/, + LC: /^(LC[0-9]{2})[A-Z]{4}[A-Z0-9]{24}$/, + LI: /^(LI[0-9]{2})\d{5}[A-Z0-9]{12}$/, + LT: /^(LT[0-9]{2})\d{16}$/, + LU: /^(LU[0-9]{2})\d{3}[A-Z0-9]{13}$/, + LV: /^(LV[0-9]{2})[A-Z]{4}[A-Z0-9]{13}$/, + MC: /^(MC[0-9]{2})\d{10}[A-Z0-9]{11}\d{2}$/, + MD: /^(MD[0-9]{2})[A-Z0-9]{20}$/, + ME: /^(ME[0-9]{2})\d{18}$/, + MK: /^(MK[0-9]{2})\d{3}[A-Z0-9]{10}\d{2}$/, + MR: /^(MR[0-9]{2})\d{23}$/, + MT: /^(MT[0-9]{2})[A-Z]{4}\d{5}[A-Z0-9]{18}$/, + MU: /^(MU[0-9]{2})[A-Z]{4}\d{19}[A-Z]{3}$/, + MZ: /^(MZ[0-9]{2})\d{21}$/, + NL: /^(NL[0-9]{2})[A-Z]{4}\d{10}$/, + NO: /^(NO[0-9]{2})\d{11}$/, + PK: /^(PK[0-9]{2})[A-Z0-9]{4}\d{16}$/, + PL: /^(PL[0-9]{2})\d{24}$/, + PS: /^(PS[0-9]{2})[A-Z0-9]{4}\d{21}$/, + PT: /^(PT[0-9]{2})\d{21}$/, + QA: /^(QA[0-9]{2})[A-Z]{4}[A-Z0-9]{21}$/, + RO: /^(RO[0-9]{2})[A-Z]{4}[A-Z0-9]{16}$/, + RS: /^(RS[0-9]{2})\d{18}$/, + SA: /^(SA[0-9]{2})\d{2}[A-Z0-9]{18}$/, + SC: /^(SC[0-9]{2})[A-Z]{4}\d{20}[A-Z]{3}$/, + SE: /^(SE[0-9]{2})\d{20}$/, + SI: /^(SI[0-9]{2})\d{15}$/, + SK: /^(SK[0-9]{2})\d{20}$/, + SM: /^(SM[0-9]{2})[A-Z]{1}\d{10}[A-Z0-9]{12}$/, + SV: /^(SV[0-9]{2})[A-Z0-9]{4}\d{20}$/, + TL: /^(TL[0-9]{2})\d{19}$/, + TN: /^(TN[0-9]{2})\d{20}$/, + TR: /^(TR[0-9]{2})\d{5}[A-Z0-9]{17}$/, + UA: /^(UA[0-9]{2})\d{6}[A-Z0-9]{19}$/, + VA: /^(VA[0-9]{2})\d{18}$/, + VG: /^(VG[0-9]{2})[A-Z0-9]{4}\d{16}$/, + XK: /^(XK[0-9]{2})\d{16}$/ +}; +/** + * Check whether string has correct universal IBAN format + * The IBAN consists of up to 34 alphanumeric characters, as follows: + * Country Code using ISO 3166-1 alpha-2, two letters + * check digits, two digits and + * Basic Bank Account Number (BBAN), up to 30 alphanumeric characters. + * NOTE: Permitted IBAN characters are: digits [0-9] and the 26 latin alphabetic [A-Z] + * + * @param {string} str - string under validation + * @return {boolean} + */ + +function hasValidIbanFormat(str) { + // Strip white spaces and hyphens + var strippedStr = str.replace(/[\s\-]+/gi, '').toUpperCase(); + var isoCountryCode = strippedStr.slice(0, 2).toUpperCase(); + return isoCountryCode in ibanRegexThroughCountryCode && ibanRegexThroughCountryCode[isoCountryCode].test(strippedStr); +} +/** + * Check whether string has valid IBAN Checksum + * by performing basic mod-97 operation and + * the remainder should equal 1 + * -- Start by rearranging the IBAN by moving the four initial characters to the end of the string + * -- Replace each letter in the string with two digits, A -> 10, B = 11, Z = 35 + * -- Interpret the string as a decimal integer and + * -- compute the remainder on division by 97 (mod 97) + * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number + * + * @param {string} str + * @return {boolean} + */ + + +function hasValidIbanChecksum(str) { + var strippedStr = str.replace(/[^A-Z0-9]+/gi, '').toUpperCase(); // Keep only digits and A-Z latin alphabetic + + var rearranged = strippedStr.slice(4) + strippedStr.slice(0, 4); + var alphaCapsReplacedWithDigits = rearranged.replace(/[A-Z]/g, function (_char) { + return _char.charCodeAt(0) - 55; + }); + var remainder = alphaCapsReplacedWithDigits.match(/\d{1,7}/g).reduce(function (acc, value) { + return Number(acc + value) % 97; + }, ''); + return remainder === 1; +} + +export default function isIBAN(str) { + assertString(str); + return hasValidIbanFormat(str) && hasValidIbanChecksum(str); +} +export var locales = Object.keys(ibanRegexThroughCountryCode); \ No newline at end of file diff --git a/node_modules/validator/es/lib/isIMEI.js b/node_modules/validator/es/lib/isIMEI.js new file mode 100644 index 0000000..27bd09d --- /dev/null +++ b/node_modules/validator/es/lib/isIMEI.js @@ -0,0 +1,47 @@ +import assertString from './util/assertString'; +var imeiRegexWithoutHypens = /^[0-9]{15}$/; +var imeiRegexWithHypens = /^\d{2}-\d{6}-\d{6}-\d{1}$/; +export default function isIMEI(str, options) { + assertString(str); + options = options || {}; // default regex for checking imei is the one without hyphens + + var imeiRegex = imeiRegexWithoutHypens; + + if (options.allow_hyphens) { + imeiRegex = imeiRegexWithHypens; + } + + if (!imeiRegex.test(str)) { + return false; + } + + str = str.replace(/-/g, ''); + var sum = 0, + mul = 2, + l = 14; + + for (var i = 0; i < l; i++) { + var digit = str.substring(l - i - 1, l - i); + var tp = parseInt(digit, 10) * mul; + + if (tp >= 10) { + sum += tp % 10 + 1; + } else { + sum += tp; + } + + if (mul === 1) { + mul += 1; + } else { + mul -= 1; + } + } + + var chk = (10 - sum % 10) % 10; + + if (chk !== parseInt(str.substring(14, 15), 10)) { + return false; + } + + return true; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isIP.js b/node_modules/validator/es/lib/isIP.js new file mode 100644 index 0000000..5cf3fd2 --- /dev/null +++ b/node_modules/validator/es/lib/isIP.js @@ -0,0 +1,62 @@ +import assertString from './util/assertString'; +/** +11.3. Examples + + The following addresses + + fe80::1234 (on the 1st link of the node) + ff02::5678 (on the 5th link of the node) + ff08::9abc (on the 10th organization of the node) + + would be represented as follows: + + fe80::1234%1 + ff02::5678%5 + ff08::9abc%10 + + (Here we assume a natural translation from a zone index to the + part, where the Nth zone of any scope is translated into + "N".) + + If we use interface names as , those addresses could also be + represented as follows: + + fe80::1234%ne0 + ff02::5678%pvc1.3 + ff08::9abc%interface10 + + where the interface "ne0" belongs to the 1st link, "pvc1.3" belongs + to the 5th link, and "interface10" belongs to the 10th organization. + * * */ + +var IPv4SegmentFormat = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'; +var IPv4AddressFormat = "(".concat(IPv4SegmentFormat, "[.]){3}").concat(IPv4SegmentFormat); +var IPv4AddressRegExp = new RegExp("^".concat(IPv4AddressFormat, "$")); +var IPv6SegmentFormat = '(?:[0-9a-fA-F]{1,4})'; +var IPv6AddressRegExp = new RegExp('^(' + "(?:".concat(IPv6SegmentFormat, ":){7}(?:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){6}(?:").concat(IPv4AddressFormat, "|:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){5}(?::").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,2}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){4}(?:(:").concat(IPv6SegmentFormat, "){0,1}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,3}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){3}(?:(:").concat(IPv6SegmentFormat, "){0,2}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,4}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){2}(?:(:").concat(IPv6SegmentFormat, "){0,3}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,5}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){1}(?:(:").concat(IPv6SegmentFormat, "){0,4}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,6}|:)|") + "(?::((?::".concat(IPv6SegmentFormat, "){0,5}:").concat(IPv4AddressFormat, "|(?::").concat(IPv6SegmentFormat, "){1,7}|:))") + ')(%[0-9a-zA-Z-.:]{1,})?$'); +export default function isIP(str) { + var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + assertString(str); + version = String(version); + + if (!version) { + return isIP(str, 4) || isIP(str, 6); + } + + if (version === '4') { + if (!IPv4AddressRegExp.test(str)) { + return false; + } + + var parts = str.split('.').sort(function (a, b) { + return a - b; + }); + return parts[3] <= 255; + } + + if (version === '6') { + return !!IPv6AddressRegExp.test(str); + } + + return false; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isIPRange.js b/node_modules/validator/es/lib/isIPRange.js new file mode 100644 index 0000000..209efdd --- /dev/null +++ b/node_modules/validator/es/lib/isIPRange.js @@ -0,0 +1,47 @@ +import assertString from './util/assertString'; +import isIP from './isIP'; +var subnetMaybe = /^\d{1,3}$/; +var v4Subnet = 32; +var v6Subnet = 128; +export default function isIPRange(str) { + var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + assertString(str); + var parts = str.split('/'); // parts[0] -> ip, parts[1] -> subnet + + if (parts.length !== 2) { + return false; + } + + if (!subnetMaybe.test(parts[1])) { + return false; + } // Disallow preceding 0 i.e. 01, 02, ... + + + if (parts[1].length > 1 && parts[1].startsWith('0')) { + return false; + } + + var isValidIP = isIP(parts[0], version); + + if (!isValidIP) { + return false; + } // Define valid subnet according to IP's version + + + var expectedSubnet = null; + + switch (String(version)) { + case '4': + expectedSubnet = v4Subnet; + break; + + case '6': + expectedSubnet = v6Subnet; + break; + + default: + expectedSubnet = isIP(parts[0], '6') ? v6Subnet : v4Subnet; + } + + return parts[1] <= expectedSubnet && parts[1] >= 0; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isISBN.js b/node_modules/validator/es/lib/isISBN.js new file mode 100644 index 0000000..da2c435 --- /dev/null +++ b/node_modules/validator/es/lib/isISBN.js @@ -0,0 +1,51 @@ +import assertString from './util/assertString'; +var isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/; +var isbn13Maybe = /^(?:[0-9]{13})$/; +var factor = [1, 3]; +export default function isISBN(str) { + var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + assertString(str); + version = String(version); + + if (!version) { + return isISBN(str, 10) || isISBN(str, 13); + } + + var sanitized = str.replace(/[\s-]+/g, ''); + var checksum = 0; + var i; + + if (version === '10') { + if (!isbn10Maybe.test(sanitized)) { + return false; + } + + for (i = 0; i < 9; i++) { + checksum += (i + 1) * sanitized.charAt(i); + } + + if (sanitized.charAt(9) === 'X') { + checksum += 10 * 10; + } else { + checksum += 10 * sanitized.charAt(9); + } + + if (checksum % 11 === 0) { + return !!sanitized; + } + } else if (version === '13') { + if (!isbn13Maybe.test(sanitized)) { + return false; + } + + for (i = 0; i < 12; i++) { + checksum += factor[i % 2] * sanitized.charAt(i); + } + + if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) { + return !!sanitized; + } + } + + return false; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isISIN.js b/node_modules/validator/es/lib/isISIN.js new file mode 100644 index 0000000..8e5b826 --- /dev/null +++ b/node_modules/validator/es/lib/isISIN.js @@ -0,0 +1,60 @@ +import assertString from './util/assertString'; +var isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/; // this link details how the check digit is calculated: +// https://www.isin.org/isin-format/. it is a little bit +// odd in that it works with digits, not numbers. in order +// to make only one pass through the ISIN characters, the +// each alpha character is handled as 2 characters within +// the loop. + +export default function isISIN(str) { + assertString(str); + + if (!isin.test(str)) { + return false; + } + + var _double = true; + var sum = 0; // convert values + + for (var i = str.length - 2; i >= 0; i--) { + if (str[i] >= 'A' && str[i] <= 'Z') { + var value = str[i].charCodeAt(0) - 55; + var lo = value % 10; + var hi = Math.trunc(value / 10); // letters have two digits, so handle the low order + // and high order digits separately. + + for (var _i = 0, _arr = [lo, hi]; _i < _arr.length; _i++) { + var digit = _arr[_i]; + + if (_double) { + if (digit >= 5) { + sum += 1 + (digit - 5) * 2; + } else { + sum += digit * 2; + } + } else { + sum += digit; + } + + _double = !_double; + } + } else { + var _digit = str[i].charCodeAt(0) - '0'.charCodeAt(0); + + if (_double) { + if (_digit >= 5) { + sum += 1 + (_digit - 5) * 2; + } else { + sum += _digit * 2; + } + } else { + sum += _digit; + } + + _double = !_double; + } + } + + var check = Math.trunc((sum + 9) / 10) * 10 - sum; + return +str[str.length - 1] === check; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isISO31661Alpha2.js b/node_modules/validator/es/lib/isISO31661Alpha2.js new file mode 100644 index 0000000..e8db93e --- /dev/null +++ b/node_modules/validator/es/lib/isISO31661Alpha2.js @@ -0,0 +1,8 @@ +import assertString from './util/assertString'; // from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 + +var validISO31661Alpha2CountriesCodes = new Set(['AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW']); +export default function isISO31661Alpha2(str) { + assertString(str); + return validISO31661Alpha2CountriesCodes.has(str.toUpperCase()); +} +export var CountryCodes = validISO31661Alpha2CountriesCodes; \ No newline at end of file diff --git a/node_modules/validator/es/lib/isISO31661Alpha3.js b/node_modules/validator/es/lib/isISO31661Alpha3.js new file mode 100644 index 0000000..41a615b --- /dev/null +++ b/node_modules/validator/es/lib/isISO31661Alpha3.js @@ -0,0 +1,7 @@ +import assertString from './util/assertString'; // from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3 + +var validISO31661Alpha3CountriesCodes = new Set(['AFG', 'ALA', 'ALB', 'DZA', 'ASM', 'AND', 'AGO', 'AIA', 'ATA', 'ATG', 'ARG', 'ARM', 'ABW', 'AUS', 'AUT', 'AZE', 'BHS', 'BHR', 'BGD', 'BRB', 'BLR', 'BEL', 'BLZ', 'BEN', 'BMU', 'BTN', 'BOL', 'BES', 'BIH', 'BWA', 'BVT', 'BRA', 'IOT', 'BRN', 'BGR', 'BFA', 'BDI', 'KHM', 'CMR', 'CAN', 'CPV', 'CYM', 'CAF', 'TCD', 'CHL', 'CHN', 'CXR', 'CCK', 'COL', 'COM', 'COG', 'COD', 'COK', 'CRI', 'CIV', 'HRV', 'CUB', 'CUW', 'CYP', 'CZE', 'DNK', 'DJI', 'DMA', 'DOM', 'ECU', 'EGY', 'SLV', 'GNQ', 'ERI', 'EST', 'ETH', 'FLK', 'FRO', 'FJI', 'FIN', 'FRA', 'GUF', 'PYF', 'ATF', 'GAB', 'GMB', 'GEO', 'DEU', 'GHA', 'GIB', 'GRC', 'GRL', 'GRD', 'GLP', 'GUM', 'GTM', 'GGY', 'GIN', 'GNB', 'GUY', 'HTI', 'HMD', 'VAT', 'HND', 'HKG', 'HUN', 'ISL', 'IND', 'IDN', 'IRN', 'IRQ', 'IRL', 'IMN', 'ISR', 'ITA', 'JAM', 'JPN', 'JEY', 'JOR', 'KAZ', 'KEN', 'KIR', 'PRK', 'KOR', 'KWT', 'KGZ', 'LAO', 'LVA', 'LBN', 'LSO', 'LBR', 'LBY', 'LIE', 'LTU', 'LUX', 'MAC', 'MKD', 'MDG', 'MWI', 'MYS', 'MDV', 'MLI', 'MLT', 'MHL', 'MTQ', 'MRT', 'MUS', 'MYT', 'MEX', 'FSM', 'MDA', 'MCO', 'MNG', 'MNE', 'MSR', 'MAR', 'MOZ', 'MMR', 'NAM', 'NRU', 'NPL', 'NLD', 'NCL', 'NZL', 'NIC', 'NER', 'NGA', 'NIU', 'NFK', 'MNP', 'NOR', 'OMN', 'PAK', 'PLW', 'PSE', 'PAN', 'PNG', 'PRY', 'PER', 'PHL', 'PCN', 'POL', 'PRT', 'PRI', 'QAT', 'REU', 'ROU', 'RUS', 'RWA', 'BLM', 'SHN', 'KNA', 'LCA', 'MAF', 'SPM', 'VCT', 'WSM', 'SMR', 'STP', 'SAU', 'SEN', 'SRB', 'SYC', 'SLE', 'SGP', 'SXM', 'SVK', 'SVN', 'SLB', 'SOM', 'ZAF', 'SGS', 'SSD', 'ESP', 'LKA', 'SDN', 'SUR', 'SJM', 'SWZ', 'SWE', 'CHE', 'SYR', 'TWN', 'TJK', 'TZA', 'THA', 'TLS', 'TGO', 'TKL', 'TON', 'TTO', 'TUN', 'TUR', 'TKM', 'TCA', 'TUV', 'UGA', 'UKR', 'ARE', 'GBR', 'USA', 'UMI', 'URY', 'UZB', 'VUT', 'VEN', 'VNM', 'VGB', 'VIR', 'WLF', 'ESH', 'YEM', 'ZMB', 'ZWE']); +export default function isISO31661Alpha3(str) { + assertString(str); + return validISO31661Alpha3CountriesCodes.has(str.toUpperCase()); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isISO4217.js b/node_modules/validator/es/lib/isISO4217.js new file mode 100644 index 0000000..3033a04 --- /dev/null +++ b/node_modules/validator/es/lib/isISO4217.js @@ -0,0 +1,8 @@ +import assertString from './util/assertString'; // from https://en.wikipedia.org/wiki/ISO_4217 + +var validISO4217CurrencyCodes = new Set(['AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BOV', 'BRL', 'BSD', 'BTN', 'BWP', 'BYN', 'BZD', 'CAD', 'CDF', 'CHE', 'CHF', 'CHW', 'CLF', 'CLP', 'CNY', 'COP', 'COU', 'CRC', 'CUC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DZD', 'EGP', 'ERN', 'ETB', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GHS', 'GIP', 'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', 'INR', 'IQD', 'IRR', 'ISK', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD', 'MMK', 'MNT', 'MOP', 'MRU', 'MUR', 'MVR', 'MWK', 'MXN', 'MXV', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO', 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOS', 'SRD', 'SSP', 'STN', 'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'USN', 'UYI', 'UYU', 'UYW', 'UZS', 'VES', 'VND', 'VUV', 'WST', 'XAF', 'XAG', 'XAU', 'XBA', 'XBB', 'XBC', 'XBD', 'XCD', 'XDR', 'XOF', 'XPD', 'XPF', 'XPT', 'XSU', 'XTS', 'XUA', 'XXX', 'YER', 'ZAR', 'ZMW', 'ZWL']); +export default function isISO4217(str) { + assertString(str); + return validISO4217CurrencyCodes.has(str.toUpperCase()); +} +export var CurrencyCodes = validISO4217CurrencyCodes; \ No newline at end of file diff --git a/node_modules/validator/es/lib/isISO8601.js b/node_modules/validator/es/lib/isISO8601.js new file mode 100644 index 0000000..8e71215 --- /dev/null +++ b/node_modules/validator/es/lib/isISO8601.js @@ -0,0 +1,47 @@ +import assertString from './util/assertString'; +/* eslint-disable max-len */ +// from http://goo.gl/0ejHHW + +var iso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; // same as above, except with a strict 'T' separator between date and time + +var iso8601StrictSeparator = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; +/* eslint-enable max-len */ + +var isValidDate = function isValidDate(str) { + // str must have passed the ISO8601 check + // this check is meant to catch invalid dates + // like 2009-02-31 + // first check for ordinal dates + var ordinalMatch = str.match(/^(\d{4})-?(\d{3})([ T]{1}\.*|$)/); + + if (ordinalMatch) { + var oYear = Number(ordinalMatch[1]); + var oDay = Number(ordinalMatch[2]); // if is leap year + + if (oYear % 4 === 0 && oYear % 100 !== 0 || oYear % 400 === 0) return oDay <= 366; + return oDay <= 365; + } + + var match = str.match(/(\d{4})-?(\d{0,2})-?(\d*)/).map(Number); + var year = match[1]; + var month = match[2]; + var day = match[3]; + var monthString = month ? "0".concat(month).slice(-2) : month; + var dayString = day ? "0".concat(day).slice(-2) : day; // create a date object and compare + + var d = new Date("".concat(year, "-").concat(monthString || '01', "-").concat(dayString || '01')); + + if (month && day) { + return d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day; + } + + return true; +}; + +export default function isISO8601(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + assertString(str); + var check = options.strictSeparator ? iso8601StrictSeparator.test(str) : iso8601.test(str); + if (check && options.strict) return isValidDate(str); + return check; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isISRC.js b/node_modules/validator/es/lib/isISRC.js new file mode 100644 index 0000000..275c10a --- /dev/null +++ b/node_modules/validator/es/lib/isISRC.js @@ -0,0 +1,7 @@ +import assertString from './util/assertString'; // see http://isrc.ifpi.org/en/isrc-standard/code-syntax + +var isrc = /^[A-Z]{2}[0-9A-Z]{3}\d{2}\d{5}$/; +export default function isISRC(str) { + assertString(str); + return isrc.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isISSN.js b/node_modules/validator/es/lib/isISSN.js new file mode 100644 index 0000000..bebfa9e --- /dev/null +++ b/node_modules/validator/es/lib/isISSN.js @@ -0,0 +1,23 @@ +import assertString from './util/assertString'; +var issn = '^\\d{4}-?\\d{3}[\\dX]$'; +export default function isISSN(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + assertString(str); + var testIssn = issn; + testIssn = options.require_hyphen ? testIssn.replace('?', '') : testIssn; + testIssn = options.case_sensitive ? new RegExp(testIssn) : new RegExp(testIssn, 'i'); + + if (!testIssn.test(str)) { + return false; + } + + var digits = str.replace('-', '').toUpperCase(); + var checksum = 0; + + for (var i = 0; i < digits.length; i++) { + var digit = digits[i]; + checksum += (digit === 'X' ? 10 : +digit) * (8 - i); + } + + return checksum % 11 === 0; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isIdentityCard.js b/node_modules/validator/es/lib/isIdentityCard.js new file mode 100644 index 0000000..3be4a97 --- /dev/null +++ b/node_modules/validator/es/lib/isIdentityCard.js @@ -0,0 +1,369 @@ +import assertString from './util/assertString'; +import isInt from './isInt'; +var validators = { + PL: function PL(str) { + assertString(str); + var weightOfDigits = { + 1: 1, + 2: 3, + 3: 7, + 4: 9, + 5: 1, + 6: 3, + 7: 7, + 8: 9, + 9: 1, + 10: 3, + 11: 0 + }; + + if (str != null && str.length === 11 && isInt(str, { + allow_leading_zeroes: true + })) { + var digits = str.split('').slice(0, -1); + var sum = digits.reduce(function (acc, digit, index) { + return acc + Number(digit) * weightOfDigits[index + 1]; + }, 0); + var modulo = sum % 10; + var lastDigit = Number(str.charAt(str.length - 1)); + + if (modulo === 0 && lastDigit === 0 || lastDigit === 10 - modulo) { + return true; + } + } + + return false; + }, + ES: function ES(str) { + assertString(str); + var DNI = /^[0-9X-Z][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/; + var charsValue = { + X: 0, + Y: 1, + Z: 2 + }; + var controlDigits = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E']; // sanitize user input + + var sanitized = str.trim().toUpperCase(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } // validate the control digit + + + var number = sanitized.slice(0, -1).replace(/[X,Y,Z]/g, function (_char) { + return charsValue[_char]; + }); + return sanitized.endsWith(controlDigits[number % 23]); + }, + FI: function FI(str) { + // https://dvv.fi/en/personal-identity-code#:~:text=control%20character%20for%20a-,personal,-identity%20code%20calculated + assertString(str); + + if (str.length !== 11) { + return false; + } + + if (!str.match(/^\d{6}[\-A\+]\d{3}[0-9ABCDEFHJKLMNPRSTUVWXY]{1}$/)) { + return false; + } + + var checkDigits = '0123456789ABCDEFHJKLMNPRSTUVWXY'; + var idAsNumber = parseInt(str.slice(0, 6), 10) * 1000 + parseInt(str.slice(7, 10), 10); + var remainder = idAsNumber % 31; + var checkDigit = checkDigits[remainder]; + return checkDigit === str.slice(10, 11); + }, + IN: function IN(str) { + var DNI = /^[1-9]\d{3}\s?\d{4}\s?\d{4}$/; // multiplication table + + var d = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]; // permutation table + + var p = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } + + var c = 0; + var invertedArray = sanitized.replace(/\s/g, '').split('').map(Number).reverse(); + invertedArray.forEach(function (val, i) { + c = d[c][p[i % 8][val]]; + }); + return c === 0; + }, + IR: function IR(str) { + if (!str.match(/^\d{10}$/)) return false; + str = "0000".concat(str).substr(str.length - 6); + if (parseInt(str.substr(3, 6), 10) === 0) return false; + var lastNumber = parseInt(str.substr(9, 1), 10); + var sum = 0; + + for (var i = 0; i < 9; i++) { + sum += parseInt(str.substr(i, 1), 10) * (10 - i); + } + + sum %= 11; + return sum < 2 && lastNumber === sum || sum >= 2 && lastNumber === 11 - sum; + }, + IT: function IT(str) { + if (str.length !== 9) return false; + if (str === 'CA00000AA') return false; // https://it.wikipedia.org/wiki/Carta_d%27identit%C3%A0_elettronica_italiana + + return str.search(/C[A-Z][0-9]{5}[A-Z]{2}/i) > -1; + }, + NO: function NO(str) { + var sanitized = str.trim(); + if (isNaN(Number(sanitized))) return false; + if (sanitized.length !== 11) return false; + if (sanitized === '00000000000') return false; // https://no.wikipedia.org/wiki/F%C3%B8dselsnummer + + var f = sanitized.split('').map(Number); + var k1 = (11 - (3 * f[0] + 7 * f[1] + 6 * f[2] + 1 * f[3] + 8 * f[4] + 9 * f[5] + 4 * f[6] + 5 * f[7] + 2 * f[8]) % 11) % 11; + var k2 = (11 - (5 * f[0] + 4 * f[1] + 3 * f[2] + 2 * f[3] + 7 * f[4] + 6 * f[5] + 5 * f[6] + 4 * f[7] + 3 * f[8] + 2 * k1) % 11) % 11; + if (k1 !== f[9] || k2 !== f[10]) return false; + return true; + }, + TH: function TH(str) { + if (!str.match(/^[1-8]\d{12}$/)) return false; // validate check digit + + var sum = 0; + + for (var i = 0; i < 12; i++) { + sum += parseInt(str[i], 10) * (13 - i); + } + + return str[12] === ((11 - sum % 11) % 10).toString(); + }, + LK: function LK(str) { + var old_nic = /^[1-9]\d{8}[vx]$/i; + var new_nic = /^[1-9]\d{11}$/i; + if (str.length === 10 && old_nic.test(str)) return true;else if (str.length === 12 && new_nic.test(str)) return true; + return false; + }, + 'he-IL': function heIL(str) { + var DNI = /^\d{9}$/; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } + + var id = sanitized; + var sum = 0, + incNum; + + for (var i = 0; i < id.length; i++) { + incNum = Number(id[i]) * (i % 2 + 1); // Multiply number by 1 or 2 + + sum += incNum > 9 ? incNum - 9 : incNum; // Sum the digits up and add to total + } + + return sum % 10 === 0; + }, + 'ar-LY': function arLY(str) { + // Libya National Identity Number NIN is 12 digits, the first digit is either 1 or 2 + var NIN = /^(1|2)\d{11}$/; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!NIN.test(sanitized)) { + return false; + } + + return true; + }, + 'ar-TN': function arTN(str) { + var DNI = /^\d{8}$/; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } + + return true; + }, + 'zh-CN': function zhCN(str) { + var provincesAndCities = ['11', // 北京 + '12', // 天津 + '13', // 河北 + '14', // 山西 + '15', // 内蒙古 + '21', // 辽宁 + '22', // 吉林 + '23', // 黑龙江 + '31', // 上海 + '32', // 江苏 + '33', // 浙江 + '34', // 安徽 + '35', // 福建 + '36', // 江西 + '37', // 山东 + '41', // 河南 + '42', // 湖北 + '43', // 湖南 + '44', // 广东 + '45', // 广西 + '46', // 海南 + '50', // 重庆 + '51', // 四川 + '52', // 贵州 + '53', // 云南 + '54', // 西藏 + '61', // 陕西 + '62', // 甘肃 + '63', // 青海 + '64', // 宁夏 + '65', // 新疆 + '71', // 台湾 + '81', // 香港 + '82', // 澳门 + '91' // 国外 + ]; + var powers = ['7', '9', '10', '5', '8', '4', '2', '1', '6', '3', '7', '9', '10', '5', '8', '4', '2']; + var parityBit = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']; + + var checkAddressCode = function checkAddressCode(addressCode) { + return provincesAndCities.includes(addressCode); + }; + + var checkBirthDayCode = function checkBirthDayCode(birDayCode) { + var yyyy = parseInt(birDayCode.substring(0, 4), 10); + var mm = parseInt(birDayCode.substring(4, 6), 10); + var dd = parseInt(birDayCode.substring(6), 10); + var xdata = new Date(yyyy, mm - 1, dd); + + if (xdata > new Date()) { + return false; // eslint-disable-next-line max-len + } else if (xdata.getFullYear() === yyyy && xdata.getMonth() === mm - 1 && xdata.getDate() === dd) { + return true; + } + + return false; + }; + + var getParityBit = function getParityBit(idCardNo) { + var id17 = idCardNo.substring(0, 17); + var power = 0; + + for (var i = 0; i < 17; i++) { + power += parseInt(id17.charAt(i), 10) * parseInt(powers[i], 10); + } + + var mod = power % 11; + return parityBit[mod]; + }; + + var checkParityBit = function checkParityBit(idCardNo) { + return getParityBit(idCardNo) === idCardNo.charAt(17).toUpperCase(); + }; + + var check15IdCardNo = function check15IdCardNo(idCardNo) { + var check = /^[1-9]\d{7}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}$/.test(idCardNo); + if (!check) return false; + var addressCode = idCardNo.substring(0, 2); + check = checkAddressCode(addressCode); + if (!check) return false; + var birDayCode = "19".concat(idCardNo.substring(6, 12)); + check = checkBirthDayCode(birDayCode); + if (!check) return false; + return true; + }; + + var check18IdCardNo = function check18IdCardNo(idCardNo) { + var check = /^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}(\d|x|X)$/.test(idCardNo); + if (!check) return false; + var addressCode = idCardNo.substring(0, 2); + check = checkAddressCode(addressCode); + if (!check) return false; + var birDayCode = idCardNo.substring(6, 14); + check = checkBirthDayCode(birDayCode); + if (!check) return false; + return checkParityBit(idCardNo); + }; + + var checkIdCardNo = function checkIdCardNo(idCardNo) { + var check = /^\d{15}|(\d{17}(\d|x|X))$/.test(idCardNo); + if (!check) return false; + + if (idCardNo.length === 15) { + return check15IdCardNo(idCardNo); + } + + return check18IdCardNo(idCardNo); + }; + + return checkIdCardNo(str); + }, + 'zh-TW': function zhTW(str) { + var ALPHABET_CODES = { + A: 10, + B: 11, + C: 12, + D: 13, + E: 14, + F: 15, + G: 16, + H: 17, + I: 34, + J: 18, + K: 19, + L: 20, + M: 21, + N: 22, + O: 35, + P: 23, + Q: 24, + R: 25, + S: 26, + T: 27, + U: 28, + V: 29, + W: 32, + X: 30, + Y: 31, + Z: 33 + }; + var sanitized = str.trim().toUpperCase(); + if (!/^[A-Z][0-9]{9}$/.test(sanitized)) return false; + return Array.from(sanitized).reduce(function (sum, number, index) { + if (index === 0) { + var code = ALPHABET_CODES[number]; + return code % 10 * 9 + Math.floor(code / 10); + } + + if (index === 9) { + return (10 - sum % 10 - Number(number)) % 10 === 0; + } + + return sum + Number(number) * (9 - index); + }, 0); + } +}; +export default function isIdentityCard(str, locale) { + assertString(str); + + if (locale in validators) { + return validators[locale](str); + } else if (locale === 'any') { + for (var key in validators) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (validators.hasOwnProperty(key)) { + var validator = validators[key]; + + if (validator(str)) { + return true; + } + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isIn.js b/node_modules/validator/es/lib/isIn.js new file mode 100644 index 0000000..452429d --- /dev/null +++ b/node_modules/validator/es/lib/isIn.js @@ -0,0 +1,28 @@ +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +import assertString from './util/assertString'; +import toString from './util/toString'; +export default function isIn(str, options) { + assertString(str); + var i; + + if (Object.prototype.toString.call(options) === '[object Array]') { + var array = []; + + for (i in options) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if ({}.hasOwnProperty.call(options, i)) { + array[i] = toString(options[i]); + } + } + + return array.indexOf(str) >= 0; + } else if (_typeof(options) === 'object') { + return options.hasOwnProperty(str); + } else if (options && typeof options.indexOf === 'function') { + return options.indexOf(str) >= 0; + } + + return false; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isInt.js b/node_modules/validator/es/lib/isInt.js new file mode 100644 index 0000000..b58dab4 --- /dev/null +++ b/node_modules/validator/es/lib/isInt.js @@ -0,0 +1,16 @@ +import assertString from './util/assertString'; +var _int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/; +var intLeadingZeroes = /^[-+]?[0-9]+$/; +export default function isInt(str, options) { + assertString(str); + options = options || {}; // Get the regex to use for testing, based on whether + // leading zeroes are allowed or not. + + var regex = options.hasOwnProperty('allow_leading_zeroes') && !options.allow_leading_zeroes ? _int : intLeadingZeroes; // Check min/max/lt/gt + + var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min; + var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max; + var ltCheckPassed = !options.hasOwnProperty('lt') || str < options.lt; + var gtCheckPassed = !options.hasOwnProperty('gt') || str > options.gt; + return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isJSON.js b/node_modules/validator/es/lib/isJSON.js new file mode 100644 index 0000000..bd110cc --- /dev/null +++ b/node_modules/validator/es/lib/isJSON.js @@ -0,0 +1,26 @@ +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +import assertString from './util/assertString'; +import merge from './util/merge'; +var default_json_options = { + allow_primitives: false +}; +export default function isJSON(str, options) { + assertString(str); + + try { + options = merge(options, default_json_options); + var primitives = []; + + if (options.allow_primitives) { + primitives = [null, false, true]; + } + + var obj = JSON.parse(str); + return primitives.includes(obj) || !!obj && _typeof(obj) === 'object'; + } catch (e) { + /* ignore */ + } + + return false; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isJWT.js b/node_modules/validator/es/lib/isJWT.js new file mode 100644 index 0000000..c1afb7b --- /dev/null +++ b/node_modules/validator/es/lib/isJWT.js @@ -0,0 +1,17 @@ +import assertString from './util/assertString'; +import isBase64 from './isBase64'; +export default function isJWT(str) { + assertString(str); + var dotSplit = str.split('.'); + var len = dotSplit.length; + + if (len > 3 || len < 2) { + return false; + } + + return dotSplit.reduce(function (acc, currElem) { + return acc && isBase64(currElem, { + urlSafe: true + }); + }, true); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isLatLong.js b/node_modules/validator/es/lib/isLatLong.js new file mode 100644 index 0000000..7362c1d --- /dev/null +++ b/node_modules/validator/es/lib/isLatLong.js @@ -0,0 +1,22 @@ +import assertString from './util/assertString'; +import merge from './util/merge'; +var lat = /^\(?[+-]?(90(\.0+)?|[1-8]?\d(\.\d+)?)$/; +var _long = /^\s?[+-]?(180(\.0+)?|1[0-7]\d(\.\d+)?|\d{1,2}(\.\d+)?)\)?$/; +var latDMS = /^(([1-8]?\d)\D+([1-5]?\d|60)\D+([1-5]?\d|60)(\.\d+)?|90\D+0\D+0)\D+[NSns]?$/i; +var longDMS = /^\s*([1-7]?\d{1,2}\D+([1-5]?\d|60)\D+([1-5]?\d|60)(\.\d+)?|180\D+0\D+0)\D+[EWew]?$/i; +var defaultLatLongOptions = { + checkDMS: false +}; +export default function isLatLong(str, options) { + assertString(str); + options = merge(options, defaultLatLongOptions); + if (!str.includes(',')) return false; + var pair = str.split(','); + if (pair[0].startsWith('(') && !pair[1].endsWith(')') || pair[1].endsWith(')') && !pair[0].startsWith('(')) return false; + + if (options.checkDMS) { + return latDMS.test(pair[0]) && longDMS.test(pair[1]); + } + + return lat.test(pair[0]) && _long.test(pair[1]); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isLength.js b/node_modules/validator/es/lib/isLength.js new file mode 100644 index 0000000..3b1a5fd --- /dev/null +++ b/node_modules/validator/es/lib/isLength.js @@ -0,0 +1,23 @@ +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +import assertString from './util/assertString'; +/* eslint-disable prefer-rest-params */ + +export default function isLength(str, options) { + assertString(str); + var min; + var max; + + if (_typeof(options) === 'object') { + min = options.min || 0; + max = options.max; + } else { + // backwards compatibility: isLength(str, min [, max]) + min = arguments[1] || 0; + max = arguments[2]; + } + + var surrogatePairs = str.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []; + var len = str.length - surrogatePairs.length; + return len >= min && (typeof max === 'undefined' || len <= max); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isLicensePlate.js b/node_modules/validator/es/lib/isLicensePlate.js new file mode 100644 index 0000000..c2a26bf --- /dev/null +++ b/node_modules/validator/es/lib/isLicensePlate.js @@ -0,0 +1,44 @@ +import assertString from './util/assertString'; +var validators = { + 'cs-CZ': function csCZ(str) { + return /^(([ABCDEFHKIJKLMNPRSTUVXYZ]|[0-9])-?){5,8}$/.test(str); + }, + 'de-DE': function deDE(str) { + return /^((AW|UL|AK|GA|AÖ|LF|AZ|AM|AS|ZE|AN|AB|A|KG|KH|BA|EW|BZ|HY|KM|BT|HP|B|BC|BI|BO|FN|TT|ÜB|BN|AH|BS|FR|HB|ZZ|BB|BK|BÖ|OC|OK|CW|CE|C|CO|LH|CB|KW|LC|LN|DA|DI|DE|DH|SY|NÖ|DO|DD|DU|DN|D|EI|EA|EE|FI|EM|EL|EN|PF|ED|EF|ER|AU|ZP|E|ES|NT|EU|FL|FO|FT|FF|F|FS|FD|FÜ|GE|G|GI|GF|GS|ZR|GG|GP|GR|NY|ZI|GÖ|GZ|GT|HA|HH|HM|HU|WL|HZ|WR|RN|HK|HD|HN|HS|GK|HE|HF|RZ|HI|HG|HO|HX|IK|IL|IN|J|JL|KL|KA|KS|KF|KE|KI|KT|KO|KN|KR|KC|KU|K|LD|LL|LA|L|OP|LM|LI|LB|LU|LÖ|HL|LG|MD|GN|MZ|MA|ML|MR|MY|AT|DM|MC|NZ|RM|RG|MM|ME|MB|MI|FG|DL|HC|MW|RL|MK|MG|MÜ|WS|MH|M|MS|NU|NB|ND|NM|NK|NW|NR|NI|NF|DZ|EB|OZ|TG|TO|N|OA|GM|OB|CA|EH|FW|OF|OL|OE|OG|BH|LR|OS|AA|GD|OH|KY|NP|WK|PB|PA|PE|PI|PS|P|PM|PR|RA|RV|RE|R|H|SB|WN|RS|RD|RT|BM|NE|GV|RP|SU|GL|RO|GÜ|RH|EG|RW|PN|SK|MQ|RU|SZ|RI|SL|SM|SC|HR|FZ|VS|SW|SN|CR|SE|SI|SO|LP|SG|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MYK|MSE|MST|MÜR|WRN|MEI|GRH|RIE|MZG|MIL|OBB|BED|FLÖ|MOL|FRW|SEE|SRB|AIB|MOS|BCH|ILL|SOB|NMS|NEA|SEF|UFF|NEW|VOH|NDH|TDO|NWM|GDB|GVM|WIS|NOM|EIN|GAN|LAU|HEB|OHV|OSL|SFB|ERB|LOS|BSK|KEL|BSB|MEL|WTL|OAL|FÜS|MOD|OHZ|OPR|BÜR|PAF|PLÖ|CAS|GLA|REG|VIT|ECK|SIM|GOA|EMS|DIZ|GOH|RÜD|SWA|NES|KÖN|MET|LRO|BÜZ|DBR|ROS|TET|HRO|ROW|BRV|HIP|PAN|GRI|SHK|EIS|SRO|SOK|LBS|SCZ|MER|QFT|SLF|SLS|HOM|SLK|ASL|BBG|SBK|SFT|SHG|MGN|MEG|ZIG|SAD|NEN|OVI|SHA|BLB|SIG|SON|SPN|FOR|GUB|SPB|IGB|WND|STD|STA|SDL|OBG|HST|BOG|SHL|PIR|FTL|SEB|SÖM|SÜW|TIR|SAB|TUT|ANG|SDT|LÜN|LSZ|MHL|VEC|VER|VIE|OVL|ANK|OVP|SBG|UEM|UER|WLG|GMN|NVP|RDG|RÜG|DAU|FKB|WAF|WAK|SLZ|WEN|SOG|APD|WUG|GUN|ESW|WIZ|WES|DIN|BRA|BÜD|WHV|HWI|GHC|WTM|WOB|WUN|MAK|SEL|OCH|HOT|WDA)[- ]?(([A-Z][- ]?\d{1,4})|([A-Z]{2}[- ]?\d{1,3})))[- ]?(E|H)?$/.test(str); + }, + 'de-LI': function deLI(str) { + return /^FL[- ]?\d{1,5}[UZ]?$/.test(str); + }, + 'fi-FI': function fiFI(str) { + return /^(?=.{4,7})(([A-Z]{1,3}|[0-9]{1,3})[\s-]?([A-Z]{1,3}|[0-9]{1,5}))$/.test(str); + }, + 'pt-PT': function ptPT(str) { + return /^([A-Z]{2}|[0-9]{2})[ -·]?([A-Z]{2}|[0-9]{2})[ -·]?([A-Z]{2}|[0-9]{2})$/.test(str); + }, + 'sq-AL': function sqAL(str) { + return /^[A-Z]{2}[- ]?((\d{3}[- ]?(([A-Z]{2})|T))|(R[- ]?\d{3}))$/.test(str); + }, + 'pt-BR': function ptBR(str) { + return /^[A-Z]{3}[ -]?[0-9][A-Z][0-9]{2}|[A-Z]{3}[ -]?[0-9]{4}$/.test(str); + } +}; +export default function isLicensePlate(str, locale) { + assertString(str); + + if (locale in validators) { + return validators[locale](str); + } else if (locale === 'any') { + for (var key in validators) { + /* eslint guard-for-in: 0 */ + var validator = validators[key]; + + if (validator(str)) { + return true; + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isLocale.js b/node_modules/validator/es/lib/isLocale.js new file mode 100644 index 0000000..5033392 --- /dev/null +++ b/node_modules/validator/es/lib/isLocale.js @@ -0,0 +1,11 @@ +import assertString from './util/assertString'; +var localeReg = /^[A-Za-z]{2,4}([_-]([A-Za-z]{4}|[\d]{3}))?([_-]([A-Za-z]{2}|[\d]{3}))?$/; +export default function isLocale(str) { + assertString(str); + + if (str === 'en_US_POSIX' || str === 'ca_ES_VALENCIA') { + return true; + } + + return localeReg.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isLowercase.js b/node_modules/validator/es/lib/isLowercase.js new file mode 100644 index 0000000..0347856 --- /dev/null +++ b/node_modules/validator/es/lib/isLowercase.js @@ -0,0 +1,5 @@ +import assertString from './util/assertString'; +export default function isLowercase(str) { + assertString(str); + return str === str.toLowerCase(); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isMACAddress.js b/node_modules/validator/es/lib/isMACAddress.js new file mode 100644 index 0000000..ac23503 --- /dev/null +++ b/node_modules/validator/es/lib/isMACAddress.js @@ -0,0 +1,16 @@ +import assertString from './util/assertString'; +var macAddress = /^(?:[0-9a-fA-F]{2}([-:\s]))([0-9a-fA-F]{2}\1){4}([0-9a-fA-F]{2})$/; +var macAddressNoSeparators = /^([0-9a-fA-F]){12}$/; +var macAddressWithDots = /^([0-9a-fA-F]{4}\.){2}([0-9a-fA-F]{4})$/; +export default function isMACAddress(str, options) { + assertString(str); + /** + * @deprecated `no_colons` TODO: remove it in the next major + */ + + if (options && (options.no_colons || options.no_separators)) { + return macAddressNoSeparators.test(str); + } + + return macAddress.test(str) || macAddressWithDots.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isMD5.js b/node_modules/validator/es/lib/isMD5.js new file mode 100644 index 0000000..701ed7b --- /dev/null +++ b/node_modules/validator/es/lib/isMD5.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +var md5 = /^[a-f0-9]{32}$/; +export default function isMD5(str) { + assertString(str); + return md5.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isMagnetURI.js b/node_modules/validator/es/lib/isMagnetURI.js new file mode 100644 index 0000000..ee4c120 --- /dev/null +++ b/node_modules/validator/es/lib/isMagnetURI.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +var magnetURI = /^magnet:\?xt(?:\.1)?=urn:(?:aich|bitprint|btih|ed2k|ed2khash|kzhash|md5|sha1|tree:tiger):[a-z0-9]{32}(?:[a-z0-9]{8})?($|&)/i; +export default function isMagnetURI(url) { + assertString(url); + return magnetURI.test(url.trim()); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isMimeType.js b/node_modules/validator/es/lib/isMimeType.js new file mode 100644 index 0000000..cddaf00 --- /dev/null +++ b/node_modules/validator/es/lib/isMimeType.js @@ -0,0 +1,39 @@ +import assertString from './util/assertString'; +/* + Checks if the provided string matches to a correct Media type format (MIME type) + + This function only checks is the string format follows the + etablished rules by the according RFC specifications. + This function supports 'charset' in textual media types + (https://tools.ietf.org/html/rfc6657). + + This function does not check against all the media types listed + by the IANA (https://www.iana.org/assignments/media-types/media-types.xhtml) + because of lightness purposes : it would require to include + all these MIME types in this librairy, which would weigh it + significantly. This kind of effort maybe is not worth for the use that + this function has in this entire librairy. + + More informations in the RFC specifications : + - https://tools.ietf.org/html/rfc2045 + - https://tools.ietf.org/html/rfc2046 + - https://tools.ietf.org/html/rfc7231#section-3.1.1.1 + - https://tools.ietf.org/html/rfc7231#section-3.1.1.5 +*/ +// Match simple MIME types +// NB : +// Subtype length must not exceed 100 characters. +// This rule does not comply to the RFC specs (what is the max length ?). + +var mimeTypeSimple = /^(application|audio|font|image|message|model|multipart|text|video)\/[a-zA-Z0-9\.\-\+]{1,100}$/i; // eslint-disable-line max-len +// Handle "charset" in "text/*" + +var mimeTypeText = /^text\/[a-zA-Z0-9\.\-\+]{1,100};\s?charset=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?$/i; // eslint-disable-line max-len +// Handle "boundary" in "multipart/*" + +var mimeTypeMultipart = /^multipart\/[a-zA-Z0-9\.\-\+]{1,100}(;\s?(boundary|charset)=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?){0,2}$/i; // eslint-disable-line max-len + +export default function isMimeType(str) { + assertString(str); + return mimeTypeSimple.test(str) || mimeTypeText.test(str) || mimeTypeMultipart.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isMobilePhone.js b/node_modules/validator/es/lib/isMobilePhone.js new file mode 100644 index 0000000..ae0f04f --- /dev/null +++ b/node_modules/validator/es/lib/isMobilePhone.js @@ -0,0 +1,187 @@ +import assertString from './util/assertString'; +/* eslint-disable max-len */ + +var phones = { + 'am-AM': /^(\+?374|0)((10|[9|7][0-9])\d{6}$|[2-4]\d{7}$)/, + 'ar-AE': /^((\+?971)|0)?5[024568]\d{7}$/, + 'ar-BH': /^(\+?973)?(3|6)\d{7}$/, + 'ar-DZ': /^(\+?213|0)(5|6|7)\d{8}$/, + 'ar-LB': /^(\+?961)?((3|81)\d{6}|7\d{7})$/, + 'ar-EG': /^((\+?20)|0)?1[0125]\d{8}$/, + 'ar-IQ': /^(\+?964|0)?7[0-9]\d{8}$/, + 'ar-JO': /^(\+?962|0)?7[789]\d{7}$/, + 'ar-KW': /^(\+?965)[569]\d{7}$/, + 'ar-LY': /^((\+?218)|0)?(9[1-6]\d{7}|[1-8]\d{7,9})$/, + 'ar-MA': /^(?:(?:\+|00)212|0)[5-7]\d{8}$/, + 'ar-OM': /^((\+|00)968)?(9[1-9])\d{6}$/, + 'ar-PS': /^(\+?970|0)5[6|9](\d{7})$/, + 'ar-SA': /^(!?(\+?966)|0)?5\d{8}$/, + 'ar-SY': /^(!?(\+?963)|0)?9\d{8}$/, + 'ar-TN': /^(\+?216)?[2459]\d{7}$/, + 'az-AZ': /^(\+994|0)(5[015]|7[07]|99)\d{7}$/, + 'bs-BA': /^((((\+|00)3876)|06))((([0-3]|[5-6])\d{6})|(4\d{7}))$/, + 'be-BY': /^(\+?375)?(24|25|29|33|44)\d{7}$/, + 'bg-BG': /^(\+?359|0)?8[789]\d{7}$/, + 'bn-BD': /^(\+?880|0)1[13456789][0-9]{8}$/, + 'ca-AD': /^(\+376)?[346]\d{5}$/, + 'cs-CZ': /^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/, + 'da-DK': /^(\+?45)?\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{2}$/, + 'de-DE': /^((\+49|0)[1|3])([0|5][0-45-9]\d|6([23]|0\d?)|7([0-57-9]|6\d))\d{7,9}$/, + 'de-AT': /^(\+43|0)\d{1,4}\d{3,12}$/, + 'de-CH': /^(\+41|0)([1-9])\d{1,9}$/, + 'de-LU': /^(\+352)?((6\d1)\d{6})$/, + 'dv-MV': /^(\+?960)?(7[2-9]|91|9[3-9])\d{7}$/, + 'el-GR': /^(\+?30|0)?(69\d{8})$/, + 'en-AU': /^(\+?61|0)4\d{8}$/, + 'en-BM': /^(\+?1)?441(((3|7)\d{6}$)|(5[0-3][0-9]\d{4}$)|(59\d{5}))/, + 'en-GB': /^(\+?44|0)7\d{9}$/, + 'en-GG': /^(\+?44|0)1481\d{6}$/, + 'en-GH': /^(\+233|0)(20|50|24|54|27|57|26|56|23|28|55|59)\d{7}$/, + 'en-GY': /^(\+592|0)6\d{6}$/, + 'en-HK': /^(\+?852[-\s]?)?[456789]\d{3}[-\s]?\d{4}$/, + 'en-MO': /^(\+?853[-\s]?)?[6]\d{3}[-\s]?\d{4}$/, + 'en-IE': /^(\+?353|0)8[356789]\d{7}$/, + 'en-IN': /^(\+?91|0)?[6789]\d{9}$/, + 'en-KE': /^(\+?254|0)(7|1)\d{8}$/, + 'en-KI': /^((\+686|686)?)?( )?((6|7)(2|3|8)[0-9]{6})$/, + 'en-MT': /^(\+?356|0)?(99|79|77|21|27|22|25)[0-9]{6}$/, + 'en-MU': /^(\+?230|0)?\d{8}$/, + 'en-NA': /^(\+?264|0)(6|8)\d{7}$/, + 'en-NG': /^(\+?234|0)?[789]\d{9}$/, + 'en-NZ': /^(\+?64|0)[28]\d{7,9}$/, + 'en-PK': /^((00|\+)?92|0)3[0-6]\d{8}$/, + 'en-PH': /^(09|\+639)\d{9}$/, + 'en-RW': /^(\+?250|0)?[7]\d{8}$/, + 'en-SG': /^(\+65)?[3689]\d{7}$/, + 'en-SL': /^(\+?232|0)\d{8}$/, + 'en-TZ': /^(\+?255|0)?[67]\d{8}$/, + 'en-UG': /^(\+?256|0)?[7]\d{8}$/, + 'en-US': /^((\+1|1)?( |-)?)?(\([2-9][0-9]{2}\)|[2-9][0-9]{2})( |-)?([2-9][0-9]{2}( |-)?[0-9]{4})$/, + 'en-ZA': /^(\+?27|0)\d{9}$/, + 'en-ZM': /^(\+?26)?09[567]\d{7}$/, + 'en-ZW': /^(\+263)[0-9]{9}$/, + 'en-BW': /^(\+?267)?(7[1-8]{1})\d{6}$/, + 'es-AR': /^\+?549(11|[2368]\d)\d{8}$/, + 'es-BO': /^(\+?591)?(6|7)\d{7}$/, + 'es-CO': /^(\+?57)?3(0(0|1|2|4|5)|1\d|2[0-4]|5(0|1))\d{7}$/, + 'es-CL': /^(\+?56|0)[2-9]\d{1}\d{7}$/, + 'es-CR': /^(\+506)?[2-8]\d{7}$/, + 'es-CU': /^(\+53|0053)?5\d{7}/, + 'es-DO': /^(\+?1)?8[024]9\d{7}$/, + 'es-HN': /^(\+?504)?[9|8]\d{7}$/, + 'es-EC': /^(\+?593|0)([2-7]|9[2-9])\d{7}$/, + 'es-ES': /^(\+?34)?[6|7]\d{8}$/, + 'es-PE': /^(\+?51)?9\d{8}$/, + 'es-MX': /^(\+?52)?(1|01)?\d{10,11}$/, + 'es-PA': /^(\+?507)\d{7,8}$/, + 'es-PY': /^(\+?595|0)9[9876]\d{7}$/, + 'es-SV': /^(\+?503)?[67]\d{7}$/, + 'es-UY': /^(\+598|0)9[1-9][\d]{6}$/, + 'es-VE': /^(\+?58)?(2|4)\d{9}$/, + 'et-EE': /^(\+?372)?\s?(5|8[1-4])\s?([0-9]\s?){6,7}$/, + 'fa-IR': /^(\+?98[\-\s]?|0)9[0-39]\d[\-\s]?\d{3}[\-\s]?\d{4}$/, + 'fi-FI': /^(\+?358|0)\s?(4(0|1|2|4|5|6)?|50)\s?(\d\s?){4,8}\d$/, + 'fj-FJ': /^(\+?679)?\s?\d{3}\s?\d{4}$/, + 'fo-FO': /^(\+?298)?\s?\d{2}\s?\d{2}\s?\d{2}$/, + 'fr-BF': /^(\+226|0)[67]\d{7}$/, + 'fr-CM': /^(\+?237)6[0-9]{8}$/, + 'fr-FR': /^(\+?33|0)[67]\d{8}$/, + 'fr-GF': /^(\+?594|0|00594)[67]\d{8}$/, + 'fr-GP': /^(\+?590|0|00590)[67]\d{8}$/, + 'fr-MQ': /^(\+?596|0|00596)[67]\d{8}$/, + 'fr-PF': /^(\+?689)?8[789]\d{6}$/, + 'fr-RE': /^(\+?262|0|00262)[67]\d{8}$/, + 'he-IL': /^(\+972|0)([23489]|5[012345689]|77)[1-9]\d{6}$/, + 'hu-HU': /^(\+?36|06)(20|30|31|50|70)\d{7}$/, + 'id-ID': /^(\+?62|0)8(1[123456789]|2[1238]|3[1238]|5[12356789]|7[78]|9[56789]|8[123456789])([\s?|\d]{5,11})$/, + 'it-IT': /^(\+?39)?\s?3\d{2} ?\d{6,7}$/, + 'it-SM': /^((\+378)|(0549)|(\+390549)|(\+3780549))?6\d{5,9}$/, + 'ja-JP': /^(\+81[ \-]?(\(0\))?|0)[6789]0[ \-]?\d{4}[ \-]?\d{4}$/, + 'ka-GE': /^(\+?995)?(5|79)\d{7}$/, + 'kk-KZ': /^(\+?7|8)?7\d{9}$/, + 'kl-GL': /^(\+?299)?\s?\d{2}\s?\d{2}\s?\d{2}$/, + 'ko-KR': /^((\+?82)[ \-]?)?0?1([0|1|6|7|8|9]{1})[ \-]?\d{3,4}[ \-]?\d{4}$/, + 'lt-LT': /^(\+370|8)\d{8}$/, + 'lv-LV': /^(\+?371)2\d{7}$/, + 'ms-MY': /^(\+?6?01){1}(([0145]{1}(\-|\s)?\d{7,8})|([236789]{1}(\s|\-)?\d{7}))$/, + 'mz-MZ': /^(\+?258)?8[234567]\d{7}$/, + 'nb-NO': /^(\+?47)?[49]\d{7}$/, + 'ne-NP': /^(\+?977)?9[78]\d{8}$/, + 'nl-BE': /^(\+?32|0)4\d{8}$/, + 'nl-NL': /^(((\+|00)?31\(0\))|((\+|00)?31)|0)6{1}\d{8}$/, + 'nn-NO': /^(\+?47)?[49]\d{7}$/, + 'pl-PL': /^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/, + 'pt-BR': /^((\+?55\ ?[1-9]{2}\ ?)|(\+?55\ ?\([1-9]{2}\)\ ?)|(0[1-9]{2}\ ?)|(\([1-9]{2}\)\ ?)|([1-9]{2}\ ?))((\d{4}\-?\d{4})|(9[2-9]{1}\d{3}\-?\d{4}))$/, + 'pt-PT': /^(\+?351)?9[1236]\d{7}$/, + 'pt-AO': /^(\+244)\d{9}$/, + 'ro-RO': /^(\+?4?0)\s?7\d{2}(\/|\s|\.|\-)?\d{3}(\s|\.|\-)?\d{3}$/, + 'ru-RU': /^(\+?7|8)?9\d{9}$/, + 'si-LK': /^(?:0|94|\+94)?(7(0|1|2|4|5|6|7|8)( |-)?)\d{7}$/, + 'sl-SI': /^(\+386\s?|0)(\d{1}\s?\d{3}\s?\d{2}\s?\d{2}|\d{2}\s?\d{3}\s?\d{3})$/, + 'sk-SK': /^(\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/, + 'sq-AL': /^(\+355|0)6[789]\d{6}$/, + 'sr-RS': /^(\+3816|06)[- \d]{5,9}$/, + 'sv-SE': /^(\+?46|0)[\s\-]?7[\s\-]?[02369]([\s\-]?\d){7}$/, + 'tg-TJ': /^(\+?992)?[5][5]\d{7}$/, + 'th-TH': /^(\+66|66|0)\d{9}$/, + 'tr-TR': /^(\+?90|0)?5\d{9}$/, + 'tk-TM': /^(\+993|993|8)\d{8}$/, + 'uk-UA': /^(\+?38|8)?0\d{9}$/, + 'uz-UZ': /^(\+?998)?(6[125-79]|7[1-69]|88|9\d)\d{7}$/, + 'vi-VN': /^((\+?84)|0)((3([2-9]))|(5([25689]))|(7([0|6-9]))|(8([1-9]))|(9([0-9])))([0-9]{7})$/, + 'zh-CN': /^((\+|00)86)?(1[3-9]|9[28])\d{9}$/, + 'zh-TW': /^(\+?886\-?|0)?9\d{8}$/, + 'dz-BT': /^(\+?975|0)?(17|16|77|02)\d{6}$/ +}; +/* eslint-enable max-len */ +// aliases + +phones['en-CA'] = phones['en-US']; +phones['fr-CA'] = phones['en-CA']; +phones['fr-BE'] = phones['nl-BE']; +phones['zh-HK'] = phones['en-HK']; +phones['zh-MO'] = phones['en-MO']; +phones['ga-IE'] = phones['en-IE']; +phones['fr-CH'] = phones['de-CH']; +phones['it-CH'] = phones['fr-CH']; +export default function isMobilePhone(str, locale, options) { + assertString(str); + + if (options && options.strictMode && !str.startsWith('+')) { + return false; + } + + if (Array.isArray(locale)) { + return locale.some(function (key) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (phones.hasOwnProperty(key)) { + var phone = phones[key]; + + if (phone.test(str)) { + return true; + } + } + + return false; + }); + } else if (locale in phones) { + return phones[locale].test(str); // alias falsey locale as 'any' + } else if (!locale || locale === 'any') { + for (var key in phones) { + // istanbul ignore else + if (phones.hasOwnProperty(key)) { + var phone = phones[key]; + + if (phone.test(str)) { + return true; + } + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} +export var locales = Object.keys(phones); \ No newline at end of file diff --git a/node_modules/validator/es/lib/isMongoId.js b/node_modules/validator/es/lib/isMongoId.js new file mode 100644 index 0000000..fc87b89 --- /dev/null +++ b/node_modules/validator/es/lib/isMongoId.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +import isHexadecimal from './isHexadecimal'; +export default function isMongoId(str) { + assertString(str); + return isHexadecimal(str) && str.length === 24; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isMultibyte.js b/node_modules/validator/es/lib/isMultibyte.js new file mode 100644 index 0000000..7a13857 --- /dev/null +++ b/node_modules/validator/es/lib/isMultibyte.js @@ -0,0 +1,10 @@ +import assertString from './util/assertString'; +/* eslint-disable no-control-regex */ + +var multibyte = /[^\x00-\x7F]/; +/* eslint-enable no-control-regex */ + +export default function isMultibyte(str) { + assertString(str); + return multibyte.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isNumeric.js b/node_modules/validator/es/lib/isNumeric.js new file mode 100644 index 0000000..398fb82 --- /dev/null +++ b/node_modules/validator/es/lib/isNumeric.js @@ -0,0 +1,12 @@ +import assertString from './util/assertString'; +import { decimal } from './alpha'; +var numericNoSymbols = /^[0-9]+$/; +export default function isNumeric(str, options) { + assertString(str); + + if (options && options.no_symbols) { + return numericNoSymbols.test(str); + } + + return new RegExp("^[+-]?([0-9]*[".concat((options || {}).locale ? decimal[options.locale] : '.', "])?[0-9]+$")).test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isOctal.js b/node_modules/validator/es/lib/isOctal.js new file mode 100644 index 0000000..3ec51dd --- /dev/null +++ b/node_modules/validator/es/lib/isOctal.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +var octal = /^(0o)?[0-7]+$/i; +export default function isOctal(str) { + assertString(str); + return octal.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isPassportNumber.js b/node_modules/validator/es/lib/isPassportNumber.js new file mode 100644 index 0000000..f626e84 --- /dev/null +++ b/node_modules/validator/es/lib/isPassportNumber.js @@ -0,0 +1,126 @@ +import assertString from './util/assertString'; +/** + * Reference: + * https://en.wikipedia.org/ -- Wikipedia + * https://docs.microsoft.com/en-us/microsoft-365/compliance/eu-passport-number -- EU Passport Number + * https://countrycode.org/ -- Country Codes + */ + +var passportRegexByCountryCode = { + AM: /^[A-Z]{2}\d{7}$/, + // ARMENIA + AR: /^[A-Z]{3}\d{6}$/, + // ARGENTINA + AT: /^[A-Z]\d{7}$/, + // AUSTRIA + AU: /^[A-Z]\d{7}$/, + // AUSTRALIA + BE: /^[A-Z]{2}\d{6}$/, + // BELGIUM + BG: /^\d{9}$/, + // BULGARIA + BR: /^[A-Z]{2}\d{6}$/, + // BRAZIL + BY: /^[A-Z]{2}\d{7}$/, + // BELARUS + CA: /^[A-Z]{2}\d{6}$/, + // CANADA + CH: /^[A-Z]\d{7}$/, + // SWITZERLAND + CN: /^G\d{8}$|^E(?![IO])[A-Z0-9]\d{7}$/, + // CHINA [G=Ordinary, E=Electronic] followed by 8-digits, or E followed by any UPPERCASE letter (except I and O) followed by 7 digits + CY: /^[A-Z](\d{6}|\d{8})$/, + // CYPRUS + CZ: /^\d{8}$/, + // CZECH REPUBLIC + DE: /^[CFGHJKLMNPRTVWXYZ0-9]{9}$/, + // GERMANY + DK: /^\d{9}$/, + // DENMARK + DZ: /^\d{9}$/, + // ALGERIA + EE: /^([A-Z]\d{7}|[A-Z]{2}\d{7})$/, + // ESTONIA (K followed by 7-digits), e-passports have 2 UPPERCASE followed by 7 digits + ES: /^[A-Z0-9]{2}([A-Z0-9]?)\d{6}$/, + // SPAIN + FI: /^[A-Z]{2}\d{7}$/, + // FINLAND + FR: /^\d{2}[A-Z]{2}\d{5}$/, + // FRANCE + GB: /^\d{9}$/, + // UNITED KINGDOM + GR: /^[A-Z]{2}\d{7}$/, + // GREECE + HR: /^\d{9}$/, + // CROATIA + HU: /^[A-Z]{2}(\d{6}|\d{7})$/, + // HUNGARY + IE: /^[A-Z0-9]{2}\d{7}$/, + // IRELAND + IN: /^[A-Z]{1}-?\d{7}$/, + // INDIA + ID: /^[A-C]\d{7}$/, + // INDONESIA + IR: /^[A-Z]\d{8}$/, + // IRAN + IS: /^(A)\d{7}$/, + // ICELAND + IT: /^[A-Z0-9]{2}\d{7}$/, + // ITALY + JP: /^[A-Z]{2}\d{7}$/, + // JAPAN + KR: /^[MS]\d{8}$/, + // SOUTH KOREA, REPUBLIC OF KOREA, [S=PS Passports, M=PM Passports] + LT: /^[A-Z0-9]{8}$/, + // LITHUANIA + LU: /^[A-Z0-9]{8}$/, + // LUXEMBURG + LV: /^[A-Z0-9]{2}\d{7}$/, + // LATVIA + LY: /^[A-Z0-9]{8}$/, + // LIBYA + MT: /^\d{7}$/, + // MALTA + MZ: /^([A-Z]{2}\d{7})|(\d{2}[A-Z]{2}\d{5})$/, + // MOZAMBIQUE + MY: /^[AHK]\d{8}$/, + // MALAYSIA + NL: /^[A-Z]{2}[A-Z0-9]{6}\d$/, + // NETHERLANDS + PL: /^[A-Z]{2}\d{7}$/, + // POLAND + PT: /^[A-Z]\d{6}$/, + // PORTUGAL + RO: /^\d{8,9}$/, + // ROMANIA + RU: /^\d{9}$/, + // RUSSIAN FEDERATION + SE: /^\d{8}$/, + // SWEDEN + SL: /^(P)[A-Z]\d{7}$/, + // SLOVANIA + SK: /^[0-9A-Z]\d{7}$/, + // SLOVAKIA + TR: /^[A-Z]\d{8}$/, + // TURKEY + UA: /^[A-Z]{2}\d{6}$/, + // UKRAINE + US: /^\d{9}$/ // UNITED STATES + +}; +/** + * Check if str is a valid passport number + * relative to provided ISO Country Code. + * + * @param {string} str + * @param {string} countryCode + * @return {boolean} + */ + +export default function isPassportNumber(str, countryCode) { + assertString(str); + /** Remove All Whitespaces, Convert to UPPERCASE */ + + var normalizedStr = str.replace(/\s/g, '').toUpperCase(); + return countryCode.toUpperCase() in passportRegexByCountryCode && passportRegexByCountryCode[countryCode].test(normalizedStr); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isPort.js b/node_modules/validator/es/lib/isPort.js new file mode 100644 index 0000000..6490cad --- /dev/null +++ b/node_modules/validator/es/lib/isPort.js @@ -0,0 +1,7 @@ +import isInt from './isInt'; +export default function isPort(str) { + return isInt(str, { + min: 0, + max: 65535 + }); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isPostalCode.js b/node_modules/validator/es/lib/isPostalCode.js new file mode 100644 index 0000000..359fa8f --- /dev/null +++ b/node_modules/validator/es/lib/isPostalCode.js @@ -0,0 +1,96 @@ +import assertString from './util/assertString'; // common patterns + +var threeDigit = /^\d{3}$/; +var fourDigit = /^\d{4}$/; +var fiveDigit = /^\d{5}$/; +var sixDigit = /^\d{6}$/; +var patterns = { + AD: /^AD\d{3}$/, + AT: fourDigit, + AU: fourDigit, + AZ: /^AZ\d{4}$/, + BE: fourDigit, + BG: fourDigit, + BR: /^\d{5}-\d{3}$/, + BY: /2[1-4]{1}\d{4}$/, + CA: /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][\s\-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i, + CH: fourDigit, + CN: /^(0[1-7]|1[012356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[1-5]|8[1345]|9[09])\d{4}$/, + CZ: /^\d{3}\s?\d{2}$/, + DE: fiveDigit, + DK: fourDigit, + DO: fiveDigit, + DZ: fiveDigit, + EE: fiveDigit, + ES: /^(5[0-2]{1}|[0-4]{1}\d{1})\d{3}$/, + FI: fiveDigit, + FR: /^\d{2}\s?\d{3}$/, + GB: /^(gir\s?0aa|[a-z]{1,2}\d[\da-z]?\s?(\d[a-z]{2})?)$/i, + GR: /^\d{3}\s?\d{2}$/, + HR: /^([1-5]\d{4}$)/, + HT: /^HT\d{4}$/, + HU: fourDigit, + ID: fiveDigit, + IE: /^(?!.*(?:o))[A-Za-z]\d[\dw]\s\w{4}$/i, + IL: /^(\d{5}|\d{7})$/, + IN: /^((?!10|29|35|54|55|65|66|86|87|88|89)[1-9][0-9]{5})$/, + IR: /\b(?!(\d)\1{3})[13-9]{4}[1346-9][013-9]{5}\b/, + IS: threeDigit, + IT: fiveDigit, + JP: /^\d{3}\-\d{4}$/, + KE: fiveDigit, + KR: /^(\d{5}|\d{6})$/, + LI: /^(948[5-9]|949[0-7])$/, + LT: /^LT\-\d{5}$/, + LU: fourDigit, + LV: /^LV\-\d{4}$/, + LK: fiveDigit, + MX: fiveDigit, + MT: /^[A-Za-z]{3}\s{0,1}\d{4}$/, + MY: fiveDigit, + NL: /^\d{4}\s?[a-z]{2}$/i, + NO: fourDigit, + NP: /^(10|21|22|32|33|34|44|45|56|57)\d{3}$|^(977)$/i, + NZ: fourDigit, + PL: /^\d{2}\-\d{3}$/, + PR: /^00[679]\d{2}([ -]\d{4})?$/, + PT: /^\d{4}\-\d{3}?$/, + RO: sixDigit, + RU: sixDigit, + SA: fiveDigit, + SE: /^[1-9]\d{2}\s?\d{2}$/, + SG: sixDigit, + SI: fourDigit, + SK: /^\d{3}\s?\d{2}$/, + TH: fiveDigit, + TN: fourDigit, + TW: /^\d{3}(\d{2})?$/, + UA: fiveDigit, + US: /^\d{5}(-\d{4})?$/, + ZA: fourDigit, + ZM: fiveDigit +}; +export var locales = Object.keys(patterns); +export default function isPostalCode(str, locale) { + assertString(str); + + if (locale in patterns) { + return patterns[locale].test(str); + } else if (locale === 'any') { + for (var key in patterns) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (patterns.hasOwnProperty(key)) { + var pattern = patterns[key]; + + if (pattern.test(str)) { + return true; + } + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isRFC3339.js b/node_modules/validator/es/lib/isRFC3339.js new file mode 100644 index 0000000..b9926ed --- /dev/null +++ b/node_modules/validator/es/lib/isRFC3339.js @@ -0,0 +1,20 @@ +import assertString from './util/assertString'; +/* Based on https://tools.ietf.org/html/rfc3339#section-5.6 */ + +var dateFullYear = /[0-9]{4}/; +var dateMonth = /(0[1-9]|1[0-2])/; +var dateMDay = /([12]\d|0[1-9]|3[01])/; +var timeHour = /([01][0-9]|2[0-3])/; +var timeMinute = /[0-5][0-9]/; +var timeSecond = /([0-5][0-9]|60)/; +var timeSecFrac = /(\.[0-9]+)?/; +var timeNumOffset = new RegExp("[-+]".concat(timeHour.source, ":").concat(timeMinute.source)); +var timeOffset = new RegExp("([zZ]|".concat(timeNumOffset.source, ")")); +var partialTime = new RegExp("".concat(timeHour.source, ":").concat(timeMinute.source, ":").concat(timeSecond.source).concat(timeSecFrac.source)); +var fullDate = new RegExp("".concat(dateFullYear.source, "-").concat(dateMonth.source, "-").concat(dateMDay.source)); +var fullTime = new RegExp("".concat(partialTime.source).concat(timeOffset.source)); +var rfc3339 = new RegExp("^".concat(fullDate.source, "[ tT]").concat(fullTime.source, "$")); +export default function isRFC3339(str) { + assertString(str); + return rfc3339.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isRgbColor.js b/node_modules/validator/es/lib/isRgbColor.js new file mode 100644 index 0000000..2fe2fbb --- /dev/null +++ b/node_modules/validator/es/lib/isRgbColor.js @@ -0,0 +1,15 @@ +import assertString from './util/assertString'; +var rgbColor = /^rgb\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\)$/; +var rgbaColor = /^rgba\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)$/; +var rgbColorPercent = /^rgb\((([0-9]%|[1-9][0-9]%|100%),){2}([0-9]%|[1-9][0-9]%|100%)\)/; +var rgbaColorPercent = /^rgba\((([0-9]%|[1-9][0-9]%|100%),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)/; +export default function isRgbColor(str) { + var includePercentValues = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + assertString(str); + + if (!includePercentValues) { + return rgbColor.test(str) || rgbaColor.test(str); + } + + return rgbColor.test(str) || rgbaColor.test(str) || rgbColorPercent.test(str) || rgbaColorPercent.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isSemVer.js b/node_modules/validator/es/lib/isSemVer.js new file mode 100644 index 0000000..f6dd9bd --- /dev/null +++ b/node_modules/validator/es/lib/isSemVer.js @@ -0,0 +1,14 @@ +import assertString from './util/assertString'; +import multilineRegexp from './util/multilineRegex'; +/** + * Regular Expression to match + * semantic versioning (SemVer) + * built from multi-line, multi-parts regexp + * Reference: https://semver.org/ + */ + +var semanticVersioningRegex = multilineRegexp(['^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)', '(?:-((?:0|[1-9]\\d*|\\d*[a-z-][0-9a-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-z-][0-9a-z-]*))*))', '?(?:\\+([0-9a-z-]+(?:\\.[0-9a-z-]+)*))?$'], 'i'); +export default function isSemVer(str) { + assertString(str); + return semanticVersioningRegex.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isSlug.js b/node_modules/validator/es/lib/isSlug.js new file mode 100644 index 0000000..b9659ef --- /dev/null +++ b/node_modules/validator/es/lib/isSlug.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +var charsetRegex = /^[^\s-_](?!.*?[-_]{2,})[a-z0-9-\\][^\s]*[^-_\s]$/; +export default function isSlug(str) { + assertString(str); + return charsetRegex.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isStrongPassword.js b/node_modules/validator/es/lib/isStrongPassword.js new file mode 100644 index 0000000..0d55633 --- /dev/null +++ b/node_modules/validator/es/lib/isStrongPassword.js @@ -0,0 +1,101 @@ +import merge from './util/merge'; +import assertString from './util/assertString'; +var upperCaseRegex = /^[A-Z]$/; +var lowerCaseRegex = /^[a-z]$/; +var numberRegex = /^[0-9]$/; +var symbolRegex = /^[-#!$@%^&*()_+|~=`{}\[\]:";'<>?,.\/ ]$/; +var defaultOptions = { + minLength: 8, + minLowercase: 1, + minUppercase: 1, + minNumbers: 1, + minSymbols: 1, + returnScore: false, + pointsPerUnique: 1, + pointsPerRepeat: 0.5, + pointsForContainingLower: 10, + pointsForContainingUpper: 10, + pointsForContainingNumber: 10, + pointsForContainingSymbol: 10 +}; +/* Counts number of occurrences of each char in a string + * could be moved to util/ ? +*/ + +function countChars(str) { + var result = {}; + Array.from(str).forEach(function (_char) { + var curVal = result[_char]; + + if (curVal) { + result[_char] += 1; + } else { + result[_char] = 1; + } + }); + return result; +} +/* Return information about a password */ + + +function analyzePassword(password) { + var charMap = countChars(password); + var analysis = { + length: password.length, + uniqueChars: Object.keys(charMap).length, + uppercaseCount: 0, + lowercaseCount: 0, + numberCount: 0, + symbolCount: 0 + }; + Object.keys(charMap).forEach(function (_char2) { + /* istanbul ignore else */ + if (upperCaseRegex.test(_char2)) { + analysis.uppercaseCount += charMap[_char2]; + } else if (lowerCaseRegex.test(_char2)) { + analysis.lowercaseCount += charMap[_char2]; + } else if (numberRegex.test(_char2)) { + analysis.numberCount += charMap[_char2]; + } else if (symbolRegex.test(_char2)) { + analysis.symbolCount += charMap[_char2]; + } + }); + return analysis; +} + +function scorePassword(analysis, scoringOptions) { + var points = 0; + points += analysis.uniqueChars * scoringOptions.pointsPerUnique; + points += (analysis.length - analysis.uniqueChars) * scoringOptions.pointsPerRepeat; + + if (analysis.lowercaseCount > 0) { + points += scoringOptions.pointsForContainingLower; + } + + if (analysis.uppercaseCount > 0) { + points += scoringOptions.pointsForContainingUpper; + } + + if (analysis.numberCount > 0) { + points += scoringOptions.pointsForContainingNumber; + } + + if (analysis.symbolCount > 0) { + points += scoringOptions.pointsForContainingSymbol; + } + + return points; +} + +export default function isStrongPassword(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + assertString(str); + var analysis = analyzePassword(str); + options = merge(options || {}, defaultOptions); + + if (options.returnScore) { + return scorePassword(analysis, options); + } + + return analysis.length >= options.minLength && analysis.lowercaseCount >= options.minLowercase && analysis.uppercaseCount >= options.minUppercase && analysis.numberCount >= options.minNumbers && analysis.symbolCount >= options.minSymbols; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isSurrogatePair.js b/node_modules/validator/es/lib/isSurrogatePair.js new file mode 100644 index 0000000..1e0efb2 --- /dev/null +++ b/node_modules/validator/es/lib/isSurrogatePair.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/; +export default function isSurrogatePair(str) { + assertString(str); + return surrogatePair.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isTaxID.js b/node_modules/validator/es/lib/isTaxID.js new file mode 100644 index 0000000..1107cc0 --- /dev/null +++ b/node_modules/validator/es/lib/isTaxID.js @@ -0,0 +1,1508 @@ +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +import assertString from './util/assertString'; +import * as algorithms from './util/algorithms'; +import isDate from './isDate'; +/** + * TIN Validation + * Validates Tax Identification Numbers (TINs) from the US, EU member states and the United Kingdom. + * + * EU-UK: + * National TIN validity is calculated using public algorithms as made available by DG TAXUD. + * + * See `https://ec.europa.eu/taxation_customs/tin/specs/FS-TIN%20Algorithms-Public.docx` for more information. + * + * US: + * An Employer Identification Number (EIN), also known as a Federal Tax Identification Number, + * is used to identify a business entity. + * + * NOTES: + * - Prefix 47 is being reserved for future use + * - Prefixes 26, 27, 45, 46 and 47 were previously assigned by the Philadelphia campus. + * + * See `http://www.irs.gov/Businesses/Small-Businesses-&-Self-Employed/How-EINs-are-Assigned-and-Valid-EIN-Prefixes` + * for more information. + */ +// Locale functions + +/* + * bg-BG validation function + * (Edinen graždanski nomer (EGN/ЕГН), persons only) + * Checks if birth date (first six digits) is valid and calculates check (last) digit + */ + +function bgBgCheck(tin) { + // Extract full year, normalize month and check birth date validity + var century_year = tin.slice(0, 2); + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 40) { + month -= 40; + century_year = "20".concat(century_year); + } else if (month > 20) { + month -= 20; + century_year = "18".concat(century_year); + } else { + century_year = "19".concat(century_year); + } + + if (month < 10) { + month = "0".concat(month); + } + + var date = "".concat(century_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // split digits into an array for further processing + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); // Calculate checksum by multiplying digits with fixed values + + var multip_lookup = [2, 4, 8, 5, 10, 9, 7, 3, 6]; + var checksum = 0; + + for (var i = 0; i < multip_lookup.length; i++) { + checksum += digits[i] * multip_lookup[i]; + } + + checksum = checksum % 11 === 10 ? 0 : checksum % 11; + return checksum === digits[9]; +} +/* + * cs-CZ validation function + * (Rodné číslo (RČ), persons only) + * Checks if birth date (first six digits) is valid and divisibility by 11 + * Material not in DG TAXUD document sourced from: + * -`https://lorenc.info/3MA381/overeni-spravnosti-rodneho-cisla.htm` + * -`https://www.mvcr.cz/clanek/rady-a-sluzby-dokumenty-rodne-cislo.aspx` + */ + + +function csCzCheck(tin) { + tin = tin.replace(/\W/, ''); // Extract full year from TIN length + + var full_year = parseInt(tin.slice(0, 2), 10); + + if (tin.length === 10) { + if (full_year < 54) { + full_year = "20".concat(full_year); + } else { + full_year = "19".concat(full_year); + } + } else { + if (tin.slice(6) === '000') { + return false; + } // Three-zero serial not assigned before 1954 + + + if (full_year < 54) { + full_year = "19".concat(full_year); + } else { + return false; // No 18XX years seen in any of the resources + } + } // Add missing zero if needed + + + if (full_year.length === 3) { + full_year = [full_year.slice(0, 2), '0', full_year.slice(2)].join(''); + } // Extract month from TIN and normalize + + + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 50) { + month -= 50; + } + + if (month > 20) { + // Month-plus-twenty was only introduced in 2004 + if (parseInt(full_year, 10) < 2004) { + return false; + } + + month -= 20; + } + + if (month < 10) { + month = "0".concat(month); + } // Check date validity + + + var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Verify divisibility by 11 + + + if (tin.length === 10) { + if (parseInt(tin, 10) % 11 !== 0) { + // Some numbers up to and including 1985 are still valid if + // check (last) digit equals 0 and modulo of first 9 digits equals 10 + var checkdigit = parseInt(tin.slice(0, 9), 10) % 11; + + if (parseInt(full_year, 10) < 1986 && checkdigit === 10) { + if (parseInt(tin.slice(9), 10) !== 0) { + return false; + } + } else { + return false; + } + } + } + + return true; +} +/* + * de-AT validation function + * (Abgabenkontonummer, persons/entities) + * Verify TIN validity by calling luhnCheck() + */ + + +function deAtCheck(tin) { + return algorithms.luhnCheck(tin); +} +/* + * de-DE validation function + * (Steueridentifikationsnummer (Steuer-IdNr.), persons only) + * Tests for single duplicate/triplicate value, then calculates ISO 7064 check (last) digit + * Partial implementation of spec (same result with both algorithms always) + */ + + +function deDeCheck(tin) { + // Split digits into an array for further processing + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); // Fill array with strings of number positions + + var occurences = []; + + for (var i = 0; i < digits.length - 1; i++) { + occurences.push(''); + + for (var j = 0; j < digits.length - 1; j++) { + if (digits[i] === digits[j]) { + occurences[i] += j; + } + } + } // Remove digits with one occurence and test for only one duplicate/triplicate + + + occurences = occurences.filter(function (a) { + return a.length > 1; + }); + + if (occurences.length !== 2 && occurences.length !== 3) { + return false; + } // In case of triplicate value only two digits are allowed next to each other + + + if (occurences[0].length === 3) { + var trip_locations = occurences[0].split('').map(function (a) { + return parseInt(a, 10); + }); + var recurrent = 0; // Amount of neighbour occurences + + for (var _i = 0; _i < trip_locations.length - 1; _i++) { + if (trip_locations[_i] + 1 === trip_locations[_i + 1]) { + recurrent += 1; + } + } + + if (recurrent === 2) { + return false; + } + } + + return algorithms.iso7064Check(tin); +} +/* + * dk-DK validation function + * (CPR-nummer (personnummer), persons only) + * Checks if birth date (first six digits) is valid and assigned to century (seventh) digit, + * and calculates check (last) digit + */ + + +function dkDkCheck(tin) { + tin = tin.replace(/\W/, ''); // Extract year, check if valid for given century digit and add century + + var year = parseInt(tin.slice(4, 6), 10); + var century_digit = tin.slice(6, 7); + + switch (century_digit) { + case '0': + case '1': + case '2': + case '3': + year = "19".concat(year); + break; + + case '4': + case '9': + if (year < 37) { + year = "20".concat(year); + } else { + year = "19".concat(year); + } + + break; + + default: + if (year < 37) { + year = "20".concat(year); + } else if (year > 58) { + year = "18".concat(year); + } else { + return false; + } + + break; + } // Add missing zero if needed + + + if (year.length === 3) { + year = [year.slice(0, 2), '0', year.slice(2)].join(''); + } // Check date validity + + + var date = "".concat(year, "/").concat(tin.slice(2, 4), "/").concat(tin.slice(0, 2)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Split digits into an array for further processing + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; + var weight = 4; // Multiply by weight and add to checksum + + for (var i = 0; i < 9; i++) { + checksum += digits[i] * weight; + weight -= 1; + + if (weight === 1) { + weight = 7; + } + } + + checksum %= 11; + + if (checksum === 1) { + return false; + } + + return checksum === 0 ? digits[9] === 0 : digits[9] === 11 - checksum; +} +/* + * el-CY validation function + * (Arithmos Forologikou Mitroou (AFM/ΑΦΜ), persons only) + * Verify TIN validity by calculating ASCII value of check (last) character + */ + + +function elCyCheck(tin) { + // split digits into an array for further processing + var digits = tin.slice(0, 8).split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; // add digits in even places + + for (var i = 1; i < digits.length; i += 2) { + checksum += digits[i]; + } // add digits in odd places + + + for (var _i2 = 0; _i2 < digits.length; _i2 += 2) { + if (digits[_i2] < 2) { + checksum += 1 - digits[_i2]; + } else { + checksum += 2 * (digits[_i2] - 2) + 5; + + if (digits[_i2] > 4) { + checksum += 2; + } + } + } + + return String.fromCharCode(checksum % 26 + 65) === tin.charAt(8); +} +/* + * el-GR validation function + * (Arithmos Forologikou Mitroou (AFM/ΑΦΜ), persons/entities) + * Verify TIN validity by calculating check (last) digit + * Algorithm not in DG TAXUD document- sourced from: + * - `http://epixeirisi.gr/%CE%9A%CE%A1%CE%99%CE%A3%CE%99%CE%9C%CE%91-%CE%98%CE%95%CE%9C%CE%91%CE%A4%CE%91-%CE%A6%CE%9F%CE%A1%CE%9F%CE%9B%CE%9F%CE%93%CE%99%CE%91%CE%A3-%CE%9A%CE%91%CE%99-%CE%9B%CE%9F%CE%93%CE%99%CE%A3%CE%A4%CE%99%CE%9A%CE%97%CE%A3/23791/%CE%91%CF%81%CE%B9%CE%B8%CE%BC%CF%8C%CF%82-%CE%A6%CE%BF%CF%81%CE%BF%CE%BB%CE%BF%CE%B3%CE%B9%CE%BA%CE%BF%CF%8D-%CE%9C%CE%B7%CF%84%CF%81%CF%8E%CE%BF%CF%85` + */ + + +function elGrCheck(tin) { + // split digits into an array for further processing + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; + + for (var i = 0; i < 8; i++) { + checksum += digits[i] * Math.pow(2, 8 - i); + } + + return checksum % 11 % 10 === digits[8]; +} +/* + * en-GB validation function (should go here if needed) + * (National Insurance Number (NINO) or Unique Taxpayer Reference (UTR), + * persons/entities respectively) + */ + +/* + * en-IE validation function + * (Personal Public Service Number (PPS No), persons only) + * Verify TIN validity by calculating check (second to last) character + */ + + +function enIeCheck(tin) { + var checksum = algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 7).map(function (a) { + return parseInt(a, 10); + }), 8); + + if (tin.length === 9 && tin[8] !== 'W') { + checksum += (tin[8].charCodeAt(0) - 64) * 9; + } + + checksum %= 23; + + if (checksum === 0) { + return tin[7].toUpperCase() === 'W'; + } + + return tin[7].toUpperCase() === String.fromCharCode(64 + checksum); +} // Valid US IRS campus prefixes + + +var enUsCampusPrefix = { + andover: ['10', '12'], + atlanta: ['60', '67'], + austin: ['50', '53'], + brookhaven: ['01', '02', '03', '04', '05', '06', '11', '13', '14', '16', '21', '22', '23', '25', '34', '51', '52', '54', '55', '56', '57', '58', '59', '65'], + cincinnati: ['30', '32', '35', '36', '37', '38', '61'], + fresno: ['15', '24'], + internet: ['20', '26', '27', '45', '46', '47'], + kansas: ['40', '44'], + memphis: ['94', '95'], + ogden: ['80', '90'], + philadelphia: ['33', '39', '41', '42', '43', '46', '48', '62', '63', '64', '66', '68', '71', '72', '73', '74', '75', '76', '77', '81', '82', '83', '84', '85', '86', '87', '88', '91', '92', '93', '98', '99'], + sba: ['31'] +}; // Return an array of all US IRS campus prefixes + +function enUsGetPrefixes() { + var prefixes = []; + + for (var location in enUsCampusPrefix) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (enUsCampusPrefix.hasOwnProperty(location)) { + prefixes.push.apply(prefixes, _toConsumableArray(enUsCampusPrefix[location])); + } + } + + return prefixes; +} +/* + * en-US validation function + * Verify that the TIN starts with a valid IRS campus prefix + */ + + +function enUsCheck(tin) { + return enUsGetPrefixes().indexOf(tin.substr(0, 2)) !== -1; +} +/* + * es-ES validation function + * (Documento Nacional de Identidad (DNI) + * or Número de Identificación de Extranjero (NIE), persons only) + * Verify TIN validity by calculating check (last) character + */ + + +function esEsCheck(tin) { + // Split characters into an array for further processing + var chars = tin.toUpperCase().split(''); // Replace initial letter if needed + + if (isNaN(parseInt(chars[0], 10)) && chars.length > 1) { + var lead_replace = 0; + + switch (chars[0]) { + case 'Y': + lead_replace = 1; + break; + + case 'Z': + lead_replace = 2; + break; + + default: + } + + chars.splice(0, 1, lead_replace); // Fill with zeros if smaller than proper + } else { + while (chars.length < 9) { + chars.unshift(0); + } + } // Calculate checksum and check according to lookup + + + var lookup = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E']; + chars = chars.join(''); + var checksum = parseInt(chars.slice(0, 8), 10) % 23; + return chars[8] === lookup[checksum]; +} +/* + * et-EE validation function + * (Isikukood (IK), persons only) + * Checks if birth date (century digit and six following) is valid and calculates check (last) digit + * Material not in DG TAXUD document sourced from: + * - `https://www.oecd.org/tax/automatic-exchange/crs-implementation-and-assistance/tax-identification-numbers/Estonia-TIN.pdf` + */ + + +function etEeCheck(tin) { + // Extract year and add century + var full_year = tin.slice(1, 3); + var century_digit = tin.slice(0, 1); + + switch (century_digit) { + case '1': + case '2': + full_year = "18".concat(full_year); + break; + + case '3': + case '4': + full_year = "19".concat(full_year); + break; + + default: + full_year = "20".concat(full_year); + break; + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(3, 5), "/").concat(tin.slice(5, 7)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Split digits into an array for further processing + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; + var weight = 1; // Multiply by weight and add to checksum + + for (var i = 0; i < 10; i++) { + checksum += digits[i] * weight; + weight += 1; + + if (weight === 10) { + weight = 1; + } + } // Do again if modulo 11 of checksum is 10 + + + if (checksum % 11 === 10) { + checksum = 0; + weight = 3; + + for (var _i3 = 0; _i3 < 10; _i3++) { + checksum += digits[_i3] * weight; + weight += 1; + + if (weight === 10) { + weight = 1; + } + } + + if (checksum % 11 === 10) { + return digits[10] === 0; + } + } + + return checksum % 11 === digits[10]; +} +/* + * fi-FI validation function + * (Henkilötunnus (HETU), persons only) + * Checks if birth date (first six digits plus century symbol) is valid + * and calculates check (last) digit + */ + + +function fiFiCheck(tin) { + // Extract year and add century + var full_year = tin.slice(4, 6); + var century_symbol = tin.slice(6, 7); + + switch (century_symbol) { + case '+': + full_year = "18".concat(full_year); + break; + + case '-': + full_year = "19".concat(full_year); + break; + + default: + full_year = "20".concat(full_year); + break; + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(2, 4), "/").concat(tin.slice(0, 2)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Calculate check character + + + var checksum = parseInt(tin.slice(0, 6) + tin.slice(7, 10), 10) % 31; + + if (checksum < 10) { + return checksum === parseInt(tin.slice(10), 10); + } + + checksum -= 10; + var letters_lookup = ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y']; + return letters_lookup[checksum] === tin.slice(10); +} +/* + * fr/nl-BE validation function + * (Numéro national (N.N.), persons only) + * Checks if birth date (first six digits) is valid and calculates check (last two) digits + */ + + +function frBeCheck(tin) { + // Zero month/day value is acceptable + if (tin.slice(2, 4) !== '00' || tin.slice(4, 6) !== '00') { + // Extract date from first six digits of TIN + var date = "".concat(tin.slice(0, 2), "/").concat(tin.slice(2, 4), "/").concat(tin.slice(4, 6)); + + if (!isDate(date, 'YY/MM/DD')) { + return false; + } + } + + var checksum = 97 - parseInt(tin.slice(0, 9), 10) % 97; + var checkdigits = parseInt(tin.slice(9, 11), 10); + + if (checksum !== checkdigits) { + checksum = 97 - parseInt("2".concat(tin.slice(0, 9)), 10) % 97; + + if (checksum !== checkdigits) { + return false; + } + } + + return true; +} +/* + * fr-FR validation function + * (Numéro fiscal de référence (numéro SPI), persons only) + * Verify TIN validity by calculating check (last three) digits + */ + + +function frFrCheck(tin) { + tin = tin.replace(/\s/g, ''); + var checksum = parseInt(tin.slice(0, 10), 10) % 511; + var checkdigits = parseInt(tin.slice(10, 13), 10); + return checksum === checkdigits; +} +/* + * fr/lb-LU validation function + * (numéro d’identification personnelle, persons only) + * Verify birth date validity and run Luhn and Verhoeff checks + */ + + +function frLuCheck(tin) { + // Extract date and check validity + var date = "".concat(tin.slice(0, 4), "/").concat(tin.slice(4, 6), "/").concat(tin.slice(6, 8)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Run Luhn check + + + if (!algorithms.luhnCheck(tin.slice(0, 12))) { + return false; + } // Remove Luhn check digit and run Verhoeff check + + + return algorithms.verhoeffCheck("".concat(tin.slice(0, 11)).concat(tin[12])); +} +/* + * hr-HR validation function + * (Osobni identifikacijski broj (OIB), persons/entities) + * Verify TIN validity by calling iso7064Check(digits) + */ + + +function hrHrCheck(tin) { + return algorithms.iso7064Check(tin); +} +/* + * hu-HU validation function + * (Adóazonosító jel, persons only) + * Verify TIN validity by calculating check (last) digit + */ + + +function huHuCheck(tin) { + // split digits into an array for further processing + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 8; + + for (var i = 1; i < 9; i++) { + checksum += digits[i] * (i + 1); + } + + return checksum % 11 === digits[9]; +} +/* + * lt-LT validation function (should go here if needed) + * (Asmens kodas, persons/entities respectively) + * Current validation check is alias of etEeCheck- same format applies + */ + +/* + * it-IT first/last name validity check + * Accepts it-IT TIN-encoded names as a three-element character array and checks their validity + * Due to lack of clarity between resources ("Are only Italian consonants used? + * What happens if a person has X in their name?" etc.) only two test conditions + * have been implemented: + * Vowels may only be followed by other vowels or an X character + * and X characters after vowels may only be followed by other X characters. + */ + + +function itItNameCheck(name) { + // true at the first occurence of a vowel + var vowelflag = false; // true at the first occurence of an X AFTER vowel + // (to properly handle last names with X as consonant) + + var xflag = false; + + for (var i = 0; i < 3; i++) { + if (!vowelflag && /[AEIOU]/.test(name[i])) { + vowelflag = true; + } else if (!xflag && vowelflag && name[i] === 'X') { + xflag = true; + } else if (i > 0) { + if (vowelflag && !xflag) { + if (!/[AEIOU]/.test(name[i])) { + return false; + } + } + + if (xflag) { + if (!/X/.test(name[i])) { + return false; + } + } + } + } + + return true; +} +/* + * it-IT validation function + * (Codice fiscale (TIN-IT), persons only) + * Verify name, birth date and codice catastale validity + * and calculate check character. + * Material not in DG-TAXUD document sourced from: + * `https://en.wikipedia.org/wiki/Italian_fiscal_code` + */ + + +function itItCheck(tin) { + // Capitalize and split characters into an array for further processing + var chars = tin.toUpperCase().split(''); // Check first and last name validity calling itItNameCheck() + + if (!itItNameCheck(chars.slice(0, 3))) { + return false; + } + + if (!itItNameCheck(chars.slice(3, 6))) { + return false; + } // Convert letters in number spaces back to numbers if any + + + var number_locations = [6, 7, 9, 10, 12, 13, 14]; + var number_replace = { + L: '0', + M: '1', + N: '2', + P: '3', + Q: '4', + R: '5', + S: '6', + T: '7', + U: '8', + V: '9' + }; + + for (var _i4 = 0, _number_locations = number_locations; _i4 < _number_locations.length; _i4++) { + var i = _number_locations[_i4]; + + if (chars[i] in number_replace) { + chars.splice(i, 1, number_replace[chars[i]]); + } + } // Extract month and day, and check date validity + + + var month_replace = { + A: '01', + B: '02', + C: '03', + D: '04', + E: '05', + H: '06', + L: '07', + M: '08', + P: '09', + R: '10', + S: '11', + T: '12' + }; + var month = month_replace[chars[8]]; + var day = parseInt(chars[9] + chars[10], 10); + + if (day > 40) { + day -= 40; + } + + if (day < 10) { + day = "0".concat(day); + } + + var date = "".concat(chars[6]).concat(chars[7], "/").concat(month, "/").concat(day); + + if (!isDate(date, 'YY/MM/DD')) { + return false; + } // Calculate check character by adding up even and odd characters as numbers + + + var checksum = 0; + + for (var _i5 = 1; _i5 < chars.length - 1; _i5 += 2) { + var char_to_int = parseInt(chars[_i5], 10); + + if (isNaN(char_to_int)) { + char_to_int = chars[_i5].charCodeAt(0) - 65; + } + + checksum += char_to_int; + } + + var odd_convert = { + // Maps of characters at odd places + A: 1, + B: 0, + C: 5, + D: 7, + E: 9, + F: 13, + G: 15, + H: 17, + I: 19, + J: 21, + K: 2, + L: 4, + M: 18, + N: 20, + O: 11, + P: 3, + Q: 6, + R: 8, + S: 12, + T: 14, + U: 16, + V: 10, + W: 22, + X: 25, + Y: 24, + Z: 23, + 0: 1, + 1: 0 + }; + + for (var _i6 = 0; _i6 < chars.length - 1; _i6 += 2) { + var _char_to_int = 0; + + if (chars[_i6] in odd_convert) { + _char_to_int = odd_convert[chars[_i6]]; + } else { + var multiplier = parseInt(chars[_i6], 10); + _char_to_int = 2 * multiplier + 1; + + if (multiplier > 4) { + _char_to_int += 2; + } + } + + checksum += _char_to_int; + } + + if (String.fromCharCode(65 + checksum % 26) !== chars[15]) { + return false; + } + + return true; +} +/* + * lv-LV validation function + * (Personas kods (PK), persons only) + * Check validity of birth date and calculate check (last) digit + * Support only for old format numbers (not starting with '32', issued before 2017/07/01) + * Material not in DG TAXUD document sourced from: + * `https://boot.ritakafija.lv/forums/index.php?/topic/88314-personas-koda-algoritms-%C4%8Deksumma/` + */ + + +function lvLvCheck(tin) { + tin = tin.replace(/\W/, ''); // Extract date from TIN + + var day = tin.slice(0, 2); + + if (day !== '32') { + // No date/checksum check if new format + var month = tin.slice(2, 4); + + if (month !== '00') { + // No date check if unknown month + var full_year = tin.slice(4, 6); + + switch (tin[6]) { + case '0': + full_year = "18".concat(full_year); + break; + + case '1': + full_year = "19".concat(full_year); + break; + + default: + full_year = "20".concat(full_year); + break; + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(2, 4), "/").concat(day); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } + } // Calculate check digit + + + var checksum = 1101; + var multip_lookup = [1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; + + for (var i = 0; i < tin.length - 1; i++) { + checksum -= parseInt(tin[i], 10) * multip_lookup[i]; + } + + return parseInt(tin[10], 10) === checksum % 11; + } + + return true; +} +/* + * mt-MT validation function + * (Identity Card Number or Unique Taxpayer Reference, persons/entities) + * Verify Identity Card Number structure (no other tests found) + */ + + +function mtMtCheck(tin) { + if (tin.length !== 9) { + // No tests for UTR + var chars = tin.toUpperCase().split(''); // Fill with zeros if smaller than proper + + while (chars.length < 8) { + chars.unshift(0); + } // Validate format according to last character + + + switch (tin[7]) { + case 'A': + case 'P': + if (parseInt(chars[6], 10) === 0) { + return false; + } + + break; + + default: + { + var first_part = parseInt(chars.join('').slice(0, 5), 10); + + if (first_part > 32000) { + return false; + } + + var second_part = parseInt(chars.join('').slice(5, 7), 10); + + if (first_part === second_part) { + return false; + } + } + } + } + + return true; +} +/* + * nl-NL validation function + * (Burgerservicenummer (BSN) or Rechtspersonen Samenwerkingsverbanden Informatie Nummer (RSIN), + * persons/entities respectively) + * Verify TIN validity by calculating check (last) digit (variant of MOD 11) + */ + + +function nlNlCheck(tin) { + return algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 8).map(function (a) { + return parseInt(a, 10); + }), 9) % 11 === parseInt(tin[8], 10); +} +/* + * pl-PL validation function + * (Powszechny Elektroniczny System Ewidencji Ludności (PESEL) + * or Numer identyfikacji podatkowej (NIP), persons/entities) + * Verify TIN validity by validating birth date (PESEL) and calculating check (last) digit + */ + + +function plPlCheck(tin) { + // NIP + if (tin.length === 10) { + // Calculate last digit by multiplying with lookup + var lookup = [6, 5, 7, 2, 3, 4, 5, 6, 7]; + var _checksum = 0; + + for (var i = 0; i < lookup.length; i++) { + _checksum += parseInt(tin[i], 10) * lookup[i]; + } + + _checksum %= 11; + + if (_checksum === 10) { + return false; + } + + return _checksum === parseInt(tin[9], 10); + } // PESEL + // Extract full year using month + + + var full_year = tin.slice(0, 2); + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 80) { + full_year = "18".concat(full_year); + month -= 80; + } else if (month > 60) { + full_year = "22".concat(full_year); + month -= 60; + } else if (month > 40) { + full_year = "21".concat(full_year); + month -= 40; + } else if (month > 20) { + full_year = "20".concat(full_year); + month -= 20; + } else { + full_year = "19".concat(full_year); + } // Add leading zero to month if needed + + + if (month < 10) { + month = "0".concat(month); + } // Check date validity + + + var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Calculate last digit by mulitplying with odd one-digit numbers except 5 + + + var checksum = 0; + var multiplier = 1; + + for (var _i7 = 0; _i7 < tin.length - 1; _i7++) { + checksum += parseInt(tin[_i7], 10) * multiplier % 10; + multiplier += 2; + + if (multiplier > 10) { + multiplier = 1; + } else if (multiplier === 5) { + multiplier += 2; + } + } + + checksum = 10 - checksum % 10; + return checksum === parseInt(tin[10], 10); +} +/* +* pt-BR validation function +* (Cadastro de Pessoas Físicas (CPF, persons) +* Cadastro Nacional de Pessoas Jurídicas (CNPJ, entities) +* Both inputs will be validated +*/ + + +function ptBrCheck(tin) { + if (tin.length === 11) { + var _sum; + + var remainder; + _sum = 0; + if ( // Reject known invalid CPFs + tin === '11111111111' || tin === '22222222222' || tin === '33333333333' || tin === '44444444444' || tin === '55555555555' || tin === '66666666666' || tin === '77777777777' || tin === '88888888888' || tin === '99999999999' || tin === '00000000000') return false; + + for (var i = 1; i <= 9; i++) { + _sum += parseInt(tin.substring(i - 1, i), 10) * (11 - i); + } + + remainder = _sum * 10 % 11; + if (remainder === 10) remainder = 0; + if (remainder !== parseInt(tin.substring(9, 10), 10)) return false; + _sum = 0; + + for (var _i8 = 1; _i8 <= 10; _i8++) { + _sum += parseInt(tin.substring(_i8 - 1, _i8), 10) * (12 - _i8); + } + + remainder = _sum * 10 % 11; + if (remainder === 10) remainder = 0; + if (remainder !== parseInt(tin.substring(10, 11), 10)) return false; + return true; + } + + if ( // Reject know invalid CNPJs + tin === '00000000000000' || tin === '11111111111111' || tin === '22222222222222' || tin === '33333333333333' || tin === '44444444444444' || tin === '55555555555555' || tin === '66666666666666' || tin === '77777777777777' || tin === '88888888888888' || tin === '99999999999999') { + return false; + } + + var length = tin.length - 2; + var identifiers = tin.substring(0, length); + var verificators = tin.substring(length); + var sum = 0; + var pos = length - 7; + + for (var _i9 = length; _i9 >= 1; _i9--) { + sum += identifiers.charAt(length - _i9) * pos; + pos -= 1; + + if (pos < 2) { + pos = 9; + } + } + + var result = sum % 11 < 2 ? 0 : 11 - sum % 11; + + if (result !== parseInt(verificators.charAt(0), 10)) { + return false; + } + + length += 1; + identifiers = tin.substring(0, length); + sum = 0; + pos = length - 7; + + for (var _i10 = length; _i10 >= 1; _i10--) { + sum += identifiers.charAt(length - _i10) * pos; + pos -= 1; + + if (pos < 2) { + pos = 9; + } + } + + result = sum % 11 < 2 ? 0 : 11 - sum % 11; + + if (result !== parseInt(verificators.charAt(1), 10)) { + return false; + } + + return true; +} +/* + * pt-PT validation function + * (Número de identificação fiscal (NIF), persons/entities) + * Verify TIN validity by calculating check (last) digit (variant of MOD 11) + */ + + +function ptPtCheck(tin) { + var checksum = 11 - algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 8).map(function (a) { + return parseInt(a, 10); + }), 9) % 11; + + if (checksum > 9) { + return parseInt(tin[8], 10) === 0; + } + + return checksum === parseInt(tin[8], 10); +} +/* + * ro-RO validation function + * (Cod Numeric Personal (CNP) or Cod de înregistrare fiscală (CIF), + * persons only) + * Verify CNP validity by calculating check (last) digit (test not found for CIF) + * Material not in DG TAXUD document sourced from: + * `https://en.wikipedia.org/wiki/National_identification_number#Romania` + */ + + +function roRoCheck(tin) { + if (tin.slice(0, 4) !== '9000') { + // No test found for this format + // Extract full year using century digit if possible + var full_year = tin.slice(1, 3); + + switch (tin[0]) { + case '1': + case '2': + full_year = "19".concat(full_year); + break; + + case '3': + case '4': + full_year = "18".concat(full_year); + break; + + case '5': + case '6': + full_year = "20".concat(full_year); + break; + + default: + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(3, 5), "/").concat(tin.slice(5, 7)); + + if (date.length === 8) { + if (!isDate(date, 'YY/MM/DD')) { + return false; + } + } else if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Calculate check digit + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var multipliers = [2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9]; + var checksum = 0; + + for (var i = 0; i < multipliers.length; i++) { + checksum += digits[i] * multipliers[i]; + } + + if (checksum % 11 === 10) { + return digits[12] === 1; + } + + return digits[12] === checksum % 11; + } + + return true; +} +/* + * sk-SK validation function + * (Rodné číslo (RČ) or bezvýznamové identifikačné číslo (BIČ), persons only) + * Checks validity of pre-1954 birth numbers (rodné číslo) only + * Due to the introduction of the pseudo-random BIČ it is not possible to test + * post-1954 birth numbers without knowing whether they are BIČ or RČ beforehand + */ + + +function skSkCheck(tin) { + if (tin.length === 9) { + tin = tin.replace(/\W/, ''); + + if (tin.slice(6) === '000') { + return false; + } // Three-zero serial not assigned before 1954 + // Extract full year from TIN length + + + var full_year = parseInt(tin.slice(0, 2), 10); + + if (full_year > 53) { + return false; + } + + if (full_year < 10) { + full_year = "190".concat(full_year); + } else { + full_year = "19".concat(full_year); + } // Extract month from TIN and normalize + + + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 50) { + month -= 50; + } + + if (month < 10) { + month = "0".concat(month); + } // Check date validity + + + var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } + } + + return true; +} +/* + * sl-SI validation function + * (Davčna številka, persons/entities) + * Verify TIN validity by calculating check (last) digit (variant of MOD 11) + */ + + +function slSiCheck(tin) { + var checksum = 11 - algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 7).map(function (a) { + return parseInt(a, 10); + }), 8) % 11; + + if (checksum === 10) { + return parseInt(tin[7], 10) === 0; + } + + return checksum === parseInt(tin[7], 10); +} +/* + * sv-SE validation function + * (Personnummer or samordningsnummer, persons only) + * Checks validity of birth date and calls luhnCheck() to validate check (last) digit + */ + + +function svSeCheck(tin) { + // Make copy of TIN and normalize to two-digit year form + var tin_copy = tin.slice(0); + + if (tin.length > 11) { + tin_copy = tin_copy.slice(2); + } // Extract date of birth + + + var full_year = ''; + var month = tin_copy.slice(2, 4); + var day = parseInt(tin_copy.slice(4, 6), 10); + + if (tin.length > 11) { + full_year = tin.slice(0, 4); + } else { + full_year = tin.slice(0, 2); + + if (tin.length === 11 && day < 60) { + // Extract full year from centenarian symbol + // Should work just fine until year 10000 or so + var current_year = new Date().getFullYear().toString(); + var current_century = parseInt(current_year.slice(0, 2), 10); + current_year = parseInt(current_year, 10); + + if (tin[6] === '-') { + if (parseInt("".concat(current_century).concat(full_year), 10) > current_year) { + full_year = "".concat(current_century - 1).concat(full_year); + } else { + full_year = "".concat(current_century).concat(full_year); + } + } else { + full_year = "".concat(current_century - 1).concat(full_year); + + if (current_year - parseInt(full_year, 10) < 100) { + return false; + } + } + } + } // Normalize day and check date validity + + + if (day > 60) { + day -= 60; + } + + if (day < 10) { + day = "0".concat(day); + } + + var date = "".concat(full_year, "/").concat(month, "/").concat(day); + + if (date.length === 8) { + if (!isDate(date, 'YY/MM/DD')) { + return false; + } + } else if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } + + return algorithms.luhnCheck(tin.replace(/\W/, '')); +} // Locale lookup objects + +/* + * Tax id regex formats for various locales + * + * Where not explicitly specified in DG-TAXUD document both + * uppercase and lowercase letters are acceptable. + */ + + +var taxIdFormat = { + 'bg-BG': /^\d{10}$/, + 'cs-CZ': /^\d{6}\/{0,1}\d{3,4}$/, + 'de-AT': /^\d{9}$/, + 'de-DE': /^[1-9]\d{10}$/, + 'dk-DK': /^\d{6}-{0,1}\d{4}$/, + 'el-CY': /^[09]\d{7}[A-Z]$/, + 'el-GR': /^([0-4]|[7-9])\d{8}$/, + 'en-GB': /^\d{10}$|^(?!GB|NK|TN|ZZ)(?![DFIQUV])[A-Z](?![DFIQUVO])[A-Z]\d{6}[ABCD ]$/i, + 'en-IE': /^\d{7}[A-W][A-IW]{0,1}$/i, + 'en-US': /^\d{2}[- ]{0,1}\d{7}$/, + 'es-ES': /^(\d{0,8}|[XYZKLM]\d{7})[A-HJ-NP-TV-Z]$/i, + 'et-EE': /^[1-6]\d{6}(00[1-9]|0[1-9][0-9]|[1-6][0-9]{2}|70[0-9]|710)\d$/, + 'fi-FI': /^\d{6}[-+A]\d{3}[0-9A-FHJ-NPR-Y]$/i, + 'fr-BE': /^\d{11}$/, + 'fr-FR': /^[0-3]\d{12}$|^[0-3]\d\s\d{2}(\s\d{3}){3}$/, + // Conforms both to official spec and provided example + 'fr-LU': /^\d{13}$/, + 'hr-HR': /^\d{11}$/, + 'hu-HU': /^8\d{9}$/, + 'it-IT': /^[A-Z]{6}[L-NP-V0-9]{2}[A-EHLMPRST][L-NP-V0-9]{2}[A-ILMZ][L-NP-V0-9]{3}[A-Z]$/i, + 'lv-LV': /^\d{6}-{0,1}\d{5}$/, + // Conforms both to DG TAXUD spec and original research + 'mt-MT': /^\d{3,7}[APMGLHBZ]$|^([1-8])\1\d{7}$/i, + 'nl-NL': /^\d{9}$/, + 'pl-PL': /^\d{10,11}$/, + 'pt-BR': /(?:^\d{11}$)|(?:^\d{14}$)/, + 'pt-PT': /^\d{9}$/, + 'ro-RO': /^\d{13}$/, + 'sk-SK': /^\d{6}\/{0,1}\d{3,4}$/, + 'sl-SI': /^[1-9]\d{7}$/, + 'sv-SE': /^(\d{6}[-+]{0,1}\d{4}|(18|19|20)\d{6}[-+]{0,1}\d{4})$/ +}; // taxIdFormat locale aliases + +taxIdFormat['lb-LU'] = taxIdFormat['fr-LU']; +taxIdFormat['lt-LT'] = taxIdFormat['et-EE']; +taxIdFormat['nl-BE'] = taxIdFormat['fr-BE']; // Algorithmic tax id check functions for various locales + +var taxIdCheck = { + 'bg-BG': bgBgCheck, + 'cs-CZ': csCzCheck, + 'de-AT': deAtCheck, + 'de-DE': deDeCheck, + 'dk-DK': dkDkCheck, + 'el-CY': elCyCheck, + 'el-GR': elGrCheck, + 'en-IE': enIeCheck, + 'en-US': enUsCheck, + 'es-ES': esEsCheck, + 'et-EE': etEeCheck, + 'fi-FI': fiFiCheck, + 'fr-BE': frBeCheck, + 'fr-FR': frFrCheck, + 'fr-LU': frLuCheck, + 'hr-HR': hrHrCheck, + 'hu-HU': huHuCheck, + 'it-IT': itItCheck, + 'lv-LV': lvLvCheck, + 'mt-MT': mtMtCheck, + 'nl-NL': nlNlCheck, + 'pl-PL': plPlCheck, + 'pt-BR': ptBrCheck, + 'pt-PT': ptPtCheck, + 'ro-RO': roRoCheck, + 'sk-SK': skSkCheck, + 'sl-SI': slSiCheck, + 'sv-SE': svSeCheck +}; // taxIdCheck locale aliases + +taxIdCheck['lb-LU'] = taxIdCheck['fr-LU']; +taxIdCheck['lt-LT'] = taxIdCheck['et-EE']; +taxIdCheck['nl-BE'] = taxIdCheck['fr-BE']; // Regexes for locales where characters should be omitted before checking format + +var allsymbols = /[-\\\/!@#$%\^&\*\(\)\+\=\[\]]+/g; +var sanitizeRegexes = { + 'de-AT': allsymbols, + 'de-DE': /[\/\\]/g, + 'fr-BE': allsymbols +}; // sanitizeRegexes locale aliases + +sanitizeRegexes['nl-BE'] = sanitizeRegexes['fr-BE']; +/* + * Validator function + * Return true if the passed string is a valid tax identification number + * for the specified locale. + * Throw an error exception if the locale is not supported. + */ + +export default function isTaxID(str) { + var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; + assertString(str); // Copy TIN to avoid replacement if sanitized + + var strcopy = str.slice(0); + + if (locale in taxIdFormat) { + if (locale in sanitizeRegexes) { + strcopy = strcopy.replace(sanitizeRegexes[locale], ''); + } + + if (!taxIdFormat[locale].test(strcopy)) { + return false; + } + + if (locale in taxIdCheck) { + return taxIdCheck[locale](strcopy); + } // Fallthrough; not all locales have algorithmic checks + + + return true; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isURL.js b/node_modules/validator/es/lib/isURL.js new file mode 100644 index 0000000..e73d25d --- /dev/null +++ b/node_modules/validator/es/lib/isURL.js @@ -0,0 +1,193 @@ +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +import assertString from './util/assertString'; +import isFQDN from './isFQDN'; +import isIP from './isIP'; +import merge from './util/merge'; +/* +options for isURL method + +require_protocol - if set as true isURL will return false if protocol is not present in the URL +require_valid_protocol - isURL will check if the URL's protocol is present in the protocols option +protocols - valid protocols can be modified with this option +require_host - if set as false isURL will not check if host is present in the URL +require_port - if set as true isURL will check if port is present in the URL +allow_protocol_relative_urls - if set as true protocol relative URLs will be allowed +validate_length - if set as false isURL will skip string length validation (IE maximum is 2083) + +*/ + +var default_url_options = { + protocols: ['http', 'https', 'ftp'], + require_tld: true, + require_protocol: false, + require_host: true, + require_port: false, + require_valid_protocol: true, + allow_underscores: false, + allow_trailing_dot: false, + allow_protocol_relative_urls: false, + allow_fragments: true, + allow_query_components: true, + validate_length: true +}; +var wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/; + +function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +} + +function checkHost(host, matches) { + for (var i = 0; i < matches.length; i++) { + var match = matches[i]; + + if (host === match || isRegExp(match) && match.test(host)) { + return true; + } + } + + return false; +} + +export default function isURL(url, options) { + assertString(url); + + if (!url || /[\s<>]/.test(url)) { + return false; + } + + if (url.indexOf('mailto:') === 0) { + return false; + } + + options = merge(options, default_url_options); + + if (options.validate_length && url.length >= 2083) { + return false; + } + + if (!options.allow_fragments && url.includes('#')) { + return false; + } + + if (!options.allow_query_components && (url.includes('?') || url.includes('&'))) { + return false; + } + + var protocol, auth, host, hostname, port, port_str, split, ipv6; + split = url.split('#'); + url = split.shift(); + split = url.split('?'); + url = split.shift(); + split = url.split('://'); + + if (split.length > 1) { + protocol = split.shift().toLowerCase(); + + if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) { + return false; + } + } else if (options.require_protocol) { + return false; + } else if (url.substr(0, 2) === '//') { + if (!options.allow_protocol_relative_urls) { + return false; + } + + split[0] = url.substr(2); + } + + url = split.join('://'); + + if (url === '') { + return false; + } + + split = url.split('/'); + url = split.shift(); + + if (url === '' && !options.require_host) { + return true; + } + + split = url.split('@'); + + if (split.length > 1) { + if (options.disallow_auth) { + return false; + } + + if (split[0] === '') { + return false; + } + + auth = split.shift(); + + if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) { + return false; + } + + var _auth$split = auth.split(':'), + _auth$split2 = _slicedToArray(_auth$split, 2), + user = _auth$split2[0], + password = _auth$split2[1]; + + if (user === '' && password === '') { + return false; + } + } + + hostname = split.join('@'); + port_str = null; + ipv6 = null; + var ipv6_match = hostname.match(wrapped_ipv6); + + if (ipv6_match) { + host = ''; + ipv6 = ipv6_match[1]; + port_str = ipv6_match[2] || null; + } else { + split = hostname.split(':'); + host = split.shift(); + + if (split.length) { + port_str = split.join(':'); + } + } + + if (port_str !== null && port_str.length > 0) { + port = parseInt(port_str, 10); + + if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) { + return false; + } + } else if (options.require_port) { + return false; + } + + if (options.host_whitelist) { + return checkHost(host, options.host_whitelist); + } + + if (!isIP(host) && !isFQDN(host, options) && (!ipv6 || !isIP(ipv6, 6))) { + return false; + } + + host = host || ipv6; + + if (options.host_blacklist && checkHost(host, options.host_blacklist)) { + return false; + } + + return true; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isUUID.js b/node_modules/validator/es/lib/isUUID.js new file mode 100644 index 0000000..33ea146 --- /dev/null +++ b/node_modules/validator/es/lib/isUUID.js @@ -0,0 +1,14 @@ +import assertString from './util/assertString'; +var uuid = { + 1: /^[0-9A-F]{8}-[0-9A-F]{4}-1[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + 2: /^[0-9A-F]{8}-[0-9A-F]{4}-2[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + 3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + 4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, + 5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, + all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i +}; +export default function isUUID(str, version) { + assertString(str); + var pattern = uuid[![undefined, null].includes(version) ? version : 'all']; + return !!pattern && pattern.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isUppercase.js b/node_modules/validator/es/lib/isUppercase.js new file mode 100644 index 0000000..fca8790 --- /dev/null +++ b/node_modules/validator/es/lib/isUppercase.js @@ -0,0 +1,5 @@ +import assertString from './util/assertString'; +export default function isUppercase(str) { + assertString(str); + return str === str.toUpperCase(); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isVAT.js b/node_modules/validator/es/lib/isVAT.js new file mode 100644 index 0000000..a211274 --- /dev/null +++ b/node_modules/validator/es/lib/isVAT.js @@ -0,0 +1,16 @@ +import assertString from './util/assertString'; +export var vatMatchers = { + GB: /^GB((\d{3} \d{4} ([0-8][0-9]|9[0-6]))|(\d{9} \d{3})|(((GD[0-4])|(HA[5-9]))[0-9]{2}))$/, + IT: /^(IT)?[0-9]{11}$/, + NL: /^(NL)?[0-9]{9}B[0-9]{2}$/ +}; +export default function isVAT(str, countryCode) { + assertString(str); + assertString(countryCode); + + if (countryCode in vatMatchers) { + return vatMatchers[countryCode].test(str); + } + + throw new Error("Invalid country code: '".concat(countryCode, "'")); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isVariableWidth.js b/node_modules/validator/es/lib/isVariableWidth.js new file mode 100644 index 0000000..890119e --- /dev/null +++ b/node_modules/validator/es/lib/isVariableWidth.js @@ -0,0 +1,7 @@ +import assertString from './util/assertString'; +import { fullWidth } from './isFullWidth'; +import { halfWidth } from './isHalfWidth'; +export default function isVariableWidth(str) { + assertString(str); + return fullWidth.test(str) && halfWidth.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/isWhitelisted.js b/node_modules/validator/es/lib/isWhitelisted.js new file mode 100644 index 0000000..2cbb95c --- /dev/null +++ b/node_modules/validator/es/lib/isWhitelisted.js @@ -0,0 +1,12 @@ +import assertString from './util/assertString'; +export default function isWhitelisted(str, chars) { + assertString(str); + + for (var i = str.length - 1; i >= 0; i--) { + if (chars.indexOf(str[i]) === -1) { + return false; + } + } + + return true; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/ltrim.js b/node_modules/validator/es/lib/ltrim.js new file mode 100644 index 0000000..0ca3abb --- /dev/null +++ b/node_modules/validator/es/lib/ltrim.js @@ -0,0 +1,7 @@ +import assertString from './util/assertString'; +export default function ltrim(str, chars) { + assertString(str); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping + + var pattern = chars ? new RegExp("^[".concat(chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), "]+"), 'g') : /^\s+/g; + return str.replace(pattern, ''); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/matches.js b/node_modules/validator/es/lib/matches.js new file mode 100644 index 0000000..7840b1c --- /dev/null +++ b/node_modules/validator/es/lib/matches.js @@ -0,0 +1,10 @@ +import assertString from './util/assertString'; +export default function matches(str, pattern, modifiers) { + assertString(str); + + if (Object.prototype.toString.call(pattern) !== '[object RegExp]') { + pattern = new RegExp(pattern, modifiers); + } + + return pattern.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/normalizeEmail.js b/node_modules/validator/es/lib/normalizeEmail.js new file mode 100644 index 0000000..3563982 --- /dev/null +++ b/node_modules/validator/es/lib/normalizeEmail.js @@ -0,0 +1,138 @@ +import merge from './util/merge'; +var default_normalize_email_options = { + // The following options apply to all email addresses + // Lowercases the local part of the email address. + // Please note this may violate RFC 5321 as per http://stackoverflow.com/a/9808332/192024). + // The domain is always lowercased, as per RFC 1035 + all_lowercase: true, + // The following conversions are specific to GMail + // Lowercases the local part of the GMail address (known to be case-insensitive) + gmail_lowercase: true, + // Removes dots from the local part of the email address, as that's ignored by GMail + gmail_remove_dots: true, + // Removes the subaddress (e.g. "+foo") from the email address + gmail_remove_subaddress: true, + // Conversts the googlemail.com domain to gmail.com + gmail_convert_googlemaildotcom: true, + // The following conversions are specific to Outlook.com / Windows Live / Hotmail + // Lowercases the local part of the Outlook.com address (known to be case-insensitive) + outlookdotcom_lowercase: true, + // Removes the subaddress (e.g. "+foo") from the email address + outlookdotcom_remove_subaddress: true, + // The following conversions are specific to Yahoo + // Lowercases the local part of the Yahoo address (known to be case-insensitive) + yahoo_lowercase: true, + // Removes the subaddress (e.g. "-foo") from the email address + yahoo_remove_subaddress: true, + // The following conversions are specific to Yandex + // Lowercases the local part of the Yandex address (known to be case-insensitive) + yandex_lowercase: true, + // The following conversions are specific to iCloud + // Lowercases the local part of the iCloud address (known to be case-insensitive) + icloud_lowercase: true, + // Removes the subaddress (e.g. "+foo") from the email address + icloud_remove_subaddress: true +}; // List of domains used by iCloud + +var icloud_domains = ['icloud.com', 'me.com']; // List of domains used by Outlook.com and its predecessors +// This list is likely incomplete. +// Partial reference: +// https://blogs.office.com/2013/04/17/outlook-com-gets-two-step-verification-sign-in-by-alias-and-new-international-domains/ + +var outlookdotcom_domains = ['hotmail.at', 'hotmail.be', 'hotmail.ca', 'hotmail.cl', 'hotmail.co.il', 'hotmail.co.nz', 'hotmail.co.th', 'hotmail.co.uk', 'hotmail.com', 'hotmail.com.ar', 'hotmail.com.au', 'hotmail.com.br', 'hotmail.com.gr', 'hotmail.com.mx', 'hotmail.com.pe', 'hotmail.com.tr', 'hotmail.com.vn', 'hotmail.cz', 'hotmail.de', 'hotmail.dk', 'hotmail.es', 'hotmail.fr', 'hotmail.hu', 'hotmail.id', 'hotmail.ie', 'hotmail.in', 'hotmail.it', 'hotmail.jp', 'hotmail.kr', 'hotmail.lv', 'hotmail.my', 'hotmail.ph', 'hotmail.pt', 'hotmail.sa', 'hotmail.sg', 'hotmail.sk', 'live.be', 'live.co.uk', 'live.com', 'live.com.ar', 'live.com.mx', 'live.de', 'live.es', 'live.eu', 'live.fr', 'live.it', 'live.nl', 'msn.com', 'outlook.at', 'outlook.be', 'outlook.cl', 'outlook.co.il', 'outlook.co.nz', 'outlook.co.th', 'outlook.com', 'outlook.com.ar', 'outlook.com.au', 'outlook.com.br', 'outlook.com.gr', 'outlook.com.pe', 'outlook.com.tr', 'outlook.com.vn', 'outlook.cz', 'outlook.de', 'outlook.dk', 'outlook.es', 'outlook.fr', 'outlook.hu', 'outlook.id', 'outlook.ie', 'outlook.in', 'outlook.it', 'outlook.jp', 'outlook.kr', 'outlook.lv', 'outlook.my', 'outlook.ph', 'outlook.pt', 'outlook.sa', 'outlook.sg', 'outlook.sk', 'passport.com']; // List of domains used by Yahoo Mail +// This list is likely incomplete + +var yahoo_domains = ['rocketmail.com', 'yahoo.ca', 'yahoo.co.uk', 'yahoo.com', 'yahoo.de', 'yahoo.fr', 'yahoo.in', 'yahoo.it', 'ymail.com']; // List of domains used by yandex.ru + +var yandex_domains = ['yandex.ru', 'yandex.ua', 'yandex.kz', 'yandex.com', 'yandex.by', 'ya.ru']; // replace single dots, but not multiple consecutive dots + +function dotsReplacer(match) { + if (match.length > 1) { + return match; + } + + return ''; +} + +export default function normalizeEmail(email, options) { + options = merge(options, default_normalize_email_options); + var raw_parts = email.split('@'); + var domain = raw_parts.pop(); + var user = raw_parts.join('@'); + var parts = [user, domain]; // The domain is always lowercased, as it's case-insensitive per RFC 1035 + + parts[1] = parts[1].toLowerCase(); + + if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') { + // Address is GMail + if (options.gmail_remove_subaddress) { + parts[0] = parts[0].split('+')[0]; + } + + if (options.gmail_remove_dots) { + // this does not replace consecutive dots like example..email@gmail.com + parts[0] = parts[0].replace(/\.+/g, dotsReplacer); + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.gmail_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + + parts[1] = options.gmail_convert_googlemaildotcom ? 'gmail.com' : parts[1]; + } else if (icloud_domains.indexOf(parts[1]) >= 0) { + // Address is iCloud + if (options.icloud_remove_subaddress) { + parts[0] = parts[0].split('+')[0]; + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.icloud_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + } else if (outlookdotcom_domains.indexOf(parts[1]) >= 0) { + // Address is Outlook.com + if (options.outlookdotcom_remove_subaddress) { + parts[0] = parts[0].split('+')[0]; + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.outlookdotcom_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + } else if (yahoo_domains.indexOf(parts[1]) >= 0) { + // Address is Yahoo + if (options.yahoo_remove_subaddress) { + var components = parts[0].split('-'); + parts[0] = components.length > 1 ? components.slice(0, -1).join('-') : components[0]; + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.yahoo_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + } else if (yandex_domains.indexOf(parts[1]) >= 0) { + if (options.all_lowercase || options.yandex_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + + parts[1] = 'yandex.ru'; // all yandex domains are equal, 1st preferred + } else if (options.all_lowercase) { + // Any other address + parts[0] = parts[0].toLowerCase(); + } + + return parts.join('@'); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/rtrim.js b/node_modules/validator/es/lib/rtrim.js new file mode 100644 index 0000000..a02f5c4 --- /dev/null +++ b/node_modules/validator/es/lib/rtrim.js @@ -0,0 +1,19 @@ +import assertString from './util/assertString'; +export default function rtrim(str, chars) { + assertString(str); + + if (chars) { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping + var pattern = new RegExp("[".concat(chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), "]+$"), 'g'); + return str.replace(pattern, ''); + } // Use a faster and more safe than regex trim method https://blog.stevenlevithan.com/archives/faster-trim-javascript + + + var strIndex = str.length - 1; + + while (/\s/.test(str.charAt(strIndex))) { + strIndex -= 1; + } + + return str.slice(0, strIndex + 1); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/stripLow.js b/node_modules/validator/es/lib/stripLow.js new file mode 100644 index 0000000..c798425 --- /dev/null +++ b/node_modules/validator/es/lib/stripLow.js @@ -0,0 +1,7 @@ +import assertString from './util/assertString'; +import blacklist from './blacklist'; +export default function stripLow(str, keep_new_lines) { + assertString(str); + var chars = keep_new_lines ? '\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F' : '\\x00-\\x1F\\x7F'; + return blacklist(str, chars); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/toBoolean.js b/node_modules/validator/es/lib/toBoolean.js new file mode 100644 index 0000000..25e1eac --- /dev/null +++ b/node_modules/validator/es/lib/toBoolean.js @@ -0,0 +1,10 @@ +import assertString from './util/assertString'; +export default function toBoolean(str, strict) { + assertString(str); + + if (strict) { + return str === '1' || /^true$/i.test(str); + } + + return str !== '0' && !/^false$/i.test(str) && str !== ''; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/toDate.js b/node_modules/validator/es/lib/toDate.js new file mode 100644 index 0000000..62422a3 --- /dev/null +++ b/node_modules/validator/es/lib/toDate.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; +export default function toDate(date) { + assertString(date); + date = Date.parse(date); + return !isNaN(date) ? new Date(date) : null; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/toFloat.js b/node_modules/validator/es/lib/toFloat.js new file mode 100644 index 0000000..f21163d --- /dev/null +++ b/node_modules/validator/es/lib/toFloat.js @@ -0,0 +1,5 @@ +import isFloat from './isFloat'; +export default function toFloat(str) { + if (!isFloat(str)) return NaN; + return parseFloat(str); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/toInt.js b/node_modules/validator/es/lib/toInt.js new file mode 100644 index 0000000..22d566e --- /dev/null +++ b/node_modules/validator/es/lib/toInt.js @@ -0,0 +1,5 @@ +import assertString from './util/assertString'; +export default function toInt(str, radix) { + assertString(str); + return parseInt(str, radix || 10); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/trim.js b/node_modules/validator/es/lib/trim.js new file mode 100644 index 0000000..b9b8fa0 --- /dev/null +++ b/node_modules/validator/es/lib/trim.js @@ -0,0 +1,5 @@ +import rtrim from './rtrim'; +import ltrim from './ltrim'; +export default function trim(str, chars) { + return rtrim(ltrim(str, chars), chars); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/unescape.js b/node_modules/validator/es/lib/unescape.js new file mode 100644 index 0000000..8ff45f5 --- /dev/null +++ b/node_modules/validator/es/lib/unescape.js @@ -0,0 +1,7 @@ +import assertString from './util/assertString'; +export default function unescape(str) { + assertString(str); + return str.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(///g, '/').replace(/\/g, '\\').replace(/`/g, '`').replace(/&/g, '&'); // & replacement has to be the last one to prevent + // bugs with intermediate strings containing escape sequences + // See: https://github.com/validatorjs/validator.js/issues/1827 +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/util/algorithms.js b/node_modules/validator/es/lib/util/algorithms.js new file mode 100644 index 0000000..eca8d6d --- /dev/null +++ b/node_modules/validator/es/lib/util/algorithms.js @@ -0,0 +1,88 @@ +/** + * Algorithmic validation functions + * May be used as is or implemented in the workflow of other validators. + */ + +/* + * ISO 7064 validation function + * Called with a string of numbers (incl. check digit) + * to validate according to ISO 7064 (MOD 11, 10). + */ +export function iso7064Check(str) { + var checkvalue = 10; + + for (var i = 0; i < str.length - 1; i++) { + checkvalue = (parseInt(str[i], 10) + checkvalue) % 10 === 0 ? 10 * 2 % 11 : (parseInt(str[i], 10) + checkvalue) % 10 * 2 % 11; + } + + checkvalue = checkvalue === 1 ? 0 : 11 - checkvalue; + return checkvalue === parseInt(str[10], 10); +} +/* + * Luhn (mod 10) validation function + * Called with a string of numbers (incl. check digit) + * to validate according to the Luhn algorithm. + */ + +export function luhnCheck(str) { + var checksum = 0; + var second = false; + + for (var i = str.length - 1; i >= 0; i--) { + if (second) { + var product = parseInt(str[i], 10) * 2; + + if (product > 9) { + // sum digits of product and add to checksum + checksum += product.toString().split('').map(function (a) { + return parseInt(a, 10); + }).reduce(function (a, b) { + return a + b; + }, 0); + } else { + checksum += product; + } + } else { + checksum += parseInt(str[i], 10); + } + + second = !second; + } + + return checksum % 10 === 0; +} +/* + * Reverse TIN multiplication and summation helper function + * Called with an array of single-digit integers and a base multiplier + * to calculate the sum of the digits multiplied in reverse. + * Normally used in variations of MOD 11 algorithmic checks. + */ + +export function reverseMultiplyAndSum(digits, base) { + var total = 0; + + for (var i = 0; i < digits.length; i++) { + total += digits[i] * (base - i); + } + + return total; +} +/* + * Verhoeff validation helper function + * Called with a string of numbers + * to validate according to the Verhoeff algorithm. + */ + +export function verhoeffCheck(str) { + var d_table = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]; + var p_table = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]; // Copy (to prevent replacement) and reverse + + var str_copy = str.split('').reverse().join(''); + var checksum = 0; + + for (var i = 0; i < str_copy.length; i++) { + checksum = d_table[checksum][p_table[i % 8][parseInt(str_copy[i], 10)]]; + } + + return checksum === 0; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/util/assertString.js b/node_modules/validator/es/lib/util/assertString.js new file mode 100644 index 0000000..f7eced5 --- /dev/null +++ b/node_modules/validator/es/lib/util/assertString.js @@ -0,0 +1,12 @@ +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +export default function assertString(input) { + var isString = typeof input === 'string' || input instanceof String; + + if (!isString) { + var invalidType = _typeof(input); + + if (input === null) invalidType = 'null';else if (invalidType === 'object') invalidType = input.constructor.name; + throw new TypeError("Expected a string but received a ".concat(invalidType)); + } +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/util/includes.js b/node_modules/validator/es/lib/util/includes.js new file mode 100644 index 0000000..b01c692 --- /dev/null +++ b/node_modules/validator/es/lib/util/includes.js @@ -0,0 +1,7 @@ +var includes = function includes(arr, val) { + return arr.some(function (arrVal) { + return val === arrVal; + }); +}; + +export default includes; \ No newline at end of file diff --git a/node_modules/validator/es/lib/util/merge.js b/node_modules/validator/es/lib/util/merge.js new file mode 100644 index 0000000..0d1f699 --- /dev/null +++ b/node_modules/validator/es/lib/util/merge.js @@ -0,0 +1,12 @@ +export default function merge() { + var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var defaults = arguments.length > 1 ? arguments[1] : undefined; + + for (var key in defaults) { + if (typeof obj[key] === 'undefined') { + obj[key] = defaults[key]; + } + } + + return obj; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/util/multilineRegex.js b/node_modules/validator/es/lib/util/multilineRegex.js new file mode 100644 index 0000000..fed25a3 --- /dev/null +++ b/node_modules/validator/es/lib/util/multilineRegex.js @@ -0,0 +1,12 @@ +/** + * Build RegExp object from an array + * of multiple/multi-line regexp parts + * + * @param {string[]} parts + * @param {string} flags + * @return {object} - RegExp object + */ +export default function multilineRegexp(parts, flags) { + var regexpAsStringLiteral = parts.join(''); + return new RegExp(regexpAsStringLiteral, flags); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/util/toString.js b/node_modules/validator/es/lib/util/toString.js new file mode 100644 index 0000000..f483fa4 --- /dev/null +++ b/node_modules/validator/es/lib/util/toString.js @@ -0,0 +1,15 @@ +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +export default function toString(input) { + if (_typeof(input) === 'object' && input !== null) { + if (typeof input.toString === 'function') { + input = input.toString(); + } else { + input = '[object Object]'; + } + } else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) { + input = ''; + } + + return String(input); +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/util/typeOf.js b/node_modules/validator/es/lib/util/typeOf.js new file mode 100644 index 0000000..b2ce41a --- /dev/null +++ b/node_modules/validator/es/lib/util/typeOf.js @@ -0,0 +1,10 @@ +/** + * Better way to handle type checking + * null, {}, array and date are objects, which confuses + */ +export default function typeOf(input) { + var rawObject = Object.prototype.toString.call(input).toLowerCase(); + var typeOfRegex = /\[object (.*)]/g; + var type = typeOfRegex.exec(rawObject)[1]; + return type; +} \ No newline at end of file diff --git a/node_modules/validator/es/lib/whitelist.js b/node_modules/validator/es/lib/whitelist.js new file mode 100644 index 0000000..244881b --- /dev/null +++ b/node_modules/validator/es/lib/whitelist.js @@ -0,0 +1,5 @@ +import assertString from './util/assertString'; +export default function whitelist(str, chars) { + assertString(str); + return str.replace(new RegExp("[^".concat(chars, "]+"), 'g'), ''); +} \ No newline at end of file diff --git a/node_modules/validator/index.js b/node_modules/validator/index.js new file mode 100644 index 0000000..36e33a0 --- /dev/null +++ b/node_modules/validator/index.js @@ -0,0 +1,309 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _toDate = _interopRequireDefault(require("./lib/toDate")); + +var _toFloat = _interopRequireDefault(require("./lib/toFloat")); + +var _toInt = _interopRequireDefault(require("./lib/toInt")); + +var _toBoolean = _interopRequireDefault(require("./lib/toBoolean")); + +var _equals = _interopRequireDefault(require("./lib/equals")); + +var _contains = _interopRequireDefault(require("./lib/contains")); + +var _matches = _interopRequireDefault(require("./lib/matches")); + +var _isEmail = _interopRequireDefault(require("./lib/isEmail")); + +var _isURL = _interopRequireDefault(require("./lib/isURL")); + +var _isMACAddress = _interopRequireDefault(require("./lib/isMACAddress")); + +var _isIP = _interopRequireDefault(require("./lib/isIP")); + +var _isIPRange = _interopRequireDefault(require("./lib/isIPRange")); + +var _isFQDN = _interopRequireDefault(require("./lib/isFQDN")); + +var _isDate = _interopRequireDefault(require("./lib/isDate")); + +var _isBoolean = _interopRequireDefault(require("./lib/isBoolean")); + +var _isLocale = _interopRequireDefault(require("./lib/isLocale")); + +var _isAlpha = _interopRequireWildcard(require("./lib/isAlpha")); + +var _isAlphanumeric = _interopRequireWildcard(require("./lib/isAlphanumeric")); + +var _isNumeric = _interopRequireDefault(require("./lib/isNumeric")); + +var _isPassportNumber = _interopRequireDefault(require("./lib/isPassportNumber")); + +var _isPort = _interopRequireDefault(require("./lib/isPort")); + +var _isLowercase = _interopRequireDefault(require("./lib/isLowercase")); + +var _isUppercase = _interopRequireDefault(require("./lib/isUppercase")); + +var _isIMEI = _interopRequireDefault(require("./lib/isIMEI")); + +var _isAscii = _interopRequireDefault(require("./lib/isAscii")); + +var _isFullWidth = _interopRequireDefault(require("./lib/isFullWidth")); + +var _isHalfWidth = _interopRequireDefault(require("./lib/isHalfWidth")); + +var _isVariableWidth = _interopRequireDefault(require("./lib/isVariableWidth")); + +var _isMultibyte = _interopRequireDefault(require("./lib/isMultibyte")); + +var _isSemVer = _interopRequireDefault(require("./lib/isSemVer")); + +var _isSurrogatePair = _interopRequireDefault(require("./lib/isSurrogatePair")); + +var _isInt = _interopRequireDefault(require("./lib/isInt")); + +var _isFloat = _interopRequireWildcard(require("./lib/isFloat")); + +var _isDecimal = _interopRequireDefault(require("./lib/isDecimal")); + +var _isHexadecimal = _interopRequireDefault(require("./lib/isHexadecimal")); + +var _isOctal = _interopRequireDefault(require("./lib/isOctal")); + +var _isDivisibleBy = _interopRequireDefault(require("./lib/isDivisibleBy")); + +var _isHexColor = _interopRequireDefault(require("./lib/isHexColor")); + +var _isRgbColor = _interopRequireDefault(require("./lib/isRgbColor")); + +var _isHSL = _interopRequireDefault(require("./lib/isHSL")); + +var _isISRC = _interopRequireDefault(require("./lib/isISRC")); + +var _isIBAN = _interopRequireWildcard(require("./lib/isIBAN")); + +var _isBIC = _interopRequireDefault(require("./lib/isBIC")); + +var _isMD = _interopRequireDefault(require("./lib/isMD5")); + +var _isHash = _interopRequireDefault(require("./lib/isHash")); + +var _isJWT = _interopRequireDefault(require("./lib/isJWT")); + +var _isJSON = _interopRequireDefault(require("./lib/isJSON")); + +var _isEmpty = _interopRequireDefault(require("./lib/isEmpty")); + +var _isLength = _interopRequireDefault(require("./lib/isLength")); + +var _isByteLength = _interopRequireDefault(require("./lib/isByteLength")); + +var _isUUID = _interopRequireDefault(require("./lib/isUUID")); + +var _isMongoId = _interopRequireDefault(require("./lib/isMongoId")); + +var _isAfter = _interopRequireDefault(require("./lib/isAfter")); + +var _isBefore = _interopRequireDefault(require("./lib/isBefore")); + +var _isIn = _interopRequireDefault(require("./lib/isIn")); + +var _isCreditCard = _interopRequireDefault(require("./lib/isCreditCard")); + +var _isIdentityCard = _interopRequireDefault(require("./lib/isIdentityCard")); + +var _isEAN = _interopRequireDefault(require("./lib/isEAN")); + +var _isISIN = _interopRequireDefault(require("./lib/isISIN")); + +var _isISBN = _interopRequireDefault(require("./lib/isISBN")); + +var _isISSN = _interopRequireDefault(require("./lib/isISSN")); + +var _isTaxID = _interopRequireDefault(require("./lib/isTaxID")); + +var _isMobilePhone = _interopRequireWildcard(require("./lib/isMobilePhone")); + +var _isEthereumAddress = _interopRequireDefault(require("./lib/isEthereumAddress")); + +var _isCurrency = _interopRequireDefault(require("./lib/isCurrency")); + +var _isBtcAddress = _interopRequireDefault(require("./lib/isBtcAddress")); + +var _isISO = _interopRequireDefault(require("./lib/isISO8601")); + +var _isRFC = _interopRequireDefault(require("./lib/isRFC3339")); + +var _isISO31661Alpha = _interopRequireDefault(require("./lib/isISO31661Alpha2")); + +var _isISO31661Alpha2 = _interopRequireDefault(require("./lib/isISO31661Alpha3")); + +var _isISO2 = _interopRequireDefault(require("./lib/isISO4217")); + +var _isBase = _interopRequireDefault(require("./lib/isBase32")); + +var _isBase2 = _interopRequireDefault(require("./lib/isBase58")); + +var _isBase3 = _interopRequireDefault(require("./lib/isBase64")); + +var _isDataURI = _interopRequireDefault(require("./lib/isDataURI")); + +var _isMagnetURI = _interopRequireDefault(require("./lib/isMagnetURI")); + +var _isMimeType = _interopRequireDefault(require("./lib/isMimeType")); + +var _isLatLong = _interopRequireDefault(require("./lib/isLatLong")); + +var _isPostalCode = _interopRequireWildcard(require("./lib/isPostalCode")); + +var _ltrim = _interopRequireDefault(require("./lib/ltrim")); + +var _rtrim = _interopRequireDefault(require("./lib/rtrim")); + +var _trim = _interopRequireDefault(require("./lib/trim")); + +var _escape = _interopRequireDefault(require("./lib/escape")); + +var _unescape = _interopRequireDefault(require("./lib/unescape")); + +var _stripLow = _interopRequireDefault(require("./lib/stripLow")); + +var _whitelist = _interopRequireDefault(require("./lib/whitelist")); + +var _blacklist = _interopRequireDefault(require("./lib/blacklist")); + +var _isWhitelisted = _interopRequireDefault(require("./lib/isWhitelisted")); + +var _normalizeEmail = _interopRequireDefault(require("./lib/normalizeEmail")); + +var _isSlug = _interopRequireDefault(require("./lib/isSlug")); + +var _isLicensePlate = _interopRequireDefault(require("./lib/isLicensePlate")); + +var _isStrongPassword = _interopRequireDefault(require("./lib/isStrongPassword")); + +var _isVAT = _interopRequireDefault(require("./lib/isVAT")); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var version = '13.7.0'; +var validator = { + version: version, + toDate: _toDate.default, + toFloat: _toFloat.default, + toInt: _toInt.default, + toBoolean: _toBoolean.default, + equals: _equals.default, + contains: _contains.default, + matches: _matches.default, + isEmail: _isEmail.default, + isURL: _isURL.default, + isMACAddress: _isMACAddress.default, + isIP: _isIP.default, + isIPRange: _isIPRange.default, + isFQDN: _isFQDN.default, + isBoolean: _isBoolean.default, + isIBAN: _isIBAN.default, + isBIC: _isBIC.default, + isAlpha: _isAlpha.default, + isAlphaLocales: _isAlpha.locales, + isAlphanumeric: _isAlphanumeric.default, + isAlphanumericLocales: _isAlphanumeric.locales, + isNumeric: _isNumeric.default, + isPassportNumber: _isPassportNumber.default, + isPort: _isPort.default, + isLowercase: _isLowercase.default, + isUppercase: _isUppercase.default, + isAscii: _isAscii.default, + isFullWidth: _isFullWidth.default, + isHalfWidth: _isHalfWidth.default, + isVariableWidth: _isVariableWidth.default, + isMultibyte: _isMultibyte.default, + isSemVer: _isSemVer.default, + isSurrogatePair: _isSurrogatePair.default, + isInt: _isInt.default, + isIMEI: _isIMEI.default, + isFloat: _isFloat.default, + isFloatLocales: _isFloat.locales, + isDecimal: _isDecimal.default, + isHexadecimal: _isHexadecimal.default, + isOctal: _isOctal.default, + isDivisibleBy: _isDivisibleBy.default, + isHexColor: _isHexColor.default, + isRgbColor: _isRgbColor.default, + isHSL: _isHSL.default, + isISRC: _isISRC.default, + isMD5: _isMD.default, + isHash: _isHash.default, + isJWT: _isJWT.default, + isJSON: _isJSON.default, + isEmpty: _isEmpty.default, + isLength: _isLength.default, + isLocale: _isLocale.default, + isByteLength: _isByteLength.default, + isUUID: _isUUID.default, + isMongoId: _isMongoId.default, + isAfter: _isAfter.default, + isBefore: _isBefore.default, + isIn: _isIn.default, + isCreditCard: _isCreditCard.default, + isIdentityCard: _isIdentityCard.default, + isEAN: _isEAN.default, + isISIN: _isISIN.default, + isISBN: _isISBN.default, + isISSN: _isISSN.default, + isMobilePhone: _isMobilePhone.default, + isMobilePhoneLocales: _isMobilePhone.locales, + isPostalCode: _isPostalCode.default, + isPostalCodeLocales: _isPostalCode.locales, + isEthereumAddress: _isEthereumAddress.default, + isCurrency: _isCurrency.default, + isBtcAddress: _isBtcAddress.default, + isISO8601: _isISO.default, + isRFC3339: _isRFC.default, + isISO31661Alpha2: _isISO31661Alpha.default, + isISO31661Alpha3: _isISO31661Alpha2.default, + isISO4217: _isISO2.default, + isBase32: _isBase.default, + isBase58: _isBase2.default, + isBase64: _isBase3.default, + isDataURI: _isDataURI.default, + isMagnetURI: _isMagnetURI.default, + isMimeType: _isMimeType.default, + isLatLong: _isLatLong.default, + ltrim: _ltrim.default, + rtrim: _rtrim.default, + trim: _trim.default, + escape: _escape.default, + unescape: _unescape.default, + stripLow: _stripLow.default, + whitelist: _whitelist.default, + blacklist: _blacklist.default, + isWhitelisted: _isWhitelisted.default, + normalizeEmail: _normalizeEmail.default, + toString: toString, + isSlug: _isSlug.default, + isStrongPassword: _isStrongPassword.default, + isTaxID: _isTaxID.default, + isDate: _isDate.default, + isLicensePlate: _isLicensePlate.default, + isVAT: _isVAT.default, + ibanLocales: _isIBAN.locales +}; +var _default = validator; +exports.default = _default; +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/alpha.js b/node_modules/validator/lib/alpha.js new file mode 100644 index 0000000..7dacc73 --- /dev/null +++ b/node_modules/validator/lib/alpha.js @@ -0,0 +1,137 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.commaDecimal = exports.dotDecimal = exports.farsiLocales = exports.arabicLocales = exports.englishLocales = exports.decimal = exports.alphanumeric = exports.alpha = void 0; +var alpha = { + 'en-US': /^[A-Z]+$/i, + 'az-AZ': /^[A-VXYZÇƏĞİıÖŞÜ]+$/i, + 'bg-BG': /^[А-Я]+$/i, + 'cs-CZ': /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i, + 'da-DK': /^[A-ZÆØÅ]+$/i, + 'de-DE': /^[A-ZÄÖÜß]+$/i, + 'el-GR': /^[Α-ώ]+$/i, + 'es-ES': /^[A-ZÁÉÍÑÓÚÜ]+$/i, + 'fa-IR': /^[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهی]+$/i, + 'fi-FI': /^[A-ZÅÄÖ]+$/i, + 'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i, + 'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i, + 'nb-NO': /^[A-ZÆØÅ]+$/i, + 'nl-NL': /^[A-ZÁÉËÏÓÖÜÚ]+$/i, + 'nn-NO': /^[A-ZÆØÅ]+$/i, + 'hu-HU': /^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i, + 'pl-PL': /^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i, + 'pt-PT': /^[A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i, + 'ru-RU': /^[А-ЯЁ]+$/i, + 'sl-SI': /^[A-ZČĆĐŠŽ]+$/i, + 'sk-SK': /^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i, + 'sr-RS@latin': /^[A-ZČĆŽŠĐ]+$/i, + 'sr-RS': /^[А-ЯЂЈЉЊЋЏ]+$/i, + 'sv-SE': /^[A-ZÅÄÖ]+$/i, + 'th-TH': /^[ก-๐\s]+$/i, + 'tr-TR': /^[A-ZÇĞİıÖŞÜ]+$/i, + 'uk-UA': /^[А-ЩЬЮЯЄIЇҐі]+$/i, + 'vi-VN': /^[A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$/i, + 'ku-IQ': /^[ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i, + ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/, + he: /^[א-ת]+$/, + fa: /^['آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی']+$/i, + 'hi-IN': /^[\u0900-\u0961]+[\u0972-\u097F]*$/i +}; +exports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٤٥٦٧٨٩0-9ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i, + 'vi-VN': /^[0-9A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$/i, + ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/, + he: /^[0-9א-ת]+$/, + fa: /^['0-9آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی۱۲۳۴۵۶۷۸۹۰']+$/i, + 'hi-IN': /^[\u0900-\u0963]+[\u0966-\u097F]*$/i +}; +exports.alphanumeric = alphanumeric; +var decimal = { + 'en-US': '.', + ar: '٫' +}; +exports.decimal = decimal; +var englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM']; +exports.englishLocales = englishLocales; + +for (var locale, i = 0; i < englishLocales.length; i++) { + locale = "en-".concat(englishLocales[i]); + alpha[locale] = alpha['en-US']; + alphanumeric[locale] = alphanumeric['en-US']; + decimal[locale] = decimal['en-US']; +} // Source: http://www.localeplanet.com/java/ + + +var arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE']; +exports.arabicLocales = arabicLocales; + +for (var _locale, _i = 0; _i < arabicLocales.length; _i++) { + _locale = "ar-".concat(arabicLocales[_i]); + alpha[_locale] = alpha.ar; + alphanumeric[_locale] = alphanumeric.ar; + decimal[_locale] = decimal.ar; +} + +var farsiLocales = ['IR', 'AF']; +exports.farsiLocales = farsiLocales; + +for (var _locale2, _i2 = 0; _i2 < farsiLocales.length; _i2++) { + _locale2 = "fa-".concat(farsiLocales[_i2]); + alphanumeric[_locale2] = alphanumeric.fa; + decimal[_locale2] = decimal.ar; +} // Source: https://en.wikipedia.org/wiki/Decimal_mark + + +var dotDecimal = ['ar-EG', 'ar-LB', 'ar-LY']; +exports.dotDecimal = dotDecimal; +var commaDecimal = ['bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-ZM', 'es-ES', 'fr-CA', 'fr-FR', 'id-ID', 'it-IT', 'ku-IQ', 'hi-IN', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA', 'vi-VN']; +exports.commaDecimal = commaDecimal; + +for (var _i3 = 0; _i3 < dotDecimal.length; _i3++) { + decimal[dotDecimal[_i3]] = decimal['en-US']; +} + +for (var _i4 = 0; _i4 < commaDecimal.length; _i4++) { + decimal[commaDecimal[_i4]] = ','; +} + +alpha['fr-CA'] = alpha['fr-FR']; +alphanumeric['fr-CA'] = alphanumeric['fr-FR']; +alpha['pt-BR'] = alpha['pt-PT']; +alphanumeric['pt-BR'] = alphanumeric['pt-PT']; +decimal['pt-BR'] = decimal['pt-PT']; // see #862 + +alpha['pl-Pl'] = alpha['pl-PL']; +alphanumeric['pl-Pl'] = alphanumeric['pl-PL']; +decimal['pl-Pl'] = decimal['pl-PL']; // see #1455 + +alpha['fa-AF'] = alpha.fa; \ No newline at end of file diff --git a/node_modules/validator/lib/blacklist.js b/node_modules/validator/lib/blacklist.js new file mode 100644 index 0000000..5dd42ed --- /dev/null +++ b/node_modules/validator/lib/blacklist.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = blacklist; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function blacklist(str, chars) { + (0, _assertString.default)(str); + return str.replace(new RegExp("[".concat(chars, "]+"), 'g'), ''); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/contains.js b/node_modules/validator/lib/contains.js new file mode 100644 index 0000000..ee3843b --- /dev/null +++ b/node_modules/validator/lib/contains.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = contains; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _toString = _interopRequireDefault(require("./util/toString")); + +var _merge = _interopRequireDefault(require("./util/merge")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaulContainsOptions = { + ignoreCase: false, + minOccurrences: 1 +}; + +function contains(str, elem, options) { + (0, _assertString.default)(str); + options = (0, _merge.default)(options, defaulContainsOptions); + + if (options.ignoreCase) { + return str.toLowerCase().split((0, _toString.default)(elem).toLowerCase()).length > options.minOccurrences; + } + + return str.split((0, _toString.default)(elem)).length > options.minOccurrences; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/equals.js b/node_modules/validator/lib/equals.js new file mode 100644 index 0000000..a33c5ab --- /dev/null +++ b/node_modules/validator/lib/equals.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = equals; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function equals(str, comparison) { + (0, _assertString.default)(str); + return str === comparison; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/escape.js b/node_modules/validator/lib/escape.js new file mode 100644 index 0000000..05e4220 --- /dev/null +++ b/node_modules/validator/lib/escape.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = escape; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function escape(str) { + (0, _assertString.default)(str); + return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>').replace(/\//g, '/').replace(/\\/g, '\').replace(/`/g, '`'); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isAfter.js b/node_modules/validator/lib/isAfter.js new file mode 100644 index 0000000..1fa18ad --- /dev/null +++ b/node_modules/validator/lib/isAfter.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isAfter; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _toDate = _interopRequireDefault(require("./toDate")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isAfter(str) { + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date()); + (0, _assertString.default)(str); + var comparison = (0, _toDate.default)(date); + var original = (0, _toDate.default)(str); + return !!(original && comparison && original > comparison); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isAlpha.js b/node_modules/validator/lib/isAlpha.js new file mode 100644 index 0000000..bfb0c17 --- /dev/null +++ b/node_modules/validator/lib/isAlpha.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isAlpha; +exports.locales = void 0; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _alpha = require("./alpha"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isAlpha(_str) { + var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + (0, _assertString.default)(_str); + var str = _str; + var ignore = options.ignore; + + if (ignore) { + if (ignore instanceof RegExp) { + str = str.replace(ignore, ''); + } else if (typeof ignore === 'string') { + str = str.replace(new RegExp("[".concat(ignore.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'), "]"), 'g'), ''); // escape regex for ignore + } else { + throw new Error('ignore should be instance of a String or RegExp'); + } + } + + if (locale in _alpha.alpha) { + return _alpha.alpha[locale].test(str); + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} + +var locales = Object.keys(_alpha.alpha); +exports.locales = locales; \ No newline at end of file diff --git a/node_modules/validator/lib/isAlphanumeric.js b/node_modules/validator/lib/isAlphanumeric.js new file mode 100644 index 0000000..e4d1d44 --- /dev/null +++ b/node_modules/validator/lib/isAlphanumeric.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isAlphanumeric; +exports.locales = void 0; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _alpha = require("./alpha"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isAlphanumeric(_str) { + var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + (0, _assertString.default)(_str); + var str = _str; + var ignore = options.ignore; + + if (ignore) { + if (ignore instanceof RegExp) { + str = str.replace(ignore, ''); + } else if (typeof ignore === 'string') { + str = str.replace(new RegExp("[".concat(ignore.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'), "]"), 'g'), ''); // escape regex for ignore + } else { + throw new Error('ignore should be instance of a String or RegExp'); + } + } + + if (locale in _alpha.alphanumeric) { + return _alpha.alphanumeric[locale].test(str); + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} + +var locales = Object.keys(_alpha.alphanumeric); +exports.locales = locales; \ No newline at end of file diff --git a/node_modules/validator/lib/isAscii.js b/node_modules/validator/lib/isAscii.js new file mode 100644 index 0000000..3c62271 --- /dev/null +++ b/node_modules/validator/lib/isAscii.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isAscii; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint-disable no-control-regex */ +var ascii = /^[\x00-\x7F]+$/; +/* eslint-enable no-control-regex */ + +function isAscii(str) { + (0, _assertString.default)(str); + return ascii.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isBIC.js b/node_modules/validator/lib/isBIC.js new file mode 100644 index 0000000..a776707 --- /dev/null +++ b/node_modules/validator/lib/isBIC.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isBIC; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _isISO31661Alpha = require("./isISO31661Alpha2"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// https://en.wikipedia.org/wiki/ISO_9362 +var isBICReg = /^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$/; + +function isBIC(str) { + (0, _assertString.default)(str); // toUpperCase() should be removed when a new major version goes out that changes + // the regex to [A-Z] (per the spec). + + if (!_isISO31661Alpha.CountryCodes.has(str.slice(4, 6).toUpperCase())) { + return false; + } + + return isBICReg.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isBase32.js b/node_modules/validator/lib/isBase32.js new file mode 100644 index 0000000..293449f --- /dev/null +++ b/node_modules/validator/lib/isBase32.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isBase32; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var base32 = /^[A-Z2-7]+=*$/; + +function isBase32(str) { + (0, _assertString.default)(str); + var len = str.length; + + if (len % 8 === 0 && base32.test(str)) { + return true; + } + + return false; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isBase58.js b/node_modules/validator/lib/isBase58.js new file mode 100644 index 0000000..a98c82c --- /dev/null +++ b/node_modules/validator/lib/isBase58.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isBase58; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// Accepted chars - 123456789ABCDEFGH JKLMN PQRSTUVWXYZabcdefghijk mnopqrstuvwxyz +var base58Reg = /^[A-HJ-NP-Za-km-z1-9]*$/; + +function isBase58(str) { + (0, _assertString.default)(str); + + if (base58Reg.test(str)) { + return true; + } + + return false; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isBase64.js b/node_modules/validator/lib/isBase64.js new file mode 100644 index 0000000..6863683 --- /dev/null +++ b/node_modules/validator/lib/isBase64.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isBase64; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _merge = _interopRequireDefault(require("./util/merge")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var notBase64 = /[^A-Z0-9+\/=]/i; +var urlSafeBase64 = /^[A-Z0-9_\-]*$/i; +var defaultBase64Options = { + urlSafe: false +}; + +function isBase64(str, options) { + (0, _assertString.default)(str); + options = (0, _merge.default)(options, defaultBase64Options); + var len = str.length; + + if (options.urlSafe) { + return urlSafeBase64.test(str); + } + + if (len % 4 !== 0 || notBase64.test(str)) { + return false; + } + + var firstPaddingChar = str.indexOf('='); + return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '='; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isBefore.js b/node_modules/validator/lib/isBefore.js new file mode 100644 index 0000000..a54eda8 --- /dev/null +++ b/node_modules/validator/lib/isBefore.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isBefore; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _toDate = _interopRequireDefault(require("./toDate")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isBefore(str) { + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date()); + (0, _assertString.default)(str); + var comparison = (0, _toDate.default)(date); + var original = (0, _toDate.default)(str); + return !!(original && comparison && original < comparison); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isBoolean.js b/node_modules/validator/lib/isBoolean.js new file mode 100644 index 0000000..e89a0e4 --- /dev/null +++ b/node_modules/validator/lib/isBoolean.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isBoolean; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultOptions = { + loose: false +}; +var strictBooleans = ['true', 'false', '1', '0']; +var looseBooleans = [].concat(strictBooleans, ['yes', 'no']); + +function isBoolean(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultOptions; + (0, _assertString.default)(str); + + if (options.loose) { + return looseBooleans.includes(str.toLowerCase()); + } + + return strictBooleans.includes(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isBtcAddress.js b/node_modules/validator/lib/isBtcAddress.js new file mode 100644 index 0000000..d1cb45c --- /dev/null +++ b/node_modules/validator/lib/isBtcAddress.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isBtcAddress; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// supports Bech32 addresses +var bech32 = /^(bc1)[a-z0-9]{25,39}$/; +var base58 = /^(1|3)[A-HJ-NP-Za-km-z1-9]{25,39}$/; + +function isBtcAddress(str) { + (0, _assertString.default)(str); // check for bech32 + + if (str.startsWith('bc1')) { + return bech32.test(str); + } + + return base58.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isByteLength.js b/node_modules/validator/lib/isByteLength.js new file mode 100644 index 0000000..c1370ea --- /dev/null +++ b/node_modules/validator/lib/isByteLength.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isByteLength; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/* eslint-disable prefer-rest-params */ +function isByteLength(str, options) { + (0, _assertString.default)(str); + var min; + var max; + + if (_typeof(options) === 'object') { + min = options.min || 0; + max = options.max; + } else { + // backwards compatibility: isByteLength(str, min [, max]) + min = arguments[1]; + max = arguments[2]; + } + + var len = encodeURI(str).split(/%..|./).length - 1; + return len >= min && (typeof max === 'undefined' || len <= max); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isCreditCard.js b/node_modules/validator/lib/isCreditCard.js new file mode 100644 index 0000000..c7ab315 --- /dev/null +++ b/node_modules/validator/lib/isCreditCard.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isCreditCard; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint-disable max-len */ +var creditCard = /^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/; +/* eslint-enable max-len */ + +function isCreditCard(str) { + (0, _assertString.default)(str); + var sanitized = str.replace(/[- ]+/g, ''); + + if (!creditCard.test(sanitized)) { + return false; + } + + var sum = 0; + var digit; + var tmpNum; + var shouldDouble; + + for (var i = sanitized.length - 1; i >= 0; i--) { + digit = sanitized.substring(i, i + 1); + tmpNum = parseInt(digit, 10); + + if (shouldDouble) { + tmpNum *= 2; + + if (tmpNum >= 10) { + sum += tmpNum % 10 + 1; + } else { + sum += tmpNum; + } + } else { + sum += tmpNum; + } + + shouldDouble = !shouldDouble; + } + + return !!(sum % 10 === 0 ? sanitized : false); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isCurrency.js b/node_modules/validator/lib/isCurrency.js new file mode 100644 index 0000000..cd7def6 --- /dev/null +++ b/node_modules/validator/lib/isCurrency.js @@ -0,0 +1,91 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isCurrency; + +var _merge = _interopRequireDefault(require("./util/merge")); + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function currencyRegex(options) { + var decimal_digits = "\\d{".concat(options.digits_after_decimal[0], "}"); + options.digits_after_decimal.forEach(function (digit, index) { + if (index !== 0) decimal_digits = "".concat(decimal_digits, "|\\d{").concat(digit, "}"); + }); + var symbol = "(".concat(options.symbol.replace(/\W/, function (m) { + return "\\".concat(m); + }), ")").concat(options.require_symbol ? '' : '?'), + negative = '-?', + whole_dollar_amount_without_sep = '[1-9]\\d*', + whole_dollar_amount_with_sep = "[1-9]\\d{0,2}(\\".concat(options.thousands_separator, "\\d{3})*"), + valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep], + whole_dollar_amount = "(".concat(valid_whole_dollar_amounts.join('|'), ")?"), + decimal_amount = "(\\".concat(options.decimal_separator, "(").concat(decimal_digits, "))").concat(options.require_decimal ? '' : '?'); + var pattern = whole_dollar_amount + (options.allow_decimal || options.require_decimal ? decimal_amount : ''); // default is negative sign before symbol, but there are two other options (besides parens) + + if (options.allow_negatives && !options.parens_for_negatives) { + if (options.negative_sign_after_digits) { + pattern += negative; + } else if (options.negative_sign_before_digits) { + pattern = negative + pattern; + } + } // South African Rand, for example, uses R 123 (space) and R-123 (no space) + + + if (options.allow_negative_sign_placeholder) { + pattern = "( (?!\\-))?".concat(pattern); + } else if (options.allow_space_after_symbol) { + pattern = " ?".concat(pattern); + } else if (options.allow_space_after_digits) { + pattern += '( (?!$))?'; + } + + if (options.symbol_after_digits) { + pattern += symbol; + } else { + pattern = symbol + pattern; + } + + if (options.allow_negatives) { + if (options.parens_for_negatives) { + pattern = "(\\(".concat(pattern, "\\)|").concat(pattern, ")"); + } else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) { + pattern = negative + pattern; + } + } // ensure there's a dollar and/or decimal amount, and that + // it doesn't start with a space or a negative sign followed by a space + + + return new RegExp("^(?!-? )(?=.*\\d)".concat(pattern, "$")); +} + +var default_currency_options = { + symbol: '$', + require_symbol: false, + allow_space_after_symbol: false, + symbol_after_digits: false, + allow_negatives: true, + parens_for_negatives: false, + negative_sign_before_digits: false, + negative_sign_after_digits: false, + allow_negative_sign_placeholder: false, + thousands_separator: ',', + decimal_separator: '.', + allow_decimal: true, + require_decimal: false, + digits_after_decimal: [2], + allow_space_after_digits: false +}; + +function isCurrency(str, options) { + (0, _assertString.default)(str); + options = (0, _merge.default)(options, default_currency_options); + return currencyRegex(options).test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isDataURI.js b/node_modules/validator/lib/isDataURI.js new file mode 100644 index 0000000..78dc309 --- /dev/null +++ b/node_modules/validator/lib/isDataURI.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isDataURI; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var validMediaType = /^[a-z]+\/[a-z0-9\-\+]+$/i; +var validAttribute = /^[a-z\-]+=[a-z0-9\-]+$/i; +var validData = /^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$/i; + +function isDataURI(str) { + (0, _assertString.default)(str); + var data = str.split(','); + + if (data.length < 2) { + return false; + } + + var attributes = data.shift().trim().split(';'); + var schemeAndMediaType = attributes.shift(); + + if (schemeAndMediaType.substr(0, 5) !== 'data:') { + return false; + } + + var mediaType = schemeAndMediaType.substr(5); + + if (mediaType !== '' && !validMediaType.test(mediaType)) { + return false; + } + + for (var i = 0; i < attributes.length; i++) { + if (!(i === attributes.length - 1 && attributes[i].toLowerCase() === 'base64') && !validAttribute.test(attributes[i])) { + return false; + } + } + + for (var _i = 0; _i < data.length; _i++) { + if (!validData.test(data[_i])) { + return false; + } + } + + return true; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isDate.js b/node_modules/validator/lib/isDate.js new file mode 100644 index 0000000..b3d8010 --- /dev/null +++ b/node_modules/validator/lib/isDate.js @@ -0,0 +1,99 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isDate; + +var _merge = _interopRequireDefault(require("./util/merge")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +var default_date_options = { + format: 'YYYY/MM/DD', + delimiters: ['/', '-'], + strictMode: false +}; + +function isValidFormat(format) { + return /(^(y{4}|y{2})[.\/-](m{1,2})[.\/-](d{1,2})$)|(^(m{1,2})[.\/-](d{1,2})[.\/-]((y{4}|y{2})$))|(^(d{1,2})[.\/-](m{1,2})[.\/-]((y{4}|y{2})$))/gi.test(format); +} + +function zip(date, format) { + var zippedArr = [], + len = Math.min(date.length, format.length); + + for (var i = 0; i < len; i++) { + zippedArr.push([date[i], format[i]]); + } + + return zippedArr; +} + +function isDate(input, options) { + if (typeof options === 'string') { + // Allow backward compatbility for old format isDate(input [, format]) + options = (0, _merge.default)({ + format: options + }, default_date_options); + } else { + options = (0, _merge.default)(options, default_date_options); + } + + if (typeof input === 'string' && isValidFormat(options.format)) { + var formatDelimiter = options.delimiters.find(function (delimiter) { + return options.format.indexOf(delimiter) !== -1; + }); + var dateDelimiter = options.strictMode ? formatDelimiter : options.delimiters.find(function (delimiter) { + return input.indexOf(delimiter) !== -1; + }); + var dateAndFormat = zip(input.split(dateDelimiter), options.format.toLowerCase().split(formatDelimiter)); + var dateObj = {}; + + var _iterator = _createForOfIteratorHelper(dateAndFormat), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _step$value = _slicedToArray(_step.value, 2), + dateWord = _step$value[0], + formatWord = _step$value[1]; + + if (dateWord.length !== formatWord.length) { + return false; + } + + dateObj[formatWord.charAt(0)] = dateWord; + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + + return new Date("".concat(dateObj.m, "/").concat(dateObj.d, "/").concat(dateObj.y)).getDate() === +dateObj.d; + } + + if (!options.strictMode) { + return Object.prototype.toString.call(input) === '[object Date]' && isFinite(input); + } + + return false; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isDecimal.js b/node_modules/validator/lib/isDecimal.js new file mode 100644 index 0000000..d45b05f --- /dev/null +++ b/node_modules/validator/lib/isDecimal.js @@ -0,0 +1,42 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isDecimal; + +var _merge = _interopRequireDefault(require("./util/merge")); + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _includes = _interopRequireDefault(require("./util/includes")); + +var _alpha = require("./alpha"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function decimalRegExp(options) { + var regExp = new RegExp("^[-+]?([0-9]+)?(\\".concat(_alpha.decimal[options.locale], "[0-9]{").concat(options.decimal_digits, "})").concat(options.force_decimal ? '' : '?', "$")); + return regExp; +} + +var default_decimal_options = { + force_decimal: false, + decimal_digits: '1,', + locale: 'en-US' +}; +var blacklist = ['', '-', '+']; + +function isDecimal(str, options) { + (0, _assertString.default)(str); + options = (0, _merge.default)(options, default_decimal_options); + + if (options.locale in _alpha.decimal) { + return !(0, _includes.default)(blacklist, str.replace(/ /g, '')) && decimalRegExp(options).test(str); + } + + throw new Error("Invalid locale '".concat(options.locale, "'")); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isDivisibleBy.js b/node_modules/validator/lib/isDivisibleBy.js new file mode 100644 index 0000000..02408b3 --- /dev/null +++ b/node_modules/validator/lib/isDivisibleBy.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isDivisibleBy; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _toFloat = _interopRequireDefault(require("./toFloat")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isDivisibleBy(str, num) { + (0, _assertString.default)(str); + return (0, _toFloat.default)(str) % parseInt(num, 10) === 0; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isEAN.js b/node_modules/validator/lib/isEAN.js new file mode 100644 index 0000000..d08d78b --- /dev/null +++ b/node_modules/validator/lib/isEAN.js @@ -0,0 +1,85 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isEAN; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The most commonly used EAN standard is + * the thirteen-digit EAN-13, while the + * less commonly used 8-digit EAN-8 barcode was + * introduced for use on small packages. + * Also EAN/UCC-14 is used for Grouping of individual + * trade items above unit level(Intermediate, Carton or Pallet). + * For more info about EAN-14 checkout: https://www.gtin.info/itf-14-barcodes/ + * EAN consists of: + * GS1 prefix, manufacturer code, product code and check digit + * Reference: https://en.wikipedia.org/wiki/International_Article_Number + * Reference: https://www.gtin.info/ + */ + +/** + * Define EAN Lenghts; 8 for EAN-8; 13 for EAN-13; 14 for EAN-14 + * and Regular Expression for valid EANs (EAN-8, EAN-13, EAN-14), + * with exact numberic matching of 8 or 13 or 14 digits [0-9] + */ +var LENGTH_EAN_8 = 8; +var LENGTH_EAN_14 = 14; +var validEanRegex = /^(\d{8}|\d{13}|\d{14})$/; +/** + * Get position weight given: + * EAN length and digit index/position + * + * @param {number} length + * @param {number} index + * @return {number} + */ + +function getPositionWeightThroughLengthAndIndex(length, index) { + if (length === LENGTH_EAN_8 || length === LENGTH_EAN_14) { + return index % 2 === 0 ? 3 : 1; + } + + return index % 2 === 0 ? 1 : 3; +} +/** + * Calculate EAN Check Digit + * Reference: https://en.wikipedia.org/wiki/International_Article_Number#Calculation_of_checksum_digit + * + * @param {string} ean + * @return {number} + */ + + +function calculateCheckDigit(ean) { + var checksum = ean.slice(0, -1).split('').map(function (char, index) { + return Number(char) * getPositionWeightThroughLengthAndIndex(ean.length, index); + }).reduce(function (acc, partialSum) { + return acc + partialSum; + }, 0); + var remainder = 10 - checksum % 10; + return remainder < 10 ? remainder : 0; +} +/** + * Check if string is valid EAN: + * Matches EAN-8/EAN-13/EAN-14 regex + * Has valid check digit. + * + * @param {string} str + * @return {boolean} + */ + + +function isEAN(str) { + (0, _assertString.default)(str); + var actualCheckDigit = Number(str.slice(-1)); + return validEanRegex.test(str) && actualCheckDigit === calculateCheckDigit(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isEmail.js b/node_modules/validator/lib/isEmail.js new file mode 100644 index 0000000..bf08492 --- /dev/null +++ b/node_modules/validator/lib/isEmail.js @@ -0,0 +1,197 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isEmail; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _merge = _interopRequireDefault(require("./util/merge")); + +var _isByteLength = _interopRequireDefault(require("./isByteLength")); + +var _isFQDN = _interopRequireDefault(require("./isFQDN")); + +var _isIP = _interopRequireDefault(require("./isIP")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var default_email_options = { + allow_display_name: false, + require_display_name: false, + allow_utf8_local_part: true, + require_tld: true, + blacklisted_chars: '', + ignore_max_length: false, + host_blacklist: [] +}; +/* eslint-disable max-len */ + +/* eslint-disable no-control-regex */ + +var splitNameAddress = /^([^\x00-\x1F\x7F-\x9F\cX]+)]/.test(display_name_without_quotes); + + if (contains_illegal) { + // if contains illegal characters, + // must to be enclosed in double-quotes, otherwise it's not a valid display name + if (display_name_without_quotes === display_name) { + return false; + } // the quotes in display name must start with character symbol \ + + + var all_start_with_back_slash = display_name_without_quotes.split('"').length === display_name_without_quotes.split('\\"').length; + + if (!all_start_with_back_slash) { + return false; + } + } + + return true; +} + +function isEmail(str, options) { + (0, _assertString.default)(str); + options = (0, _merge.default)(options, default_email_options); + + if (options.require_display_name || options.allow_display_name) { + var display_email = str.match(splitNameAddress); + + if (display_email) { + var display_name = display_email[1]; // Remove display name and angle brackets to get email address + // Can be done in the regex but will introduce a ReDOS (See #1597 for more info) + + str = str.replace(display_name, '').replace(/(^<|>$)/g, ''); // sometimes need to trim the last space to get the display name + // because there may be a space between display name and email address + // eg. myname + // the display name is `myname` instead of `myname `, so need to trim the last space + + if (display_name.endsWith(' ')) { + display_name = display_name.substr(0, display_name.length - 1); + } + + if (!validateDisplayName(display_name)) { + return false; + } + } else if (options.require_display_name) { + return false; + } + } + + if (!options.ignore_max_length && str.length > defaultMaxEmailLength) { + return false; + } + + var parts = str.split('@'); + var domain = parts.pop(); + var lower_domain = domain.toLowerCase(); + + if (options.host_blacklist.includes(lower_domain)) { + return false; + } + + var user = parts.join('@'); + + if (options.domain_specific_validation && (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com')) { + /* + Previously we removed dots for gmail addresses before validating. + This was removed because it allows `multiple..dots@gmail.com` + to be reported as valid, but it is not. + Gmail only normalizes single dots, removing them from here is pointless, + should be done in normalizeEmail + */ + user = user.toLowerCase(); // Removing sub-address from username before gmail validation + + var username = user.split('+')[0]; // Dots are not included in gmail length restriction + + if (!(0, _isByteLength.default)(username.replace(/\./g, ''), { + min: 6, + max: 30 + })) { + return false; + } + + var _user_parts = username.split('.'); + + for (var i = 0; i < _user_parts.length; i++) { + if (!gmailUserPart.test(_user_parts[i])) { + return false; + } + } + } + + if (options.ignore_max_length === false && (!(0, _isByteLength.default)(user, { + max: 64 + }) || !(0, _isByteLength.default)(domain, { + max: 254 + }))) { + return false; + } + + if (!(0, _isFQDN.default)(domain, { + require_tld: options.require_tld + })) { + if (!options.allow_ip_domain) { + return false; + } + + if (!(0, _isIP.default)(domain)) { + if (!domain.startsWith('[') || !domain.endsWith(']')) { + return false; + } + + var noBracketdomain = domain.substr(1, domain.length - 2); + + if (noBracketdomain.length === 0 || !(0, _isIP.default)(noBracketdomain)) { + return false; + } + } + } + + if (user[0] === '"') { + user = user.slice(1, user.length - 1); + return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user); + } + + var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart; + var user_parts = user.split('.'); + + for (var _i = 0; _i < user_parts.length; _i++) { + if (!pattern.test(user_parts[_i])) { + return false; + } + } + + if (options.blacklisted_chars) { + if (user.search(new RegExp("[".concat(options.blacklisted_chars, "]+"), 'g')) !== -1) return false; + } + + return true; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isEmpty.js b/node_modules/validator/lib/isEmpty.js new file mode 100644 index 0000000..26766d5 --- /dev/null +++ b/node_modules/validator/lib/isEmpty.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isEmpty; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _merge = _interopRequireDefault(require("./util/merge")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var default_is_empty_options = { + ignore_whitespace: false +}; + +function isEmpty(str, options) { + (0, _assertString.default)(str); + options = (0, _merge.default)(options, default_is_empty_options); + return (options.ignore_whitespace ? str.trim().length : str.length) === 0; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isEthereumAddress.js b/node_modules/validator/lib/isEthereumAddress.js new file mode 100644 index 0000000..e6999b9 --- /dev/null +++ b/node_modules/validator/lib/isEthereumAddress.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isEthereumAddress; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var eth = /^(0x)[0-9a-f]{40}$/i; + +function isEthereumAddress(str) { + (0, _assertString.default)(str); + return eth.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isFQDN.js b/node_modules/validator/lib/isFQDN.js new file mode 100644 index 0000000..73ce134 --- /dev/null +++ b/node_modules/validator/lib/isFQDN.js @@ -0,0 +1,89 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isFQDN; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _merge = _interopRequireDefault(require("./util/merge")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var default_fqdn_options = { + require_tld: true, + allow_underscores: false, + allow_trailing_dot: false, + allow_numeric_tld: false, + allow_wildcard: false +}; + +function isFQDN(str, options) { + (0, _assertString.default)(str); + options = (0, _merge.default)(options, default_fqdn_options); + /* Remove the optional trailing dot before checking validity */ + + if (options.allow_trailing_dot && str[str.length - 1] === '.') { + str = str.substring(0, str.length - 1); + } + /* Remove the optional wildcard before checking validity */ + + + if (options.allow_wildcard === true && str.indexOf('*.') === 0) { + str = str.substring(2); + } + + var parts = str.split('.'); + var tld = parts[parts.length - 1]; + + if (options.require_tld) { + // disallow fqdns without tld + if (parts.length < 2) { + return false; + } + + if (!/^([a-z\u00A1-\u00A8\u00AA-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) { + return false; + } // disallow spaces + + + if (/\s/.test(tld)) { + return false; + } + } // reject numeric TLDs + + + if (!options.allow_numeric_tld && /^\d+$/.test(tld)) { + return false; + } + + return parts.every(function (part) { + if (part.length > 63) { + return false; + } + + if (!/^[a-z_\u00a1-\uffff0-9-]+$/i.test(part)) { + return false; + } // disallow full-width chars + + + if (/[\uff01-\uff5e]/.test(part)) { + return false; + } // disallow parts starting or ending with hyphen + + + if (/^-|-$/.test(part)) { + return false; + } + + if (!options.allow_underscores && /_/.test(part)) { + return false; + } + + return true; + }); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isFloat.js b/node_modules/validator/lib/isFloat.js new file mode 100644 index 0000000..3fdab86 --- /dev/null +++ b/node_modules/validator/lib/isFloat.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isFloat; +exports.locales = void 0; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _alpha = require("./alpha"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isFloat(str, options) { + (0, _assertString.default)(str); + options = options || {}; + var float = new RegExp("^(?:[-+])?(?:[0-9]+)?(?:\\".concat(options.locale ? _alpha.decimal[options.locale] : '.', "[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$")); + + if (str === '' || str === '.' || str === '-' || str === '+') { + return false; + } + + var value = parseFloat(str.replace(',', '.')); + return float.test(str) && (!options.hasOwnProperty('min') || value >= options.min) && (!options.hasOwnProperty('max') || value <= options.max) && (!options.hasOwnProperty('lt') || value < options.lt) && (!options.hasOwnProperty('gt') || value > options.gt); +} + +var locales = Object.keys(_alpha.decimal); +exports.locales = locales; \ No newline at end of file diff --git a/node_modules/validator/lib/isFullWidth.js b/node_modules/validator/lib/isFullWidth.js new file mode 100644 index 0000000..1960f13 --- /dev/null +++ b/node_modules/validator/lib/isFullWidth.js @@ -0,0 +1,19 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isFullWidth; +exports.fullWidth = void 0; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fullWidth = /[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/; +exports.fullWidth = fullWidth; + +function isFullWidth(str) { + (0, _assertString.default)(str); + return fullWidth.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/lib/isHSL.js b/node_modules/validator/lib/isHSL.js new file mode 100644 index 0000000..0590b3e --- /dev/null +++ b/node_modules/validator/lib/isHSL.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isHSL; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var hslComma = /^hsla?\(((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?))(deg|grad|rad|turn)?(,(\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%){2}(,((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%?))?\)$/i; +var hslSpace = /^hsla?\(((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?))(deg|grad|rad|turn)?(\s(\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%){2}\s?(\/\s((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%?)\s?)?\)$/i; + +function isHSL(str) { + (0, _assertString.default)(str); // Strip duplicate spaces before calling the validation regex (See #1598 for more info) + + var strippedStr = str.replace(/\s+/g, ' ').replace(/\s?(hsla?\(|\)|,)\s?/ig, '$1'); + + if (strippedStr.indexOf(',') !== -1) { + return hslComma.test(strippedStr); + } + + return hslSpace.test(strippedStr); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isHalfWidth.js b/node_modules/validator/lib/isHalfWidth.js new file mode 100644 index 0000000..55a9e1a --- /dev/null +++ b/node_modules/validator/lib/isHalfWidth.js @@ -0,0 +1,19 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isHalfWidth; +exports.halfWidth = void 0; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var halfWidth = /[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/; +exports.halfWidth = halfWidth; + +function isHalfWidth(str) { + (0, _assertString.default)(str); + return halfWidth.test(str); +} \ No newline at end of file diff --git a/node_modules/validator/lib/isHash.js b/node_modules/validator/lib/isHash.js new file mode 100644 index 0000000..1083966 --- /dev/null +++ b/node_modules/validator/lib/isHash.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isHash; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var lengths = { + md5: 32, + md4: 32, + sha1: 40, + sha256: 64, + sha384: 96, + sha512: 128, + ripemd128: 32, + ripemd160: 40, + tiger128: 32, + tiger160: 40, + tiger192: 48, + crc32: 8, + crc32b: 8 +}; + +function isHash(str, algorithm) { + (0, _assertString.default)(str); + var hash = new RegExp("^[a-fA-F0-9]{".concat(lengths[algorithm], "}$")); + return hash.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isHexColor.js b/node_modules/validator/lib/isHexColor.js new file mode 100644 index 0000000..7af3889 --- /dev/null +++ b/node_modules/validator/lib/isHexColor.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isHexColor; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i; + +function isHexColor(str) { + (0, _assertString.default)(str); + return hexcolor.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isHexadecimal.js b/node_modules/validator/lib/isHexadecimal.js new file mode 100644 index 0000000..a1cf738 --- /dev/null +++ b/node_modules/validator/lib/isHexadecimal.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isHexadecimal; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var hexadecimal = /^(0x|0h)?[0-9A-F]+$/i; + +function isHexadecimal(str) { + (0, _assertString.default)(str); + return hexadecimal.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isIBAN.js b/node_modules/validator/lib/isIBAN.js new file mode 100644 index 0000000..ef804f2 --- /dev/null +++ b/node_modules/validator/lib/isIBAN.js @@ -0,0 +1,150 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isIBAN; +exports.locales = void 0; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * List of country codes with + * corresponding IBAN regular expression + * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number + */ +var ibanRegexThroughCountryCode = { + AD: /^(AD[0-9]{2})\d{8}[A-Z0-9]{12}$/, + AE: /^(AE[0-9]{2})\d{3}\d{16}$/, + AL: /^(AL[0-9]{2})\d{8}[A-Z0-9]{16}$/, + AT: /^(AT[0-9]{2})\d{16}$/, + AZ: /^(AZ[0-9]{2})[A-Z0-9]{4}\d{20}$/, + BA: /^(BA[0-9]{2})\d{16}$/, + BE: /^(BE[0-9]{2})\d{12}$/, + BG: /^(BG[0-9]{2})[A-Z]{4}\d{6}[A-Z0-9]{8}$/, + BH: /^(BH[0-9]{2})[A-Z]{4}[A-Z0-9]{14}$/, + BR: /^(BR[0-9]{2})\d{23}[A-Z]{1}[A-Z0-9]{1}$/, + BY: /^(BY[0-9]{2})[A-Z0-9]{4}\d{20}$/, + CH: /^(CH[0-9]{2})\d{5}[A-Z0-9]{12}$/, + CR: /^(CR[0-9]{2})\d{18}$/, + CY: /^(CY[0-9]{2})\d{8}[A-Z0-9]{16}$/, + CZ: /^(CZ[0-9]{2})\d{20}$/, + DE: /^(DE[0-9]{2})\d{18}$/, + DK: /^(DK[0-9]{2})\d{14}$/, + DO: /^(DO[0-9]{2})[A-Z]{4}\d{20}$/, + EE: /^(EE[0-9]{2})\d{16}$/, + EG: /^(EG[0-9]{2})\d{25}$/, + ES: /^(ES[0-9]{2})\d{20}$/, + FI: /^(FI[0-9]{2})\d{14}$/, + FO: /^(FO[0-9]{2})\d{14}$/, + FR: /^(FR[0-9]{2})\d{10}[A-Z0-9]{11}\d{2}$/, + GB: /^(GB[0-9]{2})[A-Z]{4}\d{14}$/, + GE: /^(GE[0-9]{2})[A-Z0-9]{2}\d{16}$/, + GI: /^(GI[0-9]{2})[A-Z]{4}[A-Z0-9]{15}$/, + GL: /^(GL[0-9]{2})\d{14}$/, + GR: /^(GR[0-9]{2})\d{7}[A-Z0-9]{16}$/, + GT: /^(GT[0-9]{2})[A-Z0-9]{4}[A-Z0-9]{20}$/, + HR: /^(HR[0-9]{2})\d{17}$/, + HU: /^(HU[0-9]{2})\d{24}$/, + IE: /^(IE[0-9]{2})[A-Z0-9]{4}\d{14}$/, + IL: /^(IL[0-9]{2})\d{19}$/, + IQ: /^(IQ[0-9]{2})[A-Z]{4}\d{15}$/, + IR: /^(IR[0-9]{2})0\d{2}0\d{18}$/, + IS: /^(IS[0-9]{2})\d{22}$/, + IT: /^(IT[0-9]{2})[A-Z]{1}\d{10}[A-Z0-9]{12}$/, + JO: /^(JO[0-9]{2})[A-Z]{4}\d{22}$/, + KW: /^(KW[0-9]{2})[A-Z]{4}[A-Z0-9]{22}$/, + KZ: /^(KZ[0-9]{2})\d{3}[A-Z0-9]{13}$/, + LB: /^(LB[0-9]{2})\d{4}[A-Z0-9]{20}$/, + LC: /^(LC[0-9]{2})[A-Z]{4}[A-Z0-9]{24}$/, + LI: /^(LI[0-9]{2})\d{5}[A-Z0-9]{12}$/, + LT: /^(LT[0-9]{2})\d{16}$/, + LU: /^(LU[0-9]{2})\d{3}[A-Z0-9]{13}$/, + LV: /^(LV[0-9]{2})[A-Z]{4}[A-Z0-9]{13}$/, + MC: /^(MC[0-9]{2})\d{10}[A-Z0-9]{11}\d{2}$/, + MD: /^(MD[0-9]{2})[A-Z0-9]{20}$/, + ME: /^(ME[0-9]{2})\d{18}$/, + MK: /^(MK[0-9]{2})\d{3}[A-Z0-9]{10}\d{2}$/, + MR: /^(MR[0-9]{2})\d{23}$/, + MT: /^(MT[0-9]{2})[A-Z]{4}\d{5}[A-Z0-9]{18}$/, + MU: /^(MU[0-9]{2})[A-Z]{4}\d{19}[A-Z]{3}$/, + MZ: /^(MZ[0-9]{2})\d{21}$/, + NL: /^(NL[0-9]{2})[A-Z]{4}\d{10}$/, + NO: /^(NO[0-9]{2})\d{11}$/, + PK: /^(PK[0-9]{2})[A-Z0-9]{4}\d{16}$/, + PL: /^(PL[0-9]{2})\d{24}$/, + PS: /^(PS[0-9]{2})[A-Z0-9]{4}\d{21}$/, + PT: /^(PT[0-9]{2})\d{21}$/, + QA: /^(QA[0-9]{2})[A-Z]{4}[A-Z0-9]{21}$/, + RO: /^(RO[0-9]{2})[A-Z]{4}[A-Z0-9]{16}$/, + RS: /^(RS[0-9]{2})\d{18}$/, + SA: /^(SA[0-9]{2})\d{2}[A-Z0-9]{18}$/, + SC: /^(SC[0-9]{2})[A-Z]{4}\d{20}[A-Z]{3}$/, + SE: /^(SE[0-9]{2})\d{20}$/, + SI: /^(SI[0-9]{2})\d{15}$/, + SK: /^(SK[0-9]{2})\d{20}$/, + SM: /^(SM[0-9]{2})[A-Z]{1}\d{10}[A-Z0-9]{12}$/, + SV: /^(SV[0-9]{2})[A-Z0-9]{4}\d{20}$/, + TL: /^(TL[0-9]{2})\d{19}$/, + TN: /^(TN[0-9]{2})\d{20}$/, + TR: /^(TR[0-9]{2})\d{5}[A-Z0-9]{17}$/, + UA: /^(UA[0-9]{2})\d{6}[A-Z0-9]{19}$/, + VA: /^(VA[0-9]{2})\d{18}$/, + VG: /^(VG[0-9]{2})[A-Z0-9]{4}\d{16}$/, + XK: /^(XK[0-9]{2})\d{16}$/ +}; +/** + * Check whether string has correct universal IBAN format + * The IBAN consists of up to 34 alphanumeric characters, as follows: + * Country Code using ISO 3166-1 alpha-2, two letters + * check digits, two digits and + * Basic Bank Account Number (BBAN), up to 30 alphanumeric characters. + * NOTE: Permitted IBAN characters are: digits [0-9] and the 26 latin alphabetic [A-Z] + * + * @param {string} str - string under validation + * @return {boolean} + */ + +function hasValidIbanFormat(str) { + // Strip white spaces and hyphens + var strippedStr = str.replace(/[\s\-]+/gi, '').toUpperCase(); + var isoCountryCode = strippedStr.slice(0, 2).toUpperCase(); + return isoCountryCode in ibanRegexThroughCountryCode && ibanRegexThroughCountryCode[isoCountryCode].test(strippedStr); +} +/** + * Check whether string has valid IBAN Checksum + * by performing basic mod-97 operation and + * the remainder should equal 1 + * -- Start by rearranging the IBAN by moving the four initial characters to the end of the string + * -- Replace each letter in the string with two digits, A -> 10, B = 11, Z = 35 + * -- Interpret the string as a decimal integer and + * -- compute the remainder on division by 97 (mod 97) + * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number + * + * @param {string} str + * @return {boolean} + */ + + +function hasValidIbanChecksum(str) { + var strippedStr = str.replace(/[^A-Z0-9]+/gi, '').toUpperCase(); // Keep only digits and A-Z latin alphabetic + + var rearranged = strippedStr.slice(4) + strippedStr.slice(0, 4); + var alphaCapsReplacedWithDigits = rearranged.replace(/[A-Z]/g, function (char) { + return char.charCodeAt(0) - 55; + }); + var remainder = alphaCapsReplacedWithDigits.match(/\d{1,7}/g).reduce(function (acc, value) { + return Number(acc + value) % 97; + }, ''); + return remainder === 1; +} + +function isIBAN(str) { + (0, _assertString.default)(str); + return hasValidIbanFormat(str) && hasValidIbanChecksum(str); +} + +var locales = Object.keys(ibanRegexThroughCountryCode); +exports.locales = locales; \ No newline at end of file diff --git a/node_modules/validator/lib/isIMEI.js b/node_modules/validator/lib/isIMEI.js new file mode 100644 index 0000000..aa05178 --- /dev/null +++ b/node_modules/validator/lib/isIMEI.js @@ -0,0 +1,61 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isIMEI; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var imeiRegexWithoutHypens = /^[0-9]{15}$/; +var imeiRegexWithHypens = /^\d{2}-\d{6}-\d{6}-\d{1}$/; + +function isIMEI(str, options) { + (0, _assertString.default)(str); + options = options || {}; // default regex for checking imei is the one without hyphens + + var imeiRegex = imeiRegexWithoutHypens; + + if (options.allow_hyphens) { + imeiRegex = imeiRegexWithHypens; + } + + if (!imeiRegex.test(str)) { + return false; + } + + str = str.replace(/-/g, ''); + var sum = 0, + mul = 2, + l = 14; + + for (var i = 0; i < l; i++) { + var digit = str.substring(l - i - 1, l - i); + var tp = parseInt(digit, 10) * mul; + + if (tp >= 10) { + sum += tp % 10 + 1; + } else { + sum += tp; + } + + if (mul === 1) { + mul += 1; + } else { + mul -= 1; + } + } + + var chk = (10 - sum % 10) % 10; + + if (chk !== parseInt(str.substring(14, 15), 10)) { + return false; + } + + return true; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isIP.js b/node_modules/validator/lib/isIP.js new file mode 100644 index 0000000..2b470af --- /dev/null +++ b/node_modules/validator/lib/isIP.js @@ -0,0 +1,75 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isIP; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** +11.3. Examples + + The following addresses + + fe80::1234 (on the 1st link of the node) + ff02::5678 (on the 5th link of the node) + ff08::9abc (on the 10th organization of the node) + + would be represented as follows: + + fe80::1234%1 + ff02::5678%5 + ff08::9abc%10 + + (Here we assume a natural translation from a zone index to the + part, where the Nth zone of any scope is translated into + "N".) + + If we use interface names as , those addresses could also be + represented as follows: + + fe80::1234%ne0 + ff02::5678%pvc1.3 + ff08::9abc%interface10 + + where the interface "ne0" belongs to the 1st link, "pvc1.3" belongs + to the 5th link, and "interface10" belongs to the 10th organization. + * * */ +var IPv4SegmentFormat = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'; +var IPv4AddressFormat = "(".concat(IPv4SegmentFormat, "[.]){3}").concat(IPv4SegmentFormat); +var IPv4AddressRegExp = new RegExp("^".concat(IPv4AddressFormat, "$")); +var IPv6SegmentFormat = '(?:[0-9a-fA-F]{1,4})'; +var IPv6AddressRegExp = new RegExp('^(' + "(?:".concat(IPv6SegmentFormat, ":){7}(?:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){6}(?:").concat(IPv4AddressFormat, "|:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){5}(?::").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,2}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){4}(?:(:").concat(IPv6SegmentFormat, "){0,1}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,3}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){3}(?:(:").concat(IPv6SegmentFormat, "){0,2}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,4}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){2}(?:(:").concat(IPv6SegmentFormat, "){0,3}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,5}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){1}(?:(:").concat(IPv6SegmentFormat, "){0,4}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,6}|:)|") + "(?::((?::".concat(IPv6SegmentFormat, "){0,5}:").concat(IPv4AddressFormat, "|(?::").concat(IPv6SegmentFormat, "){1,7}|:))") + ')(%[0-9a-zA-Z-.:]{1,})?$'); + +function isIP(str) { + var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + (0, _assertString.default)(str); + version = String(version); + + if (!version) { + return isIP(str, 4) || isIP(str, 6); + } + + if (version === '4') { + if (!IPv4AddressRegExp.test(str)) { + return false; + } + + var parts = str.split('.').sort(function (a, b) { + return a - b; + }); + return parts[3] <= 255; + } + + if (version === '6') { + return !!IPv6AddressRegExp.test(str); + } + + return false; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isIPRange.js b/node_modules/validator/lib/isIPRange.js new file mode 100644 index 0000000..293a1a2 --- /dev/null +++ b/node_modules/validator/lib/isIPRange.js @@ -0,0 +1,62 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isIPRange; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _isIP = _interopRequireDefault(require("./isIP")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var subnetMaybe = /^\d{1,3}$/; +var v4Subnet = 32; +var v6Subnet = 128; + +function isIPRange(str) { + var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + (0, _assertString.default)(str); + var parts = str.split('/'); // parts[0] -> ip, parts[1] -> subnet + + if (parts.length !== 2) { + return false; + } + + if (!subnetMaybe.test(parts[1])) { + return false; + } // Disallow preceding 0 i.e. 01, 02, ... + + + if (parts[1].length > 1 && parts[1].startsWith('0')) { + return false; + } + + var isValidIP = (0, _isIP.default)(parts[0], version); + + if (!isValidIP) { + return false; + } // Define valid subnet according to IP's version + + + var expectedSubnet = null; + + switch (String(version)) { + case '4': + expectedSubnet = v4Subnet; + break; + + case '6': + expectedSubnet = v6Subnet; + break; + + default: + expectedSubnet = (0, _isIP.default)(parts[0], '6') ? v6Subnet : v4Subnet; + } + + return parts[1] <= expectedSubnet && parts[1] >= 0; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isISBN.js b/node_modules/validator/lib/isISBN.js new file mode 100644 index 0000000..f00bb7a --- /dev/null +++ b/node_modules/validator/lib/isISBN.js @@ -0,0 +1,65 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isISBN; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/; +var isbn13Maybe = /^(?:[0-9]{13})$/; +var factor = [1, 3]; + +function isISBN(str) { + var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + (0, _assertString.default)(str); + version = String(version); + + if (!version) { + return isISBN(str, 10) || isISBN(str, 13); + } + + var sanitized = str.replace(/[\s-]+/g, ''); + var checksum = 0; + var i; + + if (version === '10') { + if (!isbn10Maybe.test(sanitized)) { + return false; + } + + for (i = 0; i < 9; i++) { + checksum += (i + 1) * sanitized.charAt(i); + } + + if (sanitized.charAt(9) === 'X') { + checksum += 10 * 10; + } else { + checksum += 10 * sanitized.charAt(9); + } + + if (checksum % 11 === 0) { + return !!sanitized; + } + } else if (version === '13') { + if (!isbn13Maybe.test(sanitized)) { + return false; + } + + for (i = 0; i < 12; i++) { + checksum += factor[i % 2] * sanitized.charAt(i); + } + + if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) { + return !!sanitized; + } + } + + return false; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isISIN.js b/node_modules/validator/lib/isISIN.js new file mode 100644 index 0000000..3943890 --- /dev/null +++ b/node_modules/validator/lib/isISIN.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isISIN; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/; // this link details how the check digit is calculated: +// https://www.isin.org/isin-format/. it is a little bit +// odd in that it works with digits, not numbers. in order +// to make only one pass through the ISIN characters, the +// each alpha character is handled as 2 characters within +// the loop. + +function isISIN(str) { + (0, _assertString.default)(str); + + if (!isin.test(str)) { + return false; + } + + var double = true; + var sum = 0; // convert values + + for (var i = str.length - 2; i >= 0; i--) { + if (str[i] >= 'A' && str[i] <= 'Z') { + var value = str[i].charCodeAt(0) - 55; + var lo = value % 10; + var hi = Math.trunc(value / 10); // letters have two digits, so handle the low order + // and high order digits separately. + + for (var _i = 0, _arr = [lo, hi]; _i < _arr.length; _i++) { + var digit = _arr[_i]; + + if (double) { + if (digit >= 5) { + sum += 1 + (digit - 5) * 2; + } else { + sum += digit * 2; + } + } else { + sum += digit; + } + + double = !double; + } + } else { + var _digit = str[i].charCodeAt(0) - '0'.charCodeAt(0); + + if (double) { + if (_digit >= 5) { + sum += 1 + (_digit - 5) * 2; + } else { + sum += _digit * 2; + } + } else { + sum += _digit; + } + + double = !double; + } + } + + var check = Math.trunc((sum + 9) / 10) * 10 - sum; + return +str[str.length - 1] === check; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isISO31661Alpha2.js b/node_modules/validator/lib/isISO31661Alpha2.js new file mode 100644 index 0000000..d15bb5b --- /dev/null +++ b/node_modules/validator/lib/isISO31661Alpha2.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isISO31661Alpha2; +exports.CountryCodes = void 0; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 +var validISO31661Alpha2CountriesCodes = new Set(['AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW']); + +function isISO31661Alpha2(str) { + (0, _assertString.default)(str); + return validISO31661Alpha2CountriesCodes.has(str.toUpperCase()); +} + +var CountryCodes = validISO31661Alpha2CountriesCodes; +exports.CountryCodes = CountryCodes; \ No newline at end of file diff --git a/node_modules/validator/lib/isISO31661Alpha3.js b/node_modules/validator/lib/isISO31661Alpha3.js new file mode 100644 index 0000000..cdb774f --- /dev/null +++ b/node_modules/validator/lib/isISO31661Alpha3.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isISO31661Alpha3; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3 +var validISO31661Alpha3CountriesCodes = new Set(['AFG', 'ALA', 'ALB', 'DZA', 'ASM', 'AND', 'AGO', 'AIA', 'ATA', 'ATG', 'ARG', 'ARM', 'ABW', 'AUS', 'AUT', 'AZE', 'BHS', 'BHR', 'BGD', 'BRB', 'BLR', 'BEL', 'BLZ', 'BEN', 'BMU', 'BTN', 'BOL', 'BES', 'BIH', 'BWA', 'BVT', 'BRA', 'IOT', 'BRN', 'BGR', 'BFA', 'BDI', 'KHM', 'CMR', 'CAN', 'CPV', 'CYM', 'CAF', 'TCD', 'CHL', 'CHN', 'CXR', 'CCK', 'COL', 'COM', 'COG', 'COD', 'COK', 'CRI', 'CIV', 'HRV', 'CUB', 'CUW', 'CYP', 'CZE', 'DNK', 'DJI', 'DMA', 'DOM', 'ECU', 'EGY', 'SLV', 'GNQ', 'ERI', 'EST', 'ETH', 'FLK', 'FRO', 'FJI', 'FIN', 'FRA', 'GUF', 'PYF', 'ATF', 'GAB', 'GMB', 'GEO', 'DEU', 'GHA', 'GIB', 'GRC', 'GRL', 'GRD', 'GLP', 'GUM', 'GTM', 'GGY', 'GIN', 'GNB', 'GUY', 'HTI', 'HMD', 'VAT', 'HND', 'HKG', 'HUN', 'ISL', 'IND', 'IDN', 'IRN', 'IRQ', 'IRL', 'IMN', 'ISR', 'ITA', 'JAM', 'JPN', 'JEY', 'JOR', 'KAZ', 'KEN', 'KIR', 'PRK', 'KOR', 'KWT', 'KGZ', 'LAO', 'LVA', 'LBN', 'LSO', 'LBR', 'LBY', 'LIE', 'LTU', 'LUX', 'MAC', 'MKD', 'MDG', 'MWI', 'MYS', 'MDV', 'MLI', 'MLT', 'MHL', 'MTQ', 'MRT', 'MUS', 'MYT', 'MEX', 'FSM', 'MDA', 'MCO', 'MNG', 'MNE', 'MSR', 'MAR', 'MOZ', 'MMR', 'NAM', 'NRU', 'NPL', 'NLD', 'NCL', 'NZL', 'NIC', 'NER', 'NGA', 'NIU', 'NFK', 'MNP', 'NOR', 'OMN', 'PAK', 'PLW', 'PSE', 'PAN', 'PNG', 'PRY', 'PER', 'PHL', 'PCN', 'POL', 'PRT', 'PRI', 'QAT', 'REU', 'ROU', 'RUS', 'RWA', 'BLM', 'SHN', 'KNA', 'LCA', 'MAF', 'SPM', 'VCT', 'WSM', 'SMR', 'STP', 'SAU', 'SEN', 'SRB', 'SYC', 'SLE', 'SGP', 'SXM', 'SVK', 'SVN', 'SLB', 'SOM', 'ZAF', 'SGS', 'SSD', 'ESP', 'LKA', 'SDN', 'SUR', 'SJM', 'SWZ', 'SWE', 'CHE', 'SYR', 'TWN', 'TJK', 'TZA', 'THA', 'TLS', 'TGO', 'TKL', 'TON', 'TTO', 'TUN', 'TUR', 'TKM', 'TCA', 'TUV', 'UGA', 'UKR', 'ARE', 'GBR', 'USA', 'UMI', 'URY', 'UZB', 'VUT', 'VEN', 'VNM', 'VGB', 'VIR', 'WLF', 'ESH', 'YEM', 'ZMB', 'ZWE']); + +function isISO31661Alpha3(str) { + (0, _assertString.default)(str); + return validISO31661Alpha3CountriesCodes.has(str.toUpperCase()); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isISO4217.js b/node_modules/validator/lib/isISO4217.js new file mode 100644 index 0000000..fd052f3 --- /dev/null +++ b/node_modules/validator/lib/isISO4217.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isISO4217; +exports.CurrencyCodes = void 0; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// from https://en.wikipedia.org/wiki/ISO_4217 +var validISO4217CurrencyCodes = new Set(['AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BOV', 'BRL', 'BSD', 'BTN', 'BWP', 'BYN', 'BZD', 'CAD', 'CDF', 'CHE', 'CHF', 'CHW', 'CLF', 'CLP', 'CNY', 'COP', 'COU', 'CRC', 'CUC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DZD', 'EGP', 'ERN', 'ETB', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GHS', 'GIP', 'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', 'INR', 'IQD', 'IRR', 'ISK', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD', 'MMK', 'MNT', 'MOP', 'MRU', 'MUR', 'MVR', 'MWK', 'MXN', 'MXV', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO', 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOS', 'SRD', 'SSP', 'STN', 'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'USN', 'UYI', 'UYU', 'UYW', 'UZS', 'VES', 'VND', 'VUV', 'WST', 'XAF', 'XAG', 'XAU', 'XBA', 'XBB', 'XBC', 'XBD', 'XCD', 'XDR', 'XOF', 'XPD', 'XPF', 'XPT', 'XSU', 'XTS', 'XUA', 'XXX', 'YER', 'ZAR', 'ZMW', 'ZWL']); + +function isISO4217(str) { + (0, _assertString.default)(str); + return validISO4217CurrencyCodes.has(str.toUpperCase()); +} + +var CurrencyCodes = validISO4217CurrencyCodes; +exports.CurrencyCodes = CurrencyCodes; \ No newline at end of file diff --git a/node_modules/validator/lib/isISO8601.js b/node_modules/validator/lib/isISO8601.js new file mode 100644 index 0000000..b739606 --- /dev/null +++ b/node_modules/validator/lib/isISO8601.js @@ -0,0 +1,59 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isISO8601; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint-disable max-len */ +// from http://goo.gl/0ejHHW +var iso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; // same as above, except with a strict 'T' separator between date and time + +var iso8601StrictSeparator = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; +/* eslint-enable max-len */ + +var isValidDate = function isValidDate(str) { + // str must have passed the ISO8601 check + // this check is meant to catch invalid dates + // like 2009-02-31 + // first check for ordinal dates + var ordinalMatch = str.match(/^(\d{4})-?(\d{3})([ T]{1}\.*|$)/); + + if (ordinalMatch) { + var oYear = Number(ordinalMatch[1]); + var oDay = Number(ordinalMatch[2]); // if is leap year + + if (oYear % 4 === 0 && oYear % 100 !== 0 || oYear % 400 === 0) return oDay <= 366; + return oDay <= 365; + } + + var match = str.match(/(\d{4})-?(\d{0,2})-?(\d*)/).map(Number); + var year = match[1]; + var month = match[2]; + var day = match[3]; + var monthString = month ? "0".concat(month).slice(-2) : month; + var dayString = day ? "0".concat(day).slice(-2) : day; // create a date object and compare + + var d = new Date("".concat(year, "-").concat(monthString || '01', "-").concat(dayString || '01')); + + if (month && day) { + return d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day; + } + + return true; +}; + +function isISO8601(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + (0, _assertString.default)(str); + var check = options.strictSeparator ? iso8601StrictSeparator.test(str) : iso8601.test(str); + if (check && options.strict) return isValidDate(str); + return check; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isISRC.js b/node_modules/validator/lib/isISRC.js new file mode 100644 index 0000000..c5ce1e2 --- /dev/null +++ b/node_modules/validator/lib/isISRC.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isISRC; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// see http://isrc.ifpi.org/en/isrc-standard/code-syntax +var isrc = /^[A-Z]{2}[0-9A-Z]{3}\d{2}\d{5}$/; + +function isISRC(str) { + (0, _assertString.default)(str); + return isrc.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isISSN.js b/node_modules/validator/lib/isISSN.js new file mode 100644 index 0000000..eee87b3 --- /dev/null +++ b/node_modules/validator/lib/isISSN.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isISSN; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var issn = '^\\d{4}-?\\d{3}[\\dX]$'; + +function isISSN(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + (0, _assertString.default)(str); + var testIssn = issn; + testIssn = options.require_hyphen ? testIssn.replace('?', '') : testIssn; + testIssn = options.case_sensitive ? new RegExp(testIssn) : new RegExp(testIssn, 'i'); + + if (!testIssn.test(str)) { + return false; + } + + var digits = str.replace('-', '').toUpperCase(); + var checksum = 0; + + for (var i = 0; i < digits.length; i++) { + var digit = digits[i]; + checksum += (digit === 'X' ? 10 : +digit) * (8 - i); + } + + return checksum % 11 === 0; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isIdentityCard.js b/node_modules/validator/lib/isIdentityCard.js new file mode 100644 index 0000000..993f2ad --- /dev/null +++ b/node_modules/validator/lib/isIdentityCard.js @@ -0,0 +1,384 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isIdentityCard; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _isInt = _interopRequireDefault(require("./isInt")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var validators = { + PL: function PL(str) { + (0, _assertString.default)(str); + var weightOfDigits = { + 1: 1, + 2: 3, + 3: 7, + 4: 9, + 5: 1, + 6: 3, + 7: 7, + 8: 9, + 9: 1, + 10: 3, + 11: 0 + }; + + if (str != null && str.length === 11 && (0, _isInt.default)(str, { + allow_leading_zeroes: true + })) { + var digits = str.split('').slice(0, -1); + var sum = digits.reduce(function (acc, digit, index) { + return acc + Number(digit) * weightOfDigits[index + 1]; + }, 0); + var modulo = sum % 10; + var lastDigit = Number(str.charAt(str.length - 1)); + + if (modulo === 0 && lastDigit === 0 || lastDigit === 10 - modulo) { + return true; + } + } + + return false; + }, + ES: function ES(str) { + (0, _assertString.default)(str); + var DNI = /^[0-9X-Z][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/; + var charsValue = { + X: 0, + Y: 1, + Z: 2 + }; + var controlDigits = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E']; // sanitize user input + + var sanitized = str.trim().toUpperCase(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } // validate the control digit + + + var number = sanitized.slice(0, -1).replace(/[X,Y,Z]/g, function (char) { + return charsValue[char]; + }); + return sanitized.endsWith(controlDigits[number % 23]); + }, + FI: function FI(str) { + // https://dvv.fi/en/personal-identity-code#:~:text=control%20character%20for%20a-,personal,-identity%20code%20calculated + (0, _assertString.default)(str); + + if (str.length !== 11) { + return false; + } + + if (!str.match(/^\d{6}[\-A\+]\d{3}[0-9ABCDEFHJKLMNPRSTUVWXY]{1}$/)) { + return false; + } + + var checkDigits = '0123456789ABCDEFHJKLMNPRSTUVWXY'; + var idAsNumber = parseInt(str.slice(0, 6), 10) * 1000 + parseInt(str.slice(7, 10), 10); + var remainder = idAsNumber % 31; + var checkDigit = checkDigits[remainder]; + return checkDigit === str.slice(10, 11); + }, + IN: function IN(str) { + var DNI = /^[1-9]\d{3}\s?\d{4}\s?\d{4}$/; // multiplication table + + var d = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]; // permutation table + + var p = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } + + var c = 0; + var invertedArray = sanitized.replace(/\s/g, '').split('').map(Number).reverse(); + invertedArray.forEach(function (val, i) { + c = d[c][p[i % 8][val]]; + }); + return c === 0; + }, + IR: function IR(str) { + if (!str.match(/^\d{10}$/)) return false; + str = "0000".concat(str).substr(str.length - 6); + if (parseInt(str.substr(3, 6), 10) === 0) return false; + var lastNumber = parseInt(str.substr(9, 1), 10); + var sum = 0; + + for (var i = 0; i < 9; i++) { + sum += parseInt(str.substr(i, 1), 10) * (10 - i); + } + + sum %= 11; + return sum < 2 && lastNumber === sum || sum >= 2 && lastNumber === 11 - sum; + }, + IT: function IT(str) { + if (str.length !== 9) return false; + if (str === 'CA00000AA') return false; // https://it.wikipedia.org/wiki/Carta_d%27identit%C3%A0_elettronica_italiana + + return str.search(/C[A-Z][0-9]{5}[A-Z]{2}/i) > -1; + }, + NO: function NO(str) { + var sanitized = str.trim(); + if (isNaN(Number(sanitized))) return false; + if (sanitized.length !== 11) return false; + if (sanitized === '00000000000') return false; // https://no.wikipedia.org/wiki/F%C3%B8dselsnummer + + var f = sanitized.split('').map(Number); + var k1 = (11 - (3 * f[0] + 7 * f[1] + 6 * f[2] + 1 * f[3] + 8 * f[4] + 9 * f[5] + 4 * f[6] + 5 * f[7] + 2 * f[8]) % 11) % 11; + var k2 = (11 - (5 * f[0] + 4 * f[1] + 3 * f[2] + 2 * f[3] + 7 * f[4] + 6 * f[5] + 5 * f[6] + 4 * f[7] + 3 * f[8] + 2 * k1) % 11) % 11; + if (k1 !== f[9] || k2 !== f[10]) return false; + return true; + }, + TH: function TH(str) { + if (!str.match(/^[1-8]\d{12}$/)) return false; // validate check digit + + var sum = 0; + + for (var i = 0; i < 12; i++) { + sum += parseInt(str[i], 10) * (13 - i); + } + + return str[12] === ((11 - sum % 11) % 10).toString(); + }, + LK: function LK(str) { + var old_nic = /^[1-9]\d{8}[vx]$/i; + var new_nic = /^[1-9]\d{11}$/i; + if (str.length === 10 && old_nic.test(str)) return true;else if (str.length === 12 && new_nic.test(str)) return true; + return false; + }, + 'he-IL': function heIL(str) { + var DNI = /^\d{9}$/; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } + + var id = sanitized; + var sum = 0, + incNum; + + for (var i = 0; i < id.length; i++) { + incNum = Number(id[i]) * (i % 2 + 1); // Multiply number by 1 or 2 + + sum += incNum > 9 ? incNum - 9 : incNum; // Sum the digits up and add to total + } + + return sum % 10 === 0; + }, + 'ar-LY': function arLY(str) { + // Libya National Identity Number NIN is 12 digits, the first digit is either 1 or 2 + var NIN = /^(1|2)\d{11}$/; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!NIN.test(sanitized)) { + return false; + } + + return true; + }, + 'ar-TN': function arTN(str) { + var DNI = /^\d{8}$/; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } + + return true; + }, + 'zh-CN': function zhCN(str) { + var provincesAndCities = ['11', // 北京 + '12', // 天津 + '13', // 河北 + '14', // 山西 + '15', // 内蒙古 + '21', // 辽宁 + '22', // 吉林 + '23', // 黑龙江 + '31', // 上海 + '32', // 江苏 + '33', // 浙江 + '34', // 安徽 + '35', // 福建 + '36', // 江西 + '37', // 山东 + '41', // 河南 + '42', // 湖北 + '43', // 湖南 + '44', // 广东 + '45', // 广西 + '46', // 海南 + '50', // 重庆 + '51', // 四川 + '52', // 贵州 + '53', // 云南 + '54', // 西藏 + '61', // 陕西 + '62', // 甘肃 + '63', // 青海 + '64', // 宁夏 + '65', // 新疆 + '71', // 台湾 + '81', // 香港 + '82', // 澳门 + '91' // 国外 + ]; + var powers = ['7', '9', '10', '5', '8', '4', '2', '1', '6', '3', '7', '9', '10', '5', '8', '4', '2']; + var parityBit = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']; + + var checkAddressCode = function checkAddressCode(addressCode) { + return provincesAndCities.includes(addressCode); + }; + + var checkBirthDayCode = function checkBirthDayCode(birDayCode) { + var yyyy = parseInt(birDayCode.substring(0, 4), 10); + var mm = parseInt(birDayCode.substring(4, 6), 10); + var dd = parseInt(birDayCode.substring(6), 10); + var xdata = new Date(yyyy, mm - 1, dd); + + if (xdata > new Date()) { + return false; // eslint-disable-next-line max-len + } else if (xdata.getFullYear() === yyyy && xdata.getMonth() === mm - 1 && xdata.getDate() === dd) { + return true; + } + + return false; + }; + + var getParityBit = function getParityBit(idCardNo) { + var id17 = idCardNo.substring(0, 17); + var power = 0; + + for (var i = 0; i < 17; i++) { + power += parseInt(id17.charAt(i), 10) * parseInt(powers[i], 10); + } + + var mod = power % 11; + return parityBit[mod]; + }; + + var checkParityBit = function checkParityBit(idCardNo) { + return getParityBit(idCardNo) === idCardNo.charAt(17).toUpperCase(); + }; + + var check15IdCardNo = function check15IdCardNo(idCardNo) { + var check = /^[1-9]\d{7}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}$/.test(idCardNo); + if (!check) return false; + var addressCode = idCardNo.substring(0, 2); + check = checkAddressCode(addressCode); + if (!check) return false; + var birDayCode = "19".concat(idCardNo.substring(6, 12)); + check = checkBirthDayCode(birDayCode); + if (!check) return false; + return true; + }; + + var check18IdCardNo = function check18IdCardNo(idCardNo) { + var check = /^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}(\d|x|X)$/.test(idCardNo); + if (!check) return false; + var addressCode = idCardNo.substring(0, 2); + check = checkAddressCode(addressCode); + if (!check) return false; + var birDayCode = idCardNo.substring(6, 14); + check = checkBirthDayCode(birDayCode); + if (!check) return false; + return checkParityBit(idCardNo); + }; + + var checkIdCardNo = function checkIdCardNo(idCardNo) { + var check = /^\d{15}|(\d{17}(\d|x|X))$/.test(idCardNo); + if (!check) return false; + + if (idCardNo.length === 15) { + return check15IdCardNo(idCardNo); + } + + return check18IdCardNo(idCardNo); + }; + + return checkIdCardNo(str); + }, + 'zh-TW': function zhTW(str) { + var ALPHABET_CODES = { + A: 10, + B: 11, + C: 12, + D: 13, + E: 14, + F: 15, + G: 16, + H: 17, + I: 34, + J: 18, + K: 19, + L: 20, + M: 21, + N: 22, + O: 35, + P: 23, + Q: 24, + R: 25, + S: 26, + T: 27, + U: 28, + V: 29, + W: 32, + X: 30, + Y: 31, + Z: 33 + }; + var sanitized = str.trim().toUpperCase(); + if (!/^[A-Z][0-9]{9}$/.test(sanitized)) return false; + return Array.from(sanitized).reduce(function (sum, number, index) { + if (index === 0) { + var code = ALPHABET_CODES[number]; + return code % 10 * 9 + Math.floor(code / 10); + } + + if (index === 9) { + return (10 - sum % 10 - Number(number)) % 10 === 0; + } + + return sum + Number(number) * (9 - index); + }, 0); + } +}; + +function isIdentityCard(str, locale) { + (0, _assertString.default)(str); + + if (locale in validators) { + return validators[locale](str); + } else if (locale === 'any') { + for (var key in validators) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (validators.hasOwnProperty(key)) { + var validator = validators[key]; + + if (validator(str)) { + return true; + } + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isIn.js b/node_modules/validator/lib/isIn.js new file mode 100644 index 0000000..62c5a4d --- /dev/null +++ b/node_modules/validator/lib/isIn.js @@ -0,0 +1,42 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isIn; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _toString = _interopRequireDefault(require("./util/toString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function isIn(str, options) { + (0, _assertString.default)(str); + var i; + + if (Object.prototype.toString.call(options) === '[object Array]') { + var array = []; + + for (i in options) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if ({}.hasOwnProperty.call(options, i)) { + array[i] = (0, _toString.default)(options[i]); + } + } + + return array.indexOf(str) >= 0; + } else if (_typeof(options) === 'object') { + return options.hasOwnProperty(str); + } else if (options && typeof options.indexOf === 'function') { + return options.indexOf(str) >= 0; + } + + return false; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isInt.js b/node_modules/validator/lib/isInt.js new file mode 100644 index 0000000..40f776c --- /dev/null +++ b/node_modules/validator/lib/isInt.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isInt; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/; +var intLeadingZeroes = /^[-+]?[0-9]+$/; + +function isInt(str, options) { + (0, _assertString.default)(str); + options = options || {}; // Get the regex to use for testing, based on whether + // leading zeroes are allowed or not. + + var regex = options.hasOwnProperty('allow_leading_zeroes') && !options.allow_leading_zeroes ? int : intLeadingZeroes; // Check min/max/lt/gt + + var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min; + var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max; + var ltCheckPassed = !options.hasOwnProperty('lt') || str < options.lt; + var gtCheckPassed = !options.hasOwnProperty('gt') || str > options.gt; + return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isJSON.js b/node_modules/validator/lib/isJSON.js new file mode 100644 index 0000000..78c09ef --- /dev/null +++ b/node_modules/validator/lib/isJSON.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isJSON; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _merge = _interopRequireDefault(require("./util/merge")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +var default_json_options = { + allow_primitives: false +}; + +function isJSON(str, options) { + (0, _assertString.default)(str); + + try { + options = (0, _merge.default)(options, default_json_options); + var primitives = []; + + if (options.allow_primitives) { + primitives = [null, false, true]; + } + + var obj = JSON.parse(str); + return primitives.includes(obj) || !!obj && _typeof(obj) === 'object'; + } catch (e) { + /* ignore */ + } + + return false; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isJWT.js b/node_modules/validator/lib/isJWT.js new file mode 100644 index 0000000..65d89fc --- /dev/null +++ b/node_modules/validator/lib/isJWT.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isJWT; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _isBase = _interopRequireDefault(require("./isBase64")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isJWT(str) { + (0, _assertString.default)(str); + var dotSplit = str.split('.'); + var len = dotSplit.length; + + if (len > 3 || len < 2) { + return false; + } + + return dotSplit.reduce(function (acc, currElem) { + return acc && (0, _isBase.default)(currElem, { + urlSafe: true + }); + }, true); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isLatLong.js b/node_modules/validator/lib/isLatLong.js new file mode 100644 index 0000000..e288812 --- /dev/null +++ b/node_modules/validator/lib/isLatLong.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isLatLong; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _merge = _interopRequireDefault(require("./util/merge")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var lat = /^\(?[+-]?(90(\.0+)?|[1-8]?\d(\.\d+)?)$/; +var long = /^\s?[+-]?(180(\.0+)?|1[0-7]\d(\.\d+)?|\d{1,2}(\.\d+)?)\)?$/; +var latDMS = /^(([1-8]?\d)\D+([1-5]?\d|60)\D+([1-5]?\d|60)(\.\d+)?|90\D+0\D+0)\D+[NSns]?$/i; +var longDMS = /^\s*([1-7]?\d{1,2}\D+([1-5]?\d|60)\D+([1-5]?\d|60)(\.\d+)?|180\D+0\D+0)\D+[EWew]?$/i; +var defaultLatLongOptions = { + checkDMS: false +}; + +function isLatLong(str, options) { + (0, _assertString.default)(str); + options = (0, _merge.default)(options, defaultLatLongOptions); + if (!str.includes(',')) return false; + var pair = str.split(','); + if (pair[0].startsWith('(') && !pair[1].endsWith(')') || pair[1].endsWith(')') && !pair[0].startsWith('(')) return false; + + if (options.checkDMS) { + return latDMS.test(pair[0]) && longDMS.test(pair[1]); + } + + return lat.test(pair[0]) && long.test(pair[1]); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isLength.js b/node_modules/validator/lib/isLength.js new file mode 100644 index 0000000..39b7597 --- /dev/null +++ b/node_modules/validator/lib/isLength.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isLength; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/* eslint-disable prefer-rest-params */ +function isLength(str, options) { + (0, _assertString.default)(str); + var min; + var max; + + if (_typeof(options) === 'object') { + min = options.min || 0; + max = options.max; + } else { + // backwards compatibility: isLength(str, min [, max]) + min = arguments[1] || 0; + max = arguments[2]; + } + + var surrogatePairs = str.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []; + var len = str.length - surrogatePairs.length; + return len >= min && (typeof max === 'undefined' || len <= max); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isLicensePlate.js b/node_modules/validator/lib/isLicensePlate.js new file mode 100644 index 0000000..e65428e --- /dev/null +++ b/node_modules/validator/lib/isLicensePlate.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isLicensePlate; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var validators = { + 'cs-CZ': function csCZ(str) { + return /^(([ABCDEFHKIJKLMNPRSTUVXYZ]|[0-9])-?){5,8}$/.test(str); + }, + 'de-DE': function deDE(str) { + return /^((AW|UL|AK|GA|AÖ|LF|AZ|AM|AS|ZE|AN|AB|A|KG|KH|BA|EW|BZ|HY|KM|BT|HP|B|BC|BI|BO|FN|TT|ÜB|BN|AH|BS|FR|HB|ZZ|BB|BK|BÖ|OC|OK|CW|CE|C|CO|LH|CB|KW|LC|LN|DA|DI|DE|DH|SY|NÖ|DO|DD|DU|DN|D|EI|EA|EE|FI|EM|EL|EN|PF|ED|EF|ER|AU|ZP|E|ES|NT|EU|FL|FO|FT|FF|F|FS|FD|FÜ|GE|G|GI|GF|GS|ZR|GG|GP|GR|NY|ZI|GÖ|GZ|GT|HA|HH|HM|HU|WL|HZ|WR|RN|HK|HD|HN|HS|GK|HE|HF|RZ|HI|HG|HO|HX|IK|IL|IN|J|JL|KL|KA|KS|KF|KE|KI|KT|KO|KN|KR|KC|KU|K|LD|LL|LA|L|OP|LM|LI|LB|LU|LÖ|HL|LG|MD|GN|MZ|MA|ML|MR|MY|AT|DM|MC|NZ|RM|RG|MM|ME|MB|MI|FG|DL|HC|MW|RL|MK|MG|MÜ|WS|MH|M|MS|NU|NB|ND|NM|NK|N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I': function deLI(str) { + return /^FL[- ]?\d{1,5}[UZ]?$/.test(str); + }, + 'fi-FI': function fiFI(str) { + return /^(?=.{4,7})(([A-Z]{1,3}|[0-9]{1,3})[\s-]?([A-Z]{1,3}|[0-9]{1,5}))$/.test(str); + }, + 'pt-PT': function ptPT(str) { + return /^([A-Z]{2}|[0-9]{2})[ -·]?([A-Z]{2}|[0-9]{2})[ -·]?([A-Z]{2}|[0-9]{2})$/.test(str); + }, + 'sq-AL': function sqAL(str) { + return /^[A-Z]{2}[- ]?((\d{3}[- ]?(([A-Z]{2})|T))|(R[- ]?\d{3}))$/.test(str); + }, + 'pt-BR': function ptBR(str) { + return /^[A-Z]{3}[ -]?[0-9][A-Z][0-9]{2}|[A-Z]{3}[ -]?[0-9]{4}$/.test(str); + } +}; + +function isLicensePlate(str, locale) { + (0, _assertString.default)(str); + + if (locale in validators) { + return validators[locale](str); + } else if (locale === 'any') { + for (var key in validators) { + /* eslint guard-for-in: 0 */ + var validator = validators[key]; + + if (validator(str)) { + return true; + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isLocale.js b/node_modules/validator/lib/isLocale.js new file mode 100644 index 0000000..1a4f609 --- /dev/null +++ b/node_modules/validator/lib/isLocale.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isLocale; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var localeReg = /^[A-Za-z]{2,4}([_-]([A-Za-z]{4}|[\d]{3}))?([_-]([A-Za-z]{2}|[\d]{3}))?$/; + +function isLocale(str) { + (0, _assertString.default)(str); + + if (str === 'en_US_POSIX' || str === 'ca_ES_VALENCIA') { + return true; + } + + return localeReg.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isLowercase.js b/node_modules/validator/lib/isLowercase.js new file mode 100644 index 0000000..7f412d9 --- /dev/null +++ b/node_modules/validator/lib/isLowercase.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isLowercase; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isLowercase(str) { + (0, _assertString.default)(str); + return str === str.toLowerCase(); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isMACAddress.js b/node_modules/validator/lib/isMACAddress.js new file mode 100644 index 0000000..125ea80 --- /dev/null +++ b/node_modules/validator/lib/isMACAddress.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isMACAddress; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var macAddress = /^(?:[0-9a-fA-F]{2}([-:\s]))([0-9a-fA-F]{2}\1){4}([0-9a-fA-F]{2})$/; +var macAddressNoSeparators = /^([0-9a-fA-F]){12}$/; +var macAddressWithDots = /^([0-9a-fA-F]{4}\.){2}([0-9a-fA-F]{4})$/; + +function isMACAddress(str, options) { + (0, _assertString.default)(str); + /** + * @deprecated `no_colons` TODO: remove it in the next major + */ + + if (options && (options.no_colons || options.no_separators)) { + return macAddressNoSeparators.test(str); + } + + return macAddress.test(str) || macAddressWithDots.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isMD5.js b/node_modules/validator/lib/isMD5.js new file mode 100644 index 0000000..57f2b0e --- /dev/null +++ b/node_modules/validator/lib/isMD5.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isMD5; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var md5 = /^[a-f0-9]{32}$/; + +function isMD5(str) { + (0, _assertString.default)(str); + return md5.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isMagnetURI.js b/node_modules/validator/lib/isMagnetURI.js new file mode 100644 index 0000000..7477e4c --- /dev/null +++ b/node_modules/validator/lib/isMagnetURI.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isMagnetURI; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var magnetURI = /^magnet:\?xt(?:\.1)?=urn:(?:aich|bitprint|btih|ed2k|ed2khash|kzhash|md5|sha1|tree:tiger):[a-z0-9]{32}(?:[a-z0-9]{8})?($|&)/i; + +function isMagnetURI(url) { + (0, _assertString.default)(url); + return magnetURI.test(url.trim()); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isMimeType.js b/node_modules/validator/lib/isMimeType.js new file mode 100644 index 0000000..917aef2 --- /dev/null +++ b/node_modules/validator/lib/isMimeType.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isMimeType; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* + Checks if the provided string matches to a correct Media type format (MIME type) + + This function only checks is the string format follows the + etablished rules by the according RFC specifications. + This function supports 'charset' in textual media types + (https://tools.ietf.org/html/rfc6657). + + This function does not check against all the media types listed + by the IANA (https://www.iana.org/assignments/media-types/media-types.xhtml) + because of lightness purposes : it would require to include + all these MIME types in this librairy, which would weigh it + significantly. This kind of effort maybe is not worth for the use that + this function has in this entire librairy. + + More informations in the RFC specifications : + - https://tools.ietf.org/html/rfc2045 + - https://tools.ietf.org/html/rfc2046 + - https://tools.ietf.org/html/rfc7231#section-3.1.1.1 + - https://tools.ietf.org/html/rfc7231#section-3.1.1.5 +*/ +// Match simple MIME types +// NB : +// Subtype length must not exceed 100 characters. +// This rule does not comply to the RFC specs (what is the max length ?). +var mimeTypeSimple = /^(application|audio|font|image|message|model|multipart|text|video)\/[a-zA-Z0-9\.\-\+]{1,100}$/i; // eslint-disable-line max-len +// Handle "charset" in "text/*" + +var mimeTypeText = /^text\/[a-zA-Z0-9\.\-\+]{1,100};\s?charset=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?$/i; // eslint-disable-line max-len +// Handle "boundary" in "multipart/*" + +var mimeTypeMultipart = /^multipart\/[a-zA-Z0-9\.\-\+]{1,100}(;\s?(boundary|charset)=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?){0,2}$/i; // eslint-disable-line max-len + +function isMimeType(str) { + (0, _assertString.default)(str); + return mimeTypeSimple.test(str) || mimeTypeText.test(str) || mimeTypeMultipart.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isMobilePhone.js b/node_modules/validator/lib/isMobilePhone.js new file mode 100644 index 0000000..a349f06 --- /dev/null +++ b/node_modules/validator/lib/isMobilePhone.js @@ -0,0 +1,200 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isMobilePhone; +exports.locales = void 0; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint-disable max-len */ +var phones = { + 'am-AM': /^(\+?374|0)((10|[9|7][0-9])\d{6}$|[2-4]\d{7}$)/, + 'ar-AE': /^((\+?971)|0)?5[024568]\d{7}$/, + 'ar-BH': /^(\+?973)?(3|6)\d{7}$/, + 'ar-DZ': /^(\+?213|0)(5|6|7)\d{8}$/, + 'ar-LB': /^(\+?961)?((3|81)\d{6}|7\d{7})$/, + 'ar-EG': /^((\+?20)|0)?1[0125]\d{8}$/, + 'ar-IQ': /^(\+?964|0)?7[0-9]\d{8}$/, + 'ar-JO': /^(\+?962|0)?7[789]\d{7}$/, + 'ar-KW': /^(\+?965)[569]\d{7}$/, + 'ar-LY': /^((\+?218)|0)?(9[1-6]\d{7}|[1-8]\d{7,9})$/, + 'ar-MA': /^(?:(?:\+|00)212|0)[5-7]\d{8}$/, + 'ar-OM': /^((\+|00)968)?(9[1-9])\d{6}$/, + 'ar-PS': /^(\+?970|0)5[6|9](\d{7})$/, + 'ar-SA': /^(!?(\+?966)|0)?5\d{8}$/, + 'ar-SY': /^(!?(\+?963)|0)?9\d{8}$/, + 'ar-TN': /^(\+?216)?[2459]\d{7}$/, + 'az-AZ': /^(\+994|0)(5[015]|7[07]|99)\d{7}$/, + 'bs-BA': /^((((\+|00)3876)|06))((([0-3]|[5-6])\d{6})|(4\d{7}))$/, + 'be-BY': /^(\+?375)?(24|25|29|33|44)\d{7}$/, + 'bg-BG': /^(\+?359|0)?8[789]\d{7}$/, + 'bn-BD': /^(\+?880|0)1[13456789][0-9]{8}$/, + 'ca-AD': /^(\+376)?[346]\d{5}$/, + 'cs-CZ': /^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/, + 'da-DK': /^(\+?45)?\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{2}$/, + 'de-DE': /^((\+49|0)[1|3])([0|5][0-45-9]\d|6([23]|0\d?)|7([0-57-9]|6\d))\d{7,9}$/, + 'de-AT': /^(\+43|0)\d{1,4}\d{3,12}$/, + 'de-CH': /^(\+41|0)([1-9])\d{1,9}$/, + 'de-LU': /^(\+352)?((6\d1)\d{6})$/, + 'dv-MV': /^(\+?960)?(7[2-9]|91|9[3-9])\d{7}$/, + 'el-GR': /^(\+?30|0)?(69\d{8})$/, + 'en-AU': /^(\+?61|0)4\d{8}$/, + 'en-BM': /^(\+?1)?441(((3|7)\d{6}$)|(5[0-3][0-9]\d{4}$)|(59\d{5}))/, + 'en-GB': /^(\+?44|0)7\d{9}$/, + 'en-GG': /^(\+?44|0)1481\d{6}$/, + 'en-GH': /^(\+233|0)(20|50|24|54|27|57|26|56|23|28|55|59)\d{7}$/, + 'en-GY': /^(\+592|0)6\d{6}$/, + 'en-HK': /^(\+?852[-\s]?)?[456789]\d{3}[-\s]?\d{4}$/, + 'en-MO': /^(\+?853[-\s]?)?[6]\d{3}[-\s]?\d{4}$/, + 'en-IE': /^(\+?353|0)8[356789]\d{7}$/, + 'en-IN': /^(\+?91|0)?[6789]\d{9}$/, + 'en-KE': /^(\+?254|0)(7|1)\d{8}$/, + 'en-KI': /^((\+686|686)?)?( )?((6|7)(2|3|8)[0-9]{6})$/, + 'en-MT': /^(\+?356|0)?(99|79|77|21|27|22|25)[0-9]{6}$/, + 'en-MU': /^(\+?230|0)?\d{8}$/, + 'en-NA': /^(\+?264|0)(6|8)\d{7}$/, + 'en-NG': /^(\+?234|0)?[789]\d{9}$/, + 'en-NZ': /^(\+?64|0)[28]\d{7,9}$/, + 'en-PK': /^((00|\+)?92|0)3[0-6]\d{8}$/, + 'en-PH': /^(09|\+639)\d{9}$/, + 'en-RW': /^(\+?250|0)?[7]\d{8}$/, + 'en-SG': /^(\+65)?[3689]\d{7}$/, + 'en-SL': /^(\+?232|0)\d{8}$/, + 'en-TZ': /^(\+?255|0)?[67]\d{8}$/, + 'en-UG': /^(\+?256|0)?[7]\d{8}$/, + 'en-US': /^((\+1|1)?( |-)?)?(\([2-9][0-9]{2}\)|[2-9][0-9]{2})( |-)?([2-9][0-9]{2}( |-)?[0-9]{4})$/, + 'en-ZA': /^(\+?27|0)\d{9}$/, + 'en-ZM': /^(\+?26)?09[567]\d{7}$/, + 'en-ZW': /^(\+263)[0-9]{9}$/, + 'en-BW': /^(\+?267)?(7[1-8]{1})\d{6}$/, + 'es-AR': /^\+?549(11|[2368]\d)\d{8}$/, + 'es-BO': /^(\+?591)?(6|7)\d{7}$/, + 'es-CO': /^(\+?57)?3(0(0|1|2|4|5)|1\d|2[0-4]|5(0|1))\d{7}$/, + 'es-CL': /^(\+?56|0)[2-9]\d{1}\d{7}$/, + 'es-CR': /^(\+506)?[2-8]\d{7}$/, + 'es-CU': /^(\+53|0053)?5\d{7}/, + 'es-DO': /^(\+?1)?8[024]9\d{7}$/, + 'es-HN': /^(\+?504)?[9|8]\d{7}$/, + 'es-EC': /^(\+?593|0)([2-7]|9[2-9])\d{7}$/, + 'es-ES': /^(\+?34)?[6|7]\d{8}$/, + 'es-PE': /^(\+?51)?9\d{8}$/, + 'es-MX': /^(\+?52)?(1|01)?\d{10,11}$/, + 'es-PA': /^(\+?507)\d{7,8}$/, + 'es-PY': /^(\+?595|0)9[9876]\d{7}$/, + 'es-SV': /^(\+?503)?[67]\d{7}$/, + 'es-UY': /^(\+598|0)9[1-9][\d]{6}$/, + 'es-VE': /^(\+?58)?(2|4)\d{9}$/, + 'et-EE': /^(\+?372)?\s?(5|8[1-4])\s?([0-9]\s?){6,7}$/, + 'fa-IR': /^(\+?98[\-\s]?|0)9[0-39]\d[\-\s]?\d{3}[\-\s]?\d{4}$/, + 'fi-FI': /^(\+?358|0)\s?(4(0|1|2|4|5|6)?|50)\s?(\d\s?){4,8}\d$/, + 'fj-FJ': /^(\+?679)?\s?\d{3}\s?\d{4}$/, + 'fo-FO': /^(\+?298)?\s?\d{2}\s?\d{2}\s?\d{2}$/, + 'fr-BF': /^(\+226|0)[67]\d{7}$/, + 'fr-CM': /^(\+?237)6[0-9]{8}$/, + 'fr-FR': /^(\+?33|0)[67]\d{8}$/, + 'fr-GF': /^(\+?594|0|00594)[67]\d{8}$/, + 'fr-GP': /^(\+?590|0|00590)[67]\d{8}$/, + 'fr-MQ': /^(\+?596|0|00596)[67]\d{8}$/, + 'fr-PF': /^(\+?689)?8[789]\d{6}$/, + 'fr-RE': /^(\+?262|0|00262)[67]\d{8}$/, + 'he-IL': /^(\+972|0)([23489]|5[012345689]|77)[1-9]\d{6}$/, + 'hu-HU': /^(\+?36|06)(20|30|31|50|70)\d{7}$/, + 'id-ID': /^(\+?62|0)8(1[123456789]|2[1238]|3[1238]|5[12356789]|7[78]|9[56789]|8[123456789])([\s?|\d]{5,11})$/, + 'it-IT': /^(\+?39)?\s?3\d{2} ?\d{6,7}$/, + 'it-SM': /^((\+378)|(0549)|(\+390549)|(\+3780549))?6\d{5,9}$/, + 'ja-JP': /^(\+81[ \-]?(\(0\))?|0)[6789]0[ \-]?\d{4}[ \-]?\d{4}$/, + 'ka-GE': /^(\+?995)?(5|79)\d{7}$/, + 'kk-KZ': /^(\+?7|8)?7\d{9}$/, + 'kl-GL': /^(\+?299)?\s?\d{2}\s?\d{2}\s?\d{2}$/, + 'ko-KR': /^((\+?82)[ \-]?)?0?1([0|1|6|7|8|9]{1})[ \-]?\d{3,4}[ \-]?\d{4}$/, + 'lt-LT': /^(\+370|8)\d{8}$/, + 'lv-LV': /^(\+?371)2\d{7}$/, + 'ms-MY': /^(\+?6?01){1}(([0145]{1}(\-|\s)?\d{7,8})|([236789]{1}(\s|\-)?\d{7}))$/, + 'mz-MZ': /^(\+?258)?8[234567]\d{7}$/, + 'nb-NO': /^(\+?47)?[49]\d{7}$/, + 'ne-NP': /^(\+?977)?9[78]\d{8}$/, + 'nl-BE': /^(\+?32|0)4\d{8}$/, + 'nl-NL': /^(((\+|00)?31\(0\))|((\+|00)?31)|0)6{1}\d{8}$/, + 'nn-NO': /^(\+?47)?[49]\d{7}$/, + 'pl-PL': /^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/, + 'pt-BR': /^((\+?55\ ?[1-9]{2}\ ?)|(\+?55\ ?\([1-9]{2}\)\ ?)|(0[1-9]{2}\ ?)|(\([1-9]{2}\)\ ?)|([1-9]{2}\ ?))((\d{4}\-?\d{4})|(9[2-9]{1}\d{3}\-?\d{4}))$/, + 'pt-PT': /^(\+?351)?9[1236]\d{7}$/, + 'pt-AO': /^(\+244)\d{9}$/, + 'ro-RO': /^(\+?4?0)\s?7\d{2}(\/|\s|\.|\-)?\d{3}(\s|\.|\-)?\d{3}$/, + 'ru-RU': /^(\+?7|8)?9\d{9}$/, + 'si-LK': /^(?:0|94|\+94)?(7(0|1|2|4|5|6|7|8)( |-)?)\d{7}$/, + 'sl-SI': /^(\+386\s?|0)(\d{1}\s?\d{3}\s?\d{2}\s?\d{2}|\d{2}\s?\d{3}\s?\d{3})$/, + 'sk-SK': /^(\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/, + 'sq-AL': /^(\+355|0)6[789]\d{6}$/, + 'sr-RS': /^(\+3816|06)[- \d]{5,9}$/, + 'sv-SE': /^(\+?46|0)[\s\-]?7[\s\-]?[02369]([\s\-]?\d){7}$/, + 'tg-TJ': /^(\+?992)?[5][5]\d{7}$/, + 'th-TH': /^(\+66|66|0)\d{9}$/, + 'tr-TR': /^(\+?90|0)?5\d{9}$/, + 'tk-TM': /^(\+993|993|8)\d{8}$/, + 'uk-UA': /^(\+?38|8)?0\d{9}$/, + 'uz-UZ': /^(\+?998)?(6[125-79]|7[1-69]|88|9\d)\d{7}$/, + 'vi-VN': /^((\+?84)|0)((3([2-9]))|(5([25689]))|(7([0|6-9]))|(8([1-9]))|(9([0-9])))([0-9]{7})$/, + 'zh-CN': /^((\+|00)86)?(1[3-9]|9[28])\d{9}$/, + 'zh-TW': /^(\+?886\-?|0)?9\d{8}$/, + 'dz-BT': /^(\+?975|0)?(17|16|77|02)\d{6}$/ +}; +/* eslint-enable max-len */ +// aliases + +phones['en-CA'] = phones['en-US']; +phones['fr-CA'] = phones['en-CA']; +phones['fr-BE'] = phones['nl-BE']; +phones['zh-HK'] = phones['en-HK']; +phones['zh-MO'] = phones['en-MO']; +phones['ga-IE'] = phones['en-IE']; +phones['fr-CH'] = phones['de-CH']; +phones['it-CH'] = phones['fr-CH']; + +function isMobilePhone(str, locale, options) { + (0, _assertString.default)(str); + + if (options && options.strictMode && !str.startsWith('+')) { + return false; + } + + if (Array.isArray(locale)) { + return locale.some(function (key) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (phones.hasOwnProperty(key)) { + var phone = phones[key]; + + if (phone.test(str)) { + return true; + } + } + + return false; + }); + } else if (locale in phones) { + return phones[locale].test(str); // alias falsey locale as 'any' + } else if (!locale || locale === 'any') { + for (var key in phones) { + // istanbul ignore else + if (phones.hasOwnProperty(key)) { + var phone = phones[key]; + + if (phone.test(str)) { + return true; + } + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} + +var locales = Object.keys(phones); +exports.locales = locales; \ No newline at end of file diff --git a/node_modules/validator/lib/isMongoId.js b/node_modules/validator/lib/isMongoId.js new file mode 100644 index 0000000..2e9884d --- /dev/null +++ b/node_modules/validator/lib/isMongoId.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isMongoId; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _isHexadecimal = _interopRequireDefault(require("./isHexadecimal")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isMongoId(str) { + (0, _assertString.default)(str); + return (0, _isHexadecimal.default)(str) && str.length === 24; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isMultibyte.js b/node_modules/validator/lib/isMultibyte.js new file mode 100644 index 0000000..3b4477e --- /dev/null +++ b/node_modules/validator/lib/isMultibyte.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isMultibyte; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint-disable no-control-regex */ +var multibyte = /[^\x00-\x7F]/; +/* eslint-enable no-control-regex */ + +function isMultibyte(str) { + (0, _assertString.default)(str); + return multibyte.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isNumeric.js b/node_modules/validator/lib/isNumeric.js new file mode 100644 index 0000000..441f30f --- /dev/null +++ b/node_modules/validator/lib/isNumeric.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isNumeric; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _alpha = require("./alpha"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var numericNoSymbols = /^[0-9]+$/; + +function isNumeric(str, options) { + (0, _assertString.default)(str); + + if (options && options.no_symbols) { + return numericNoSymbols.test(str); + } + + return new RegExp("^[+-]?([0-9]*[".concat((options || {}).locale ? _alpha.decimal[options.locale] : '.', "])?[0-9]+$")).test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isOctal.js b/node_modules/validator/lib/isOctal.js new file mode 100644 index 0000000..8d3a1c7 --- /dev/null +++ b/node_modules/validator/lib/isOctal.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isOctal; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var octal = /^(0o)?[0-7]+$/i; + +function isOctal(str) { + (0, _assertString.default)(str); + return octal.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isPassportNumber.js b/node_modules/validator/lib/isPassportNumber.js new file mode 100644 index 0000000..192414e --- /dev/null +++ b/node_modules/validator/lib/isPassportNumber.js @@ -0,0 +1,138 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isPassportNumber; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reference: + * https://en.wikipedia.org/ -- Wikipedia + * https://docs.microsoft.com/en-us/microsoft-365/compliance/eu-passport-number -- EU Passport Number + * https://countrycode.org/ -- Country Codes + */ +var passportRegexByCountryCode = { + AM: /^[A-Z]{2}\d{7}$/, + // ARMENIA + AR: /^[A-Z]{3}\d{6}$/, + // ARGENTINA + AT: /^[A-Z]\d{7}$/, + // AUSTRIA + AU: /^[A-Z]\d{7}$/, + // AUSTRALIA + BE: /^[A-Z]{2}\d{6}$/, + // BELGIUM + BG: /^\d{9}$/, + // BULGARIA + BR: /^[A-Z]{2}\d{6}$/, + // BRAZIL + BY: /^[A-Z]{2}\d{7}$/, + // BELARUS + CA: /^[A-Z]{2}\d{6}$/, + // CANADA + CH: /^[A-Z]\d{7}$/, + // SWITZERLAND + CN: /^G\d{8}$|^E(?![IO])[A-Z0-9]\d{7}$/, + // CHINA [G=Ordinary, E=Electronic] followed by 8-digits, or E followed by any UPPERCASE letter (except I and O) followed by 7 digits + CY: /^[A-Z](\d{6}|\d{8})$/, + // CYPRUS + CZ: /^\d{8}$/, + // CZECH REPUBLIC + DE: /^[CFGHJKLMNPRTVWXYZ0-9]{9}$/, + // GERMANY + DK: /^\d{9}$/, + // DENMARK + DZ: /^\d{9}$/, + // ALGERIA + EE: /^([A-Z]\d{7}|[A-Z]{2}\d{7})$/, + // ESTONIA (K followed by 7-digits), e-passports have 2 UPPERCASE followed by 7 digits + ES: /^[A-Z0-9]{2}([A-Z0-9]?)\d{6}$/, + // SPAIN + FI: /^[A-Z]{2}\d{7}$/, + // FINLAND + FR: /^\d{2}[A-Z]{2}\d{5}$/, + // FRANCE + GB: /^\d{9}$/, + // UNITED KINGDOM + GR: /^[A-Z]{2}\d{7}$/, + // GREECE + HR: /^\d{9}$/, + // CROATIA + HU: /^[A-Z]{2}(\d{6}|\d{7})$/, + // HUNGARY + IE: /^[A-Z0-9]{2}\d{7}$/, + // IRELAND + IN: /^[A-Z]{1}-?\d{7}$/, + // INDIA + ID: /^[A-C]\d{7}$/, + // INDONESIA + IR: /^[A-Z]\d{8}$/, + // IRAN + IS: /^(A)\d{7}$/, + // ICELAND + IT: /^[A-Z0-9]{2}\d{7}$/, + // ITALY + JP: /^[A-Z]{2}\d{7}$/, + // JAPAN + KR: /^[MS]\d{8}$/, + // SOUTH KOREA, REPUBLIC OF KOREA, [S=PS Passports, M=PM Passports] + LT: /^[A-Z0-9]{8}$/, + // LITHUANIA + LU: /^[A-Z0-9]{8}$/, + // LUXEMBURG + LV: /^[A-Z0-9]{2}\d{7}$/, + // LATVIA + LY: /^[A-Z0-9]{8}$/, + // LIBYA + MT: /^\d{7}$/, + // MALTA + MZ: /^([A-Z]{2}\d{7})|(\d{2}[A-Z]{2}\d{5})$/, + // MOZAMBIQUE + MY: /^[AHK]\d{8}$/, + // MALAYSIA + NL: /^[A-Z]{2}[A-Z0-9]{6}\d$/, + // NETHERLANDS + PL: /^[A-Z]{2}\d{7}$/, + // POLAND + PT: /^[A-Z]\d{6}$/, + // PORTUGAL + RO: /^\d{8,9}$/, + // ROMANIA + RU: /^\d{9}$/, + // RUSSIAN FEDERATION + SE: /^\d{8}$/, + // SWEDEN + SL: /^(P)[A-Z]\d{7}$/, + // SLOVANIA + SK: /^[0-9A-Z]\d{7}$/, + // SLOVAKIA + TR: /^[A-Z]\d{8}$/, + // TURKEY + UA: /^[A-Z]{2}\d{6}$/, + // UKRAINE + US: /^\d{9}$/ // UNITED STATES + +}; +/** + * Check if str is a valid passport number + * relative to provided ISO Country Code. + * + * @param {string} str + * @param {string} countryCode + * @return {boolean} + */ + +function isPassportNumber(str, countryCode) { + (0, _assertString.default)(str); + /** Remove All Whitespaces, Convert to UPPERCASE */ + + var normalizedStr = str.replace(/\s/g, '').toUpperCase(); + return countryCode.toUpperCase() in passportRegexByCountryCode && passportRegexByCountryCode[countryCode].test(normalizedStr); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isPort.js b/node_modules/validator/lib/isPort.js new file mode 100644 index 0000000..9274a4c --- /dev/null +++ b/node_modules/validator/lib/isPort.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isPort; + +var _isInt = _interopRequireDefault(require("./isInt")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isPort(str) { + return (0, _isInt.default)(str, { + min: 0, + max: 65535 + }); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isPostalCode.js b/node_modules/validator/lib/isPostalCode.js new file mode 100644 index 0000000..17c5318 --- /dev/null +++ b/node_modules/validator/lib/isPostalCode.js @@ -0,0 +1,109 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isPostalCode; +exports.locales = void 0; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// common patterns +var threeDigit = /^\d{3}$/; +var fourDigit = /^\d{4}$/; +var fiveDigit = /^\d{5}$/; +var sixDigit = /^\d{6}$/; +var patterns = { + AD: /^AD\d{3}$/, + AT: fourDigit, + AU: fourDigit, + AZ: /^AZ\d{4}$/, + BE: fourDigit, + BG: fourDigit, + BR: /^\d{5}-\d{3}$/, + BY: /2[1-4]{1}\d{4}$/, + CA: /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][\s\-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i, + CH: fourDigit, + CN: /^(0[1-7]|1[012356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[1-5]|8[1345]|9[09])\d{4}$/, + CZ: /^\d{3}\s?\d{2}$/, + DE: fiveDigit, + DK: fourDigit, + DO: fiveDigit, + DZ: fiveDigit, + EE: fiveDigit, + ES: /^(5[0-2]{1}|[0-4]{1}\d{1})\d{3}$/, + FI: fiveDigit, + FR: /^\d{2}\s?\d{3}$/, + GB: /^(gir\s?0aa|[a-z]{1,2}\d[\da-z]?\s?(\d[a-z]{2})?)$/i, + GR: /^\d{3}\s?\d{2}$/, + HR: /^([1-5]\d{4}$)/, + HT: /^HT\d{4}$/, + HU: fourDigit, + ID: fiveDigit, + IE: /^(?!.*(?:o))[A-Za-z]\d[\dw]\s\w{4}$/i, + IL: /^(\d{5}|\d{7})$/, + IN: /^((?!10|29|35|54|55|65|66|86|87|88|89)[1-9][0-9]{5})$/, + IR: /\b(?!(\d)\1{3})[13-9]{4}[1346-9][013-9]{5}\b/, + IS: threeDigit, + IT: fiveDigit, + JP: /^\d{3}\-\d{4}$/, + KE: fiveDigit, + KR: /^(\d{5}|\d{6})$/, + LI: /^(948[5-9]|949[0-7])$/, + LT: /^LT\-\d{5}$/, + LU: fourDigit, + LV: /^LV\-\d{4}$/, + LK: fiveDigit, + MX: fiveDigit, + MT: /^[A-Za-z]{3}\s{0,1}\d{4}$/, + MY: fiveDigit, + NL: /^\d{4}\s?[a-z]{2}$/i, + NO: fourDigit, + NP: /^(10|21|22|32|33|34|44|45|56|57)\d{3}$|^(977)$/i, + NZ: fourDigit, + PL: /^\d{2}\-\d{3}$/, + PR: /^00[679]\d{2}([ -]\d{4})?$/, + PT: /^\d{4}\-\d{3}?$/, + RO: sixDigit, + RU: sixDigit, + SA: fiveDigit, + SE: /^[1-9]\d{2}\s?\d{2}$/, + SG: sixDigit, + SI: fourDigit, + SK: /^\d{3}\s?\d{2}$/, + TH: fiveDigit, + TN: fourDigit, + TW: /^\d{3}(\d{2})?$/, + UA: fiveDigit, + US: /^\d{5}(-\d{4})?$/, + ZA: fourDigit, + ZM: fiveDigit +}; +var locales = Object.keys(patterns); +exports.locales = locales; + +function isPostalCode(str, locale) { + (0, _assertString.default)(str); + + if (locale in patterns) { + return patterns[locale].test(str); + } else if (locale === 'any') { + for (var key in patterns) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (patterns.hasOwnProperty(key)) { + var pattern = patterns[key]; + + if (pattern.test(str)) { + return true; + } + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} \ No newline at end of file diff --git a/node_modules/validator/lib/isRFC3339.js b/node_modules/validator/lib/isRFC3339.js new file mode 100644 index 0000000..da10790 --- /dev/null +++ b/node_modules/validator/lib/isRFC3339.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isRFC3339; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* Based on https://tools.ietf.org/html/rfc3339#section-5.6 */ +var dateFullYear = /[0-9]{4}/; +var dateMonth = /(0[1-9]|1[0-2])/; +var dateMDay = /([12]\d|0[1-9]|3[01])/; +var timeHour = /([01][0-9]|2[0-3])/; +var timeMinute = /[0-5][0-9]/; +var timeSecond = /([0-5][0-9]|60)/; +var timeSecFrac = /(\.[0-9]+)?/; +var timeNumOffset = new RegExp("[-+]".concat(timeHour.source, ":").concat(timeMinute.source)); +var timeOffset = new RegExp("([zZ]|".concat(timeNumOffset.source, ")")); +var partialTime = new RegExp("".concat(timeHour.source, ":").concat(timeMinute.source, ":").concat(timeSecond.source).concat(timeSecFrac.source)); +var fullDate = new RegExp("".concat(dateFullYear.source, "-").concat(dateMonth.source, "-").concat(dateMDay.source)); +var fullTime = new RegExp("".concat(partialTime.source).concat(timeOffset.source)); +var rfc3339 = new RegExp("^".concat(fullDate.source, "[ tT]").concat(fullTime.source, "$")); + +function isRFC3339(str) { + (0, _assertString.default)(str); + return rfc3339.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isRgbColor.js b/node_modules/validator/lib/isRgbColor.js new file mode 100644 index 0000000..9622291 --- /dev/null +++ b/node_modules/validator/lib/isRgbColor.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isRgbColor; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var rgbColor = /^rgb\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\)$/; +var rgbaColor = /^rgba\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)$/; +var rgbColorPercent = /^rgb\((([0-9]%|[1-9][0-9]%|100%),){2}([0-9]%|[1-9][0-9]%|100%)\)/; +var rgbaColorPercent = /^rgba\((([0-9]%|[1-9][0-9]%|100%),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)/; + +function isRgbColor(str) { + var includePercentValues = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + (0, _assertString.default)(str); + + if (!includePercentValues) { + return rgbColor.test(str) || rgbaColor.test(str); + } + + return rgbColor.test(str) || rgbaColor.test(str) || rgbColorPercent.test(str) || rgbaColorPercent.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isSemVer.js b/node_modules/validator/lib/isSemVer.js new file mode 100644 index 0000000..27355cd --- /dev/null +++ b/node_modules/validator/lib/isSemVer.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isSemVer; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _multilineRegex = _interopRequireDefault(require("./util/multilineRegex")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Regular Expression to match + * semantic versioning (SemVer) + * built from multi-line, multi-parts regexp + * Reference: https://semver.org/ + */ +var semanticVersioningRegex = (0, _multilineRegex.default)(['^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)', '(?:-((?:0|[1-9]\\d*|\\d*[a-z-][0-9a-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-z-][0-9a-z-]*))*))', '?(?:\\+([0-9a-z-]+(?:\\.[0-9a-z-]+)*))?$'], 'i'); + +function isSemVer(str) { + (0, _assertString.default)(str); + return semanticVersioningRegex.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isSlug.js b/node_modules/validator/lib/isSlug.js new file mode 100644 index 0000000..c40e6ad --- /dev/null +++ b/node_modules/validator/lib/isSlug.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isSlug; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var charsetRegex = /^[^\s-_](?!.*?[-_]{2,})[a-z0-9-\\][^\s]*[^-_\s]$/; + +function isSlug(str) { + (0, _assertString.default)(str); + return charsetRegex.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isStrongPassword.js b/node_modules/validator/lib/isStrongPassword.js new file mode 100644 index 0000000..a6a5a33 --- /dev/null +++ b/node_modules/validator/lib/isStrongPassword.js @@ -0,0 +1,115 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isStrongPassword; + +var _merge = _interopRequireDefault(require("./util/merge")); + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var upperCaseRegex = /^[A-Z]$/; +var lowerCaseRegex = /^[a-z]$/; +var numberRegex = /^[0-9]$/; +var symbolRegex = /^[-#!$@%^&*()_+|~=`{}\[\]:";'<>?,.\/ ]$/; +var defaultOptions = { + minLength: 8, + minLowercase: 1, + minUppercase: 1, + minNumbers: 1, + minSymbols: 1, + returnScore: false, + pointsPerUnique: 1, + pointsPerRepeat: 0.5, + pointsForContainingLower: 10, + pointsForContainingUpper: 10, + pointsForContainingNumber: 10, + pointsForContainingSymbol: 10 +}; +/* Counts number of occurrences of each char in a string + * could be moved to util/ ? +*/ + +function countChars(str) { + var result = {}; + Array.from(str).forEach(function (char) { + var curVal = result[char]; + + if (curVal) { + result[char] += 1; + } else { + result[char] = 1; + } + }); + return result; +} +/* Return information about a password */ + + +function analyzePassword(password) { + var charMap = countChars(password); + var analysis = { + length: password.length, + uniqueChars: Object.keys(charMap).length, + uppercaseCount: 0, + lowercaseCount: 0, + numberCount: 0, + symbolCount: 0 + }; + Object.keys(charMap).forEach(function (char) { + /* istanbul ignore else */ + if (upperCaseRegex.test(char)) { + analysis.uppercaseCount += charMap[char]; + } else if (lowerCaseRegex.test(char)) { + analysis.lowercaseCount += charMap[char]; + } else if (numberRegex.test(char)) { + analysis.numberCount += charMap[char]; + } else if (symbolRegex.test(char)) { + analysis.symbolCount += charMap[char]; + } + }); + return analysis; +} + +function scorePassword(analysis, scoringOptions) { + var points = 0; + points += analysis.uniqueChars * scoringOptions.pointsPerUnique; + points += (analysis.length - analysis.uniqueChars) * scoringOptions.pointsPerRepeat; + + if (analysis.lowercaseCount > 0) { + points += scoringOptions.pointsForContainingLower; + } + + if (analysis.uppercaseCount > 0) { + points += scoringOptions.pointsForContainingUpper; + } + + if (analysis.numberCount > 0) { + points += scoringOptions.pointsForContainingNumber; + } + + if (analysis.symbolCount > 0) { + points += scoringOptions.pointsForContainingSymbol; + } + + return points; +} + +function isStrongPassword(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + (0, _assertString.default)(str); + var analysis = analyzePassword(str); + options = (0, _merge.default)(options || {}, defaultOptions); + + if (options.returnScore) { + return scorePassword(analysis, options); + } + + return analysis.length >= options.minLength && analysis.lowercaseCount >= options.minLowercase && analysis.uppercaseCount >= options.minUppercase && analysis.numberCount >= options.minNumbers && analysis.symbolCount >= options.minSymbols; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isSurrogatePair.js b/node_modules/validator/lib/isSurrogatePair.js new file mode 100644 index 0000000..ee5678b --- /dev/null +++ b/node_modules/validator/lib/isSurrogatePair.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isSurrogatePair; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/; + +function isSurrogatePair(str) { + (0, _assertString.default)(str); + return surrogatePair.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isTaxID.js b/node_modules/validator/lib/isTaxID.js new file mode 100644 index 0000000..2a893b7 --- /dev/null +++ b/node_modules/validator/lib/isTaxID.js @@ -0,0 +1,1528 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isTaxID; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var algorithms = _interopRequireWildcard(require("./util/algorithms")); + +var _isDate = _interopRequireDefault(require("./isDate")); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +/** + * TIN Validation + * Validates Tax Identification Numbers (TINs) from the US, EU member states and the United Kingdom. + * + * EU-UK: + * National TIN validity is calculated using public algorithms as made available by DG TAXUD. + * + * See `https://ec.europa.eu/taxation_customs/tin/specs/FS-TIN%20Algorithms-Public.docx` for more information. + * + * US: + * An Employer Identification Number (EIN), also known as a Federal Tax Identification Number, + * is used to identify a business entity. + * + * NOTES: + * - Prefix 47 is being reserved for future use + * - Prefixes 26, 27, 45, 46 and 47 were previously assigned by the Philadelphia campus. + * + * See `http://www.irs.gov/Businesses/Small-Businesses-&-Self-Employed/How-EINs-are-Assigned-and-Valid-EIN-Prefixes` + * for more information. + */ +// Locale functions + +/* + * bg-BG validation function + * (Edinen graždanski nomer (EGN/ЕГН), persons only) + * Checks if birth date (first six digits) is valid and calculates check (last) digit + */ +function bgBgCheck(tin) { + // Extract full year, normalize month and check birth date validity + var century_year = tin.slice(0, 2); + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 40) { + month -= 40; + century_year = "20".concat(century_year); + } else if (month > 20) { + month -= 20; + century_year = "18".concat(century_year); + } else { + century_year = "19".concat(century_year); + } + + if (month < 10) { + month = "0".concat(month); + } + + var date = "".concat(century_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) { + return false; + } // split digits into an array for further processing + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); // Calculate checksum by multiplying digits with fixed values + + var multip_lookup = [2, 4, 8, 5, 10, 9, 7, 3, 6]; + var checksum = 0; + + for (var i = 0; i < multip_lookup.length; i++) { + checksum += digits[i] * multip_lookup[i]; + } + + checksum = checksum % 11 === 10 ? 0 : checksum % 11; + return checksum === digits[9]; +} +/* + * cs-CZ validation function + * (Rodné číslo (RČ), persons only) + * Checks if birth date (first six digits) is valid and divisibility by 11 + * Material not in DG TAXUD document sourced from: + * -`https://lorenc.info/3MA381/overeni-spravnosti-rodneho-cisla.htm` + * -`https://www.mvcr.cz/clanek/rady-a-sluzby-dokumenty-rodne-cislo.aspx` + */ + + +function csCzCheck(tin) { + tin = tin.replace(/\W/, ''); // Extract full year from TIN length + + var full_year = parseInt(tin.slice(0, 2), 10); + + if (tin.length === 10) { + if (full_year < 54) { + full_year = "20".concat(full_year); + } else { + full_year = "19".concat(full_year); + } + } else { + if (tin.slice(6) === '000') { + return false; + } // Three-zero serial not assigned before 1954 + + + if (full_year < 54) { + full_year = "19".concat(full_year); + } else { + return false; // No 18XX years seen in any of the resources + } + } // Add missing zero if needed + + + if (full_year.length === 3) { + full_year = [full_year.slice(0, 2), '0', full_year.slice(2)].join(''); + } // Extract month from TIN and normalize + + + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 50) { + month -= 50; + } + + if (month > 20) { + // Month-plus-twenty was only introduced in 2004 + if (parseInt(full_year, 10) < 2004) { + return false; + } + + month -= 20; + } + + if (month < 10) { + month = "0".concat(month); + } // Check date validity + + + var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) { + return false; + } // Verify divisibility by 11 + + + if (tin.length === 10) { + if (parseInt(tin, 10) % 11 !== 0) { + // Some numbers up to and including 1985 are still valid if + // check (last) digit equals 0 and modulo of first 9 digits equals 10 + var checkdigit = parseInt(tin.slice(0, 9), 10) % 11; + + if (parseInt(full_year, 10) < 1986 && checkdigit === 10) { + if (parseInt(tin.slice(9), 10) !== 0) { + return false; + } + } else { + return false; + } + } + } + + return true; +} +/* + * de-AT validation function + * (Abgabenkontonummer, persons/entities) + * Verify TIN validity by calling luhnCheck() + */ + + +function deAtCheck(tin) { + return algorithms.luhnCheck(tin); +} +/* + * de-DE validation function + * (Steueridentifikationsnummer (Steuer-IdNr.), persons only) + * Tests for single duplicate/triplicate value, then calculates ISO 7064 check (last) digit + * Partial implementation of spec (same result with both algorithms always) + */ + + +function deDeCheck(tin) { + // Split digits into an array for further processing + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); // Fill array with strings of number positions + + var occurences = []; + + for (var i = 0; i < digits.length - 1; i++) { + occurences.push(''); + + for (var j = 0; j < digits.length - 1; j++) { + if (digits[i] === digits[j]) { + occurences[i] += j; + } + } + } // Remove digits with one occurence and test for only one duplicate/triplicate + + + occurences = occurences.filter(function (a) { + return a.length > 1; + }); + + if (occurences.length !== 2 && occurences.length !== 3) { + return false; + } // In case of triplicate value only two digits are allowed next to each other + + + if (occurences[0].length === 3) { + var trip_locations = occurences[0].split('').map(function (a) { + return parseInt(a, 10); + }); + var recurrent = 0; // Amount of neighbour occurences + + for (var _i = 0; _i < trip_locations.length - 1; _i++) { + if (trip_locations[_i] + 1 === trip_locations[_i + 1]) { + recurrent += 1; + } + } + + if (recurrent === 2) { + return false; + } + } + + return algorithms.iso7064Check(tin); +} +/* + * dk-DK validation function + * (CPR-nummer (personnummer), persons only) + * Checks if birth date (first six digits) is valid and assigned to century (seventh) digit, + * and calculates check (last) digit + */ + + +function dkDkCheck(tin) { + tin = tin.replace(/\W/, ''); // Extract year, check if valid for given century digit and add century + + var year = parseInt(tin.slice(4, 6), 10); + var century_digit = tin.slice(6, 7); + + switch (century_digit) { + case '0': + case '1': + case '2': + case '3': + year = "19".concat(year); + break; + + case '4': + case '9': + if (year < 37) { + year = "20".concat(year); + } else { + year = "19".concat(year); + } + + break; + + default: + if (year < 37) { + year = "20".concat(year); + } else if (year > 58) { + year = "18".concat(year); + } else { + return false; + } + + break; + } // Add missing zero if needed + + + if (year.length === 3) { + year = [year.slice(0, 2), '0', year.slice(2)].join(''); + } // Check date validity + + + var date = "".concat(year, "/").concat(tin.slice(2, 4), "/").concat(tin.slice(0, 2)); + + if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) { + return false; + } // Split digits into an array for further processing + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; + var weight = 4; // Multiply by weight and add to checksum + + for (var i = 0; i < 9; i++) { + checksum += digits[i] * weight; + weight -= 1; + + if (weight === 1) { + weight = 7; + } + } + + checksum %= 11; + + if (checksum === 1) { + return false; + } + + return checksum === 0 ? digits[9] === 0 : digits[9] === 11 - checksum; +} +/* + * el-CY validation function + * (Arithmos Forologikou Mitroou (AFM/ΑΦΜ), persons only) + * Verify TIN validity by calculating ASCII value of check (last) character + */ + + +function elCyCheck(tin) { + // split digits into an array for further processing + var digits = tin.slice(0, 8).split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; // add digits in even places + + for (var i = 1; i < digits.length; i += 2) { + checksum += digits[i]; + } // add digits in odd places + + + for (var _i2 = 0; _i2 < digits.length; _i2 += 2) { + if (digits[_i2] < 2) { + checksum += 1 - digits[_i2]; + } else { + checksum += 2 * (digits[_i2] - 2) + 5; + + if (digits[_i2] > 4) { + checksum += 2; + } + } + } + + return String.fromCharCode(checksum % 26 + 65) === tin.charAt(8); +} +/* + * el-GR validation function + * (Arithmos Forologikou Mitroou (AFM/ΑΦΜ), persons/entities) + * Verify TIN validity by calculating check (last) digit + * Algorithm not in DG TAXUD document- sourced from: + * - `http://epixeirisi.gr/%CE%9A%CE%A1%CE%99%CE%A3%CE%99%CE%9C%CE%91-%CE%98%CE%95%CE%9C%CE%91%CE%A4%CE%91-%CE%A6%CE%9F%CE%A1%CE%9F%CE%9B%CE%9F%CE%93%CE%99%CE%91%CE%A3-%CE%9A%CE%91%CE%99-%CE%9B%CE%9F%CE%93%CE%99%CE%A3%CE%A4%CE%99%CE%9A%CE%97%CE%A3/23791/%CE%91%CF%81%CE%B9%CE%B8%CE%BC%CF%8C%CF%82-%CE%A6%CE%BF%CF%81%CE%BF%CE%BB%CE%BF%CE%B3%CE%B9%CE%BA%CE%BF%CF%8D-%CE%9C%CE%B7%CF%84%CF%81%CF%8E%CE%BF%CF%85` + */ + + +function elGrCheck(tin) { + // split digits into an array for further processing + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; + + for (var i = 0; i < 8; i++) { + checksum += digits[i] * Math.pow(2, 8 - i); + } + + return checksum % 11 % 10 === digits[8]; +} +/* + * en-GB validation function (should go here if needed) + * (National Insurance Number (NINO) or Unique Taxpayer Reference (UTR), + * persons/entities respectively) + */ + +/* + * en-IE validation function + * (Personal Public Service Number (PPS No), persons only) + * Verify TIN validity by calculating check (second to last) character + */ + + +function enIeCheck(tin) { + var checksum = algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 7).map(function (a) { + return parseInt(a, 10); + }), 8); + + if (tin.length === 9 && tin[8] !== 'W') { + checksum += (tin[8].charCodeAt(0) - 64) * 9; + } + + checksum %= 23; + + if (checksum === 0) { + return tin[7].toUpperCase() === 'W'; + } + + return tin[7].toUpperCase() === String.fromCharCode(64 + checksum); +} // Valid US IRS campus prefixes + + +var enUsCampusPrefix = { + andover: ['10', '12'], + atlanta: ['60', '67'], + austin: ['50', '53'], + brookhaven: ['01', '02', '03', '04', '05', '06', '11', '13', '14', '16', '21', '22', '23', '25', '34', '51', '52', '54', '55', '56', '57', '58', '59', '65'], + cincinnati: ['30', '32', '35', '36', '37', '38', '61'], + fresno: ['15', '24'], + internet: ['20', '26', '27', '45', '46', '47'], + kansas: ['40', '44'], + memphis: ['94', '95'], + ogden: ['80', '90'], + philadelphia: ['33', '39', '41', '42', '43', '46', '48', '62', '63', '64', '66', '68', '71', '72', '73', '74', '75', '76', '77', '81', '82', '83', '84', '85', '86', '87', '88', '91', '92', '93', '98', '99'], + sba: ['31'] +}; // Return an array of all US IRS campus prefixes + +function enUsGetPrefixes() { + var prefixes = []; + + for (var location in enUsCampusPrefix) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (enUsCampusPrefix.hasOwnProperty(location)) { + prefixes.push.apply(prefixes, _toConsumableArray(enUsCampusPrefix[location])); + } + } + + return prefixes; +} +/* + * en-US validation function + * Verify that the TIN starts with a valid IRS campus prefix + */ + + +function enUsCheck(tin) { + return enUsGetPrefixes().indexOf(tin.substr(0, 2)) !== -1; +} +/* + * es-ES validation function + * (Documento Nacional de Identidad (DNI) + * or Número de Identificación de Extranjero (NIE), persons only) + * Verify TIN validity by calculating check (last) character + */ + + +function esEsCheck(tin) { + // Split characters into an array for further processing + var chars = tin.toUpperCase().split(''); // Replace initial letter if needed + + if (isNaN(parseInt(chars[0], 10)) && chars.length > 1) { + var lead_replace = 0; + + switch (chars[0]) { + case 'Y': + lead_replace = 1; + break; + + case 'Z': + lead_replace = 2; + break; + + default: + } + + chars.splice(0, 1, lead_replace); // Fill with zeros if smaller than proper + } else { + while (chars.length < 9) { + chars.unshift(0); + } + } // Calculate checksum and check according to lookup + + + var lookup = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E']; + chars = chars.join(''); + var checksum = parseInt(chars.slice(0, 8), 10) % 23; + return chars[8] === lookup[checksum]; +} +/* + * et-EE validation function + * (Isikukood (IK), persons only) + * Checks if birth date (century digit and six following) is valid and calculates check (last) digit + * Material not in DG TAXUD document sourced from: + * - `https://www.oecd.org/tax/automatic-exchange/crs-implementation-and-assistance/tax-identification-numbers/Estonia-TIN.pdf` + */ + + +function etEeCheck(tin) { + // Extract year and add century + var full_year = tin.slice(1, 3); + var century_digit = tin.slice(0, 1); + + switch (century_digit) { + case '1': + case '2': + full_year = "18".concat(full_year); + break; + + case '3': + case '4': + full_year = "19".concat(full_year); + break; + + default: + full_year = "20".concat(full_year); + break; + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(3, 5), "/").concat(tin.slice(5, 7)); + + if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) { + return false; + } // Split digits into an array for further processing + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; + var weight = 1; // Multiply by weight and add to checksum + + for (var i = 0; i < 10; i++) { + checksum += digits[i] * weight; + weight += 1; + + if (weight === 10) { + weight = 1; + } + } // Do again if modulo 11 of checksum is 10 + + + if (checksum % 11 === 10) { + checksum = 0; + weight = 3; + + for (var _i3 = 0; _i3 < 10; _i3++) { + checksum += digits[_i3] * weight; + weight += 1; + + if (weight === 10) { + weight = 1; + } + } + + if (checksum % 11 === 10) { + return digits[10] === 0; + } + } + + return checksum % 11 === digits[10]; +} +/* + * fi-FI validation function + * (Henkilötunnus (HETU), persons only) + * Checks if birth date (first six digits plus century symbol) is valid + * and calculates check (last) digit + */ + + +function fiFiCheck(tin) { + // Extract year and add century + var full_year = tin.slice(4, 6); + var century_symbol = tin.slice(6, 7); + + switch (century_symbol) { + case '+': + full_year = "18".concat(full_year); + break; + + case '-': + full_year = "19".concat(full_year); + break; + + default: + full_year = "20".concat(full_year); + break; + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(2, 4), "/").concat(tin.slice(0, 2)); + + if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) { + return false; + } // Calculate check character + + + var checksum = parseInt(tin.slice(0, 6) + tin.slice(7, 10), 10) % 31; + + if (checksum < 10) { + return checksum === parseInt(tin.slice(10), 10); + } + + checksum -= 10; + var letters_lookup = ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y']; + return letters_lookup[checksum] === tin.slice(10); +} +/* + * fr/nl-BE validation function + * (Numéro national (N.N.), persons only) + * Checks if birth date (first six digits) is valid and calculates check (last two) digits + */ + + +function frBeCheck(tin) { + // Zero month/day value is acceptable + if (tin.slice(2, 4) !== '00' || tin.slice(4, 6) !== '00') { + // Extract date from first six digits of TIN + var date = "".concat(tin.slice(0, 2), "/").concat(tin.slice(2, 4), "/").concat(tin.slice(4, 6)); + + if (!(0, _isDate.default)(date, 'YY/MM/DD')) { + return false; + } + } + + var checksum = 97 - parseInt(tin.slice(0, 9), 10) % 97; + var checkdigits = parseInt(tin.slice(9, 11), 10); + + if (checksum !== checkdigits) { + checksum = 97 - parseInt("2".concat(tin.slice(0, 9)), 10) % 97; + + if (checksum !== checkdigits) { + return false; + } + } + + return true; +} +/* + * fr-FR validation function + * (Numéro fiscal de référence (numéro SPI), persons only) + * Verify TIN validity by calculating check (last three) digits + */ + + +function frFrCheck(tin) { + tin = tin.replace(/\s/g, ''); + var checksum = parseInt(tin.slice(0, 10), 10) % 511; + var checkdigits = parseInt(tin.slice(10, 13), 10); + return checksum === checkdigits; +} +/* + * fr/lb-LU validation function + * (numéro d’identification personnelle, persons only) + * Verify birth date validity and run Luhn and Verhoeff checks + */ + + +function frLuCheck(tin) { + // Extract date and check validity + var date = "".concat(tin.slice(0, 4), "/").concat(tin.slice(4, 6), "/").concat(tin.slice(6, 8)); + + if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) { + return false; + } // Run Luhn check + + + if (!algorithms.luhnCheck(tin.slice(0, 12))) { + return false; + } // Remove Luhn check digit and run Verhoeff check + + + return algorithms.verhoeffCheck("".concat(tin.slice(0, 11)).concat(tin[12])); +} +/* + * hr-HR validation function + * (Osobni identifikacijski broj (OIB), persons/entities) + * Verify TIN validity by calling iso7064Check(digits) + */ + + +function hrHrCheck(tin) { + return algorithms.iso7064Check(tin); +} +/* + * hu-HU validation function + * (Adóazonosító jel, persons only) + * Verify TIN validity by calculating check (last) digit + */ + + +function huHuCheck(tin) { + // split digits into an array for further processing + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 8; + + for (var i = 1; i < 9; i++) { + checksum += digits[i] * (i + 1); + } + + return checksum % 11 === digits[9]; +} +/* + * lt-LT validation function (should go here if needed) + * (Asmens kodas, persons/entities respectively) + * Current validation check is alias of etEeCheck- same format applies + */ + +/* + * it-IT first/last name validity check + * Accepts it-IT TIN-encoded names as a three-element character array and checks their validity + * Due to lack of clarity between resources ("Are only Italian consonants used? + * What happens if a person has X in their name?" etc.) only two test conditions + * have been implemented: + * Vowels may only be followed by other vowels or an X character + * and X characters after vowels may only be followed by other X characters. + */ + + +function itItNameCheck(name) { + // true at the first occurence of a vowel + var vowelflag = false; // true at the first occurence of an X AFTER vowel + // (to properly handle last names with X as consonant) + + var xflag = false; + + for (var i = 0; i < 3; i++) { + if (!vowelflag && /[AEIOU]/.test(name[i])) { + vowelflag = true; + } else if (!xflag && vowelflag && name[i] === 'X') { + xflag = true; + } else if (i > 0) { + if (vowelflag && !xflag) { + if (!/[AEIOU]/.test(name[i])) { + return false; + } + } + + if (xflag) { + if (!/X/.test(name[i])) { + return false; + } + } + } + } + + return true; +} +/* + * it-IT validation function + * (Codice fiscale (TIN-IT), persons only) + * Verify name, birth date and codice catastale validity + * and calculate check character. + * Material not in DG-TAXUD document sourced from: + * `https://en.wikipedia.org/wiki/Italian_fiscal_code` + */ + + +function itItCheck(tin) { + // Capitalize and split characters into an array for further processing + var chars = tin.toUpperCase().split(''); // Check first and last name validity calling itItNameCheck() + + if (!itItNameCheck(chars.slice(0, 3))) { + return false; + } + + if (!itItNameCheck(chars.slice(3, 6))) { + return false; + } // Convert letters in number spaces back to numbers if any + + + var number_locations = [6, 7, 9, 10, 12, 13, 14]; + var number_replace = { + L: '0', + M: '1', + N: '2', + P: '3', + Q: '4', + R: '5', + S: '6', + T: '7', + U: '8', + V: '9' + }; + + for (var _i4 = 0, _number_locations = number_locations; _i4 < _number_locations.length; _i4++) { + var i = _number_locations[_i4]; + + if (chars[i] in number_replace) { + chars.splice(i, 1, number_replace[chars[i]]); + } + } // Extract month and day, and check date validity + + + var month_replace = { + A: '01', + B: '02', + C: '03', + D: '04', + E: '05', + H: '06', + L: '07', + M: '08', + P: '09', + R: '10', + S: '11', + T: '12' + }; + var month = month_replace[chars[8]]; + var day = parseInt(chars[9] + chars[10], 10); + + if (day > 40) { + day -= 40; + } + + if (day < 10) { + day = "0".concat(day); + } + + var date = "".concat(chars[6]).concat(chars[7], "/").concat(month, "/").concat(day); + + if (!(0, _isDate.default)(date, 'YY/MM/DD')) { + return false; + } // Calculate check character by adding up even and odd characters as numbers + + + var checksum = 0; + + for (var _i5 = 1; _i5 < chars.length - 1; _i5 += 2) { + var char_to_int = parseInt(chars[_i5], 10); + + if (isNaN(char_to_int)) { + char_to_int = chars[_i5].charCodeAt(0) - 65; + } + + checksum += char_to_int; + } + + var odd_convert = { + // Maps of characters at odd places + A: 1, + B: 0, + C: 5, + D: 7, + E: 9, + F: 13, + G: 15, + H: 17, + I: 19, + J: 21, + K: 2, + L: 4, + M: 18, + N: 20, + O: 11, + P: 3, + Q: 6, + R: 8, + S: 12, + T: 14, + U: 16, + V: 10, + W: 22, + X: 25, + Y: 24, + Z: 23, + 0: 1, + 1: 0 + }; + + for (var _i6 = 0; _i6 < chars.length - 1; _i6 += 2) { + var _char_to_int = 0; + + if (chars[_i6] in odd_convert) { + _char_to_int = odd_convert[chars[_i6]]; + } else { + var multiplier = parseInt(chars[_i6], 10); + _char_to_int = 2 * multiplier + 1; + + if (multiplier > 4) { + _char_to_int += 2; + } + } + + checksum += _char_to_int; + } + + if (String.fromCharCode(65 + checksum % 26) !== chars[15]) { + return false; + } + + return true; +} +/* + * lv-LV validation function + * (Personas kods (PK), persons only) + * Check validity of birth date and calculate check (last) digit + * Support only for old format numbers (not starting with '32', issued before 2017/07/01) + * Material not in DG TAXUD document sourced from: + * `https://boot.ritakafija.lv/forums/index.php?/topic/88314-personas-koda-algoritms-%C4%8Deksumma/` + */ + + +function lvLvCheck(tin) { + tin = tin.replace(/\W/, ''); // Extract date from TIN + + var day = tin.slice(0, 2); + + if (day !== '32') { + // No date/checksum check if new format + var month = tin.slice(2, 4); + + if (month !== '00') { + // No date check if unknown month + var full_year = tin.slice(4, 6); + + switch (tin[6]) { + case '0': + full_year = "18".concat(full_year); + break; + + case '1': + full_year = "19".concat(full_year); + break; + + default: + full_year = "20".concat(full_year); + break; + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(2, 4), "/").concat(day); + + if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) { + return false; + } + } // Calculate check digit + + + var checksum = 1101; + var multip_lookup = [1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; + + for (var i = 0; i < tin.length - 1; i++) { + checksum -= parseInt(tin[i], 10) * multip_lookup[i]; + } + + return parseInt(tin[10], 10) === checksum % 11; + } + + return true; +} +/* + * mt-MT validation function + * (Identity Card Number or Unique Taxpayer Reference, persons/entities) + * Verify Identity Card Number structure (no other tests found) + */ + + +function mtMtCheck(tin) { + if (tin.length !== 9) { + // No tests for UTR + var chars = tin.toUpperCase().split(''); // Fill with zeros if smaller than proper + + while (chars.length < 8) { + chars.unshift(0); + } // Validate format according to last character + + + switch (tin[7]) { + case 'A': + case 'P': + if (parseInt(chars[6], 10) === 0) { + return false; + } + + break; + + default: + { + var first_part = parseInt(chars.join('').slice(0, 5), 10); + + if (first_part > 32000) { + return false; + } + + var second_part = parseInt(chars.join('').slice(5, 7), 10); + + if (first_part === second_part) { + return false; + } + } + } + } + + return true; +} +/* + * nl-NL validation function + * (Burgerservicenummer (BSN) or Rechtspersonen Samenwerkingsverbanden Informatie Nummer (RSIN), + * persons/entities respectively) + * Verify TIN validity by calculating check (last) digit (variant of MOD 11) + */ + + +function nlNlCheck(tin) { + return algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 8).map(function (a) { + return parseInt(a, 10); + }), 9) % 11 === parseInt(tin[8], 10); +} +/* + * pl-PL validation function + * (Powszechny Elektroniczny System Ewidencji Ludności (PESEL) + * or Numer identyfikacji podatkowej (NIP), persons/entities) + * Verify TIN validity by validating birth date (PESEL) and calculating check (last) digit + */ + + +function plPlCheck(tin) { + // NIP + if (tin.length === 10) { + // Calculate last digit by multiplying with lookup + var lookup = [6, 5, 7, 2, 3, 4, 5, 6, 7]; + var _checksum = 0; + + for (var i = 0; i < lookup.length; i++) { + _checksum += parseInt(tin[i], 10) * lookup[i]; + } + + _checksum %= 11; + + if (_checksum === 10) { + return false; + } + + return _checksum === parseInt(tin[9], 10); + } // PESEL + // Extract full year using month + + + var full_year = tin.slice(0, 2); + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 80) { + full_year = "18".concat(full_year); + month -= 80; + } else if (month > 60) { + full_year = "22".concat(full_year); + month -= 60; + } else if (month > 40) { + full_year = "21".concat(full_year); + month -= 40; + } else if (month > 20) { + full_year = "20".concat(full_year); + month -= 20; + } else { + full_year = "19".concat(full_year); + } // Add leading zero to month if needed + + + if (month < 10) { + month = "0".concat(month); + } // Check date validity + + + var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) { + return false; + } // Calculate last digit by mulitplying with odd one-digit numbers except 5 + + + var checksum = 0; + var multiplier = 1; + + for (var _i7 = 0; _i7 < tin.length - 1; _i7++) { + checksum += parseInt(tin[_i7], 10) * multiplier % 10; + multiplier += 2; + + if (multiplier > 10) { + multiplier = 1; + } else if (multiplier === 5) { + multiplier += 2; + } + } + + checksum = 10 - checksum % 10; + return checksum === parseInt(tin[10], 10); +} +/* +* pt-BR validation function +* (Cadastro de Pessoas Físicas (CPF, persons) +* Cadastro Nacional de Pessoas Jurídicas (CNPJ, entities) +* Both inputs will be validated +*/ + + +function ptBrCheck(tin) { + if (tin.length === 11) { + var _sum; + + var remainder; + _sum = 0; + if ( // Reject known invalid CPFs + tin === '11111111111' || tin === '22222222222' || tin === '33333333333' || tin === '44444444444' || tin === '55555555555' || tin === '66666666666' || tin === '77777777777' || tin === '88888888888' || tin === '99999999999' || tin === '00000000000') return false; + + for (var i = 1; i <= 9; i++) { + _sum += parseInt(tin.substring(i - 1, i), 10) * (11 - i); + } + + remainder = _sum * 10 % 11; + if (remainder === 10) remainder = 0; + if (remainder !== parseInt(tin.substring(9, 10), 10)) return false; + _sum = 0; + + for (var _i8 = 1; _i8 <= 10; _i8++) { + _sum += parseInt(tin.substring(_i8 - 1, _i8), 10) * (12 - _i8); + } + + remainder = _sum * 10 % 11; + if (remainder === 10) remainder = 0; + if (remainder !== parseInt(tin.substring(10, 11), 10)) return false; + return true; + } + + if ( // Reject know invalid CNPJs + tin === '00000000000000' || tin === '11111111111111' || tin === '22222222222222' || tin === '33333333333333' || tin === '44444444444444' || tin === '55555555555555' || tin === '66666666666666' || tin === '77777777777777' || tin === '88888888888888' || tin === '99999999999999') { + return false; + } + + var length = tin.length - 2; + var identifiers = tin.substring(0, length); + var verificators = tin.substring(length); + var sum = 0; + var pos = length - 7; + + for (var _i9 = length; _i9 >= 1; _i9--) { + sum += identifiers.charAt(length - _i9) * pos; + pos -= 1; + + if (pos < 2) { + pos = 9; + } + } + + var result = sum % 11 < 2 ? 0 : 11 - sum % 11; + + if (result !== parseInt(verificators.charAt(0), 10)) { + return false; + } + + length += 1; + identifiers = tin.substring(0, length); + sum = 0; + pos = length - 7; + + for (var _i10 = length; _i10 >= 1; _i10--) { + sum += identifiers.charAt(length - _i10) * pos; + pos -= 1; + + if (pos < 2) { + pos = 9; + } + } + + result = sum % 11 < 2 ? 0 : 11 - sum % 11; + + if (result !== parseInt(verificators.charAt(1), 10)) { + return false; + } + + return true; +} +/* + * pt-PT validation function + * (Número de identificação fiscal (NIF), persons/entities) + * Verify TIN validity by calculating check (last) digit (variant of MOD 11) + */ + + +function ptPtCheck(tin) { + var checksum = 11 - algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 8).map(function (a) { + return parseInt(a, 10); + }), 9) % 11; + + if (checksum > 9) { + return parseInt(tin[8], 10) === 0; + } + + return checksum === parseInt(tin[8], 10); +} +/* + * ro-RO validation function + * (Cod Numeric Personal (CNP) or Cod de înregistrare fiscală (CIF), + * persons only) + * Verify CNP validity by calculating check (last) digit (test not found for CIF) + * Material not in DG TAXUD document sourced from: + * `https://en.wikipedia.org/wiki/National_identification_number#Romania` + */ + + +function roRoCheck(tin) { + if (tin.slice(0, 4) !== '9000') { + // No test found for this format + // Extract full year using century digit if possible + var full_year = tin.slice(1, 3); + + switch (tin[0]) { + case '1': + case '2': + full_year = "19".concat(full_year); + break; + + case '3': + case '4': + full_year = "18".concat(full_year); + break; + + case '5': + case '6': + full_year = "20".concat(full_year); + break; + + default: + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(3, 5), "/").concat(tin.slice(5, 7)); + + if (date.length === 8) { + if (!(0, _isDate.default)(date, 'YY/MM/DD')) { + return false; + } + } else if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) { + return false; + } // Calculate check digit + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var multipliers = [2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9]; + var checksum = 0; + + for (var i = 0; i < multipliers.length; i++) { + checksum += digits[i] * multipliers[i]; + } + + if (checksum % 11 === 10) { + return digits[12] === 1; + } + + return digits[12] === checksum % 11; + } + + return true; +} +/* + * sk-SK validation function + * (Rodné číslo (RČ) or bezvýznamové identifikačné číslo (BIČ), persons only) + * Checks validity of pre-1954 birth numbers (rodné číslo) only + * Due to the introduction of the pseudo-random BIČ it is not possible to test + * post-1954 birth numbers without knowing whether they are BIČ or RČ beforehand + */ + + +function skSkCheck(tin) { + if (tin.length === 9) { + tin = tin.replace(/\W/, ''); + + if (tin.slice(6) === '000') { + return false; + } // Three-zero serial not assigned before 1954 + // Extract full year from TIN length + + + var full_year = parseInt(tin.slice(0, 2), 10); + + if (full_year > 53) { + return false; + } + + if (full_year < 10) { + full_year = "190".concat(full_year); + } else { + full_year = "19".concat(full_year); + } // Extract month from TIN and normalize + + + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 50) { + month -= 50; + } + + if (month < 10) { + month = "0".concat(month); + } // Check date validity + + + var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) { + return false; + } + } + + return true; +} +/* + * sl-SI validation function + * (Davčna številka, persons/entities) + * Verify TIN validity by calculating check (last) digit (variant of MOD 11) + */ + + +function slSiCheck(tin) { + var checksum = 11 - algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 7).map(function (a) { + return parseInt(a, 10); + }), 8) % 11; + + if (checksum === 10) { + return parseInt(tin[7], 10) === 0; + } + + return checksum === parseInt(tin[7], 10); +} +/* + * sv-SE validation function + * (Personnummer or samordningsnummer, persons only) + * Checks validity of birth date and calls luhnCheck() to validate check (last) digit + */ + + +function svSeCheck(tin) { + // Make copy of TIN and normalize to two-digit year form + var tin_copy = tin.slice(0); + + if (tin.length > 11) { + tin_copy = tin_copy.slice(2); + } // Extract date of birth + + + var full_year = ''; + var month = tin_copy.slice(2, 4); + var day = parseInt(tin_copy.slice(4, 6), 10); + + if (tin.length > 11) { + full_year = tin.slice(0, 4); + } else { + full_year = tin.slice(0, 2); + + if (tin.length === 11 && day < 60) { + // Extract full year from centenarian symbol + // Should work just fine until year 10000 or so + var current_year = new Date().getFullYear().toString(); + var current_century = parseInt(current_year.slice(0, 2), 10); + current_year = parseInt(current_year, 10); + + if (tin[6] === '-') { + if (parseInt("".concat(current_century).concat(full_year), 10) > current_year) { + full_year = "".concat(current_century - 1).concat(full_year); + } else { + full_year = "".concat(current_century).concat(full_year); + } + } else { + full_year = "".concat(current_century - 1).concat(full_year); + + if (current_year - parseInt(full_year, 10) < 100) { + return false; + } + } + } + } // Normalize day and check date validity + + + if (day > 60) { + day -= 60; + } + + if (day < 10) { + day = "0".concat(day); + } + + var date = "".concat(full_year, "/").concat(month, "/").concat(day); + + if (date.length === 8) { + if (!(0, _isDate.default)(date, 'YY/MM/DD')) { + return false; + } + } else if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) { + return false; + } + + return algorithms.luhnCheck(tin.replace(/\W/, '')); +} // Locale lookup objects + +/* + * Tax id regex formats for various locales + * + * Where not explicitly specified in DG-TAXUD document both + * uppercase and lowercase letters are acceptable. + */ + + +var taxIdFormat = { + 'bg-BG': /^\d{10}$/, + 'cs-CZ': /^\d{6}\/{0,1}\d{3,4}$/, + 'de-AT': /^\d{9}$/, + 'de-DE': /^[1-9]\d{10}$/, + 'dk-DK': /^\d{6}-{0,1}\d{4}$/, + 'el-CY': /^[09]\d{7}[A-Z]$/, + 'el-GR': /^([0-4]|[7-9])\d{8}$/, + 'en-GB': /^\d{10}$|^(?!GB|NK|TN|ZZ)(?![DFIQUV])[A-Z](?![DFIQUVO])[A-Z]\d{6}[ABCD ]$/i, + 'en-IE': /^\d{7}[A-W][A-IW]{0,1}$/i, + 'en-US': /^\d{2}[- ]{0,1}\d{7}$/, + 'es-ES': /^(\d{0,8}|[XYZKLM]\d{7})[A-HJ-NP-TV-Z]$/i, + 'et-EE': /^[1-6]\d{6}(00[1-9]|0[1-9][0-9]|[1-6][0-9]{2}|70[0-9]|710)\d$/, + 'fi-FI': /^\d{6}[-+A]\d{3}[0-9A-FHJ-NPR-Y]$/i, + 'fr-BE': /^\d{11}$/, + 'fr-FR': /^[0-3]\d{12}$|^[0-3]\d\s\d{2}(\s\d{3}){3}$/, + // Conforms both to official spec and provided example + 'fr-LU': /^\d{13}$/, + 'hr-HR': /^\d{11}$/, + 'hu-HU': /^8\d{9}$/, + 'it-IT': /^[A-Z]{6}[L-NP-V0-9]{2}[A-EHLMPRST][L-NP-V0-9]{2}[A-ILMZ][L-NP-V0-9]{3}[A-Z]$/i, + 'lv-LV': /^\d{6}-{0,1}\d{5}$/, + // Conforms both to DG TAXUD spec and original research + 'mt-MT': /^\d{3,7}[APMGLHBZ]$|^([1-8])\1\d{7}$/i, + 'nl-NL': /^\d{9}$/, + 'pl-PL': /^\d{10,11}$/, + 'pt-BR': /(?:^\d{11}$)|(?:^\d{14}$)/, + 'pt-PT': /^\d{9}$/, + 'ro-RO': /^\d{13}$/, + 'sk-SK': /^\d{6}\/{0,1}\d{3,4}$/, + 'sl-SI': /^[1-9]\d{7}$/, + 'sv-SE': /^(\d{6}[-+]{0,1}\d{4}|(18|19|20)\d{6}[-+]{0,1}\d{4})$/ +}; // taxIdFormat locale aliases + +taxIdFormat['lb-LU'] = taxIdFormat['fr-LU']; +taxIdFormat['lt-LT'] = taxIdFormat['et-EE']; +taxIdFormat['nl-BE'] = taxIdFormat['fr-BE']; // Algorithmic tax id check functions for various locales + +var taxIdCheck = { + 'bg-BG': bgBgCheck, + 'cs-CZ': csCzCheck, + 'de-AT': deAtCheck, + 'de-DE': deDeCheck, + 'dk-DK': dkDkCheck, + 'el-CY': elCyCheck, + 'el-GR': elGrCheck, + 'en-IE': enIeCheck, + 'en-US': enUsCheck, + 'es-ES': esEsCheck, + 'et-EE': etEeCheck, + 'fi-FI': fiFiCheck, + 'fr-BE': frBeCheck, + 'fr-FR': frFrCheck, + 'fr-LU': frLuCheck, + 'hr-HR': hrHrCheck, + 'hu-HU': huHuCheck, + 'it-IT': itItCheck, + 'lv-LV': lvLvCheck, + 'mt-MT': mtMtCheck, + 'nl-NL': nlNlCheck, + 'pl-PL': plPlCheck, + 'pt-BR': ptBrCheck, + 'pt-PT': ptPtCheck, + 'ro-RO': roRoCheck, + 'sk-SK': skSkCheck, + 'sl-SI': slSiCheck, + 'sv-SE': svSeCheck +}; // taxIdCheck locale aliases + +taxIdCheck['lb-LU'] = taxIdCheck['fr-LU']; +taxIdCheck['lt-LT'] = taxIdCheck['et-EE']; +taxIdCheck['nl-BE'] = taxIdCheck['fr-BE']; // Regexes for locales where characters should be omitted before checking format + +var allsymbols = /[-\\\/!@#$%\^&\*\(\)\+\=\[\]]+/g; +var sanitizeRegexes = { + 'de-AT': allsymbols, + 'de-DE': /[\/\\]/g, + 'fr-BE': allsymbols +}; // sanitizeRegexes locale aliases + +sanitizeRegexes['nl-BE'] = sanitizeRegexes['fr-BE']; +/* + * Validator function + * Return true if the passed string is a valid tax identification number + * for the specified locale. + * Throw an error exception if the locale is not supported. + */ + +function isTaxID(str) { + var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; + (0, _assertString.default)(str); // Copy TIN to avoid replacement if sanitized + + var strcopy = str.slice(0); + + if (locale in taxIdFormat) { + if (locale in sanitizeRegexes) { + strcopy = strcopy.replace(sanitizeRegexes[locale], ''); + } + + if (!taxIdFormat[locale].test(strcopy)) { + return false; + } + + if (locale in taxIdCheck) { + return taxIdCheck[locale](strcopy); + } // Fallthrough; not all locales have algorithmic checks + + + return true; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isURL.js b/node_modules/validator/lib/isURL.js new file mode 100644 index 0000000..b8d5e87 --- /dev/null +++ b/node_modules/validator/lib/isURL.js @@ -0,0 +1,208 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isURL; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _isFQDN = _interopRequireDefault(require("./isFQDN")); + +var _isIP = _interopRequireDefault(require("./isIP")); + +var _merge = _interopRequireDefault(require("./util/merge")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +/* +options for isURL method + +require_protocol - if set as true isURL will return false if protocol is not present in the URL +require_valid_protocol - isURL will check if the URL's protocol is present in the protocols option +protocols - valid protocols can be modified with this option +require_host - if set as false isURL will not check if host is present in the URL +require_port - if set as true isURL will check if port is present in the URL +allow_protocol_relative_urls - if set as true protocol relative URLs will be allowed +validate_length - if set as false isURL will skip string length validation (IE maximum is 2083) + +*/ +var default_url_options = { + protocols: ['http', 'https', 'ftp'], + require_tld: true, + require_protocol: false, + require_host: true, + require_port: false, + require_valid_protocol: true, + allow_underscores: false, + allow_trailing_dot: false, + allow_protocol_relative_urls: false, + allow_fragments: true, + allow_query_components: true, + validate_length: true +}; +var wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/; + +function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +} + +function checkHost(host, matches) { + for (var i = 0; i < matches.length; i++) { + var match = matches[i]; + + if (host === match || isRegExp(match) && match.test(host)) { + return true; + } + } + + return false; +} + +function isURL(url, options) { + (0, _assertString.default)(url); + + if (!url || /[\s<>]/.test(url)) { + return false; + } + + if (url.indexOf('mailto:') === 0) { + return false; + } + + options = (0, _merge.default)(options, default_url_options); + + if (options.validate_length && url.length >= 2083) { + return false; + } + + if (!options.allow_fragments && url.includes('#')) { + return false; + } + + if (!options.allow_query_components && (url.includes('?') || url.includes('&'))) { + return false; + } + + var protocol, auth, host, hostname, port, port_str, split, ipv6; + split = url.split('#'); + url = split.shift(); + split = url.split('?'); + url = split.shift(); + split = url.split('://'); + + if (split.length > 1) { + protocol = split.shift().toLowerCase(); + + if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) { + return false; + } + } else if (options.require_protocol) { + return false; + } else if (url.substr(0, 2) === '//') { + if (!options.allow_protocol_relative_urls) { + return false; + } + + split[0] = url.substr(2); + } + + url = split.join('://'); + + if (url === '') { + return false; + } + + split = url.split('/'); + url = split.shift(); + + if (url === '' && !options.require_host) { + return true; + } + + split = url.split('@'); + + if (split.length > 1) { + if (options.disallow_auth) { + return false; + } + + if (split[0] === '') { + return false; + } + + auth = split.shift(); + + if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) { + return false; + } + + var _auth$split = auth.split(':'), + _auth$split2 = _slicedToArray(_auth$split, 2), + user = _auth$split2[0], + password = _auth$split2[1]; + + if (user === '' && password === '') { + return false; + } + } + + hostname = split.join('@'); + port_str = null; + ipv6 = null; + var ipv6_match = hostname.match(wrapped_ipv6); + + if (ipv6_match) { + host = ''; + ipv6 = ipv6_match[1]; + port_str = ipv6_match[2] || null; + } else { + split = hostname.split(':'); + host = split.shift(); + + if (split.length) { + port_str = split.join(':'); + } + } + + if (port_str !== null && port_str.length > 0) { + port = parseInt(port_str, 10); + + if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) { + return false; + } + } else if (options.require_port) { + return false; + } + + if (options.host_whitelist) { + return checkHost(host, options.host_whitelist); + } + + if (!(0, _isIP.default)(host) && !(0, _isFQDN.default)(host, options) && (!ipv6 || !(0, _isIP.default)(ipv6, 6))) { + return false; + } + + host = host || ipv6; + + if (options.host_blacklist && checkHost(host, options.host_blacklist)) { + return false; + } + + return true; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isUUID.js b/node_modules/validator/lib/isUUID.js new file mode 100644 index 0000000..f2fdc79 --- /dev/null +++ b/node_modules/validator/lib/isUUID.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isUUID; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var uuid = { + 1: /^[0-9A-F]{8}-[0-9A-F]{4}-1[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + 2: /^[0-9A-F]{8}-[0-9A-F]{4}-2[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + 3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + 4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, + 5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, + all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i +}; + +function isUUID(str, version) { + (0, _assertString.default)(str); + var pattern = uuid[![undefined, null].includes(version) ? version : 'all']; + return !!pattern && pattern.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isUppercase.js b/node_modules/validator/lib/isUppercase.js new file mode 100644 index 0000000..c1c02f9 --- /dev/null +++ b/node_modules/validator/lib/isUppercase.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isUppercase; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isUppercase(str) { + (0, _assertString.default)(str); + return str === str.toUpperCase(); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isVAT.js b/node_modules/validator/lib/isVAT.js new file mode 100644 index 0000000..bfd7beb --- /dev/null +++ b/node_modules/validator/lib/isVAT.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isVAT; +exports.vatMatchers = void 0; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var vatMatchers = { + GB: /^GB((\d{3} \d{4} ([0-8][0-9]|9[0-6]))|(\d{9} \d{3})|(((GD[0-4])|(HA[5-9]))[0-9]{2}))$/, + IT: /^(IT)?[0-9]{11}$/, + NL: /^(NL)?[0-9]{9}B[0-9]{2}$/ +}; +exports.vatMatchers = vatMatchers; + +function isVAT(str, countryCode) { + (0, _assertString.default)(str); + (0, _assertString.default)(countryCode); + + if (countryCode in vatMatchers) { + return vatMatchers[countryCode].test(str); + } + + throw new Error("Invalid country code: '".concat(countryCode, "'")); +} \ No newline at end of file diff --git a/node_modules/validator/lib/isVariableWidth.js b/node_modules/validator/lib/isVariableWidth.js new file mode 100644 index 0000000..6bf226e --- /dev/null +++ b/node_modules/validator/lib/isVariableWidth.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isVariableWidth; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _isFullWidth = require("./isFullWidth"); + +var _isHalfWidth = require("./isHalfWidth"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isVariableWidth(str) { + (0, _assertString.default)(str); + return _isFullWidth.fullWidth.test(str) && _isHalfWidth.halfWidth.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/isWhitelisted.js b/node_modules/validator/lib/isWhitelisted.js new file mode 100644 index 0000000..5a80a1b --- /dev/null +++ b/node_modules/validator/lib/isWhitelisted.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isWhitelisted; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isWhitelisted(str, chars) { + (0, _assertString.default)(str); + + for (var i = str.length - 1; i >= 0; i--) { + if (chars.indexOf(str[i]) === -1) { + return false; + } + } + + return true; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/ltrim.js b/node_modules/validator/lib/ltrim.js new file mode 100644 index 0000000..fc39160 --- /dev/null +++ b/node_modules/validator/lib/ltrim.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = ltrim; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ltrim(str, chars) { + (0, _assertString.default)(str); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping + + var pattern = chars ? new RegExp("^[".concat(chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), "]+"), 'g') : /^\s+/g; + return str.replace(pattern, ''); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/matches.js b/node_modules/validator/lib/matches.js new file mode 100644 index 0000000..ea01ac1 --- /dev/null +++ b/node_modules/validator/lib/matches.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = matches; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function matches(str, pattern, modifiers) { + (0, _assertString.default)(str); + + if (Object.prototype.toString.call(pattern) !== '[object RegExp]') { + pattern = new RegExp(pattern, modifiers); + } + + return pattern.test(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/normalizeEmail.js b/node_modules/validator/lib/normalizeEmail.js new file mode 100644 index 0000000..990f431 --- /dev/null +++ b/node_modules/validator/lib/normalizeEmail.js @@ -0,0 +1,151 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = normalizeEmail; + +var _merge = _interopRequireDefault(require("./util/merge")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var default_normalize_email_options = { + // The following options apply to all email addresses + // Lowercases the local part of the email address. + // Please note this may violate RFC 5321 as per http://stackoverflow.com/a/9808332/192024). + // The domain is always lowercased, as per RFC 1035 + all_lowercase: true, + // The following conversions are specific to GMail + // Lowercases the local part of the GMail address (known to be case-insensitive) + gmail_lowercase: true, + // Removes dots from the local part of the email address, as that's ignored by GMail + gmail_remove_dots: true, + // Removes the subaddress (e.g. "+foo") from the email address + gmail_remove_subaddress: true, + // Conversts the googlemail.com domain to gmail.com + gmail_convert_googlemaildotcom: true, + // The following conversions are specific to Outlook.com / Windows Live / Hotmail + // Lowercases the local part of the Outlook.com address (known to be case-insensitive) + outlookdotcom_lowercase: true, + // Removes the subaddress (e.g. "+foo") from the email address + outlookdotcom_remove_subaddress: true, + // The following conversions are specific to Yahoo + // Lowercases the local part of the Yahoo address (known to be case-insensitive) + yahoo_lowercase: true, + // Removes the subaddress (e.g. "-foo") from the email address + yahoo_remove_subaddress: true, + // The following conversions are specific to Yandex + // Lowercases the local part of the Yandex address (known to be case-insensitive) + yandex_lowercase: true, + // The following conversions are specific to iCloud + // Lowercases the local part of the iCloud address (known to be case-insensitive) + icloud_lowercase: true, + // Removes the subaddress (e.g. "+foo") from the email address + icloud_remove_subaddress: true +}; // List of domains used by iCloud + +var icloud_domains = ['icloud.com', 'me.com']; // List of domains used by Outlook.com and its predecessors +// This list is likely incomplete. +// Partial reference: +// https://blogs.office.com/2013/04/17/outlook-com-gets-two-step-verification-sign-in-by-alias-and-new-international-domains/ + +var outlookdotcom_domains = ['hotmail.at', 'hotmail.be', 'hotmail.ca', 'hotmail.cl', 'hotmail.co.il', 'hotmail.co.nz', 'hotmail.co.th', 'hotmail.co.uk', 'hotmail.com', 'hotmail.com.ar', 'hotmail.com.au', 'hotmail.com.br', 'hotmail.com.gr', 'hotmail.com.mx', 'hotmail.com.pe', 'hotmail.com.tr', 'hotmail.com.vn', 'hotmail.cz', 'hotmail.de', 'hotmail.dk', 'hotmail.es', 'hotmail.fr', 'hotmail.hu', 'hotmail.id', 'hotmail.ie', 'hotmail.in', 'hotmail.it', 'hotmail.jp', 'hotmail.kr', 'hotmail.lv', 'hotmail.my', 'hotmail.ph', 'hotmail.pt', 'hotmail.sa', 'hotmail.sg', 'hotmail.sk', 'live.be', 'live.co.uk', 'live.com', 'live.com.ar', 'live.com.mx', 'live.de', 'live.es', 'live.eu', 'live.fr', 'live.it', 'live.nl', 'msn.com', 'outlook.at', 'outlook.be', 'outlook.cl', 'outlook.co.il', 'outlook.co.nz', 'outlook.co.th', 'outlook.com', 'outlook.com.ar', 'outlook.com.au', 'outlook.com.br', 'outlook.com.gr', 'outlook.com.pe', 'outlook.com.tr', 'outlook.com.vn', 'outlook.cz', 'outlook.de', 'outlook.dk', 'outlook.es', 'outlook.fr', 'outlook.hu', 'outlook.id', 'outlook.ie', 'outlook.in', 'outlook.it', 'outlook.jp', 'outlook.kr', 'outlook.lv', 'outlook.my', 'outlook.ph', 'outlook.pt', 'outlook.sa', 'outlook.sg', 'outlook.sk', 'passport.com']; // List of domains used by Yahoo Mail +// This list is likely incomplete + +var yahoo_domains = ['rocketmail.com', 'yahoo.ca', 'yahoo.co.uk', 'yahoo.com', 'yahoo.de', 'yahoo.fr', 'yahoo.in', 'yahoo.it', 'ymail.com']; // List of domains used by yandex.ru + +var yandex_domains = ['yandex.ru', 'yandex.ua', 'yandex.kz', 'yandex.com', 'yandex.by', 'ya.ru']; // replace single dots, but not multiple consecutive dots + +function dotsReplacer(match) { + if (match.length > 1) { + return match; + } + + return ''; +} + +function normalizeEmail(email, options) { + options = (0, _merge.default)(options, default_normalize_email_options); + var raw_parts = email.split('@'); + var domain = raw_parts.pop(); + var user = raw_parts.join('@'); + var parts = [user, domain]; // The domain is always lowercased, as it's case-insensitive per RFC 1035 + + parts[1] = parts[1].toLowerCase(); + + if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') { + // Address is GMail + if (options.gmail_remove_subaddress) { + parts[0] = parts[0].split('+')[0]; + } + + if (options.gmail_remove_dots) { + // this does not replace consecutive dots like example..email@gmail.com + parts[0] = parts[0].replace(/\.+/g, dotsReplacer); + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.gmail_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + + parts[1] = options.gmail_convert_googlemaildotcom ? 'gmail.com' : parts[1]; + } else if (icloud_domains.indexOf(parts[1]) >= 0) { + // Address is iCloud + if (options.icloud_remove_subaddress) { + parts[0] = parts[0].split('+')[0]; + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.icloud_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + } else if (outlookdotcom_domains.indexOf(parts[1]) >= 0) { + // Address is Outlook.com + if (options.outlookdotcom_remove_subaddress) { + parts[0] = parts[0].split('+')[0]; + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.outlookdotcom_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + } else if (yahoo_domains.indexOf(parts[1]) >= 0) { + // Address is Yahoo + if (options.yahoo_remove_subaddress) { + var components = parts[0].split('-'); + parts[0] = components.length > 1 ? components.slice(0, -1).join('-') : components[0]; + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.yahoo_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + } else if (yandex_domains.indexOf(parts[1]) >= 0) { + if (options.all_lowercase || options.yandex_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + + parts[1] = 'yandex.ru'; // all yandex domains are equal, 1st preferred + } else if (options.all_lowercase) { + // Any other address + parts[0] = parts[0].toLowerCase(); + } + + return parts.join('@'); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/rtrim.js b/node_modules/validator/lib/rtrim.js new file mode 100644 index 0000000..e056a47 --- /dev/null +++ b/node_modules/validator/lib/rtrim.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rtrim; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function rtrim(str, chars) { + (0, _assertString.default)(str); + + if (chars) { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping + var pattern = new RegExp("[".concat(chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), "]+$"), 'g'); + return str.replace(pattern, ''); + } // Use a faster and more safe than regex trim method https://blog.stevenlevithan.com/archives/faster-trim-javascript + + + var strIndex = str.length - 1; + + while (/\s/.test(str.charAt(strIndex))) { + strIndex -= 1; + } + + return str.slice(0, strIndex + 1); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/stripLow.js b/node_modules/validator/lib/stripLow.js new file mode 100644 index 0000000..aec2e0b --- /dev/null +++ b/node_modules/validator/lib/stripLow.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = stripLow; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +var _blacklist = _interopRequireDefault(require("./blacklist")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stripLow(str, keep_new_lines) { + (0, _assertString.default)(str); + var chars = keep_new_lines ? '\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F' : '\\x00-\\x1F\\x7F'; + return (0, _blacklist.default)(str, chars); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/toBoolean.js b/node_modules/validator/lib/toBoolean.js new file mode 100644 index 0000000..a1b1fe4 --- /dev/null +++ b/node_modules/validator/lib/toBoolean.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = toBoolean; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function toBoolean(str, strict) { + (0, _assertString.default)(str); + + if (strict) { + return str === '1' || /^true$/i.test(str); + } + + return str !== '0' && !/^false$/i.test(str) && str !== ''; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/toDate.js b/node_modules/validator/lib/toDate.js new file mode 100644 index 0000000..cb0756c --- /dev/null +++ b/node_modules/validator/lib/toDate.js @@ -0,0 +1,19 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = toDate; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function toDate(date) { + (0, _assertString.default)(date); + date = Date.parse(date); + return !isNaN(date) ? new Date(date) : null; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/toFloat.js b/node_modules/validator/lib/toFloat.js new file mode 100644 index 0000000..96adafd --- /dev/null +++ b/node_modules/validator/lib/toFloat.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = toFloat; + +var _isFloat = _interopRequireDefault(require("./isFloat")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function toFloat(str) { + if (!(0, _isFloat.default)(str)) return NaN; + return parseFloat(str); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/toInt.js b/node_modules/validator/lib/toInt.js new file mode 100644 index 0000000..4c0e7ad --- /dev/null +++ b/node_modules/validator/lib/toInt.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = toInt; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function toInt(str, radix) { + (0, _assertString.default)(str); + return parseInt(str, radix || 10); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/trim.js b/node_modules/validator/lib/trim.js new file mode 100644 index 0000000..497e3c3 --- /dev/null +++ b/node_modules/validator/lib/trim.js @@ -0,0 +1,19 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = trim; + +var _rtrim = _interopRequireDefault(require("./rtrim")); + +var _ltrim = _interopRequireDefault(require("./ltrim")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function trim(str, chars) { + return (0, _rtrim.default)((0, _ltrim.default)(str, chars), chars); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/unescape.js b/node_modules/validator/lib/unescape.js new file mode 100644 index 0000000..303d20c --- /dev/null +++ b/node_modules/validator/lib/unescape.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = unescape; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function unescape(str) { + (0, _assertString.default)(str); + return str.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(///g, '/').replace(/\/g, '\\').replace(/`/g, '`').replace(/&/g, '&'); // & replacement has to be the last one to prevent + // bugs with intermediate strings containing escape sequences + // See: https://github.com/validatorjs/validator.js/issues/1827 +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/util/algorithms.js b/node_modules/validator/lib/util/algorithms.js new file mode 100644 index 0000000..cf8e512 --- /dev/null +++ b/node_modules/validator/lib/util/algorithms.js @@ -0,0 +1,101 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.iso7064Check = iso7064Check; +exports.luhnCheck = luhnCheck; +exports.reverseMultiplyAndSum = reverseMultiplyAndSum; +exports.verhoeffCheck = verhoeffCheck; + +/** + * Algorithmic validation functions + * May be used as is or implemented in the workflow of other validators. + */ + +/* + * ISO 7064 validation function + * Called with a string of numbers (incl. check digit) + * to validate according to ISO 7064 (MOD 11, 10). + */ +function iso7064Check(str) { + var checkvalue = 10; + + for (var i = 0; i < str.length - 1; i++) { + checkvalue = (parseInt(str[i], 10) + checkvalue) % 10 === 0 ? 10 * 2 % 11 : (parseInt(str[i], 10) + checkvalue) % 10 * 2 % 11; + } + + checkvalue = checkvalue === 1 ? 0 : 11 - checkvalue; + return checkvalue === parseInt(str[10], 10); +} +/* + * Luhn (mod 10) validation function + * Called with a string of numbers (incl. check digit) + * to validate according to the Luhn algorithm. + */ + + +function luhnCheck(str) { + var checksum = 0; + var second = false; + + for (var i = str.length - 1; i >= 0; i--) { + if (second) { + var product = parseInt(str[i], 10) * 2; + + if (product > 9) { + // sum digits of product and add to checksum + checksum += product.toString().split('').map(function (a) { + return parseInt(a, 10); + }).reduce(function (a, b) { + return a + b; + }, 0); + } else { + checksum += product; + } + } else { + checksum += parseInt(str[i], 10); + } + + second = !second; + } + + return checksum % 10 === 0; +} +/* + * Reverse TIN multiplication and summation helper function + * Called with an array of single-digit integers and a base multiplier + * to calculate the sum of the digits multiplied in reverse. + * Normally used in variations of MOD 11 algorithmic checks. + */ + + +function reverseMultiplyAndSum(digits, base) { + var total = 0; + + for (var i = 0; i < digits.length; i++) { + total += digits[i] * (base - i); + } + + return total; +} +/* + * Verhoeff validation helper function + * Called with a string of numbers + * to validate according to the Verhoeff algorithm. + */ + + +function verhoeffCheck(str) { + var d_table = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]; + var p_table = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]; // Copy (to prevent replacement) and reverse + + var str_copy = str.split('').reverse().join(''); + var checksum = 0; + + for (var i = 0; i < str_copy.length; i++) { + checksum = d_table[checksum][p_table[i % 8][parseInt(str_copy[i], 10)]]; + } + + return checksum === 0; +} \ No newline at end of file diff --git a/node_modules/validator/lib/util/assertString.js b/node_modules/validator/lib/util/assertString.js new file mode 100644 index 0000000..2c508af --- /dev/null +++ b/node_modules/validator/lib/util/assertString.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = assertString; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function assertString(input) { + var isString = typeof input === 'string' || input instanceof String; + + if (!isString) { + var invalidType = _typeof(input); + + if (input === null) invalidType = 'null';else if (invalidType === 'object') invalidType = input.constructor.name; + throw new TypeError("Expected a string but received a ".concat(invalidType)); + } +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/util/includes.js b/node_modules/validator/lib/util/includes.js new file mode 100644 index 0000000..e061828 --- /dev/null +++ b/node_modules/validator/lib/util/includes.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var includes = function includes(arr, val) { + return arr.some(function (arrVal) { + return val === arrVal; + }); +}; + +var _default = includes; +exports.default = _default; +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/util/merge.js b/node_modules/validator/lib/util/merge.js new file mode 100644 index 0000000..a96c739 --- /dev/null +++ b/node_modules/validator/lib/util/merge.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = merge; + +function merge() { + var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var defaults = arguments.length > 1 ? arguments[1] : undefined; + + for (var key in defaults) { + if (typeof obj[key] === 'undefined') { + obj[key] = defaults[key]; + } + } + + return obj; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/util/multilineRegex.js b/node_modules/validator/lib/util/multilineRegex.js new file mode 100644 index 0000000..6980d14 --- /dev/null +++ b/node_modules/validator/lib/util/multilineRegex.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = multilineRegexp; + +/** + * Build RegExp object from an array + * of multiple/multi-line regexp parts + * + * @param {string[]} parts + * @param {string} flags + * @return {object} - RegExp object + */ +function multilineRegexp(parts, flags) { + var regexpAsStringLiteral = parts.join(''); + return new RegExp(regexpAsStringLiteral, flags); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/util/toString.js b/node_modules/validator/lib/util/toString.js new file mode 100644 index 0000000..6295192 --- /dev/null +++ b/node_modules/validator/lib/util/toString.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = toString; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function toString(input) { + if (_typeof(input) === 'object' && input !== null) { + if (typeof input.toString === 'function') { + input = input.toString(); + } else { + input = '[object Object]'; + } + } else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) { + input = ''; + } + + return String(input); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/util/typeOf.js b/node_modules/validator/lib/util/typeOf.js new file mode 100644 index 0000000..5bfacdb --- /dev/null +++ b/node_modules/validator/lib/util/typeOf.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = typeOf; + +/** + * Better way to handle type checking + * null, {}, array and date are objects, which confuses + */ +function typeOf(input) { + var rawObject = Object.prototype.toString.call(input).toLowerCase(); + var typeOfRegex = /\[object (.*)]/g; + var type = typeOfRegex.exec(rawObject)[1]; + return type; +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/lib/whitelist.js b/node_modules/validator/lib/whitelist.js new file mode 100644 index 0000000..7ae624e --- /dev/null +++ b/node_modules/validator/lib/whitelist.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = whitelist; + +var _assertString = _interopRequireDefault(require("./util/assertString")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function whitelist(str, chars) { + (0, _assertString.default)(str); + return str.replace(new RegExp("[^".concat(chars, "]+"), 'g'), ''); +} + +module.exports = exports.default; +module.exports.default = exports.default; \ No newline at end of file diff --git a/node_modules/validator/package.json b/node_modules/validator/package.json new file mode 100644 index 0000000..7d50520 --- /dev/null +++ b/node_modules/validator/package.json @@ -0,0 +1,75 @@ +{ + "name": "validator", + "description": "String validation and sanitization", + "version": "13.7.0", + "sideEffects": false, + "homepage": "https://github.com/validatorjs/validator.js", + "files": [ + "index.js", + "es", + "lib", + "README.md", + "LICENCE", + "validator.js", + "validator.min.js" + ], + "keywords": [ + "validator", + "validation", + "validate", + "sanitization", + "sanitize", + "sanitisation", + "sanitise", + "assert" + ], + "author": "Chris O'Hara ", + "contributors": [ + "Anthony Nandaa (https://github.com/profnandaa)" + ], + "main": "index.js", + "bugs": { + "url": "https://github.com/validatorjs/validator.js/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/validatorjs/validator.js.git" + }, + "devDependencies": { + "@babel/cli": "^7.0.0", + "@babel/core": "^7.0.0", + "@babel/preset-env": "^7.0.0", + "@babel/register": "^7.0.0", + "babel-eslint": "^10.0.1", + "babel-plugin-add-module-exports": "^1.0.0", + "eslint": "^4.19.1", + "eslint-config-airbnb-base": "^12.1.0", + "eslint-plugin-import": "^2.11.0", + "mocha": "^6.2.3", + "npm-run-all": "^4.1.5", + "nyc": "^14.1.0", + "rimraf": "^3.0.0", + "rollup": "^0.47.0", + "rollup-plugin-babel": "^4.0.1", + "uglify-js": "^3.0.19" + }, + "scripts": { + "lint": "eslint src test", + "lint:fix": "eslint --fix src test", + "clean:node": "rimraf index.js lib", + "clean:es": "rimraf es", + "clean:browser": "rimraf validator*.js", + "clean": "run-p clean:*", + "minify": "uglifyjs validator.js -o validator.min.js --compress --mangle --comments /Copyright/", + "build:browser": "node --require @babel/register build-browser && npm run minify", + "build:es": "babel src -d es --env-name=es", + "build:node": "babel src -d .", + "build": "run-p build:*", + "pretest": "npm run build && npm run lint", + "test": "nyc --reporter=cobertura --reporter=text-summary mocha --require @babel/register --reporter dot" + }, + "engines": { + "node": ">= 0.10" + }, + "license": "MIT" +} diff --git a/node_modules/validator/validator.js b/node_modules/validator/validator.js new file mode 100644 index 0000000..32a8814 --- /dev/null +++ b/node_modules/validator/validator.js @@ -0,0 +1,5094 @@ +/*! + * Copyright (c) 2018 Chris O'Hara + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.validator = factory()); +}(this, (function () { 'use strict'; + +function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} + +function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); +} + +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); +} + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); +} + +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} + +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); +} + +function _iterableToArrayLimit(arr, i) { + if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; +} + +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); +} + +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + + return arr2; +} + +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +function _createForOfIteratorHelper(o, allowArrayLike) { + var it; + + if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { + if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + + var F = function () {}; + + return { + s: F, + n: function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function (e) { + throw e; + }, + f: F + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var normalCompletion = true, + didErr = false, + err; + return { + s: function () { + it = o[Symbol.iterator](); + }, + n: function () { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function (e) { + didErr = true; + err = e; + }, + f: function () { + try { + if (!normalCompletion && it.return != null) it.return(); + } finally { + if (didErr) throw err; + } + } + }; +} + +function assertString(input) { + var isString = typeof input === 'string' || input instanceof String; + + if (!isString) { + var invalidType = _typeof(input); + + if (input === null) invalidType = 'null';else if (invalidType === 'object') invalidType = input.constructor.name; + throw new TypeError("Expected a string but received a ".concat(invalidType)); + } +} + +function toDate(date) { + assertString(date); + date = Date.parse(date); + return !isNaN(date) ? new Date(date) : null; +} + +var alpha = { + 'en-US': /^[A-Z]+$/i, + 'az-AZ': /^[A-VXYZÇƏĞİıÖŞÜ]+$/i, + 'bg-BG': /^[А-Я]+$/i, + 'cs-CZ': /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i, + 'da-DK': /^[A-ZÆØÅ]+$/i, + 'de-DE': /^[A-ZÄÖÜß]+$/i, + 'el-GR': /^[Α-ώ]+$/i, + 'es-ES': /^[A-ZÁÉÍÑÓÚÜ]+$/i, + 'fa-IR': /^[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهی]+$/i, + 'fi-FI': /^[A-ZÅÄÖ]+$/i, + 'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i, + 'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i, + 'nb-NO': /^[A-ZÆØÅ]+$/i, + 'nl-NL': /^[A-ZÁÉËÏÓÖÜÚ]+$/i, + 'nn-NO': /^[A-ZÆØÅ]+$/i, + 'hu-HU': /^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i, + 'pl-PL': /^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i, + 'pt-PT': /^[A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i, + 'ru-RU': /^[А-ЯЁ]+$/i, + 'sl-SI': /^[A-ZČĆĐŠŽ]+$/i, + 'sk-SK': /^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i, + 'sr-RS@latin': /^[A-ZČĆŽŠĐ]+$/i, + 'sr-RS': /^[А-ЯЂЈЉЊЋЏ]+$/i, + 'sv-SE': /^[A-ZÅÄÖ]+$/i, + 'th-TH': /^[ก-๐\s]+$/i, + 'tr-TR': /^[A-ZÇĞİıÖŞÜ]+$/i, + 'uk-UA': /^[А-ЩЬЮЯЄIЇҐі]+$/i, + 'vi-VN': /^[A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$/i, + 'ku-IQ': /^[ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i, + ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/, + he: /^[א-ת]+$/, + fa: /^['آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی']+$/i, + 'hi-IN': /^[\u0900-\u0961]+[\u0972-\u097F]*$/i +}; +var alphanumeric = { + 'en-US': /^[0-9A-Z]+$/i, + 'az-AZ': /^[0-9A-VXYZÇƏĞİıÖŞÜ]+$/i, + 'bg-BG': /^[0-9А-Я]+$/i, + 'cs-CZ': /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i, + 'da-DK': /^[0-9A-ZÆØÅ]+$/i, + 'de-DE': /^[0-9A-ZÄÖÜß]+$/i, + 'el-GR': /^[0-9Α-ω]+$/i, + 'es-ES': /^[0-9A-ZÁÉÍÑÓÚÜ]+$/i, + 'fi-FI': /^[0-9A-ZÅÄÖ]+$/i, + 'fr-FR': /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i, + 'it-IT': /^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i, + 'hu-HU': /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i, + 'nb-NO': /^[0-9A-ZÆØÅ]+$/i, + 'nl-NL': /^[0-9A-ZÁÉËÏÓÖÜÚ]+$/i, + 'nn-NO': /^[0-9A-ZÆØÅ]+$/i, + 'pl-PL': /^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$/i, + 'pt-PT': /^[0-9A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i, + 'ru-RU': /^[0-9А-ЯЁ]+$/i, + 'sl-SI': /^[0-9A-ZČĆĐŠŽ]+$/i, + 'sk-SK': /^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i, + 'sr-RS@latin': /^[0-9A-ZČĆŽŠĐ]+$/i, + 'sr-RS': /^[0-9А-ЯЂЈЉЊЋЏ]+$/i, + 'sv-SE': /^[0-9A-ZÅÄÖ]+$/i, + 'th-TH': /^[ก-๙\s]+$/i, + 'tr-TR': /^[0-9A-ZÇĞİıÖŞÜ]+$/i, + 'uk-UA': /^[0-9А-ЩЬЮЯЄIЇҐі]+$/i, + 'ku-IQ': /^[٠١٢٣٤٥٦٧٨٩0-9ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i, + 'vi-VN': /^[0-9A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$/i, + ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/, + he: /^[0-9א-ת]+$/, + fa: /^['0-9آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی۱۲۳۴۵۶۷۸۹۰']+$/i, + 'hi-IN': /^[\u0900-\u0963]+[\u0966-\u097F]*$/i +}; +var decimal = { + 'en-US': '.', + ar: '٫' +}; +var englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM']; + +for (var locale, i = 0; i < englishLocales.length; i++) { + locale = "en-".concat(englishLocales[i]); + alpha[locale] = alpha['en-US']; + alphanumeric[locale] = alphanumeric['en-US']; + decimal[locale] = decimal['en-US']; +} // Source: http://www.localeplanet.com/java/ + + +var arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE']; + +for (var _locale, _i = 0; _i < arabicLocales.length; _i++) { + _locale = "ar-".concat(arabicLocales[_i]); + alpha[_locale] = alpha.ar; + alphanumeric[_locale] = alphanumeric.ar; + decimal[_locale] = decimal.ar; +} + +var farsiLocales = ['IR', 'AF']; + +for (var _locale2, _i2 = 0; _i2 < farsiLocales.length; _i2++) { + _locale2 = "fa-".concat(farsiLocales[_i2]); + alphanumeric[_locale2] = alphanumeric.fa; + decimal[_locale2] = decimal.ar; +} // Source: https://en.wikipedia.org/wiki/Decimal_mark + + +var dotDecimal = ['ar-EG', 'ar-LB', 'ar-LY']; +var commaDecimal = ['bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-ZM', 'es-ES', 'fr-CA', 'fr-FR', 'id-ID', 'it-IT', 'ku-IQ', 'hi-IN', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA', 'vi-VN']; + +for (var _i3 = 0; _i3 < dotDecimal.length; _i3++) { + decimal[dotDecimal[_i3]] = decimal['en-US']; +} + +for (var _i4 = 0; _i4 < commaDecimal.length; _i4++) { + decimal[commaDecimal[_i4]] = ','; +} + +alpha['fr-CA'] = alpha['fr-FR']; +alphanumeric['fr-CA'] = alphanumeric['fr-FR']; +alpha['pt-BR'] = alpha['pt-PT']; +alphanumeric['pt-BR'] = alphanumeric['pt-PT']; +decimal['pt-BR'] = decimal['pt-PT']; // see #862 + +alpha['pl-Pl'] = alpha['pl-PL']; +alphanumeric['pl-Pl'] = alphanumeric['pl-PL']; +decimal['pl-Pl'] = decimal['pl-PL']; // see #1455 + +alpha['fa-AF'] = alpha.fa; + +function isFloat(str, options) { + assertString(str); + options = options || {}; + + var _float = new RegExp("^(?:[-+])?(?:[0-9]+)?(?:\\".concat(options.locale ? decimal[options.locale] : '.', "[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$")); + + if (str === '' || str === '.' || str === '-' || str === '+') { + return false; + } + + var value = parseFloat(str.replace(',', '.')); + return _float.test(str) && (!options.hasOwnProperty('min') || value >= options.min) && (!options.hasOwnProperty('max') || value <= options.max) && (!options.hasOwnProperty('lt') || value < options.lt) && (!options.hasOwnProperty('gt') || value > options.gt); +} +var locales = Object.keys(decimal); + +function toFloat(str) { + if (!isFloat(str)) return NaN; + return parseFloat(str); +} + +function toInt(str, radix) { + assertString(str); + return parseInt(str, radix || 10); +} + +function toBoolean(str, strict) { + assertString(str); + + if (strict) { + return str === '1' || /^true$/i.test(str); + } + + return str !== '0' && !/^false$/i.test(str) && str !== ''; +} + +function equals(str, comparison) { + assertString(str); + return str === comparison; +} + +function toString$1(input) { + if (_typeof(input) === 'object' && input !== null) { + if (typeof input.toString === 'function') { + input = input.toString(); + } else { + input = '[object Object]'; + } + } else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) { + input = ''; + } + + return String(input); +} + +function merge() { + var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var defaults = arguments.length > 1 ? arguments[1] : undefined; + + for (var key in defaults) { + if (typeof obj[key] === 'undefined') { + obj[key] = defaults[key]; + } + } + + return obj; +} + +var defaulContainsOptions = { + ignoreCase: false, + minOccurrences: 1 +}; +function contains(str, elem, options) { + assertString(str); + options = merge(options, defaulContainsOptions); + + if (options.ignoreCase) { + return str.toLowerCase().split(toString$1(elem).toLowerCase()).length > options.minOccurrences; + } + + return str.split(toString$1(elem)).length > options.minOccurrences; +} + +function matches(str, pattern, modifiers) { + assertString(str); + + if (Object.prototype.toString.call(pattern) !== '[object RegExp]') { + pattern = new RegExp(pattern, modifiers); + } + + return pattern.test(str); +} + +/* eslint-disable prefer-rest-params */ + +function isByteLength(str, options) { + assertString(str); + var min; + var max; + + if (_typeof(options) === 'object') { + min = options.min || 0; + max = options.max; + } else { + // backwards compatibility: isByteLength(str, min [, max]) + min = arguments[1]; + max = arguments[2]; + } + + var len = encodeURI(str).split(/%..|./).length - 1; + return len >= min && (typeof max === 'undefined' || len <= max); +} + +var default_fqdn_options = { + require_tld: true, + allow_underscores: false, + allow_trailing_dot: false, + allow_numeric_tld: false, + allow_wildcard: false +}; +function isFQDN(str, options) { + assertString(str); + options = merge(options, default_fqdn_options); + /* Remove the optional trailing dot before checking validity */ + + if (options.allow_trailing_dot && str[str.length - 1] === '.') { + str = str.substring(0, str.length - 1); + } + /* Remove the optional wildcard before checking validity */ + + + if (options.allow_wildcard === true && str.indexOf('*.') === 0) { + str = str.substring(2); + } + + var parts = str.split('.'); + var tld = parts[parts.length - 1]; + + if (options.require_tld) { + // disallow fqdns without tld + if (parts.length < 2) { + return false; + } + + if (!/^([a-z\u00A1-\u00A8\u00AA-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) { + return false; + } // disallow spaces + + + if (/\s/.test(tld)) { + return false; + } + } // reject numeric TLDs + + + if (!options.allow_numeric_tld && /^\d+$/.test(tld)) { + return false; + } + + return parts.every(function (part) { + if (part.length > 63) { + return false; + } + + if (!/^[a-z_\u00a1-\uffff0-9-]+$/i.test(part)) { + return false; + } // disallow full-width chars + + + if (/[\uff01-\uff5e]/.test(part)) { + return false; + } // disallow parts starting or ending with hyphen + + + if (/^-|-$/.test(part)) { + return false; + } + + if (!options.allow_underscores && /_/.test(part)) { + return false; + } + + return true; + }); +} + +/** +11.3. Examples + + The following addresses + + fe80::1234 (on the 1st link of the node) + ff02::5678 (on the 5th link of the node) + ff08::9abc (on the 10th organization of the node) + + would be represented as follows: + + fe80::1234%1 + ff02::5678%5 + ff08::9abc%10 + + (Here we assume a natural translation from a zone index to the + part, where the Nth zone of any scope is translated into + "N".) + + If we use interface names as , those addresses could also be + represented as follows: + + fe80::1234%ne0 + ff02::5678%pvc1.3 + ff08::9abc%interface10 + + where the interface "ne0" belongs to the 1st link, "pvc1.3" belongs + to the 5th link, and "interface10" belongs to the 10th organization. + * * */ + +var IPv4SegmentFormat = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'; +var IPv4AddressFormat = "(".concat(IPv4SegmentFormat, "[.]){3}").concat(IPv4SegmentFormat); +var IPv4AddressRegExp = new RegExp("^".concat(IPv4AddressFormat, "$")); +var IPv6SegmentFormat = '(?:[0-9a-fA-F]{1,4})'; +var IPv6AddressRegExp = new RegExp('^(' + "(?:".concat(IPv6SegmentFormat, ":){7}(?:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){6}(?:").concat(IPv4AddressFormat, "|:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){5}(?::").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,2}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){4}(?:(:").concat(IPv6SegmentFormat, "){0,1}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,3}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){3}(?:(:").concat(IPv6SegmentFormat, "){0,2}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,4}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){2}(?:(:").concat(IPv6SegmentFormat, "){0,3}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,5}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){1}(?:(:").concat(IPv6SegmentFormat, "){0,4}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,6}|:)|") + "(?::((?::".concat(IPv6SegmentFormat, "){0,5}:").concat(IPv4AddressFormat, "|(?::").concat(IPv6SegmentFormat, "){1,7}|:))") + ')(%[0-9a-zA-Z-.:]{1,})?$'); +function isIP(str) { + var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + assertString(str); + version = String(version); + + if (!version) { + return isIP(str, 4) || isIP(str, 6); + } + + if (version === '4') { + if (!IPv4AddressRegExp.test(str)) { + return false; + } + + var parts = str.split('.').sort(function (a, b) { + return a - b; + }); + return parts[3] <= 255; + } + + if (version === '6') { + return !!IPv6AddressRegExp.test(str); + } + + return false; +} + +var default_email_options = { + allow_display_name: false, + require_display_name: false, + allow_utf8_local_part: true, + require_tld: true, + blacklisted_chars: '', + ignore_max_length: false, + host_blacklist: [] +}; +/* eslint-disable max-len */ + +/* eslint-disable no-control-regex */ + +var splitNameAddress = /^([^\x00-\x1F\x7F-\x9F\cX]+)]/.test(display_name_without_quotes); + + if (contains_illegal) { + // if contains illegal characters, + // must to be enclosed in double-quotes, otherwise it's not a valid display name + if (display_name_without_quotes === display_name) { + return false; + } // the quotes in display name must start with character symbol \ + + + var all_start_with_back_slash = display_name_without_quotes.split('"').length === display_name_without_quotes.split('\\"').length; + + if (!all_start_with_back_slash) { + return false; + } + } + + return true; +} + +function isEmail(str, options) { + assertString(str); + options = merge(options, default_email_options); + + if (options.require_display_name || options.allow_display_name) { + var display_email = str.match(splitNameAddress); + + if (display_email) { + var display_name = display_email[1]; // Remove display name and angle brackets to get email address + // Can be done in the regex but will introduce a ReDOS (See #1597 for more info) + + str = str.replace(display_name, '').replace(/(^<|>$)/g, ''); // sometimes need to trim the last space to get the display name + // because there may be a space between display name and email address + // eg. myname + // the display name is `myname` instead of `myname `, so need to trim the last space + + if (display_name.endsWith(' ')) { + display_name = display_name.substr(0, display_name.length - 1); + } + + if (!validateDisplayName(display_name)) { + return false; + } + } else if (options.require_display_name) { + return false; + } + } + + if (!options.ignore_max_length && str.length > defaultMaxEmailLength) { + return false; + } + + var parts = str.split('@'); + var domain = parts.pop(); + var lower_domain = domain.toLowerCase(); + + if (options.host_blacklist.includes(lower_domain)) { + return false; + } + + var user = parts.join('@'); + + if (options.domain_specific_validation && (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com')) { + /* + Previously we removed dots for gmail addresses before validating. + This was removed because it allows `multiple..dots@gmail.com` + to be reported as valid, but it is not. + Gmail only normalizes single dots, removing them from here is pointless, + should be done in normalizeEmail + */ + user = user.toLowerCase(); // Removing sub-address from username before gmail validation + + var username = user.split('+')[0]; // Dots are not included in gmail length restriction + + if (!isByteLength(username.replace(/\./g, ''), { + min: 6, + max: 30 + })) { + return false; + } + + var _user_parts = username.split('.'); + + for (var i = 0; i < _user_parts.length; i++) { + if (!gmailUserPart.test(_user_parts[i])) { + return false; + } + } + } + + if (options.ignore_max_length === false && (!isByteLength(user, { + max: 64 + }) || !isByteLength(domain, { + max: 254 + }))) { + return false; + } + + if (!isFQDN(domain, { + require_tld: options.require_tld + })) { + if (!options.allow_ip_domain) { + return false; + } + + if (!isIP(domain)) { + if (!domain.startsWith('[') || !domain.endsWith(']')) { + return false; + } + + var noBracketdomain = domain.substr(1, domain.length - 2); + + if (noBracketdomain.length === 0 || !isIP(noBracketdomain)) { + return false; + } + } + } + + if (user[0] === '"') { + user = user.slice(1, user.length - 1); + return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user); + } + + var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart; + var user_parts = user.split('.'); + + for (var _i = 0; _i < user_parts.length; _i++) { + if (!pattern.test(user_parts[_i])) { + return false; + } + } + + if (options.blacklisted_chars) { + if (user.search(new RegExp("[".concat(options.blacklisted_chars, "]+"), 'g')) !== -1) return false; + } + + return true; +} + +/* +options for isURL method + +require_protocol - if set as true isURL will return false if protocol is not present in the URL +require_valid_protocol - isURL will check if the URL's protocol is present in the protocols option +protocols - valid protocols can be modified with this option +require_host - if set as false isURL will not check if host is present in the URL +require_port - if set as true isURL will check if port is present in the URL +allow_protocol_relative_urls - if set as true protocol relative URLs will be allowed +validate_length - if set as false isURL will skip string length validation (IE maximum is 2083) + +*/ + +var default_url_options = { + protocols: ['http', 'https', 'ftp'], + require_tld: true, + require_protocol: false, + require_host: true, + require_port: false, + require_valid_protocol: true, + allow_underscores: false, + allow_trailing_dot: false, + allow_protocol_relative_urls: false, + allow_fragments: true, + allow_query_components: true, + validate_length: true +}; +var wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/; + +function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +} + +function checkHost(host, matches) { + for (var i = 0; i < matches.length; i++) { + var match = matches[i]; + + if (host === match || isRegExp(match) && match.test(host)) { + return true; + } + } + + return false; +} + +function isURL(url, options) { + assertString(url); + + if (!url || /[\s<>]/.test(url)) { + return false; + } + + if (url.indexOf('mailto:') === 0) { + return false; + } + + options = merge(options, default_url_options); + + if (options.validate_length && url.length >= 2083) { + return false; + } + + if (!options.allow_fragments && url.includes('#')) { + return false; + } + + if (!options.allow_query_components && (url.includes('?') || url.includes('&'))) { + return false; + } + + var protocol, auth, host, hostname, port, port_str, split, ipv6; + split = url.split('#'); + url = split.shift(); + split = url.split('?'); + url = split.shift(); + split = url.split('://'); + + if (split.length > 1) { + protocol = split.shift().toLowerCase(); + + if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) { + return false; + } + } else if (options.require_protocol) { + return false; + } else if (url.substr(0, 2) === '//') { + if (!options.allow_protocol_relative_urls) { + return false; + } + + split[0] = url.substr(2); + } + + url = split.join('://'); + + if (url === '') { + return false; + } + + split = url.split('/'); + url = split.shift(); + + if (url === '' && !options.require_host) { + return true; + } + + split = url.split('@'); + + if (split.length > 1) { + if (options.disallow_auth) { + return false; + } + + if (split[0] === '') { + return false; + } + + auth = split.shift(); + + if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) { + return false; + } + + var _auth$split = auth.split(':'), + _auth$split2 = _slicedToArray(_auth$split, 2), + user = _auth$split2[0], + password = _auth$split2[1]; + + if (user === '' && password === '') { + return false; + } + } + + hostname = split.join('@'); + port_str = null; + ipv6 = null; + var ipv6_match = hostname.match(wrapped_ipv6); + + if (ipv6_match) { + host = ''; + ipv6 = ipv6_match[1]; + port_str = ipv6_match[2] || null; + } else { + split = hostname.split(':'); + host = split.shift(); + + if (split.length) { + port_str = split.join(':'); + } + } + + if (port_str !== null && port_str.length > 0) { + port = parseInt(port_str, 10); + + if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) { + return false; + } + } else if (options.require_port) { + return false; + } + + if (options.host_whitelist) { + return checkHost(host, options.host_whitelist); + } + + if (!isIP(host) && !isFQDN(host, options) && (!ipv6 || !isIP(ipv6, 6))) { + return false; + } + + host = host || ipv6; + + if (options.host_blacklist && checkHost(host, options.host_blacklist)) { + return false; + } + + return true; +} + +var macAddress = /^(?:[0-9a-fA-F]{2}([-:\s]))([0-9a-fA-F]{2}\1){4}([0-9a-fA-F]{2})$/; +var macAddressNoSeparators = /^([0-9a-fA-F]){12}$/; +var macAddressWithDots = /^([0-9a-fA-F]{4}\.){2}([0-9a-fA-F]{4})$/; +function isMACAddress(str, options) { + assertString(str); + /** + * @deprecated `no_colons` TODO: remove it in the next major + */ + + if (options && (options.no_colons || options.no_separators)) { + return macAddressNoSeparators.test(str); + } + + return macAddress.test(str) || macAddressWithDots.test(str); +} + +var subnetMaybe = /^\d{1,3}$/; +var v4Subnet = 32; +var v6Subnet = 128; +function isIPRange(str) { + var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + assertString(str); + var parts = str.split('/'); // parts[0] -> ip, parts[1] -> subnet + + if (parts.length !== 2) { + return false; + } + + if (!subnetMaybe.test(parts[1])) { + return false; + } // Disallow preceding 0 i.e. 01, 02, ... + + + if (parts[1].length > 1 && parts[1].startsWith('0')) { + return false; + } + + var isValidIP = isIP(parts[0], version); + + if (!isValidIP) { + return false; + } // Define valid subnet according to IP's version + + + var expectedSubnet = null; + + switch (String(version)) { + case '4': + expectedSubnet = v4Subnet; + break; + + case '6': + expectedSubnet = v6Subnet; + break; + + default: + expectedSubnet = isIP(parts[0], '6') ? v6Subnet : v4Subnet; + } + + return parts[1] <= expectedSubnet && parts[1] >= 0; +} + +var default_date_options = { + format: 'YYYY/MM/DD', + delimiters: ['/', '-'], + strictMode: false +}; + +function isValidFormat(format) { + return /(^(y{4}|y{2})[.\/-](m{1,2})[.\/-](d{1,2})$)|(^(m{1,2})[.\/-](d{1,2})[.\/-]((y{4}|y{2})$))|(^(d{1,2})[.\/-](m{1,2})[.\/-]((y{4}|y{2})$))/gi.test(format); +} + +function zip(date, format) { + var zippedArr = [], + len = Math.min(date.length, format.length); + + for (var i = 0; i < len; i++) { + zippedArr.push([date[i], format[i]]); + } + + return zippedArr; +} + +function isDate(input, options) { + if (typeof options === 'string') { + // Allow backward compatbility for old format isDate(input [, format]) + options = merge({ + format: options + }, default_date_options); + } else { + options = merge(options, default_date_options); + } + + if (typeof input === 'string' && isValidFormat(options.format)) { + var formatDelimiter = options.delimiters.find(function (delimiter) { + return options.format.indexOf(delimiter) !== -1; + }); + var dateDelimiter = options.strictMode ? formatDelimiter : options.delimiters.find(function (delimiter) { + return input.indexOf(delimiter) !== -1; + }); + var dateAndFormat = zip(input.split(dateDelimiter), options.format.toLowerCase().split(formatDelimiter)); + var dateObj = {}; + + var _iterator = _createForOfIteratorHelper(dateAndFormat), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _step$value = _slicedToArray(_step.value, 2), + dateWord = _step$value[0], + formatWord = _step$value[1]; + + if (dateWord.length !== formatWord.length) { + return false; + } + + dateObj[formatWord.charAt(0)] = dateWord; + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + + return new Date("".concat(dateObj.m, "/").concat(dateObj.d, "/").concat(dateObj.y)).getDate() === +dateObj.d; + } + + if (!options.strictMode) { + return Object.prototype.toString.call(input) === '[object Date]' && isFinite(input); + } + + return false; +} + +var defaultOptions = { + loose: false +}; +var strictBooleans = ['true', 'false', '1', '0']; +var looseBooleans = [].concat(strictBooleans, ['yes', 'no']); +function isBoolean(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultOptions; + assertString(str); + + if (options.loose) { + return looseBooleans.includes(str.toLowerCase()); + } + + return strictBooleans.includes(str); +} + +var localeReg = /^[A-Za-z]{2,4}([_-]([A-Za-z]{4}|[\d]{3}))?([_-]([A-Za-z]{2}|[\d]{3}))?$/; +function isLocale(str) { + assertString(str); + + if (str === 'en_US_POSIX' || str === 'ca_ES_VALENCIA') { + return true; + } + + return localeReg.test(str); +} + +function isAlpha(_str) { + var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + assertString(_str); + var str = _str; + var ignore = options.ignore; + + if (ignore) { + if (ignore instanceof RegExp) { + str = str.replace(ignore, ''); + } else if (typeof ignore === 'string') { + str = str.replace(new RegExp("[".concat(ignore.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'), "]"), 'g'), ''); // escape regex for ignore + } else { + throw new Error('ignore should be instance of a String or RegExp'); + } + } + + if (locale in alpha) { + return alpha[locale].test(str); + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} +var locales$1 = Object.keys(alpha); + +function isAlphanumeric(_str) { + var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + assertString(_str); + var str = _str; + var ignore = options.ignore; + + if (ignore) { + if (ignore instanceof RegExp) { + str = str.replace(ignore, ''); + } else if (typeof ignore === 'string') { + str = str.replace(new RegExp("[".concat(ignore.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'), "]"), 'g'), ''); // escape regex for ignore + } else { + throw new Error('ignore should be instance of a String or RegExp'); + } + } + + if (locale in alphanumeric) { + return alphanumeric[locale].test(str); + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} +var locales$2 = Object.keys(alphanumeric); + +var numericNoSymbols = /^[0-9]+$/; +function isNumeric(str, options) { + assertString(str); + + if (options && options.no_symbols) { + return numericNoSymbols.test(str); + } + + return new RegExp("^[+-]?([0-9]*[".concat((options || {}).locale ? decimal[options.locale] : '.', "])?[0-9]+$")).test(str); +} + +/** + * Reference: + * https://en.wikipedia.org/ -- Wikipedia + * https://docs.microsoft.com/en-us/microsoft-365/compliance/eu-passport-number -- EU Passport Number + * https://countrycode.org/ -- Country Codes + */ + +var passportRegexByCountryCode = { + AM: /^[A-Z]{2}\d{7}$/, + // ARMENIA + AR: /^[A-Z]{3}\d{6}$/, + // ARGENTINA + AT: /^[A-Z]\d{7}$/, + // AUSTRIA + AU: /^[A-Z]\d{7}$/, + // AUSTRALIA + BE: /^[A-Z]{2}\d{6}$/, + // BELGIUM + BG: /^\d{9}$/, + // BULGARIA + BR: /^[A-Z]{2}\d{6}$/, + // BRAZIL + BY: /^[A-Z]{2}\d{7}$/, + // BELARUS + CA: /^[A-Z]{2}\d{6}$/, + // CANADA + CH: /^[A-Z]\d{7}$/, + // SWITZERLAND + CN: /^G\d{8}$|^E(?![IO])[A-Z0-9]\d{7}$/, + // CHINA [G=Ordinary, E=Electronic] followed by 8-digits, or E followed by any UPPERCASE letter (except I and O) followed by 7 digits + CY: /^[A-Z](\d{6}|\d{8})$/, + // CYPRUS + CZ: /^\d{8}$/, + // CZECH REPUBLIC + DE: /^[CFGHJKLMNPRTVWXYZ0-9]{9}$/, + // GERMANY + DK: /^\d{9}$/, + // DENMARK + DZ: /^\d{9}$/, + // ALGERIA + EE: /^([A-Z]\d{7}|[A-Z]{2}\d{7})$/, + // ESTONIA (K followed by 7-digits), e-passports have 2 UPPERCASE followed by 7 digits + ES: /^[A-Z0-9]{2}([A-Z0-9]?)\d{6}$/, + // SPAIN + FI: /^[A-Z]{2}\d{7}$/, + // FINLAND + FR: /^\d{2}[A-Z]{2}\d{5}$/, + // FRANCE + GB: /^\d{9}$/, + // UNITED KINGDOM + GR: /^[A-Z]{2}\d{7}$/, + // GREECE + HR: /^\d{9}$/, + // CROATIA + HU: /^[A-Z]{2}(\d{6}|\d{7})$/, + // HUNGARY + IE: /^[A-Z0-9]{2}\d{7}$/, + // IRELAND + IN: /^[A-Z]{1}-?\d{7}$/, + // INDIA + ID: /^[A-C]\d{7}$/, + // INDONESIA + IR: /^[A-Z]\d{8}$/, + // IRAN + IS: /^(A)\d{7}$/, + // ICELAND + IT: /^[A-Z0-9]{2}\d{7}$/, + // ITALY + JP: /^[A-Z]{2}\d{7}$/, + // JAPAN + KR: /^[MS]\d{8}$/, + // SOUTH KOREA, REPUBLIC OF KOREA, [S=PS Passports, M=PM Passports] + LT: /^[A-Z0-9]{8}$/, + // LITHUANIA + LU: /^[A-Z0-9]{8}$/, + // LUXEMBURG + LV: /^[A-Z0-9]{2}\d{7}$/, + // LATVIA + LY: /^[A-Z0-9]{8}$/, + // LIBYA + MT: /^\d{7}$/, + // MALTA + MZ: /^([A-Z]{2}\d{7})|(\d{2}[A-Z]{2}\d{5})$/, + // MOZAMBIQUE + MY: /^[AHK]\d{8}$/, + // MALAYSIA + NL: /^[A-Z]{2}[A-Z0-9]{6}\d$/, + // NETHERLANDS + PL: /^[A-Z]{2}\d{7}$/, + // POLAND + PT: /^[A-Z]\d{6}$/, + // PORTUGAL + RO: /^\d{8,9}$/, + // ROMANIA + RU: /^\d{9}$/, + // RUSSIAN FEDERATION + SE: /^\d{8}$/, + // SWEDEN + SL: /^(P)[A-Z]\d{7}$/, + // SLOVANIA + SK: /^[0-9A-Z]\d{7}$/, + // SLOVAKIA + TR: /^[A-Z]\d{8}$/, + // TURKEY + UA: /^[A-Z]{2}\d{6}$/, + // UKRAINE + US: /^\d{9}$/ // UNITED STATES + +}; +/** + * Check if str is a valid passport number + * relative to provided ISO Country Code. + * + * @param {string} str + * @param {string} countryCode + * @return {boolean} + */ + +function isPassportNumber(str, countryCode) { + assertString(str); + /** Remove All Whitespaces, Convert to UPPERCASE */ + + var normalizedStr = str.replace(/\s/g, '').toUpperCase(); + return countryCode.toUpperCase() in passportRegexByCountryCode && passportRegexByCountryCode[countryCode].test(normalizedStr); +} + +var _int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/; +var intLeadingZeroes = /^[-+]?[0-9]+$/; +function isInt(str, options) { + assertString(str); + options = options || {}; // Get the regex to use for testing, based on whether + // leading zeroes are allowed or not. + + var regex = options.hasOwnProperty('allow_leading_zeroes') && !options.allow_leading_zeroes ? _int : intLeadingZeroes; // Check min/max/lt/gt + + var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min; + var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max; + var ltCheckPassed = !options.hasOwnProperty('lt') || str < options.lt; + var gtCheckPassed = !options.hasOwnProperty('gt') || str > options.gt; + return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed; +} + +function isPort(str) { + return isInt(str, { + min: 0, + max: 65535 + }); +} + +function isLowercase(str) { + assertString(str); + return str === str.toLowerCase(); +} + +function isUppercase(str) { + assertString(str); + return str === str.toUpperCase(); +} + +var imeiRegexWithoutHypens = /^[0-9]{15}$/; +var imeiRegexWithHypens = /^\d{2}-\d{6}-\d{6}-\d{1}$/; +function isIMEI(str, options) { + assertString(str); + options = options || {}; // default regex for checking imei is the one without hyphens + + var imeiRegex = imeiRegexWithoutHypens; + + if (options.allow_hyphens) { + imeiRegex = imeiRegexWithHypens; + } + + if (!imeiRegex.test(str)) { + return false; + } + + str = str.replace(/-/g, ''); + var sum = 0, + mul = 2, + l = 14; + + for (var i = 0; i < l; i++) { + var digit = str.substring(l - i - 1, l - i); + var tp = parseInt(digit, 10) * mul; + + if (tp >= 10) { + sum += tp % 10 + 1; + } else { + sum += tp; + } + + if (mul === 1) { + mul += 1; + } else { + mul -= 1; + } + } + + var chk = (10 - sum % 10) % 10; + + if (chk !== parseInt(str.substring(14, 15), 10)) { + return false; + } + + return true; +} + +/* eslint-disable no-control-regex */ + +var ascii = /^[\x00-\x7F]+$/; +/* eslint-enable no-control-regex */ + +function isAscii(str) { + assertString(str); + return ascii.test(str); +} + +var fullWidth = /[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/; +function isFullWidth(str) { + assertString(str); + return fullWidth.test(str); +} + +var halfWidth = /[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/; +function isHalfWidth(str) { + assertString(str); + return halfWidth.test(str); +} + +function isVariableWidth(str) { + assertString(str); + return fullWidth.test(str) && halfWidth.test(str); +} + +/* eslint-disable no-control-regex */ + +var multibyte = /[^\x00-\x7F]/; +/* eslint-enable no-control-regex */ + +function isMultibyte(str) { + assertString(str); + return multibyte.test(str); +} + +/** + * Build RegExp object from an array + * of multiple/multi-line regexp parts + * + * @param {string[]} parts + * @param {string} flags + * @return {object} - RegExp object + */ +function multilineRegexp(parts, flags) { + var regexpAsStringLiteral = parts.join(''); + return new RegExp(regexpAsStringLiteral, flags); +} + +/** + * Regular Expression to match + * semantic versioning (SemVer) + * built from multi-line, multi-parts regexp + * Reference: https://semver.org/ + */ + +var semanticVersioningRegex = multilineRegexp(['^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)', '(?:-((?:0|[1-9]\\d*|\\d*[a-z-][0-9a-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-z-][0-9a-z-]*))*))', '?(?:\\+([0-9a-z-]+(?:\\.[0-9a-z-]+)*))?$'], 'i'); +function isSemVer(str) { + assertString(str); + return semanticVersioningRegex.test(str); +} + +var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/; +function isSurrogatePair(str) { + assertString(str); + return surrogatePair.test(str); +} + +var includes = function includes(arr, val) { + return arr.some(function (arrVal) { + return val === arrVal; + }); +}; + +function decimalRegExp(options) { + var regExp = new RegExp("^[-+]?([0-9]+)?(\\".concat(decimal[options.locale], "[0-9]{").concat(options.decimal_digits, "})").concat(options.force_decimal ? '' : '?', "$")); + return regExp; +} + +var default_decimal_options = { + force_decimal: false, + decimal_digits: '1,', + locale: 'en-US' +}; +var blacklist = ['', '-', '+']; +function isDecimal(str, options) { + assertString(str); + options = merge(options, default_decimal_options); + + if (options.locale in decimal) { + return !includes(blacklist, str.replace(/ /g, '')) && decimalRegExp(options).test(str); + } + + throw new Error("Invalid locale '".concat(options.locale, "'")); +} + +var hexadecimal = /^(0x|0h)?[0-9A-F]+$/i; +function isHexadecimal(str) { + assertString(str); + return hexadecimal.test(str); +} + +var octal = /^(0o)?[0-7]+$/i; +function isOctal(str) { + assertString(str); + return octal.test(str); +} + +function isDivisibleBy(str, num) { + assertString(str); + return toFloat(str) % parseInt(num, 10) === 0; +} + +var hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i; +function isHexColor(str) { + assertString(str); + return hexcolor.test(str); +} + +var rgbColor = /^rgb\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\)$/; +var rgbaColor = /^rgba\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)$/; +var rgbColorPercent = /^rgb\((([0-9]%|[1-9][0-9]%|100%),){2}([0-9]%|[1-9][0-9]%|100%)\)/; +var rgbaColorPercent = /^rgba\((([0-9]%|[1-9][0-9]%|100%),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)/; +function isRgbColor(str) { + var includePercentValues = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + assertString(str); + + if (!includePercentValues) { + return rgbColor.test(str) || rgbaColor.test(str); + } + + return rgbColor.test(str) || rgbaColor.test(str) || rgbColorPercent.test(str) || rgbaColorPercent.test(str); +} + +var hslComma = /^hsla?\(((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?))(deg|grad|rad|turn)?(,(\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%){2}(,((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%?))?\)$/i; +var hslSpace = /^hsla?\(((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?))(deg|grad|rad|turn)?(\s(\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%){2}\s?(\/\s((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%?)\s?)?\)$/i; +function isHSL(str) { + assertString(str); // Strip duplicate spaces before calling the validation regex (See #1598 for more info) + + var strippedStr = str.replace(/\s+/g, ' ').replace(/\s?(hsla?\(|\)|,)\s?/ig, '$1'); + + if (strippedStr.indexOf(',') !== -1) { + return hslComma.test(strippedStr); + } + + return hslSpace.test(strippedStr); +} + +var isrc = /^[A-Z]{2}[0-9A-Z]{3}\d{2}\d{5}$/; +function isISRC(str) { + assertString(str); + return isrc.test(str); +} + +/** + * List of country codes with + * corresponding IBAN regular expression + * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number + */ + +var ibanRegexThroughCountryCode = { + AD: /^(AD[0-9]{2})\d{8}[A-Z0-9]{12}$/, + AE: /^(AE[0-9]{2})\d{3}\d{16}$/, + AL: /^(AL[0-9]{2})\d{8}[A-Z0-9]{16}$/, + AT: /^(AT[0-9]{2})\d{16}$/, + AZ: /^(AZ[0-9]{2})[A-Z0-9]{4}\d{20}$/, + BA: /^(BA[0-9]{2})\d{16}$/, + BE: /^(BE[0-9]{2})\d{12}$/, + BG: /^(BG[0-9]{2})[A-Z]{4}\d{6}[A-Z0-9]{8}$/, + BH: /^(BH[0-9]{2})[A-Z]{4}[A-Z0-9]{14}$/, + BR: /^(BR[0-9]{2})\d{23}[A-Z]{1}[A-Z0-9]{1}$/, + BY: /^(BY[0-9]{2})[A-Z0-9]{4}\d{20}$/, + CH: /^(CH[0-9]{2})\d{5}[A-Z0-9]{12}$/, + CR: /^(CR[0-9]{2})\d{18}$/, + CY: /^(CY[0-9]{2})\d{8}[A-Z0-9]{16}$/, + CZ: /^(CZ[0-9]{2})\d{20}$/, + DE: /^(DE[0-9]{2})\d{18}$/, + DK: /^(DK[0-9]{2})\d{14}$/, + DO: /^(DO[0-9]{2})[A-Z]{4}\d{20}$/, + EE: /^(EE[0-9]{2})\d{16}$/, + EG: /^(EG[0-9]{2})\d{25}$/, + ES: /^(ES[0-9]{2})\d{20}$/, + FI: /^(FI[0-9]{2})\d{14}$/, + FO: /^(FO[0-9]{2})\d{14}$/, + FR: /^(FR[0-9]{2})\d{10}[A-Z0-9]{11}\d{2}$/, + GB: /^(GB[0-9]{2})[A-Z]{4}\d{14}$/, + GE: /^(GE[0-9]{2})[A-Z0-9]{2}\d{16}$/, + GI: /^(GI[0-9]{2})[A-Z]{4}[A-Z0-9]{15}$/, + GL: /^(GL[0-9]{2})\d{14}$/, + GR: /^(GR[0-9]{2})\d{7}[A-Z0-9]{16}$/, + GT: /^(GT[0-9]{2})[A-Z0-9]{4}[A-Z0-9]{20}$/, + HR: /^(HR[0-9]{2})\d{17}$/, + HU: /^(HU[0-9]{2})\d{24}$/, + IE: /^(IE[0-9]{2})[A-Z0-9]{4}\d{14}$/, + IL: /^(IL[0-9]{2})\d{19}$/, + IQ: /^(IQ[0-9]{2})[A-Z]{4}\d{15}$/, + IR: /^(IR[0-9]{2})0\d{2}0\d{18}$/, + IS: /^(IS[0-9]{2})\d{22}$/, + IT: /^(IT[0-9]{2})[A-Z]{1}\d{10}[A-Z0-9]{12}$/, + JO: /^(JO[0-9]{2})[A-Z]{4}\d{22}$/, + KW: /^(KW[0-9]{2})[A-Z]{4}[A-Z0-9]{22}$/, + KZ: /^(KZ[0-9]{2})\d{3}[A-Z0-9]{13}$/, + LB: /^(LB[0-9]{2})\d{4}[A-Z0-9]{20}$/, + LC: /^(LC[0-9]{2})[A-Z]{4}[A-Z0-9]{24}$/, + LI: /^(LI[0-9]{2})\d{5}[A-Z0-9]{12}$/, + LT: /^(LT[0-9]{2})\d{16}$/, + LU: /^(LU[0-9]{2})\d{3}[A-Z0-9]{13}$/, + LV: /^(LV[0-9]{2})[A-Z]{4}[A-Z0-9]{13}$/, + MC: /^(MC[0-9]{2})\d{10}[A-Z0-9]{11}\d{2}$/, + MD: /^(MD[0-9]{2})[A-Z0-9]{20}$/, + ME: /^(ME[0-9]{2})\d{18}$/, + MK: /^(MK[0-9]{2})\d{3}[A-Z0-9]{10}\d{2}$/, + MR: /^(MR[0-9]{2})\d{23}$/, + MT: /^(MT[0-9]{2})[A-Z]{4}\d{5}[A-Z0-9]{18}$/, + MU: /^(MU[0-9]{2})[A-Z]{4}\d{19}[A-Z]{3}$/, + MZ: /^(MZ[0-9]{2})\d{21}$/, + NL: /^(NL[0-9]{2})[A-Z]{4}\d{10}$/, + NO: /^(NO[0-9]{2})\d{11}$/, + PK: /^(PK[0-9]{2})[A-Z0-9]{4}\d{16}$/, + PL: /^(PL[0-9]{2})\d{24}$/, + PS: /^(PS[0-9]{2})[A-Z0-9]{4}\d{21}$/, + PT: /^(PT[0-9]{2})\d{21}$/, + QA: /^(QA[0-9]{2})[A-Z]{4}[A-Z0-9]{21}$/, + RO: /^(RO[0-9]{2})[A-Z]{4}[A-Z0-9]{16}$/, + RS: /^(RS[0-9]{2})\d{18}$/, + SA: /^(SA[0-9]{2})\d{2}[A-Z0-9]{18}$/, + SC: /^(SC[0-9]{2})[A-Z]{4}\d{20}[A-Z]{3}$/, + SE: /^(SE[0-9]{2})\d{20}$/, + SI: /^(SI[0-9]{2})\d{15}$/, + SK: /^(SK[0-9]{2})\d{20}$/, + SM: /^(SM[0-9]{2})[A-Z]{1}\d{10}[A-Z0-9]{12}$/, + SV: /^(SV[0-9]{2})[A-Z0-9]{4}\d{20}$/, + TL: /^(TL[0-9]{2})\d{19}$/, + TN: /^(TN[0-9]{2})\d{20}$/, + TR: /^(TR[0-9]{2})\d{5}[A-Z0-9]{17}$/, + UA: /^(UA[0-9]{2})\d{6}[A-Z0-9]{19}$/, + VA: /^(VA[0-9]{2})\d{18}$/, + VG: /^(VG[0-9]{2})[A-Z0-9]{4}\d{16}$/, + XK: /^(XK[0-9]{2})\d{16}$/ +}; +/** + * Check whether string has correct universal IBAN format + * The IBAN consists of up to 34 alphanumeric characters, as follows: + * Country Code using ISO 3166-1 alpha-2, two letters + * check digits, two digits and + * Basic Bank Account Number (BBAN), up to 30 alphanumeric characters. + * NOTE: Permitted IBAN characters are: digits [0-9] and the 26 latin alphabetic [A-Z] + * + * @param {string} str - string under validation + * @return {boolean} + */ + +function hasValidIbanFormat(str) { + // Strip white spaces and hyphens + var strippedStr = str.replace(/[\s\-]+/gi, '').toUpperCase(); + var isoCountryCode = strippedStr.slice(0, 2).toUpperCase(); + return isoCountryCode in ibanRegexThroughCountryCode && ibanRegexThroughCountryCode[isoCountryCode].test(strippedStr); +} +/** + * Check whether string has valid IBAN Checksum + * by performing basic mod-97 operation and + * the remainder should equal 1 + * -- Start by rearranging the IBAN by moving the four initial characters to the end of the string + * -- Replace each letter in the string with two digits, A -> 10, B = 11, Z = 35 + * -- Interpret the string as a decimal integer and + * -- compute the remainder on division by 97 (mod 97) + * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number + * + * @param {string} str + * @return {boolean} + */ + + +function hasValidIbanChecksum(str) { + var strippedStr = str.replace(/[^A-Z0-9]+/gi, '').toUpperCase(); // Keep only digits and A-Z latin alphabetic + + var rearranged = strippedStr.slice(4) + strippedStr.slice(0, 4); + var alphaCapsReplacedWithDigits = rearranged.replace(/[A-Z]/g, function (_char) { + return _char.charCodeAt(0) - 55; + }); + var remainder = alphaCapsReplacedWithDigits.match(/\d{1,7}/g).reduce(function (acc, value) { + return Number(acc + value) % 97; + }, ''); + return remainder === 1; +} + +function isIBAN(str) { + assertString(str); + return hasValidIbanFormat(str) && hasValidIbanChecksum(str); +} +var locales$3 = Object.keys(ibanRegexThroughCountryCode); + +var validISO31661Alpha2CountriesCodes = new Set(['AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW']); +function isISO31661Alpha2(str) { + assertString(str); + return validISO31661Alpha2CountriesCodes.has(str.toUpperCase()); +} +var CountryCodes = validISO31661Alpha2CountriesCodes; + +var isBICReg = /^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$/; +function isBIC(str) { + assertString(str); // toUpperCase() should be removed when a new major version goes out that changes + // the regex to [A-Z] (per the spec). + + if (!CountryCodes.has(str.slice(4, 6).toUpperCase())) { + return false; + } + + return isBICReg.test(str); +} + +var md5 = /^[a-f0-9]{32}$/; +function isMD5(str) { + assertString(str); + return md5.test(str); +} + +var lengths = { + md5: 32, + md4: 32, + sha1: 40, + sha256: 64, + sha384: 96, + sha512: 128, + ripemd128: 32, + ripemd160: 40, + tiger128: 32, + tiger160: 40, + tiger192: 48, + crc32: 8, + crc32b: 8 +}; +function isHash(str, algorithm) { + assertString(str); + var hash = new RegExp("^[a-fA-F0-9]{".concat(lengths[algorithm], "}$")); + return hash.test(str); +} + +var notBase64 = /[^A-Z0-9+\/=]/i; +var urlSafeBase64 = /^[A-Z0-9_\-]*$/i; +var defaultBase64Options = { + urlSafe: false +}; +function isBase64(str, options) { + assertString(str); + options = merge(options, defaultBase64Options); + var len = str.length; + + if (options.urlSafe) { + return urlSafeBase64.test(str); + } + + if (len % 4 !== 0 || notBase64.test(str)) { + return false; + } + + var firstPaddingChar = str.indexOf('='); + return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '='; +} + +function isJWT(str) { + assertString(str); + var dotSplit = str.split('.'); + var len = dotSplit.length; + + if (len > 3 || len < 2) { + return false; + } + + return dotSplit.reduce(function (acc, currElem) { + return acc && isBase64(currElem, { + urlSafe: true + }); + }, true); +} + +var default_json_options = { + allow_primitives: false +}; +function isJSON(str, options) { + assertString(str); + + try { + options = merge(options, default_json_options); + var primitives = []; + + if (options.allow_primitives) { + primitives = [null, false, true]; + } + + var obj = JSON.parse(str); + return primitives.includes(obj) || !!obj && _typeof(obj) === 'object'; + } catch (e) { + /* ignore */ + } + + return false; +} + +var default_is_empty_options = { + ignore_whitespace: false +}; +function isEmpty(str, options) { + assertString(str); + options = merge(options, default_is_empty_options); + return (options.ignore_whitespace ? str.trim().length : str.length) === 0; +} + +/* eslint-disable prefer-rest-params */ + +function isLength(str, options) { + assertString(str); + var min; + var max; + + if (_typeof(options) === 'object') { + min = options.min || 0; + max = options.max; + } else { + // backwards compatibility: isLength(str, min [, max]) + min = arguments[1] || 0; + max = arguments[2]; + } + + var surrogatePairs = str.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []; + var len = str.length - surrogatePairs.length; + return len >= min && (typeof max === 'undefined' || len <= max); +} + +var uuid = { + 1: /^[0-9A-F]{8}-[0-9A-F]{4}-1[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + 2: /^[0-9A-F]{8}-[0-9A-F]{4}-2[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + 3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + 4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, + 5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, + all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i +}; +function isUUID(str, version) { + assertString(str); + var pattern = uuid[![undefined, null].includes(version) ? version : 'all']; + return !!pattern && pattern.test(str); +} + +function isMongoId(str) { + assertString(str); + return isHexadecimal(str) && str.length === 24; +} + +function isAfter(str) { + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date()); + assertString(str); + var comparison = toDate(date); + var original = toDate(str); + return !!(original && comparison && original > comparison); +} + +function isBefore(str) { + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date()); + assertString(str); + var comparison = toDate(date); + var original = toDate(str); + return !!(original && comparison && original < comparison); +} + +function isIn(str, options) { + assertString(str); + var i; + + if (Object.prototype.toString.call(options) === '[object Array]') { + var array = []; + + for (i in options) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if ({}.hasOwnProperty.call(options, i)) { + array[i] = toString$1(options[i]); + } + } + + return array.indexOf(str) >= 0; + } else if (_typeof(options) === 'object') { + return options.hasOwnProperty(str); + } else if (options && typeof options.indexOf === 'function') { + return options.indexOf(str) >= 0; + } + + return false; +} + +/* eslint-disable max-len */ + +var creditCard = /^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/; +/* eslint-enable max-len */ + +function isCreditCard(str) { + assertString(str); + var sanitized = str.replace(/[- ]+/g, ''); + + if (!creditCard.test(sanitized)) { + return false; + } + + var sum = 0; + var digit; + var tmpNum; + var shouldDouble; + + for (var i = sanitized.length - 1; i >= 0; i--) { + digit = sanitized.substring(i, i + 1); + tmpNum = parseInt(digit, 10); + + if (shouldDouble) { + tmpNum *= 2; + + if (tmpNum >= 10) { + sum += tmpNum % 10 + 1; + } else { + sum += tmpNum; + } + } else { + sum += tmpNum; + } + + shouldDouble = !shouldDouble; + } + + return !!(sum % 10 === 0 ? sanitized : false); +} + +var validators = { + PL: function PL(str) { + assertString(str); + var weightOfDigits = { + 1: 1, + 2: 3, + 3: 7, + 4: 9, + 5: 1, + 6: 3, + 7: 7, + 8: 9, + 9: 1, + 10: 3, + 11: 0 + }; + + if (str != null && str.length === 11 && isInt(str, { + allow_leading_zeroes: true + })) { + var digits = str.split('').slice(0, -1); + var sum = digits.reduce(function (acc, digit, index) { + return acc + Number(digit) * weightOfDigits[index + 1]; + }, 0); + var modulo = sum % 10; + var lastDigit = Number(str.charAt(str.length - 1)); + + if (modulo === 0 && lastDigit === 0 || lastDigit === 10 - modulo) { + return true; + } + } + + return false; + }, + ES: function ES(str) { + assertString(str); + var DNI = /^[0-9X-Z][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/; + var charsValue = { + X: 0, + Y: 1, + Z: 2 + }; + var controlDigits = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E']; // sanitize user input + + var sanitized = str.trim().toUpperCase(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } // validate the control digit + + + var number = sanitized.slice(0, -1).replace(/[X,Y,Z]/g, function (_char) { + return charsValue[_char]; + }); + return sanitized.endsWith(controlDigits[number % 23]); + }, + FI: function FI(str) { + // https://dvv.fi/en/personal-identity-code#:~:text=control%20character%20for%20a-,personal,-identity%20code%20calculated + assertString(str); + + if (str.length !== 11) { + return false; + } + + if (!str.match(/^\d{6}[\-A\+]\d{3}[0-9ABCDEFHJKLMNPRSTUVWXY]{1}$/)) { + return false; + } + + var checkDigits = '0123456789ABCDEFHJKLMNPRSTUVWXY'; + var idAsNumber = parseInt(str.slice(0, 6), 10) * 1000 + parseInt(str.slice(7, 10), 10); + var remainder = idAsNumber % 31; + var checkDigit = checkDigits[remainder]; + return checkDigit === str.slice(10, 11); + }, + IN: function IN(str) { + var DNI = /^[1-9]\d{3}\s?\d{4}\s?\d{4}$/; // multiplication table + + var d = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]; // permutation table + + var p = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } + + var c = 0; + var invertedArray = sanitized.replace(/\s/g, '').split('').map(Number).reverse(); + invertedArray.forEach(function (val, i) { + c = d[c][p[i % 8][val]]; + }); + return c === 0; + }, + IR: function IR(str) { + if (!str.match(/^\d{10}$/)) return false; + str = "0000".concat(str).substr(str.length - 6); + if (parseInt(str.substr(3, 6), 10) === 0) return false; + var lastNumber = parseInt(str.substr(9, 1), 10); + var sum = 0; + + for (var i = 0; i < 9; i++) { + sum += parseInt(str.substr(i, 1), 10) * (10 - i); + } + + sum %= 11; + return sum < 2 && lastNumber === sum || sum >= 2 && lastNumber === 11 - sum; + }, + IT: function IT(str) { + if (str.length !== 9) return false; + if (str === 'CA00000AA') return false; // https://it.wikipedia.org/wiki/Carta_d%27identit%C3%A0_elettronica_italiana + + return str.search(/C[A-Z][0-9]{5}[A-Z]{2}/i) > -1; + }, + NO: function NO(str) { + var sanitized = str.trim(); + if (isNaN(Number(sanitized))) return false; + if (sanitized.length !== 11) return false; + if (sanitized === '00000000000') return false; // https://no.wikipedia.org/wiki/F%C3%B8dselsnummer + + var f = sanitized.split('').map(Number); + var k1 = (11 - (3 * f[0] + 7 * f[1] + 6 * f[2] + 1 * f[3] + 8 * f[4] + 9 * f[5] + 4 * f[6] + 5 * f[7] + 2 * f[8]) % 11) % 11; + var k2 = (11 - (5 * f[0] + 4 * f[1] + 3 * f[2] + 2 * f[3] + 7 * f[4] + 6 * f[5] + 5 * f[6] + 4 * f[7] + 3 * f[8] + 2 * k1) % 11) % 11; + if (k1 !== f[9] || k2 !== f[10]) return false; + return true; + }, + TH: function TH(str) { + if (!str.match(/^[1-8]\d{12}$/)) return false; // validate check digit + + var sum = 0; + + for (var i = 0; i < 12; i++) { + sum += parseInt(str[i], 10) * (13 - i); + } + + return str[12] === ((11 - sum % 11) % 10).toString(); + }, + LK: function LK(str) { + var old_nic = /^[1-9]\d{8}[vx]$/i; + var new_nic = /^[1-9]\d{11}$/i; + if (str.length === 10 && old_nic.test(str)) return true;else if (str.length === 12 && new_nic.test(str)) return true; + return false; + }, + 'he-IL': function heIL(str) { + var DNI = /^\d{9}$/; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } + + var id = sanitized; + var sum = 0, + incNum; + + for (var i = 0; i < id.length; i++) { + incNum = Number(id[i]) * (i % 2 + 1); // Multiply number by 1 or 2 + + sum += incNum > 9 ? incNum - 9 : incNum; // Sum the digits up and add to total + } + + return sum % 10 === 0; + }, + 'ar-LY': function arLY(str) { + // Libya National Identity Number NIN is 12 digits, the first digit is either 1 or 2 + var NIN = /^(1|2)\d{11}$/; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!NIN.test(sanitized)) { + return false; + } + + return true; + }, + 'ar-TN': function arTN(str) { + var DNI = /^\d{8}$/; // sanitize user input + + var sanitized = str.trim(); // validate the data structure + + if (!DNI.test(sanitized)) { + return false; + } + + return true; + }, + 'zh-CN': function zhCN(str) { + var provincesAndCities = ['11', // 北京 + '12', // 天津 + '13', // 河北 + '14', // 山西 + '15', // 内蒙古 + '21', // 辽宁 + '22', // 吉林 + '23', // 黑龙江 + '31', // 上海 + '32', // 江苏 + '33', // 浙江 + '34', // 安徽 + '35', // 福建 + '36', // 江西 + '37', // 山东 + '41', // 河南 + '42', // 湖北 + '43', // 湖南 + '44', // 广东 + '45', // 广西 + '46', // 海南 + '50', // 重庆 + '51', // 四川 + '52', // 贵州 + '53', // 云南 + '54', // 西藏 + '61', // 陕西 + '62', // 甘肃 + '63', // 青海 + '64', // 宁夏 + '65', // 新疆 + '71', // 台湾 + '81', // 香港 + '82', // 澳门 + '91' // 国外 + ]; + var powers = ['7', '9', '10', '5', '8', '4', '2', '1', '6', '3', '7', '9', '10', '5', '8', '4', '2']; + var parityBit = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']; + + var checkAddressCode = function checkAddressCode(addressCode) { + return provincesAndCities.includes(addressCode); + }; + + var checkBirthDayCode = function checkBirthDayCode(birDayCode) { + var yyyy = parseInt(birDayCode.substring(0, 4), 10); + var mm = parseInt(birDayCode.substring(4, 6), 10); + var dd = parseInt(birDayCode.substring(6), 10); + var xdata = new Date(yyyy, mm - 1, dd); + + if (xdata > new Date()) { + return false; // eslint-disable-next-line max-len + } else if (xdata.getFullYear() === yyyy && xdata.getMonth() === mm - 1 && xdata.getDate() === dd) { + return true; + } + + return false; + }; + + var getParityBit = function getParityBit(idCardNo) { + var id17 = idCardNo.substring(0, 17); + var power = 0; + + for (var i = 0; i < 17; i++) { + power += parseInt(id17.charAt(i), 10) * parseInt(powers[i], 10); + } + + var mod = power % 11; + return parityBit[mod]; + }; + + var checkParityBit = function checkParityBit(idCardNo) { + return getParityBit(idCardNo) === idCardNo.charAt(17).toUpperCase(); + }; + + var check15IdCardNo = function check15IdCardNo(idCardNo) { + var check = /^[1-9]\d{7}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}$/.test(idCardNo); + if (!check) return false; + var addressCode = idCardNo.substring(0, 2); + check = checkAddressCode(addressCode); + if (!check) return false; + var birDayCode = "19".concat(idCardNo.substring(6, 12)); + check = checkBirthDayCode(birDayCode); + if (!check) return false; + return true; + }; + + var check18IdCardNo = function check18IdCardNo(idCardNo) { + var check = /^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}(\d|x|X)$/.test(idCardNo); + if (!check) return false; + var addressCode = idCardNo.substring(0, 2); + check = checkAddressCode(addressCode); + if (!check) return false; + var birDayCode = idCardNo.substring(6, 14); + check = checkBirthDayCode(birDayCode); + if (!check) return false; + return checkParityBit(idCardNo); + }; + + var checkIdCardNo = function checkIdCardNo(idCardNo) { + var check = /^\d{15}|(\d{17}(\d|x|X))$/.test(idCardNo); + if (!check) return false; + + if (idCardNo.length === 15) { + return check15IdCardNo(idCardNo); + } + + return check18IdCardNo(idCardNo); + }; + + return checkIdCardNo(str); + }, + 'zh-TW': function zhTW(str) { + var ALPHABET_CODES = { + A: 10, + B: 11, + C: 12, + D: 13, + E: 14, + F: 15, + G: 16, + H: 17, + I: 34, + J: 18, + K: 19, + L: 20, + M: 21, + N: 22, + O: 35, + P: 23, + Q: 24, + R: 25, + S: 26, + T: 27, + U: 28, + V: 29, + W: 32, + X: 30, + Y: 31, + Z: 33 + }; + var sanitized = str.trim().toUpperCase(); + if (!/^[A-Z][0-9]{9}$/.test(sanitized)) return false; + return Array.from(sanitized).reduce(function (sum, number, index) { + if (index === 0) { + var code = ALPHABET_CODES[number]; + return code % 10 * 9 + Math.floor(code / 10); + } + + if (index === 9) { + return (10 - sum % 10 - Number(number)) % 10 === 0; + } + + return sum + Number(number) * (9 - index); + }, 0); + } +}; +function isIdentityCard(str, locale) { + assertString(str); + + if (locale in validators) { + return validators[locale](str); + } else if (locale === 'any') { + for (var key in validators) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (validators.hasOwnProperty(key)) { + var validator = validators[key]; + + if (validator(str)) { + return true; + } + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} + +/** + * The most commonly used EAN standard is + * the thirteen-digit EAN-13, while the + * less commonly used 8-digit EAN-8 barcode was + * introduced for use on small packages. + * Also EAN/UCC-14 is used for Grouping of individual + * trade items above unit level(Intermediate, Carton or Pallet). + * For more info about EAN-14 checkout: https://www.gtin.info/itf-14-barcodes/ + * EAN consists of: + * GS1 prefix, manufacturer code, product code and check digit + * Reference: https://en.wikipedia.org/wiki/International_Article_Number + * Reference: https://www.gtin.info/ + */ +/** + * Define EAN Lenghts; 8 for EAN-8; 13 for EAN-13; 14 for EAN-14 + * and Regular Expression for valid EANs (EAN-8, EAN-13, EAN-14), + * with exact numberic matching of 8 or 13 or 14 digits [0-9] + */ + +var LENGTH_EAN_8 = 8; +var LENGTH_EAN_14 = 14; +var validEanRegex = /^(\d{8}|\d{13}|\d{14})$/; +/** + * Get position weight given: + * EAN length and digit index/position + * + * @param {number} length + * @param {number} index + * @return {number} + */ + +function getPositionWeightThroughLengthAndIndex(length, index) { + if (length === LENGTH_EAN_8 || length === LENGTH_EAN_14) { + return index % 2 === 0 ? 3 : 1; + } + + return index % 2 === 0 ? 1 : 3; +} +/** + * Calculate EAN Check Digit + * Reference: https://en.wikipedia.org/wiki/International_Article_Number#Calculation_of_checksum_digit + * + * @param {string} ean + * @return {number} + */ + + +function calculateCheckDigit(ean) { + var checksum = ean.slice(0, -1).split('').map(function (_char, index) { + return Number(_char) * getPositionWeightThroughLengthAndIndex(ean.length, index); + }).reduce(function (acc, partialSum) { + return acc + partialSum; + }, 0); + var remainder = 10 - checksum % 10; + return remainder < 10 ? remainder : 0; +} +/** + * Check if string is valid EAN: + * Matches EAN-8/EAN-13/EAN-14 regex + * Has valid check digit. + * + * @param {string} str + * @return {boolean} + */ + + +function isEAN(str) { + assertString(str); + var actualCheckDigit = Number(str.slice(-1)); + return validEanRegex.test(str) && actualCheckDigit === calculateCheckDigit(str); +} + +var isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/; // this link details how the check digit is calculated: +// https://www.isin.org/isin-format/. it is a little bit +// odd in that it works with digits, not numbers. in order +// to make only one pass through the ISIN characters, the +// each alpha character is handled as 2 characters within +// the loop. + +function isISIN(str) { + assertString(str); + + if (!isin.test(str)) { + return false; + } + + var _double = true; + var sum = 0; // convert values + + for (var i = str.length - 2; i >= 0; i--) { + if (str[i] >= 'A' && str[i] <= 'Z') { + var value = str[i].charCodeAt(0) - 55; + var lo = value % 10; + var hi = Math.trunc(value / 10); // letters have two digits, so handle the low order + // and high order digits separately. + + for (var _i = 0, _arr = [lo, hi]; _i < _arr.length; _i++) { + var digit = _arr[_i]; + + if (_double) { + if (digit >= 5) { + sum += 1 + (digit - 5) * 2; + } else { + sum += digit * 2; + } + } else { + sum += digit; + } + + _double = !_double; + } + } else { + var _digit = str[i].charCodeAt(0) - '0'.charCodeAt(0); + + if (_double) { + if (_digit >= 5) { + sum += 1 + (_digit - 5) * 2; + } else { + sum += _digit * 2; + } + } else { + sum += _digit; + } + + _double = !_double; + } + } + + var check = Math.trunc((sum + 9) / 10) * 10 - sum; + return +str[str.length - 1] === check; +} + +var isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/; +var isbn13Maybe = /^(?:[0-9]{13})$/; +var factor = [1, 3]; +function isISBN(str) { + var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + assertString(str); + version = String(version); + + if (!version) { + return isISBN(str, 10) || isISBN(str, 13); + } + + var sanitized = str.replace(/[\s-]+/g, ''); + var checksum = 0; + var i; + + if (version === '10') { + if (!isbn10Maybe.test(sanitized)) { + return false; + } + + for (i = 0; i < 9; i++) { + checksum += (i + 1) * sanitized.charAt(i); + } + + if (sanitized.charAt(9) === 'X') { + checksum += 10 * 10; + } else { + checksum += 10 * sanitized.charAt(9); + } + + if (checksum % 11 === 0) { + return !!sanitized; + } + } else if (version === '13') { + if (!isbn13Maybe.test(sanitized)) { + return false; + } + + for (i = 0; i < 12; i++) { + checksum += factor[i % 2] * sanitized.charAt(i); + } + + if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) { + return !!sanitized; + } + } + + return false; +} + +var issn = '^\\d{4}-?\\d{3}[\\dX]$'; +function isISSN(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + assertString(str); + var testIssn = issn; + testIssn = options.require_hyphen ? testIssn.replace('?', '') : testIssn; + testIssn = options.case_sensitive ? new RegExp(testIssn) : new RegExp(testIssn, 'i'); + + if (!testIssn.test(str)) { + return false; + } + + var digits = str.replace('-', '').toUpperCase(); + var checksum = 0; + + for (var i = 0; i < digits.length; i++) { + var digit = digits[i]; + checksum += (digit === 'X' ? 10 : +digit) * (8 - i); + } + + return checksum % 11 === 0; +} + +/** + * Algorithmic validation functions + * May be used as is or implemented in the workflow of other validators. + */ + +/* + * ISO 7064 validation function + * Called with a string of numbers (incl. check digit) + * to validate according to ISO 7064 (MOD 11, 10). + */ +function iso7064Check(str) { + var checkvalue = 10; + + for (var i = 0; i < str.length - 1; i++) { + checkvalue = (parseInt(str[i], 10) + checkvalue) % 10 === 0 ? 10 * 2 % 11 : (parseInt(str[i], 10) + checkvalue) % 10 * 2 % 11; + } + + checkvalue = checkvalue === 1 ? 0 : 11 - checkvalue; + return checkvalue === parseInt(str[10], 10); +} +/* + * Luhn (mod 10) validation function + * Called with a string of numbers (incl. check digit) + * to validate according to the Luhn algorithm. + */ + +function luhnCheck(str) { + var checksum = 0; + var second = false; + + for (var i = str.length - 1; i >= 0; i--) { + if (second) { + var product = parseInt(str[i], 10) * 2; + + if (product > 9) { + // sum digits of product and add to checksum + checksum += product.toString().split('').map(function (a) { + return parseInt(a, 10); + }).reduce(function (a, b) { + return a + b; + }, 0); + } else { + checksum += product; + } + } else { + checksum += parseInt(str[i], 10); + } + + second = !second; + } + + return checksum % 10 === 0; +} +/* + * Reverse TIN multiplication and summation helper function + * Called with an array of single-digit integers and a base multiplier + * to calculate the sum of the digits multiplied in reverse. + * Normally used in variations of MOD 11 algorithmic checks. + */ + +function reverseMultiplyAndSum(digits, base) { + var total = 0; + + for (var i = 0; i < digits.length; i++) { + total += digits[i] * (base - i); + } + + return total; +} +/* + * Verhoeff validation helper function + * Called with a string of numbers + * to validate according to the Verhoeff algorithm. + */ + +function verhoeffCheck(str) { + var d_table = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]; + var p_table = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]; // Copy (to prevent replacement) and reverse + + var str_copy = str.split('').reverse().join(''); + var checksum = 0; + + for (var i = 0; i < str_copy.length; i++) { + checksum = d_table[checksum][p_table[i % 8][parseInt(str_copy[i], 10)]]; + } + + return checksum === 0; +} + +/** + * TIN Validation + * Validates Tax Identification Numbers (TINs) from the US, EU member states and the United Kingdom. + * + * EU-UK: + * National TIN validity is calculated using public algorithms as made available by DG TAXUD. + * + * See `https://ec.europa.eu/taxation_customs/tin/specs/FS-TIN%20Algorithms-Public.docx` for more information. + * + * US: + * An Employer Identification Number (EIN), also known as a Federal Tax Identification Number, + * is used to identify a business entity. + * + * NOTES: + * - Prefix 47 is being reserved for future use + * - Prefixes 26, 27, 45, 46 and 47 were previously assigned by the Philadelphia campus. + * + * See `http://www.irs.gov/Businesses/Small-Businesses-&-Self-Employed/How-EINs-are-Assigned-and-Valid-EIN-Prefixes` + * for more information. + */ +// Locale functions + +/* + * bg-BG validation function + * (Edinen graždanski nomer (EGN/ЕГН), persons only) + * Checks if birth date (first six digits) is valid and calculates check (last) digit + */ + +function bgBgCheck(tin) { + // Extract full year, normalize month and check birth date validity + var century_year = tin.slice(0, 2); + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 40) { + month -= 40; + century_year = "20".concat(century_year); + } else if (month > 20) { + month -= 20; + century_year = "18".concat(century_year); + } else { + century_year = "19".concat(century_year); + } + + if (month < 10) { + month = "0".concat(month); + } + + var date = "".concat(century_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // split digits into an array for further processing + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); // Calculate checksum by multiplying digits with fixed values + + var multip_lookup = [2, 4, 8, 5, 10, 9, 7, 3, 6]; + var checksum = 0; + + for (var i = 0; i < multip_lookup.length; i++) { + checksum += digits[i] * multip_lookup[i]; + } + + checksum = checksum % 11 === 10 ? 0 : checksum % 11; + return checksum === digits[9]; +} +/* + * cs-CZ validation function + * (Rodné číslo (RČ), persons only) + * Checks if birth date (first six digits) is valid and divisibility by 11 + * Material not in DG TAXUD document sourced from: + * -`https://lorenc.info/3MA381/overeni-spravnosti-rodneho-cisla.htm` + * -`https://www.mvcr.cz/clanek/rady-a-sluzby-dokumenty-rodne-cislo.aspx` + */ + + +function csCzCheck(tin) { + tin = tin.replace(/\W/, ''); // Extract full year from TIN length + + var full_year = parseInt(tin.slice(0, 2), 10); + + if (tin.length === 10) { + if (full_year < 54) { + full_year = "20".concat(full_year); + } else { + full_year = "19".concat(full_year); + } + } else { + if (tin.slice(6) === '000') { + return false; + } // Three-zero serial not assigned before 1954 + + + if (full_year < 54) { + full_year = "19".concat(full_year); + } else { + return false; // No 18XX years seen in any of the resources + } + } // Add missing zero if needed + + + if (full_year.length === 3) { + full_year = [full_year.slice(0, 2), '0', full_year.slice(2)].join(''); + } // Extract month from TIN and normalize + + + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 50) { + month -= 50; + } + + if (month > 20) { + // Month-plus-twenty was only introduced in 2004 + if (parseInt(full_year, 10) < 2004) { + return false; + } + + month -= 20; + } + + if (month < 10) { + month = "0".concat(month); + } // Check date validity + + + var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Verify divisibility by 11 + + + if (tin.length === 10) { + if (parseInt(tin, 10) % 11 !== 0) { + // Some numbers up to and including 1985 are still valid if + // check (last) digit equals 0 and modulo of first 9 digits equals 10 + var checkdigit = parseInt(tin.slice(0, 9), 10) % 11; + + if (parseInt(full_year, 10) < 1986 && checkdigit === 10) { + if (parseInt(tin.slice(9), 10) !== 0) { + return false; + } + } else { + return false; + } + } + } + + return true; +} +/* + * de-AT validation function + * (Abgabenkontonummer, persons/entities) + * Verify TIN validity by calling luhnCheck() + */ + + +function deAtCheck(tin) { + return luhnCheck(tin); +} +/* + * de-DE validation function + * (Steueridentifikationsnummer (Steuer-IdNr.), persons only) + * Tests for single duplicate/triplicate value, then calculates ISO 7064 check (last) digit + * Partial implementation of spec (same result with both algorithms always) + */ + + +function deDeCheck(tin) { + // Split digits into an array for further processing + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); // Fill array with strings of number positions + + var occurences = []; + + for (var i = 0; i < digits.length - 1; i++) { + occurences.push(''); + + for (var j = 0; j < digits.length - 1; j++) { + if (digits[i] === digits[j]) { + occurences[i] += j; + } + } + } // Remove digits with one occurence and test for only one duplicate/triplicate + + + occurences = occurences.filter(function (a) { + return a.length > 1; + }); + + if (occurences.length !== 2 && occurences.length !== 3) { + return false; + } // In case of triplicate value only two digits are allowed next to each other + + + if (occurences[0].length === 3) { + var trip_locations = occurences[0].split('').map(function (a) { + return parseInt(a, 10); + }); + var recurrent = 0; // Amount of neighbour occurences + + for (var _i = 0; _i < trip_locations.length - 1; _i++) { + if (trip_locations[_i] + 1 === trip_locations[_i + 1]) { + recurrent += 1; + } + } + + if (recurrent === 2) { + return false; + } + } + + return iso7064Check(tin); +} +/* + * dk-DK validation function + * (CPR-nummer (personnummer), persons only) + * Checks if birth date (first six digits) is valid and assigned to century (seventh) digit, + * and calculates check (last) digit + */ + + +function dkDkCheck(tin) { + tin = tin.replace(/\W/, ''); // Extract year, check if valid for given century digit and add century + + var year = parseInt(tin.slice(4, 6), 10); + var century_digit = tin.slice(6, 7); + + switch (century_digit) { + case '0': + case '1': + case '2': + case '3': + year = "19".concat(year); + break; + + case '4': + case '9': + if (year < 37) { + year = "20".concat(year); + } else { + year = "19".concat(year); + } + + break; + + default: + if (year < 37) { + year = "20".concat(year); + } else if (year > 58) { + year = "18".concat(year); + } else { + return false; + } + + break; + } // Add missing zero if needed + + + if (year.length === 3) { + year = [year.slice(0, 2), '0', year.slice(2)].join(''); + } // Check date validity + + + var date = "".concat(year, "/").concat(tin.slice(2, 4), "/").concat(tin.slice(0, 2)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Split digits into an array for further processing + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; + var weight = 4; // Multiply by weight and add to checksum + + for (var i = 0; i < 9; i++) { + checksum += digits[i] * weight; + weight -= 1; + + if (weight === 1) { + weight = 7; + } + } + + checksum %= 11; + + if (checksum === 1) { + return false; + } + + return checksum === 0 ? digits[9] === 0 : digits[9] === 11 - checksum; +} +/* + * el-CY validation function + * (Arithmos Forologikou Mitroou (AFM/ΑΦΜ), persons only) + * Verify TIN validity by calculating ASCII value of check (last) character + */ + + +function elCyCheck(tin) { + // split digits into an array for further processing + var digits = tin.slice(0, 8).split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; // add digits in even places + + for (var i = 1; i < digits.length; i += 2) { + checksum += digits[i]; + } // add digits in odd places + + + for (var _i2 = 0; _i2 < digits.length; _i2 += 2) { + if (digits[_i2] < 2) { + checksum += 1 - digits[_i2]; + } else { + checksum += 2 * (digits[_i2] - 2) + 5; + + if (digits[_i2] > 4) { + checksum += 2; + } + } + } + + return String.fromCharCode(checksum % 26 + 65) === tin.charAt(8); +} +/* + * el-GR validation function + * (Arithmos Forologikou Mitroou (AFM/ΑΦΜ), persons/entities) + * Verify TIN validity by calculating check (last) digit + * Algorithm not in DG TAXUD document- sourced from: + * - `http://epixeirisi.gr/%CE%9A%CE%A1%CE%99%CE%A3%CE%99%CE%9C%CE%91-%CE%98%CE%95%CE%9C%CE%91%CE%A4%CE%91-%CE%A6%CE%9F%CE%A1%CE%9F%CE%9B%CE%9F%CE%93%CE%99%CE%91%CE%A3-%CE%9A%CE%91%CE%99-%CE%9B%CE%9F%CE%93%CE%99%CE%A3%CE%A4%CE%99%CE%9A%CE%97%CE%A3/23791/%CE%91%CF%81%CE%B9%CE%B8%CE%BC%CF%8C%CF%82-%CE%A6%CE%BF%CF%81%CE%BF%CE%BB%CE%BF%CE%B3%CE%B9%CE%BA%CE%BF%CF%8D-%CE%9C%CE%B7%CF%84%CF%81%CF%8E%CE%BF%CF%85` + */ + + +function elGrCheck(tin) { + // split digits into an array for further processing + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; + + for (var i = 0; i < 8; i++) { + checksum += digits[i] * Math.pow(2, 8 - i); + } + + return checksum % 11 % 10 === digits[8]; +} +/* + * en-GB validation function (should go here if needed) + * (National Insurance Number (NINO) or Unique Taxpayer Reference (UTR), + * persons/entities respectively) + */ + +/* + * en-IE validation function + * (Personal Public Service Number (PPS No), persons only) + * Verify TIN validity by calculating check (second to last) character + */ + + +function enIeCheck(tin) { + var checksum = reverseMultiplyAndSum(tin.split('').slice(0, 7).map(function (a) { + return parseInt(a, 10); + }), 8); + + if (tin.length === 9 && tin[8] !== 'W') { + checksum += (tin[8].charCodeAt(0) - 64) * 9; + } + + checksum %= 23; + + if (checksum === 0) { + return tin[7].toUpperCase() === 'W'; + } + + return tin[7].toUpperCase() === String.fromCharCode(64 + checksum); +} // Valid US IRS campus prefixes + + +var enUsCampusPrefix = { + andover: ['10', '12'], + atlanta: ['60', '67'], + austin: ['50', '53'], + brookhaven: ['01', '02', '03', '04', '05', '06', '11', '13', '14', '16', '21', '22', '23', '25', '34', '51', '52', '54', '55', '56', '57', '58', '59', '65'], + cincinnati: ['30', '32', '35', '36', '37', '38', '61'], + fresno: ['15', '24'], + internet: ['20', '26', '27', '45', '46', '47'], + kansas: ['40', '44'], + memphis: ['94', '95'], + ogden: ['80', '90'], + philadelphia: ['33', '39', '41', '42', '43', '46', '48', '62', '63', '64', '66', '68', '71', '72', '73', '74', '75', '76', '77', '81', '82', '83', '84', '85', '86', '87', '88', '91', '92', '93', '98', '99'], + sba: ['31'] +}; // Return an array of all US IRS campus prefixes + +function enUsGetPrefixes() { + var prefixes = []; + + for (var location in enUsCampusPrefix) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (enUsCampusPrefix.hasOwnProperty(location)) { + prefixes.push.apply(prefixes, _toConsumableArray(enUsCampusPrefix[location])); + } + } + + return prefixes; +} +/* + * en-US validation function + * Verify that the TIN starts with a valid IRS campus prefix + */ + + +function enUsCheck(tin) { + return enUsGetPrefixes().indexOf(tin.substr(0, 2)) !== -1; +} +/* + * es-ES validation function + * (Documento Nacional de Identidad (DNI) + * or Número de Identificación de Extranjero (NIE), persons only) + * Verify TIN validity by calculating check (last) character + */ + + +function esEsCheck(tin) { + // Split characters into an array for further processing + var chars = tin.toUpperCase().split(''); // Replace initial letter if needed + + if (isNaN(parseInt(chars[0], 10)) && chars.length > 1) { + var lead_replace = 0; + + switch (chars[0]) { + case 'Y': + lead_replace = 1; + break; + + case 'Z': + lead_replace = 2; + break; + + default: + } + + chars.splice(0, 1, lead_replace); // Fill with zeros if smaller than proper + } else { + while (chars.length < 9) { + chars.unshift(0); + } + } // Calculate checksum and check according to lookup + + + var lookup = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E']; + chars = chars.join(''); + var checksum = parseInt(chars.slice(0, 8), 10) % 23; + return chars[8] === lookup[checksum]; +} +/* + * et-EE validation function + * (Isikukood (IK), persons only) + * Checks if birth date (century digit and six following) is valid and calculates check (last) digit + * Material not in DG TAXUD document sourced from: + * - `https://www.oecd.org/tax/automatic-exchange/crs-implementation-and-assistance/tax-identification-numbers/Estonia-TIN.pdf` + */ + + +function etEeCheck(tin) { + // Extract year and add century + var full_year = tin.slice(1, 3); + var century_digit = tin.slice(0, 1); + + switch (century_digit) { + case '1': + case '2': + full_year = "18".concat(full_year); + break; + + case '3': + case '4': + full_year = "19".concat(full_year); + break; + + default: + full_year = "20".concat(full_year); + break; + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(3, 5), "/").concat(tin.slice(5, 7)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Split digits into an array for further processing + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 0; + var weight = 1; // Multiply by weight and add to checksum + + for (var i = 0; i < 10; i++) { + checksum += digits[i] * weight; + weight += 1; + + if (weight === 10) { + weight = 1; + } + } // Do again if modulo 11 of checksum is 10 + + + if (checksum % 11 === 10) { + checksum = 0; + weight = 3; + + for (var _i3 = 0; _i3 < 10; _i3++) { + checksum += digits[_i3] * weight; + weight += 1; + + if (weight === 10) { + weight = 1; + } + } + + if (checksum % 11 === 10) { + return digits[10] === 0; + } + } + + return checksum % 11 === digits[10]; +} +/* + * fi-FI validation function + * (Henkilötunnus (HETU), persons only) + * Checks if birth date (first six digits plus century symbol) is valid + * and calculates check (last) digit + */ + + +function fiFiCheck(tin) { + // Extract year and add century + var full_year = tin.slice(4, 6); + var century_symbol = tin.slice(6, 7); + + switch (century_symbol) { + case '+': + full_year = "18".concat(full_year); + break; + + case '-': + full_year = "19".concat(full_year); + break; + + default: + full_year = "20".concat(full_year); + break; + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(2, 4), "/").concat(tin.slice(0, 2)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Calculate check character + + + var checksum = parseInt(tin.slice(0, 6) + tin.slice(7, 10), 10) % 31; + + if (checksum < 10) { + return checksum === parseInt(tin.slice(10), 10); + } + + checksum -= 10; + var letters_lookup = ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y']; + return letters_lookup[checksum] === tin.slice(10); +} +/* + * fr/nl-BE validation function + * (Numéro national (N.N.), persons only) + * Checks if birth date (first six digits) is valid and calculates check (last two) digits + */ + + +function frBeCheck(tin) { + // Zero month/day value is acceptable + if (tin.slice(2, 4) !== '00' || tin.slice(4, 6) !== '00') { + // Extract date from first six digits of TIN + var date = "".concat(tin.slice(0, 2), "/").concat(tin.slice(2, 4), "/").concat(tin.slice(4, 6)); + + if (!isDate(date, 'YY/MM/DD')) { + return false; + } + } + + var checksum = 97 - parseInt(tin.slice(0, 9), 10) % 97; + var checkdigits = parseInt(tin.slice(9, 11), 10); + + if (checksum !== checkdigits) { + checksum = 97 - parseInt("2".concat(tin.slice(0, 9)), 10) % 97; + + if (checksum !== checkdigits) { + return false; + } + } + + return true; +} +/* + * fr-FR validation function + * (Numéro fiscal de référence (numéro SPI), persons only) + * Verify TIN validity by calculating check (last three) digits + */ + + +function frFrCheck(tin) { + tin = tin.replace(/\s/g, ''); + var checksum = parseInt(tin.slice(0, 10), 10) % 511; + var checkdigits = parseInt(tin.slice(10, 13), 10); + return checksum === checkdigits; +} +/* + * fr/lb-LU validation function + * (numéro d’identification personnelle, persons only) + * Verify birth date validity and run Luhn and Verhoeff checks + */ + + +function frLuCheck(tin) { + // Extract date and check validity + var date = "".concat(tin.slice(0, 4), "/").concat(tin.slice(4, 6), "/").concat(tin.slice(6, 8)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Run Luhn check + + + if (!luhnCheck(tin.slice(0, 12))) { + return false; + } // Remove Luhn check digit and run Verhoeff check + + + return verhoeffCheck("".concat(tin.slice(0, 11)).concat(tin[12])); +} +/* + * hr-HR validation function + * (Osobni identifikacijski broj (OIB), persons/entities) + * Verify TIN validity by calling iso7064Check(digits) + */ + + +function hrHrCheck(tin) { + return iso7064Check(tin); +} +/* + * hu-HU validation function + * (Adóazonosító jel, persons only) + * Verify TIN validity by calculating check (last) digit + */ + + +function huHuCheck(tin) { + // split digits into an array for further processing + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var checksum = 8; + + for (var i = 1; i < 9; i++) { + checksum += digits[i] * (i + 1); + } + + return checksum % 11 === digits[9]; +} +/* + * lt-LT validation function (should go here if needed) + * (Asmens kodas, persons/entities respectively) + * Current validation check is alias of etEeCheck- same format applies + */ + +/* + * it-IT first/last name validity check + * Accepts it-IT TIN-encoded names as a three-element character array and checks their validity + * Due to lack of clarity between resources ("Are only Italian consonants used? + * What happens if a person has X in their name?" etc.) only two test conditions + * have been implemented: + * Vowels may only be followed by other vowels or an X character + * and X characters after vowels may only be followed by other X characters. + */ + + +function itItNameCheck(name) { + // true at the first occurence of a vowel + var vowelflag = false; // true at the first occurence of an X AFTER vowel + // (to properly handle last names with X as consonant) + + var xflag = false; + + for (var i = 0; i < 3; i++) { + if (!vowelflag && /[AEIOU]/.test(name[i])) { + vowelflag = true; + } else if (!xflag && vowelflag && name[i] === 'X') { + xflag = true; + } else if (i > 0) { + if (vowelflag && !xflag) { + if (!/[AEIOU]/.test(name[i])) { + return false; + } + } + + if (xflag) { + if (!/X/.test(name[i])) { + return false; + } + } + } + } + + return true; +} +/* + * it-IT validation function + * (Codice fiscale (TIN-IT), persons only) + * Verify name, birth date and codice catastale validity + * and calculate check character. + * Material not in DG-TAXUD document sourced from: + * `https://en.wikipedia.org/wiki/Italian_fiscal_code` + */ + + +function itItCheck(tin) { + // Capitalize and split characters into an array for further processing + var chars = tin.toUpperCase().split(''); // Check first and last name validity calling itItNameCheck() + + if (!itItNameCheck(chars.slice(0, 3))) { + return false; + } + + if (!itItNameCheck(chars.slice(3, 6))) { + return false; + } // Convert letters in number spaces back to numbers if any + + + var number_locations = [6, 7, 9, 10, 12, 13, 14]; + var number_replace = { + L: '0', + M: '1', + N: '2', + P: '3', + Q: '4', + R: '5', + S: '6', + T: '7', + U: '8', + V: '9' + }; + + for (var _i4 = 0, _number_locations = number_locations; _i4 < _number_locations.length; _i4++) { + var i = _number_locations[_i4]; + + if (chars[i] in number_replace) { + chars.splice(i, 1, number_replace[chars[i]]); + } + } // Extract month and day, and check date validity + + + var month_replace = { + A: '01', + B: '02', + C: '03', + D: '04', + E: '05', + H: '06', + L: '07', + M: '08', + P: '09', + R: '10', + S: '11', + T: '12' + }; + var month = month_replace[chars[8]]; + var day = parseInt(chars[9] + chars[10], 10); + + if (day > 40) { + day -= 40; + } + + if (day < 10) { + day = "0".concat(day); + } + + var date = "".concat(chars[6]).concat(chars[7], "/").concat(month, "/").concat(day); + + if (!isDate(date, 'YY/MM/DD')) { + return false; + } // Calculate check character by adding up even and odd characters as numbers + + + var checksum = 0; + + for (var _i5 = 1; _i5 < chars.length - 1; _i5 += 2) { + var char_to_int = parseInt(chars[_i5], 10); + + if (isNaN(char_to_int)) { + char_to_int = chars[_i5].charCodeAt(0) - 65; + } + + checksum += char_to_int; + } + + var odd_convert = { + // Maps of characters at odd places + A: 1, + B: 0, + C: 5, + D: 7, + E: 9, + F: 13, + G: 15, + H: 17, + I: 19, + J: 21, + K: 2, + L: 4, + M: 18, + N: 20, + O: 11, + P: 3, + Q: 6, + R: 8, + S: 12, + T: 14, + U: 16, + V: 10, + W: 22, + X: 25, + Y: 24, + Z: 23, + 0: 1, + 1: 0 + }; + + for (var _i6 = 0; _i6 < chars.length - 1; _i6 += 2) { + var _char_to_int = 0; + + if (chars[_i6] in odd_convert) { + _char_to_int = odd_convert[chars[_i6]]; + } else { + var multiplier = parseInt(chars[_i6], 10); + _char_to_int = 2 * multiplier + 1; + + if (multiplier > 4) { + _char_to_int += 2; + } + } + + checksum += _char_to_int; + } + + if (String.fromCharCode(65 + checksum % 26) !== chars[15]) { + return false; + } + + return true; +} +/* + * lv-LV validation function + * (Personas kods (PK), persons only) + * Check validity of birth date and calculate check (last) digit + * Support only for old format numbers (not starting with '32', issued before 2017/07/01) + * Material not in DG TAXUD document sourced from: + * `https://boot.ritakafija.lv/forums/index.php?/topic/88314-personas-koda-algoritms-%C4%8Deksumma/` + */ + + +function lvLvCheck(tin) { + tin = tin.replace(/\W/, ''); // Extract date from TIN + + var day = tin.slice(0, 2); + + if (day !== '32') { + // No date/checksum check if new format + var month = tin.slice(2, 4); + + if (month !== '00') { + // No date check if unknown month + var full_year = tin.slice(4, 6); + + switch (tin[6]) { + case '0': + full_year = "18".concat(full_year); + break; + + case '1': + full_year = "19".concat(full_year); + break; + + default: + full_year = "20".concat(full_year); + break; + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(2, 4), "/").concat(day); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } + } // Calculate check digit + + + var checksum = 1101; + var multip_lookup = [1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; + + for (var i = 0; i < tin.length - 1; i++) { + checksum -= parseInt(tin[i], 10) * multip_lookup[i]; + } + + return parseInt(tin[10], 10) === checksum % 11; + } + + return true; +} +/* + * mt-MT validation function + * (Identity Card Number or Unique Taxpayer Reference, persons/entities) + * Verify Identity Card Number structure (no other tests found) + */ + + +function mtMtCheck(tin) { + if (tin.length !== 9) { + // No tests for UTR + var chars = tin.toUpperCase().split(''); // Fill with zeros if smaller than proper + + while (chars.length < 8) { + chars.unshift(0); + } // Validate format according to last character + + + switch (tin[7]) { + case 'A': + case 'P': + if (parseInt(chars[6], 10) === 0) { + return false; + } + + break; + + default: + { + var first_part = parseInt(chars.join('').slice(0, 5), 10); + + if (first_part > 32000) { + return false; + } + + var second_part = parseInt(chars.join('').slice(5, 7), 10); + + if (first_part === second_part) { + return false; + } + } + } + } + + return true; +} +/* + * nl-NL validation function + * (Burgerservicenummer (BSN) or Rechtspersonen Samenwerkingsverbanden Informatie Nummer (RSIN), + * persons/entities respectively) + * Verify TIN validity by calculating check (last) digit (variant of MOD 11) + */ + + +function nlNlCheck(tin) { + return reverseMultiplyAndSum(tin.split('').slice(0, 8).map(function (a) { + return parseInt(a, 10); + }), 9) % 11 === parseInt(tin[8], 10); +} +/* + * pl-PL validation function + * (Powszechny Elektroniczny System Ewidencji Ludności (PESEL) + * or Numer identyfikacji podatkowej (NIP), persons/entities) + * Verify TIN validity by validating birth date (PESEL) and calculating check (last) digit + */ + + +function plPlCheck(tin) { + // NIP + if (tin.length === 10) { + // Calculate last digit by multiplying with lookup + var lookup = [6, 5, 7, 2, 3, 4, 5, 6, 7]; + var _checksum = 0; + + for (var i = 0; i < lookup.length; i++) { + _checksum += parseInt(tin[i], 10) * lookup[i]; + } + + _checksum %= 11; + + if (_checksum === 10) { + return false; + } + + return _checksum === parseInt(tin[9], 10); + } // PESEL + // Extract full year using month + + + var full_year = tin.slice(0, 2); + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 80) { + full_year = "18".concat(full_year); + month -= 80; + } else if (month > 60) { + full_year = "22".concat(full_year); + month -= 60; + } else if (month > 40) { + full_year = "21".concat(full_year); + month -= 40; + } else if (month > 20) { + full_year = "20".concat(full_year); + month -= 20; + } else { + full_year = "19".concat(full_year); + } // Add leading zero to month if needed + + + if (month < 10) { + month = "0".concat(month); + } // Check date validity + + + var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Calculate last digit by mulitplying with odd one-digit numbers except 5 + + + var checksum = 0; + var multiplier = 1; + + for (var _i7 = 0; _i7 < tin.length - 1; _i7++) { + checksum += parseInt(tin[_i7], 10) * multiplier % 10; + multiplier += 2; + + if (multiplier > 10) { + multiplier = 1; + } else if (multiplier === 5) { + multiplier += 2; + } + } + + checksum = 10 - checksum % 10; + return checksum === parseInt(tin[10], 10); +} +/* +* pt-BR validation function +* (Cadastro de Pessoas Físicas (CPF, persons) +* Cadastro Nacional de Pessoas Jurídicas (CNPJ, entities) +* Both inputs will be validated +*/ + + +function ptBrCheck(tin) { + if (tin.length === 11) { + var _sum; + + var remainder; + _sum = 0; + if ( // Reject known invalid CPFs + tin === '11111111111' || tin === '22222222222' || tin === '33333333333' || tin === '44444444444' || tin === '55555555555' || tin === '66666666666' || tin === '77777777777' || tin === '88888888888' || tin === '99999999999' || tin === '00000000000') return false; + + for (var i = 1; i <= 9; i++) { + _sum += parseInt(tin.substring(i - 1, i), 10) * (11 - i); + } + + remainder = _sum * 10 % 11; + if (remainder === 10) remainder = 0; + if (remainder !== parseInt(tin.substring(9, 10), 10)) return false; + _sum = 0; + + for (var _i8 = 1; _i8 <= 10; _i8++) { + _sum += parseInt(tin.substring(_i8 - 1, _i8), 10) * (12 - _i8); + } + + remainder = _sum * 10 % 11; + if (remainder === 10) remainder = 0; + if (remainder !== parseInt(tin.substring(10, 11), 10)) return false; + return true; + } + + if ( // Reject know invalid CNPJs + tin === '00000000000000' || tin === '11111111111111' || tin === '22222222222222' || tin === '33333333333333' || tin === '44444444444444' || tin === '55555555555555' || tin === '66666666666666' || tin === '77777777777777' || tin === '88888888888888' || tin === '99999999999999') { + return false; + } + + var length = tin.length - 2; + var identifiers = tin.substring(0, length); + var verificators = tin.substring(length); + var sum = 0; + var pos = length - 7; + + for (var _i9 = length; _i9 >= 1; _i9--) { + sum += identifiers.charAt(length - _i9) * pos; + pos -= 1; + + if (pos < 2) { + pos = 9; + } + } + + var result = sum % 11 < 2 ? 0 : 11 - sum % 11; + + if (result !== parseInt(verificators.charAt(0), 10)) { + return false; + } + + length += 1; + identifiers = tin.substring(0, length); + sum = 0; + pos = length - 7; + + for (var _i10 = length; _i10 >= 1; _i10--) { + sum += identifiers.charAt(length - _i10) * pos; + pos -= 1; + + if (pos < 2) { + pos = 9; + } + } + + result = sum % 11 < 2 ? 0 : 11 - sum % 11; + + if (result !== parseInt(verificators.charAt(1), 10)) { + return false; + } + + return true; +} +/* + * pt-PT validation function + * (Número de identificação fiscal (NIF), persons/entities) + * Verify TIN validity by calculating check (last) digit (variant of MOD 11) + */ + + +function ptPtCheck(tin) { + var checksum = 11 - reverseMultiplyAndSum(tin.split('').slice(0, 8).map(function (a) { + return parseInt(a, 10); + }), 9) % 11; + + if (checksum > 9) { + return parseInt(tin[8], 10) === 0; + } + + return checksum === parseInt(tin[8], 10); +} +/* + * ro-RO validation function + * (Cod Numeric Personal (CNP) or Cod de înregistrare fiscală (CIF), + * persons only) + * Verify CNP validity by calculating check (last) digit (test not found for CIF) + * Material not in DG TAXUD document sourced from: + * `https://en.wikipedia.org/wiki/National_identification_number#Romania` + */ + + +function roRoCheck(tin) { + if (tin.slice(0, 4) !== '9000') { + // No test found for this format + // Extract full year using century digit if possible + var full_year = tin.slice(1, 3); + + switch (tin[0]) { + case '1': + case '2': + full_year = "19".concat(full_year); + break; + + case '3': + case '4': + full_year = "18".concat(full_year); + break; + + case '5': + case '6': + full_year = "20".concat(full_year); + break; + + default: + } // Check date validity + + + var date = "".concat(full_year, "/").concat(tin.slice(3, 5), "/").concat(tin.slice(5, 7)); + + if (date.length === 8) { + if (!isDate(date, 'YY/MM/DD')) { + return false; + } + } else if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } // Calculate check digit + + + var digits = tin.split('').map(function (a) { + return parseInt(a, 10); + }); + var multipliers = [2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9]; + var checksum = 0; + + for (var i = 0; i < multipliers.length; i++) { + checksum += digits[i] * multipliers[i]; + } + + if (checksum % 11 === 10) { + return digits[12] === 1; + } + + return digits[12] === checksum % 11; + } + + return true; +} +/* + * sk-SK validation function + * (Rodné číslo (RČ) or bezvýznamové identifikačné číslo (BIČ), persons only) + * Checks validity of pre-1954 birth numbers (rodné číslo) only + * Due to the introduction of the pseudo-random BIČ it is not possible to test + * post-1954 birth numbers without knowing whether they are BIČ or RČ beforehand + */ + + +function skSkCheck(tin) { + if (tin.length === 9) { + tin = tin.replace(/\W/, ''); + + if (tin.slice(6) === '000') { + return false; + } // Three-zero serial not assigned before 1954 + // Extract full year from TIN length + + + var full_year = parseInt(tin.slice(0, 2), 10); + + if (full_year > 53) { + return false; + } + + if (full_year < 10) { + full_year = "190".concat(full_year); + } else { + full_year = "19".concat(full_year); + } // Extract month from TIN and normalize + + + var month = parseInt(tin.slice(2, 4), 10); + + if (month > 50) { + month -= 50; + } + + if (month < 10) { + month = "0".concat(month); + } // Check date validity + + + var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6)); + + if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } + } + + return true; +} +/* + * sl-SI validation function + * (Davčna številka, persons/entities) + * Verify TIN validity by calculating check (last) digit (variant of MOD 11) + */ + + +function slSiCheck(tin) { + var checksum = 11 - reverseMultiplyAndSum(tin.split('').slice(0, 7).map(function (a) { + return parseInt(a, 10); + }), 8) % 11; + + if (checksum === 10) { + return parseInt(tin[7], 10) === 0; + } + + return checksum === parseInt(tin[7], 10); +} +/* + * sv-SE validation function + * (Personnummer or samordningsnummer, persons only) + * Checks validity of birth date and calls luhnCheck() to validate check (last) digit + */ + + +function svSeCheck(tin) { + // Make copy of TIN and normalize to two-digit year form + var tin_copy = tin.slice(0); + + if (tin.length > 11) { + tin_copy = tin_copy.slice(2); + } // Extract date of birth + + + var full_year = ''; + var month = tin_copy.slice(2, 4); + var day = parseInt(tin_copy.slice(4, 6), 10); + + if (tin.length > 11) { + full_year = tin.slice(0, 4); + } else { + full_year = tin.slice(0, 2); + + if (tin.length === 11 && day < 60) { + // Extract full year from centenarian symbol + // Should work just fine until year 10000 or so + var current_year = new Date().getFullYear().toString(); + var current_century = parseInt(current_year.slice(0, 2), 10); + current_year = parseInt(current_year, 10); + + if (tin[6] === '-') { + if (parseInt("".concat(current_century).concat(full_year), 10) > current_year) { + full_year = "".concat(current_century - 1).concat(full_year); + } else { + full_year = "".concat(current_century).concat(full_year); + } + } else { + full_year = "".concat(current_century - 1).concat(full_year); + + if (current_year - parseInt(full_year, 10) < 100) { + return false; + } + } + } + } // Normalize day and check date validity + + + if (day > 60) { + day -= 60; + } + + if (day < 10) { + day = "0".concat(day); + } + + var date = "".concat(full_year, "/").concat(month, "/").concat(day); + + if (date.length === 8) { + if (!isDate(date, 'YY/MM/DD')) { + return false; + } + } else if (!isDate(date, 'YYYY/MM/DD')) { + return false; + } + + return luhnCheck(tin.replace(/\W/, '')); +} // Locale lookup objects + +/* + * Tax id regex formats for various locales + * + * Where not explicitly specified in DG-TAXUD document both + * uppercase and lowercase letters are acceptable. + */ + + +var taxIdFormat = { + 'bg-BG': /^\d{10}$/, + 'cs-CZ': /^\d{6}\/{0,1}\d{3,4}$/, + 'de-AT': /^\d{9}$/, + 'de-DE': /^[1-9]\d{10}$/, + 'dk-DK': /^\d{6}-{0,1}\d{4}$/, + 'el-CY': /^[09]\d{7}[A-Z]$/, + 'el-GR': /^([0-4]|[7-9])\d{8}$/, + 'en-GB': /^\d{10}$|^(?!GB|NK|TN|ZZ)(?![DFIQUV])[A-Z](?![DFIQUVO])[A-Z]\d{6}[ABCD ]$/i, + 'en-IE': /^\d{7}[A-W][A-IW]{0,1}$/i, + 'en-US': /^\d{2}[- ]{0,1}\d{7}$/, + 'es-ES': /^(\d{0,8}|[XYZKLM]\d{7})[A-HJ-NP-TV-Z]$/i, + 'et-EE': /^[1-6]\d{6}(00[1-9]|0[1-9][0-9]|[1-6][0-9]{2}|70[0-9]|710)\d$/, + 'fi-FI': /^\d{6}[-+A]\d{3}[0-9A-FHJ-NPR-Y]$/i, + 'fr-BE': /^\d{11}$/, + 'fr-FR': /^[0-3]\d{12}$|^[0-3]\d\s\d{2}(\s\d{3}){3}$/, + // Conforms both to official spec and provided example + 'fr-LU': /^\d{13}$/, + 'hr-HR': /^\d{11}$/, + 'hu-HU': /^8\d{9}$/, + 'it-IT': /^[A-Z]{6}[L-NP-V0-9]{2}[A-EHLMPRST][L-NP-V0-9]{2}[A-ILMZ][L-NP-V0-9]{3}[A-Z]$/i, + 'lv-LV': /^\d{6}-{0,1}\d{5}$/, + // Conforms both to DG TAXUD spec and original research + 'mt-MT': /^\d{3,7}[APMGLHBZ]$|^([1-8])\1\d{7}$/i, + 'nl-NL': /^\d{9}$/, + 'pl-PL': /^\d{10,11}$/, + 'pt-BR': /(?:^\d{11}$)|(?:^\d{14}$)/, + 'pt-PT': /^\d{9}$/, + 'ro-RO': /^\d{13}$/, + 'sk-SK': /^\d{6}\/{0,1}\d{3,4}$/, + 'sl-SI': /^[1-9]\d{7}$/, + 'sv-SE': /^(\d{6}[-+]{0,1}\d{4}|(18|19|20)\d{6}[-+]{0,1}\d{4})$/ +}; // taxIdFormat locale aliases + +taxIdFormat['lb-LU'] = taxIdFormat['fr-LU']; +taxIdFormat['lt-LT'] = taxIdFormat['et-EE']; +taxIdFormat['nl-BE'] = taxIdFormat['fr-BE']; // Algorithmic tax id check functions for various locales + +var taxIdCheck = { + 'bg-BG': bgBgCheck, + 'cs-CZ': csCzCheck, + 'de-AT': deAtCheck, + 'de-DE': deDeCheck, + 'dk-DK': dkDkCheck, + 'el-CY': elCyCheck, + 'el-GR': elGrCheck, + 'en-IE': enIeCheck, + 'en-US': enUsCheck, + 'es-ES': esEsCheck, + 'et-EE': etEeCheck, + 'fi-FI': fiFiCheck, + 'fr-BE': frBeCheck, + 'fr-FR': frFrCheck, + 'fr-LU': frLuCheck, + 'hr-HR': hrHrCheck, + 'hu-HU': huHuCheck, + 'it-IT': itItCheck, + 'lv-LV': lvLvCheck, + 'mt-MT': mtMtCheck, + 'nl-NL': nlNlCheck, + 'pl-PL': plPlCheck, + 'pt-BR': ptBrCheck, + 'pt-PT': ptPtCheck, + 'ro-RO': roRoCheck, + 'sk-SK': skSkCheck, + 'sl-SI': slSiCheck, + 'sv-SE': svSeCheck +}; // taxIdCheck locale aliases + +taxIdCheck['lb-LU'] = taxIdCheck['fr-LU']; +taxIdCheck['lt-LT'] = taxIdCheck['et-EE']; +taxIdCheck['nl-BE'] = taxIdCheck['fr-BE']; // Regexes for locales where characters should be omitted before checking format + +var allsymbols = /[-\\\/!@#$%\^&\*\(\)\+\=\[\]]+/g; +var sanitizeRegexes = { + 'de-AT': allsymbols, + 'de-DE': /[\/\\]/g, + 'fr-BE': allsymbols +}; // sanitizeRegexes locale aliases + +sanitizeRegexes['nl-BE'] = sanitizeRegexes['fr-BE']; +/* + * Validator function + * Return true if the passed string is a valid tax identification number + * for the specified locale. + * Throw an error exception if the locale is not supported. + */ + +function isTaxID(str) { + var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; + assertString(str); // Copy TIN to avoid replacement if sanitized + + var strcopy = str.slice(0); + + if (locale in taxIdFormat) { + if (locale in sanitizeRegexes) { + strcopy = strcopy.replace(sanitizeRegexes[locale], ''); + } + + if (!taxIdFormat[locale].test(strcopy)) { + return false; + } + + if (locale in taxIdCheck) { + return taxIdCheck[locale](strcopy); + } // Fallthrough; not all locales have algorithmic checks + + + return true; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} + +/* eslint-disable max-len */ + +var phones = { + 'am-AM': /^(\+?374|0)((10|[9|7][0-9])\d{6}$|[2-4]\d{7}$)/, + 'ar-AE': /^((\+?971)|0)?5[024568]\d{7}$/, + 'ar-BH': /^(\+?973)?(3|6)\d{7}$/, + 'ar-DZ': /^(\+?213|0)(5|6|7)\d{8}$/, + 'ar-LB': /^(\+?961)?((3|81)\d{6}|7\d{7})$/, + 'ar-EG': /^((\+?20)|0)?1[0125]\d{8}$/, + 'ar-IQ': /^(\+?964|0)?7[0-9]\d{8}$/, + 'ar-JO': /^(\+?962|0)?7[789]\d{7}$/, + 'ar-KW': /^(\+?965)[569]\d{7}$/, + 'ar-LY': /^((\+?218)|0)?(9[1-6]\d{7}|[1-8]\d{7,9})$/, + 'ar-MA': /^(?:(?:\+|00)212|0)[5-7]\d{8}$/, + 'ar-OM': /^((\+|00)968)?(9[1-9])\d{6}$/, + 'ar-PS': /^(\+?970|0)5[6|9](\d{7})$/, + 'ar-SA': /^(!?(\+?966)|0)?5\d{8}$/, + 'ar-SY': /^(!?(\+?963)|0)?9\d{8}$/, + 'ar-TN': /^(\+?216)?[2459]\d{7}$/, + 'az-AZ': /^(\+994|0)(5[015]|7[07]|99)\d{7}$/, + 'bs-BA': /^((((\+|00)3876)|06))((([0-3]|[5-6])\d{6})|(4\d{7}))$/, + 'be-BY': /^(\+?375)?(24|25|29|33|44)\d{7}$/, + 'bg-BG': /^(\+?359|0)?8[789]\d{7}$/, + 'bn-BD': /^(\+?880|0)1[13456789][0-9]{8}$/, + 'ca-AD': /^(\+376)?[346]\d{5}$/, + 'cs-CZ': /^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/, + 'da-DK': /^(\+?45)?\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{2}$/, + 'de-DE': /^((\+49|0)[1|3])([0|5][0-45-9]\d|6([23]|0\d?)|7([0-57-9]|6\d))\d{7,9}$/, + 'de-AT': /^(\+43|0)\d{1,4}\d{3,12}$/, + 'de-CH': /^(\+41|0)([1-9])\d{1,9}$/, + 'de-LU': /^(\+352)?((6\d1)\d{6})$/, + 'dv-MV': /^(\+?960)?(7[2-9]|91|9[3-9])\d{7}$/, + 'el-GR': /^(\+?30|0)?(69\d{8})$/, + 'en-AU': /^(\+?61|0)4\d{8}$/, + 'en-BM': /^(\+?1)?441(((3|7)\d{6}$)|(5[0-3][0-9]\d{4}$)|(59\d{5}))/, + 'en-GB': /^(\+?44|0)7\d{9}$/, + 'en-GG': /^(\+?44|0)1481\d{6}$/, + 'en-GH': /^(\+233|0)(20|50|24|54|27|57|26|56|23|28|55|59)\d{7}$/, + 'en-GY': /^(\+592|0)6\d{6}$/, + 'en-HK': /^(\+?852[-\s]?)?[456789]\d{3}[-\s]?\d{4}$/, + 'en-MO': /^(\+?853[-\s]?)?[6]\d{3}[-\s]?\d{4}$/, + 'en-IE': /^(\+?353|0)8[356789]\d{7}$/, + 'en-IN': /^(\+?91|0)?[6789]\d{9}$/, + 'en-KE': /^(\+?254|0)(7|1)\d{8}$/, + 'en-KI': /^((\+686|686)?)?( )?((6|7)(2|3|8)[0-9]{6})$/, + 'en-MT': /^(\+?356|0)?(99|79|77|21|27|22|25)[0-9]{6}$/, + 'en-MU': /^(\+?230|0)?\d{8}$/, + 'en-NA': /^(\+?264|0)(6|8)\d{7}$/, + 'en-NG': /^(\+?234|0)?[789]\d{9}$/, + 'en-NZ': /^(\+?64|0)[28]\d{7,9}$/, + 'en-PK': /^((00|\+)?92|0)3[0-6]\d{8}$/, + 'en-PH': /^(09|\+639)\d{9}$/, + 'en-RW': /^(\+?250|0)?[7]\d{8}$/, + 'en-SG': /^(\+65)?[3689]\d{7}$/, + 'en-SL': /^(\+?232|0)\d{8}$/, + 'en-TZ': /^(\+?255|0)?[67]\d{8}$/, + 'en-UG': /^(\+?256|0)?[7]\d{8}$/, + 'en-US': /^((\+1|1)?( |-)?)?(\([2-9][0-9]{2}\)|[2-9][0-9]{2})( |-)?([2-9][0-9]{2}( |-)?[0-9]{4})$/, + 'en-ZA': /^(\+?27|0)\d{9}$/, + 'en-ZM': /^(\+?26)?09[567]\d{7}$/, + 'en-ZW': /^(\+263)[0-9]{9}$/, + 'en-BW': /^(\+?267)?(7[1-8]{1})\d{6}$/, + 'es-AR': /^\+?549(11|[2368]\d)\d{8}$/, + 'es-BO': /^(\+?591)?(6|7)\d{7}$/, + 'es-CO': /^(\+?57)?3(0(0|1|2|4|5)|1\d|2[0-4]|5(0|1))\d{7}$/, + 'es-CL': /^(\+?56|0)[2-9]\d{1}\d{7}$/, + 'es-CR': /^(\+506)?[2-8]\d{7}$/, + 'es-CU': /^(\+53|0053)?5\d{7}/, + 'es-DO': /^(\+?1)?8[024]9\d{7}$/, + 'es-HN': /^(\+?504)?[9|8]\d{7}$/, + 'es-EC': /^(\+?593|0)([2-7]|9[2-9])\d{7}$/, + 'es-ES': /^(\+?34)?[6|7]\d{8}$/, + 'es-PE': /^(\+?51)?9\d{8}$/, + 'es-MX': /^(\+?52)?(1|01)?\d{10,11}$/, + 'es-PA': /^(\+?507)\d{7,8}$/, + 'es-PY': /^(\+?595|0)9[9876]\d{7}$/, + 'es-SV': /^(\+?503)?[67]\d{7}$/, + 'es-UY': /^(\+598|0)9[1-9][\d]{6}$/, + 'es-VE': /^(\+?58)?(2|4)\d{9}$/, + 'et-EE': /^(\+?372)?\s?(5|8[1-4])\s?([0-9]\s?){6,7}$/, + 'fa-IR': /^(\+?98[\-\s]?|0)9[0-39]\d[\-\s]?\d{3}[\-\s]?\d{4}$/, + 'fi-FI': /^(\+?358|0)\s?(4(0|1|2|4|5|6)?|50)\s?(\d\s?){4,8}\d$/, + 'fj-FJ': /^(\+?679)?\s?\d{3}\s?\d{4}$/, + 'fo-FO': /^(\+?298)?\s?\d{2}\s?\d{2}\s?\d{2}$/, + 'fr-BF': /^(\+226|0)[67]\d{7}$/, + 'fr-CM': /^(\+?237)6[0-9]{8}$/, + 'fr-FR': /^(\+?33|0)[67]\d{8}$/, + 'fr-GF': /^(\+?594|0|00594)[67]\d{8}$/, + 'fr-GP': /^(\+?590|0|00590)[67]\d{8}$/, + 'fr-MQ': /^(\+?596|0|00596)[67]\d{8}$/, + 'fr-PF': /^(\+?689)?8[789]\d{6}$/, + 'fr-RE': /^(\+?262|0|00262)[67]\d{8}$/, + 'he-IL': /^(\+972|0)([23489]|5[012345689]|77)[1-9]\d{6}$/, + 'hu-HU': /^(\+?36|06)(20|30|31|50|70)\d{7}$/, + 'id-ID': /^(\+?62|0)8(1[123456789]|2[1238]|3[1238]|5[12356789]|7[78]|9[56789]|8[123456789])([\s?|\d]{5,11})$/, + 'it-IT': /^(\+?39)?\s?3\d{2} ?\d{6,7}$/, + 'it-SM': /^((\+378)|(0549)|(\+390549)|(\+3780549))?6\d{5,9}$/, + 'ja-JP': /^(\+81[ \-]?(\(0\))?|0)[6789]0[ \-]?\d{4}[ \-]?\d{4}$/, + 'ka-GE': /^(\+?995)?(5|79)\d{7}$/, + 'kk-KZ': /^(\+?7|8)?7\d{9}$/, + 'kl-GL': /^(\+?299)?\s?\d{2}\s?\d{2}\s?\d{2}$/, + 'ko-KR': /^((\+?82)[ \-]?)?0?1([0|1|6|7|8|9]{1})[ \-]?\d{3,4}[ \-]?\d{4}$/, + 'lt-LT': /^(\+370|8)\d{8}$/, + 'lv-LV': /^(\+?371)2\d{7}$/, + 'ms-MY': /^(\+?6?01){1}(([0145]{1}(\-|\s)?\d{7,8})|([236789]{1}(\s|\-)?\d{7}))$/, + 'mz-MZ': /^(\+?258)?8[234567]\d{7}$/, + 'nb-NO': /^(\+?47)?[49]\d{7}$/, + 'ne-NP': /^(\+?977)?9[78]\d{8}$/, + 'nl-BE': /^(\+?32|0)4\d{8}$/, + 'nl-NL': /^(((\+|00)?31\(0\))|((\+|00)?31)|0)6{1}\d{8}$/, + 'nn-NO': /^(\+?47)?[49]\d{7}$/, + 'pl-PL': /^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/, + 'pt-BR': /^((\+?55\ ?[1-9]{2}\ ?)|(\+?55\ ?\([1-9]{2}\)\ ?)|(0[1-9]{2}\ ?)|(\([1-9]{2}\)\ ?)|([1-9]{2}\ ?))((\d{4}\-?\d{4})|(9[2-9]{1}\d{3}\-?\d{4}))$/, + 'pt-PT': /^(\+?351)?9[1236]\d{7}$/, + 'pt-AO': /^(\+244)\d{9}$/, + 'ro-RO': /^(\+?4?0)\s?7\d{2}(\/|\s|\.|\-)?\d{3}(\s|\.|\-)?\d{3}$/, + 'ru-RU': /^(\+?7|8)?9\d{9}$/, + 'si-LK': /^(?:0|94|\+94)?(7(0|1|2|4|5|6|7|8)( |-)?)\d{7}$/, + 'sl-SI': /^(\+386\s?|0)(\d{1}\s?\d{3}\s?\d{2}\s?\d{2}|\d{2}\s?\d{3}\s?\d{3})$/, + 'sk-SK': /^(\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/, + 'sq-AL': /^(\+355|0)6[789]\d{6}$/, + 'sr-RS': /^(\+3816|06)[- \d]{5,9}$/, + 'sv-SE': /^(\+?46|0)[\s\-]?7[\s\-]?[02369]([\s\-]?\d){7}$/, + 'tg-TJ': /^(\+?992)?[5][5]\d{7}$/, + 'th-TH': /^(\+66|66|0)\d{9}$/, + 'tr-TR': /^(\+?90|0)?5\d{9}$/, + 'tk-TM': /^(\+993|993|8)\d{8}$/, + 'uk-UA': /^(\+?38|8)?0\d{9}$/, + 'uz-UZ': /^(\+?998)?(6[125-79]|7[1-69]|88|9\d)\d{7}$/, + 'vi-VN': /^((\+?84)|0)((3([2-9]))|(5([25689]))|(7([0|6-9]))|(8([1-9]))|(9([0-9])))([0-9]{7})$/, + 'zh-CN': /^((\+|00)86)?(1[3-9]|9[28])\d{9}$/, + 'zh-TW': /^(\+?886\-?|0)?9\d{8}$/, + 'dz-BT': /^(\+?975|0)?(17|16|77|02)\d{6}$/ +}; +/* eslint-enable max-len */ +// aliases + +phones['en-CA'] = phones['en-US']; +phones['fr-CA'] = phones['en-CA']; +phones['fr-BE'] = phones['nl-BE']; +phones['zh-HK'] = phones['en-HK']; +phones['zh-MO'] = phones['en-MO']; +phones['ga-IE'] = phones['en-IE']; +phones['fr-CH'] = phones['de-CH']; +phones['it-CH'] = phones['fr-CH']; +function isMobilePhone(str, locale, options) { + assertString(str); + + if (options && options.strictMode && !str.startsWith('+')) { + return false; + } + + if (Array.isArray(locale)) { + return locale.some(function (key) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (phones.hasOwnProperty(key)) { + var phone = phones[key]; + + if (phone.test(str)) { + return true; + } + } + + return false; + }); + } else if (locale in phones) { + return phones[locale].test(str); // alias falsey locale as 'any' + } else if (!locale || locale === 'any') { + for (var key in phones) { + // istanbul ignore else + if (phones.hasOwnProperty(key)) { + var phone = phones[key]; + + if (phone.test(str)) { + return true; + } + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} +var locales$4 = Object.keys(phones); + +var eth = /^(0x)[0-9a-f]{40}$/i; +function isEthereumAddress(str) { + assertString(str); + return eth.test(str); +} + +function currencyRegex(options) { + var decimal_digits = "\\d{".concat(options.digits_after_decimal[0], "}"); + options.digits_after_decimal.forEach(function (digit, index) { + if (index !== 0) decimal_digits = "".concat(decimal_digits, "|\\d{").concat(digit, "}"); + }); + var symbol = "(".concat(options.symbol.replace(/\W/, function (m) { + return "\\".concat(m); + }), ")").concat(options.require_symbol ? '' : '?'), + negative = '-?', + whole_dollar_amount_without_sep = '[1-9]\\d*', + whole_dollar_amount_with_sep = "[1-9]\\d{0,2}(\\".concat(options.thousands_separator, "\\d{3})*"), + valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep], + whole_dollar_amount = "(".concat(valid_whole_dollar_amounts.join('|'), ")?"), + decimal_amount = "(\\".concat(options.decimal_separator, "(").concat(decimal_digits, "))").concat(options.require_decimal ? '' : '?'); + var pattern = whole_dollar_amount + (options.allow_decimal || options.require_decimal ? decimal_amount : ''); // default is negative sign before symbol, but there are two other options (besides parens) + + if (options.allow_negatives && !options.parens_for_negatives) { + if (options.negative_sign_after_digits) { + pattern += negative; + } else if (options.negative_sign_before_digits) { + pattern = negative + pattern; + } + } // South African Rand, for example, uses R 123 (space) and R-123 (no space) + + + if (options.allow_negative_sign_placeholder) { + pattern = "( (?!\\-))?".concat(pattern); + } else if (options.allow_space_after_symbol) { + pattern = " ?".concat(pattern); + } else if (options.allow_space_after_digits) { + pattern += '( (?!$))?'; + } + + if (options.symbol_after_digits) { + pattern += symbol; + } else { + pattern = symbol + pattern; + } + + if (options.allow_negatives) { + if (options.parens_for_negatives) { + pattern = "(\\(".concat(pattern, "\\)|").concat(pattern, ")"); + } else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) { + pattern = negative + pattern; + } + } // ensure there's a dollar and/or decimal amount, and that + // it doesn't start with a space or a negative sign followed by a space + + + return new RegExp("^(?!-? )(?=.*\\d)".concat(pattern, "$")); +} + +var default_currency_options = { + symbol: '$', + require_symbol: false, + allow_space_after_symbol: false, + symbol_after_digits: false, + allow_negatives: true, + parens_for_negatives: false, + negative_sign_before_digits: false, + negative_sign_after_digits: false, + allow_negative_sign_placeholder: false, + thousands_separator: ',', + decimal_separator: '.', + allow_decimal: true, + require_decimal: false, + digits_after_decimal: [2], + allow_space_after_digits: false +}; +function isCurrency(str, options) { + assertString(str); + options = merge(options, default_currency_options); + return currencyRegex(options).test(str); +} + +var bech32 = /^(bc1)[a-z0-9]{25,39}$/; +var base58 = /^(1|3)[A-HJ-NP-Za-km-z1-9]{25,39}$/; +function isBtcAddress(str) { + assertString(str); // check for bech32 + + if (str.startsWith('bc1')) { + return bech32.test(str); + } + + return base58.test(str); +} + +/* eslint-disable max-len */ +// from http://goo.gl/0ejHHW + +var iso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; // same as above, except with a strict 'T' separator between date and time + +var iso8601StrictSeparator = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; +/* eslint-enable max-len */ + +var isValidDate = function isValidDate(str) { + // str must have passed the ISO8601 check + // this check is meant to catch invalid dates + // like 2009-02-31 + // first check for ordinal dates + var ordinalMatch = str.match(/^(\d{4})-?(\d{3})([ T]{1}\.*|$)/); + + if (ordinalMatch) { + var oYear = Number(ordinalMatch[1]); + var oDay = Number(ordinalMatch[2]); // if is leap year + + if (oYear % 4 === 0 && oYear % 100 !== 0 || oYear % 400 === 0) return oDay <= 366; + return oDay <= 365; + } + + var match = str.match(/(\d{4})-?(\d{0,2})-?(\d*)/).map(Number); + var year = match[1]; + var month = match[2]; + var day = match[3]; + var monthString = month ? "0".concat(month).slice(-2) : month; + var dayString = day ? "0".concat(day).slice(-2) : day; // create a date object and compare + + var d = new Date("".concat(year, "-").concat(monthString || '01', "-").concat(dayString || '01')); + + if (month && day) { + return d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day; + } + + return true; +}; + +function isISO8601(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + assertString(str); + var check = options.strictSeparator ? iso8601StrictSeparator.test(str) : iso8601.test(str); + if (check && options.strict) return isValidDate(str); + return check; +} + +/* Based on https://tools.ietf.org/html/rfc3339#section-5.6 */ + +var dateFullYear = /[0-9]{4}/; +var dateMonth = /(0[1-9]|1[0-2])/; +var dateMDay = /([12]\d|0[1-9]|3[01])/; +var timeHour = /([01][0-9]|2[0-3])/; +var timeMinute = /[0-5][0-9]/; +var timeSecond = /([0-5][0-9]|60)/; +var timeSecFrac = /(\.[0-9]+)?/; +var timeNumOffset = new RegExp("[-+]".concat(timeHour.source, ":").concat(timeMinute.source)); +var timeOffset = new RegExp("([zZ]|".concat(timeNumOffset.source, ")")); +var partialTime = new RegExp("".concat(timeHour.source, ":").concat(timeMinute.source, ":").concat(timeSecond.source).concat(timeSecFrac.source)); +var fullDate = new RegExp("".concat(dateFullYear.source, "-").concat(dateMonth.source, "-").concat(dateMDay.source)); +var fullTime = new RegExp("".concat(partialTime.source).concat(timeOffset.source)); +var rfc3339 = new RegExp("^".concat(fullDate.source, "[ tT]").concat(fullTime.source, "$")); +function isRFC3339(str) { + assertString(str); + return rfc3339.test(str); +} + +var validISO31661Alpha3CountriesCodes = new Set(['AFG', 'ALA', 'ALB', 'DZA', 'ASM', 'AND', 'AGO', 'AIA', 'ATA', 'ATG', 'ARG', 'ARM', 'ABW', 'AUS', 'AUT', 'AZE', 'BHS', 'BHR', 'BGD', 'BRB', 'BLR', 'BEL', 'BLZ', 'BEN', 'BMU', 'BTN', 'BOL', 'BES', 'BIH', 'BWA', 'BVT', 'BRA', 'IOT', 'BRN', 'BGR', 'BFA', 'BDI', 'KHM', 'CMR', 'CAN', 'CPV', 'CYM', 'CAF', 'TCD', 'CHL', 'CHN', 'CXR', 'CCK', 'COL', 'COM', 'COG', 'COD', 'COK', 'CRI', 'CIV', 'HRV', 'CUB', 'CUW', 'CYP', 'CZE', 'DNK', 'DJI', 'DMA', 'DOM', 'ECU', 'EGY', 'SLV', 'GNQ', 'ERI', 'EST', 'ETH', 'FLK', 'FRO', 'FJI', 'FIN', 'FRA', 'GUF', 'PYF', 'ATF', 'GAB', 'GMB', 'GEO', 'DEU', 'GHA', 'GIB', 'GRC', 'GRL', 'GRD', 'GLP', 'GUM', 'GTM', 'GGY', 'GIN', 'GNB', 'GUY', 'HTI', 'HMD', 'VAT', 'HND', 'HKG', 'HUN', 'ISL', 'IND', 'IDN', 'IRN', 'IRQ', 'IRL', 'IMN', 'ISR', 'ITA', 'JAM', 'JPN', 'JEY', 'JOR', 'KAZ', 'KEN', 'KIR', 'PRK', 'KOR', 'KWT', 'KGZ', 'LAO', 'LVA', 'LBN', 'LSO', 'LBR', 'LBY', 'LIE', 'LTU', 'LUX', 'MAC', 'MKD', 'MDG', 'MWI', 'MYS', 'MDV', 'MLI', 'MLT', 'MHL', 'MTQ', 'MRT', 'MUS', 'MYT', 'MEX', 'FSM', 'MDA', 'MCO', 'MNG', 'MNE', 'MSR', 'MAR', 'MOZ', 'MMR', 'NAM', 'NRU', 'NPL', 'NLD', 'NCL', 'NZL', 'NIC', 'NER', 'NGA', 'NIU', 'NFK', 'MNP', 'NOR', 'OMN', 'PAK', 'PLW', 'PSE', 'PAN', 'PNG', 'PRY', 'PER', 'PHL', 'PCN', 'POL', 'PRT', 'PRI', 'QAT', 'REU', 'ROU', 'RUS', 'RWA', 'BLM', 'SHN', 'KNA', 'LCA', 'MAF', 'SPM', 'VCT', 'WSM', 'SMR', 'STP', 'SAU', 'SEN', 'SRB', 'SYC', 'SLE', 'SGP', 'SXM', 'SVK', 'SVN', 'SLB', 'SOM', 'ZAF', 'SGS', 'SSD', 'ESP', 'LKA', 'SDN', 'SUR', 'SJM', 'SWZ', 'SWE', 'CHE', 'SYR', 'TWN', 'TJK', 'TZA', 'THA', 'TLS', 'TGO', 'TKL', 'TON', 'TTO', 'TUN', 'TUR', 'TKM', 'TCA', 'TUV', 'UGA', 'UKR', 'ARE', 'GBR', 'USA', 'UMI', 'URY', 'UZB', 'VUT', 'VEN', 'VNM', 'VGB', 'VIR', 'WLF', 'ESH', 'YEM', 'ZMB', 'ZWE']); +function isISO31661Alpha3(str) { + assertString(str); + return validISO31661Alpha3CountriesCodes.has(str.toUpperCase()); +} + +var validISO4217CurrencyCodes = new Set(['AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BOV', 'BRL', 'BSD', 'BTN', 'BWP', 'BYN', 'BZD', 'CAD', 'CDF', 'CHE', 'CHF', 'CHW', 'CLF', 'CLP', 'CNY', 'COP', 'COU', 'CRC', 'CUC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DZD', 'EGP', 'ERN', 'ETB', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GHS', 'GIP', 'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', 'INR', 'IQD', 'IRR', 'ISK', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD', 'MMK', 'MNT', 'MOP', 'MRU', 'MUR', 'MVR', 'MWK', 'MXN', 'MXV', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO', 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOS', 'SRD', 'SSP', 'STN', 'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'USN', 'UYI', 'UYU', 'UYW', 'UZS', 'VES', 'VND', 'VUV', 'WST', 'XAF', 'XAG', 'XAU', 'XBA', 'XBB', 'XBC', 'XBD', 'XCD', 'XDR', 'XOF', 'XPD', 'XPF', 'XPT', 'XSU', 'XTS', 'XUA', 'XXX', 'YER', 'ZAR', 'ZMW', 'ZWL']); +function isISO4217(str) { + assertString(str); + return validISO4217CurrencyCodes.has(str.toUpperCase()); +} + +var base32 = /^[A-Z2-7]+=*$/; +function isBase32(str) { + assertString(str); + var len = str.length; + + if (len % 8 === 0 && base32.test(str)) { + return true; + } + + return false; +} + +var base58Reg = /^[A-HJ-NP-Za-km-z1-9]*$/; +function isBase58(str) { + assertString(str); + + if (base58Reg.test(str)) { + return true; + } + + return false; +} + +var validMediaType = /^[a-z]+\/[a-z0-9\-\+]+$/i; +var validAttribute = /^[a-z\-]+=[a-z0-9\-]+$/i; +var validData = /^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$/i; +function isDataURI(str) { + assertString(str); + var data = str.split(','); + + if (data.length < 2) { + return false; + } + + var attributes = data.shift().trim().split(';'); + var schemeAndMediaType = attributes.shift(); + + if (schemeAndMediaType.substr(0, 5) !== 'data:') { + return false; + } + + var mediaType = schemeAndMediaType.substr(5); + + if (mediaType !== '' && !validMediaType.test(mediaType)) { + return false; + } + + for (var i = 0; i < attributes.length; i++) { + if (!(i === attributes.length - 1 && attributes[i].toLowerCase() === 'base64') && !validAttribute.test(attributes[i])) { + return false; + } + } + + for (var _i = 0; _i < data.length; _i++) { + if (!validData.test(data[_i])) { + return false; + } + } + + return true; +} + +var magnetURI = /^magnet:\?xt(?:\.1)?=urn:(?:aich|bitprint|btih|ed2k|ed2khash|kzhash|md5|sha1|tree:tiger):[a-z0-9]{32}(?:[a-z0-9]{8})?($|&)/i; +function isMagnetURI(url) { + assertString(url); + return magnetURI.test(url.trim()); +} + +/* + Checks if the provided string matches to a correct Media type format (MIME type) + + This function only checks is the string format follows the + etablished rules by the according RFC specifications. + This function supports 'charset' in textual media types + (https://tools.ietf.org/html/rfc6657). + + This function does not check against all the media types listed + by the IANA (https://www.iana.org/assignments/media-types/media-types.xhtml) + because of lightness purposes : it would require to include + all these MIME types in this librairy, which would weigh it + significantly. This kind of effort maybe is not worth for the use that + this function has in this entire librairy. + + More informations in the RFC specifications : + - https://tools.ietf.org/html/rfc2045 + - https://tools.ietf.org/html/rfc2046 + - https://tools.ietf.org/html/rfc7231#section-3.1.1.1 + - https://tools.ietf.org/html/rfc7231#section-3.1.1.5 +*/ +// Match simple MIME types +// NB : +// Subtype length must not exceed 100 characters. +// This rule does not comply to the RFC specs (what is the max length ?). + +var mimeTypeSimple = /^(application|audio|font|image|message|model|multipart|text|video)\/[a-zA-Z0-9\.\-\+]{1,100}$/i; // eslint-disable-line max-len +// Handle "charset" in "text/*" + +var mimeTypeText = /^text\/[a-zA-Z0-9\.\-\+]{1,100};\s?charset=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?$/i; // eslint-disable-line max-len +// Handle "boundary" in "multipart/*" + +var mimeTypeMultipart = /^multipart\/[a-zA-Z0-9\.\-\+]{1,100}(;\s?(boundary|charset)=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?){0,2}$/i; // eslint-disable-line max-len + +function isMimeType(str) { + assertString(str); + return mimeTypeSimple.test(str) || mimeTypeText.test(str) || mimeTypeMultipart.test(str); +} + +var lat = /^\(?[+-]?(90(\.0+)?|[1-8]?\d(\.\d+)?)$/; +var _long = /^\s?[+-]?(180(\.0+)?|1[0-7]\d(\.\d+)?|\d{1,2}(\.\d+)?)\)?$/; +var latDMS = /^(([1-8]?\d)\D+([1-5]?\d|60)\D+([1-5]?\d|60)(\.\d+)?|90\D+0\D+0)\D+[NSns]?$/i; +var longDMS = /^\s*([1-7]?\d{1,2}\D+([1-5]?\d|60)\D+([1-5]?\d|60)(\.\d+)?|180\D+0\D+0)\D+[EWew]?$/i; +var defaultLatLongOptions = { + checkDMS: false +}; +function isLatLong(str, options) { + assertString(str); + options = merge(options, defaultLatLongOptions); + if (!str.includes(',')) return false; + var pair = str.split(','); + if (pair[0].startsWith('(') && !pair[1].endsWith(')') || pair[1].endsWith(')') && !pair[0].startsWith('(')) return false; + + if (options.checkDMS) { + return latDMS.test(pair[0]) && longDMS.test(pair[1]); + } + + return lat.test(pair[0]) && _long.test(pair[1]); +} + +var threeDigit = /^\d{3}$/; +var fourDigit = /^\d{4}$/; +var fiveDigit = /^\d{5}$/; +var sixDigit = /^\d{6}$/; +var patterns = { + AD: /^AD\d{3}$/, + AT: fourDigit, + AU: fourDigit, + AZ: /^AZ\d{4}$/, + BE: fourDigit, + BG: fourDigit, + BR: /^\d{5}-\d{3}$/, + BY: /2[1-4]{1}\d{4}$/, + CA: /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][\s\-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i, + CH: fourDigit, + CN: /^(0[1-7]|1[012356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[1-5]|8[1345]|9[09])\d{4}$/, + CZ: /^\d{3}\s?\d{2}$/, + DE: fiveDigit, + DK: fourDigit, + DO: fiveDigit, + DZ: fiveDigit, + EE: fiveDigit, + ES: /^(5[0-2]{1}|[0-4]{1}\d{1})\d{3}$/, + FI: fiveDigit, + FR: /^\d{2}\s?\d{3}$/, + GB: /^(gir\s?0aa|[a-z]{1,2}\d[\da-z]?\s?(\d[a-z]{2})?)$/i, + GR: /^\d{3}\s?\d{2}$/, + HR: /^([1-5]\d{4}$)/, + HT: /^HT\d{4}$/, + HU: fourDigit, + ID: fiveDigit, + IE: /^(?!.*(?:o))[A-Za-z]\d[\dw]\s\w{4}$/i, + IL: /^(\d{5}|\d{7})$/, + IN: /^((?!10|29|35|54|55|65|66|86|87|88|89)[1-9][0-9]{5})$/, + IR: /\b(?!(\d)\1{3})[13-9]{4}[1346-9][013-9]{5}\b/, + IS: threeDigit, + IT: fiveDigit, + JP: /^\d{3}\-\d{4}$/, + KE: fiveDigit, + KR: /^(\d{5}|\d{6})$/, + LI: /^(948[5-9]|949[0-7])$/, + LT: /^LT\-\d{5}$/, + LU: fourDigit, + LV: /^LV\-\d{4}$/, + LK: fiveDigit, + MX: fiveDigit, + MT: /^[A-Za-z]{3}\s{0,1}\d{4}$/, + MY: fiveDigit, + NL: /^\d{4}\s?[a-z]{2}$/i, + NO: fourDigit, + NP: /^(10|21|22|32|33|34|44|45|56|57)\d{3}$|^(977)$/i, + NZ: fourDigit, + PL: /^\d{2}\-\d{3}$/, + PR: /^00[679]\d{2}([ -]\d{4})?$/, + PT: /^\d{4}\-\d{3}?$/, + RO: sixDigit, + RU: sixDigit, + SA: fiveDigit, + SE: /^[1-9]\d{2}\s?\d{2}$/, + SG: sixDigit, + SI: fourDigit, + SK: /^\d{3}\s?\d{2}$/, + TH: fiveDigit, + TN: fourDigit, + TW: /^\d{3}(\d{2})?$/, + UA: fiveDigit, + US: /^\d{5}(-\d{4})?$/, + ZA: fourDigit, + ZM: fiveDigit +}; +var locales$5 = Object.keys(patterns); +function isPostalCode(str, locale) { + assertString(str); + + if (locale in patterns) { + return patterns[locale].test(str); + } else if (locale === 'any') { + for (var key in patterns) { + // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes + // istanbul ignore else + if (patterns.hasOwnProperty(key)) { + var pattern = patterns[key]; + + if (pattern.test(str)) { + return true; + } + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} + +function ltrim(str, chars) { + assertString(str); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping + + var pattern = chars ? new RegExp("^[".concat(chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), "]+"), 'g') : /^\s+/g; + return str.replace(pattern, ''); +} + +function rtrim(str, chars) { + assertString(str); + + if (chars) { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping + var pattern = new RegExp("[".concat(chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), "]+$"), 'g'); + return str.replace(pattern, ''); + } // Use a faster and more safe than regex trim method https://blog.stevenlevithan.com/archives/faster-trim-javascript + + + var strIndex = str.length - 1; + + while (/\s/.test(str.charAt(strIndex))) { + strIndex -= 1; + } + + return str.slice(0, strIndex + 1); +} + +function trim(str, chars) { + return rtrim(ltrim(str, chars), chars); +} + +function escape(str) { + assertString(str); + return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>').replace(/\//g, '/').replace(/\\/g, '\').replace(/`/g, '`'); +} + +function unescape(str) { + assertString(str); + return str.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(///g, '/').replace(/\/g, '\\').replace(/`/g, '`').replace(/&/g, '&'); // & replacement has to be the last one to prevent + // bugs with intermediate strings containing escape sequences + // See: https://github.com/validatorjs/validator.js/issues/1827 +} + +function blacklist$1(str, chars) { + assertString(str); + return str.replace(new RegExp("[".concat(chars, "]+"), 'g'), ''); +} + +function stripLow(str, keep_new_lines) { + assertString(str); + var chars = keep_new_lines ? '\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F' : '\\x00-\\x1F\\x7F'; + return blacklist$1(str, chars); +} + +function whitelist(str, chars) { + assertString(str); + return str.replace(new RegExp("[^".concat(chars, "]+"), 'g'), ''); +} + +function isWhitelisted(str, chars) { + assertString(str); + + for (var i = str.length - 1; i >= 0; i--) { + if (chars.indexOf(str[i]) === -1) { + return false; + } + } + + return true; +} + +var default_normalize_email_options = { + // The following options apply to all email addresses + // Lowercases the local part of the email address. + // Please note this may violate RFC 5321 as per http://stackoverflow.com/a/9808332/192024). + // The domain is always lowercased, as per RFC 1035 + all_lowercase: true, + // The following conversions are specific to GMail + // Lowercases the local part of the GMail address (known to be case-insensitive) + gmail_lowercase: true, + // Removes dots from the local part of the email address, as that's ignored by GMail + gmail_remove_dots: true, + // Removes the subaddress (e.g. "+foo") from the email address + gmail_remove_subaddress: true, + // Conversts the googlemail.com domain to gmail.com + gmail_convert_googlemaildotcom: true, + // The following conversions are specific to Outlook.com / Windows Live / Hotmail + // Lowercases the local part of the Outlook.com address (known to be case-insensitive) + outlookdotcom_lowercase: true, + // Removes the subaddress (e.g. "+foo") from the email address + outlookdotcom_remove_subaddress: true, + // The following conversions are specific to Yahoo + // Lowercases the local part of the Yahoo address (known to be case-insensitive) + yahoo_lowercase: true, + // Removes the subaddress (e.g. "-foo") from the email address + yahoo_remove_subaddress: true, + // The following conversions are specific to Yandex + // Lowercases the local part of the Yandex address (known to be case-insensitive) + yandex_lowercase: true, + // The following conversions are specific to iCloud + // Lowercases the local part of the iCloud address (known to be case-insensitive) + icloud_lowercase: true, + // Removes the subaddress (e.g. "+foo") from the email address + icloud_remove_subaddress: true +}; // List of domains used by iCloud + +var icloud_domains = ['icloud.com', 'me.com']; // List of domains used by Outlook.com and its predecessors +// This list is likely incomplete. +// Partial reference: +// https://blogs.office.com/2013/04/17/outlook-com-gets-two-step-verification-sign-in-by-alias-and-new-international-domains/ + +var outlookdotcom_domains = ['hotmail.at', 'hotmail.be', 'hotmail.ca', 'hotmail.cl', 'hotmail.co.il', 'hotmail.co.nz', 'hotmail.co.th', 'hotmail.co.uk', 'hotmail.com', 'hotmail.com.ar', 'hotmail.com.au', 'hotmail.com.br', 'hotmail.com.gr', 'hotmail.com.mx', 'hotmail.com.pe', 'hotmail.com.tr', 'hotmail.com.vn', 'hotmail.cz', 'hotmail.de', 'hotmail.dk', 'hotmail.es', 'hotmail.fr', 'hotmail.hu', 'hotmail.id', 'hotmail.ie', 'hotmail.in', 'hotmail.it', 'hotmail.jp', 'hotmail.kr', 'hotmail.lv', 'hotmail.my', 'hotmail.ph', 'hotmail.pt', 'hotmail.sa', 'hotmail.sg', 'hotmail.sk', 'live.be', 'live.co.uk', 'live.com', 'live.com.ar', 'live.com.mx', 'live.de', 'live.es', 'live.eu', 'live.fr', 'live.it', 'live.nl', 'msn.com', 'outlook.at', 'outlook.be', 'outlook.cl', 'outlook.co.il', 'outlook.co.nz', 'outlook.co.th', 'outlook.com', 'outlook.com.ar', 'outlook.com.au', 'outlook.com.br', 'outlook.com.gr', 'outlook.com.pe', 'outlook.com.tr', 'outlook.com.vn', 'outlook.cz', 'outlook.de', 'outlook.dk', 'outlook.es', 'outlook.fr', 'outlook.hu', 'outlook.id', 'outlook.ie', 'outlook.in', 'outlook.it', 'outlook.jp', 'outlook.kr', 'outlook.lv', 'outlook.my', 'outlook.ph', 'outlook.pt', 'outlook.sa', 'outlook.sg', 'outlook.sk', 'passport.com']; // List of domains used by Yahoo Mail +// This list is likely incomplete + +var yahoo_domains = ['rocketmail.com', 'yahoo.ca', 'yahoo.co.uk', 'yahoo.com', 'yahoo.de', 'yahoo.fr', 'yahoo.in', 'yahoo.it', 'ymail.com']; // List of domains used by yandex.ru + +var yandex_domains = ['yandex.ru', 'yandex.ua', 'yandex.kz', 'yandex.com', 'yandex.by', 'ya.ru']; // replace single dots, but not multiple consecutive dots + +function dotsReplacer(match) { + if (match.length > 1) { + return match; + } + + return ''; +} + +function normalizeEmail(email, options) { + options = merge(options, default_normalize_email_options); + var raw_parts = email.split('@'); + var domain = raw_parts.pop(); + var user = raw_parts.join('@'); + var parts = [user, domain]; // The domain is always lowercased, as it's case-insensitive per RFC 1035 + + parts[1] = parts[1].toLowerCase(); + + if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') { + // Address is GMail + if (options.gmail_remove_subaddress) { + parts[0] = parts[0].split('+')[0]; + } + + if (options.gmail_remove_dots) { + // this does not replace consecutive dots like example..email@gmail.com + parts[0] = parts[0].replace(/\.+/g, dotsReplacer); + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.gmail_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + + parts[1] = options.gmail_convert_googlemaildotcom ? 'gmail.com' : parts[1]; + } else if (icloud_domains.indexOf(parts[1]) >= 0) { + // Address is iCloud + if (options.icloud_remove_subaddress) { + parts[0] = parts[0].split('+')[0]; + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.icloud_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + } else if (outlookdotcom_domains.indexOf(parts[1]) >= 0) { + // Address is Outlook.com + if (options.outlookdotcom_remove_subaddress) { + parts[0] = parts[0].split('+')[0]; + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.outlookdotcom_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + } else if (yahoo_domains.indexOf(parts[1]) >= 0) { + // Address is Yahoo + if (options.yahoo_remove_subaddress) { + var components = parts[0].split('-'); + parts[0] = components.length > 1 ? components.slice(0, -1).join('-') : components[0]; + } + + if (!parts[0].length) { + return false; + } + + if (options.all_lowercase || options.yahoo_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + } else if (yandex_domains.indexOf(parts[1]) >= 0) { + if (options.all_lowercase || options.yandex_lowercase) { + parts[0] = parts[0].toLowerCase(); + } + + parts[1] = 'yandex.ru'; // all yandex domains are equal, 1st preferred + } else if (options.all_lowercase) { + // Any other address + parts[0] = parts[0].toLowerCase(); + } + + return parts.join('@'); +} + +var charsetRegex = /^[^\s-_](?!.*?[-_]{2,})[a-z0-9-\\][^\s]*[^-_\s]$/; +function isSlug(str) { + assertString(str); + return charsetRegex.test(str); +} + +var validators$1 = { + 'cs-CZ': function csCZ(str) { + return /^(([ABCDEFHKIJKLMNPRSTUVXYZ]|[0-9])-?){5,8}$/.test(str); + }, + 'de-DE': function deDE(str) { + return /^((AW|UL|AK|GA|AÖ|LF|AZ|AM|AS|ZE|AN|AB|A|KG|KH|BA|EW|BZ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D|SWA|NES|KÖN|MET|LRO|BÜZ|DBR|ROS|TET|HRO|ROW|BRV|HIP|PAN|GRI|SHK|EIS|SRO|SOK|LBS|SCZ|MER|QFT|SLF|SLS|HOM|SLK|ASL|BBG|SBK|SFT|SHG|MGN|MEG|ZIG|SAD|NEN|OVI|SHA|BLB|SIG|SON|SPN|FOR|GUB|SPB|IGB|WND|STD|STA|SDL|OBG|HST|BOG|SHL|PIR|FTL|SEB|SÖM|SÜW|TIR|SAB|TUT|ANG|SDT|LÜN|LSZ|MHL|VEC|VER|VIE|OVL|ANK|OVP|SBG|UEM|UER|WLG|GMN|NVP|RDG|RÜG|DAU|FKB|WAF|WAK|SLZ|WEN|SOG|APD|WUG|GUN|ESW|WIZ|WES|DIN|BRA|BÜD|WHV|HWI|GHC|WTM|WOB|WUN|MAK|SEL|OCH|HOT|WDA)[- ]?(([A-Z][- ]?\d{1,4})|([A-Z]{2}[- ]?\d{1,3})))[- ]?(E|H)?$/.test(str); + }, + 'de-LI': function deLI(str) { + return /^FL[- ]?\d{1,5}[UZ]?$/.test(str); + }, + 'fi-FI': function fiFI(str) { + return /^(?=.{4,7})(([A-Z]{1,3}|[0-9]{1,3})[\s-]?([A-Z]{1,3}|[0-9]{1,5}))$/.test(str); + }, + 'pt-PT': function ptPT(str) { + return /^([A-Z]{2}|[0-9]{2})[ -·]?([A-Z]{2}|[0-9]{2})[ -·]?([A-Z]{2}|[0-9]{2})$/.test(str); + }, + 'sq-AL': function sqAL(str) { + return /^[A-Z]{2}[- ]?((\d{3}[- ]?(([A-Z]{2})|T))|(R[- ]?\d{3}))$/.test(str); + }, + 'pt-BR': function ptBR(str) { + return /^[A-Z]{3}[ -]?[0-9][A-Z][0-9]{2}|[A-Z]{3}[ -]?[0-9]{4}$/.test(str); + } +}; +function isLicensePlate(str, locale) { + assertString(str); + + if (locale in validators$1) { + return validators$1[locale](str); + } else if (locale === 'any') { + for (var key in validators$1) { + /* eslint guard-for-in: 0 */ + var validator = validators$1[key]; + + if (validator(str)) { + return true; + } + } + + return false; + } + + throw new Error("Invalid locale '".concat(locale, "'")); +} + +var upperCaseRegex = /^[A-Z]$/; +var lowerCaseRegex = /^[a-z]$/; +var numberRegex = /^[0-9]$/; +var symbolRegex = /^[-#!$@%^&*()_+|~=`{}\[\]:";'<>?,.\/ ]$/; +var defaultOptions$1 = { + minLength: 8, + minLowercase: 1, + minUppercase: 1, + minNumbers: 1, + minSymbols: 1, + returnScore: false, + pointsPerUnique: 1, + pointsPerRepeat: 0.5, + pointsForContainingLower: 10, + pointsForContainingUpper: 10, + pointsForContainingNumber: 10, + pointsForContainingSymbol: 10 +}; +/* Counts number of occurrences of each char in a string + * could be moved to util/ ? +*/ + +function countChars(str) { + var result = {}; + Array.from(str).forEach(function (_char) { + var curVal = result[_char]; + + if (curVal) { + result[_char] += 1; + } else { + result[_char] = 1; + } + }); + return result; +} +/* Return information about a password */ + + +function analyzePassword(password) { + var charMap = countChars(password); + var analysis = { + length: password.length, + uniqueChars: Object.keys(charMap).length, + uppercaseCount: 0, + lowercaseCount: 0, + numberCount: 0, + symbolCount: 0 + }; + Object.keys(charMap).forEach(function (_char2) { + /* istanbul ignore else */ + if (upperCaseRegex.test(_char2)) { + analysis.uppercaseCount += charMap[_char2]; + } else if (lowerCaseRegex.test(_char2)) { + analysis.lowercaseCount += charMap[_char2]; + } else if (numberRegex.test(_char2)) { + analysis.numberCount += charMap[_char2]; + } else if (symbolRegex.test(_char2)) { + analysis.symbolCount += charMap[_char2]; + } + }); + return analysis; +} + +function scorePassword(analysis, scoringOptions) { + var points = 0; + points += analysis.uniqueChars * scoringOptions.pointsPerUnique; + points += (analysis.length - analysis.uniqueChars) * scoringOptions.pointsPerRepeat; + + if (analysis.lowercaseCount > 0) { + points += scoringOptions.pointsForContainingLower; + } + + if (analysis.uppercaseCount > 0) { + points += scoringOptions.pointsForContainingUpper; + } + + if (analysis.numberCount > 0) { + points += scoringOptions.pointsForContainingNumber; + } + + if (analysis.symbolCount > 0) { + points += scoringOptions.pointsForContainingSymbol; + } + + return points; +} + +function isStrongPassword(str) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + assertString(str); + var analysis = analyzePassword(str); + options = merge(options || {}, defaultOptions$1); + + if (options.returnScore) { + return scorePassword(analysis, options); + } + + return analysis.length >= options.minLength && analysis.lowercaseCount >= options.minLowercase && analysis.uppercaseCount >= options.minUppercase && analysis.numberCount >= options.minNumbers && analysis.symbolCount >= options.minSymbols; +} + +var vatMatchers = { + GB: /^GB((\d{3} \d{4} ([0-8][0-9]|9[0-6]))|(\d{9} \d{3})|(((GD[0-4])|(HA[5-9]))[0-9]{2}))$/, + IT: /^(IT)?[0-9]{11}$/, + NL: /^(NL)?[0-9]{9}B[0-9]{2}$/ +}; +function isVAT(str, countryCode) { + assertString(str); + assertString(countryCode); + + if (countryCode in vatMatchers) { + return vatMatchers[countryCode].test(str); + } + + throw new Error("Invalid country code: '".concat(countryCode, "'")); +} + +var version = '13.7.0'; +var validator = { + version: version, + toDate: toDate, + toFloat: toFloat, + toInt: toInt, + toBoolean: toBoolean, + equals: equals, + contains: contains, + matches: matches, + isEmail: isEmail, + isURL: isURL, + isMACAddress: isMACAddress, + isIP: isIP, + isIPRange: isIPRange, + isFQDN: isFQDN, + isBoolean: isBoolean, + isIBAN: isIBAN, + isBIC: isBIC, + isAlpha: isAlpha, + isAlphaLocales: locales$1, + isAlphanumeric: isAlphanumeric, + isAlphanumericLocales: locales$2, + isNumeric: isNumeric, + isPassportNumber: isPassportNumber, + isPort: isPort, + isLowercase: isLowercase, + isUppercase: isUppercase, + isAscii: isAscii, + isFullWidth: isFullWidth, + isHalfWidth: isHalfWidth, + isVariableWidth: isVariableWidth, + isMultibyte: isMultibyte, + isSemVer: isSemVer, + isSurrogatePair: isSurrogatePair, + isInt: isInt, + isIMEI: isIMEI, + isFloat: isFloat, + isFloatLocales: locales, + isDecimal: isDecimal, + isHexadecimal: isHexadecimal, + isOctal: isOctal, + isDivisibleBy: isDivisibleBy, + isHexColor: isHexColor, + isRgbColor: isRgbColor, + isHSL: isHSL, + isISRC: isISRC, + isMD5: isMD5, + isHash: isHash, + isJWT: isJWT, + isJSON: isJSON, + isEmpty: isEmpty, + isLength: isLength, + isLocale: isLocale, + isByteLength: isByteLength, + isUUID: isUUID, + isMongoId: isMongoId, + isAfter: isAfter, + isBefore: isBefore, + isIn: isIn, + isCreditCard: isCreditCard, + isIdentityCard: isIdentityCard, + isEAN: isEAN, + isISIN: isISIN, + isISBN: isISBN, + isISSN: isISSN, + isMobilePhone: isMobilePhone, + isMobilePhoneLocales: locales$4, + isPostalCode: isPostalCode, + isPostalCodeLocales: locales$5, + isEthereumAddress: isEthereumAddress, + isCurrency: isCurrency, + isBtcAddress: isBtcAddress, + isISO8601: isISO8601, + isRFC3339: isRFC3339, + isISO31661Alpha2: isISO31661Alpha2, + isISO31661Alpha3: isISO31661Alpha3, + isISO4217: isISO4217, + isBase32: isBase32, + isBase58: isBase58, + isBase64: isBase64, + isDataURI: isDataURI, + isMagnetURI: isMagnetURI, + isMimeType: isMimeType, + isLatLong: isLatLong, + ltrim: ltrim, + rtrim: rtrim, + trim: trim, + escape: escape, + unescape: unescape, + stripLow: stripLow, + whitelist: whitelist, + blacklist: blacklist$1, + isWhitelisted: isWhitelisted, + normalizeEmail: normalizeEmail, + toString: toString, + isSlug: isSlug, + isStrongPassword: isStrongPassword, + isTaxID: isTaxID, + isDate: isDate, + isLicensePlate: isLicensePlate, + isVAT: isVAT, + ibanLocales: locales$3 +}; + +return validator; + +}))); diff --git a/node_modules/validator/validator.min.js b/node_modules/validator/validator.min.js new file mode 100644 index 0000000..f847fd2 --- /dev/null +++ b/node_modules/validator/validator.min.js @@ -0,0 +1,23 @@ +/*! + * Copyright (c) 2018 Chris O'Hara + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.validator=e()}(this,function(){"use strict";function i(t){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function u(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t)){var r=[],n=!0,i=!1,a=void 0;try{for(var o,s=t[Symbol.iterator]();!(n=(o=s.next()).done)&&(r.push(o.value),!e||r.length!==e);n=!0);}catch(t){i=!0,a=t}finally{try{n||null==s.return||s.return()}finally{if(i)throw a}}return r}}(t,e)||d(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(t){return function(t){if(Array.isArray(t))return n(t)}(t)||function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}(t)||d(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(t,e){if(t){if("string"==typeof t)return n(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);return"Map"===(r="Object"===r&&t.constructor?t.constructor.name:r)||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(t,e):void 0}}function n(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=e.min)&&(!e.hasOwnProperty("max")||n<=e.max)&&(!e.hasOwnProperty("lt")||ne.gt)}o["fr-CA"]=o["fr-FR"],s["fr-CA"]=s["fr-FR"],o["pt-BR"]=o["pt-PT"],s["pt-BR"]=s["pt-PT"],c["pt-BR"]=c["pt-PT"],o["pl-Pl"]=o["pl-PL"],s["pl-Pl"]=s["pl-PL"],c["pl-Pl"]=c["pl-PL"],o["fa-AF"]=o.fa;var m=Object.keys(c);function Z(t){return L(t)?parseFloat(t):NaN}function M(t){return"object"===i(t)&&null!==t?t="function"==typeof t.toString?t.toString():"[object Object]":(null==t||isNaN(t)&&!t.length)&&(t=""),String(t)}function B(t,e){var r,n=0=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:e}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,o=!1;return{s:function(){r=t[Symbol.iterator]()},n:function(){var t=r.next();return a=t.done,t},e:function(t){o=!0,i=t},f:function(){try{a||null==r.return||r.return()}finally{if(o)throw i}}}}(function(t,e){for(var r=[],n=Math.min(t.length,e.length),i=0;i=e.min,i=!e.hasOwnProperty("max")||t<=e.max,a=!e.hasOwnProperty("lt")||te.gt;return r.test(t)&&n&&i&&a&&e}var dt=/^[0-9]{15}$/,ft=/^\d{2}-\d{6}-\d{6}-\d{1}$/;var At=/^[\x00-\x7F]+$/;var $t=/[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;var pt=/[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;var St=/[^\x00-\x7F]/;var ht,gt,Et=(gt="i",ht=(ht=["^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)","(?:-((?:0|[1-9]\\d*|\\d*[a-z-][0-9a-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-z-][0-9a-z-]*))*))","?(?:\\+([0-9a-z-]+(?:\\.[0-9a-z-]+)*))?$"]).join(""),new RegExp(ht,gt));var It=/[\uD800-\uDBFF][\uDC00-\uDFFF]/;var Rt={force_decimal:!1,decimal_digits:"1,",locale:"en-US"},vt=["","-","+"];var Lt=/^(0x|0h)?[0-9A-F]+$/i;function mt(t){return l(t),Lt.test(t)}var Zt=/^(0o)?[0-7]+$/i;var Mt=/^#?([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i;var Bt=/^rgb\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\)$/,Nt=/^rgba\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)$/,Ft=/^rgb\((([0-9]%|[1-9][0-9]%|100%),){2}([0-9]%|[1-9][0-9]%|100%)\)/,Dt=/^rgba\((([0-9]%|[1-9][0-9]%|100%),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)/;var Ct=/^hsla?\(((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?))(deg|grad|rad|turn)?(,(\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%){2}(,((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-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Z0-9]{18}$/,MU:/^(MU[0-9]{2})[A-Z]{4}\d{19}[A-Z]{3}$/,MZ:/^(MZ[0-9]{2})\d{21}$/,NL:/^(NL[0-9]{2})[A-Z]{4}\d{10}$/,NO:/^(NO[0-9]{2})\d{11}$/,PK:/^(PK[0-9]{2})[A-Z0-9]{4}\d{16}$/,PL:/^(PL[0-9]{2})\d{24}$/,PS:/^(PS[0-9]{2})[A-Z0-9]{4}\d{21}$/,PT:/^(PT[0-9]{2})\d{21}$/,QA:/^(QA[0-9]{2})[A-Z]{4}[A-Z0-9]{21}$/,RO:/^(RO[0-9]{2})[A-Z]{4}[A-Z0-9]{16}$/,RS:/^(RS[0-9]{2})\d{18}$/,SA:/^(SA[0-9]{2})\d{2}[A-Z0-9]{18}$/,SC:/^(SC[0-9]{2})[A-Z]{4}\d{20}[A-Z]{3}$/,SE:/^(SE[0-9]{2})\d{20}$/,SI:/^(SI[0-9]{2})\d{15}$/,SK:/^(SK[0-9]{2})\d{20}$/,SM:/^(SM[0-9]{2})[A-Z]{1}\d{10}[A-Z0-9]{12}$/,SV:/^(SV[0-9]{2})[A-Z0-9]{4}\d{20}$/,TL:/^(TL[0-9]{2})\d{19}$/,TN:/^(TN[0-9]{2})\d{20}$/,TR:/^(TR[0-9]{2})\d{5}[A-Z0-9]{17}$/,UA:/^(UA[0-9]{2})\d{6}[A-Z0-9]{19}$/,VA:/^(VA[0-9]{2})\d{18}$/,VG:/^(VG[0-9]{2})[A-Z0-9]{4}\d{16}$/,XK:/^(XK[0-9]{2})\d{16}$/};var _t=Object.keys(Ot),Ht=new Set(["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE","YT","ZA","ZM","ZW"]);var Pt=Ht,bt=/^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$/;var Ut=/^[a-f0-9]{32}$/;var Kt={md5:32,md4:32,sha1:40,sha256:64,sha384:96,sha512:128,ripemd128:32,ripemd160:40,tiger128:32,tiger160:40,tiger192:48,crc32:8,crc32b:8};var wt=/[^A-Z0-9+\/=]/i,yt=/^[A-Z0-9_\-]*$/i,Wt={urlSafe:!1};function Yt(t,e){l(t),e=B(e,Wt);var r=t.length;if(e.urlSafe)return yt.test(t);if(r%4!=0||wt.test(t))return!1;e=t.indexOf("=");return-1===e||e===r-1||e===r-2&&"="===t[r-1]}var xt={allow_primitives:!1};var Vt={ignore_whitespace:!1};var kt={1:/^[0-9A-F]{8}-[0-9A-F]{4}-1[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,2:/^[0-9A-F]{8}-[0-9A-F]{4}-2[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};var zt=/^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/;var Xt={PL:function(t){l(t);var n={1:1,2:3,3:7,4:9,5:1,6:3,7:7,8:9,9:1,10:3,11:0};if(null!=t&&11===t.length&&ut(t,{allow_leading_zeroes:!0})){var e=t.split("").slice(0,-1).reduce(function(t,e,r){return t+Number(e)*n[r+1]},0)%10,t=Number(t.charAt(t.length-1));if(0==e&&0===t||t===10-e)return!0}return!1},ES:function(t){l(t);var e={X:0,Y:1,Z:2},r=t.trim().toUpperCase();if(!/^[0-9X-Z][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/.test(r))return!1;t=r.slice(0,-1).replace(/[X,Y,Z]/g,function(t){return e[t]});return r.endsWith(["T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E"][t%23])},FI:function(t){if(l(t),11!==t.length)return!1;if(!t.match(/^\d{6}[\-A\+]\d{3}[0-9ABCDEFHJKLMNPRSTUVWXY]{1}$/))return!1;return"0123456789ABCDEFHJKLMNPRSTUVWXY"[(1e3*parseInt(t.slice(0,6),10)+parseInt(t.slice(7,10),10))%31]===t.slice(10,11)},IN:function(t){var r=[[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,0,6,7,8,9,5],[2,3,4,0,1,7,8,9,5,6],[3,4,0,1,2,8,9,5,6,7],[4,0,1,2,3,9,5,6,7,8],[5,9,8,7,6,0,4,3,2,1],[6,5,9,8,7,1,0,4,3,2],[7,6,5,9,8,2,1,0,4,3],[8,7,6,5,9,3,2,1,0,4],[9,8,7,6,5,4,3,2,1,0]],n=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]],t=t.trim();if(!/^[1-9]\d{3}\s?\d{4}\s?\d{4}$/.test(t))return!1;var i=0;return t.replace(/\s/g,"").split("").map(Number).reverse().forEach(function(t,e){i=r[i][n[e%8][t]]}),0===i},IR:function(t){if(!t.match(/^\d{10}$/))return!1;if(t="0000".concat(t).substr(t.length-6),0===parseInt(t.substr(3,6),10))return!1;for(var e=parseInt(t.substr(9,1),10),r=0,n=0;n<9;n++)r+=parseInt(t.substr(n,1),10)*(10-n);return(r%=11)<2&&e===r||2<=r&&e===11-r},IT:function(t){return 9===t.length&&("CA00000AA"!==t&&-1new Date)&&(t.getFullYear()===e&&t.getMonth()===r-1&&t.getDate()===n)}function a(t){return function(t){for(var e=t.substring(0,17),r=0,n=0;n<17;n++)r+=parseInt(e.charAt(n),10)*parseInt(o[n],10);return s[r%11]}(t)===t.charAt(17).toUpperCase()}var e,r=["11","12","13","14","15","21","22","23","31","32","33","34","35","36","37","41","42","43","44","45","46","50","51","52","53","54","61","62","63","64","65","71","81","82","91"],o=["7","9","10","5","8","4","2","1","6","3","7","9","10","5","8","4","2"],s=["1","0","X","9","8","7","6","5","4","3","2"];return!!/^\d{15}|(\d{17}(\d|x|X))$/.test(e=t)&&(15===e.length?function(t){var e=/^[1-9]\d{7}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}$/.test(t);if(!e)return!1;var r=t.substring(0,2);if(!(e=n(r)))return!1;t="19".concat(t.substring(6,12));return!!(e=i(t))}:function(t){var e=/^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}(\d|x|X)$/.test(t);if(!e)return!1;var r=t.substring(0,2);if(!(e=n(r)))return!1;r=t.substring(6,14);return!!(e=i(r))&&a(t)})(e)},"zh-TW":function(t){var n={A:10,B:11,C:12,D:13,E:14,F:15,G:16,H:17,I:34,J:18,K:19,L:20,M:21,N:22,O:35,P:23,Q:24,R:25,S:26,T:27,U:28,V:29,W:32,X:30,Y:31,Z:33},t=t.trim().toUpperCase();return!!/^[A-Z][0-9]{9}$/.test(t)&&Array.from(t).reduce(function(t,e,r){if(0!==r)return 9===r?(10-t%10-Number(e))%10==0:t+Number(e)*(9-r);e=n[e];return e%10*9+Math.floor(e/10)},0)}};var Jt=8,jt=14,Qt=/^(\d{8}|\d{13}|\d{14})$/;function qt(r){var t=10-r.slice(0,-1).split("").map(function(t,e){return Number(t)*(t=r.length,e=e,t===Jt||t===jt?e%2==0?3:1:e%2==0?1:3)}).reduce(function(t,e){return t+e},0)%10;return t<10?t:0}var te=/^[A-Z]{2}[0-9A-Z]{9}[0-9]$/;var ee=/^(?:[0-9]{9}X|[0-9]{10})$/,re=/^(?:[0-9]{13})$/,ne=[1,3];function ie(t){for(var e=10,r=0;ra?"".concat(e-1):"".concat(e)).concat(r);else if(r="".concat(e-1).concat(r),a-parseInt(r,10)<100)return!1}if(60?,.\/ ]$/,qe={minLength:8,minLowercase:1,minUppercase:1,minNumbers:1,minSymbols:1,returnScore:!1,pointsPerUnique:1,pointsPerRepeat:.5,pointsForContainingLower:10,pointsForContainingUpper:10,pointsForContainingNumber:10,pointsForContainingSymbol:10};function tr(t){var e,r,n=(e=t,r={},Array.from(e).forEach(function(t){r[t]?r[t]+=1:r[t]=1}),r),i={length:t.length,uniqueChars:Object.keys(n).length,uppercaseCount:0,lowercaseCount:0,numberCount:0,symbolCount:0};return Object.keys(n).forEach(function(t){Xe.test(t)?i.uppercaseCount+=n[t]:Je.test(t)?i.lowercaseCount+=n[t]:je.test(t)?i.numberCount+=n[t]:Qe.test(t)&&(i.symbolCount+=n[t])}),i}var er={GB:/^GB((\d{3} \d{4} ([0-8][0-9]|9[0-6]))|(\d{9} \d{3})|(((GD[0-4])|(HA[5-9]))[0-9]{2}))$/,IT:/^(IT)?[0-9]{11}$/,NL:/^(NL)?[0-9]{9}B[0-9]{2}$/};return{version:"13.7.0",toDate:a,toFloat:Z,toInt:function(t,e){return l(t),parseInt(t,e||10)},toBoolean:function(t,e){return l(t),e?"1"===t||/^true$/i.test(t):"0"!==t&&!/^false$/i.test(t)&&""!==t},equals:function(t,e){return l(t),t===e},contains:function(t,e,r){return l(t),(r=B(r,N)).ignoreCase?t.toLowerCase().split(M(e).toLowerCase()).length>r.minOccurrences:t.split(M(e)).length>r.minOccurrences},matches:function(t,e,r){return l(t),(e="[object RegExp]"!==Object.prototype.toString.call(e)?new RegExp(e,r):e).test(t)},isEmail:function(t,e){if(l(t),(e=B(e,b)).require_display_name||e.allow_display_name){var r=t.match(U);if(r){var n=r[1];if(t=t.replace(n,"").replace(/(^<|>$)/g,""),!function(t){var e=t.replace(/^"(.+)"$/,"$1");if(e.trim()){if(/[\.";<>]/.test(e)){if(e===t)return;if(!(e.split('"').length===e.split('\\"').length))return}return 1}}(n=n.endsWith(" ")?n.substr(0,n.length-1):n))return!1}else if(e.require_display_name)return!1}if(!e.ignore_max_length&&254]/.test(t))return!1;if(0===t.indexOf("mailto:"))return!1;if((e=B(e,x)).validate_length&&2083<=t.length)return!1;if(!e.allow_fragments&&t.includes("#"))return!1;if(!e.allow_query_components&&(t.includes("?")||t.includes("&")))return!1;var r,n,i=t.split("#");if(1<(i=(t=(i=(t=i.shift()).split("?")).shift()).split("://")).length){if(r=i.shift().toLowerCase(),e.require_valid_protocol&&-1===e.protocols.indexOf(r))return!1}else{if(e.require_protocol)return!1;if("//"===t.substr(0,2)){if(!e.allow_protocol_relative_urls)return!1;i[0]=t.substr(2)}}if(""===(t=i.join("://")))return!1;if(""===(t=(i=t.split("/")).shift())&&!e.require_host)return!0;if(1<(i=t.split("@")).length){if(e.disallow_auth)return!1;if(""===i[0])return!1;if(0<=(c=i.shift()).indexOf(":")&&2/g,">").replace(/\//g,"/").replace(/\\/g,"\").replace(/`/g,"`")},unescape:function(t){return l(t),t.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(///g,"/").replace(/\/g,"\\").replace(/`/g,"`").replace(/&/g,"&")},stripLow:function(t,e){return l(t),Ke(t,e?"\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F":"\\x00-\\x1F\\x7F")},whitelist:function(t,e){return l(t),t.replace(new RegExp("[^".concat(e,"]+"),"g"),"")},blacklist:Ke,isWhitelisted:function(t,e){l(t);for(var r=t.length-1;0<=r;r--)if(-1===e.indexOf(t[r]))return!1;return!0},normalizeEmail:function(t,e){e=B(e,we);var r=t.split("@"),t=r.pop();if((r=[r.join("@"),t])[1]=r[1].toLowerCase(),"gmail.com"===r[1]||"googlemail.com"===r[1]){if(e.gmail_remove_subaddress&&(r[0]=r[0].split("+")[0]),e.gmail_remove_dots&&(r[0]=r[0].replace(/\.+/g,Ve)),!r[0].length)return!1;(e.all_lowercase||e.gmail_lowercase)&&(r[0]=r[0].toLowerCase()),r[1]=e.gmail_convert_googlemaildotcom?"gmail.com":r[1]}else if(0<=ye.indexOf(r[1])){if(e.icloud_remove_subaddress&&(r[0]=r[0].split("+")[0]),!r[0].length)return!1;(e.all_lowercase||e.icloud_lowercase)&&(r[0]=r[0].toLowerCase())}else if(0<=We.indexOf(r[1])){if(e.outlookdotcom_remove_subaddress&&(r[0]=r[0].split("+")[0]),!r[0].length)return!1;(e.all_lowercase||e.outlookdotcom_lowercase)&&(r[0]=r[0].toLowerCase())}else if(0<=Ye.indexOf(r[1])){if(e.yahoo_remove_subaddress&&(t=r[0].split("-"),r[0]=1=e.minLength&&i.lowercaseCount>=e.minLowercase&&i.uppercaseCount>=e.minUppercase&&i.numberCount>=e.minNumbers&&i.symbolCount>=e.minSymbols},isTaxID:function(t){var e=1 + +```js +var vary = require('vary') +``` + +### vary(res, field) + +Adds the given header `field` to the `Vary` response header of `res`. +This can be a string of a single field, a string of a valid `Vary` +header, or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. + + + +```js +// Append "Origin" to the Vary header of the response +vary(res, 'Origin') +``` + +### vary.append(header, field) + +Adds the given header `field` to the `Vary` response header string `header`. +This can be a string of a single field, a string of a valid `Vary` header, +or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. The new header string is returned. + + + +```js +// Get header string appending "Origin" to "Accept, User-Agent" +vary.append('Accept, User-Agent', 'Origin') +``` + +## Examples + +### Updating the Vary header when content is based on it + +```js +var http = require('http') +var vary = require('vary') + +http.createServer(function onRequest (req, res) { + // about to user-agent sniff + vary(res, 'User-Agent') + + var ua = req.headers['user-agent'] || '' + var isMobile = /mobi|android|touch|mini/i.test(ua) + + // serve site, depending on isMobile + res.setHeader('Content-Type', 'text/html') + res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user') +}) +``` + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/vary.svg +[npm-url]: https://npmjs.org/package/vary +[node-version-image]: https://img.shields.io/node/v/vary.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg +[travis-url]: https://travis-ci.org/jshttp/vary +[coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/vary +[downloads-image]: https://img.shields.io/npm/dm/vary.svg +[downloads-url]: https://npmjs.org/package/vary diff --git a/node_modules/vary/index.js b/node_modules/vary/index.js new file mode 100644 index 0000000..5b5e741 --- /dev/null +++ b/node_modules/vary/index.js @@ -0,0 +1,149 @@ +/*! + * vary + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = vary +module.exports.append = append + +/** + * RegExp to match field-name in RFC 7230 sec 3.2 + * + * field-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + */ + +var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/ + +/** + * Append a field to a vary header. + * + * @param {String} header + * @param {String|Array} field + * @return {String} + * @public + */ + +function append (header, field) { + if (typeof header !== 'string') { + throw new TypeError('header argument is required') + } + + if (!field) { + throw new TypeError('field argument is required') + } + + // get fields array + var fields = !Array.isArray(field) + ? parse(String(field)) + : field + + // assert on invalid field names + for (var j = 0; j < fields.length; j++) { + if (!FIELD_NAME_REGEXP.test(fields[j])) { + throw new TypeError('field argument contains an invalid header name') + } + } + + // existing, unspecified vary + if (header === '*') { + return header + } + + // enumerate current values + var val = header + var vals = parse(header.toLowerCase()) + + // unspecified vary + if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { + return '*' + } + + for (var i = 0; i < fields.length; i++) { + var fld = fields[i].toLowerCase() + + // append value (case-preserving) + if (vals.indexOf(fld) === -1) { + vals.push(fld) + val = val + ? val + ', ' + fields[i] + : fields[i] + } + } + + return val +} + +/** + * Parse a vary header into an array. + * + * @param {String} header + * @return {Array} + * @private + */ + +function parse (header) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = header.length; i < len; i++) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(header.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(header.substring(start, end)) + + return list +} + +/** + * Mark that a request is varied on a header field. + * + * @param {Object} res + * @param {String|Array} field + * @public + */ + +function vary (res, field) { + if (!res || !res.getHeader || !res.setHeader) { + // quack quack + throw new TypeError('res argument is required') + } + + // get existing header + var val = res.getHeader('Vary') || '' + var header = Array.isArray(val) + ? val.join(', ') + : String(val) + + // set new header + if ((val = append(header, field))) { + res.setHeader('Vary', val) + } +} diff --git a/node_modules/vary/package.json b/node_modules/vary/package.json new file mode 100644 index 0000000..028f72a --- /dev/null +++ b/node_modules/vary/package.json @@ -0,0 +1,43 @@ +{ + "name": "vary", + "description": "Manipulate the HTTP Vary header", + "version": "1.1.2", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "http", + "res", + "vary" + ], + "repository": "jshttp/vary", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3", + "supertest": "1.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/webidl-conversions/LICENSE.md b/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 0000000..d4a994f --- /dev/null +++ b/node_modules/webidl-conversions/LICENSE.md @@ -0,0 +1,12 @@ +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/webidl-conversions/README.md b/node_modules/webidl-conversions/README.md new file mode 100644 index 0000000..305f0f0 --- /dev/null +++ b/node_modules/webidl-conversions/README.md @@ -0,0 +1,101 @@ +# Web IDL Type Conversions on JavaScript Values + +This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). + +The goal is that you should be able to write code like + +```js +"use strict"; +const conversions = require("webidl-conversions"); + +function doStuff(x, y) { + x = conversions["boolean"](x); + y = conversions["unsigned long"](y); + // actual algorithm code here +} +``` + +and your function `doStuff` will behave the same as a Web IDL operation declared as + +```webidl +void doStuff(boolean x, unsigned long y); +``` + +## API + +This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). + +Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`) + +If we are dealing with multiple JavaScript realms (such as those created using Node.js' [vm](https://nodejs.org/api/vm.html) module or the HTML `iframe` element), and exceptions from another realm need to be thrown, one can supply an object option `globals` containing the following properties: + +```js +{ + globals: { + Number, + String, + TypeError + } +} +``` + +Those specific functions will be used when throwing exceptions. + +Specific conversions may also accept other options, the details of which can be found below. + +## Conversions implemented + +Conversions for all of the basic types from the Web IDL specification are implemented: + +- [`any`](https://heycam.github.io/webidl/#es-any) +- [`void`](https://heycam.github.io/webidl/#es-void) +- [`boolean`](https://heycam.github.io/webidl/#es-boolean) +- [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter +- [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float) +- [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double) +- [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter +- [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString) +- [`object`](https://heycam.github.io/webidl/#es-object) +- [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter + +Additionally, for convenience, the following derived type definitions are implemented: + +- [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter +- [`BufferSource`](https://heycam.github.io/webidl/#BufferSource) +- [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp) +- [`Function`](https://heycam.github.io/webidl/#Function) +- [`VoidFunction`](https://heycam.github.io/webidl/#VoidFunction) (although it will not censor the return type) + +Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project. + +### A note on the `long long` types + +The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers. Conversions are still accurate as we make use of BigInt in the conversion process, but in the case of `unsigned long long` we simply cannot represent some possible output values in JavaScript. For example, converting the JavaScript number `-1` to a Web IDL `unsigned long long` is supposed to produce the Web IDL value `18446744073709551615`. Since we are representing our Web IDL values in JavaScript, we can't represent `18446744073709551615`, so we instead the best we could do is `18446744073709551616` as the output. + +To mitigate this, we could return the raw BigInt value from the conversion function, but right now it is not implemented. If your use case requires such precision, [file an issue](https://github.com/jsdom/webidl-conversions/issues/new). + +On the other hand, `long long` conversion is always accurate, since the input value can never be more precise than the output value. + +### A note on `BufferSource` types + +All of the `BufferSource` types will throw when the relevant `ArrayBuffer` has been detached. This technically is not part of the [specified conversion algorithm](https://heycam.github.io/webidl/#es-buffer-source-types), but instead part of the [getting a reference/getting a copy](https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-reference%E2%91%A0) algorithms. We've consolidated them here for convenience and ease of implementation, but if there is a need to separate them in the future, please open an issue so we can investigate. + +## Background + +What's actually going on here, conceptually, is pretty weird. Let's try to explain. + +Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. + +Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on. + +Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. + +The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell. + +And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`. + +## Don't use this + +Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript. + +The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/jsdom/jsdom) project. diff --git a/node_modules/webidl-conversions/lib/index.js b/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 0000000..71d394a --- /dev/null +++ b/node_modules/webidl-conversions/lib/index.js @@ -0,0 +1,489 @@ +"use strict"; + +function makeException(ErrorType, message, opts = {}) { + if (opts.globals) { + ErrorType = opts.globals[ErrorType.name]; + } + return new ErrorType(`${opts.context ? opts.context : "Value"} ${message}.`); +} + +function toNumber(value, opts = {}) { + if (!opts.globals) { + return +value; + } + if (typeof value === "bigint") { + throw opts.globals.TypeError("Cannot convert a BigInt value to a number"); + } + return opts.globals.Number(value); +} + +function type(V) { + if (V === null) { + return "Null"; + } + switch (typeof V) { + case "undefined": + return "Undefined"; + case "boolean": + return "Boolean"; + case "number": + return "Number"; + case "string": + return "String"; + case "symbol": + return "Symbol"; + case "bigint": + return "BigInt"; + case "object": + // Falls through + case "function": + // Falls through + default: + // Per ES spec, typeof returns an implemention-defined value that is not any of the existing ones for + // uncallable non-standard exotic objects. Yet Type() which the Web IDL spec depends on returns Object for + // such cases. So treat the default case as an object. + return "Object"; + } +} + +// Round x to the nearest integer, choosing the even integer if it lies halfway between two. +function evenRound(x) { + // There are four cases for numbers with fractional part being .5: + // + // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example + // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0 + // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2 + // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0 + // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2 + // (where n is a non-negative integer) + // + // Branch here for cases 1 and 4 + if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) || + (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) { + return censorNegativeZero(Math.floor(x)); + } + + return censorNegativeZero(Math.round(x)); +} + +function integerPart(n) { + return censorNegativeZero(Math.trunc(n)); +} + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function modulo(x, y) { + // https://tc39.github.io/ecma262/#eqn-modulo + // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos + const signMightNotMatch = x % y; + if (sign(y) !== sign(signMightNotMatch)) { + return signMightNotMatch + y; + } + return signMightNotMatch; +} + +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} + +function createIntegerConversion(bitLength, typeOpts) { + const isSigned = !typeOpts.unsigned; + + let lowerBound; + let upperBound; + if (bitLength === 64) { + upperBound = Number.MAX_SAFE_INTEGER; + lowerBound = !isSigned ? 0 : Number.MIN_SAFE_INTEGER; + } else if (!isSigned) { + lowerBound = 0; + upperBound = Math.pow(2, bitLength) - 1; + } else { + lowerBound = -Math.pow(2, bitLength - 1); + upperBound = Math.pow(2, bitLength - 1) - 1; + } + + const twoToTheBitLength = Math.pow(2, bitLength); + const twoToOneLessThanTheBitLength = Math.pow(2, bitLength - 1); + + return (V, opts = {}) => { + let x = toNumber(V, opts); + x = censorNegativeZero(x); + + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite number", opts); + } + + x = integerPart(x); + + if (x < lowerBound || x > upperBound) { + throw makeException(TypeError, + `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts); + } + + return x; + } + + if (!Number.isNaN(x) && opts.clamp) { + x = Math.min(Math.max(x, lowerBound), upperBound); + x = evenRound(x); + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + x = integerPart(x); + + // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if + // possible. Hopefully it's an optimization for the non-64-bitLength cases too. + if (x >= lowerBound && x <= upperBound) { + return x; + } + + // These will not work great for bitLength of 64, but oh well. See the README for more details. + x = modulo(x, twoToTheBitLength); + if (isSigned && x >= twoToOneLessThanTheBitLength) { + return x - twoToTheBitLength; + } + return x; + }; +} + +function createLongLongConversion(bitLength, { unsigned }) { + const upperBound = Number.MAX_SAFE_INTEGER; + const lowerBound = unsigned ? 0 : Number.MIN_SAFE_INTEGER; + const asBigIntN = unsigned ? BigInt.asUintN : BigInt.asIntN; + + return (V, opts = {}) => { + if (opts === undefined) { + opts = {}; + } + + let x = toNumber(V, opts); + x = censorNegativeZero(x); + + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite number", opts); + } + + x = integerPart(x); + + if (x < lowerBound || x > upperBound) { + throw makeException(TypeError, + `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts); + } + + return x; + } + + if (!Number.isNaN(x) && opts.clamp) { + x = Math.min(Math.max(x, lowerBound), upperBound); + x = evenRound(x); + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + + let xBigInt = BigInt(integerPart(x)); + xBigInt = asBigIntN(bitLength, xBigInt); + return Number(xBigInt); + }; +} + +exports.any = V => { + return V; +}; + +exports.void = function () { + return undefined; +}; + +exports.boolean = function (val) { + return !!val; +}; + +exports.byte = createIntegerConversion(8, { unsigned: false }); +exports.octet = createIntegerConversion(8, { unsigned: true }); + +exports.short = createIntegerConversion(16, { unsigned: false }); +exports["unsigned short"] = createIntegerConversion(16, { unsigned: true }); + +exports.long = createIntegerConversion(32, { unsigned: false }); +exports["unsigned long"] = createIntegerConversion(32, { unsigned: true }); + +exports["long long"] = createLongLongConversion(64, { unsigned: false }); +exports["unsigned long long"] = createLongLongConversion(64, { unsigned: true }); + +exports.double = (V, opts) => { + const x = toNumber(V, opts); + + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite floating-point value", opts); + } + + return x; +}; + +exports["unrestricted double"] = (V, opts) => { + const x = toNumber(V, opts); + + return x; +}; + +exports.float = (V, opts) => { + const x = toNumber(V, opts); + + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite floating-point value", opts); + } + + if (Object.is(x, -0)) { + return x; + } + + const y = Math.fround(x); + + if (!Number.isFinite(y)) { + throw makeException(TypeError, "is outside the range of a single-precision floating-point value", opts); + } + + return y; +}; + +exports["unrestricted float"] = (V, opts) => { + const x = toNumber(V, opts); + + if (isNaN(x)) { + return x; + } + + if (Object.is(x, -0)) { + return x; + } + + return Math.fround(x); +}; + +exports.DOMString = function (V, opts = {}) { + if (opts.treatNullAsEmptyString && V === null) { + return ""; + } + + if (typeof V === "symbol") { + throw makeException(TypeError, "is a symbol, which cannot be converted to a string", opts); + } + + const StringCtor = opts.globals ? opts.globals.String : String; + return StringCtor(V); +}; + +exports.ByteString = (V, opts) => { + const x = exports.DOMString(V, opts); + let c; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw makeException(TypeError, "is not a valid ByteString", opts); + } + } + + return x; +}; + +exports.USVString = (V, opts) => { + const S = exports.DOMString(V, opts); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + + return U.join(""); +}; + +exports.object = (V, opts) => { + if (type(V) !== "Object") { + throw makeException(TypeError, "is not an object", opts); + } + + return V; +}; + +// Not exported, but used in Function and VoidFunction. + +// Neither Function nor VoidFunction is defined with [TreatNonObjectAsNull], so +// handling for that is omitted. +function convertCallbackFunction(V, opts) { + if (typeof V !== "function") { + throw makeException(TypeError, "is not a function", opts); + } + return V; +} + +const abByteLengthGetter = + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; +const sabByteLengthGetter = + Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get; + +function isNonSharedArrayBuffer(V) { + try { + // This will throw on SharedArrayBuffers, but not detached ArrayBuffers. + // (The spec says it should throw, but the spec conflicts with implementations: https://github.com/tc39/ecma262/issues/678) + abByteLengthGetter.call(V); + + return true; + } catch { + return false; + } +} + +function isSharedArrayBuffer(V) { + try { + sabByteLengthGetter.call(V); + return true; + } catch { + return false; + } +} + +function isArrayBufferDetached(V) { + try { + // eslint-disable-next-line no-new + new Uint8Array(V); + return false; + } catch { + return true; + } +} + +exports.ArrayBuffer = (V, opts = {}) => { + if (!isNonSharedArrayBuffer(V)) { + if (opts.allowShared && !isSharedArrayBuffer(V)) { + throw makeException(TypeError, "is not an ArrayBuffer or SharedArrayBuffer", opts); + } + throw makeException(TypeError, "is not an ArrayBuffer", opts); + } + if (isArrayBufferDetached(V)) { + throw makeException(TypeError, "is a detached ArrayBuffer", opts); + } + + return V; +}; + +const dvByteLengthGetter = + Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get; +exports.DataView = (V, opts = {}) => { + try { + dvByteLengthGetter.call(V); + } catch (e) { + throw makeException(TypeError, "is not a DataView", opts); + } + + if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) { + throw makeException(TypeError, "is backed by a SharedArrayBuffer, which is not allowed", opts); + } + if (isArrayBufferDetached(V.buffer)) { + throw makeException(TypeError, "is backed by a detached ArrayBuffer", opts); + } + + return V; +}; + +// Returns the unforgeable `TypedArray` constructor name or `undefined`, +// if the `this` value isn't a valid `TypedArray` object. +// +// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag +const typedArrayNameGetter = Object.getOwnPropertyDescriptor( + Object.getPrototypeOf(Uint8Array).prototype, + Symbol.toStringTag +).get; +[ + Int8Array, Int16Array, Int32Array, Uint8Array, + Uint16Array, Uint32Array, Uint8ClampedArray, Float32Array, Float64Array +].forEach(func => { + const name = func.name; + const article = /^[AEIOU]/.test(name) ? "an" : "a"; + exports[name] = (V, opts = {}) => { + if (!ArrayBuffer.isView(V) || typedArrayNameGetter.call(V) !== name) { + throw makeException(TypeError, `is not ${article} ${name} object`, opts); + } + if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts); + } + if (isArrayBufferDetached(V.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts); + } + + return V; + }; +}); + +// Common definitions + +exports.ArrayBufferView = (V, opts = {}) => { + if (!ArrayBuffer.isView(V)) { + throw makeException(TypeError, "is not a view on an ArrayBuffer or SharedArrayBuffer", opts); + } + + if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts); + } + + if (isArrayBufferDetached(V.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts); + } + return V; +}; + +exports.BufferSource = (V, opts = {}) => { + if (ArrayBuffer.isView(V)) { + if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts); + } + + if (isArrayBufferDetached(V.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts); + } + return V; + } + + if (!opts.allowShared && !isNonSharedArrayBuffer(V)) { + throw makeException(TypeError, "is not an ArrayBuffer or a view on one", opts); + } + if (opts.allowShared && !isSharedArrayBuffer(V) && !isNonSharedArrayBuffer(V)) { + throw makeException(TypeError, "is not an ArrayBuffer, SharedArrayBufer, or a view on one", opts); + } + if (isArrayBufferDetached(V)) { + throw makeException(TypeError, "is a detached ArrayBuffer", opts); + } + + return V; +}; + +exports.DOMTimeStamp = exports["unsigned long long"]; + +exports.Function = convertCallbackFunction; + +exports.VoidFunction = convertCallbackFunction; diff --git a/node_modules/webidl-conversions/package.json b/node_modules/webidl-conversions/package.json new file mode 100644 index 0000000..c27689c --- /dev/null +++ b/node_modules/webidl-conversions/package.json @@ -0,0 +1,30 @@ +{ + "name": "webidl-conversions", + "version": "6.1.0", + "description": "Implements the WebIDL algorithms for converting to and from JavaScript values", + "main": "lib/index.js", + "scripts": { + "lint": "eslint .", + "test": "mocha test/*.js", + "coverage": "nyc mocha test/*.js" + }, + "repository": "jsdom/webidl-conversions", + "keywords": [ + "webidl", + "web", + "types" + ], + "files": [ + "lib/" + ], + "author": "Domenic Denicola (https://domenic.me/)", + "license": "BSD-2-Clause", + "devDependencies": { + "eslint": "^6.8.0", + "mocha": "^7.1.1", + "nyc": "^15.0.0" + }, + "engines": { + "node": ">=10.4" + } +} diff --git a/node_modules/whatwg-url/LICENSE.txt b/node_modules/whatwg-url/LICENSE.txt new file mode 100644 index 0000000..54dfac3 --- /dev/null +++ b/node_modules/whatwg-url/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015–2016 Sebastian Mayr + +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/whatwg-url/README.md b/node_modules/whatwg-url/README.md new file mode 100644 index 0000000..6e1eb45 --- /dev/null +++ b/node_modules/whatwg-url/README.md @@ -0,0 +1,105 @@ +# whatwg-url + +whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/jsdom/jsdom). + +## Specification conformance + +whatwg-url is currently up to date with the URL spec up to commit [ab0e820](https://github.com/whatwg/url/commit/ab0e820b0b559610b30c731b7f2c1a8094181680). + +For `file:` URLs, whose [origin is left unspecified](https://url.spec.whatwg.org/#concept-url-origin), whatwg-url chooses to use a new opaque origin (which serializes to `"null"`). + +whatwg-url does not yet implement any encoding handling beyond UTF-8. That is, the _encoding override_ parameter does not exist in our API. + +## API + +### The `URL` and `URLSearchParams` classes + +The main API is provided by the [`URL`](https://url.spec.whatwg.org/#url-class) and [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) exports, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use these. + +### Low-level URL Standard API + +The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They mostly operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. + +- [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL })` +- [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, url, stateOverride })` +- [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` +- [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` +- [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` +- [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin): `serializeURLOrigin(urlRecord)` +- [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` +- [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` +- [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` +- [Percent decode bytes](https://url.spec.whatwg.org/#percent-decode): `percentDecodeBytes(uint8Array)` +- [Percent decode a string](https://url.spec.whatwg.org/#percent-decode-string): `percentDecodeString(string)` + +The `stateOverride` parameter is one of the following strings: + +- [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) +- [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) +- [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) +- [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) +- [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) +- [`"relative"`](https://url.spec.whatwg.org/#relative-state) +- [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) +- [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) +- [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) +- [`"authority"`](https://url.spec.whatwg.org/#authority-state) +- [`"host"`](https://url.spec.whatwg.org/#host-state) +- [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) +- [`"port"`](https://url.spec.whatwg.org/#port-state) +- [`"file"`](https://url.spec.whatwg.org/#file-state) +- [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) +- [`"file host"`](https://url.spec.whatwg.org/#file-host-state) +- [`"path start"`](https://url.spec.whatwg.org/#path-start-state) +- [`"path"`](https://url.spec.whatwg.org/#path-state) +- [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) +- [`"query"`](https://url.spec.whatwg.org/#query-state) +- [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) + +The URL record type has the following API: + +- [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) +- [`username`](https://url.spec.whatwg.org/#concept-url-username) +- [`password`](https://url.spec.whatwg.org/#concept-url-password) +- [`host`](https://url.spec.whatwg.org/#concept-url-host) +- [`port`](https://url.spec.whatwg.org/#concept-url-port) +- [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) +- [`query`](https://url.spec.whatwg.org/#concept-url-query) +- [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) +- [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) + +These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. + +The return value of "failure" in the spec is represented by `null`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ `null`. + +### `whatwg-url/webidl2js-wrapper` module + +This module exports the `URL` and `URLSearchParams` [interface wrappers API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js). + +## Development instructions + +First, install [Node.js](https://nodejs.org/). Then, fetch the dependencies of whatwg-url, by running from this directory: + + npm install + +To run tests: + + npm test + +To generate a coverage report: + + npm run coverage + +To build and run the live viewer: + + npm run prepare + npm run build-live-viewer + +Serve the contents of the `live-viewer` directory using any web server. + +## Supporting whatwg-url + +The jsdom project (including whatwg-url) is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support us by: + +- [Getting professional support for whatwg-url](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&utm_medium=referral&utm_campaign=readme) as part of a Tidelift subscription. Tidelift helps making open source sustainable for us while giving teams assurances for maintenance, licensing, and security. +- Contributing directly to the project. diff --git a/node_modules/whatwg-url/dist/Function.js b/node_modules/whatwg-url/dist/Function.js new file mode 100644 index 0000000..bf5c808 --- /dev/null +++ b/node_modules/whatwg-url/dist/Function.js @@ -0,0 +1,46 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +exports.convert = (value, { context = "The provided value" } = {}) => { + if (typeof value !== "function") { + throw new TypeError(context + " is not a function"); + } + + function invokeTheCallbackFunction(...args) { + if (new.target !== undefined) { + throw new Error("Internal error: invokeTheCallbackFunction is not a constructor"); + } + + const thisArg = utils.tryWrapperForImpl(this); + let callResult; + + for (let i = 0; i < args.length; i++) { + args[i] = utils.tryWrapperForImpl(args[i]); + } + + callResult = Reflect.apply(value, thisArg, args); + + callResult = conversions["any"](callResult, { context: context }); + + return callResult; + } + + invokeTheCallbackFunction.construct = (...args) => { + for (let i = 0; i < args.length; i++) { + args[i] = utils.tryWrapperForImpl(args[i]); + } + + let callResult = Reflect.construct(value, args); + + callResult = conversions["any"](callResult, { context: context }); + + return callResult; + }; + + invokeTheCallbackFunction[utils.wrapperSymbol] = value; + invokeTheCallbackFunction.objectReference = value; + + return invokeTheCallbackFunction; +}; diff --git a/node_modules/whatwg-url/dist/URL-impl.js b/node_modules/whatwg-url/dist/URL-impl.js new file mode 100644 index 0000000..7a11661 --- /dev/null +++ b/node_modules/whatwg-url/dist/URL-impl.js @@ -0,0 +1,217 @@ +"use strict"; +const usm = require("./url-state-machine"); +const urlencoded = require("./urlencoded"); +const URLSearchParams = require("./URLSearchParams"); + +exports.implementation = class URLImpl { + constructor(globalObject, constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === null) { + throw new TypeError(`Invalid base URL: ${base}`); + } + } + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === null) { + throw new TypeError(`Invalid URL: ${url}`); + } + + const query = parsedURL.query !== null ? parsedURL.query : ""; + + this._url = parsedURL; + + // We cannot invoke the "new URLSearchParams object" algorithm without going through the constructor, which strips + // question mark by default. Therefore the doNotStripQMark hack is used. + this._query = URLSearchParams.createImpl(globalObject, [query], { doNotStripQMark: true }); + this._query._url = this; + } + + get href() { + return usm.serializeURL(this._url); + } + + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === null) { + throw new TypeError(`Invalid URL: ${v}`); + } + + this._url = parsedURL; + + this._query._list.splice(0); + const { query } = parsedURL; + if (query !== null) { + this._query._list = urlencoded.parseUrlencodedString(query); + } + } + + get origin() { + return usm.serializeURLOrigin(this._url); + } + + get protocol() { + return `${this._url.scheme}:`; + } + + set protocol(v) { + usm.basicURLParse(`${v}:`, { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; + } + + if (url.port === null) { + return usm.serializeHost(url.host); + } + + return `${usm.serializeHost(url.host)}:${usm.serializeInteger(url.port)}`; + } + + set host(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; + } + + return usm.serializeHost(this._url.host); + } + + set hostname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; + } + + return usm.serializeInteger(this._url.port); + } + + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } + + get pathname() { + if (this._url.cannotBeABaseURL) { + return this._url.path[0]; + } + + if (this._url.path.length === 0) { + return ""; + } + + return `/${this._url.path.join("/")}`; + } + + set pathname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } + + return `?${this._url.query}`; + } + + set search(v) { + const url = this._url; + + if (v === "") { + url.query = null; + this._query._list = []; + return; + } + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + this._query._list = urlencoded.parseUrlencodedString(input); + } + + get searchParams() { + return this._query; + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } + + return `#${this._url.fragment}`; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } +}; diff --git a/node_modules/whatwg-url/dist/URL.js b/node_modules/whatwg-url/dist/URL.js new file mode 100644 index 0000000..6d859d9 --- /dev/null +++ b/node_modules/whatwg-url/dist/URL.js @@ -0,0 +1,417 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +const implSymbol = utils.implSymbol; +const ctorRegistrySymbol = utils.ctorRegistrySymbol; + +const interfaceName = "URL"; + +exports.is = value => { + return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation; +}; +exports.isImpl = value => { + return utils.isObject(value) && value instanceof Impl.implementation; +}; +exports.convert = (value, { context = "The provided value" } = {}) => { + if (exports.is(value)) { + return utils.implForWrapper(value); + } + throw new TypeError(`${context} is not of type 'URL'.`); +}; + +function makeWrapper(globalObject) { + if (globalObject[ctorRegistrySymbol] === undefined) { + throw new Error("Internal error: invalid global object"); + } + + const ctor = globalObject[ctorRegistrySymbol]["URL"]; + if (ctor === undefined) { + throw new Error("Internal error: constructor URL is not installed on the passed global object"); + } + + return Object.create(ctor.prototype); +} + +exports.create = (globalObject, constructorArgs, privateData) => { + const wrapper = makeWrapper(globalObject); + return exports.setup(wrapper, globalObject, constructorArgs, privateData); +}; + +exports.createImpl = (globalObject, constructorArgs, privateData) => { + const wrapper = exports.create(globalObject, constructorArgs, privateData); + return utils.implForWrapper(wrapper); +}; + +exports._internalSetup = (wrapper, globalObject) => {}; + +exports.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => { + privateData.wrapper = wrapper; + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: new Impl.implementation(globalObject, constructorArgs, privateData), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper; +}; + +exports.new = globalObject => { + const wrapper = makeWrapper(globalObject); + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: Object.create(Impl.implementation.prototype), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper[implSymbol]; +}; + +const exposed = new Set(["Window", "Worker"]); + +exports.install = (globalObject, globalNames) => { + if (!globalNames.some(globalName => exposed.has(globalName))) { + return; + } + class URL { + constructor(url) { + if (arguments.length < 1) { + throw new TypeError( + "Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present." + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { context: "Failed to construct 'URL': parameter 1" }); + args.push(curArg); + } + { + let curArg = arguments[1]; + if (curArg !== undefined) { + curArg = conversions["USVString"](curArg, { context: "Failed to construct 'URL': parameter 2" }); + } + args.push(curArg); + } + return exports.setup(Object.create(new.target.prototype), globalObject, args); + } + + toJSON() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new TypeError("'toJSON' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol].toJSON(); + } + + get href() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get href' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["href"]; + } + + set href(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'set href' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { context: "Failed to set the 'href' property on 'URL': The provided value" }); + + esValue[implSymbol]["href"] = V; + } + + toString() { + const esValue = this; + if (!exports.is(esValue)) { + throw new TypeError("'toString' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["href"]; + } + + get origin() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get origin' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["origin"]; + } + + get protocol() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get protocol' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["protocol"]; + } + + set protocol(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'set protocol' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'protocol' property on 'URL': The provided value" + }); + + esValue[implSymbol]["protocol"] = V; + } + + get username() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get username' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["username"]; + } + + set username(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'set username' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'username' property on 'URL': The provided value" + }); + + esValue[implSymbol]["username"] = V; + } + + get password() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get password' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["password"]; + } + + set password(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'set password' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'password' property on 'URL': The provided value" + }); + + esValue[implSymbol]["password"] = V; + } + + get host() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get host' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["host"]; + } + + set host(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'set host' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { context: "Failed to set the 'host' property on 'URL': The provided value" }); + + esValue[implSymbol]["host"] = V; + } + + get hostname() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get hostname' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["hostname"]; + } + + set hostname(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'set hostname' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'hostname' property on 'URL': The provided value" + }); + + esValue[implSymbol]["hostname"] = V; + } + + get port() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get port' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["port"]; + } + + set port(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'set port' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { context: "Failed to set the 'port' property on 'URL': The provided value" }); + + esValue[implSymbol]["port"] = V; + } + + get pathname() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get pathname' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["pathname"]; + } + + set pathname(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'set pathname' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'pathname' property on 'URL': The provided value" + }); + + esValue[implSymbol]["pathname"] = V; + } + + get search() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get search' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["search"]; + } + + set search(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'set search' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { context: "Failed to set the 'search' property on 'URL': The provided value" }); + + esValue[implSymbol]["search"] = V; + } + + get searchParams() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get searchParams' called on an object that is not a valid instance of URL."); + } + + return utils.getSameObject(this, "searchParams", () => { + return utils.tryWrapperForImpl(esValue[implSymbol]["searchParams"]); + }); + } + + get hash() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'get hash' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["hash"]; + } + + set hash(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new TypeError("'set hash' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { context: "Failed to set the 'hash' property on 'URL': The provided value" }); + + esValue[implSymbol]["hash"] = V; + } + } + Object.defineProperties(URL.prototype, { + toJSON: { enumerable: true }, + href: { enumerable: true }, + toString: { enumerable: true }, + origin: { enumerable: true }, + protocol: { enumerable: true }, + username: { enumerable: true }, + password: { enumerable: true }, + host: { enumerable: true }, + hostname: { enumerable: true }, + port: { enumerable: true }, + pathname: { enumerable: true }, + search: { enumerable: true }, + searchParams: { enumerable: true }, + hash: { enumerable: true }, + [Symbol.toStringTag]: { value: "URL", configurable: true } + }); + if (globalObject[ctorRegistrySymbol] === undefined) { + globalObject[ctorRegistrySymbol] = Object.create(null); + } + globalObject[ctorRegistrySymbol][interfaceName] = URL; + + Object.defineProperty(globalObject, interfaceName, { + configurable: true, + writable: true, + value: URL + }); + + if (globalNames.includes("Window")) { + Object.defineProperty(globalObject, "webkitURL", { + configurable: true, + writable: true, + value: URL + }); + } +}; + +const Impl = require("./URL-impl.js"); diff --git a/node_modules/whatwg-url/dist/URLSearchParams-impl.js b/node_modules/whatwg-url/dist/URLSearchParams-impl.js new file mode 100644 index 0000000..ef8d604 --- /dev/null +++ b/node_modules/whatwg-url/dist/URLSearchParams-impl.js @@ -0,0 +1,130 @@ +"use strict"; +const urlencoded = require("./urlencoded"); + +exports.implementation = class URLSearchParamsImpl { + constructor(globalObject, constructorArgs, { doNotStripQMark = false }) { + let init = constructorArgs[0]; + this._list = []; + this._url = null; + + if (!doNotStripQMark && typeof init === "string" && init[0] === "?") { + init = init.slice(1); + } + + if (Array.isArray(init)) { + for (const pair of init) { + if (pair.length !== 2) { + throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not " + + "contain exactly two elements."); + } + this._list.push([pair[0], pair[1]]); + } + } else if (typeof init === "object" && Object.getPrototypeOf(init) === null) { + for (const name of Object.keys(init)) { + const value = init[name]; + this._list.push([name, value]); + } + } else { + this._list = urlencoded.parseUrlencodedString(init); + } + } + + _updateSteps() { + if (this._url !== null) { + let query = urlencoded.serializeUrlencoded(this._list); + if (query === "") { + query = null; + } + this._url._url.query = query; + } + } + + append(name, value) { + this._list.push([name, value]); + this._updateSteps(); + } + + delete(name) { + let i = 0; + while (i < this._list.length) { + if (this._list[i][0] === name) { + this._list.splice(i, 1); + } else { + i++; + } + } + this._updateSteps(); + } + + get(name) { + for (const tuple of this._list) { + if (tuple[0] === name) { + return tuple[1]; + } + } + return null; + } + + getAll(name) { + const output = []; + for (const tuple of this._list) { + if (tuple[0] === name) { + output.push(tuple[1]); + } + } + return output; + } + + has(name) { + for (const tuple of this._list) { + if (tuple[0] === name) { + return true; + } + } + return false; + } + + set(name, value) { + let found = false; + let i = 0; + while (i < this._list.length) { + if (this._list[i][0] === name) { + if (found) { + this._list.splice(i, 1); + } else { + found = true; + this._list[i][1] = value; + i++; + } + } else { + i++; + } + } + if (!found) { + this._list.push([name, value]); + } + this._updateSteps(); + } + + sort() { + this._list.sort((a, b) => { + if (a[0] < b[0]) { + return -1; + } + if (a[0] > b[0]) { + return 1; + } + return 0; + }); + + this._updateSteps(); + } + + [Symbol.iterator]() { + return this._list[Symbol.iterator](); + } + + toString() { + return urlencoded.serializeUrlencoded(this._list); + } +}; diff --git a/node_modules/whatwg-url/dist/URLSearchParams.js b/node_modules/whatwg-url/dist/URLSearchParams.js new file mode 100644 index 0000000..ba29f06 --- /dev/null +++ b/node_modules/whatwg-url/dist/URLSearchParams.js @@ -0,0 +1,457 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +const Function = require("./Function.js"); +const implSymbol = utils.implSymbol; +const ctorRegistrySymbol = utils.ctorRegistrySymbol; + +const interfaceName = "URLSearchParams"; + +const IteratorPrototype = Object.create(utils.IteratorPrototype, { + next: { + value: function next() { + const internal = this && this[utils.iterInternalSymbol]; + if (!internal) { + throw new TypeError("next() called on a value that is not an iterator prototype object"); + } + + const { target, kind, index } = internal; + const values = Array.from(target[implSymbol]); + const len = values.length; + if (index >= len) { + return { value: undefined, done: true }; + } + + const pair = values[index]; + internal.index = index + 1; + return utils.iteratorResult(pair.map(utils.tryWrapperForImpl), kind); + }, + writable: true, + enumerable: true, + configurable: true + }, + [Symbol.toStringTag]: { + value: "URLSearchParams Iterator", + configurable: true + } +}); + +exports.is = value => { + return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation; +}; +exports.isImpl = value => { + return utils.isObject(value) && value instanceof Impl.implementation; +}; +exports.convert = (value, { context = "The provided value" } = {}) => { + if (exports.is(value)) { + return utils.implForWrapper(value); + } + throw new TypeError(`${context} is not of type 'URLSearchParams'.`); +}; + +exports.createDefaultIterator = (target, kind) => { + const iterator = Object.create(IteratorPrototype); + Object.defineProperty(iterator, utils.iterInternalSymbol, { + value: { target, kind, index: 0 }, + configurable: true + }); + return iterator; +}; + +function makeWrapper(globalObject) { + if (globalObject[ctorRegistrySymbol] === undefined) { + throw new Error("Internal error: invalid global object"); + } + + const ctor = globalObject[ctorRegistrySymbol]["URLSearchParams"]; + if (ctor === undefined) { + throw new Error("Internal error: constructor URLSearchParams is not installed on the passed global object"); + } + + return Object.create(ctor.prototype); +} + +exports.create = (globalObject, constructorArgs, privateData) => { + const wrapper = makeWrapper(globalObject); + return exports.setup(wrapper, globalObject, constructorArgs, privateData); +}; + +exports.createImpl = (globalObject, constructorArgs, privateData) => { + const wrapper = exports.create(globalObject, constructorArgs, privateData); + return utils.implForWrapper(wrapper); +}; + +exports._internalSetup = (wrapper, globalObject) => {}; + +exports.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => { + privateData.wrapper = wrapper; + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: new Impl.implementation(globalObject, constructorArgs, privateData), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper; +}; + +exports.new = globalObject => { + const wrapper = makeWrapper(globalObject); + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: Object.create(Impl.implementation.prototype), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper[implSymbol]; +}; + +const exposed = new Set(["Window", "Worker"]); + +exports.install = (globalObject, globalNames) => { + if (!globalNames.some(globalName => exposed.has(globalName))) { + return; + } + class URLSearchParams { + constructor() { + const args = []; + { + let curArg = arguments[0]; + if (curArg !== undefined) { + if (utils.isObject(curArg)) { + if (curArg[Symbol.iterator] !== undefined) { + if (!utils.isObject(curArg)) { + throw new TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + " sequence" + " is not an iterable object." + ); + } else { + const V = []; + const tmp = curArg; + for (let nextItem of tmp) { + if (!utils.isObject(nextItem)) { + throw new TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + + " sequence" + + "'s element" + + " is not an iterable object." + ); + } else { + const V = []; + const tmp = nextItem; + for (let nextItem of tmp) { + nextItem = conversions["USVString"](nextItem, { + context: + "Failed to construct 'URLSearchParams': parameter 1" + + " sequence" + + "'s element" + + "'s element" + }); + + V.push(nextItem); + } + nextItem = V; + } + + V.push(nextItem); + } + curArg = V; + } + } else { + if (!utils.isObject(curArg)) { + throw new TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + " record" + " is not an object." + ); + } else { + const result = Object.create(null); + for (const key of Reflect.ownKeys(curArg)) { + const desc = Object.getOwnPropertyDescriptor(curArg, key); + if (desc && desc.enumerable) { + let typedKey = key; + + typedKey = conversions["USVString"](typedKey, { + context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s key" + }); + + let typedValue = curArg[key]; + + typedValue = conversions["USVString"](typedValue, { + context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s value" + }); + + result[typedKey] = typedValue; + } + } + curArg = result; + } + } + } else { + curArg = conversions["USVString"](curArg, { + context: "Failed to construct 'URLSearchParams': parameter 1" + }); + } + } else { + curArg = ""; + } + args.push(curArg); + } + return exports.setup(Object.create(new.target.prototype), globalObject, args); + } + + append(name, value) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new TypeError("'append' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 2) { + throw new TypeError( + "Failed to execute 'append' on 'URLSearchParams': 2 arguments required, but only " + + arguments.length + + " present." + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'append' on 'URLSearchParams': parameter 1" + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'append' on 'URLSearchParams': parameter 2" + }); + args.push(curArg); + } + return esValue[implSymbol].append(...args); + } + + delete(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new TypeError("'delete' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 1) { + throw new TypeError( + "Failed to execute 'delete' on 'URLSearchParams': 1 argument required, but only " + + arguments.length + + " present." + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'delete' on 'URLSearchParams': parameter 1" + }); + args.push(curArg); + } + return esValue[implSymbol].delete(...args); + } + + get(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new TypeError("'get' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 1) { + throw new TypeError( + "Failed to execute 'get' on 'URLSearchParams': 1 argument required, but only " + + arguments.length + + " present." + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'get' on 'URLSearchParams': parameter 1" + }); + args.push(curArg); + } + return esValue[implSymbol].get(...args); + } + + getAll(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new TypeError("'getAll' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 1) { + throw new TypeError( + "Failed to execute 'getAll' on 'URLSearchParams': 1 argument required, but only " + + arguments.length + + " present." + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'getAll' on 'URLSearchParams': parameter 1" + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].getAll(...args)); + } + + has(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new TypeError("'has' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 1) { + throw new TypeError( + "Failed to execute 'has' on 'URLSearchParams': 1 argument required, but only " + + arguments.length + + " present." + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'has' on 'URLSearchParams': parameter 1" + }); + args.push(curArg); + } + return esValue[implSymbol].has(...args); + } + + set(name, value) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new TypeError("'set' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 2) { + throw new TypeError( + "Failed to execute 'set' on 'URLSearchParams': 2 arguments required, but only " + + arguments.length + + " present." + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'set' on 'URLSearchParams': parameter 1" + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'set' on 'URLSearchParams': parameter 2" + }); + args.push(curArg); + } + return esValue[implSymbol].set(...args); + } + + sort() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new TypeError("'sort' called on an object that is not a valid instance of URLSearchParams."); + } + + return esValue[implSymbol].sort(); + } + + toString() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new TypeError("'toString' called on an object that is not a valid instance of URLSearchParams."); + } + + return esValue[implSymbol].toString(); + } + + keys() { + if (!exports.is(this)) { + throw new TypeError("'keys' called on an object that is not a valid instance of URLSearchParams."); + } + return exports.createDefaultIterator(this, "key"); + } + + values() { + if (!exports.is(this)) { + throw new TypeError("'values' called on an object that is not a valid instance of URLSearchParams."); + } + return exports.createDefaultIterator(this, "value"); + } + + entries() { + if (!exports.is(this)) { + throw new TypeError("'entries' called on an object that is not a valid instance of URLSearchParams."); + } + return exports.createDefaultIterator(this, "key+value"); + } + + forEach(callback) { + if (!exports.is(this)) { + throw new TypeError("'forEach' called on an object that is not a valid instance of URLSearchParams."); + } + if (arguments.length < 1) { + throw new TypeError("Failed to execute 'forEach' on 'iterable': 1 argument required, " + "but only 0 present."); + } + callback = Function.convert(callback, { + context: "Failed to execute 'forEach' on 'iterable': The callback provided as parameter 1" + }); + const thisArg = arguments[1]; + let pairs = Array.from(this[implSymbol]); + let i = 0; + while (i < pairs.length) { + const [key, value] = pairs[i].map(utils.tryWrapperForImpl); + callback.call(thisArg, value, key, this); + pairs = Array.from(this[implSymbol]); + i++; + } + } + } + Object.defineProperties(URLSearchParams.prototype, { + append: { enumerable: true }, + delete: { enumerable: true }, + get: { enumerable: true }, + getAll: { enumerable: true }, + has: { enumerable: true }, + set: { enumerable: true }, + sort: { enumerable: true }, + toString: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true }, + forEach: { enumerable: true }, + [Symbol.toStringTag]: { value: "URLSearchParams", configurable: true }, + [Symbol.iterator]: { value: URLSearchParams.prototype.entries, configurable: true, writable: true } + }); + if (globalObject[ctorRegistrySymbol] === undefined) { + globalObject[ctorRegistrySymbol] = Object.create(null); + } + globalObject[ctorRegistrySymbol][interfaceName] = URLSearchParams; + + Object.defineProperty(globalObject, interfaceName, { + configurable: true, + writable: true, + value: URLSearchParams + }); +}; + +const Impl = require("./URLSearchParams-impl.js"); diff --git a/node_modules/whatwg-url/dist/VoidFunction.js b/node_modules/whatwg-url/dist/VoidFunction.js new file mode 100644 index 0000000..43b0051 --- /dev/null +++ b/node_modules/whatwg-url/dist/VoidFunction.js @@ -0,0 +1,30 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +exports.convert = (value, { context = "The provided value" } = {}) => { + if (typeof value !== "function") { + throw new TypeError(context + " is not a function"); + } + + function invokeTheCallbackFunction() { + if (new.target !== undefined) { + throw new Error("Internal error: invokeTheCallbackFunction is not a constructor"); + } + + const thisArg = utils.tryWrapperForImpl(this); + let callResult; + + callResult = Reflect.apply(value, thisArg, []); + } + + invokeTheCallbackFunction.construct = () => { + let callResult = Reflect.construct(value, []); + }; + + invokeTheCallbackFunction[utils.wrapperSymbol] = value; + invokeTheCallbackFunction.objectReference = value; + + return invokeTheCallbackFunction; +}; diff --git a/node_modules/whatwg-url/dist/encoding.js b/node_modules/whatwg-url/dist/encoding.js new file mode 100644 index 0000000..cb66b8f --- /dev/null +++ b/node_modules/whatwg-url/dist/encoding.js @@ -0,0 +1,16 @@ +"use strict"; +const utf8Encoder = new TextEncoder(); +const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true }); + +function utf8Encode(string) { + return utf8Encoder.encode(string); +} + +function utf8DecodeWithoutBOM(bytes) { + return utf8Decoder.decode(bytes); +} + +module.exports = { + utf8Encode, + utf8DecodeWithoutBOM +}; diff --git a/node_modules/whatwg-url/dist/infra.js b/node_modules/whatwg-url/dist/infra.js new file mode 100644 index 0000000..4a984a3 --- /dev/null +++ b/node_modules/whatwg-url/dist/infra.js @@ -0,0 +1,26 @@ +"use strict"; + +// Note that we take code points as JS numbers, not JS strings. + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +module.exports = { + isASCIIDigit, + isASCIIAlpha, + isASCIIAlphanumeric, + isASCIIHex +}; diff --git a/node_modules/whatwg-url/dist/percent-encoding.js b/node_modules/whatwg-url/dist/percent-encoding.js new file mode 100644 index 0000000..f8464d3 --- /dev/null +++ b/node_modules/whatwg-url/dist/percent-encoding.js @@ -0,0 +1,138 @@ +"use strict"; +const { isASCIIHex } = require("./infra"); +const { utf8Encode } = require("./encoding"); + +// https://url.spec.whatwg.org/#percent-encode +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = `0${hex}`; + } + + return `%${hex}`; +} + +// https://url.spec.whatwg.org/#percent-decode +function percentDecodeBytes(input) { + const output = new Uint8Array(input.byteLength); + let outputIndex = 0; + for (let i = 0; i < input.byteLength; ++i) { + const byte = input[i]; + if (byte !== 0x25) { + output[outputIndex++] = byte; + } else if (byte === 0x25 && (!isASCIIHex(input[i + 1]) || !isASCIIHex(input[i + 2]))) { + output[outputIndex++] = byte; + } else { + const bytePoint = parseInt(String.fromCodePoint(input[i + 1], input[i + 2]), 16); + output[outputIndex++] = bytePoint; + i += 2; + } + } + + return output.slice(0, outputIndex); +} + +// https://url.spec.whatwg.org/#string-percent-decode +function percentDecodeString(input) { + const bytes = utf8Encode(input); + return percentDecodeBytes(bytes); +} + +// https://url.spec.whatwg.org/#c0-control-percent-encode-set +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +// https://url.spec.whatwg.org/#fragment-percent-encode-set +const extraFragmentPercentEncodeSet = new Set([32, 34, 60, 62, 96]); +function isFragmentPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraFragmentPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#query-percent-encode-set +const extraQueryPercentEncodeSet = new Set([32, 34, 35, 60, 62]); +function isQueryPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraQueryPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#special-query-percent-encode-set +function isSpecialQueryPercentEncode(c) { + return isQueryPercentEncode(c) || c === 39; +} + +// https://url.spec.whatwg.org/#path-percent-encode-set +const extraPathPercentEncodeSet = new Set([63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isQueryPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#userinfo-percent-encode-set +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#component-percent-encode-set +const extraComponentPercentEncodeSet = new Set([36, 37, 38, 43, 44]); +function isComponentPercentEncode(c) { + return isUserinfoPercentEncode(c) || extraComponentPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#application-x-www-form-urlencoded-percent-encode-set +const extraURLEncodedPercentEncodeSet = new Set([33, 39, 40, 41, 126]); +function isURLEncodedPercentEncode(c) { + return isComponentPercentEncode(c) || extraURLEncodedPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#code-point-percent-encode-after-encoding +// https://url.spec.whatwg.org/#utf-8-percent-encode +// Assuming encoding is always utf-8 allows us to trim one of the logic branches. TODO: support encoding. +// The "-Internal" variant here has code points as JS strings. The external version used by other files has code points +// as JS numbers, like the rest of the codebase. +function utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate) { + const bytes = utf8Encode(codePoint); + let output = ""; + for (const byte of bytes) { + // Our percentEncodePredicate operates on bytes, not code points, so this is slightly different from the spec. + if (!percentEncodePredicate(byte)) { + output += String.fromCharCode(byte); + } else { + output += percentEncode(byte); + } + } + + return output; +} + +function utf8PercentEncodeCodePoint(codePoint, percentEncodePredicate) { + return utf8PercentEncodeCodePointInternal(String.fromCodePoint(codePoint), percentEncodePredicate); +} + +// https://url.spec.whatwg.org/#string-percent-encode-after-encoding +// https://url.spec.whatwg.org/#string-utf-8-percent-encode +function utf8PercentEncodeString(input, percentEncodePredicate, spaceAsPlus = false) { + let output = ""; + for (const codePoint of input) { + if (spaceAsPlus && codePoint === " ") { + output += "+"; + } else { + output += utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate); + } + } + return output; +} + +module.exports = { + isC0ControlPercentEncode, + isFragmentPercentEncode, + isQueryPercentEncode, + isSpecialQueryPercentEncode, + isPathPercentEncode, + isUserinfoPercentEncode, + isURLEncodedPercentEncode, + percentDecodeString, + percentDecodeBytes, + utf8PercentEncodeString, + utf8PercentEncodeCodePoint +}; diff --git a/node_modules/whatwg-url/dist/url-state-machine.js b/node_modules/whatwg-url/dist/url-state-machine.js new file mode 100644 index 0000000..2d4bd11 --- /dev/null +++ b/node_modules/whatwg-url/dist/url-state-machine.js @@ -0,0 +1,1230 @@ +"use strict"; +const tr46 = require("tr46"); + +const infra = require("./infra"); +const { utf8DecodeWithoutBOM } = require("./encoding"); +const { percentDecodeString, utf8PercentEncodeCodePoint, utf8PercentEncodeString, isC0ControlPercentEncode, + isFragmentPercentEncode, isQueryPercentEncode, isSpecialQueryPercentEncode, isPathPercentEncode, + isUserinfoPercentEncode } = require("./percent-encoding"); + +const specialSchemes = { + ftp: 21, + file: null, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return [...str].length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return infra.isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function isNotSpecial(url) { + return !isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function parseIPv4Number(input) { + if (input === "") { + return failure; + } + + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + let regex = /[^0-7]/u; + if (R === 10) { + regex = /[^0-9]/u; + } + if (R === 16) { + regex = /[^0-9A-Fa-f]/u; + } + + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return failure; + } + + const numbers = []; + for (const part of parts) { + const n = parseIPv4Number(part); + if (n === failure) { + return failure; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= 256 ** (5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * 256 ** (3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = `.${output}`; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = Array.from(input, c => c.codePointAt(0)); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && infra.isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!infra.isASCIIDigit(input[pointer])) { + return failure; + } + + while (infra.isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const compress = findLongestZeroSequence(address); + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isNotSpecialArg = false) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (isNotSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8DecodeWithoutBOM(percentDecodeString(input)); + const asciiDomain = domainToASCII(domain); + if (asciiDomain === failure) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + if (endsInANumber(asciiDomain)) { + return parseIPv4(asciiDomain); + } + + return asciiDomain; +} + +function endsInANumber(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length === 1) { + return false; + } + parts.pop(); + } + + const last = parts[parts.length - 1]; + if (parseIPv4Number(last) !== failure) { + return true; + } + + if (/^[0-9]+$/u.test(last)) { + return true; + } + + return false; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + return utf8PercentEncodeString(input, isC0ControlPercentEncode); +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + return currStart; + } + + return maxIdx; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return `[${serializeIPv6(host)}]`; + } + + return host; +} + +function domainToASCII(domain, beStrict = false) { + const result = tr46.toASCII(domain, { + checkBidi: true, + checkHyphens: false, + checkJoiners: true, + useSTD3ASCIIRules: beStrict, + verifyDNSLength: beStrict + }); + if (result === null || result === "") { + return failure; + } + return result; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/ug, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/ug, ""); +} + +function shortenPath(url) { + const { path } = url; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/u.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = Array.from(this.input, c => c.codePointAt(0)); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this[`parse ${this.state}`](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (infra.isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (infra.isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && this.url.host === "") { + return false; + } + } + this.url.scheme = this.buffer; + if (this.stateOverride) { + if (this.url.port === defaultPort(this.url.scheme)) { + this.url.port = null; + } + return false; + } + this.buffer = ""; + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (c === 47) { + this.state = "relative slash"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (!isNaN(c)) { + this.url.query = null; + this.url.path.pop(); + this.state = "path"; + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = `%40${this.buffer}`; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = utf8PercentEncodeCodePoint(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + if (this.stateOverride === "hostname") { + return false; + } + + const host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (infra.isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > 2 ** 16 - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +function startsWithWindowsDriveLetter(input, pointer) { + const length = input.length - pointer; + return length >= 2 && + isWindowsDriveLetterCodePoints(input[pointer], input[pointer + 1]) && + (length === 2 || fileOtherwiseCodePoints.has(input[pointer + 2])); +} + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + this.url.host = ""; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (!isNaN(c)) { + this.url.query = null; + if (!startsWithWindowsDriveLetter(this.input, this.pointer)) { + shortenPath(this.url); + } else { + this.parseError = true; + this.url.path = []; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (!startsWithWindowsDriveLetter(this.input, this.pointer) && + isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } + this.url.host = this.base.host; + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } else if (this.stateOverride && this.url.host === null) { + this.url.path.push(""); + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + this.buffer = `${this.buffer[0]}:`; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += utf8PercentEncodeCodePoint(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] += utf8PercentEncodeCodePoint(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + if ((!this.stateOverride && c === 35) || isNaN(c)) { + const queryPercentEncodePredicate = isSpecial(this.url) ? isSpecialQueryPercentEncode : isQueryPercentEncode; + this.url.query += utf8PercentEncodeString(this.buffer, queryPercentEncodePredicate); + + this.buffer = ""; + + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else if (!isNaN(c)) { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (!isNaN(c)) { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += utf8PercentEncodeCodePoint(c, isFragmentPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = `${url.scheme}:`; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += `:${url.password}`; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += `:${url.port}`; + } + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + if (url.host === null && url.path.length > 1 && url.path[0] === "") { + output += "/."; + } + for (const segment of url.path) { + output += `/${segment}`; + } + } + + if (url.query !== null) { + output += `?${url.query}`; + } + + if (!excludeFragment && url.fragment !== null) { + output += `#${url.fragment}`; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = `${tuple.scheme}://`; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += `:${tuple.port}`; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // The spec says: + // > Unfortunate as it is, this is left as an exercise to the reader. When in doubt, return a new opaque origin. + // Browsers tested so far: + // - Chrome says "file://", but treats file: URLs as cross-origin for most (all?) purposes; see e.g. + // https://bugs.chromium.org/p/chromium/issues/detail?id=37586 + // - Firefox says "null", but treats file: URLs as same-origin sometimes based on directory stuff; see + // https://developer.mozilla.org/en-US/docs/Archive/Misc_top_level/Same-origin_policy_for_file:_URIs + return "null"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return null; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = utf8PercentEncodeString(username, isUserinfoPercentEncode); +}; + +module.exports.setThePassword = function (url, password) { + url.password = utf8PercentEncodeString(password, isUserinfoPercentEncode); +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; diff --git a/node_modules/whatwg-url/dist/urlencoded.js b/node_modules/whatwg-url/dist/urlencoded.js new file mode 100644 index 0000000..c2ccf3d --- /dev/null +++ b/node_modules/whatwg-url/dist/urlencoded.js @@ -0,0 +1,102 @@ +"use strict"; +const { utf8Encode, utf8DecodeWithoutBOM } = require("./encoding"); +const { percentDecodeBytes, utf8PercentEncodeString, isURLEncodedPercentEncode } = require("./percent-encoding"); + +// https://url.spec.whatwg.org/#concept-urlencoded-parser +function parseUrlencoded(input) { + const sequences = strictlySplitByteSequence(input, 38); + const output = []; + for (const bytes of sequences) { + if (bytes.length === 0) { + continue; + } + + let name, value; + const indexOfEqual = bytes.indexOf(61); + + if (indexOfEqual >= 0) { + name = bytes.slice(0, indexOfEqual); + value = bytes.slice(indexOfEqual + 1); + } else { + name = bytes; + value = new Uint8Array(0); + } + + name = replaceByteInByteSequence(name, 0x2B, 0x20); + value = replaceByteInByteSequence(value, 0x2B, 0x20); + + const nameString = utf8DecodeWithoutBOM(percentDecodeBytes(name)); + const valueString = utf8DecodeWithoutBOM(percentDecodeBytes(value)); + + output.push([nameString, valueString]); + } + return output; +} + +// https://url.spec.whatwg.org/#concept-urlencoded-string-parser +function parseUrlencodedString(input) { + return parseUrlencoded(utf8Encode(input)); +} + +// https://url.spec.whatwg.org/#concept-urlencoded-serializer +function serializeUrlencoded(tuples, encodingOverride = undefined) { + let encoding = "utf-8"; + if (encodingOverride !== undefined) { + // TODO "get the output encoding", i.e. handle encoding labels vs. names. + encoding = encodingOverride; + } + + let output = ""; + for (const [i, tuple] of tuples.entries()) { + // TODO: handle encoding override + + const name = utf8PercentEncodeString(tuple[0], isURLEncodedPercentEncode, true); + + let value = tuple[1]; + if (tuple.length > 2 && tuple[2] !== undefined) { + if (tuple[2] === "hidden" && name === "_charset_") { + value = encoding; + } else if (tuple[2] === "file") { + // value is a File object + value = value.name; + } + } + + value = utf8PercentEncodeString(value, isURLEncodedPercentEncode, true); + + if (i !== 0) { + output += "&"; + } + output += `${name}=${value}`; + } + return output; +} + +function strictlySplitByteSequence(buf, cp) { + const list = []; + let last = 0; + let i = buf.indexOf(cp); + while (i >= 0) { + list.push(buf.slice(last, i)); + last = i + 1; + i = buf.indexOf(cp, last); + } + if (last !== buf.length) { + list.push(buf.slice(last)); + } + return list; +} + +function replaceByteInByteSequence(buf, from, to) { + let i = buf.indexOf(from); + while (i >= 0) { + buf[i] = to; + i = buf.indexOf(from, i + 1); + } + return buf; +} + +module.exports = { + parseUrlencodedString, + serializeUrlencoded +}; diff --git a/node_modules/whatwg-url/dist/utils.js b/node_modules/whatwg-url/dist/utils.js new file mode 100644 index 0000000..cf6d232 --- /dev/null +++ b/node_modules/whatwg-url/dist/utils.js @@ -0,0 +1,141 @@ +"use strict"; + +// Returns "Type(value) is Object" in ES terminology. +function isObject(value) { + return typeof value === "object" && value !== null || typeof value === "function"; +} + +const hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty); + +const wrapperSymbol = Symbol("wrapper"); +const implSymbol = Symbol("impl"); +const sameObjectCaches = Symbol("SameObject caches"); +const ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry"); + +function getSameObject(wrapper, prop, creator) { + if (!wrapper[sameObjectCaches]) { + wrapper[sameObjectCaches] = Object.create(null); + } + + if (prop in wrapper[sameObjectCaches]) { + return wrapper[sameObjectCaches][prop]; + } + + wrapper[sameObjectCaches][prop] = creator(); + return wrapper[sameObjectCaches][prop]; +} + +function wrapperForImpl(impl) { + return impl ? impl[wrapperSymbol] : null; +} + +function implForWrapper(wrapper) { + return wrapper ? wrapper[implSymbol] : null; +} + +function tryWrapperForImpl(impl) { + const wrapper = wrapperForImpl(impl); + return wrapper ? wrapper : impl; +} + +function tryImplForWrapper(wrapper) { + const impl = implForWrapper(wrapper); + return impl ? impl : wrapper; +} + +const iterInternalSymbol = Symbol("internal"); +const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype); + +function isArrayIndexPropName(P) { + if (typeof P !== "string") { + return false; + } + const i = P >>> 0; + if (i === Math.pow(2, 32) - 1) { + return false; + } + const s = `${i}`; + if (P !== s) { + return false; + } + return true; +} + +const byteLengthGetter = + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; +function isArrayBuffer(value) { + try { + byteLengthGetter.call(value); + return true; + } catch (e) { + return false; + } +} + +function iteratorResult([key, value], kind) { + let result; + switch (kind) { + case "key": + result = key; + break; + case "value": + result = value; + break; + case "key+value": + result = [key, value]; + break; + } + return { value: result, done: false }; +} + +const supportsPropertyIndex = Symbol("supports property index"); +const supportedPropertyIndices = Symbol("supported property indices"); +const supportsPropertyName = Symbol("supports property name"); +const supportedPropertyNames = Symbol("supported property names"); +const indexedGet = Symbol("indexed property get"); +const indexedSetNew = Symbol("indexed property set new"); +const indexedSetExisting = Symbol("indexed property set existing"); +const namedGet = Symbol("named property get"); +const namedSetNew = Symbol("named property set new"); +const namedSetExisting = Symbol("named property set existing"); +const namedDelete = Symbol("named property delete"); + +const asyncIteratorNext = Symbol("async iterator get the next iteration result"); +const asyncIteratorReturn = Symbol("async iterator return steps"); +const asyncIteratorInit = Symbol("async iterator initialization steps"); +const asyncIteratorEOI = Symbol("async iterator end of iteration"); + +module.exports = exports = { + isObject, + hasOwn, + wrapperSymbol, + implSymbol, + getSameObject, + ctorRegistrySymbol, + wrapperForImpl, + implForWrapper, + tryWrapperForImpl, + tryImplForWrapper, + iterInternalSymbol, + IteratorPrototype, + AsyncIteratorPrototype, + isArrayBuffer, + isArrayIndexPropName, + supportsPropertyIndex, + supportedPropertyIndices, + supportsPropertyName, + supportedPropertyNames, + indexedGet, + indexedSetNew, + indexedSetExisting, + namedGet, + namedSetNew, + namedSetExisting, + namedDelete, + asyncIteratorNext, + asyncIteratorReturn, + asyncIteratorInit, + asyncIteratorEOI, + iteratorResult +}; diff --git a/node_modules/whatwg-url/index.js b/node_modules/whatwg-url/index.js new file mode 100644 index 0000000..e6f3a2b --- /dev/null +++ b/node_modules/whatwg-url/index.js @@ -0,0 +1,25 @@ +"use strict"; + +const { URL, URLSearchParams } = require("./webidl2js-wrapper"); +const urlStateMachine = require("./dist/url-state-machine"); +const percentEncoding = require("./dist/percent-encoding"); + +const sharedGlobalObject = {}; +URL.install(sharedGlobalObject, ["Window"]); +URLSearchParams.install(sharedGlobalObject, ["Window"]); + +exports.URL = sharedGlobalObject.URL; +exports.URLSearchParams = sharedGlobalObject.URLSearchParams; + +exports.parseURL = urlStateMachine.parseURL; +exports.basicURLParse = urlStateMachine.basicURLParse; +exports.serializeURL = urlStateMachine.serializeURL; +exports.serializeHost = urlStateMachine.serializeHost; +exports.serializeInteger = urlStateMachine.serializeInteger; +exports.serializeURLOrigin = urlStateMachine.serializeURLOrigin; +exports.setTheUsername = urlStateMachine.setTheUsername; +exports.setThePassword = urlStateMachine.setThePassword; +exports.cannotHaveAUsernamePasswordPort = urlStateMachine.cannotHaveAUsernamePasswordPort; + +exports.percentDecodeString = percentEncoding.percentDecodeString; +exports.percentDecodeBytes = percentEncoding.percentDecodeBytes; diff --git a/node_modules/whatwg-url/package.json b/node_modules/whatwg-url/package.json new file mode 100644 index 0000000..0534b96 --- /dev/null +++ b/node_modules/whatwg-url/package.json @@ -0,0 +1,59 @@ +{ + "name": "whatwg-url", + "version": "9.1.0", + "description": "An implementation of the WHATWG URL Standard's URL API and parsing machinery", + "main": "index.js", + "files": [ + "index.js", + "webidl2js-wrapper.js", + "dist/" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "repository": "jsdom/whatwg-url", + "dependencies": { + "tr46": "^2.1.0", + "webidl-conversions": "^6.1.0" + }, + "devDependencies": { + "@domenic/eslint-config": "^1.2.0", + "browserify": "^17.0.0", + "domexception": "^2.0.1", + "eslint": "^7.29.0", + "glob": "^7.1.7", + "got": "^11.8.2", + "jest": "^27.0.5", + "recast": "^0.20.4", + "webidl2js": "^16.2.0" + }, + "engines": { + "node": ">=12" + }, + "scripts": { + "coverage": "jest --coverage", + "lint": "eslint .", + "prepare": "node scripts/transform.js", + "pretest": "node scripts/get-latest-platform-tests.js && node scripts/transform.js", + "build-live-viewer": "browserify index.js --standalone whatwgURL > live-viewer/whatwg-url.js", + "test": "jest" + }, + "jest": { + "collectCoverageFrom": [ + "lib/**/*.js", + "!lib/utils.js" + ], + "coverageDirectory": "coverage", + "coverageReporters": [ + "lcov", + "text-summary" + ], + "testEnvironment": "node", + "testMatch": [ + "/test/**/*.js" + ], + "testPathIgnorePatterns": [ + "^/test/testharness.js$", + "^/test/web-platform-tests/" + ] + } +} diff --git a/node_modules/whatwg-url/webidl2js-wrapper.js b/node_modules/whatwg-url/webidl2js-wrapper.js new file mode 100644 index 0000000..849f6a7 --- /dev/null +++ b/node_modules/whatwg-url/webidl2js-wrapper.js @@ -0,0 +1,7 @@ +"use strict"; + +const URL = require("./dist/URL"); +const URLSearchParams = require("./dist/URLSearchParams"); + +exports.URL = URL; +exports.URLSearchParams = URLSearchParams; diff --git a/node_modules/wide-align/LICENSE b/node_modules/wide-align/LICENSE new file mode 100644 index 0000000..f4be44d --- /dev/null +++ b/node_modules/wide-align/LICENSE @@ -0,0 +1,14 @@ +Copyright (c) 2015, Rebecca Turner + +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/wide-align/README.md b/node_modules/wide-align/README.md new file mode 100644 index 0000000..32f1be0 --- /dev/null +++ b/node_modules/wide-align/README.md @@ -0,0 +1,47 @@ +wide-align +---------- + +A wide-character aware text alignment function for use in terminals / on the +console. + +### Usage + +``` +var align = require('wide-align') + +// Note that if you view this on a unicode console, all of the slashes are +// aligned. This is because on a console, all narrow characters are +// an en wide and all wide characters are an em. In browsers, this isn't +// held to and wide characters like "古" can be less than two narrow +// characters even with a fixed width font. + +console.log(align.center('abc', 10)) // ' abc ' +console.log(align.center('古古古', 10)) // ' 古古古 ' +console.log(align.left('abc', 10)) // 'abc ' +console.log(align.left('古古古', 10)) // '古古古 ' +console.log(align.right('abc', 10)) // ' abc' +console.log(align.right('古古古', 10)) // ' 古古古' +``` + +### Functions + +#### `align.center(str, length)` → `str` + +Returns *str* with spaces added to both sides such that that it is *length* +chars long and centered in the spaces. + +#### `align.left(str, length)` → `str` + +Returns *str* with spaces to the right such that it is *length* chars long. + +### `align.right(str, length)` → `str` + +Returns *str* with spaces to the left such that it is *length* chars long. + +### Origins + +These functions were originally taken from +[cliui](https://npmjs.com/package/cliui). Changes include switching to the +MUCH faster pad generation function from +[lodash](https://npmjs.com/package/lodash), making center alignment pad +both sides and adding left alignment. diff --git a/node_modules/wide-align/align.js b/node_modules/wide-align/align.js new file mode 100644 index 0000000..4f94ca4 --- /dev/null +++ b/node_modules/wide-align/align.js @@ -0,0 +1,65 @@ +'use strict' +var stringWidth = require('string-width') + +exports.center = alignCenter +exports.left = alignLeft +exports.right = alignRight + +// lodash's way of generating pad characters. + +function createPadding (width) { + var result = '' + var string = ' ' + var n = width + do { + if (n % 2) { + result += string; + } + n = Math.floor(n / 2); + string += string; + } while (n); + + return result; +} + +function alignLeft (str, width) { + var trimmed = str.trimRight() + if (trimmed.length === 0 && str.length >= width) return str + var padding = '' + var strWidth = stringWidth(trimmed) + + if (strWidth < width) { + padding = createPadding(width - strWidth) + } + + return trimmed + padding +} + +function alignRight (str, width) { + var trimmed = str.trimLeft() + if (trimmed.length === 0 && str.length >= width) return str + var padding = '' + var strWidth = stringWidth(trimmed) + + if (strWidth < width) { + padding = createPadding(width - strWidth) + } + + return padding + trimmed +} + +function alignCenter (str, width) { + var trimmed = str.trim() + if (trimmed.length === 0 && str.length >= width) return str + var padLeft = '' + var padRight = '' + var strWidth = stringWidth(trimmed) + + if (strWidth < width) { + var padLeftBy = parseInt((width - strWidth) / 2, 10) + padLeft = createPadding(padLeftBy) + padRight = createPadding(width - (strWidth + padLeftBy)) + } + + return padLeft + trimmed + padRight +} diff --git a/node_modules/wide-align/package.json b/node_modules/wide-align/package.json new file mode 100644 index 0000000..2dd2707 --- /dev/null +++ b/node_modules/wide-align/package.json @@ -0,0 +1,33 @@ +{ + "name": "wide-align", + "version": "1.1.5", + "description": "A wide-character aware text alignment function for use on the console or with fixed width fonts.", + "main": "align.js", + "scripts": { + "test": "tap --coverage test/*.js" + }, + "keywords": [ + "wide", + "double", + "unicode", + "cjkv", + "pad", + "align" + ], + "author": "Rebecca Turner (http://re-becca.org/)", + "license": "ISC", + "repository": { + "type": "git", + "url": "https://github.com/iarna/wide-align" + }, + "//": "But not version 5 of string-width, as that's ESM only", + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + }, + "devDependencies": { + "tap": "*" + }, + "files": [ + "align.js" + ] +} diff --git a/node_modules/wrappy/LICENSE b/node_modules/wrappy/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/wrappy/README.md b/node_modules/wrappy/README.md new file mode 100644 index 0000000..98eab25 --- /dev/null +++ b/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/node_modules/wrappy/package.json b/node_modules/wrappy/package.json new file mode 100644 index 0000000..1307520 --- /dev/null +++ b/node_modules/wrappy/package.json @@ -0,0 +1,29 @@ +{ + "name": "wrappy", + "version": "1.0.2", + "description": "Callback wrapping utility", + "main": "wrappy.js", + "files": [ + "wrappy.js" + ], + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tap": "^2.3.1" + }, + "scripts": { + "test": "tap --coverage test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/npm/wrappy" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "homepage": "https://github.com/npm/wrappy" +} diff --git a/node_modules/wrappy/wrappy.js b/node_modules/wrappy/wrappy.js new file mode 100644 index 0000000..bb7e7d6 --- /dev/null +++ b/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/node_modules/yallist/LICENSE b/node_modules/yallist/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/yallist/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/yallist/README.md b/node_modules/yallist/README.md new file mode 100644 index 0000000..f586101 --- /dev/null +++ b/node_modules/yallist/README.md @@ -0,0 +1,204 @@ +# yallist + +Yet Another Linked List + +There are many doubly-linked list implementations like it, but this +one is mine. + +For when an array would be too big, and a Map can't be iterated in +reverse order. + + +[![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) + +## basic usage + +```javascript +var yallist = require('yallist') +var myList = yallist.create([1, 2, 3]) +myList.push('foo') +myList.unshift('bar') +// of course pop() and shift() are there, too +console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] +myList.forEach(function (k) { + // walk the list head to tail +}) +myList.forEachReverse(function (k, index, list) { + // walk the list tail to head +}) +var myDoubledList = myList.map(function (k) { + return k + k +}) +// now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] +// mapReverse is also a thing +var myDoubledListReverse = myList.mapReverse(function (k) { + return k + k +}) // ['foofoo', 6, 4, 2, 'barbar'] + +var reduced = myList.reduce(function (set, entry) { + set += entry + return set +}, 'start') +console.log(reduced) // 'startfoo123bar' +``` + +## api + +The whole API is considered "public". + +Functions with the same name as an Array method work more or less the +same way. + +There's reverse versions of most things because that's the point. + +### Yallist + +Default export, the class that holds and manages a list. + +Call it with either a forEach-able (like an array) or a set of +arguments, to initialize the list. + +The Array-ish methods all act like you'd expect. No magic length, +though, so if you change that it won't automatically prune or add +empty spots. + +### Yallist.create(..) + +Alias for Yallist function. Some people like factories. + +#### yallist.head + +The first node in the list + +#### yallist.tail + +The last node in the list + +#### yallist.length + +The number of nodes in the list. (Change this at your peril. It is +not magic like Array length.) + +#### yallist.toArray() + +Convert the list to an array. + +#### yallist.forEach(fn, [thisp]) + +Call a function on each item in the list. + +#### yallist.forEachReverse(fn, [thisp]) + +Call a function on each item in the list, in reverse order. + +#### yallist.get(n) + +Get the data at position `n` in the list. If you use this a lot, +probably better off just using an Array. + +#### yallist.getReverse(n) + +Get the data at position `n`, counting from the tail. + +#### yallist.map(fn, thisp) + +Create a new Yallist with the result of calling the function on each +item. + +#### yallist.mapReverse(fn, thisp) + +Same as `map`, but in reverse. + +#### yallist.pop() + +Get the data from the list tail, and remove the tail from the list. + +#### yallist.push(item, ...) + +Insert one or more items to the tail of the list. + +#### yallist.reduce(fn, initialValue) + +Like Array.reduce. + +#### yallist.reduceReverse + +Like Array.reduce, but in reverse. + +#### yallist.reverse + +Reverse the list in place. + +#### yallist.shift() + +Get the data from the list head, and remove the head from the list. + +#### yallist.slice([from], [to]) + +Just like Array.slice, but returns a new Yallist. + +#### yallist.sliceReverse([from], [to]) + +Just like yallist.slice, but the result is returned in reverse. + +#### yallist.toArray() + +Create an array representation of the list. + +#### yallist.toArrayReverse() + +Create a reversed array representation of the list. + +#### yallist.unshift(item, ...) + +Insert one or more items to the head of the list. + +#### yallist.unshiftNode(node) + +Move a Node object to the front of the list. (That is, pull it out of +wherever it lives, and make it the new head.) + +If the node belongs to a different list, then that list will remove it +first. + +#### yallist.pushNode(node) + +Move a Node object to the end of the list. (That is, pull it out of +wherever it lives, and make it the new tail.) + +If the node belongs to a list already, then that list will remove it +first. + +#### yallist.removeNode(node) + +Remove a node from the list, preserving referential integrity of head +and tail and other nodes. + +Will throw an error if you try to have a list remove a node that +doesn't belong to it. + +### Yallist.Node + +The class that holds the data and is actually the list. + +Call with `var n = new Node(value, previousNode, nextNode)` + +Note that if you do direct operations on Nodes themselves, it's very +easy to get into weird states where the list is broken. Be careful :) + +#### node.next + +The next node in the list. + +#### node.prev + +The previous node in the list. + +#### node.value + +The data the node contains. + +#### node.list + +The list to which this node belongs. (Null if it does not belong to +any list.) diff --git a/node_modules/yallist/iterator.js b/node_modules/yallist/iterator.js new file mode 100644 index 0000000..d41c97a --- /dev/null +++ b/node_modules/yallist/iterator.js @@ -0,0 +1,8 @@ +'use strict' +module.exports = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value + } + } +} diff --git a/node_modules/yallist/package.json b/node_modules/yallist/package.json new file mode 100644 index 0000000..8a08386 --- /dev/null +++ b/node_modules/yallist/package.json @@ -0,0 +1,29 @@ +{ + "name": "yallist", + "version": "4.0.0", + "description": "Yet Another Linked List", + "main": "yallist.js", + "directories": { + "test": "test" + }, + "files": [ + "yallist.js", + "iterator.js" + ], + "dependencies": {}, + "devDependencies": { + "tap": "^12.1.0" + }, + "scripts": { + "test": "tap test/*.js --100", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/yallist.git" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/node_modules/yallist/yallist.js b/node_modules/yallist/yallist.js new file mode 100644 index 0000000..4e83ab1 --- /dev/null +++ b/node_modules/yallist/yallist.js @@ -0,0 +1,426 @@ +'use strict' +module.exports = Yallist + +Yallist.Node = Node +Yallist.create = Yallist + +function Yallist (list) { + var self = this + if (!(self instanceof Yallist)) { + self = new Yallist() + } + + self.tail = null + self.head = null + self.length = 0 + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item) + }) + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]) + } + } + + return self +} + +Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next + var prev = node.prev + + if (next) { + next.prev = prev + } + + if (prev) { + prev.next = next + } + + if (node === this.head) { + this.head = next + } + if (node === this.tail) { + this.tail = prev + } + + node.list.length-- + node.next = null + node.prev = null + node.list = null + + return next +} + +Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var head = this.head + node.list = this + node.next = head + if (head) { + head.prev = node + } + + this.head = node + if (!this.tail) { + this.tail = node + } + this.length++ +} + +Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var tail = this.tail + node.list = this + node.prev = tail + if (tail) { + tail.next = node + } + + this.tail = node + if (!this.head) { + this.head = node + } + this.length++ +} + +Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value + this.tail = this.tail.prev + if (this.tail) { + this.tail.next = null + } else { + this.head = null + } + this.length-- + return res +} + +Yallist.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value + this.head = this.head.next + if (this.head) { + this.head.prev = null + } else { + this.tail = null + } + this.length-- + return res +} + +Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this) + walker = walker.next + } +} + +Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this) + walker = walker.prev + } +} + +Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.next + } + return res +} + +Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.prev + } + return res +} + +Yallist.prototype.reduce = function (fn, initial) { + var acc + var walker = this.head + if (arguments.length > 1) { + acc = initial + } else if (this.head) { + walker = this.head.next + acc = this.head.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i) + walker = walker.next + } + + return acc +} + +Yallist.prototype.reduceReverse = function (fn, initial) { + var acc + var walker = this.tail + if (arguments.length > 1) { + acc = initial + } else if (this.tail) { + walker = this.tail.prev + acc = this.tail.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i) + walker = walker.prev + } + + return acc +} + +Yallist.prototype.toArray = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value + walker = walker.next + } + return arr +} + +Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value + walker = walker.prev + } + return arr +} + +Yallist.prototype.slice = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1 + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next + } + + var ret = [] + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value) + walker = this.removeNode(walker) + } + if (walker === null) { + walker = this.tail + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]) + } + return ret; +} + +Yallist.prototype.reverse = function () { + var head = this.head + var tail = this.tail + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev + walker.prev = walker.next + walker.next = p + } + this.head = tail + this.tail = head + return this +} + +function insert (self, node, value) { + var inserted = node === self.head ? + new Node(value, null, node, self) : + new Node(value, node, node.next, self) + + if (inserted.next === null) { + self.tail = inserted + } + if (inserted.prev === null) { + self.head = inserted + } + + self.length++ + + return inserted +} + +function push (self, item) { + self.tail = new Node(item, self.tail, null, self) + if (!self.head) { + self.head = self.tail + } + self.length++ +} + +function unshift (self, item) { + self.head = new Node(item, null, self.head, self) + if (!self.tail) { + self.tail = self.head + } + self.length++ +} + +function Node (value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list) + } + + this.list = list + this.value = value + + if (prev) { + prev.next = this + this.prev = prev + } else { + this.prev = null + } + + if (next) { + next.prev = this + this.next = next + } else { + this.next = null + } +} + +try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist) +} catch (er) {} diff --git a/package-lock.json b/package-lock.json index 1d4dda8..85136b9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,8 +1,1514 @@ { "name": "rocked_backend", "version": "1.0.0", - "lockfileVersion": 1, + "lockfileVersion": 2, "requires": true, + "packages": { + "": { + "name": "rocked_backend", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "bcrypt": "^5.0.1", + "bcryptjs": "^2.4.3", + "child_process": "^1.0.2", + "express": "^4.17.1", + "http-status": "^1.5.0", + "jsonwebtoken": "^8.5.1", + "mongoose": "^6.0.11", + "passport": "^0.5.2", + "passport-jwt": "^4.0.0", + "validator": "^13.7.0" + } + }, + "node_modules/@mapbox/node-pre-gyp": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.8.tgz", + "integrity": "sha512-CMGKi28CF+qlbXh26hDe6NxCd7amqeAzEqnS6IHeO6LoaKyM/n+Xw3HT1COdq8cuioOdlKdqn/hCmqPUOMOywg==", + "dependencies": { + "detect-libc": "^1.0.3", + "https-proxy-agent": "^5.0.0", + "make-dir": "^3.1.0", + "node-fetch": "^2.6.5", + "nopt": "^5.0.0", + "npmlog": "^5.0.1", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.11" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp" + } + }, + "node_modules/@types/node": { + "version": "16.11.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.11.1.tgz", + "integrity": "sha512-PYGcJHL9mwl1Ek3PLiYgyEKtwTMmkMw4vbiyz/ps3pfdRYLVv+SN7qHVAImrjdAXxgluDEw6Ph4lyv+m9UpRmA==" + }, + "node_modules/@types/webidl-conversions": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-6.1.1.tgz", + "integrity": "sha512-XAahCdThVuCFDQLT7R7Pk/vqeObFNL3YqRyFZg+AqAP/W1/w3xHaIxuW7WszQqTbIBOPRcItYJIou3i/mppu3Q==" + }, + "node_modules/@types/whatwg-url": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-8.2.1.tgz", + "integrity": "sha512-2YubE1sjj5ifxievI5Ge1sckb9k/Er66HyR2c+3+I6VDUUg1TLPdYYTEbQ+DjRkS4nTxMJhgWfSfMRD2sl2EYQ==", + "dependencies": { + "@types/node": "*", + "@types/webidl-conversions": "*" + } + }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" + }, + "node_modules/accepts": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", + "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", + "dependencies": { + "mime-types": "~2.1.24", + "negotiator": "0.6.2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/agent-base/node_modules/debug": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", + "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/agent-base/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "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/aproba": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==" + }, + "node_modules/are-we-there-yet": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", + "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==", + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/bcrypt": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.0.1.tgz", + "integrity": "sha512-9BTgmrhZM2t1bNuDtrtIMVSmmxZBrJ71n8Wg+YgdjHuIWYF7SjjmCPZFB+/5i/o/PIeRpwVJR3P+NrpIItUjqw==", + "hasInstallScript": true, + "dependencies": { + "@mapbox/node-pre-gyp": "^1.0.0", + "node-addon-api": "^3.1.0" + }, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/bcryptjs": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", + "integrity": "sha1-mrVie5PmBiH/fNrF2pczAn3x0Ms=" + }, + "node_modules/body-parser": { + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", + "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", + "dependencies": { + "bytes": "3.1.0", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.2", + "http-errors": "1.7.2", + "iconv-lite": "0.4.24", + "on-finished": "~2.3.0", + "qs": "6.7.0", + "raw-body": "2.4.0", + "type-is": "~1.6.17" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/bson": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/bson/-/bson-4.5.3.tgz", + "integrity": "sha512-qVX7LX79Mtj7B3NPLzCfBiCP6RAsjiV8N63DjlaVVpZW+PFoDTxQ4SeDbSpcqgE6mXksM5CAwZnXxxxn/XwC0g==", + "dependencies": { + "buffer": "^5.6.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" + }, + "node_modules/bytes": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", + "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/child_process": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/child_process/-/child_process-1.0.2.tgz", + "integrity": "sha1-sffn/HPSXn/R1FWtyU4UODAYK1o=" + }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "engines": { + "node": ">=10" + } + }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "bin": { + "color-support": "bin.js" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=" + }, + "node_modules/content-disposition": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", + "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", + "dependencies": { + "safe-buffer": "5.1.2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", + "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=" + }, + "node_modules/denque": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.0.1.tgz", + "integrity": "sha512-tfiWc6BQLXNLpNiR5iGd0Ocu3P3VpxfzFiqubLgMfhfOw9WyvgJBd46CClNn9k3qfbjvT//0cf7AlYRX/OslMQ==", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/destroy": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" + }, + "node_modules/detect-libc": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz", + "integrity": "sha1-+hN8S9aY7fVc1c0CrFWfkaTEups=", + "bin": { + "detect-libc": "bin/detect-libc.js" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" + }, + "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/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.17.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", + "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", + "dependencies": { + "accepts": "~1.3.7", + "array-flatten": "1.1.1", + "body-parser": "1.19.0", + "content-disposition": "0.5.3", + "content-type": "~1.0.4", + "cookie": "0.4.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.2", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.1.2", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.5", + "qs": "6.7.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.1.2", + "send": "0.17.1", + "serve-static": "1.14.1", + "setprototypeof": "1.1.1", + "statuses": "~1.5.0", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/finalhandler": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", + "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "statuses": "~1.5.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "node_modules/gauge": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz", + "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==", + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.2", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.1", + "object-assign": "^4.1.1", + "signal-exit": "^3.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=" + }, + "node_modules/http-errors": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", + "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.1", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-status": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/http-status/-/http-status-1.5.0.tgz", + "integrity": "sha512-wcGvY31MpFNHIkUcXHHnvrE4IKYlpvitJw5P/1u892gMBAM46muQ+RH7UN1d+Ntnfx5apnOnVY6vcLmrWHOLwg==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz", + "integrity": "sha512-EkYm5BcKUGiduxzSt3Eppko+PiNWNEpa4ySk9vTC6wDsQJW9rHSa+UhGNJoRYp7bz6Ht1eaRIa6QaJqO5rCFbA==", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/https-proxy-agent/node_modules/debug": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", + "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/https-proxy-agent/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.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/jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=4", + "npm": ">=1.4.28" + } + }, + "node_modules/jsonwebtoken/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/jsonwebtoken/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/kareem": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.3.2.tgz", + "integrity": "sha512-STHz9P7X2L4Kwn72fA4rGyqyXdmrMSdxqHx9IXon/FXluXieaFA6KJ2upcHAHxQPQ0LeM/OjLrhFxifHewOALQ==" + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "optional": true + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.50.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.50.0.tgz", + "integrity": "sha512-9tMZCDlYHqeERXEHO9f/hKfNXhre5dK2eE/krIvUjZbS2KPcqGDfNShIWS1uW9XOTKQKqK6qbeOci18rbfW77A==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.33", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.33.tgz", + "integrity": "sha512-plLElXp7pRDd0bNZHw+nMd52vRYjLwQjygaNg7ddJ2uJtTlmnTCjWuPKxVu6//AdaRuME84SvLW91sIkBqGT0g==", + "dependencies": { + "mime-db": "1.50.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minipass": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.1.6.tgz", + "integrity": "sha512-rty5kpw9/z8SX9dmxblFA6edItUmwJgMeYDZRrwlIVN27i8gysGbznJwUggw2V/FVqFSDdWy040ZPS811DYAqQ==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mongodb": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-4.1.2.tgz", + "integrity": "sha512-pHCKDoOy1h6mVurziJmXmTMPatYWOx8pbnyFgSgshja9Y36Q+caHUzTDY6rrIy9HCSrjnbXmx3pCtvNZHmR8xg==", + "dependencies": { + "bson": "^4.5.2", + "denque": "^2.0.1", + "mongodb-connection-string-url": "^2.0.0" + }, + "engines": { + "node": ">=12.9.0" + }, + "optionalDependencies": { + "saslprep": "^1.0.3" + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.1.0.tgz", + "integrity": "sha512-Qf9Zw7KGiRljWvMrrUFDdVqo46KIEiDuCzvEN97rh/PcKzk2bd6n9KuzEwBwW9xo5glwx69y1mI6s+jFUD/aIQ==", + "dependencies": { + "@types/whatwg-url": "^8.2.1", + "whatwg-url": "^9.1.0" + } + }, + "node_modules/mongoose": { + "version": "6.0.11", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-6.0.11.tgz", + "integrity": "sha512-ESLnGIZB15xpqAbtjL/wcx+NEmzewlNuST/Dp/md4eqirVGTuEeN+IhS4qr3D5GFhnQAGdadpGlTfrWj5Ggykw==", + "dependencies": { + "bson": "^4.2.2", + "kareem": "2.3.2", + "mongodb": "4.1.2", + "mpath": "0.8.4", + "mquery": "4.0.0", + "ms": "2.1.2", + "regexp-clone": "1.0.0", + "sift": "13.5.2", + "sliced": "1.0.1" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/mongoose/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/mpath": { + "version": "0.8.4", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.8.4.tgz", + "integrity": "sha512-DTxNZomBcTWlrMW76jy1wvV37X/cNNxPW1y2Jzd4DZkAaC5ZGsm8bfGfNOthcDuRJujXLqiuS6o3Tpy0JEoh7g==", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mquery": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-4.0.0.tgz", + "integrity": "sha512-nGjm89lHja+T/b8cybAby6H0YgA4qYC/lx6UlwvHGqvTq8bDaNeCwl1sY8uRELrNbVWJzIihxVd+vphGGn1vBw==", + "dependencies": { + "debug": "4.x", + "regexp-clone": "^1.0.0", + "sliced": "1.0.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/mquery/node_modules/debug": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", + "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/mquery/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "node_modules/negotiator": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", + "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-addon-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.2.1.tgz", + "integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==" + }, + "node_modules/node-fetch": { + "version": "2.6.6", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.6.tgz", + "integrity": "sha512-Z8/6vRlTUChSdIgMa51jxQ4lrw/Jy5SOW10ObaA47/RElsAN2c5Pn8bTgFGWn/ibwzXTE8qwr1Yzx28vsecXEA==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + } + }, + "node_modules/node-fetch/node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o=" + }, + "node_modules/node-fetch/node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=" + }, + "node_modules/node-fetch/node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/npmlog": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", + "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==", + "dependencies": { + "are-we-there-yet": "^2.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^3.0.0", + "set-blocking": "^2.0.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/passport": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/passport/-/passport-0.5.2.tgz", + "integrity": "sha512-w9n/Ot5I7orGD4y+7V3EFJCQEznE5RxHamUxcqLT2QoJY0f2JdN8GyHonYFvN0Vz+L6lUJfVhrk2aZz2LbuREw==", + "dependencies": { + "passport-strategy": "1.x.x", + "pause": "0.0.1" + }, + "engines": { + "node": ">= 0.4.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jaredhanson" + } + }, + "node_modules/passport-jwt": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/passport-jwt/-/passport-jwt-4.0.0.tgz", + "integrity": "sha512-BwC0n2GP/1hMVjR4QpnvqA61TxenUMlmfNjYNgK0ZAs0HK4SOQkHcSv4L328blNTLtHq7DbmvyNJiH+bn6C5Mg==", + "dependencies": { + "jsonwebtoken": "^8.2.0", + "passport-strategy": "^1.0.0" + } + }, + "node_modules/passport-strategy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/passport-strategy/-/passport-strategy-1.0.0.tgz", + "integrity": "sha1-tVOaqPwiWj0a0XlHbd8ja0QPUuQ=", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" + }, + "node_modules/pause": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz", + "integrity": "sha1-HUCLP9t2kjuVQ9lvtMnf1TXZy10=" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.7.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", + "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz", + "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==", + "dependencies": { + "bytes": "3.1.0", + "http-errors": "1.7.2", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readable-stream": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/regexp-clone": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-1.0.0.tgz", + "integrity": "sha512-TuAasHQNamyyJ2hb97IuBEif4qBHGjPHBS64sZwytpLEqtBQ1gPJTnOaQ6qmpET16cK14kkjbazl6+p0RRv0yw==" + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/saslprep": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", + "integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", + "optional": true, + "dependencies": { + "sparse-bitfield": "^3.0.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/semver": { + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.17.1", + "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", + "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==", + "dependencies": { + "debug": "2.6.9", + "depd": "~1.1.2", + "destroy": "~1.0.4", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "~1.7.2", + "mime": "1.6.0", + "ms": "2.1.1", + "on-finished": "~2.3.0", + "range-parser": "~1.2.1", + "statuses": "~1.5.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" + }, + "node_modules/serve-static": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz", + "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.17.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" + }, + "node_modules/setprototypeof": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", + "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==" + }, + "node_modules/sift": { + "version": "13.5.2", + "resolved": "https://registry.npmjs.org/sift/-/sift-13.5.2.tgz", + "integrity": "sha512-+gxdEOMA2J+AI+fVsCqeNn7Tgx3M9ZN9jdi95939l1IJ8cZsqS8sqpJyOkic2SJk+1+98Uwryt/gL6XDaV+UZA==" + }, + "node_modules/signal-exit": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.6.tgz", + "integrity": "sha512-sDl4qMFpijcGw22U5w63KmD3cZJfBuFlVNbVMKje2keoKML7X2UzWbc4XrmEbDwg0NXJc3yv4/ox7b+JWb57kQ==" + }, + "node_modules/sliced": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", + "integrity": "sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E=" + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", + "optional": true, + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "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/tar": { + "version": "6.1.11", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.1.11.tgz", + "integrity": "sha512-an/KZQzQUkZCkuoAA64hM92X0Urb6VpRhAFllDzz44U2mcD5scmT3zBc4VgVpkugF580+DQn8eAFSyoQt0tznA==", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^3.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/toidentifier": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", + "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tr46": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-2.1.0.tgz", + "integrity": "sha512-15Ih7phfcdP5YxqiB+iDtLoaTz4Nd35+IiAv0kQ5FNKHzXgdWqPoTIqEDDJmXceQt4JZk6lVPT8lnDlPpGDppw==", + "dependencies": { + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/validator": { + "version": "13.7.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.7.0.tgz", + "integrity": "sha512-nYXQLCBkpJ8X6ltALua9dRrZDHVYxjJ1wgskNt1lH9fzGjs3tgojGSCBjmEPwkWS1y29+DrizMTW19Pr9uB2nw==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/webidl-conversions": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-6.1.0.tgz", + "integrity": "sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w==", + "engines": { + "node": ">=10.4" + } + }, + "node_modules/whatwg-url": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-9.1.0.tgz", + "integrity": "sha512-CQ0UcrPHyomtlOCot1TL77WyMIm/bCwrJ2D6AOKGwEczU9EpyoqAokfqrf/MioU9kHcMsmJZcg1egXix2KYEsA==", + "dependencies": { + "tr46": "^2.1.0", + "webidl-conversions": "^6.1.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + } + }, "dependencies": { "@mapbox/node-pre-gyp": { "version": "1.0.8", @@ -1019,16 +2525,6 @@ "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=" }, - "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==", - "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - } - }, "string_decoder": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", @@ -1044,6 +2540,16 @@ } } }, + "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==", + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, "strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", diff --git a/routes/v1/index.js b/routes/v1/index.js index e6cf5bd..ebb3cf0 100644 --- a/routes/v1/index.js +++ b/routes/v1/index.js @@ -2,14 +2,14 @@ const express = require("express"); const router = express.Router(); const CropRoute=require("./crops.route") const authRoute=require("./auth.route") -// const modelRoute=require("./model.route") +const modelRoute=require("./model.route") // router.get("/", (req, res)=>{ // res.send("Faisal"); // }) router.use("/crops", CropRoute); router.use("/auth", authRoute); -// router.use("/model", modelRoute); +router.use("/model", modelRoute); diff --git a/routes/v1/model.route.js b/routes/v1/model.route.js index f375910..5238512 100644 --- a/routes/v1/model.route.js +++ b/routes/v1/model.route.js @@ -1,43 +1,32 @@ -// var express = require('express'); -// const router = express.Router(); -// const auth=require('../../middleware/auth'); -// // var spawn = require("child_process").spawn; -// const User=require("../../model/User") -// const httpStatus = require("http-status"); +var express = require('express'); +const router = express.Router(); +const auth=require('../../middleware/auth'); +const User=require("../../model/User") +const httpStatus = require("http-status"); -// async function callbackfxn(req, res) { - // var arr=["./python/ml_model.py"]; - // (req.body.arr).map((elem)=>{ - // arr.push(elem); - // }) - // console.log('Array:', arr); - // var childProcess = spawn('python', arr); - // console.log(req.user) - // childProcess.stdout.on('data', async function (data) { - // let vx=data.toString(); - // let userElem=await User.findOne({email:req.user.email}); - // // let obj={details:[...(req.body.arr)], cropSuggested:vx}; - // // console.log() - // await userElem.history.push(req.body.value); - // userElem.save() +async function callbackfxn(req, res) { + + let userElem = await User.findOne({email: req.user.email}); + let obj = {details: req.body.details, cropSuggested: req.body.cropSuggested} + await userElem.history.push(obj); + userElem.save() - // res.send("Sucessfully added!"); - // }) - // childProcess.stderr.on('data', function(data) { - // console.log('runs:', data.toString('utf8')) - // }) -// } + res.status(httpStatus.CREATED).send({ + message: 'success' + }) + +} -// async function newcallback(req, res){ -// let userElem=await User.findOne({email:req.user.email}); -// let hist=await userElem.history; -// console.log(hist); -// res.status(httpStatus.FOUND).json({history:hist}); -// } +async function newcallback(req, res){ + let userElem=await User.findOne({email:req.user.email}); + let hist=await userElem.history; + console.log(hist); + res.status(httpStatus.FOUND).json({history:hist}); +} -// router.post('/history', auth(), callbackfxn); -// router.get('/history', auth(), newcallback); +router.post('/history', auth(), callbackfxn); +router.get('/history', auth(), newcallback); -// module.exports = router; +module.exports = router;